@htmlbricks/hb-player-live 0.61.51 → 0.61.53
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 +31 -39
- package/main.iife.js.map +1 -1
- package/manifest.json +1 -1
- package/package.json +1 -1
package/main.iife.js
CHANGED
|
@@ -1,45 +1,45 @@
|
|
|
1
|
-
(function(Un){"use strict";typeof window<"u"&&((window.__svelte??={}).v??=new Set).add("5");const Zc=1,eu=2,Gn="[",Kn="[!",Vn="]",fs={},be=Symbol(),Hn=!1;var Wn=Array.isArray,tu=Array.prototype.indexOf,su=Array.from,ri=Object.keys,gs=Object.defineProperty,ms=Object.getOwnPropertyDescriptor,iu=Object.prototype,ru=Array.prototype,nu=Object.getPrototypeOf,Yn=Object.isExtensible;function jn(r){for(var e=0;e<r.length;e++)r[e]()}function au(){var r,e,t=new Promise((s,i)=>{r=s,e=i});return{promise:t,resolve:r,reject:e}}const Ve=2,sr=4,qn=8,ps=16,Tt=32,Pt=64,Xn=128,Qe=256,ni=512,Oe=1024,Je=2048,kt=4096,wt=8192,jt=16384,ir=32768,rr=65536,zn=1<<17,ou=1<<18,ys=1<<19,lu=1<<20,nr=1<<21,ar=1<<22,qt=1<<23,or=Symbol("$state"),cu=Symbol("legacy props"),lr=new class extends Error{name="StaleReactionError";message="The reaction that called `getAbortSignal()` was re-run or destroyed"},Qn=3,ai=8;function uu(){throw new Error("https://svelte.dev/e/await_outside_boundary")}function hu(r){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function du(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function fu(r){throw new Error("https://svelte.dev/e/effect_in_teardown")}function gu(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function mu(r){throw new Error("https://svelte.dev/e/effect_orphan")}function pu(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function yu(){throw new Error("https://svelte.dev/e/hydration_failed")}function vu(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function Eu(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function Tu(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function oi(r){console.warn("https://svelte.dev/e/hydration_mismatch")}let De=!1;function vs(r){De=r}let Te;function Ot(r){if(r===null)throw oi(),fs;return Te=r}function li(){return Ot(es(Te))}function de(r){if(De){if(es(Te)!==null)throw oi(),fs;Te=r}}function Su(){for(var r=0,e=Te;;){if(e.nodeType===ai){var t=e.data;if(t===Vn){if(r===0)return e;r-=1}else(t===Gn||t===Kn)&&(r+=1)}var s=es(e);e.remove(),e=s}}function xu(r){if(!r||r.nodeType!==ai)throw oi(),fs;return r.data}function Jn(r){return r===this.v}function Au(r,e){return r!=r?e==e:r!==e||r!==null&&typeof r=="object"||typeof r=="function"}function Lu(r){return!Au(r,this.v)}let Iu=!1,Ze=null;function ci(r){Ze=r}function Zn(r,e=!1,t){Ze={p:Ze,c:null,e:null,s:r,x:null,l:null}}function ea(r){var e=Ze,t=e.e;if(t!==null){e.e=null;for(var s of t)va(s)}return r!==void 0&&(e.x=r),Ze=e.p,r??{}}function ta(){return!0}const _u=new WeakMap;function Ru(r){var e=te;if(e===null)return se.f|=qt,r;if((e.f&ir)===0){if((e.f&Xn)===0)throw!e.parent&&r instanceof Error&&sa(r),r;e.b.error(r)}else cr(r,e)}function cr(r,e){for(;e!==null;){if((e.f&Xn)!==0)try{e.b.error(r);return}catch(t){r=t}e=e.parent}throw r instanceof Error&&sa(r),r}function sa(r){const e=_u.get(r);e&&(gs(r,"message",{value:e.message}),gs(r,"stack",{value:e.stack}))}let ur=[],hr=[];function bu(){var r=ur;ur=[],jn(r)}function Du(){var r=hr;hr=[],jn(r)}function Cu(){ur.length>0&&bu(),hr.length>0&&Du()}function Pu(){const r=te.b;return r===null&&uu(),r}function ia(r){var e=Ve|Je,t=se!==null&&(se.f&Ve)!==0?se:null;return te===null||t!==null&&(t.f&Qe)!==0?e|=Qe:te.f|=ys,{ctx:Ze,deps:null,effects:null,equals:Jn,f:e,fn:r,reactions:null,rv:0,v:be,wv:0,parent:t??te,ac:null}}function ku(r,e){let t=te;t===null&&du();var s=t.b,i=void 0,n=mr(be),a=null,o=!se;return Hu(()=>{try{var c=r();a&&Promise.resolve(c).catch(()=>{})}catch(f){c=Promise.reject(f)}var l=()=>c;i=a?.then(l,l)??Promise.resolve(c),a=i;var u=Ce,h=s.is_pending();o&&(s.update_pending_count(1),h||u.increment());const d=(f,g=void 0)=>{a=null,h||u.activate(),g?g!==lr&&(n.f|=qt,pr(n,g)):((n.f&qt)!==0&&(n.f^=qt),pr(n,f)),o&&(s.update_pending_count(-1),h||u.decrement()),aa()};if(i.then(d,f=>d(null,f||"unknown")),u)return()=>{queueMicrotask(()=>u.neuter())}}),new Promise(c=>{function l(u){function h(){u===i?c(n):l(i)}u.then(h,h)}l(i)})}function ra(r){var e=r.effects;if(e!==null){r.effects=null;for(var t=0;t<e.length;t+=1)Ft(e[t])}}function wu(r){for(var e=r.parent;e!==null;){if((e.f&Ve)===0)return e;e=e.parent}return null}function dr(r){var e,t=te;Nt(wu(r));try{ra(r),e=ka(r)}finally{Nt(t)}return e}function na(r){var e=dr(r);if(r.equals(e)||(r.v=e,r.wv=Ca()),!ss){var t=($t||(r.f&Qe)!==0)&&r.deps!==null?kt:Oe;We(r,t)}}function Ou(r,e,t){const s=ia;if(e.length===0){t(r.map(s));return}var i=Ce,n=te,a=Mu(),o=Pu();Promise.all(e.map(c=>ku(c))).then(c=>{i?.activate(),a();try{t([...r.map(s),...c])}catch(l){(n.f&jt)===0&&cr(l,n)}i?.deactivate(),aa()}).catch(c=>{o.error(c)})}function Mu(){var r=te,e=se,t=Ze,s=Ce;return function(){Nt(r),ut(e),ci(t),s?.activate()}}function aa(){Nt(null),ut(null),ci(null)}const fr=new Set;let Ce=null,oa=new Set,ui=[];function la(){const r=ui.shift();ui.length>0&&queueMicrotask(la),r()}let Xt=[],hi=null,gr=!1,di=!1;class zt{current=new Map;#t=new Map;#e=new Set;#s=0;#c=null;#u=!1;#r=[];#a=[];#n=[];#i=[];#o=[];#h=[];#d=[];skipped_effects=new Set;process(e){Xt=[];for(const i of e)this.#g(i);if(this.#r.length===0&&this.#s===0){this.#f();var t=this.#n,s=this.#i;this.#n=[],this.#i=[],this.#o=[],Ce=null,ua(t),ua(s),Ce===null?Ce=this:fr.delete(this),this.#c?.resolve()}else this.#l(this.#n),this.#l(this.#i),this.#l(this.#o);for(const i of this.#r)xs(i);for(const i of this.#a)xs(i);this.#r=[],this.#a=[]}#g(e){e.f^=Oe;for(var t=e.first;t!==null;){var s=t.f,i=(s&(Tt|Pt))!==0,n=i&&(s&Oe)!==0,a=n||(s&wt)!==0||this.skipped_effects.has(t);if(!a&&t.fn!==null){if(i)t.f^=Oe;else if((s&sr)!==0)this.#i.push(t);else if((s&Oe)===0)if((s&ar)!==0){var o=t.b?.is_pending()?this.#a:this.#r;o.push(t)}else gi(t)&&((t.f&ps)!==0&&this.#o.push(t),xs(t));var c=t.first;if(c!==null){t=c;continue}}var l=t.parent;for(t=t.next;t===null&&l!==null;)t=l.next,l=l.parent}}#l(e){for(const t of e)((t.f&Je)!==0?this.#h:this.#d).push(t),We(t,Oe);e.length=0}capture(e,t){this.#t.has(e)||this.#t.set(e,t),this.current.set(e,e.v)}activate(){Ce=this}deactivate(){Ce=null;for(const e of oa)if(oa.delete(e),e(),Ce!==null)break}neuter(){this.#u=!0}flush(){Xt.length>0?ca():this.#f(),Ce===this&&(this.#s===0&&fr.delete(this),this.deactivate())}#f(){if(!this.#u)for(const e of this.#e)e();this.#e.clear()}increment(){this.#s+=1}decrement(){if(this.#s-=1,this.#s===0){for(const e of this.#h)We(e,Je),Es(e);for(const e of this.#d)We(e,kt),Es(e);this.#n=[],this.#i=[],this.flush()}else this.deactivate()}add_callback(e){this.#e.add(e)}settled(){return(this.#c??=au()).promise}static ensure(){if(Ce===null){const e=Ce=new zt;fr.add(Ce),di||zt.enqueue(()=>{Ce===e&&e.flush()})}return Ce}static enqueue(e){ui.length===0&&queueMicrotask(la),ui.unshift(e)}}function Qt(r){var e=di;di=!0;try{for(var t;;){if(Cu(),Xt.length===0&&(Ce?.flush(),Xt.length===0))return hi=null,t;ca()}}finally{di=e}}function ca(){var r=Ss;gr=!0;try{var e=0;for(_a(!0);Xt.length>0;){var t=zt.ensure();if(e++>1e3){var s,i;Fu()}t.process(Xt),Mt.clear()}}finally{gr=!1,_a(r),hi=null}}function Fu(){try{pu()}catch(r){cr(r,hi)}}let Jt=null;function ua(r){var e=r.length;if(e!==0){for(var t=0;t<e;){var s=r[t++];if((s.f&(jt|wt))===0&&gi(s)&&(Jt=[],xs(s),s.deps===null&&s.first===null&&s.nodes_start===null&&(s.teardown===null&&s.ac===null?xa(s):s.fn=null),Jt?.length>0)){Mt.clear();for(const i of Jt)xs(i);Jt=[]}}Jt=null}}function Es(r){for(var e=hi=r;e.parent!==null;){e=e.parent;var t=e.f;if(gr&&e===te&&(t&ps)!==0)return;if((t&(Pt|Tt))!==0){if((t&Oe)===0)return;e.f^=Oe}}Xt.push(e)}const Mt=new Map;function mr(r,e){var t={f:0,v:r,reactions:null,equals:Jn,rv:0,wv:0};return t}function Be(r,e){const t=mr(r);return Qu(t),t}function Nu(r,e=!1,t=!0){const s=mr(r);return e||(s.equals=Lu),s}function he(r,e,t=!1){se!==null&&(!ct||(se.f&zn)!==0)&&ta()&&(se.f&(Ve|ps|ar|zn))!==0&&!At?.includes(r)&&Tu();let s=t?Us(e):e;return pr(r,s)}function pr(r,e){if(!r.equals(e)){var t=r.v;ss?Mt.set(r,e):Mt.set(r,t),r.v=e;var s=zt.ensure();s.capture(r,t),(r.f&Ve)!==0&&((r.f&Je)!==0&&dr(r),We(r,(r.f&Qe)===0?Oe:kt)),r.wv=Ca(),ha(r,Je),te!==null&&(te.f&Oe)!==0&&(te.f&(Tt|Pt))===0&&(et===null?Ju([r]):et.push(r))}return e}function yr(r){he(r,r.v+1)}function ha(r,e){var t=r.reactions;if(t!==null)for(var s=t.length,i=0;i<s;i++){var n=t[i],a=n.f,o=(a&Je)===0;o&&We(n,e),(a&Ve)!==0?ha(n,kt):o&&((a&ps)!==0&&Jt!==null&&Jt.push(n),Es(n))}}function Us(r){if(typeof r!="object"||r===null||or in r)return r;const e=nu(r);if(e!==iu&&e!==ru)return r;var t=new Map,s=Wn(r),i=Be(0),n=is,a=o=>{if(is===n)return o();var c=se,l=is;ut(null),Da(n);var u=o();return ut(c),Da(l),u};return s&&t.set("length",Be(r.length)),new Proxy(r,{defineProperty(o,c,l){(!("value"in l)||l.configurable===!1||l.enumerable===!1||l.writable===!1)&&vu();var u=t.get(c);return u===void 0?u=a(()=>{var h=Be(l.value);return t.set(c,h),h}):he(u,l.value,!0),!0},deleteProperty(o,c){var l=t.get(c);if(l===void 0){if(c in o){const u=a(()=>Be(be));t.set(c,u),yr(i)}}else he(l,be),yr(i);return!0},get(o,c,l){if(c===or)return r;var u=t.get(c),h=c in o;if(u===void 0&&(!h||ms(o,c)?.writable)&&(u=a(()=>{var f=Us(h?o[c]:be),g=Be(f);return g}),t.set(c,u)),u!==void 0){var d=ae(u);return d===be?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=ae(u))}else if(l===void 0){var h=t.get(c),d=h?.v;if(h!==void 0&&d!==be)return{enumerable:!0,configurable:!0,value:d,writable:!0}}return l},has(o,c){if(c===or)return!0;var l=t.get(c),u=l!==void 0&&l.v!==be||Reflect.has(o,c);if(l!==void 0||te!==null&&(!u||ms(o,c)?.writable)){l===void 0&&(l=a(()=>{var d=u?Us(o[c]):be,f=Be(d);return f}),t.set(c,l));var h=ae(l);if(h===be)return!1}return u},set(o,c,l,u){var h=t.get(c),d=c in o;if(s&&c==="length")for(var f=l;f<h.v;f+=1){var g=t.get(f+"");g!==void 0?he(g,be):f in o&&(g=a(()=>Be(be)),t.set(f+"",g))}if(h===void 0)(!d||ms(o,c)?.writable)&&(h=a(()=>Be(void 0)),he(h,Us(l)),t.set(c,h));else{d=h.v!==be;var p=a(()=>Us(l));he(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&&he(v,E+1)}yr(i)}return!0},ownKeys(o){ae(i);var c=Reflect.ownKeys(o).filter(h=>{var d=t.get(h);return d===void 0||d.v!==be});for(var[l,u]of t)u.v!==be&&!(l in o)&&c.push(l);return c},setPrototypeOf(){Eu()}})}var da,fa,ga,ma;function vr(){if(da===void 0){da=window,fa=/Firefox/.test(navigator.userAgent);var r=Element.prototype,e=Node.prototype,t=Text.prototype;ga=ms(e,"firstChild").get,ma=ms(e,"nextSibling").get,Yn(r)&&(r.__click=void 0,r.__className=void 0,r.__attributes=null,r.__style=void 0,r.__e=void 0),Yn(t)&&(t.__t=void 0)}}function Zt(r=""){return document.createTextNode(r)}function Ts(r){return ga.call(r)}function es(r){return ma.call(r)}function fe(r,e){if(!De)return Ts(r);var t=Ts(Te);return t===null&&(t=Te.appendChild(Zt())),Ot(t),t}function St(r,e){if(!De){var t=Ts(r);return t instanceof Comment&&t.data===""?es(t):t}return Te}function fi(r,e=1,t=!1){let s=De?Te:r;for(var i;e--;)i=s,s=es(s);if(!De)return s;if(t&&s?.nodeType!==Qn){var n=Zt();return s===null?i?.after(n):s.before(n),Ot(n),n}return Ot(s),s}function $u(r){r.textContent=""}function Bu(){return!1}function pa(r){var e=se,t=te;ut(null),Nt(null);try{return r()}finally{ut(e),Nt(t)}}function Uu(r){te===null&&se===null&&mu(),se!==null&&(se.f&Qe)!==0&&te===null&&gu(),ss&&fu()}function Gu(r,e){var t=e.last;t===null?e.last=e.first=r:(t.next=r,r.prev=t,e.last=r)}function xt(r,e,t,s=!0){var i=te;i!==null&&(i.f&wt)!==0&&(r|=wt);var n={ctx:Ze,deps:null,nodes_start:null,nodes_end:null,f:r|Je,first:null,fn:e,last:null,next:null,parent:i,b:i&&i.b,prev:null,teardown:null,transitions:null,wv:0,ac:null};if(t)try{xs(n),n.f|=ir}catch(c){throw Ft(n),c}else e!==null&&Es(n);if(s){var a=n;if(t&&a.deps===null&&a.teardown===null&&a.nodes_start===null&&a.first===a.last&&(a.f&ys)===0&&(a=a.first),a!==null&&(a.parent=i,i!==null&&Gu(a,i),se!==null&&(se.f&Ve)!==0&&(r&Pt)===0)){var o=se;(o.effects??=[]).push(a)}}return n}function ya(r){Uu();var e=te.f,t=!se&&(e&Tt)!==0&&(e&ir)===0;if(t){var s=Ze;(s.e??=[]).push(r)}else return va(r)}function va(r){return xt(sr|lu,r,!1)}function Ku(r){zt.ensure();const e=xt(Pt|ys,r,!0);return()=>{Ft(e)}}function Vu(r){zt.ensure();const e=xt(Pt|ys,r,!0);return(t={})=>new Promise(s=>{t.outro?Aa(e,()=>{Ft(e),s(void 0)}):(Ft(e),s(void 0))})}function Ea(r){return xt(sr,r,!1)}function Hu(r){return xt(ar|ys,r,!0)}function Wu(r,e=0){return xt(qn|e,r,!0)}function ts(r,e=[],t=[]){Ou(e,t,s=>{xt(qn,()=>r(...s.map(ae)),!0)})}function Yu(r,e=0){var t=xt(ps|e,r,!0);return t}function Er(r,e=!0){return xt(Tt|ys,r,!0,e)}function Ta(r){var e=r.teardown;if(e!==null){const t=ss,s=se;Ra(!0),ut(null);try{e.call(null)}finally{Ra(t),ut(s)}}}function Sa(r,e=!1){var t=r.first;for(r.first=r.last=null;t!==null;){const i=t.ac;i!==null&&pa(()=>{i.abort(lr)});var s=t.next;(t.f&Pt)!==0?t.parent=null:Ft(t,e),t=s}}function ju(r){for(var e=r.first;e!==null;){var t=e.next;(e.f&Tt)===0&&Ft(e),e=t}}function Ft(r,e=!0){var t=!1;(e||(r.f&ou)!==0)&&r.nodes_start!==null&&r.nodes_end!==null&&(qu(r.nodes_start,r.nodes_end),t=!0),Sa(r,e&&!t),mi(r,0),We(r,jt);var s=r.transitions;if(s!==null)for(const n of s)n.stop();Ta(r);var i=r.parent;i!==null&&i.first!==null&&xa(r),r.next=r.prev=r.teardown=r.ctx=r.deps=r.fn=r.nodes_start=r.nodes_end=r.ac=null}function qu(r,e){for(;r!==null;){var t=r===e?null:es(r);r.remove(),r=t}}function xa(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 Aa(r,e){var t=[];La(r,t,!0),Xu(t,()=>{Ft(r),e&&e()})}function Xu(r,e){var t=r.length;if(t>0){var s=()=>--t||e();for(var i of r)i.out(s)}else e()}function La(r,e,t){if((r.f&wt)===0){if(r.f^=wt,r.transitions!==null)for(const a of r.transitions)(a.is_global||t)&&e.push(a);for(var s=r.first;s!==null;){var i=s.next,n=(s.f&rr)!==0||(s.f&Tt)!==0;La(s,e,n?t:!1),s=i}}}function zu(r){Ia(r,!0)}function Ia(r,e){if((r.f&wt)!==0){r.f^=wt,(r.f&Oe)===0&&(We(r,Je),Es(r));for(var t=r.first;t!==null;){var s=t.next,i=(t.f&rr)!==0||(t.f&Tt)!==0;Ia(t,i?e:!1),t=s}if(r.transitions!==null)for(const n of r.transitions)(n.is_global||e)&&n.in()}}let Ss=!1;function _a(r){Ss=r}let ss=!1;function Ra(r){ss=r}let se=null,ct=!1;function ut(r){se=r}let te=null;function Nt(r){te=r}let At=null;function Qu(r){se!==null&&(At===null?At=[r]:At.push(r))}let Me=null,He=0,et=null;function Ju(r){et=r}let ba=1,Gs=0,is=Gs;function Da(r){is=r}let $t=!1;function Ca(){return++ba}function gi(r){var e=r.f;if((e&Je)!==0)return!0;if((e&kt)!==0){var t=r.deps,s=(e&Qe)!==0;if(t!==null){var i,n,a=(e&ni)!==0,o=s&&te!==null&&!$t,c=t.length;if((a||o)&&(te===null||(te.f&jt)===0)){var l=r,u=l.parent;for(i=0;i<c;i++)n=t[i],(a||!n?.reactions?.includes(l))&&(n.reactions??=[]).push(l);a&&(l.f^=ni),o&&u!==null&&(u.f&Qe)===0&&(l.f^=Qe)}for(i=0;i<c;i++)if(n=t[i],gi(n)&&na(n),n.wv>r.wv)return!0}(!s||te!==null&&!$t)&&We(r,Oe)}return!1}function Pa(r,e,t=!0){var s=r.reactions;if(s!==null&&!At?.includes(r))for(var i=0;i<s.length;i++){var n=s[i];(n.f&Ve)!==0?Pa(n,e,!1):e===n&&(t?We(n,Je):(n.f&Oe)!==0&&We(n,kt),Es(n))}}function ka(r){var e=Me,t=He,s=et,i=se,n=$t,a=At,o=Ze,c=ct,l=is,u=r.f;Me=null,He=0,et=null,$t=(u&Qe)!==0&&(ct||!Ss||se===null),se=(u&(Tt|Pt))===0?r:null,At=null,ci(r.ctx),ct=!1,is=++Gs,r.ac!==null&&(pa(()=>{r.ac.abort(lr)}),r.ac=null);try{r.f|=nr;var h=r.fn,d=h(),f=r.deps;if(Me!==null){var g;if(mi(r,He),f!==null&&He>0)for(f.length=He+Me.length,g=0;g<Me.length;g++)f[He+g]=Me[g];else r.deps=f=Me;if(!$t||(u&Ve)!==0&&r.reactions!==null)for(g=He;g<f.length;g++)(f[g].reactions??=[]).push(r)}else f!==null&&He<f.length&&(mi(r,He),f.length=He);if(ta()&&et!==null&&!ct&&f!==null&&(r.f&(Ve|kt|Je))===0)for(g=0;g<et.length;g++)Pa(et[g],r);return i!==null&&i!==r&&(Gs++,et!==null&&(s===null?s=et:s.push(...et))),(r.f&qt)!==0&&(r.f^=qt),d}catch(p){return Ru(p)}finally{r.f^=nr,Me=e,He=t,et=s,se=i,$t=n,At=a,ci(o),ct=c,is=l}}function Zu(r,e){let t=e.reactions;if(t!==null){var s=tu.call(t,r);if(s!==-1){var i=t.length-1;i===0?t=e.reactions=null:(t[s]=t[i],t.pop())}}t===null&&(e.f&Ve)!==0&&(Me===null||!Me.includes(e))&&(We(e,kt),(e.f&(Qe|ni))===0&&(e.f^=ni),ra(e),mi(e,0))}function mi(r,e){var t=r.deps;if(t!==null)for(var s=e;s<t.length;s++)Zu(r,t[s])}function xs(r){var e=r.f;if((e&jt)===0){We(r,Oe);var t=te,s=Ss;te=r,Ss=!0;try{(e&ps)!==0?ju(r):Sa(r),Ta(r);var i=ka(r);r.teardown=typeof i=="function"?i:null,r.wv=ba;var n;Hn&&Iu&&(r.f&Je)!==0&&r.deps}finally{Ss=s,te=t}}}function ae(r){var e=r.f,t=(e&Ve)!==0;if(se!==null&&!ct){var s=te!==null&&(te.f&jt)!==0;if(!s&&!At?.includes(r)){var i=se.deps;if((se.f&nr)!==0)r.rv<Gs&&(r.rv=Gs,Me===null&&i!==null&&i[He]===r?He++:Me===null?Me=[r]:(!$t||!Me.includes(r))&&Me.push(r));else{(se.deps??=[]).push(r);var n=r.reactions;n===null?r.reactions=[se]:n.includes(se)||n.push(se)}}}else if(t&&r.deps===null&&r.effects===null){var a=r,o=a.parent;o!==null&&(o.f&Qe)===0&&(a.f^=Qe)}if(ss){if(Mt.has(r))return Mt.get(r);if(t){a=r;var c=a.v;return((a.f&Oe)===0&&a.reactions!==null||wa(a))&&(c=dr(a)),Mt.set(a,c),c}}else t&&(a=r,gi(a)&&na(a));if((r.f&qt)!==0)throw r.v;return r.v}function wa(r){if(r.v===be)return!0;if(r.deps===null)return!1;for(const e of r.deps)if(Mt.has(e)||(e.f&Ve)!==0&&wa(e))return!0;return!1}function Oa(r){var e=ct;try{return ct=!0,r()}finally{ct=e}}const eh=-7169;function We(r,e){r.f=r.f&eh|e}const th=new Set,Ma=new Set;let Fa=null;function pi(r){var e=this,t=e.ownerDocument,s=r.type,i=r.composedPath?.()||[],n=i[0]||r.target;Fa=r;var a=0,o=Fa===r&&r.__root;if(o){var c=i.indexOf(o);if(c!==-1&&(e===document||e===window)){r.__root=e;return}var l=i.indexOf(e);if(l===-1)return;c<=l&&(a=c)}if(n=i[a]||r.target,n!==e){gs(r,"currentTarget",{configurable:!0,get(){return n||t}});var u=se,h=te;ut(null),Nt(null);try{for(var d,f=[];n!==null;){var g=n.assignedSlot||n.parentNode||n.host||null;try{var p=n["__"+s];if(p!=null&&(!n.disabled||r.target===n))if(Wn(p)){var[y,...v]=p;y.apply(n,[r,...v])}else p.call(n,r)}catch(E){d?f.push(E):d=E}if(r.cancelBubble||g===e||g===null)break;n=g}if(d){for(let E of f)queueMicrotask(()=>{throw E});throw d}}finally{r.__root=e,delete r.currentTarget,ut(u),Nt(h)}}}function sh(r){var e=document.createElement("template");return e.innerHTML=r.replaceAll("<!>","<!---->"),e.content}function Bt(r,e){var t=te;t.nodes_start===null&&(t.nodes_start=r,t.nodes_end=e)}function Ut(r,e){var t=(e&Zc)!==0,s=(e&eu)!==0,i,n=!r.startsWith("<!>");return()=>{if(De)return Bt(Te,null),Te;i===void 0&&(i=sh(n?r:"<!>"+r),t||(i=Ts(i)));var a=s||fa?document.importNode(i,!0):i.cloneNode(!0);if(t){var o=Ts(a),c=a.lastChild;Bt(o,c)}else Bt(a,a);return a}}function As(r=""){if(!De){var e=Zt(r+"");return Bt(e,e),e}var t=Te;return t.nodeType!==Qn&&(t.before(t=Zt()),Ot(t)),Bt(t,t),t}function rs(){if(De)return Bt(Te,null),Te;var r=document.createDocumentFragment(),e=document.createComment(""),t=Zt();return r.append(e,t),Bt(e,t),r}function ve(r,e){if(De){te.nodes_end=Te,li();return}r!==null&&r.before(e)}const ih=["touchstart","touchmove"];function rh(r){return ih.includes(r)}function Ls(r,e){var t=e==null?"":typeof e=="object"?e+"":e;t!==(r.__t??=r.nodeValue)&&(r.__t=t,r.nodeValue=t+"")}function Na(r,e){return $a(r,e)}function nh(r,e){vr(),e.intro=e.intro??!1;const t=e.target,s=De,i=Te;try{for(var n=Ts(t);n&&(n.nodeType!==ai||n.data!==Gn);)n=es(n);if(!n)throw fs;vs(!0),Ot(n),li();const a=$a(r,{...e,anchor:n});if(Te===null||Te.nodeType!==ai||Te.data!==Vn)throw oi(),fs;return vs(!1),a}catch(a){if(a instanceof Error&&a.message.split(`
|
|
2
|
-
`).some(o=>o.startsWith("https://svelte.dev/e/")))throw a;return a!==fs&&console.warn("Failed to hydrate: ",a),e.recover===!1&&yu(),vr(),$u(t),vs(!1),Na(r,e)}finally{vs(s),Ot(i)}}const Is=new Map;function $a(r,{target:e,anchor:t,props:s={},events:i,context:n,intro:a=!0}){vr();var o=new Set,c=h=>{for(var d=0;d<h.length;d++){var f=h[d];if(!o.has(f)){o.add(f);var g=rh(f);e.addEventListener(f,pi,{passive:g});var p=Is.get(f);p===void 0?(document.addEventListener(f,pi,{passive:g}),Is.set(f,1)):Is.set(f,p+1)}}};c(su(th)),Ma.add(c);var l=void 0,u=Vu(()=>{var h=t??e.appendChild(Zt());return Er(()=>{if(n){Zn({});var d=Ze;d.c=n}i&&(s.$$events=i),De&&Bt(h,null),l=r(h,s)||{},De&&(te.nodes_end=Te),n&&ea()}),()=>{for(var d of o){e.removeEventListener(d,pi);var f=Is.get(d);--f===0?(document.removeEventListener(d,pi),Is.delete(d)):Is.set(d,f)}Ma.delete(c),h!==t&&h.parentNode?.removeChild(h)}});return Tr.set(l,u),l}let Tr=new WeakMap;function ah(r,e){const t=Tr.get(r);return t?(Tr.delete(r),t(e)):Promise.resolve()}function oh(r){Ze===null&&hu(),ya(()=>{const e=Oa(r);if(typeof e=="function")return e})}function ns(r,e,t=!1){De&&li();var s=r,i=null,n=null,a=be,o=t?rr:0,c=!1;const l=(f,g=!0)=>{c=!0,d(g,f)};var u=null;function h(){u!==null&&(u.lastChild.remove(),s.before(u),u=null);var f=a?i:n,g=a?n:i;f&&zu(f),g&&Aa(g,()=>{a?n=null:i=null})}const d=(f,g)=>{if(a===(a=f))return;let p=!1;if(De){const A=xu(s)===Kn;!!a===A&&(s=Su(),Ot(s),vs(!1),p=!0)}var y=Bu(),v=s;if(y&&(u=document.createDocumentFragment(),u.append(v=Zt())),a?i??=g&&Er(()=>g(v)):n??=g&&Er(()=>g(v)),y){var E=Ce,T=a?i:n,S=a?n:i;T&&E.skipped_effects.delete(T),S&&E.skipped_effects.add(S),E.add_callback(h)}else h();p&&vs(!0)};Yu(()=>{c=!1,e(l),c||d(null,null)},o),De&&(s=Te)}function Lt(r,e,t,s,i){De&&li();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 lh(r,e){Ea(()=>{var t=r.getRootNode(),s=t.host?t:t.head??t.ownerDocument.head;if(!s.querySelector("#"+e.hash)){const i=document.createElement("style");i.id=e.hash,i.textContent=e.code,s.appendChild(i)}})}function ch(r,e,t){Ea(()=>{var s=Oa(()=>e(r,t?.())||{});if(s?.destroy)return()=>s.destroy()})}function _s(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=ia(()=>(l=!1,c())),h=te;return(function(d,f){if(arguments.length>0){const g=f?ae(u):d;return he(u,g),l=!0,i!==void 0&&(i=g),d}return ss&&l||(h.f&jt)!==0?u.v:ae(u)})}function uh(r){return new hh(r)}class hh{#t;#e;constructor(e){var t=new Map,s=(n,a)=>{var o=Nu(a,!1,!1);return t.set(n,o),o};const i=new Proxy({...e.props||{},$$events:{}},{get(n,a){return ae(t.get(a)??s(a,Reflect.get(n,a)))},has(n,a){return a===cu?!0:(ae(t.get(a)??s(a,Reflect.get(n,a))),Reflect.has(n,a))},set(n,a,o){return he(t.get(a)??s(a,o),o),Reflect.set(n,a,o)}});this.#e=(e.hydrate?nh:Na)(e.component,{target:e.target,anchor:e.anchor,props:i,context:e.context,intro:e.intro??!1,recover:e.recover}),(!e?.props?.$$host||e.sync===!1)&&Qt(),this.#t=i.$$events;for(const n of Object.keys(this.#e))n==="$set"||n==="$destroy"||n==="$on"||gs(this,n,{get(){return this.#e[n]},set(a){this.#e[n]=a},enumerable:!0});this.#e.$set=n=>{Object.assign(i,n)},this.#e.$destroy=()=>{ah(this.#e)}}$set(e){this.#e.$set(e)}$on(e,t){this.#t[e]=this.#t[e]||[];const s=(...i)=>t.call(this,...i);return this.#t[e].push(s),()=>{this.#t[e]=this.#t[e].filter(i=>i!==s)}}$destroy(){this.#e.$destroy()}}let Ba;typeof HTMLElement=="function"&&(Ba=class extends HTMLElement{$$ctor;$$s;$$c;$$cn=!1;$$d={};$$r=!1;$$p_d={};$$l={};$$l_u=new Map;$$me;constructor(r,e,t){super(),this.$$ctor=r,this.$$s=e,t&&this.attachShadow({mode:"open"})}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=document.createElement("slot");s!=="default"&&(n.name=s),ve(i,n)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;const e={},t=dh(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]=yi(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=uh({component:this.$$ctor,target:this.shadowRoot||this,props:{...this.$$d,$$slots:e,$$host:this}}),this.$$me=Ku(()=>{Wu(()=>{this.$$r=!0;for(const s of ri(this.$$c)){if(!this.$$p_d[s]?.reflect)continue;this.$$d[s]=this.$$c[s];const i=yi(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]=yi(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 ri(this.$$p_d).find(e=>this.$$p_d[e].attribute===r||!this.$$p_d[e].attribute&&e.toLowerCase()===r)||r}});function yi(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 dh(r){const e={};return r.childNodes.forEach(t=>{e[t.slot||"default"]=!0}),e}function fh(r,e,t,s,i,n){let a=class extends Ba{constructor(){super(r,t,i),this.$$p_d=e}static get observedAttributes(){return ri(e).map(o=>(e[o].attribute||o).toLowerCase())}};return ri(e).forEach(o=>{gs(a.prototype,o,{get(){return this.$$c&&o in this.$$c?this.$$c[o]:this.$$d[o]},set(c){c=yi(o,c,e),this.$$d[o]=c;var l=this.$$c;if(l){var u=ms(l,o)?.get;u?l[o]=c:l.$set({[o]:c})}}})}),s.forEach(o=>{gs(a.prototype,o,{get(){return this.$$c?.[o]}})}),r.element=a,a}const $=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},gh=Number.isSafeInteger||function(r){return typeof r=="number"&&Math.abs(r)<=mh},mh=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})({}),b=(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"},V={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Rs{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 ph{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 Rs(e),this.fast_=new Rs(t),this.defaultTTFB_=i,this.ttfb_=new Rs(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:n}=this;s.halfLife!==e&&(this.slow_=new Rs(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new Rs(t,i.getEstimate(),i.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new Rs(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 yh(r,e,t){return(e=Eh(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function oe(){return oe=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},oe.apply(null,arguments)}function Ua(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 re(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Ua(Object(t),!0).forEach(function(s){yh(r,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Ua(Object(t)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(t,s))})}return r}function vh(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 Eh(r){var e=vh(r,"string");return typeof e=="symbol"?e:e+""}class tt{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=Gt,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 Gt=function(){},Th={trace:Gt,debug:Gt,log:Gt,warn:Gt,info:Gt,error:Gt};function Sr(){return oe({},Th)}function Sh(r,e){const t=self.console[r];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${r}] >`):Gt}function Ga(r,e,t){return e[r]?e[r].bind(e):Sh(r,t)}const xr=Sr();function xh(r,e,t){const s=Sr();if(typeof console=="object"&&r===!0||typeof r=="object"){const i=["debug","log","info","warn","error"];i.forEach(n=>{s[n]=Ga(n,r,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.12`)}catch{return Sr()}i.forEach(n=>{xr[n]=Ga(n,r)})}else oe(xr,s);return s}const ne=xr;function Kt(r=!0){return typeof self>"u"?void 0:(r||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Ah(r){return typeof self<"u"&&r===self.ManagedMediaSource}function Ka(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 Ye(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 Ue(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 Va(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Lh(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ar={exports:{}},Ha;function Ih(){return Ha||(Ha=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 f=o.parseURL(c);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=i.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(p.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)p.path=f.path,d.params||(p.params=f.params,d.query||(p.query=f.query));else{var y=f.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})()})(Ar)),Ar.exports}var Lr=Ih();class Ir{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 le={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Wa{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,Rh(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={[le.AUDIO]:null,[le.VIDEO]:null,[le.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 Ir),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Lr.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[le.AUDIO]=null,e[le.VIDEO]=null,e[le.AUDIOVIDEO]=null}}function Se(r){return r.sn!=="initSegment"}class _r extends Wa{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(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const s=Object.keys(this.levelkeys);if(s.length===1){const i=this._decryptdata=this.levelkeys[s[0]]||null;if(i)return i.getDecryptData(this.sn)}}}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 Se(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){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}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 _h extends Wa{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 Ya(r,e){const t=Object.getPrototypeOf(r);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||Ya(t,e)}}function Rh(r,e){const t=Ya(r,e);t&&(t.enumerable=!0,Object.defineProperty(r,e,t))}const ja=Math.pow(2,32)-1,bh=[].push,qa={video:1,audio:2,id3:3,text:4};function Le(r){return String.fromCharCode.apply(null,r)}function Xa(r,e){const t=r[e]<<8|r[e+1];return t<0?65536+t:t}function j(r,e){const t=Qa(r,e);return t<0?4294967296+t:t}function za(r,e){let t=j(r,e);return t*=Math.pow(2,32),t+=j(r,e+4),t}function Qa(r,e){return r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}function Dh(r){const e=r.byteLength;for(let t=0;t<e;){const s=j(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=j(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&&bh.apply(t,c)}i=o}return t}function Ch(r){const e=[],t=r[0];let s=8;const i=j(r,s);s+=4;let n=0,a=0;t===0?(n=j(r,s),a=j(r,s+4),s+=8):(n=za(r,s),a=za(r,s+8),s+=16),s+=2;let o=r.length+a;const c=Xa(r,s);s+=2;for(let l=0;l<c;l++){let u=s;const h=j(r,u);u+=4;const d=h&2147483647;if((h&2147483648)>>>31===1)return ne.warn("SIDX has hierarchical references (not supported)"),null;const g=j(r,u);u+=4,e.push({referenceSize:d,subsegmentDuration:g,info:{duration:g/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 Ja(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=j(a,o===0?12:20),l=J(n,["mdia","mdhd"])[0];if(l){o=l[0];const u=j(l,o===0?12:20),h=J(n,["mdia","hdlr"])[0];if(h){const d=Le(h.subarray(8,12)),f={soun:le.AUDIO,vide:le.VIDEO}[d],g=J(n,["mdia","minf","stbl","stsd"])[0],p=Ph(g);f?(e[c]={timescale:u,type:f,stsd:p},e[f]=re({timescale:u,id:c},p)):e[c]={timescale:u,type:d,stsd:p}}}}}return J(r,["moov","mvex","trex"]).forEach(i=>{const n=j(i,4),a=e[n];a&&(a.default={duration:j(i,12),flags:j(i,20)})}),e}function Ph(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 f=Le(d.subarray(4,8));if(f==="cbcs"||f==="cenc"){const g=J(h,["frma"])[0];g&&(i=Le(g))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const c=J(t,["avcC"])[0];c&&c.length>3&&(i+="."+Ei(c[1])+Ei(c[2])+Ei(c[3]),n=vi(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=Rr(l,u),u+=2;const h=l[u++];if(h&128&&(u+=2),h&64&&(u+=l[u++]),l[u++]!==4)break;u=Rr(l,u);const d=l[u++];if(d===64)i+="."+Ei(d);else break;if(u+=12,l[u++]!==5)break;u=Rr(l,u);const f=l[u++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((l[u]&224)>>5)),i+="."+g}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=j(c,2),f=(l&32)>>5?"H":"L",g=c[12],p=c.subarray(6,12);i+="."+u+h,i+="."+kh(d).toString(16).toUpperCase(),i+="."+f+g;let y="";for(let v=p.length;v--;){const E=p[v];(E||y)&&(y="."+E.toString(16).toUpperCase()+y)}i+=y}n=vi(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=vi(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+="."+ht(l)+"."+ht(u)+"."+ht(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,f=(c[2]&32)>>5,g=l===2&&d?f?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+"."+ht(u)+h+"."+ht(g)+"."+p+"."+y+v+E+"."+ht(1)+"."+ht(1)+"."+ht(1)+"."+0,n=vi("dav1",t)}break}}return{codec:i,encrypted:a,supplemental:n}}function vi(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+"."+ht(i)+"."+ht(n)}}function kh(r){let e=0;for(let t=0;t<32;t++)e|=(r>>t&1)<<31-t;return e>>>0}function Rr(r,e){const t=e+5;for(;r[e++]&128&&e<t;);return e}function Ei(r){return("0"+r.toString(16).toUpperCase()).slice(-2)}function ht(r){return(r<10?"0":"")+r}function wh(r,e){if(!r||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&J(r,["moov","trak"]).forEach(i=>{const a=J(i,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=J(a,["enca"]);const c=o.length>0;c||(o=J(a,["encv"])),o.forEach(l=>{const u=c?l.subarray(28):l.subarray(78);J(u,["sinf"]).forEach(d=>{const f=Za(d);if(f){const g=f.subarray(8,24);g.some(p=>p!==0)||(ne.log(`[eme] Patching keyId in 'enc${c?"a":"v"}>sinf>>tenc' box: ${Ue(g)} -> ${Ue(t)}`),f.set(t,8))}})})})}function Za(r){const e=J(r,["schm"])[0];if(e){const t=Le(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return J(r,["schi","tenc"])[0]}return null}function Oh(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=j(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=j(h,4);T===1&&(S===ja?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=ja+1,S+=j(h,8))),$(S)&&(!$(u.start)||S<u.start)&&(u.start=S)}const d=l.default,f=j(o,0)|d?.flags;let g=d?.duration||0;f&8&&(f&2?g=j(o,12):g=j(o,8));const p=J(a,["trun"]);let y=u.start||0,v=0,E=g;for(let T=0;T<p.length;T++){const S=p[T],A=j(S,4),D=u.sampleCount;u.sampleCount+=A;const L=S[3]&1,x=S[3]&4,I=S[2]&1,_=S[2]&2,C=S[2]&4,F=S[2]&8;let N=8,U=A;for(L&&(N+=4),x&&A&&(!(S[N+1]&1)&&u.keyFrameIndex===void 0&&(u.keyFrameIndex=D),N+=4,I?(E=j(S,N),N+=4):E=g,_&&(N+=4),F&&(N+=4),y+=E,v+=E,U--);U--;)I?(E=j(S,N),N+=4):E=g,_&&(N+=4),C&&(S[N+1]&1||u.keyFrameIndex===void 0&&(u.keyFrameIndex=u.sampleCount-(U+1),u.keyFrameStart=y),N+=4),F&&(N+=4),y+=E,v+=E;!v&&g&&(v+=g*A)}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=Ch(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 Mh(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 st(r,e){const t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function eo(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(f=>{const g=f[0];let p=j(f,4);return g===1&&(p*=Math.pow(2,32),p+=j(f,8)),p/i})[0];return d!==void 0&&(r=d),J(h,["tfhd"]).map(f=>{const g=j(f,4),p=j(f,0)&16777215,y=(p&1)!==0,v=(p&2)!==0,E=(p&8)!==0;let T=0;const S=(p&16)!==0;let A=0;const D=(p&32)!==0;let L=8;g===n&&(y&&(L+=8),v&&(L+=4),E&&(T=j(f,L),L+=4),S&&(A=j(f,L),L+=4),D&&(L+=4),e.type==="video"&&(a=Ti(e.codec)),J(h,["trun"]).map(x=>{const I=x[0],_=j(x,0)&16777215,C=(_&1)!==0;let F=0;const N=(_&4)!==0,U=(_&256)!==0;let B=0;const w=(_&512)!==0;let G=0;const O=(_&1024)!==0,K=(_&2048)!==0;let W=0;const M=j(x,4);let k=8;C&&(F=j(x,k),k+=4),N&&(k+=4);let Y=F+l;for(let Z=0;Z<M;Z++){if(U?(B=j(x,k),k+=4):B=T,w?(G=j(x,k),k+=4):G=A,O&&(k+=4),K&&(I===0?W=j(x,k):W=Qa(x,k),k+=4),e.type===le.VIDEO){let q=0;for(;q<G;){const z=j(s,Y);if(Y+=4,Fh(a,s[Y])){const me=s.subarray(Y,Y+z);br(me,a?2:1,r+W/i,t)}Y+=z,q+=z+4}}r+=B/i}}))})})}),t}function Ti(r){if(!r)return!1;const e=r.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Fh(r,e){if(r){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function br(r,e,t,s){const i=to(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){ne.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(a===4){if(i[u++]===181){const d=Xa(i,u);if(u+=2,d===49){const f=j(i,u);if(u+=4,f===1195456820){const g=i[u++];if(g===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:g,payloadType:a,pts:t,bytes:T})}}}}}else if(a===5&&o>16){const h=[];for(let g=0;g<16;g++){const p=i[u++].toString(16);h.push(p.length==1?"0"+p:p),(g===3||g===5||g===7||g===9)&&h.push("-")}const d=o-16,f=new Uint8Array(d);for(let g=0;g<d;g++)f[g]=i[u++];s.push({payloadType:a,pts:t,uuid:h.join(""),userData:Ye(f),userDataBytes:f})}}}function to(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 Nh(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=j(r,12),n=j(r,16),o=j(r,20),c=j(r,24),l=28}else if(e===1){l+=4,i=j(r,l),l+=4;const h=j(r,l);l+=4;const d=j(r,l);for(l+=4,a=2**32*h+d,gh(a)||(a=Number.MAX_SAFE_INTEGER,ne.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=j(r,l),l+=4,c=j(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 $h(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 Bh(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),$h([112,115,115,104],new Uint8Array([s,0,0,0]),r,n,i,a,t)}function Uh(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=Gh(i);e.push(n),s+=n.size}}return e}function Gh(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=Ue(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 f=0;f<d;f++)c.push(new Uint8Array(a,t+32+f*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 so=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),bs={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 Dr(r,e){const t=bs[e];return!!t&&!!t[r.slice(0,4)]}function Ks(r,e,t=!0){return!r.split(",").some(s=>!Cr(s,e,t))}function Cr(r,e,t=!0){var s;const i=Kt(t);return(s=i?.isTypeSupported(Vs(r,e)))!=null?s:!1}function Vs(r,e){return`${e}/mp4;codecs=${r}`}function io(r){if(r){const e=r.substring(0,4);return bs.video[e]}return 2}function Si(r){const e=so();return r.split(",").reduce((t,s)=>{const n=e&&Ti(s)?9:bs.video[s];return n?(n*2+t)/(t?3:2):(bs.audio[s]+t)/(t?2:1)},0)}const Pr={};function Kh(r,e=!0){if(Pr[r])return Pr[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(Cr(t[i],"audio",e))return Pr[r]=t[i],t[i];if(t[i]==="mp3"&&(s=Kt(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return r}const Vh=/flac|opus|mp4a\.40\.34/i;function xi(r,e=!0){return r.replace(Vh,t=>Kh(t.toLowerCase(),e))}function Hh(r,e){const t=[];if(r){const s=r.split(",");for(let i=0;i<s.length;i++)Dr(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function Ai(r,e){if(r&&(r.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(r)!==-1)&&(ro(r,"audio")||ro(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 ro(r,e){return Dr(r,e)&&Cr(r,e)}function Wh(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 Yh(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 no(r){const e=Kt(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 kr(r){return r.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const jh={supported:!0,powerEfficient:!0,smooth:!0},qh={supported:!1,smooth:!1,powerEfficient:!1},ao={supported:!0,configurations:[],decodingInfoResults:[jh]};function oo(r,e){return{supported:!1,configurations:e,decodingInfoResults:[qh],error:r}}function Xh(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,f)=>{if(f){const g=e.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(p=>{d[p]=(d[p]||0)+g.channels[p]})}return d},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(d=>Ti(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 lo(r,e,t,s={}){const i=r.videoCodec;if(!i&&!r.audioCodec||!t)return Promise.resolve(ao);const n=[],a=zh(r),o=a.length,c=Qh(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=>Ti(h))&&so())return Promise.resolve(oo(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),n))}return Promise.all(n.map(u=>{const h=Zh(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 zh(r){var e;const t=(e=r.videoCodec)==null?void 0:e.split(","),s=co(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:Vs(Yh(c),"video"),width:i,height:n,bitrate:s,framerate:a};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function Qh(r,e,t){var s;const i=(s=r.audioCodec)==null?void 0:s.split(","),n=co(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(f=>{const g={contentType:Vs(f,"audio"),bitrate:t?Jh(f,n):n};d&&(g.channels=""+d),u.push(g)})}return u},a):a},[]):[]}function Jh(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 co(r){return Math.ceil(Math.max(r.bitrate*.9,r.averageBitrate)/1e3)*1e3||1}function Zh(r){let e="";const{audio:t,video:s}=r;if(s){const i=kr(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=kr(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}const wr=["NONE","TYPE-0","TYPE-1",null];function ed(r){return wr.indexOf(r)>-1}const Li=["SDR","PQ","HLG"];function td(r){return!!r&&Li.indexOf(r)>-1}var Ii={No:"",Yes:"YES",v2:"v2"};function uo(r){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=r,i=s<e/2;return e&&i?t?Ii.v2:Ii.Yes:Ii.No}class ho{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 Hs{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 fo(this._audioGroups,e)}hasSubtitleGroup(e){return fo(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 fo(r,e){return!e||!r?!1:r.indexOf(e)!==-1}function sd(){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 id(r,e){let t=!1,s=[];if(r&&(t=r!=="SDR",s=[r]),e){s=e.allowedVideoRanges||Li.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&sd(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const rd=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}},ce=(r,e)=>JSON.stringify(r,rd(e));function nd(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,f=1/0,g=1/0,p=1/0,y=0,v=[];const{preferHDR:E,allowedVideoRanges:T}=id(e,i);for(let x=n.length;x--;){const I=r[n[x]];u||(u=I.channels[2]>0),d=Math.min(d,I.minHeight),f=Math.min(f,I.minFramerate),g=Math.min(g,I.minBitrate),T.filter(C=>I.videoRanges[C]>0).length>0&&(h=!0)}d=$(d)?d:0,f=$(f)?f:0;const S=Math.max(1080,d),A=Math.max(30,f);g=$(g)?g:t,t=Math.max(g,t),h||(e=void 0);const D=n.length>1;return{codecSet:n.reduce((x,I)=>{const _=r[I];if(I===x)return x;if(v=h?T.filter(C=>_.videoRanges[C]>0):[],D){if(_.minBitrate>t)return dt(I,`min bitrate of ${_.minBitrate} > current estimate of ${t}`),x;if(!_.hasDefaultAudio)return dt(I,"no renditions with default or auto-select sound found"),x;if(o&&I.indexOf(o.substring(0,4))%5!==0)return dt(I,`audio codec preference "${o}" not found`),x;if(a&&!l){if(!_.channels[a])return dt(I,`no renditions with ${a} channel sound found (channels options: ${Object.keys(_.channels)})`),x}else if((!o||l)&&u&&_.channels[2]===0)return dt(I,"no renditions with stereo sound found"),x;if(_.minHeight>S)return dt(I,`min resolution of ${_.minHeight} > maximum of ${S}`),x;if(_.minFramerate>A)return dt(I,`min framerate of ${_.minFramerate} > maximum of ${A}`),x;if(!v.some(C=>_.videoRanges[C]>0))return dt(I,`no variants with VIDEO-RANGE of ${ce(v)} found`),x;if(c&&I.indexOf(c.substring(0,4))%5!==0)return dt(I,`video codec preference "${c}" not found`),x;if(_.maxScore<y)return dt(I,`max score of ${_.maxScore} < selected max of ${y}`),x}return x&&(Si(I)>=Si(x)||_.fragmentError>r[x].fragmentError)?x:(p=_.minIndex,y=_.maxScore,I)},void 0),videoRanges:v,preferHDR:E,minFramerate:f,minBitrate:g,minIndex:p}}function dt(r,e){ne.log(`[abr] start candidates with "${r}" ignored because ${e}`)}function go(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 ad(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 mo(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 ft(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(as(r,i,t))return s}return-1}function as(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||od(n,e.lang))&&(n===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in r)||ld(r.characteristics||"",e.characteristics))&&(t===void 0||t(r,e))}function od(r,e="--"){return r.length===e.length?r===e:r.startsWith(e)||e.startsWith(r)}function ld(r,e=""){const t=r.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function os(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 cd(r,e,t,s,i){const n=e[s],o=e.reduce((d,f,g)=>{const p=f.uri;return(d[p]||(d[p]=[])).push(g),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=po(e,s,d=>{if(d.videoRange!==c||d.frameRate!==l||d.codecSet.substring(0,4)!==u)return!1;const f=d.audioGroups,g=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return ft(r,g,i)>-1});return h>-1?h:po(e,s,d=>{const f=d.audioGroups,g=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return ft(r,g,i)>-1})}function po(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 _i(r,e){var t;return!!r&&r!==((t=e.loadLevelObj)==null?void 0:t.uri)}class ud extends tt{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,f=a.minAutoLevel,g=i.level,p=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const y=p>-1&&p!==g,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 A=E?E.len/S:0,D=u.loading.first?u.loading.first-u.loading.start:-1,L=u.loaded&&D>-1,x=this.getBwEstimate(),I=a.levels,_=I[g],C=Math.max(u.loaded,Math.round(h*(i.bitrate||_.averageBitrate)/8));let F=L?d-D:d;F<1&&L&&(F=Math.min(d,u.loaded*8/x));const N=L?u.loaded*1e3/F:0,U=T/1e3,B=N?(C-u.loaded)/N:C*8/x+U;if(B<=A)return;const w=N?N*8:x,G=((s=t?.details||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,O=this.hls.config.abrBandWidthUpFactor;let K=Number.POSITIVE_INFINITY,W;for(W=g-1;W>f;W--){const Z=I[W].maxBitrate,q=!I[W].details||G;if(K=this.getTimeToLoadFrag(U,w,h*Z,q),K<Math.min(A,h+U))break}if(K>=B||K>h*10)return;L?this.bwEstimator.sample(d-Math.min(T,D),u.loaded):this.bwEstimator.sampleTTFB(d);const M=I[W].maxBitrate;this.getBwEstimate()*O>M&&this.resetEstimator(M);const k=this.findBestLevel(M,f,W,0,A,1,1);k>-1&&(W=k),this.warn(`Fragment ${i.sn}${n?" part "+n.index:""} of level ${g} is loading too slowly;
|
|
1
|
+
(function(jn){"use strict";typeof window<"u"&&((window.__svelte??={}).v??=new Set).add("5");const du=1,fu=2,Xn="[",pr="[!",zn="]",Ts={},ke=Symbol(),Qn=!1;var gu=Array.isArray,mu=Array.prototype.indexOf,pu=Array.from,pi=Object.keys,yi=Object.defineProperty,Ss=Object.getOwnPropertyDescriptor,yu=Object.prototype,vu=Array.prototype,Eu=Object.getPrototypeOf,Jn=Object.isExtensible;function Tu(r){for(var e=0;e<r.length;e++)r[e]()}function Zn(){var r,e,t=new Promise((s,i)=>{r=s,e=i});return{promise:t,resolve:r,reject:e}}const we=2,vi=4,yr=8,Dt=16,Ct=32,Ht=64,Ei=128,lt=512,Oe=1024,Ke=2048,Pt=4096,gt=8192,Wt=16384,vr=32768,xs=65536,ea=1<<17,ta=1<<18,ss=1<<19,Su=1<<20,Ws=32768,Er=1<<21,Tr=1<<22,Yt=1<<23,Sr=Symbol("$state"),xu=Symbol("legacy props"),As=new class extends Error{name="StaleReactionError";message="The reaction that called `getAbortSignal()` was re-run or destroyed"},xr=3,Ys=8;function Au(r){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function _u(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function Iu(r){throw new Error("https://svelte.dev/e/effect_in_teardown")}function Lu(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function Ru(r){throw new Error("https://svelte.dev/e/effect_orphan")}function bu(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function Du(){throw new Error("https://svelte.dev/e/hydration_failed")}function Cu(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function Pu(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function ku(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function wu(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}function Ti(r){console.warn("https://svelte.dev/e/hydration_mismatch")}function Ou(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}let Ee=!1;function _s(r){Ee=r}let le;function ct(r){if(r===null)throw Ti(),Ts;return le=r}function Si(){return ct(wt(le))}function fe(r){if(Ee){if(wt(le)!==null)throw Ti(),Ts;le=r}}function Mu(r=1){if(Ee){for(var e=r,t=le;e--;)t=wt(t);le=t}}function sa(r=!0){for(var e=0,t=le;;){if(t.nodeType===Ys){var s=t.data;if(s===zn){if(e===0)return t;e-=1}else(s===Xn||s===pr)&&(e+=1)}var i=wt(t);r&&t.remove(),t=i}}function Fu(r){if(!r||r.nodeType!==Ys)throw Ti(),Ts;return r.data}function ia(r){return r===this.v}function Nu(r,e){return r!=r?e==e:r!==e||r!==null&&typeof r=="object"||typeof r=="function"}function $u(r){return!Nu(r,this.v)}let Bu=!1,je=null;function Is(r){je=r}function ra(r,e=!1,t){je={p:je,i:!1,c:null,e:null,s:r,x:null,l:null}}function na(r){var e=je,t=e.e;if(t!==null){e.e=null;for(var s of t)_a(s)}return r!==void 0&&(e.x=r),e.i=!0,je=e.p,r??{}}function aa(){return!0}let is=[];function oa(){var r=is;is=[],Tu(r)}function Ar(r){if(is.length===0&&!qs){var e=is;queueMicrotask(()=>{e===is&&oa()})}is.push(r)}function Uu(){for(;is.length>0;)oa()}function la(r){var e=ie;if(e===null)return te.f|=Yt,r;if((e.f&vr)===0){if((e.f&Ei)===0)throw r;e.b.error(r)}else Ls(r,e)}function Ls(r,e){for(;e!==null;){if((e.f&Ei)!==0)try{e.b.error(r);return}catch(t){r=t}e=e.parent}throw r}const xi=new Set;let Ie=null,Xe=null,mt=[],Ai=null,_r=!1,qs=!1;class ut{committed=!1;current=new Map;previous=new Map;#t=new Set;#e=new Set;#s=0;#i=0;#l=null;#a=[];#o=[];skipped_effects=new Set;is_fork=!1;process(e){mt=[],this.apply();var t={parent:null,effect:null,effects:[],render_effects:[],block_effects:[]};for(const s of e)this.#r(s,t);this.is_fork||this.#c(),this.#i>0||this.is_fork?(this.#n(t.effects),this.#n(t.render_effects),this.#n(t.block_effects)):(Ie=null,ua(t.render_effects),ua(t.effects),this.#l?.resolve()),Xe=null}#r(e,t){e.f^=Oe;for(var s=e.first;s!==null;){var i=s.f,n=(i&(Ct|Ht))!==0,a=n&&(i&Oe)!==0,o=a||(i>)!==0||this.skipped_effects.has(s);if((s.f&Ei)!==0&&s.b?.is_pending()&&(t={parent:t,effect:s,effects:[],render_effects:[],block_effects:[]}),!o&&s.fn!==null){n?s.f^=Oe:(i&vi)!==0?t.effects.push(s):Zs(s)&&((s.f&Dt)!==0&&t.block_effects.push(s),ei(s));var c=s.first;if(c!==null){s=c;continue}}var l=s.parent;for(s=s.next;s===null&&l!==null;)l===t.effect&&(this.#n(t.effects),this.#n(t.render_effects),this.#n(t.block_effects),t=t.parent),s=l.next,l=l.parent}}#n(e){for(const t of e)((t.f&Ke)!==0?this.#a:this.#o).push(t),Me(t,Oe)}capture(e,t){this.previous.has(e)||this.previous.set(e,t),(e.f&Yt)===0&&(this.current.set(e,e.v),Xe?.set(e,e.v))}activate(){Ie=this,this.apply()}deactivate(){Ie=null,Xe=null}flush(){if(this.activate(),mt.length>0){if(ca(),Ie!==null&&Ie!==this)return}else this.#s===0&&this.process([]);this.deactivate()}discard(){for(const e of this.#e)e(this);this.#e.clear()}#c(){if(this.#i===0){for(const e of this.#t)e();this.#t.clear()}this.#s===0&&this.#u()}#u(){if(xi.size>1){this.previous.clear();var e=Xe,t=!0,s={parent:null,effect:null,effects:[],render_effects:[],block_effects:[]};for(const i of xi){if(i===this){t=!1;continue}const n=[];for(const[o,c]of this.current){if(i.current.has(o))if(t&&c!==i.current.get(o))i.current.set(o,c);else continue;n.push(o)}if(n.length===0)continue;const a=[...i.current.keys()].filter(o=>!this.current.has(o));if(a.length>0){const o=new Set,c=new Map;for(const l of n)ha(l,a,o,c);if(mt.length>0){Ie=i,i.apply();for(const l of mt)i.#r(l,s);mt=[],i.deactivate()}}}Ie=null,Xe=e}this.committed=!0,xi.delete(this)}increment(e){this.#s+=1,e&&(this.#i+=1)}decrement(e){this.#s-=1,e&&(this.#i-=1),this.revive()}revive(){for(const e of this.#a)Me(e,Ke),ns(e);for(const e of this.#o)Me(e,Pt),ns(e);this.#a=[],this.#o=[],this.flush()}oncommit(e){this.#t.add(e)}ondiscard(e){this.#e.add(e)}settled(){return(this.#l??=Zn()).promise}static ensure(){if(Ie===null){const e=Ie=new ut;xi.add(Ie),qs||ut.enqueue(()=>{Ie===e&&e.flush()})}return Ie}static enqueue(e){Ar(e)}apply(){}}function rs(r){var e=qs;qs=!0;try{for(var t;;){if(Uu(),mt.length===0&&(Ie?.flush(),mt.length===0))return Ai=null,t;ca()}}finally{qs=e}}function ca(){var r=os;_r=!0;try{var e=0;for(Oa(!0);mt.length>0;){var t=ut.ensure();if(e++>1e3){var s,i;Gu()}t.process(mt),qt.clear()}}finally{_r=!1,Oa(r),Ai=null}}function Gu(){try{bu()}catch(r){Ls(r,Ai)}}let kt=null;function ua(r){var e=r.length;if(e!==0){for(var t=0;t<e;){var s=r[t++];if((s.f&(Wt|gt))===0&&Zs(s)&&(kt=new Set,ei(s),s.deps===null&&s.first===null&&s.nodes_start===null&&(s.teardown===null&&s.ac===null?Ca(s):s.fn=null),kt?.size>0)){qt.clear();for(const i of kt){if((i.f&(Wt|gt))!==0)continue;const n=[i];let a=i.parent;for(;a!==null;)kt.has(a)&&(kt.delete(a),n.push(a)),a=a.parent;for(let o=n.length-1;o>=0;o--){const c=n[o];(c.f&(Wt|gt))===0&&ei(c)}}kt.clear()}}kt=null}}function ha(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&we)!==0?ha(i,e,t,s):(n&(Tr|Dt))!==0&&(n&Ke)===0&&da(i,e,s)&&(Me(i,Ke),ns(i))}}function da(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(e.includes(i))return!0;if((i.f&we)!==0&&da(i,e,t))return t.set(i,!0),!0}return t.set(r,!1),!1}function ns(r){for(var e=Ai=r;e.parent!==null;){e=e.parent;var t=e.f;if(_r&&e===ie&&(t&Dt)!==0&&(t&ta)===0)return;if((t&(Ht|Ct))!==0){if((t&Oe)===0)return;e.f^=Oe}}mt.push(e)}function Ku(r){let e=0,t=js(0),s;return()=>{Ri()&&(re(t),La(()=>(e===0&&(s=br(()=>r(()=>Xs(t)))),e+=1,()=>{Ar(()=>{e-=1,e===0&&(s?.(),s=void 0,Xs(t))})})))}}var Vu=xs|ss|Ei;function Hu(r,e,t){new Wu(r,e,t)}class Wu{parent;#t=!1;#e;#s=Ee?le:null;#i;#l;#a;#o=null;#r=null;#n=null;#c=null;#u=null;#f=0;#h=0;#g=!1;#d=null;#E=Ku(()=>(this.#d=js(this.#f),()=>{this.#d=null}));constructor(e,t,s){this.#e=e,this.#i=t,this.#l=s,this.parent=ie.b,this.#t=!!this.#i.pending,this.#a=Ra(()=>{if(ie.b=this,Ee){const n=this.#s;Si(),n.nodeType===Ys&&n.data===pr?this.#S():this.#T()}else{var i=this.#y();try{this.#o=Mt(()=>s(i))}catch(n){this.error(n)}this.#h>0?this.#p():this.#t=!1}return()=>{this.#u?.remove()}},Vu),Ee&&(this.#e=le)}#T(){try{this.#o=Mt(()=>this.#l(this.#e))}catch(e){this.error(e)}this.#t=!1}#S(){const e=this.#i.pending;e&&(this.#r=Mt(()=>e(this.#e)),ut.enqueue(()=>{var t=this.#y();this.#o=this.#m(()=>(ut.ensure(),Mt(()=>this.#l(t)))),this.#h>0?this.#p():(Qs(this.#r,()=>{this.#r=null}),this.#t=!1)}))}#y(){var e=this.#e;return this.#t&&(this.#u=pt(),this.#e.before(this.#u),e=this.#u),e}is_pending(){return this.#t||!!this.parent&&this.parent.is_pending()}has_pending_snippet(){return!!this.#i.pending}#m(e){var t=ie,s=te,i=je;Et(this.#a),We(this.#a),Is(this.#a.ctx);try{return e()}catch(n){return la(n),null}finally{Et(t),We(s),Is(i)}}#p(){const e=this.#i.pending;this.#o!==null&&(this.#c=document.createDocumentFragment(),this.#c.append(this.#u),wa(this.#o,this.#c)),this.#r===null&&(this.#r=Mt(()=>e(this.#e)))}#v(e){if(!this.has_pending_snippet()){this.parent&&this.parent.#v(e);return}this.#h+=e,this.#h===0&&(this.#t=!1,this.#r&&Qs(this.#r,()=>{this.#r=null}),this.#c&&(this.#e.before(this.#c),this.#c=null))}update_pending_count(e){this.#v(e),this.#f+=e,this.#d&&Ii(this.#d,this.#f)}get_effect_pending(){return this.#E(),re(this.#d)}error(e){var t=this.#i.onerror;let s=this.#i.failed;if(this.#g||!t&&!s)throw e;this.#o&&(He(this.#o),this.#o=null),this.#r&&(He(this.#r),this.#r=null),this.#n&&(He(this.#n),this.#n=null),Ee&&(ct(this.#s),Mu(),ct(sa()));var i=!1,n=!1;const a=()=>{if(i){Ou();return}i=!0,n&&wu(),ut.ensure(),this.#f=0,this.#n!==null&&Qs(this.#n,()=>{this.#n=null}),this.#t=this.has_pending_snippet(),this.#o=this.#m(()=>(this.#g=!1,Mt(()=>this.#l(this.#e)))),this.#h>0?this.#p():this.#t=!1};var o=te;try{We(null),n=!0,t?.(e,a),n=!1}catch(c){Ls(c,this.#a&&this.#a.parent)}finally{We(o)}s&&Ar(()=>{this.#n=this.#m(()=>{ut.ensure(),this.#g=!0;try{return Mt(()=>{s(this.#e,()=>e,()=>a)})}catch(c){return Ls(c,this.#a.parent),null}finally{this.#g=!1}})})}}function Yu(r,e,t,s){const i=fa;if(t.length===0&&r.length===0){s(e.map(i));return}var n=Ie,a=ie,o=qu();function c(){Promise.all(t.map(l=>ju(l))).then(l=>{o();try{s([...e.map(i),...l])}catch(u){(a.f&Wt)===0&&Ls(u,a)}n?.deactivate(),_i()}).catch(l=>{Ls(l,a)})}r.length>0?Promise.all(r).then(()=>{o();try{return c()}finally{n?.deactivate(),_i()}}):c()}function qu(){var r=ie,e=te,t=je,s=Ie;return function(n=!0){Et(r),We(e),Is(t),n&&s?.activate()}}function _i(){Et(null),We(null),Is(null)}function fa(r){var e=we|Ke,t=te!==null&&(te.f&we)!==0?te:null;return ie!==null&&(ie.f|=ss),{ctx:je,deps:null,effects:null,equals:ia,f:e,fn:r,reactions:null,rv:0,v:ke,wv:0,parent:t??ie,ac:null}}function ju(r,e){let t=ie;t===null&&_u();var s=t.b,i=void 0,n=js(ke),a=!te,o=new Map;return nh(()=>{var c=Zn();i=c.promise;try{Promise.resolve(r()).then(c.resolve,c.reject).then(()=>{l===Ie&&l.committed&&l.deactivate(),_i()})}catch(d){c.reject(d),_i()}var l=Ie;if(a){var u=!s.is_pending();s.update_pending_count(1),l.increment(u),o.get(l)?.reject(As),o.delete(l),o.set(l,c)}const h=(d,f=void 0)=>{if(l.activate(),f)f!==As&&(n.f|=Yt,Ii(n,f));else{(n.f&Yt)!==0&&(n.f^=Yt),Ii(n,d);for(const[g,p]of o){if(o.delete(g),g===l)break;p.reject(As)}}a&&(s.update_pending_count(-1),l.decrement(u))};c.promise.then(h,d=>h(null,d||"unknown"))}),sh(()=>{for(const c of o.values())c.reject(As)}),new Promise(c=>{function l(u){function h(){u===i?c(n):l(i)}u.then(h,h)}l(i)})}function ga(r){var e=r.effects;if(e!==null){r.effects=null;for(var t=0;t<e.length;t+=1)He(e[t])}}function Xu(r){for(var e=r.parent;e!==null;){if((e.f&we)===0)return e;e=e.parent}return null}function Ir(r){var e,t=ie;Et(Xu(r));try{r.f&=~Ws,ga(r),e=Ua(r)}finally{Et(t)}return e}function ma(r){var e=Ir(r);if(r.equals(e)||(r.v=e,r.wv=$a()),!ls)if(Xe!==null)Ri()&&Xe.set(r,r.v);else{var t=(r.f<)===0?Pt:Oe;Me(r,t)}}let Lr=new Set;const qt=new Map;let pa=!1;function js(r,e){var t={f:0,v:r,reactions:null,equals:ia,rv:0,wv:0};return t}function Ve(r,e){const t=js(r);return uh(t),t}function zu(r,e=!1,t=!0){const s=js(r);return e||(s.equals=$u),s}function de(r,e,t=!1){te!==null&&(!vt||(te.f&ea)!==0)&&aa()&&(te.f&(we|Dt|Tr|ea))!==0&&!Ft?.includes(r)&&ku();let s=t?zs(e):e;return Ii(r,s)}function Ii(r,e){if(!r.equals(e)){var t=r.v;ls?qt.set(r,e):qt.set(r,t),r.v=e;var s=ut.ensure();s.capture(r,t),(r.f&we)!==0&&((r.f&Ke)!==0&&Ir(r),Me(r,(r.f<)!==0?Oe:Pt)),r.wv=$a(),ya(r,Ke),ie!==null&&(ie.f&Oe)!==0&&(ie.f&(Ct|Ht))===0&&(it===null?hh([r]):it.push(r)),!s.is_fork&&Lr.size>0&&!pa&&Qu()}return e}function Qu(){pa=!1;const r=Array.from(Lr);for(const e of r)(e.f&Oe)!==0&&Me(e,Pt),Zs(e)&&ei(e);Lr.clear()}function Xs(r){de(r,r.v+1)}function ya(r,e){var t=r.reactions;if(t!==null)for(var s=t.length,i=0;i<s;i++){var n=t[i],a=n.f,o=(a&Ke)===0;if(o&&Me(n,e),(a&we)!==0){var c=n;Xe?.delete(c),(a&Ws)===0&&(a<&&(n.f|=Ws),ya(c,Pt))}else o&&((a&Dt)!==0&&kt!==null&&kt.add(n),ns(n))}}function zs(r){if(typeof r!="object"||r===null||Sr in r)return r;const e=Eu(r);if(e!==yu&&e!==vu)return r;var t=new Map,s=gu(r),i=Ve(0),n=cs,a=o=>{if(cs===n)return o();var c=te,l=cs;We(null),Na(n);var u=o();return We(c),Na(l),u};return s&&t.set("length",Ve(r.length)),new Proxy(r,{defineProperty(o,c,l){(!("value"in l)||l.configurable===!1||l.enumerable===!1||l.writable===!1)&&Cu();var u=t.get(c);return u===void 0?u=a(()=>{var h=Ve(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(()=>Ve(ke));t.set(c,u),Xs(i)}}else de(l,ke),Xs(i);return!0},get(o,c,l){if(c===Sr)return r;var u=t.get(c),h=c in o;if(u===void 0&&(!h||Ss(o,c)?.writable)&&(u=a(()=>{var f=zs(h?o[c]:ke),g=Ve(f);return g}),t.set(c,u)),u!==void 0){var d=re(u);return d===ke?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!==ke)return{enumerable:!0,configurable:!0,value:d,writable:!0}}return l},has(o,c){if(c===Sr)return!0;var l=t.get(c),u=l!==void 0&&l.v!==ke||Reflect.has(o,c);if(l!==void 0||ie!==null&&(!u||Ss(o,c)?.writable)){l===void 0&&(l=a(()=>{var d=u?zs(o[c]):ke,f=Ve(d);return f}),t.set(c,l));var h=re(l);if(h===ke)return!1}return u},set(o,c,l,u){var h=t.get(c),d=c in o;if(s&&c==="length")for(var f=l;f<h.v;f+=1){var g=t.get(f+"");g!==void 0?de(g,ke):f in o&&(g=a(()=>Ve(ke)),t.set(f+"",g))}if(h===void 0)(!d||Ss(o,c)?.writable)&&(h=a(()=>Ve(void 0)),de(h,zs(l)),t.set(c,h));else{d=h.v!==ke;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!==ke});for(var[l,u]of t)u.v!==ke&&!(l in o)&&c.push(l);return c},setPrototypeOf(){Pu()}})}var va,Ea,Ta,Sa;function Rr(){if(va===void 0){va=window,Ea=/Firefox/.test(navigator.userAgent);var r=Element.prototype,e=Node.prototype,t=Text.prototype;Ta=Ss(e,"firstChild").get,Sa=Ss(e,"nextSibling").get,Jn(r)&&(r.__click=void 0,r.__className=void 0,r.__attributes=null,r.__style=void 0,r.__e=void 0),Jn(t)&&(t.__t=void 0)}}function pt(r=""){return document.createTextNode(r)}function Rs(r){return Ta.call(r)}function wt(r){return Sa.call(r)}function ge(r,e){if(!Ee)return Rs(r);var t=Rs(le);return t===null&&(t=le.appendChild(pt())),ct(t),t}function Ot(r,e=!1){if(!Ee){var t=Rs(r);return t instanceof Comment&&t.data===""?wt(t):t}if(e&&le?.nodeType!==xr){var s=pt();return le?.before(s),ct(s),s}return le}function Li(r,e=1,t=!1){let s=Ee?le:r;for(var i;e--;)i=s,s=wt(s);if(!Ee)return s;if(t&&s?.nodeType!==xr){var n=pt();return s===null?i?.after(n):s.before(n),ct(n),n}return ct(s),s}function Ju(r){r.textContent=""}function Zu(){return!1}function xa(r){var e=te,t=ie;We(null),Et(null);try{return r()}finally{We(e),Et(t)}}function eh(r){ie===null&&(te===null&&Ru(),Lu()),ls&&Iu()}function th(r,e){var t=e.last;t===null?e.last=e.first=r:(t.next=r,r.prev=t,e.last=r)}function yt(r,e,t,s=!0){var i=ie;i!==null&&(i.f>)!==0&&(r|=gt);var n={ctx:je,deps:null,nodes_start:null,nodes_end:null,f:r|Ke|lt,first:null,fn:e,last:null,next:null,parent:i,b:i&&i.b,prev:null,teardown:null,transitions:null,wv:0,ac:null};if(t)try{ei(n),n.f|=vr}catch(c){throw He(n),c}else e!==null&&ns(n);if(s){var a=n;if(t&&a.deps===null&&a.teardown===null&&a.nodes_start===null&&a.first===a.last&&(a.f&ss)===0&&(a=a.first,(r&Dt)!==0&&(r&xs)!==0&&a!==null&&(a.f|=xs)),a!==null&&(a.parent=i,i!==null&&th(a,i),te!==null&&(te.f&we)!==0&&(r&Ht)===0)){var o=te;(o.effects??=[]).push(a)}}return n}function Ri(){return te!==null&&!vt}function sh(r){const e=yt(yr,null,!1);return Me(e,Oe),e.teardown=r,e}function Aa(r){eh();var e=ie.f,t=!te&&(e&Ct)!==0&&(e&vr)===0;if(t){var s=je;(s.e??=[]).push(r)}else return _a(r)}function _a(r){return yt(vi|Su,r,!1)}function ih(r){ut.ensure();const e=yt(Ht|ss,r,!0);return()=>{He(e)}}function rh(r){ut.ensure();const e=yt(Ht|ss,r,!0);return(t={})=>new Promise(s=>{t.outro?Qs(e,()=>{He(e),s(void 0)}):(He(e),s(void 0))})}function Ia(r){return yt(vi,r,!1)}function nh(r){return yt(Tr|ss,r,!0)}function La(r,e=0){return yt(yr|e,r,!0)}function as(r,e=[],t=[],s=[],i=!1){Yu(s,e,t,n=>{yt(i?vi:yr,()=>r(...n.map(re)),!0)})}function Ra(r,e=0){var t=yt(Dt|e,r,!0);return t}function Mt(r,e=!0){return yt(Ct|ss,r,!0,e)}function ba(r){var e=r.teardown;if(e!==null){const t=ls,s=te;Ma(!0),We(null);try{e.call(null)}finally{Ma(t),We(s)}}}function Da(r,e=!1){var t=r.first;for(r.first=r.last=null;t!==null;){const i=t.ac;i!==null&&xa(()=>{i.abort(As)});var s=t.next;(t.f&Ht)!==0?t.parent=null:He(t,e),t=s}}function ah(r){for(var e=r.first;e!==null;){var t=e.next;(e.f&Ct)===0&&He(e),e=t}}function He(r,e=!0){var t=!1;(e||(r.f&ta)!==0)&&r.nodes_start!==null&&r.nodes_end!==null&&(oh(r.nodes_start,r.nodes_end),t=!0),Da(r,e&&!t),bi(r,0),Me(r,Wt);var s=r.transitions;if(s!==null)for(const n of s)n.stop();ba(r);var i=r.parent;i!==null&&i.first!==null&&Ca(r),r.next=r.prev=r.teardown=r.ctx=r.deps=r.fn=r.nodes_start=r.nodes_end=r.ac=null}function oh(r,e){for(;r!==null;){var t=r===e?null:wt(r);r.remove(),r=t}}function Ca(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 Qs(r,e,t=!0){var s=[];Pa(r,s,!0),lh(s,()=>{t&&He(r),e&&e()})}function lh(r,e){var t=r.length;if(t>0){var s=()=>--t||e();for(var i of r)i.out(s)}else e()}function Pa(r,e,t){if((r.f>)===0){if(r.f^=gt,r.transitions!==null)for(const a of r.transitions)(a.is_global||t)&&e.push(a);for(var s=r.first;s!==null;){var i=s.next,n=(s.f&xs)!==0||(s.f&Ct)!==0&&(r.f&Dt)!==0;Pa(s,e,n?t:!1),s=i}}}function ch(r){ka(r,!0)}function ka(r,e){if((r.f>)!==0){r.f^=gt,(r.f&Oe)===0&&(Me(r,Ke),ns(r));for(var t=r.first;t!==null;){var s=t.next,i=(t.f&xs)!==0||(t.f&Ct)!==0;ka(t,i?e:!1),t=s}if(r.transitions!==null)for(const n of r.transitions)(n.is_global||e)&&n.in()}}function wa(r,e){for(var t=r.nodes_start,s=r.nodes_end;t!==null;){var i=t===s?null:wt(t);e.append(t),t=i}}let os=!1;function Oa(r){os=r}let ls=!1;function Ma(r){ls=r}let te=null,vt=!1;function We(r){te=r}let ie=null;function Et(r){ie=r}let Ft=null;function uh(r){te!==null&&(Ft===null?Ft=[r]:Ft.push(r))}let $e=null,ze=0,it=null;function hh(r){it=r}let Fa=1,Js=0,cs=Js;function Na(r){cs=r}function $a(){return++Fa}function Zs(r){var e=r.f;if((e&Ke)!==0)return!0;if(e&we&&(r.f&=~Ws),(e&Pt)!==0){var t=r.deps;if(t!==null)for(var s=t.length,i=0;i<s;i++){var n=t[i];if(Zs(n)&&ma(n),n.wv>r.wv)return!0}(e<)!==0&&Xe===null&&Me(r,Oe)}return!1}function Ba(r,e,t=!0){var s=r.reactions;if(s!==null&&!Ft?.includes(r))for(var i=0;i<s.length;i++){var n=s[i];(n.f&we)!==0?Ba(n,e,!1):e===n&&(t?Me(n,Ke):(n.f&Oe)!==0&&Me(n,Pt),ns(n))}}function Ua(r){var e=$e,t=ze,s=it,i=te,n=Ft,a=je,o=vt,c=cs,l=r.f;$e=null,ze=0,it=null,te=(l&(Ct|Ht))===0?r:null,Ft=null,Is(r.ctx),vt=!1,cs=++Js,r.ac!==null&&(xa(()=>{r.ac.abort(As)}),r.ac=null);try{r.f|=Er;var u=r.fn,h=u(),d=r.deps;if($e!==null){var f;if(bi(r,ze),d!==null&&ze>0)for(d.length=ze+$e.length,f=0;f<$e.length;f++)d[ze+f]=$e[f];else r.deps=d=$e;if(os&&Ri()&&(r.f<)!==0)for(f=ze;f<d.length;f++)(d[f].reactions??=[]).push(r)}else d!==null&&ze<d.length&&(bi(r,ze),d.length=ze);if(aa()&&it!==null&&!vt&&d!==null&&(r.f&(we|Pt|Ke))===0)for(f=0;f<it.length;f++)Ba(it[f],r);return i!==null&&i!==r&&(Js++,it!==null&&(s===null?s=it:s.push(...it))),(r.f&Yt)!==0&&(r.f^=Yt),h}catch(g){return la(g)}finally{r.f^=Er,$e=e,ze=t,it=s,te=i,Ft=n,Is(a),vt=o,cs=c}}function dh(r,e){let t=e.reactions;if(t!==null){var s=mu.call(t,r);if(s!==-1){var i=t.length-1;i===0?t=e.reactions=null:(t[s]=t[i],t.pop())}}t===null&&(e.f&we)!==0&&($e===null||!$e.includes(e))&&(Me(e,Pt),(e.f<)!==0&&(e.f^=lt,e.f&=~Ws),ga(e),bi(e,0))}function bi(r,e){var t=r.deps;if(t!==null)for(var s=e;s<t.length;s++)dh(r,t[s])}function ei(r){var e=r.f;if((e&Wt)===0){Me(r,Oe);var t=ie,s=os;ie=r,os=!0;try{(e&Dt)!==0?ah(r):Da(r),ba(r);var i=Ua(r);r.teardown=typeof i=="function"?i:null,r.wv=Fa;var n;Qn&&Bu&&(r.f&Ke)!==0&&r.deps}finally{os=s,ie=t}}}function re(r){var e=r.f,t=(e&we)!==0;if(te!==null&&!vt){var s=ie!==null&&(ie.f&Wt)!==0;if(!s&&!Ft?.includes(r)){var i=te.deps;if((te.f&Er)!==0)r.rv<Js&&(r.rv=Js,$e===null&&i!==null&&i[ze]===r?ze++:$e===null?$e=[r]:$e.includes(r)||$e.push(r));else{(te.deps??=[]).push(r);var n=r.reactions;n===null?r.reactions=[te]:n.includes(te)||n.push(te)}}}if(ls){if(qt.has(r))return qt.get(r);if(t){var a=r,o=a.v;return((a.f&Oe)===0&&a.reactions!==null||Ka(a))&&(o=Ir(a)),qt.set(a,o),o}}else if(t){if(a=r,Xe?.has(a))return Xe.get(a);Zs(a)&&ma(a),os&&Ri()&&(a.f<)===0&&Ga(a)}else if(Xe?.has(r))return Xe.get(r);if((r.f&Yt)!==0)throw r.v;return r.v}function Ga(r){if(r.deps!==null){r.f^=lt;for(const e of r.deps)(e.reactions??=[]).push(r),(e.f&we)!==0&&(e.f<)===0&&Ga(e)}}function Ka(r){if(r.v===ke)return!0;if(r.deps===null)return!1;for(const e of r.deps)if(qt.has(e)||(e.f&we)!==0&&Ka(e))return!0;return!1}function br(r){var e=vt;try{return vt=!0,r()}finally{vt=e}}const fh=-7169;function Me(r,e){r.f=r.f&fh|e}const gh=new Set,Va=new Set;let Ha=null;function Di(r){var e=this,t=e.ownerDocument,s=r.type,i=r.composedPath?.()||[],n=i[0]||r.target;Ha=r;var a=0,o=Ha===r&&r.__root;if(o){var c=i.indexOf(o);if(c!==-1&&(e===document||e===window)){r.__root=e;return}var l=i.indexOf(e);if(l===-1)return;c<=l&&(a=c)}if(n=i[a]||r.target,n!==e){yi(r,"currentTarget",{configurable:!0,get(){return n||t}});var u=te,h=ie;We(null),Et(null);try{for(var d,f=[];n!==null;){var g=n.assignedSlot||n.parentNode||n.host||null;try{var p=n["__"+s];p!=null&&(!n.disabled||r.target===n)&&p.call(n,r)}catch(y){d?f.push(y):d=y}if(r.cancelBubble||g===e||g===null)break;n=g}if(d){for(let y of f)queueMicrotask(()=>{throw y});throw d}}finally{r.__root=e,delete r.currentTarget,We(u),Et(h)}}}function mh(r){var e=document.createElement("template");return e.innerHTML=r.replaceAll("<!>","<!---->"),e.content}function jt(r,e){var t=ie;t.nodes_start===null&&(t.nodes_start=r,t.nodes_end=e)}function Xt(r,e){var t=(e&du)!==0,s=(e&fu)!==0,i,n=!r.startsWith("<!>");return()=>{if(Ee)return jt(le,null),le;i===void 0&&(i=mh(n?r:"<!>"+r),t||(i=Rs(i)));var a=s||Ea?document.importNode(i,!0):i.cloneNode(!0);if(t){var o=Rs(a),c=a.lastChild;jt(o,c)}else jt(a,a);return a}}function bs(r=""){if(!Ee){var e=pt(r+"");return jt(e,e),e}var t=le;return t.nodeType!==xr&&(t.before(t=pt()),ct(t)),jt(t,t),t}function us(){if(Ee)return jt(le,null),le;var r=document.createDocumentFragment(),e=document.createComment(""),t=pt();return r.append(e,t),jt(e,t),r}function Te(r,e){if(Ee){ie.nodes_end=le,Si();return}r!==null&&r.before(e)}const ph=["touchstart","touchmove"];function yh(r){return ph.includes(r)}function Ds(r,e){var t=e==null?"":typeof e=="object"?e+"":e;t!==(r.__t??=r.nodeValue)&&(r.__t=t,r.nodeValue=t+"")}function Wa(r,e){return Ya(r,e)}function vh(r,e){Rr(),e.intro=e.intro??!1;const t=e.target,s=Ee,i=le;try{for(var n=Rs(t);n&&(n.nodeType!==Ys||n.data!==Xn);)n=wt(n);if(!n)throw Ts;_s(!0),ct(n);const a=Ya(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!==Ts&&console.warn("Failed to hydrate: ",a),e.recover===!1&&Du(),Rr(),Ju(t),_s(!1),Wa(r,e)}finally{_s(s),ct(i)}}const Cs=new Map;function Ya(r,{target:e,anchor:t,props:s={},events:i,context:n,intro:a=!0}){Rr();var o=new Set,c=h=>{for(var d=0;d<h.length;d++){var f=h[d];if(!o.has(f)){o.add(f);var g=yh(f);e.addEventListener(f,Di,{passive:g});var p=Cs.get(f);p===void 0?(document.addEventListener(f,Di,{passive:g}),Cs.set(f,1)):Cs.set(f,p+1)}}};c(pu(gh)),Va.add(c);var l=void 0,u=rh(()=>{var h=t??e.appendChild(pt());return Hu(h,{pending:()=>{}},d=>{if(n){ra({});var f=je;f.c=n}if(i&&(s.$$events=i),Ee&&jt(d,null),l=r(d,s)||{},Ee&&(ie.nodes_end=le,le===null||le.nodeType!==Ys||le.data!==zn))throw Ti(),Ts;n&&na()}),()=>{for(var d of o){e.removeEventListener(d,Di);var f=Cs.get(d);--f===0?(document.removeEventListener(d,Di),Cs.delete(d)):Cs.set(d,f)}Va.delete(c),h!==t&&h.parentNode?.removeChild(h)}});return Dr.set(l,u),l}let Dr=new WeakMap;function Eh(r,e){const t=Dr.get(r);return t?(Dr.delete(r),t(e)):Promise.resolve()}class Th{anchor;#t=new Map;#e=new Map;#s=new Map;#i=!0;constructor(e,t=!0){this.anchor=e,this.#i=t}#l=()=>{var e=Ie;if(this.#t.has(e)){var t=this.#t.get(e),s=this.#e.get(t);if(s)ch(s);else{var i=this.#s.get(t);i&&(this.#e.set(t,i.effect),this.#s.delete(t),i.fragment.lastChild.remove(),this.anchor.before(i.fragment),s=i.effect)}for(const[n,a]of this.#t){if(this.#t.delete(n),n===e)break;const o=this.#s.get(a);o&&(He(o.effect),this.#s.delete(a))}for(const[n,a]of this.#e){if(n===t)continue;const o=()=>{if(Array.from(this.#t.values()).includes(n)){var l=document.createDocumentFragment();wa(a,l),l.append(pt()),this.#s.set(n,{effect:a,fragment:l})}else He(a);this.#e.delete(n)};this.#i||!s?Qs(a,o,!1):o()}}};#a=e=>{this.#t.delete(e);const t=Array.from(this.#t.values());for(const[s,i]of this.#s)t.includes(s)||(He(i.effect),this.#s.delete(s))};ensure(e,t){var s=Ie,i=Zu();if(t&&!this.#e.has(e)&&!this.#s.has(e))if(i){var n=document.createDocumentFragment(),a=pt();n.append(a),this.#s.set(e,{effect:Mt(()=>t(a)),fragment:n})}else this.#e.set(e,Mt(()=>t(this.anchor)));if(this.#t.set(s,e),i){for(const[o,c]of this.#e)o===e?s.skipped_effects.delete(c):s.skipped_effects.add(c);for(const[o,c]of this.#s)o===e?s.skipped_effects.delete(c.effect):s.skipped_effects.add(c.effect);s.oncommit(this.#l),s.ondiscard(this.#a)}else Ee&&(this.anchor=le),this.#l()}}function Sh(r){je===null&&Au(),Aa(()=>{const e=br(r);if(typeof e=="function")return e})}function hs(r,e,t=!1){Ee&&Si();var s=new Th(r),i=t?xs:0;function n(a,o){if(Ee){const l=Fu(r)===pr;if(a===l){var c=sa();ct(c),s.anchor=c,_s(!1),s.ensure(a,o),_s(!0);return}}s.ensure(a,o)}Ra(()=>{var a=!1;e((o,c=!0)=>{a=!0,n(c,o)}),a||n(!1,null)},i)}function Nt(r,e,t,s,i){Ee&&Si();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 xh(r,e){Ia(()=>{var t=r.getRootNode(),s=t.host?t:t.head??t.ownerDocument.head;if(!s.querySelector("#"+e.hash)){const i=document.createElement("style");i.id=e.hash,i.textContent=e.code,s.appendChild(i)}})}function Ah(r,e,t){Ia(()=>{var s=br(()=>e(r,t?.())||{});if(s?.destroy)return()=>s.destroy()})}function Ps(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=fa(()=>(l=!1,c())),h=ie;return(function(d,f){if(arguments.length>0){const g=f?re(u):d;return de(u,g),l=!0,i!==void 0&&(i=g),d}return ls&&l||(h.f&Wt)!==0?u.v:re(u)})}function _h(r){return new Ih(r)}class Ih{#t;#e;constructor(e){var t=new Map,s=(n,a)=>{var o=zu(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===xu?!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.#e=(e.hydrate?vh:Wa)(e.component,{target:e.target,anchor:e.anchor,props:i,context:e.context,intro:e.intro??!1,recover:e.recover}),(!e?.props?.$$host||e.sync===!1)&&rs(),this.#t=i.$$events;for(const n of Object.keys(this.#e))n==="$set"||n==="$destroy"||n==="$on"||yi(this,n,{get(){return this.#e[n]},set(a){this.#e[n]=a},enumerable:!0});this.#e.$set=n=>{Object.assign(i,n)},this.#e.$destroy=()=>{Eh(this.#e)}}$set(e){this.#e.$set(e)}$on(e,t){this.#t[e]=this.#t[e]||[];const s=(...i)=>t.call(this,...i);return this.#t[e].push(s),()=>{this.#t[e]=this.#t[e].filter(i=>i!==s)}}$destroy(){this.#e.$destroy()}}let qa;typeof HTMLElement=="function"&&(qa=class extends HTMLElement{$$ctor;$$s;$$c;$$cn=!1;$$d={};$$r=!1;$$p_d={};$$l={};$$l_u=new Map;$$me;constructor(r,e,t){super(),this.$$ctor=r,this.$$s=e,t&&this.attachShadow({mode:"open"})}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=document.createElement("slot");s!=="default"&&(n.name=s),Te(i,n)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;const e={},t=Lh(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]=Ci(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=_h({component:this.$$ctor,target:this.shadowRoot||this,props:{...this.$$d,$$slots:e,$$host:this}}),this.$$me=ih(()=>{La(()=>{this.$$r=!0;for(const s of pi(this.$$c)){if(!this.$$p_d[s]?.reflect)continue;this.$$d[s]=this.$$c[s];const i=Ci(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]=Ci(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 pi(this.$$p_d).find(e=>this.$$p_d[e].attribute===r||!this.$$p_d[e].attribute&&e.toLowerCase()===r)||r}});function Ci(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 Lh(r){const e={};return r.childNodes.forEach(t=>{e[t.slot||"default"]=!0}),e}function Rh(r,e,t,s,i,n){let a=class extends qa{constructor(){super(r,t,i),this.$$p_d=e}static get observedAttributes(){return pi(e).map(o=>(e[o].attribute||o).toLowerCase())}};return pi(e).forEach(o=>{yi(a.prototype,o,{get(){return this.$$c&&o in this.$$c?this.$$c[o]:this.$$d[o]},set(c){c=Ci(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=>{yi(a.prototype,o,{get(){return this.$$c?.[o]}})}),r.element=a,a}const $=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},bh=Number.isSafeInteger||function(r){return typeof r=="number"&&Math.abs(r)<=Dh},Dh=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})({}),b=(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"},V={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 Ch{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 Ph(r,e,t){return(e=wh(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function oe(){return oe=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},oe.apply(null,arguments)}function ja(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 ne(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?ja(Object(t),!0).forEach(function(s){Ph(r,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):ja(Object(t)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(t,s))})}return r}function kh(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 wh(r){var e=kh(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=zt,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 zt=function(){},Oh={trace:zt,debug:zt,log:zt,warn:zt,info:zt,error:zt};function Cr(){return oe({},Oh)}function Mh(r,e){const t=self.console[r];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${r}] >`):zt}function Xa(r,e,t){return e[r]?e[r].bind(e):Mh(r,t)}const Pr=Cr();function Fh(r,e,t){const s=Cr();if(typeof console=="object"&&r===!0||typeof r=="object"){const i=["debug","log","info","warn","error"];i.forEach(n=>{s[n]=Xa(n,r,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.14`)}catch{return Cr()}i.forEach(n=>{Pr[n]=Xa(n,r)})}else oe(Pr,s);return s}const ae=Pr;function Qt(r=!0){return typeof self>"u"?void 0:(r||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Nh(r){return typeof self<"u"&&r===self.ManagedMediaSource}function za(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 Qe(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 Be(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 Qa(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function $h(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var kr={exports:{}},Ja;function Bh(){return Ja||(Ja=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 f=o.parseURL(c);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=i.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(p.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)p.path=f.path,d.params||(p.params=f.params,d.query||(p.query=f.query));else{var y=f.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})()})(kr)),kr.exports}var wr=Bh();class Or{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 Za{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,Gh(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 Or),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=wr.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 Mr extends Za{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 Uh extends Za{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 eo(r,e){const t=Object.getPrototypeOf(r);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||eo(t,e)}}function Gh(r,e){const t=eo(r,e);t&&(t.enumerable=!0,Object.defineProperty(r,e,t))}const to=Math.pow(2,32)-1,Kh=[].push,so={video:1,audio:2,id3:3,text:4};function Le(r){return String.fromCharCode.apply(null,r)}function io(r,e){const t=r[e]<<8|r[e+1];return t<0?65536+t:t}function q(r,e){const t=no(r,e);return t<0?4294967296+t:t}function ro(r,e){let t=q(r,e);return t*=Math.pow(2,32),t+=q(r,e+4),t}function no(r,e){return r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}function Vh(r){const e=r.byteLength;for(let t=0;t<e;){const s=q(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=q(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&&Kh.apply(t,c)}i=o}return t}function Hh(r){const e=[],t=r[0];let s=8;const i=q(r,s);s+=4;let n=0,a=0;t===0?(n=q(r,s),a=q(r,s+4),s+=8):(n=ro(r,s),a=ro(r,s+8),s+=16),s+=2;let o=r.length+a;const c=io(r,s);s+=2;for(let l=0;l<c;l++){let u=s;const h=q(r,u);u+=4;const d=h&2147483647;if((h&2147483648)>>>31===1)return ae.warn("SIDX has hierarchical references (not supported)"),null;const g=q(r,u);u+=4,e.push({referenceSize:d,subsegmentDuration:g,info:{duration:g/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 ao(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=q(a,o===0?12:20),l=J(n,["mdia","mdhd"])[0];if(l){o=l[0];const u=q(l,o===0?12:20),h=J(n,["mdia","hdlr"])[0];if(h){const d=Le(h.subarray(8,12)),f={soun:ce.AUDIO,vide:ce.VIDEO}[d],g=J(n,["mdia","minf","stbl","stsd"])[0],p=Wh(g);f?(e[c]={timescale:u,type:f,stsd:p},e[f]=ne({timescale:u,id:c},p)):e[c]={timescale:u,type:d,stsd:p}}}}}return J(r,["moov","mvex","trex"]).forEach(i=>{const n=q(i,4),a=e[n];a&&(a.default={duration:q(i,12),flags:q(i,20)})}),e}function Wh(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 f=Le(d.subarray(4,8));if(f==="cbcs"||f==="cenc"){const g=J(h,["frma"])[0];g&&(i=Le(g))}}})}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=Pi(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=Fr(l,u),u+=2;const h=l[u++];if(h&128&&(u+=2),h&64&&(u+=l[u++]),l[u++]!==4)break;u=Fr(l,u);const d=l[u++];if(d===64)i+="."+ki(d);else break;if(u+=12,l[u++]!==5)break;u=Fr(l,u);const f=l[u++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((l[u]&224)>>5)),i+="."+g}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=q(c,2),f=(l&32)>>5?"H":"L",g=c[12],p=c.subarray(6,12);i+="."+u+h,i+="."+Yh(d).toString(16).toUpperCase(),i+="."+f+g;let y="";for(let v=p.length;v--;){const E=p[v];(E||y)&&(y="."+E.toString(16).toUpperCase()+y)}i+=y}n=Pi(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=Pi(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+="."+Tt(l)+"."+Tt(u)+"."+Tt(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,f=(c[2]&32)>>5,g=l===2&&d?f?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+"."+Tt(u)+h+"."+Tt(g)+"."+p+"."+y+v+E+"."+Tt(1)+"."+Tt(1)+"."+Tt(1)+"."+0,n=Pi("dav1",t)}break}}return{codec:i,encrypted:a,supplemental:n}}function Pi(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+"."+Tt(i)+"."+Tt(n)}}function Yh(r){let e=0;for(let t=0;t<32;t++)e|=(r>>t&1)<<31-t;return e>>>0}function Fr(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 Tt(r){return(r<10?"0":"")+r}function qh(r,e){if(!r||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&oo(r,(s,i)=>{const n=s.subarray(8,24);n.some(a=>a!==0)||(ae.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Be(n)} -> ${Be(t)}`),s.set(t,8))})}function jh(r){const e=[];return oo(r,t=>e.push(t.subarray(8,24))),e}function oo(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=lo(h);d&&e(d,o)})})})}function lo(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 Xh(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=q(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=q(h,4);T===1&&(S===to?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=to+1,S+=q(h,8))),$(S)&&(!$(u.start)||S<u.start)&&(u.start=S)}const d=l.default,f=q(o,0)|d?.flags;let g=d?.duration||0;f&8&&(f&2?g=q(o,12):g=q(o,8));const p=J(a,["trun"]);let y=u.start||0,v=0,E=g;for(let T=0;T<p.length;T++){const S=p[T],A=q(S,4),D=u.sampleCount;u.sampleCount+=A;const _=S[3]&1,x=S[3]&4,I=S[2]&1,L=S[2]&2,C=S[2]&4,F=S[2]&8;let N=8,G=A;for(_&&(N+=4),x&&A&&(!(S[N+1]&1)&&u.keyFrameIndex===void 0&&(u.keyFrameIndex=D),N+=4,I?(E=q(S,N),N+=4):E=g,L&&(N+=4),F&&(N+=4),y+=E,v+=E,G--);G--;)I?(E=q(S,N),N+=4):E=g,L&&(N+=4),C&&(S[N+1]&1||u.keyFrameIndex===void 0&&(u.keyFrameIndex=u.sampleCount-(G+1),u.keyFrameStart=y),N+=4),F&&(N+=4),y+=E,v+=E;!v&&g&&(v+=g*A)}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=Hh(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 zh(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 co(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(f=>{const g=f[0];let p=q(f,4);return g===1&&(p*=Math.pow(2,32),p+=q(f,8)),p/i})[0];return d!==void 0&&(r=d),J(h,["tfhd"]).map(f=>{const g=q(f,4),p=q(f,0)&16777215,y=(p&1)!==0,v=(p&2)!==0,E=(p&8)!==0;let T=0;const S=(p&16)!==0;let A=0;const D=(p&32)!==0;let _=8;g===n&&(y&&(_+=8),v&&(_+=4),E&&(T=q(f,_),_+=4),S&&(A=q(f,_),_+=4),D&&(_+=4),e.type==="video"&&(a=wi(e.codec)),J(h,["trun"]).map(x=>{const I=x[0],L=q(x,0)&16777215,C=(L&1)!==0;let F=0;const N=(L&4)!==0,G=(L&256)!==0;let U=0;const k=(L&512)!==0;let B=0;const O=(L&1024)!==0,K=(L&2048)!==0;let W=0;const M=q(x,4);let w=8;C&&(F=q(x,w),w+=4),N&&(w+=4);let Y=F+l;for(let Z=0;Z<M;Z++){if(G?(U=q(x,w),w+=4):U=T,k?(B=q(x,w),w+=4):B=A,O&&(w+=4),K&&(I===0?W=q(x,w):W=no(x,w),w+=4),e.type===ce.VIDEO){let j=0;for(;j<B;){const z=q(s,Y);if(Y+=4,Qh(a,s[Y])){const pe=s.subarray(Y,Y+z);Nr(pe,a?2:1,r+W/i,t)}Y+=z,j+=z+4}}r+=U/i}}))})})}),t}function wi(r){if(!r)return!1;const e=r.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Qh(r,e){if(r){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Nr(r,e,t,s){const i=uo(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){ae.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(a===4){if(i[u++]===181){const d=io(i,u);if(u+=2,d===49){const f=q(i,u);if(u+=4,f===1195456820){const g=i[u++];if(g===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:g,payloadType:a,pts:t,bytes:T})}}}}}else if(a===5&&o>16){const h=[];for(let g=0;g<16;g++){const p=i[u++].toString(16);h.push(p.length==1?"0"+p:p),(g===3||g===5||g===7||g===9)&&h.push("-")}const d=o-16,f=new Uint8Array(d);for(let g=0;g<d;g++)f[g]=i[u++];s.push({payloadType:a,pts:t,uuid:h.join(""),userData:Qe(f),userDataBytes:f})}}}function uo(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 Jh(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=q(r,12),n=q(r,16),o=q(r,20),c=q(r,24),l=28}else if(e===1){l+=4,i=q(r,l),l+=4;const h=q(r,l);l+=4;const d=q(r,l);for(l+=4,a=2**32*h+d,bh(a)||(a=Number.MAX_SAFE_INTEGER,ae.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=q(r,l),l+=4,c=q(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 Zh(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 ed(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),Zh([112,115,115,104],new Uint8Array([s,0,0,0]),r,n,i,a,t)}function td(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=sd(i);e.push(n),s+=n.size}}return e}function sd(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=Be(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 f=0;f<d;f++)c.push(new Uint8Array(a,t+32+f*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 ho=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),ws={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 $r(r,e){const t=ws[e];return!!t&&!!t[r.slice(0,4)]}function ti(r,e,t=!0){return!r.split(",").some(s=>!Br(s,e,t))}function Br(r,e,t=!0){var s;const i=Qt(t);return(s=i?.isTypeSupported(si(r,e)))!=null?s:!1}function si(r,e){return`${e}/mp4;codecs=${r}`}function fo(r){if(r){const e=r.substring(0,4);return ws.video[e]}return 2}function Oi(r){const e=ho();return r.split(",").reduce((t,s)=>{const n=e&&wi(s)?9:ws.video[s];return n?(n*2+t)/(t?3:2):(ws.audio[s]+t)/(t?2:1)},0)}const Ur={};function id(r,e=!0){if(Ur[r])return Ur[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(Br(t[i],"audio",e))return Ur[r]=t[i],t[i];if(t[i]==="mp3"&&(s=Qt(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return r}const rd=/flac|opus|mp4a\.40\.34/i;function Mi(r,e=!0){return r.replace(rd,t=>id(t.toLowerCase(),e))}function nd(r,e){const t=[];if(r){const s=r.split(",");for(let i=0;i<s.length;i++)$r(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function Fi(r,e){if(r&&(r.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(r)!==-1)&&(go(r,"audio")||go(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 go(r,e){return $r(r,e)&&Br(r,e)}function ad(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 od(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 mo(r){const e=Qt(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 Gr(r){return r.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const ld={supported:!0,powerEfficient:!0,smooth:!0},cd={supported:!1,smooth:!1,powerEfficient:!1},po={supported:!0,configurations:[],decodingInfoResults:[ld]};function yo(r,e){return{supported:!1,configurations:e,decodingInfoResults:[cd],error:r}}function ud(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,f)=>{if(f){const g=e.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(p=>{d[p]=(d[p]||0)+g.channels[p]})}return d},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(d=>wi(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 vo(r,e,t,s={}){const i=r.videoCodec;if(!i&&!r.audioCodec||!t)return Promise.resolve(po);const n=[],a=hd(r),o=a.length,c=dd(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=>wi(h))&&ho())return Promise.resolve(yo(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),n))}return Promise.all(n.map(u=>{const h=gd(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 hd(r){var e;const t=(e=r.videoCodec)==null?void 0:e.split(","),s=Eo(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(od(c),"video"),width:i,height:n,bitrate:s,framerate:a};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function dd(r,e,t){var s;const i=(s=r.audioCodec)==null?void 0:s.split(","),n=Eo(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(f=>{const g={contentType:si(f,"audio"),bitrate:t?fd(f,n):n};d&&(g.channels=""+d),u.push(g)})}return u},a):a},[]):[]}function fd(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 Eo(r){return Math.ceil(Math.max(r.bitrate*.9,r.averageBitrate)/1e3)*1e3||1}function gd(r){let e="";const{audio:t,video:s}=r;if(s){const i=Gr(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=Gr(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}const Kr=["NONE","TYPE-0","TYPE-1",null];function md(r){return Kr.indexOf(r)>-1}const Ni=["SDR","PQ","HLG"];function pd(r){return!!r&&Ni.indexOf(r)>-1}var $i={No:"",Yes:"YES",v2:"v2"};function To(r){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=r,i=s<e/2;return e&&i?t?$i.v2:$i.Yes:$i.No}class So{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 xo(this._audioGroups,e)}hasSubtitleGroup(e){return xo(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 xo(r,e){return!e||!r?!1:r.indexOf(e)!==-1}function yd(){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 vd(r,e){let t=!1,s=[];if(r&&(t=r!=="SDR",s=[r]),e){s=e.allowedVideoRanges||Ni.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&yd(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const Ed=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,Ed(e));function Td(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,f=1/0,g=1/0,p=1/0,y=0,v=[];const{preferHDR:E,allowedVideoRanges:T}=vd(e,i);for(let x=n.length;x--;){const I=r[n[x]];u||(u=I.channels[2]>0),d=Math.min(d,I.minHeight),f=Math.min(f,I.minFramerate),g=Math.min(g,I.minBitrate),T.filter(C=>I.videoRanges[C]>0).length>0&&(h=!0)}d=$(d)?d:0,f=$(f)?f:0;const S=Math.max(1080,d),A=Math.max(30,f);g=$(g)?g:t,t=Math.max(g,t),h||(e=void 0);const D=n.length>1;return{codecSet:n.reduce((x,I)=>{const L=r[I];if(I===x)return x;if(v=h?T.filter(C=>L.videoRanges[C]>0):[],D){if(L.minBitrate>t)return St(I,`min bitrate of ${L.minBitrate} > current estimate of ${t}`),x;if(!L.hasDefaultAudio)return St(I,"no renditions with default or auto-select sound found"),x;if(o&&I.indexOf(o.substring(0,4))%5!==0)return St(I,`audio codec preference "${o}" not found`),x;if(a&&!l){if(!L.channels[a])return St(I,`no renditions with ${a} channel sound found (channels options: ${Object.keys(L.channels)})`),x}else if((!o||l)&&u&&L.channels[2]===0)return St(I,"no renditions with stereo sound found"),x;if(L.minHeight>S)return St(I,`min resolution of ${L.minHeight} > maximum of ${S}`),x;if(L.minFramerate>A)return St(I,`min framerate of ${L.minFramerate} > maximum of ${A}`),x;if(!v.some(C=>L.videoRanges[C]>0))return St(I,`no variants with VIDEO-RANGE of ${ue(v)} found`),x;if(c&&I.indexOf(c.substring(0,4))%5!==0)return St(I,`video codec preference "${c}" not found`),x;if(L.maxScore<y)return St(I,`max score of ${L.maxScore} < selected max of ${y}`),x}return x&&(Oi(I)>=Oi(x)||L.fragmentError>r[x].fragmentError)?x:(p=L.minIndex,y=L.maxScore,I)},void 0),videoRanges:v,preferHDR:E,minFramerate:f,minBitrate:g,minIndex:p}}function St(r,e){ae.log(`[abr] start candidates with "${r}" ignored because ${e}`)}function Ao(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 Sd(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 _o(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 xt(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||xd(n,e.lang))&&(n===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in r)||Ad(r.characteristics||"",e.characteristics))&&(t===void 0||t(r,e))}function xd(r,e="--"){return r.length===e.length?r===e:r.startsWith(e)||e.startsWith(r)}function Ad(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 _d(r,e,t,s,i){const n=e[s],o=e.reduce((d,f,g)=>{const p=f.uri;return(d[p]||(d[p]=[])).push(g),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=Io(e,s,d=>{if(d.videoRange!==c||d.frameRate!==l||d.codecSet.substring(0,4)!==u)return!1;const f=d.audioGroups,g=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return xt(r,g,i)>-1});return h>-1?h:Io(e,s,d=>{const f=d.audioGroups,g=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return xt(r,g,i)>-1})}function Io(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 Bi(r,e){var t;return!!r&&r!==((t=e.loadLevelObj)==null?void 0:t.uri)}class Id 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,f=a.minAutoLevel,g=i.level,p=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const y=p>-1&&p!==g,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 A=E?E.len/S:0,D=u.loading.first?u.loading.first-u.loading.start:-1,_=u.loaded&&D>-1,x=this.getBwEstimate(),I=a.levels,L=I[g],C=Math.max(u.loaded,Math.round(h*(i.bitrate||L.averageBitrate)/8));let F=_?d-D:d;F<1&&_&&(F=Math.min(d,u.loaded*8/x));const N=_?u.loaded*1e3/F:0,G=T/1e3,U=N?(C-u.loaded)/N:C*8/x+G;if(U<=A)return;const k=N?N*8:x,B=((s=t?.details||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,O=this.hls.config.abrBandWidthUpFactor;let K=Number.POSITIVE_INFINITY,W;for(W=g-1;W>f;W--){const Z=I[W].maxBitrate,j=!I[W].details||B;if(K=this.getTimeToLoadFrag(G,k,h*Z,j),K<Math.min(A,h+G))break}if(K>=U||K>h*10)return;_?this.bwEstimator.sample(d-Math.min(T,D),u.loaded):this.bwEstimator.sampleTTFB(d);const M=I[W].maxBitrate;this.getBwEstimate()*O>M&&this.resetEstimator(M);const w=this.findBestLevel(M,f,W,0,A,1,1);w>-1&&(W=w),this.warn(`Fragment ${i.sn}${n?" part "+n.index:""} of level ${g} is loading too slowly;
|
|
3
3
|
Fragment duration: ${i.duration.toFixed(3)}
|
|
4
4
|
Time to underbuffer: ${A.toFixed(3)} s
|
|
5
|
-
Estimated load time for current fragment: ${
|
|
5
|
+
Estimated load time for current fragment: ${U.toFixed(3)} s
|
|
6
6
|
Estimated load time for down switch fragment: ${K.toFixed(3)} s
|
|
7
7
|
TTFB estimate: ${D|0} ms
|
|
8
8
|
Current BW estimate: ${$(x)?x|0:"Unknown"} bps
|
|
9
9
|
New BW estimate: ${this.getBwEstimate()|0} bps
|
|
10
10
|
Switching to level ${W} @ ${M|0} bps`),a.nextLoadLevel=a.nextAutoLevel=W,this.clearTimer();const Y=()=>{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
11
|
Fragment duration: ${i.duration.toFixed(3)} s
|
|
12
|
-
Time to underbuffer: ${Z.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,W>f){let q=this.findBestLevel(this.hls.levels[f].bitrate,f,W,0,Z,1,1);q===-1&&(q=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=q,this.resetEstimator(this.hls.levels[q].bitrate)}}};y||B>K*2?Y():this.timer=self.setInterval(Y,K*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 ph(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 b.BUFFER_ADD_CODEC_ERROR:case b.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case b.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===V.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!==V.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 f=this.findBestLevel(c,a,i,l,d,u,h);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const g=s.levels[a],p=s.loadLevelObj;return p&&g?.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:f}=this,{levels:g,allAudioTracks:p,loadLevel:y,config:v}=this.hls;if(g.length===1)return 0;const E=g[h],T=!!((c=this.hls.latestLevelDetails)!=null&&c.live),S=y===-1||u===-1;let A,D="SDR",L=E?.frameRate||0;const{audioPreference:x,videoPreference:I}=v,_=this.audioTracksByGroup||(this.audioTracksByGroup=go(p));let C=-1;if(S){if(this.firstSelection!==-1)return this.firstSelection;const w=this.codecTiers||(this.codecTiers=ad(g,_,t,s)),G=nd(w,D,e,x,I),{codecSet:O,videoRanges:K,minFramerate:W,minBitrate:M,minIndex:k,preferHDR:Y}=G;C=k,A=O,D=Y?K[K.length-1]:K[0],L=W,e=Math.max(e,M),this.log(`picked start tier ${ce(G)}`)}else A=E?.codecSet,D=E?.videoRange;const F=f?f.duration:d?d.duration:0,N=this.bwEstimator.getEstimateTTFB()/1e3,U=[];for(let w=s;w>=t;w--){var B;const G=g[w],O=w>h;if(!G)continue;if(v.useMediaCapabilities&&!G.supportedResult&&!G.supportedPromise){const q=navigator.mediaCapabilities;typeof q?.decodingInfo=="function"&&Xh(G,_,D,L,e,x)?(G.supportedPromise=lo(G,_,q,this.supportedCache),G.supportedPromise.then(z=>{if(!this.hls)return;G.supportedResult=z;const me=this.hls.levels,ue=me.indexOf(G);z.error?this.warn(`MediaCapabilities decodingInfo error: "${z.error}" for level ${ue} ${ce(z)}`):z.supported?z.decodingInfoResults.some(Ae=>Ae.smooth===!1||Ae.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ue} not smooth or powerEfficient: ${ce(z)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ue} ${ce(z)}`),ue>-1&&me.length>1&&(this.log(`Removing unsupported level ${ue}`),this.hls.removeLevel(ue),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(z=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${z}`)})):G.supportedResult=ao}if((A&&G.codecSet!==A||D&&G.videoRange!==D||O&&L>G.frameRate||!O&&L>0&&L<G.frameRate||(B=G.supportedResult)!=null&&(B=B.decodingInfoResults)!=null&&B.some(q=>q.smooth===!1))&&(!S||w!==C)){U.push(w);continue}const K=G.details,W=(f?K?.partTarget:K?.averagetargetduration)||F;let M;O?M=o*e:M=a*e;const k=F&&i>=F*2&&n===0?G.averageBitrate:G.maxBitrate,Y=this.getTimeToLoadFrag(N,M,k*W,K===void 0);if(M>=k&&(w===u||G.loadError===0&&G.fragmentError===0)&&(Y<=N||!$(Y)||T&&!this.bitrateTestDelay||Y<l)){const q=this.forcedAutoLevel;return w!==y&&(q===-1||q!==y)&&(U.length&&this.trace(`Skipped level(s) ${U.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[U[0]].codecs}" ${g[U[0]].videoRange}; not compatible with "${A}" ${D}`),this.info(`switch candidate:${h}->${w} adjustedbw(${Math.round(M)})-bitrate=${Math.round(M-k)} ttfb:${N.toFixed(1)} avgDuration:${W.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${Y.toFixed(1)} firstSelection:${S} codecSet:${G.codecSet} videoRange:${G.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 yo={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 hd(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(fd(e,t,a))return a}return null}function ls(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)&&vo(t,s,n)===0||dd(n,r,Math.min(i,s))))return n;const a=yo.search(e,vo.bind(null,t,s));return a&&(a!==r||!n)?a:n}function dd(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 vo(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 fd(r,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>r}function Eo(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 yo.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 Ri(r){switch(r.details){case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_TIMEOUT:case b.LEVEL_LOAD_TIMEOUT:case b.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function To(r){return r.details.startsWith("key")}function So(r){return To(r)&&!!r.frag&&!r.frag.decryptdata}function xo(r,e){const t=Ri(e);return r.default[`${t?"timeout":"error"}Retry`]}function Or(r,e){const t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function Ao(r){return re(re({},r),{errorRetry:null,timeoutRetry:null})}function bi(r,e,t,s){if(!r)return!1;const i=s?.code,n=e<r.maxNumRetry&&(gd(i)||!!t);return r.shouldRetry?r.shouldRetry(r,e,t,s,n):n}function gd(r){return Mr(r)||!!r&&(r<400||r>499)}function Mr(r){return r===0&&navigator.onLine===!1}var Pe={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},je={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class md extends tt{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===V.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 b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case b.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=Ds();return}case b.FRAG_GAP:case b.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Pe.SendAlternateToPenaltyBox;return}case b.LEVEL_EMPTY_ERROR:case b.LEVEL_PARSING_ERROR:{var a;const c=t.parent===V.MAIN?t.level:i.loadLevel;t.details===b.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 b.LEVEL_LOAD_ERROR:case b.LEVEL_LOAD_TIMEOUT:typeof n?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case b.AUDIO_TRACK_LOAD_ERROR:case b.AUDIO_TRACK_LOAD_TIMEOUT:case b.SUBTITLE_LOAD_ERROR:case b.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=Pe.SendAlternateToPenaltyBox,t.errorAction.flags=je.MoveAllAlternatesMatchingHost;return}}return;case b.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Pe.SendAlternateToPenaltyBox,flags:je.MoveAllAlternatesMatchingHDCP};return;case b.KEY_SYSTEM_SESSION_UPDATE_FAILED:case b.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case b.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Pe.SendAlternateToPenaltyBox,flags:je.MoveAllAlternatesMatchingKey};return;case b.BUFFER_ADD_CODEC_ERROR:case b.REMUX_ALLOC_ERROR:case b.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:i.loadLevel)}return;case b.INTERNAL_EXCEPTION:case b.BUFFER_APPENDING_ERROR:case b.BUFFER_FULL_ERROR:case b.LEVEL_SWITCH_ERROR:case b.BUFFER_STALLED_ERROR:case b.BUFFER_SEEK_OVER_HOLE:case b.BUFFER_NUDGE_ON_STALL:t.errorAction=Ds();return}t.type===H.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Ds())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=xo(s.config.playlistLoadPolicy,e),n=this.playlistError++;if(bi(i,n,Ri(e),e.response))return{action:Pe.RetryRequest,flags:je.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=xo(To(e)?a:n,e),c=t.levels.reduce((u,h)=>u+h.fragmentError,0);if(i&&(e.details!==b.FRAG_GAP&&i.fragmentError++,!So(e)&&bi(o,c,Ri(e),e.response)))return{action:Pe.RetryRequest,flags:je.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===b.BUFFER_APPEND_ERROR&&i.fragmentError++;let u=-1;const{levels:h,loadLevel:d,minAutoLevel:f,maxAutoLevel:g}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const p=(n=e.frag)==null?void 0:n.type,v=(p===V.AUDIO&&l===b.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===b.BUFFER_ADD_CODEC_ERROR||l===b.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:D})=>i.audioCodec!==D),T=e.sourceBufferName==="video"&&(l===b.BUFFER_ADD_CODEC_ERROR||l===b.BUFFER_APPEND_ERROR)&&h.some(({codecSet:D,audioCodec:L})=>i.codecSet!==D&&i.audioCodec===L),{type:S,groupId:A}=(a=e.context)!=null?a:{};for(let D=h.length;D--;){const L=(D+d)%h.length;if(L!==d&&L>=f&&L<=g&&h[L].loadError===0){var o,c;const x=h[L];if(l===b.FRAG_GAP&&p===V.MAIN&&e.frag){const I=h[L].details;if(I){const _=ls(e.frag,I.fragments,e.frag.start);if(_!=null&&_.gap)continue}}else{if(S===ee.AUDIO_TRACK&&x.hasAudioGroup(A)||S===ee.SUBTITLE_TRACK&&x.hasSubtitleGroup(A))continue;if(p===V.AUDIO&&(o=i.audioGroups)!=null&&o.some(I=>x.hasAudioGroup(I))||p===V.SUBTITLE&&(c=i.subtitleGroups)!=null&&c.some(I=>x.hasSubtitleGroup(I))||v&&i.audioCodec===x.audioCodec||T&&i.codecSet===x.codecSet||!v&&i.codecSet!==x.codecSet)continue}u=L;break}}if(u>-1&&s.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:Pe.SendAlternateToPenaltyBox,flags:je.None,nextAutoLevel:u}}return{action:Pe.SendAlternateToPenaltyBox,flags:je.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case Pe.DoNothing:break;case Pe.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==b.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 je.None:this.switchLevel(e,n);break;case je.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=wr[wr.indexOf(u)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case je.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) ${Ue(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!==V.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===b.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=kr(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 Ds(r){const e={action:Pe.DoNothing,flags:je.None};return r&&(e.resolved=!0),e}var Ie={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class pd{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=Cs(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?(n.buffered=!0,(n.body.endList=s.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),Di(n)||this.removeParts(s.sn-1,s.type)):this.removeFragment(n.body)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Lo(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=Cs(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,i.buffered=!0)}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 f=Math.max(a,i.start(u)),g=Math.min(o,i.end(u));g>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:g}))}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&&Di(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||Di(t))}getState(e){const t=Cs(e),s=this.fragments[t];return s?s.buffered?Di(s)?Ie.PARTIAL:Ie.OK:Ie.APPENDING:Ie.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=Cs(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=Cs(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=Cs(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=Lo(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 Di(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 Cs(r){return`${r.type}_${r.level}_${r.sn}`}function Lo(r,e){return r.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var Vt={cbc:0,ctr:1};class yd{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 Vt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Vt.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 vd(r){const e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?r.slice(0,e-t):r}class Ed{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],f=new Uint32Array(256);let g=0,p=0,y=0;for(y=0;y<256;y++)y<128?f[y]=y<<1:f[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[g]=v,t[v]=g;const E=f[g],T=f[E],S=f[T];let A=f[v]*257^v*16843008;i[g]=A<<24|A>>>8,n[g]=A<<16|A>>>16,a[g]=A<<8|A>>>24,o[g]=A,A=S*16843009^T*65537^E*257^g*16843008,l[v]=A<<24|A>>>8,u[v]=A<<16|A>>>16,h[v]=A<<8|A>>>24,d[v]=A,g?(g=E^f[f[f[S^E]]],p^=f[f[p]]):g=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,f=this.invSubMix,g=f[0],p=f[1],y=f[2],v=f[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]=g[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 f=d[0],g=d[1],p=d[2],y=d[3];const v=new Int32Array(e),E=new Int32Array(v.length);let T,S,A,D,L,x,I,_,C,F,N,U,B,w;const G=this.networkToHostOrderSwap;for(;t<v.length;){for(C=G(v[t]),F=G(v[t+1]),N=G(v[t+2]),U=G(v[t+3]),L=C^n[0],x=U^n[1],I=N^n[2],_=F^n[3],B=4,w=1;w<i;w++)T=c[L>>>24]^l[x>>16&255]^u[I>>8&255]^h[_&255]^n[B],S=c[x>>>24]^l[I>>16&255]^u[_>>8&255]^h[L&255]^n[B+1],A=c[I>>>24]^l[_>>16&255]^u[L>>8&255]^h[x&255]^n[B+2],D=c[_>>>24]^l[L>>16&255]^u[x>>8&255]^h[I&255]^n[B+3],L=T,x=S,I=A,_=D,B=B+4;T=a[L>>>24]<<24^a[x>>16&255]<<16^a[I>>8&255]<<8^a[_&255]^n[B],S=a[x>>>24]<<24^a[I>>16&255]<<16^a[_>>8&255]<<8^a[L&255]^n[B+1],A=a[I>>>24]<<24^a[_>>16&255]<<16^a[L>>8&255]<<8^a[x&255]^n[B+2],D=a[_>>>24]<<24^a[L>>16&255]<<16^a[x>>8&255]<<8^a[I&255]^n[B+3],E[t]=G(T^f),E[t+1]=G(D^g),E[t+2]=G(A^p),E[t+3]=G(S^y),f=C,g=F,p=N,y=U,t=t+4}return E.buffer}}class Td{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=Sd(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function Sd(r){switch(r){case Vt.cbc:return"AES-CBC";case Vt.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${r}`)}}const xd=16;class Fr{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?vd(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!==Vt.cbc||t.byteLength!==16)return ne.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=st(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 Ed),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 Td(this.subtle,t,i)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new yd(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(ne.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%xd;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(ne.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Io=Math.pow(2,17);class Ad{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 It({type:H.NETWORK_ERROR,details:b.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(g=>g[0]==="GAP")){c(Ro(e));return}else e.gap=!1;const l=this.loader=n?new n(i):new a(i),u=_o(e);e.loader=l;const h=Ao(i.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Io};e.stats=l.stats;const f={onSuccess:(g,p,y,v)=>{this.resetLoader(e,l);let E=g.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:(g,p,y,v)=>{this.resetLoader(e,l),c(new It({type:H.NETWORK_ERROR,details:b.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:re({url:s,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:y,stats:v}))},onAbort:(g,p,y)=>{this.resetLoader(e,l),c(new It({type:H.NETWORK_ERROR,details:b.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:y,stats:g}))},onTimeout:(g,p,y)=>{this.resetLoader(e,l),c(new It({type:H.NETWORK_ERROR,details:b.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:y,stats:g}))}};t&&(f.onProgress=(g,p,y,v)=>t({frag:e,part:null,payload:y,networkDetails:v})),l.load(u,d,f)})}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(Ro(e,t));return}const l=this.loader=n?new n(i):new a(i),u=_o(e,t);e.loader=l;const h=Ao(i.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Io};t.stats=l.stats,l.load(u,d,{onSuccess:(f,g,p,y)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:f.data,networkDetails:y};s(v),o(v)},onError:(f,g,p,y)=>{this.resetLoader(e,l),c(new It({type:H.NETWORK_ERROR,details:b.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:re({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:y}))},onAbort:(f,g,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new It({type:H.NETWORK_ERROR,details:b.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,l),c(new It({type:H.NETWORK_ERROR,details:b.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:p,stats:f}))}})})}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 _o(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"&&Ld((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 Ro(r,e){const t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),s={type:H.MEDIA_ERROR,details:b.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(s.part=e),(e||r).stats.aborted=!0,new It(s)}function Ld(r){return r==="AES-128"||r==="AES-256"}class It extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class bo extends tt{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 Nr{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=Ci(),this.buffering={audio:Ci(),video:Ci(),audiovideo:Ci()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=n,this.partial=a}}function Ci(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Do={length:0,start:()=>0,end:()=>0};class X{static isBuffered(e,t){if(e){const s=X.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=X.getBuffered(e);return X.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=X.bufferedRanges(e);if(i.length)return X.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||Do}catch(t){return ne.log("failed to get media.buffered",t),Do}}}const Co=/\{\$([a-zA-Z0-9-_]+)\}/g;function Po(r){return Co.test(r)}function $r(r,e){if(r.variableList!==null||r.hasVariableRefs){const t=r.variableList;return e.replace(Co,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 ko(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 Id(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 _d=/^(\d+)x(\d+)$/,wo=/(.+?)=(".*?"|.*?)(?:,|$)/g;class pe{constructor(e,t){typeof e=="string"&&(e=pe.parseAttrList(e,t)),oe(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=_d.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(wo.lastIndex=0;(s=wo.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=$r(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":ne.warn(`${e}: attribute ${a} is missing quotes`)}i[a]=o}return i}}const Rd="com.apple.hls.interstitial";function bd(r){return r!=="ID"&&r!=="CLASS"&&r!=="CUE"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function Dd(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"||r==="SCTE35-CMD"}class Oo{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]){ne.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=oe(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?(ne.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===Rd}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 Cd=10;class Pd{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||Cd}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 Br(r,e){return r.length===e.length?!r.some((t,s)=>t!==e[s]):!1}function Mo(r,e){return!r&&!e?!0:!r||!e?!1:Br(r,e)}function Ps(r){return r==="AES-128"||r==="AES-256"||r==="AES-256-CTR"}function Ur(r){switch(r){case"AES-128":case"AES-256":return Vt.cbc;case"AES-256-CTR":return Vt.ctr;default:throw new Error(`invalid full segment method ${r}`)}}function Gr(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function Kr(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}function kd(r){const e=Kr(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Fo(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 wd(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=Gr(a)):t=kd(a)}}return t}const Pi=typeof self<"u"?self:void 0;var ye={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Fe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function ki(r){switch(r){case Fe.FAIRPLAY:return ye.FAIRPLAY;case Fe.PLAYREADY:return ye.PLAYREADY;case Fe.WIDEVINE:return ye.WIDEVINE;case Fe.CLEARKEY:return ye.CLEARKEY}}function Vr(r){switch(r){case ye.FAIRPLAY:return Fe.FAIRPLAY;case ye.PLAYREADY:return Fe.PLAYREADY;case ye.WIDEVINE:return Fe.WIDEVINE;case ye.CLEARKEY:return Fe.CLEARKEY}}function Ws(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 No=(function(r){return Pi!=null&&(r=Pi.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function Od(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 Md(i,e,t,s)}function Md(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 Fd(r){var e;return!!r&&(r.sessionType==="persistent-license"||!!((e=r.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Nd(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=Gr(o).subarray(0,16);return Fo(c),c}}return null}let wi={};class Ys{static clearKeyUriToKeyIdMap(){wi={}}static setKeyIdForUri(e,t){wi[e]=t}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&&!Ps(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Va(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Br(e.keyFormatVersions,this.keyFormatVersions)&&Mo(e.iv,this.iv)&&Mo(e.keyId,this.keyId)}isSupported(){if(this.method){if(Ps(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Fe.FAIRPLAY:case Fe.WIDEVINE:case Fe.PLAYREADY:case Fe.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(Ps(this.method)){let i=this.iv;return i||(typeof e!="number"&&(ne.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),i=$d(e)),new Ys(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.pssh&&this.keyId)return this;const t=wd(this.uri);if(t)switch(this.keyFormat){case Fe.WIDEVINE:if(this.pssh=t,!this.keyId){const i=Uh(t.buffer);if(i.length){var s;const n=i[0];this.keyId=(s=n.kids)!=null&&s.length?n.kids[0]:null}}if(!this.keyId){const i=t.length-22;this.keyId=t.subarray(i,i+16)}break;case Fe.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Bh(i,null,t),this.keyId=Nd(t);break}default:{let i=t.subarray(0,16);if(i.length!==16){const n=new Uint8Array(16);n.set(i,16-i.length),i=n}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=wi[this.uri];if(!i){const n=Object.keys(wi).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,n),Ys.setKeyIdForUri(this.uri,i)}this.keyId=i}return this}}function $d(r){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}const $o=/#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,Bo=/#EXT-X-MEDIA:(.*)/g,Bd=/^#EXT(?:INF|-X-TARGETDURATION):/m,Hr=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Ud=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 gt{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 Lr.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Bd.test(e)}static parseMasterPlaylist(e,t){const s=Po(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},n=[];if($o.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let a;for(;(a=$o.exec(e))!=null;)if(a[1]){var o;const l=new pe(a[1],i),u=$r(i,a[2]),h={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:gt.resolve(u,t)},d=l.decimalResolution("RESOLUTION");d&&(h.width=d.width,h.height=d.height),Vo(l.CODECS,h);const f=l["SUPPLEMENTAL-CODECS"];f&&(h.supplemental={},Vo(f,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=Go(u,t,i);h.encrypted&&h.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(h)):ne.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const h=new pe(u,i);ko(i,h,t)}break}case"CONTENT-STEERING":{const h=new pe(u,i);i.contentSteering={uri:gt.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=Ko(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(Bo.lastIndex=0;(i=Bo.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 f=l.LANGUAGE,g=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||f||"",type:u,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:f,url:l.URI?gt.resolve(l.URI,t):""};if(g&&(E.assocLang=g),p&&(E.channels=p),y&&(E.characteristics=y),v&&(E.instreamId=v),h!=null&&h.length){const T=gt.findGroup(h,E.groupId)||h[0];Ho(E,T,"audioCodec"),Ho(E,T,"textCodec")}d.push(E)}}return n}static parseLevelPlaylist(e,t,s,i,n,a){var o;const c={url:t},l=new Pd(t),u=l.fragments,h=[];let d=null,f=0,g=0,p=0,y=0,v=0,E=null,T=new _r(i,c),S,A,D,L=-1,x=!1,I=null,_;if(Hr.lastIndex=0,l.m3u8=e,l.hasVariableRefs=Po(e),((o=Hr.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(S=Hr.exec(e))!==null;){x&&(x=!1,T=new _r(i,c),T.playlistOffset=p,T.setStart(p),T.sn=f,T.cc=y,v&&(T.bitrate=v),T.level=s,d&&(T.initSegment=d,d.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),I&&(T.setByteRange(I),I=null)));const U=S[1];if(U){T.duration=parseFloat(U);const B=(" "+S[2]).slice(1);T.title=B||null,T.tagList.push(B?["INF",U,B]:["INF",U])}else if(S[3]){if($(T.duration)){T.playlistOffset=p,T.setStart(p),D&&Yo(T,D,l),T.sn=f,T.level=s,T.cc=y,u.push(T);const B=(" "+S[3]).slice(1);T.relurl=$r(l,B),Wr(T,E,h),E=T,p+=T.duration,f++,g=0,x=!0}}else{if(S=S[0].match(Ud),!S){ne.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A<S.length&&S[A]===void 0;A++);const B=(" "+S[A]).slice(1),w=(" "+S[A+1]).slice(1),G=S[A+2]?(" "+S[A+2]).slice(1):null;switch(B){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]),L===-1&&(L=u.length);break;case"PLAYLIST-TYPE":l.type&&_t(l,B,S),l.type=w.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?_t(l,B,S):u.length>0&&jo(l,B,S),f=l.startSN=parseInt(w);break;case"SKIP":{l.skippedSegments&&_t(l,B,S);const O=new pe(w,l),K=O.decimalInteger("SKIPPED-SEGMENTS");if($(K)){l.skippedSegments+=K;for(let M=K;M--;)u.push(null);f+=K}const W=O.enumeratedString("RECENTLY-REMOVED-DATERANGES");W&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(W.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&_t(l,B,S),l.targetduration=Math.max(parseInt(w),1);break;case"VERSION":l.version!==null&&_t(l,B,S),l.version=parseInt(w);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||_t(l,B,S),l.live=!1;break;case"#":(w||G)&&T.tagList.push(G?[w,G]:[w]);break;case"DISCONTINUITY":y++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([B]);break;case"BITRATE":T.tagList.push([B,w]),v=parseInt(w)*1e3,$(v)?T.bitrate=v:v=0;break;case"DATERANGE":{const O=new pe(w,l),K=new Oo(O,l.dateRanges[O.ID],l.dateRangeTagCount);l.dateRangeTagCount++,K.isValid||l.skippedSegments?l.dateRanges[K.id]=K:ne.warn(`Ignoring invalid DATERANGE tag: "${w}"`),T.tagList.push(["EXT-X-DATERANGE",w]);break}case"DEFINE":{{const O=new pe(w,l);"IMPORT"in O?Id(l,O,a):ko(l,O,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?_t(l,B,S):u.length>0&&jo(l,B,S),l.startCC=y=parseInt(w);break;case"KEY":{const O=Go(w,t,l);if(O.isSupported()){if(O.method==="NONE"){D=void 0;break}D||(D={});const K=D[O.keyFormat];K!=null&&K.matches(O)||(K&&(D=oe({},D)),D[O.keyFormat]=O)}else ne.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${w}"`);break}case"START":l.startTimeOffset=Ko(w);break;case"MAP":{const O=new pe(w,l);if(T.duration){const K=new _r(i,c);Wo(K,O,s,D),d=K,T.initSegment=d,d.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime)}else{const K=T.byteRangeEndOffset;if(K){const W=T.byteRangeStartOffset;I=`${K-W}@${W}`}else I=null;Wo(T,O,s,D),d=T,x=!0}d.cc=y;break}case"SERVER-CONTROL":{_&&_t(l,B,S),_=new pe(w),l.canBlockReload=_.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=_.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&_.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=_.optionalFloat("PART-HOLD-BACK",0),l.holdBack=_.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&_t(l,B,S);const O=new pe(w);l.partTarget=O.decimalFloatingPoint("PART-TARGET");break}case"PART":{let O=l.partList;O||(O=l.partList=[]);const K=g>0?O[O.length-1]:void 0,W=g++,M=new pe(w,l),k=new _h(M,T,c,W,K);O.push(k),T.duration+=k.duration;break}case"PRELOAD-HINT":{const O=new pe(w,l);l.preloadHint=O;break}case"RENDITION-REPORT":{const O=new pe(w,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(O);break}default:ne.warn(`line parsed but not handled: ${S}`);break}}}E&&!E.relurl?(u.pop(),p-=E.duration,l.partList&&(l.fragmentHint=E)):l.partList&&(Wr(T,E,h),T.cc=y,l.fragmentHint=T,D&&Yo(T,D,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const C=u.length,F=u[0],N=u[C-1];if(p+=l.skippedSegments*l.targetduration,p>0&&C&&N){l.averagetargetduration=p/C;const U=N.sn;l.endSN=U!=="initSegment"?U:0,l.live||(N.endList=!0),L>0&&(Kd(u,L),F&&h.unshift(F))}return l.fragmentHint&&(p+=l.fragmentHint.duration),l.totalduration=p,h.length&&l.dateRangeTagCount&&F&&Uo(h,l),l.endCC=y,l}}function Uo(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=Gd(e,l,r,u,i);if(h!==-1){c.tagAnchor=e.fragments[h].ref;break}}}}function Gd(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 f=d;f>l;f--){const g=u[f].programDateTime;if(e>=g&&e<g+u[f].duration*1e3)return f}}return l}}}return-1}function Go(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&&ne.error(`Invalid IV: ${n.IV}`);const h=o?gt.resolve(o,e):"",d=(l||"1").split("/").map(Number).filter(Number.isFinite);return new Ys(a,h,u,d,c,n.KEYID)}function Ko(r){const t=new pe(r).decimalFloatingPoint("TIME-OFFSET");return $(t)?t:null}function Vo(r,e){let t=(r||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const i=t.filter(n=>Dr(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 Ho(r,e,t){const s=e[t];s&&(r[t]=s)}function Kd(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 Wr(r,e,t){r.rawProgramDateTime?t.push(r):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime)}function Wo(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 Yo(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 _t(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function jo(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Yr(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 qo(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 f=e.sn;if(!r||f<r.startSN||f>r.endSN)return 0;let g;const p=f-r.startSN,y=r.fragments;for(y[p]=e,g=p;g>0;g--)Yr(y[g],y[g-1]);for(g=p;g<y.length-1;g++)Yr(y[g],y[g+1]);return r.fragmentHint&&Yr(y[y.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,d}function Vd(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;Yd(r,e,(u,h,d,f)=>{if((!e.startCC||e.skippedSegments)&&h.cc!==u.cc){const g=u.cc-h.cc;for(let p=d;p<f.length;p++)f[p].cc+=g;e.endCC=f[f.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=Hd(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&&Wr(o[h],o[h-1],u);Uo(u,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var c;const u=Jo(r,e.startSN-1);e.startCC=(c=u?.cc)!=null?c:a[0].cc}Wd(r.partList,e.partList,(u,h)=>{h.elementaryStreams=u.elementaryStreams,h.stats=u.stats}),n?qo(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,t):zo(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 Hd(r,e,t){const{dateRanges:s,recentlyRemovedDateranges:i}=e,n=oe({},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 Oo(s[c].attr,l);u.isValid?(n[c]=u,l||(u.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ce(s[c].attr)}"`)}),n):s}function Wd(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 Yd(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,f=h.relurl;if(d&&jd(d,f)){e.playlistParsingError=Xo(`media sequence mismatch ${h.sn}:`,r,e,u,h);return}else if(u.cc!==h.cc){e.playlistParsingError=Xo(`discontinuity sequence mismatch (${u.cc}!=${h.cc})`,r,e,u,h);return}}}}function Xo(r,e,t,s,i){return new Error(`${r} ${i.url}
|
|
12
|
+
Time to underbuffer: ${Z.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,W>f){let j=this.findBestLevel(this.hls.levels[f].bitrate,f,W,0,Z,1,1);j===-1&&(j=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=j,this.resetEstimator(this.hls.levels[j].bitrate)}}};y||U>K*2?Y():this.timer=self.setInterval(Y,K*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 Ch(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 b.BUFFER_ADD_CODEC_ERROR:case b.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case b.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===V.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!==V.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 f=this.findBestLevel(c,a,i,l,d,u,h);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const g=s.levels[a],p=s.loadLevelObj;return p&&g?.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:f}=this,{levels:g,allAudioTracks:p,loadLevel:y,config:v}=this.hls;if(g.length===1)return 0;const E=g[h],T=!!((c=this.hls.latestLevelDetails)!=null&&c.live),S=y===-1||u===-1;let A,D="SDR",_=E?.frameRate||0;const{audioPreference:x,videoPreference:I}=v,L=this.audioTracksByGroup||(this.audioTracksByGroup=Ao(p));let C=-1;if(S){if(this.firstSelection!==-1)return this.firstSelection;const k=this.codecTiers||(this.codecTiers=Sd(g,L,t,s)),B=Td(k,D,e,x,I),{codecSet:O,videoRanges:K,minFramerate:W,minBitrate:M,minIndex:w,preferHDR:Y}=B;C=w,A=O,D=Y?K[K.length-1]:K[0],_=W,e=Math.max(e,M),this.log(`picked start tier ${ue(B)}`)}else A=E?.codecSet,D=E?.videoRange;const F=f?f.duration:d?d.duration:0,N=this.bwEstimator.getEstimateTTFB()/1e3,G=[];for(let k=s;k>=t;k--){var U;const B=g[k],O=k>h;if(!B)continue;if(v.useMediaCapabilities&&!B.supportedResult&&!B.supportedPromise){const j=navigator.mediaCapabilities;typeof j?.decodingInfo=="function"&&ud(B,L,D,_,e,x)?(B.supportedPromise=vo(B,L,j,this.supportedCache),B.supportedPromise.then(z=>{if(!this.hls)return;B.supportedResult=z;const pe=this.hls.levels,he=pe.indexOf(B);z.error?this.warn(`MediaCapabilities decodingInfo error: "${z.error}" for level ${he} ${ue(z)}`):z.supported?z.decodingInfoResults.some(_e=>_e.smooth===!1||_e.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${he} not smooth or powerEfficient: ${ue(z)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${he} ${ue(z)}`),he>-1&&pe.length>1&&(this.log(`Removing unsupported level ${he}`),this.hls.removeLevel(he),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(z=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${z}`)})):B.supportedResult=po}if((A&&B.codecSet!==A||D&&B.videoRange!==D||O&&_>B.frameRate||!O&&_>0&&_<B.frameRate||(U=B.supportedResult)!=null&&(U=U.decodingInfoResults)!=null&&U.some(j=>j.smooth===!1))&&(!S||k!==C)){G.push(k);continue}const K=B.details,W=(f?K?.partTarget:K?.averagetargetduration)||F;let M;O?M=o*e:M=a*e;const w=F&&i>=F*2&&n===0?B.averageBitrate:B.maxBitrate,Y=this.getTimeToLoadFrag(N,M,w*W,K===void 0);if(M>=w&&(k===u||B.loadError===0&&B.fragmentError===0)&&(Y<=N||!$(Y)||T&&!this.bitrateTestDelay||Y<l)){const j=this.forcedAutoLevel;return k!==y&&(j===-1||j!==y)&&(G.length&&this.trace(`Skipped level(s) ${G.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[G[0]].codecs}" ${g[G[0]].videoRange}; not compatible with "${A}" ${D}`),this.info(`switch candidate:${h}->${k} adjustedbw(${Math.round(M)})-bitrate=${Math.round(M-w)} ttfb:${N.toFixed(1)} avgDuration:${W.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${Y.toFixed(1)} firstSelection:${S} codecSet:${B.codecSet} videoRange:${B.videoRange} hls.loadLevel:${y}`)),S&&(this.firstSelection=k),k}}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 Lo={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 Ld(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(bd(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)&&Ro(t,s,n)===0||Rd(n,r,Math.min(i,s))))return n;const a=Lo.search(e,Ro.bind(null,t,s));return a&&(a!==r||!n)?a:n}function Rd(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 Ro(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 bd(r,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>r}function bo(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 Lo.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 Ui(r){switch(r.details){case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_TIMEOUT:case b.LEVEL_LOAD_TIMEOUT:case b.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Do(r){return r.details.startsWith("key")}function Co(r){return Do(r)&&!!r.frag&&!r.frag.decryptdata}function Po(r,e){const t=Ui(e);return r.default[`${t?"timeout":"error"}Retry`]}function Vr(r,e){const t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function ko(r){return ne(ne({},r),{errorRetry:null,timeoutRetry:null})}function Gi(r,e,t,s){if(!r)return!1;const i=s?.code,n=e<r.maxNumRetry&&(Dd(i)||!!t);return r.shouldRetry?r.shouldRetry(r,e,t,s,n):n}function Dd(r){return Hr(r)||!!r&&(r<400||r>499)}function Hr(r){return r===0&&navigator.onLine===!1}var Ce={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Je={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class Cd 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===V.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 b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case b.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=Os();return}case b.FRAG_GAP:case b.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Ce.SendAlternateToPenaltyBox;return}case b.LEVEL_EMPTY_ERROR:case b.LEVEL_PARSING_ERROR:{var a;const c=t.parent===V.MAIN?t.level:i.loadLevel;t.details===b.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 b.LEVEL_LOAD_ERROR:case b.LEVEL_LOAD_TIMEOUT:typeof n?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case b.AUDIO_TRACK_LOAD_ERROR:case b.AUDIO_TRACK_LOAD_TIMEOUT:case b.SUBTITLE_LOAD_ERROR:case b.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=Ce.SendAlternateToPenaltyBox,t.errorAction.flags=Je.MoveAllAlternatesMatchingHost;return}}return;case b.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Ce.SendAlternateToPenaltyBox,flags:Je.MoveAllAlternatesMatchingHDCP};return;case b.KEY_SYSTEM_SESSION_UPDATE_FAILED:case b.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case b.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Ce.SendAlternateToPenaltyBox,flags:Je.MoveAllAlternatesMatchingKey};return;case b.BUFFER_ADD_CODEC_ERROR:case b.REMUX_ALLOC_ERROR:case b.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:i.loadLevel)}return;case b.INTERNAL_EXCEPTION:case b.BUFFER_APPENDING_ERROR:case b.BUFFER_FULL_ERROR:case b.LEVEL_SWITCH_ERROR:case b.BUFFER_STALLED_ERROR:case b.BUFFER_SEEK_OVER_HOLE:case b.BUFFER_NUDGE_ON_STALL:t.errorAction=Os();return}t.type===H.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Os())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=Po(s.config.playlistLoadPolicy,e),n=this.playlistError++;if(Gi(i,n,Ui(e),e.response))return{action:Ce.RetryRequest,flags:Je.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=Po(Do(e)?a:n,e),c=t.levels.reduce((u,h)=>u+h.fragmentError,0);if(i&&(e.details!==b.FRAG_GAP&&i.fragmentError++,!Co(e)&&Gi(o,c,Ui(e),e.response)))return{action:Ce.RetryRequest,flags:Je.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===b.BUFFER_APPEND_ERROR&&i.fragmentError++;let u=-1;const{levels:h,loadLevel:d,minAutoLevel:f,maxAutoLevel:g}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const p=(n=e.frag)==null?void 0:n.type,v=(p===V.AUDIO&&l===b.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===b.BUFFER_ADD_CODEC_ERROR||l===b.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:D})=>i.audioCodec!==D),T=e.sourceBufferName==="video"&&(l===b.BUFFER_ADD_CODEC_ERROR||l===b.BUFFER_APPEND_ERROR)&&h.some(({codecSet:D,audioCodec:_})=>i.codecSet!==D&&i.audioCodec===_),{type:S,groupId:A}=(a=e.context)!=null?a:{};for(let D=h.length;D--;){const _=(D+d)%h.length;if(_!==d&&_>=f&&_<=g&&h[_].loadError===0){var o,c;const x=h[_];if(l===b.FRAG_GAP&&p===V.MAIN&&e.frag){const I=h[_].details;if(I){const L=gs(e.frag,I.fragments,e.frag.start);if(L!=null&&L.gap)continue}}else{if(S===ee.AUDIO_TRACK&&x.hasAudioGroup(A)||S===ee.SUBTITLE_TRACK&&x.hasSubtitleGroup(A))continue;if(p===V.AUDIO&&(o=i.audioGroups)!=null&&o.some(I=>x.hasAudioGroup(I))||p===V.SUBTITLE&&(c=i.subtitleGroups)!=null&&c.some(I=>x.hasSubtitleGroup(I))||v&&i.audioCodec===x.audioCodec||T&&i.codecSet===x.codecSet||!v&&i.codecSet!==x.codecSet)continue}u=_;break}}if(u>-1&&s.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:Ce.SendAlternateToPenaltyBox,flags:Je.None,nextAutoLevel:u}}return{action:Ce.SendAlternateToPenaltyBox,flags:Je.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case Ce.DoNothing:break;case Ce.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==b.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 Je.None:this.switchLevel(e,n);break;case Je.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=Kr[Kr.indexOf(u)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Je.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) ${Be(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!==V.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===b.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=Gr(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 Os(r){const e={action:Ce.DoNothing,flags:Je.None};return r&&(e.resolved=!0),e}var Re={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Pd{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=Ms(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?(n.buffered=!0,(n.body.endList=s.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),Ki(n)||this.removeParts(s.sn-1,s.type)):this.removeFragment(n.body)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=wo(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=Ms(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,i.buffered=!0)}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 f=Math.max(a,i.start(u)),g=Math.min(o,i.end(u));g>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:g}))}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&&Ki(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||Ki(t))}getState(e){const t=Ms(e),s=this.fragments[t];return s?s.buffered?Ki(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=Ms(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=Ms(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=Ms(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 Ki(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 Ms(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 Jt={cbc:0,ctr:1};class kd{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 Jt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Jt.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 wd(r){const e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?r.slice(0,e-t):r}class Od{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],f=new Uint32Array(256);let g=0,p=0,y=0;for(y=0;y<256;y++)y<128?f[y]=y<<1:f[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[g]=v,t[v]=g;const E=f[g],T=f[E],S=f[T];let A=f[v]*257^v*16843008;i[g]=A<<24|A>>>8,n[g]=A<<16|A>>>16,a[g]=A<<8|A>>>24,o[g]=A,A=S*16843009^T*65537^E*257^g*16843008,l[v]=A<<24|A>>>8,u[v]=A<<16|A>>>16,h[v]=A<<8|A>>>24,d[v]=A,g?(g=E^f[f[f[S^E]]],p^=f[f[p]]):g=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,f=this.invSubMix,g=f[0],p=f[1],y=f[2],v=f[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]=g[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 f=d[0],g=d[1],p=d[2],y=d[3];const v=new Int32Array(e),E=new Int32Array(v.length);let T,S,A,D,_,x,I,L,C,F,N,G,U,k;const B=this.networkToHostOrderSwap;for(;t<v.length;){for(C=B(v[t]),F=B(v[t+1]),N=B(v[t+2]),G=B(v[t+3]),_=C^n[0],x=G^n[1],I=N^n[2],L=F^n[3],U=4,k=1;k<i;k++)T=c[_>>>24]^l[x>>16&255]^u[I>>8&255]^h[L&255]^n[U],S=c[x>>>24]^l[I>>16&255]^u[L>>8&255]^h[_&255]^n[U+1],A=c[I>>>24]^l[L>>16&255]^u[_>>8&255]^h[x&255]^n[U+2],D=c[L>>>24]^l[_>>16&255]^u[x>>8&255]^h[I&255]^n[U+3],_=T,x=S,I=A,L=D,U=U+4;T=a[_>>>24]<<24^a[x>>16&255]<<16^a[I>>8&255]<<8^a[L&255]^n[U],S=a[x>>>24]<<24^a[I>>16&255]<<16^a[L>>8&255]<<8^a[_&255]^n[U+1],A=a[I>>>24]<<24^a[L>>16&255]<<16^a[_>>8&255]<<8^a[x&255]^n[U+2],D=a[L>>>24]<<24^a[_>>16&255]<<16^a[x>>8&255]<<8^a[I&255]^n[U+3],E[t]=B(T^f),E[t+1]=B(D^g),E[t+2]=B(A^p),E[t+3]=B(S^y),f=C,g=F,p=N,y=G,t=t+4}return E.buffer}}class Md{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=Fd(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function Fd(r){switch(r){case Jt.cbc:return"AES-CBC";case Jt.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${r}`)}}const Nd=16;class Wr{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?wd(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!==Jt.cbc||t.byteLength!==16)return ae.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 Od),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 Md(this.subtle,t,i)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new kd(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(ae.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%Nd;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(ae.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Oo=Math.pow(2,17);class $d{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 $t({type:H.NETWORK_ERROR,details:b.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(g=>g[0]==="GAP")){c(Fo(e));return}else e.gap=!1;const l=this.loader=n?new n(i):new a(i),u=Mo(e);e.loader=l;const h=ko(i.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Oo};e.stats=l.stats;const f={onSuccess:(g,p,y,v)=>{this.resetLoader(e,l);let E=g.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:(g,p,y,v)=>{this.resetLoader(e,l),c(new $t({type:H.NETWORK_ERROR,details:b.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:ne({url:s,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:y,stats:v}))},onAbort:(g,p,y)=>{this.resetLoader(e,l),c(new $t({type:H.NETWORK_ERROR,details:b.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:y,stats:g}))},onTimeout:(g,p,y)=>{this.resetLoader(e,l),c(new $t({type:H.NETWORK_ERROR,details:b.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:y,stats:g}))}};t&&(f.onProgress=(g,p,y,v)=>t({frag:e,part:null,payload:y,networkDetails:v})),l.load(u,d,f)})}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(Fo(e,t));return}const l=this.loader=n?new n(i):new a(i),u=Mo(e,t);e.loader=l;const h=ko(i.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Oo};t.stats=l.stats,l.load(u,d,{onSuccess:(f,g,p,y)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:f.data,networkDetails:y};s(v),o(v)},onError:(f,g,p,y)=>{this.resetLoader(e,l),c(new $t({type:H.NETWORK_ERROR,details:b.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:ne({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:y}))},onAbort:(f,g,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new $t({type:H.NETWORK_ERROR,details:b.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,l),c(new $t({type:H.NETWORK_ERROR,details:b.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:p,stats:f}))}})})}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 Mo(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"&&Bd((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 Fo(r,e){const t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),s={type:H.MEDIA_ERROR,details:b.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(s.part=e),(e||r).stats.aborted=!0,new $t(s)}function Bd(r){return r==="AES-128"||r==="AES-256"}class $t extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class No 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 Yr{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=Vi(),this.buffering={audio:Vi(),video:Vi(),audiovideo:Vi()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=n,this.partial=a}}function Vi(){return{start:0,executeStart:0,executeEnd:0,end:0}}const $o={length:0,start:()=>0,end:()=>0};class X{static isBuffered(e,t){if(e){const s=X.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=X.getBuffered(e);return X.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=X.bufferedRanges(e);if(i.length)return X.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||$o}catch(t){return ae.log("failed to get media.buffered",t),$o}}}const Bo=/\{\$([a-zA-Z0-9-_]+)\}/g;function Uo(r){return Bo.test(r)}function qr(r,e){if(r.variableList!==null||r.hasVariableRefs){const t=r.variableList;return e.replace(Bo,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 Go(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 Ud(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 Gd=/^(\d+)x(\d+)$/,Ko=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ye{constructor(e,t){typeof e=="string"&&(e=ye.parseAttrList(e,t)),oe(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=Gd.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(Ko.lastIndex=0;(s=Ko.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=qr(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":ae.warn(`${e}: attribute ${a} is missing quotes`)}i[a]=o}return i}}const Kd="com.apple.hls.interstitial";function Vd(r){return r!=="ID"&&r!=="CLASS"&&r!=="CUE"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function Hd(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"||r==="SCTE35-CMD"}class Vo{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]){ae.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=oe(new ye({}),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?(ae.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===Kd}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 Wd=10;class Yd{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||Wd}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 Hi(r,e){return r.length===e.length?!r.some((t,s)=>t!==e[s]):!1}function Ho(r,e){return!r&&!e?!0:!r||!e?!1:Hi(r,e)}function Fs(r){return r==="AES-128"||r==="AES-256"||r==="AES-256-CTR"}function jr(r){switch(r){case"AES-128":case"AES-256":return Jt.cbc;case"AES-256-CTR":return Jt.ctr;default:throw new Error(`invalid full segment method ${r}`)}}function Xr(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function zr(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}function qd(r){const e=zr(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Wo(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 Yo(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=Xr(a)):t=qd(a)}}return t}const Wi=typeof self<"u"?self:void 0;var ve={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Pe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Yi(r){switch(r){case Pe.FAIRPLAY:return ve.FAIRPLAY;case Pe.PLAYREADY:return ve.PLAYREADY;case Pe.WIDEVINE:return ve.WIDEVINE;case Pe.CLEARKEY:return ve.CLEARKEY}}function Qr(r){switch(r){case ve.FAIRPLAY:return Pe.FAIRPLAY;case ve.PLAYREADY:return Pe.PLAYREADY;case ve.WIDEVINE:return Pe.WIDEVINE;case ve.CLEARKEY:return Pe.CLEARKEY}}function ri(r){const{drmSystems:e,widevineLicenseUrl:t}=r,s=e?[ve.FAIRPLAY,ve.WIDEVINE,ve.PLAYREADY,ve.CLEARKEY].filter(i=>!!e[i]):[];return!s[ve.WIDEVINE]&&t&&s.push(ve.WIDEVINE),s}const qo=(function(r){return Wi!=null&&(r=Wi.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function jd(r,e,t,s){let i;switch(r){case ve.FAIRPLAY:i=["cenc","sinf"];break;case ve.WIDEVINE:case ve.PLAYREADY:i=["cenc"];break;case ve.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return Xd(i,e,t,s)}function Xd(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 zd(r){var e;return!!r&&(r.sessionType==="persistent-license"||!!((e=r.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function jo(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=Xr(o).subarray(0,16);return Wo(c),c}}return null}let qi={};class ms{static clearKeyUriToKeyIdMap(){qi={}}static setKeyIdForUri(e,t){qi[e]=t}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&&!Fs(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Qa(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Hi(e.keyFormatVersions,this.keyFormatVersions)&&Ho(e.iv,this.iv)&&Ho(e.keyId,this.keyId)}isSupported(){if(this.method){if(Fs(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Pe.FAIRPLAY:case Pe.WIDEVINE:case Pe.PLAYREADY:case Pe.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(Fs(this.method)){let n=this.iv;return n||(typeof e!="number"&&(ae.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),n=Jd(e)),new ms(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){const n=qi[this.uri];if(n&&!Hi(this.keyId,n)&&ms.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=Yo(this.uri);if(s)switch(this.keyFormat){case Pe.WIDEVINE:if(this.pssh=s,!this.keyId){const n=td(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=Xo(t));break;case Pe.PLAYREADY:{const n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=ed(n,null,s),this.keyId=jo(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=Qd(t),n||(n=Xo(t),n||(n=qi[this.uri])),n&&(this.keyId=n,ms.setKeyIdForUri(this.uri,n))}return this}}function Qd(r){const e=r?.[Pe.WIDEVINE];return e?e.keyId:null}function Xo(r){const e=r?.[Pe.PLAYREADY];if(e){const t=Yo(e.uri);if(t)return jo(t)}return null}function Jd(r){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}const zo=/#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,Qo=/#EXT-X-MEDIA:(.*)/g,Zd=/^#EXT(?:INF|-X-TARGETDURATION):/m,Jr=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),ef=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 At{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 wr.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Zd.test(e)}static parseMasterPlaylist(e,t){const s=Uo(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},n=[];if(zo.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let a;for(;(a=zo.exec(e))!=null;)if(a[1]){var o;const l=new ye(a[1],i),u=qr(i,a[2]),h={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:At.resolve(u,t)},d=l.decimalResolution("RESOLUTION");d&&(h.width=d.width,h.height=d.height),tl(l.CODECS,h);const f=l["SUPPLEMENTAL-CODECS"];f&&(h.supplemental={},tl(f,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 ye(u,i),d=h["DATA-ID"];d&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[d]=h);break}case"SESSION-KEY":{const h=Zo(u,t,i);h.encrypted&&h.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(h)):ae.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const h=new ye(u,i);Go(i,h,t)}break}case"CONTENT-STEERING":{const h=new ye(u,i);i.contentSteering={uri:At.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=el(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(Qo.lastIndex=0;(i=Qo.exec(e))!==null;){const l=new ye(i[1],s),u=l.TYPE;if(u){const h=o[u],d=n[u]||[];n[u]=d;const f=l.LANGUAGE,g=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||f||"",type:u,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:f,url:l.URI?At.resolve(l.URI,t):""};if(g&&(E.assocLang=g),p&&(E.channels=p),y&&(E.characteristics=y),v&&(E.instreamId=v),h!=null&&h.length){const T=At.findGroup(h,E.groupId)||h[0];sl(E,T,"audioCodec"),sl(E,T,"textCodec")}d.push(E)}}return n}static parseLevelPlaylist(e,t,s,i,n,a){var o;const c={url:t},l=new Yd(t),u=l.fragments,h=[];let d=null,f=0,g=0,p=0,y=0,v=0,E=null,T=new Mr(i,c),S,A,D,_=-1,x=!1,I=null,L;if(Jr.lastIndex=0,l.m3u8=e,l.hasVariableRefs=Uo(e),((o=Jr.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(S=Jr.exec(e))!==null;){x&&(x=!1,T=new Mr(i,c),T.playlistOffset=p,T.setStart(p),T.sn=f,T.cc=y,v&&(T.bitrate=v),T.level=s,d&&(T.initSegment=d,d.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),I&&(T.setByteRange(I),I=null)));const G=S[1];if(G){T.duration=parseFloat(G);const U=(" "+S[2]).slice(1);T.title=U||null,T.tagList.push(U?["INF",G,U]:["INF",G])}else if(S[3]){if($(T.duration)){T.playlistOffset=p,T.setStart(p),D&&rl(T,D,l),T.sn=f,T.level=s,T.cc=y,u.push(T);const U=(" "+S[3]).slice(1);T.relurl=qr(l,U),Zr(T,E,h),E=T,p+=T.duration,f++,g=0,x=!0}}else{if(S=S[0].match(ef),!S){ae.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A<S.length&&S[A]===void 0;A++);const U=(" "+S[A]).slice(1),k=(" "+S[A+1]).slice(1),B=S[A+2]?(" "+S[A+2]).slice(1):null;switch(U){case"BYTERANGE":E?T.setByteRange(k,E):T.setByteRange(k);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=k,T.tagList.push(["PROGRAM-DATE-TIME",k]),_===-1&&(_=u.length);break;case"PLAYLIST-TYPE":l.type&&Bt(l,U,S),l.type=k.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?Bt(l,U,S):u.length>0&&nl(l,U,S),f=l.startSN=parseInt(k);break;case"SKIP":{l.skippedSegments&&Bt(l,U,S);const O=new ye(k,l),K=O.decimalInteger("SKIPPED-SEGMENTS");if($(K)){l.skippedSegments+=K;for(let M=K;M--;)u.push(null);f+=K}const W=O.enumeratedString("RECENTLY-REMOVED-DATERANGES");W&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(W.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&Bt(l,U,S),l.targetduration=Math.max(parseInt(k),1);break;case"VERSION":l.version!==null&&Bt(l,U,S),l.version=parseInt(k);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Bt(l,U,S),l.live=!1;break;case"#":(k||B)&&T.tagList.push(B?[k,B]:[k]);break;case"DISCONTINUITY":y++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([U]);break;case"BITRATE":T.tagList.push([U,k]),v=parseInt(k)*1e3,$(v)?T.bitrate=v:v=0;break;case"DATERANGE":{const O=new ye(k,l),K=new Vo(O,l.dateRanges[O.ID],l.dateRangeTagCount);l.dateRangeTagCount++,K.isValid||l.skippedSegments?l.dateRanges[K.id]=K:ae.warn(`Ignoring invalid DATERANGE tag: "${k}"`),T.tagList.push(["EXT-X-DATERANGE",k]);break}case"DEFINE":{{const O=new ye(k,l);"IMPORT"in O?Ud(l,O,a):Go(l,O,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?Bt(l,U,S):u.length>0&&nl(l,U,S),l.startCC=y=parseInt(k);break;case"KEY":{const O=Zo(k,t,l);if(O.isSupported()){if(O.method==="NONE"){D=void 0;break}D||(D={});const K=D[O.keyFormat];K!=null&&K.matches(O)||(K&&(D=oe({},D)),D[O.keyFormat]=O)}else ae.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${k}"`);break}case"START":l.startTimeOffset=el(k);break;case"MAP":{const O=new ye(k,l);if(T.duration){const K=new Mr(i,c);il(K,O,s,D),d=K,T.initSegment=d,d.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime)}else{const K=T.byteRangeEndOffset;if(K){const W=T.byteRangeStartOffset;I=`${K-W}@${W}`}else I=null;il(T,O,s,D),d=T,x=!0}d.cc=y;break}case"SERVER-CONTROL":{L&&Bt(l,U,S),L=new ye(k),l.canBlockReload=L.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=L.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&L.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=L.optionalFloat("PART-HOLD-BACK",0),l.holdBack=L.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&Bt(l,U,S);const O=new ye(k);l.partTarget=O.decimalFloatingPoint("PART-TARGET");break}case"PART":{let O=l.partList;O||(O=l.partList=[]);const K=g>0?O[O.length-1]:void 0,W=g++,M=new ye(k,l),w=new Uh(M,T,c,W,K);O.push(w),T.duration+=w.duration;break}case"PRELOAD-HINT":{const O=new ye(k,l);l.preloadHint=O;break}case"RENDITION-REPORT":{const O=new ye(k,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(O);break}default:ae.warn(`line parsed but not handled: ${S}`);break}}}E&&!E.relurl?(u.pop(),p-=E.duration,l.partList&&(l.fragmentHint=E)):l.partList&&(Zr(T,E,h),T.cc=y,l.fragmentHint=T,D&&rl(T,D,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const C=u.length,F=u[0],N=u[C-1];if(p+=l.skippedSegments*l.targetduration,p>0&&C&&N){l.averagetargetduration=p/C;const G=N.sn;l.endSN=G!=="initSegment"?G:0,l.live||(N.endList=!0),_>0&&(sf(u,_),F&&h.unshift(F))}return l.fragmentHint&&(p+=l.fragmentHint.duration),l.totalduration=p,h.length&&l.dateRangeTagCount&&F&&Jo(h,l),l.endCC=y,l}}function Jo(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=tf(e,l,r,u,i);if(h!==-1){c.tagAnchor=e.fragments[h].ref;break}}}}function tf(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 f=d;f>l;f--){const g=u[f].programDateTime;if(e>=g&&e<g+u[f].duration*1e3)return f}}return l}}}return-1}function Zo(r,e,t){var s,i;const n=new ye(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&&ae.error(`Invalid IV: ${n.IV}`);const h=o?At.resolve(o,e):"",d=(l||"1").split("/").map(Number).filter(Number.isFinite);return new ms(a,h,u,d,c,n.KEYID)}function el(r){const t=new ye(r).decimalFloatingPoint("TIME-OFFSET");return $(t)?t:null}function tl(r,e){let t=(r||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const i=t.filter(n=>$r(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 sl(r,e,t){const s=e[t];s&&(r[t]=s)}function sf(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 Zr(r,e,t){r.rawProgramDateTime?t.push(r):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime)}function il(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 rl(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 Bt(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function nl(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function en(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 al(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 f=e.sn;if(!r||f<r.startSN||f>r.endSN)return 0;let g;const p=f-r.startSN,y=r.fragments;for(y[p]=e,g=p;g>0;g--)en(y[g],y[g-1]);for(g=p;g<y.length-1;g++)en(y[g],y[g+1]);return r.fragmentHint&&en(y[y.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,d}function rf(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;of(r,e,(u,h,d,f)=>{if((!e.startCC||e.skippedSegments)&&h.cc!==u.cc){const g=u.cc-h.cc;for(let p=d;p<f.length;p++)f[p].cc+=g;e.endCC=f[f.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=nf(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&&Zr(o[h],o[h-1],u);Jo(u,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var c;const u=ul(r,e.startSN-1);e.startCC=(c=u?.cc)!=null?c:a[0].cc}af(r.partList,e.partList,(u,h)=>{h.elementaryStreams=u.elementaryStreams,h.stats=u.stats}),n?al(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,t):ll(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 nf(r,e,t){const{dateRanges:s,recentlyRemovedDateranges:i}=e,n=oe({},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 Vo(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 af(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 of(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,f=h.relurl;if(d&&lf(d,f)){e.playlistParsingError=ol(`media sequence mismatch ${h.sn}:`,r,e,u,h);return}else if(u.cc!==h.cc){e.playlistParsingError=ol(`discontinuity sequence mismatch (${u.cc}!=${h.cc})`,r,e,u,h);return}}}}function ol(r,e,t,s,i){return new Error(`${r} ${i.url}
|
|
13
13
|
Playlist starting @${e.startSN}
|
|
14
14
|
${e.m3u8}
|
|
15
15
|
|
|
16
16
|
Playlist starting @${t.startSN}
|
|
17
|
-
${t.m3u8}`)}function zo(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;jr(e,a)}function jr(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 Qo(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 Jo(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 Zo(r,e,t){return r?el(r.partList,e,t):null}function el(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 tl(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 jd(r,e){return r!==e&&e?sl(r)!==sl(e):!1}function sl(r){return r.replace(/\?[^?]*$/,"")}function js(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 qd(r,e){return!!(r&&e.startCC<r.endCC&&e.endCC>r.startCC)}function il(r,e){const t=r.start+e;r.startPTS=t,r.setStart(t),r.endPTS=t+r.duration}function rl(r,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)il(t[s],r);e.fragmentHint&&il(e.fragmentHint,r),e.alignedSliding=!0}function Xd(r,e){r&&(nl(e,r),e.alignedSliding||Oi(e,r),!e.alignedSliding&&!e.skippedSegments&&zo(r,e,!1))}function nl(r,e){if(!qd(e,r))return;const t=Math.min(e.endCC,r.endCC),s=js(e.fragments,t),i=js(r.fragments,t);if(!s||!i)return;ne.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const n=s.start-i.start;rl(n,r)}function Oi(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=js(s,a),n=js(t,a)),(!i||!n)&&(i=s[Math.floor(s.length/2)],n=js(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);rl(l,r)}function Ne(r,e,t){Ge(r,e,t),r.addEventListener(e,t)}function Ge(r,e,t){r.removeEventListener(e,t)}const zd={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 qr extends bo{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=X.bufferInfo(l||c,h,a.maxBufferHole),f=!d.len;if(this.log(`Media seeking to ${$(h)?h.toFixed(3):h}, state: ${u}, ${f?"out of":"in"} buffer`),this.state===P.ENDED)this.resetLoadingState();else if(o){const g=a.maxFragLookUpTolerance,p=o.start-g,y=o.start+o.duration+g;if(f||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 g=this.lastCurrentTime;if(h>g&&(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 ${f?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,f&&(this.startPosition=h)),f&&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 Ad(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Fr(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=X.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 X.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;Ne(s,"seeking",this.onMediaSeeking),Ne(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),Ge(i,"seeking",this.onMediaSeeking),Ge(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)===Ie.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)===Ie.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&&Ps(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,Ur(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:b.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:b.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?zd.toString(X.getBuffered(s)):"(detached)"})`),Se(e)){var i;if(e.type!==V.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 Nr(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(Se(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&&Se(e)){const d=a.partList;if(d&&i){s>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const f=this.getNextPart(d,e,s);if(f>-1){const g=d[f];e=this.fragCurrent=g.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${g.index} (${f}/${d.length-1}) of ${this.fragInfo(e,!1,g)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=g.start+g.duration,this.state=P.FRAG_LOADING;let p;return o?p=o.then(y=>!y||this.fragContextChanged(y.frag)?null:this.doFragPartsLoad(e,g,t,i)).catch(y=>this.handleFragLoadError(y)):p=this.doFragPartsLoad(e,g,t,i).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:g,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(Se(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;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 f=d.part;this.hls.trigger(m.FRAG_LOADED,d);const g=Zo(s.details,e.sn,h.index+1)||el(l,e.sn,h.index+1);if(g)u(g);else return n({frag:e,part:f,partsLoaded:c})}).catch(a)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===b.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:b.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===V.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?Zo(c,n,a):null,u=l?l.fragment:Jo(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=st(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(!X.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=X.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=X.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 X.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=V.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,f=this.hls.liveSyncPosition,g=c?(d!==-1&&d>=a?d:f)||c.start:e;this.log(`Setting startPosition to ${g} to match start frag at live edge. mainStart: ${d} liveSyncPosition: ${f} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=g}}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===Ie.OK||s===Ie.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(al(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(al(this.config)&&e.type!==V.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=hd(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=Eo(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 f;const p=e<this.lastCurrentTime||e>t-l||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:l;d=ls(n,a,e,p)}else d=a[a.length-1];if(d){const g=d.sn-s.startSN,p=this.fragmentTracker.getState(d);if((p===Ie.OK||p===Ie.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[g+1];d.sn<o&&this.fragmentTracker.getState(v)!==Ie.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){Xd(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&&Se(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===b.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,f=d&&c===Pe.RetryRequest,g=d&&!o.resolved&&l===je.MoveAllAlternatesMatchingHost,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!f&&g&&Se(i)&&!i.endList&&p&&!So(t))this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((f||g)&&u<h.maxNumRetry){var y;const v=Mr((y=t.response)==null?void 0:y.code),E=Or(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!==Pe.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${u})`);return}else c===Pe.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&&!Mr(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===V.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=X.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:qo(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;if(s.fragmentError===0&&this.treatAsGap(e,s),((o=this.transmuxer)==null?void 0:o.error)===null){const c=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(c.message),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!1,error:c,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===V.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 al(r){return!!r.interstitialsController&&r.enableInterstitialPlayback!==!1}class ol{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=Qd(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function Qd(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 Xr={exports:{}},ll;function Jd(){return ll||(ll=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 f=new i(u,h||c,d),g=t?t+l:l;return c._events[g]?c._events[g].fn?c._events[g]=[c._events[g],f]:c._events[g].push(f):(c._events[g]=f,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,f=h.length,g=new Array(f);d<f;d++)g[d]=h[d].fn;return g},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,f,g){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,f),!0;case 6:return y.fn.call(y.context,u,h,d,f,g),!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,A;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(A=1,E=new Array(v-1);A<v;A++)E[A-1]=arguments[A];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 f=t?t+l:l;if(!this._events[f])return this;if(!u)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===u&&(!d||g.once)&&(!h||g.context===h)&&a(this,f);else{for(var p=0,y=[],v=g.length;p<v;p++)(g[p].fn!==u||d&&!g[p].once||h&&g[p].context!==h)&&y.push(g[p]);y.length?this._events[f]=y.length===1?y[0]:y:a(this,f)}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})(Xr)),Xr.exports}var Zd=Jd(),zr=Lh(Zd);const qs="1.6.12",ks={};function ef(){return typeof __HLS_WORKER_BUNDLE__=="function"}function tf(){const r=ks[qs];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 ks[qs]=i,i}function sf(r){const e=ks[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 ks[r]=i,i}function rf(r){const e=ks[r||qs];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete ks[r||qs],i&&self.URL.revokeObjectURL(i),s.terminate()}}function cl(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 Qr(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 Mi(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 Xs(r,e){const t=e;let s=0;for(;Qr(r,e);){s+=10;const i=Mi(r,e+6);s+=i,cl(r,e+10)&&(s+=10),e+=s}if(s>0)return r.subarray(t,t+s)}function nf(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 f=new Error(`invalid ADTS sampling index:${a}`);r.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.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 ne.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 ul(r,e){return r[e]===255&&(r[e+1]&246)===240}function hl(r,e){return r[e+1]&1?7:9}function Jr(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function af(r,e){return e+5<r.length}function Fi(r,e){return e+1<r.length&&ul(r,e)}function of(r,e){return af(r,e)&&ul(r,e)&&Jr(r,e)<=r.length-e}function lf(r,e){if(Fi(r,e)){const t=hl(r,e);if(e+t>=r.length)return!1;const s=Jr(r,e);if(s<=t)return!1;const i=e+s;return i===r.length||Fi(r,i)}return!1}function dl(r,e,t,s,i){if(!r.samplerate){const n=nf(e,t,s,i);if(!n)return;oe(r,n)}}function fl(r){return 1024*9e4/r}function cf(r,e){const t=hl(r,e);if(e+t<=r.length){const s=Jr(r,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function gl(r,e,t,s,i){const n=fl(r.samplerate),a=s+i*n,o=cf(e,t);let c;if(o){const{frameLength:h,headerLength:d}=o,f=d+h,g=Math.max(0,t+f-e.length);g?(c=new Uint8Array(f-d),c.set(e.subarray(t+d,e.length),0)):c=e.subarray(t+d,t+f);const p={unit:c,pts:a};return g||r.samples.push(p),{sample:p,length:f,missing:g}}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 uf(r,e){return Qr(r,e)&&Mi(r,e+6)+10<=r.length-e}function hf(r){return r instanceof ArrayBuffer?r:r.byteOffset==0&&r.byteLength==r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer}function Zr(r,e=0,t=1/0){return df(r,e,t,Uint8Array)}function df(r,e,t,s){const i=ff(r);let n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);const a=gf(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 ff(r){return r instanceof ArrayBuffer?r:r.buffer}function gf(r){return r&&r.buffer instanceof ArrayBuffer&&r.byteLength!==void 0&&r.byteOffset!==void 0}function mf(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=Ye(Zr(r.data,1,s)),n=r.data[2+s],a=r.data.subarray(3+s).indexOf(0);if(a===-1)return;const o=Ye(Zr(r.data,3+s,a));let c;return i==="-->"?c=Ye(Zr(r.data,4+s+a)):c=hf(r.data.subarray(4+s+a)),e.mimeType=i,e.pictureType=n,e.description=o,e.data=c,e}function pf(r){if(r.size<2)return;const e=Ye(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}}function yf(r){if(r.size<2)return;if(r.type==="TXXX"){let t=1;const s=Ye(r.data.subarray(t),!0);t+=s.length+1;const i=Ye(r.data.subarray(t));return{key:r.type,info:s,data:i}}const e=Ye(r.data.subarray(1));return{key:r.type,info:"",data:e}}function vf(r){if(r.type==="WXXX"){if(r.size<2)return;let t=1;const s=Ye(r.data.subarray(t),!0);t+=s.length+1;const i=Ye(r.data.subarray(t));return{key:r.type,info:s,data:i}}const e=Ye(r.data);return{key:r.type,info:"",data:e}}function Ef(r){return r.type==="PRIV"?pf(r):r.type[0]==="W"?vf(r):r.type==="APIC"?mf(r):yf(r)}function Tf(r){const e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=Mi(r,4),s=10;return{type:e,size:t,data:r.subarray(s,s+t)}}const Ni=10,Sf=10;function ml(r){let e=0;const t=[];for(;Qr(r,e);){const s=Mi(r,e+6);r[e+5]>>6&1&&(e+=Ni),e+=Ni;const i=e+s;for(;e+Sf<i;){const n=Tf(r.subarray(e)),a=Ef(n);a&&t.push(a),e+=n.size+Ni}cl(r,e)&&(e+=Ni)}return t}function pl(r){return r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp"}function xf(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 en(r){const e=ml(r);for(let t=0;t<e.length;t++){const s=e[t];if(pl(s))return xf(s)}}let qe=(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 mt(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class tn{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=st(this.cachedData,e),this.cachedData=null);let s=Xs(e,0),i=s?s.length:0,n;const a=this._audioTrack,o=this._id3Track,c=s?en(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&$(c))&&(this.basePTS=Af(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:qe.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 uf(e,i)?(s=Xs(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:qe.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=st(this.cachedData,u):this.cachedData=u}}return{audioTrack:a,videoTrack:mt(),id3Track:o,textTrack:mt()}}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:mt(),id3Track:this._id3Track,textTrack:mt()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Af=(r,e,t)=>{if($(r))return r*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let $i=null;const Lf=[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],If=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],_f=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Rf=[0,1,1,4];function yl(r,e,t,s,i){if(t+24>e.length)return;const n=vl(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 vl(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=Lf[c*14+i-1]*1e3,h=If[(t===3?0:t===2?1:2)*3+n],d=o===3?1:2,f=_f[t][s],g=Rf[s],p=f*8*g,y=Math.floor(f*l/h+a)*g;if($i===null){const T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);$i=T?parseInt(T[1]):0}return!!$i&&$i<=87&&s===2&&l>=224e3&&o===0&&(r[e+3]=r[e+3]|128),{sampleRate:h,channelCount:d,frameLength:y,samplesPerFrame:p}}}function sn(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function El(r,e){return e+1<r.length&&sn(r,e)}function bf(r,e){return sn(r,e)&&4<=r.length-e}function Tl(r,e){if(e+1<r.length&&sn(r,e)){const s=vl(r,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const n=e+i;return n===r.length||El(r,n)}return!1}class Df extends tn{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=Xs(e,0);let i=s?.length||0;if(Tl(e,i))return!1;for(let n=e.length;i<n;i++)if(lf(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return of(e,t)}appendFrame(e,t,s){dl(e,this.observer,t,s,e.manifestCodec);const i=gl(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const Sl=(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 Cf extends tn{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=xl(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=Xs(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&en(t)!==void 0&&Sl(e,s)<16}}function xl(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 f=(e[t+6]<<8|e[t+7])>>12-d&1,p=[2,1,2,3,3,4,4,5][h]+f,y=e[t+5]>>3,v=e[t+5]&7,E=new Uint8Array([n<<6|y<<1|v>>2,(v&3)<<6|h<<3|f<<2|c>>4,c<<4&224]),T=1536/o*9e4,S=s+i*T,A=e.subarray(t,t+u);return r.config=E,r.channelCount=p,r.samplerate=o,r.samples.push({unit:A,pts:S}),u}class Pf extends tn{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=Xs(e,0);let s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&en(t)!==void 0&&Sl(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(Tl(e,s))return ne.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return bf(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return yl(e,t,s,this.basePTS,this.frameIndex)}}const kf=/\/emsg[-/]ID3/i;class wf{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=mt("video",1),a=this.audioTrack=mt("audio",1),o=this.txtTrack=mt("text",1);if(this.id3Track=mt("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=Ja(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=qa.text,n.sampleDuration=0,n.duration=a.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return Dh(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=st(this.remainderData,e));const o=Mh(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const a=this.extractID3Track(i,t);return n.samples=eo(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=eo(e,t),{videoTrack:t,audioTrack:mt(),id3Track:i,textTrack:mt()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=J(e.samples,["emsg"]);i&&i.forEach(n=>{const a=Nh(n);if(kf.test(a.schemeIdUri)){const o=Al(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:qe.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=Al(a,t);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:qe.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 Al(r,e){return $(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale}class Of{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Fr(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Vt.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=to(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 Ll{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,f=0;for(n===-1&&(d=0,f=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 g={data:t.subarray(d,u),type:f};o.push(g)}else{const g=this.getLastNalUnit(e.samples);g&&(a&&c<=4-a&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-a)),u>0&&(g.data=st(g.data,t.subarray(0,u)),g.state=0))}c<i?(h=this.getNALuType(t,c),d=c,f=h,n=0):n=-1}else n=0}if(d>=0&&n>=0){const g={data:t.subarray(d,i),type:f,state:n};o.push(g)}if(o.length===0){const g=this.getLastNalUnit(e.samples);g&&(g.data=st(g.data,t))}return e.naluState=n,o}}class zs{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&&ne.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 Mf extends Ll{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,br(l.data,1,s.pts,t.samples);break}case 7:{var f,g;o=!0,c=!0;const p=l.data,y=this.readSPS(p);if(!e.sps||e.width!==y.width||e.height!==y.height||((f=e.pixelRatio)==null?void 0:f[0])!==y.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[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 zs(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 zs(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),f=t.readBoolean.bind(t),g=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),g(3),u(),y(),E===100||E===110||E===122||E===244||E===44||E===83||E===86||E===118||E===128){const x=d();if(x===3&&g(1),y(),y(),g(1),f())for(c=x!==3?8:12,l=0;l<c;l++)f()&&(l<6?v(16,t):v(64,t))}y();const T=d();if(T===0)d();else if(T===1)for(g(1),p(),p(),o=d(),l=0;l<o;l++)p();y(),g(1);const S=d(),A=d(),D=h(1);D===0&&g(1),g(1),f()&&(s=d(),i=d(),n=d(),a=d());let L=[1,1];if(f()&&f())switch(u()){case 1:L=[1,1];break;case 2:L=[12,11];break;case 3:L=[10,11];break;case 4:L=[16,11];break;case 5:L=[40,33];break;case 6:L=[24,11];break;case 7:L=[20,11];break;case 8:L=[32,11];break;case 9:L=[80,33];break;case 10:L=[18,11];break;case 11:L=[15,11];break;case 12:L=[64,33];break;case 13:L=[160,99];break;case 14:L=[4,3];break;case 15:L=[3,2];break;case 16:L=[2,1];break;case 255:{L=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((S+1)*16-s*2-i*2),height:(2-D)*(A+1)*16-(D?2:4)*(n+a),pixelRatio:L}}}class Ff extends Ll{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,br(l.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=oe(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 f=this.readSPS(l.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const g in f.params)e.params[g]=f.params[g]}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 f=this.readPPS(l.data);for(const g in f)e.params[g]=f[g]}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 zs(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 zs(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(),f=t.readUByte(),g=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 A=t.readUEG(),D=t.readUEG(),L=t.readBoolean();let x=0,I=0,_=0,C=0;L&&(x+=t.readUEG(),I+=t.readUEG(),_+=t.readUEG(),C+=t.readUEG());const F=t.readUEG(),N=t.readUEG(),U=t.readUEG(),B=t.readBoolean();for(let ie=B?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 we=0;we<4;we++)for(let nt=0;nt<(we===3?2:6);nt++)if(!t.readBoolean())t.readUEG();else{const lt=Math.min(64,1<<4+(we<<1));we>1&&t.readEG();for(let Bs=0;Bs<lt;Bs++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const O=t.readUEG();let K=0;for(let ie=0;ie<O;ie++){let we=!1;if(ie!==0&&(we=t.readBoolean()),we){ie===O&&t.readUEG(),t.readBoolean(),t.readUEG();let nt=0;for(let hs=0;hs<=K;hs++){const lt=t.readBoolean();let Bs=!1;lt||(Bs=t.readBoolean()),(lt||Bs)&&nt++}K=nt}else{const nt=t.readUEG(),hs=t.readUEG();K=nt+hs;for(let lt=0;lt<nt;lt++)t.readUEG(),t.readBoolean();for(let lt=0;lt<hs;lt++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const ie=t.readUEG();for(let we=0;we<ie;we++){for(let nt=0;nt<U+4;nt++)t.readBits(1);t.readBits(1)}}let M=0,k=1,Y=1,Z=!0,q=1,z=0;t.readBoolean(),t.readBoolean();let me=!1;if(t.readBoolean()){if(t.readBoolean()){const ds=t.readUByte(),qc=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],tr=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];ds>0&&ds<16?(k=qc[ds-1],Y=tr[ds-1]):ds===255&&(k=t.readBits(16),Y=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(),me=t.readBoolean(),me&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(q=t.readBits(32),z=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const tr=t.readBoolean(),Xc=t.readBoolean();let si=!1;(tr||Xc)&&(si=t.readBoolean(),si&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),si&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let zc=0;zc<=s;zc++){Z=t.readBoolean();const I0=Z||t.readBoolean();let Qc=!1;I0?t.readEG():Qc=t.readBoolean();const Jc=Qc?1:t.readUEG()+1;if(tr)for(let ii=0;ii<Jc;ii++)t.readUEG(),t.readUEG(),si&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Xc)for(let ii=0;ii<Jc;ii++)t.readUEG(),t.readUEG(),si&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),M=t.readUEG())}let Ae=A,Re=D;if(L){let ie=1,we=1;S===1?ie=we=2:S==2&&(ie=2),Ae=A-ie*I-ie*x,Re=D-we*C-we*_}const $e=i?["A","B","C"][i]:"",Dt=o<<24|c<<16|l<<8|u;let ke=0;for(let ie=0;ie<32;ie++)ke=(ke|(Dt>>ie&1)<<31-ie)>>>0;let Ct=ke.toString(16);return a===1&&Ct==="2"&&(Ct="6"),{codecString:`hvc1.${$e}${a}.${Ct}.${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,f,g,p,y],general_level_idc:v,bit_depth:F+8,bit_depth_luma_minus8:F,bit_depth_chroma_minus8:N,min_spatial_segmentation_idc:M,chroma_format_idc:S,frame_rate:{fixed:Z,fps:z/q}},width:Ae,height:Re,pixelRatio:[k,Y]}}readPPS(e){const t=new zs(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 _e=188;class Ht{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=Ht.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(_e*5,t-_e)+1,i=0;for(;i<s;){let n=!1,a=-1,o=0;for(let c=i;c<t;c+=_e)if(e[c]===71&&(t-c===_e||e[c+_e]===71)){if(o++,a===-1&&(a=c,a!==0&&(s=Math.min(a+_e*99,e.length-_e)+1)),n||(n=rn(e,c)===0),n&&o>1&&(a===0&&o>2||c+_e>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:qa[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=Ht.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=Ht.createTrack("audio",i),this._id3Track=Ht.createTrack("id3"),this._txtTrack=Ht.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,f=c.pid,g=o.pesData,p=c.pesData,y=null,v=this.pmtParsed,E=this._pmtId,T=e.length;if(this.remainderData&&(e=st(this.remainderData,e),T=e.length,this.remainderData=null),T<_e&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};const S=Math.max(0,Ht.syncOffset(e));T-=(T-S)%_e,T<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,T,e.buffer.byteLength-T));let A=0;for(let L=S;L<T;L+=_e)if(e[L]===71){const x=!!(e[L+1]&64),I=rn(e,L),_=(e[L+3]&48)>>4;let C;if(_>1){if(C=L+5+e[L+4],C===L+_e)continue}else C=L+4;switch(I){case u:x&&(h&&(n=ws(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,L+_e)),h.size+=L+_e-C);break;case d:if(x){if(g&&(n=ws(g,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}g={data:[],size:0}}g&&(g.data.push(e.subarray(C,L+_e)),g.size+=L+_e-C);break;case f:x&&(p&&(n=ws(p,this.logger))&&this.parseID3PES(c,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(C,L+_e)),p.size+=L+_e-C);break;case 0:x&&(C+=e[C]+1),E=this._pmtId=Nf(e,C);break;case E:{x&&(C+=e[C]+1);const F=$f(e,C,this.typeSupported,s,this.observer,this.logger);u=F.videoPid,u>0&&(a.pid=u,a.segmentCodec=F.segmentVideoCodec),d=F.audioPid,d>0&&(o.pid=d,o.segmentCodec=F.segmentAudioCodec),f=F.id3Pid,f>0&&(c.pid=f),y!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${L} after unknown PID '${y}'. Backtracking to sync byte @${S} to parse all TS packets.`),y=null,L=S-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=I;break}}else A++;A>0&&nn(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=h,o.pesData=g,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=ws(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=ws(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=ws(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 Of(this.observer,this.config,t);return this.decrypt(i,n)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Mf:e==="hevc"&&(this.videoParser=new Ff))}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=st(i.sample.unit,n);else{const f=d-h;i.sample.unit.set(n.subarray(0,h),f),e.samples.push(i.sample),s=i.missing}}let a,o;for(a=s,o=n.length;a<o-1&&!Fi(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",nn(this.observer,new Error(h),d,this.logger),!d)return}dl(e,this.observer,n,a,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){const h=fl(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=gl(e,n,a,c,l),a+=u.length,u.missing){this.aacOverFlow=u;break}else for(l++;a<o-1&&!Fi(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(El(s,a)){const c=yl(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=xl(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=oe({},t,{type:this._videoTrack?qe.emsg:qe.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function rn(r,e){return((r[e+1]&31)<<8)+r[e+2]}function Nf(r,e){return(r[e+10]&31)<<8|r[e+11]}function $f(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=rn(r,e),h=(r[e+3]&15)<<8|r[e+4];switch(r[e]){case 207:if(!s){an("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){an("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){an("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,f=h;for(;f>2;){switch(r[d]){case 106:t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=u,a.segmentAudioCodec="ac3");break}const p=r[d+1]+2;d+=p,f-=p}}break;case 194:case 135:return nn(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 nn(r,e,t,s){s.warn(`parsing error: ${e.message}`),r.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function an(r,e){e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function ws(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]=st(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 f=0,g=c.length;f<g;f++){s=c[f];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 Bf{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 Wt=Math.pow(2,32)-1;class R{static init(){R.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 R.types)R.types.hasOwnProperty(e)&&(R.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]);R.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]);R.STTS=R.STSC=R.STCO=n,R.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),R.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),R.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),R.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]);R.FTYP=R.box(R.types.ftyp,a,c,a,o),R.DINF=R.box(R.types.dinf,R.box(R.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 R.box(R.types.hdlr,R.HDLR_TYPES[e])}static mdat(e){return R.box(R.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(Wt+1)),i=Math.floor(t%(Wt+1));return R.box(R.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 R.box(R.types.mdia,R.mdhd(e.timescale||0,e.duration||0),R.hdlr(e.type),R.minf(e))}static mfhd(e){return R.box(R.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"?R.box(R.types.minf,R.box(R.types.smhd,R.SMHD),R.DINF,R.stbl(e)):R.box(R.types.minf,R.box(R.types.vmhd,R.VMHD),R.DINF,R.stbl(e))}static moof(e,t,s){return R.box(R.types.moof,R.mfhd(e),R.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=R.trak(e[t]);return R.box.apply(null,[R.types.moov,R.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(R.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=R.trex(e[t]);return R.box.apply(null,[R.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(Wt+1)),i=Math.floor(t%(Wt+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 R.box(R.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 R.box(R.types.sdtp,s)}static stbl(e){return R.box(R.types.stbl,R.stsd(e),R.box(R.types.stts,R.STTS),R.box(R.types.stsc,R.STSC),R.box(R.types.stsz,R.STSZ),R.box(R.types.stco,R.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=R.box(R.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 R.box(R.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,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.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 R.box(R.types.mp4a,R.audioStsd(e),R.box(R.types.esds,R.esds(e)))}static mp3(e){return R.box(R.types[".mp3"],R.audioStsd(e))}static ac3(e){return R.box(R.types["ac-3"],R.audioStsd(e),R.box(R.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return R.box(R.types.stsd,R.STSD,R.mp4a(e));if(t==="ac3"&&e.config)return R.box(R.types.stsd,R.STSD,R.ac3(e));if(t==="mp3"&&e.codec==="mp3")return R.box(R.types.stsd,R.STSD,R.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return R.box(R.types.stsd,R.STSD,R.avc1(e));if(t==="hevc"&&e.vps)return R.box(R.types.stsd,R.STSD,R.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/(Wt+1)),o=Math.floor(s%(Wt+1));return R.box(R.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=R.sdtp(e),i=e.id,n=Math.floor(t/(Wt+1)),a=Math.floor(t%(Wt+1));return R.box(R.types.traf,R.box(R.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),R.box(R.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])),R.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,R.box(R.types.trak,R.tkhd(e),R.mdia(e))}static trex(e){const t=e.id;return R.box(R.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 R.box(R.types.trun,a)}static initSegment(e){R.types||R.init();const t=R.moov(e);return st(R.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 g=0;g<s.length;g+=1){a+=3;for(let p=0;p<s[g].length;p+=1)a+=2+s[g][p].length}const o=new Uint8Array(a);o.set(n,0),a=n.length;const c=s.length-1;for(let g=0;g<s.length;g+=1){o.set(new Uint8Array([32+g|(g===c?128:0),0,s[g].length]),a),a+=3;for(let p=0;p<s[g].length;p+=1)o.set(new Uint8Array([s[g][p].length>>8,s[g][p].length&255]),a),a+=2,o.set(s[g][p],a),a+=s[g][p].length}const l=R.box(R.types.hvcC,o),u=e.width,h=e.height,d=e.pixelRatio[0],f=e.pixelRatio[1];return R.box(R.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,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}}R.types=void 0,R.HDLR_TYPES=void 0,R.STTS=void 0,R.STSC=void 0,R.STCO=void 0,R.STSZ=void 0,R.VMHD=void 0,R.SMHD=void 0,R.STSD=void 0,R.FTYP=void 0,R.DINF=void 0;const Il=9e4;function on(r,e,t=1,s=!1){const i=r*e*t;return s?Math.round(i):i}function Uf(r,e,t=1,s=!1){return on(r,e,1/t,s)}function Qs(r,e=!1){return on(r,1e3,1/Il,e)}function Gf(r,e=1){return on(r,Il,1/e)}const Kf=10*1e3,Vf=1024,Hf=1152,Wf=1536;let Os=null,ln=null;function _l(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 Bi extends tt{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,Os===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Os=a?parseInt(a[1]):0}if(ln===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);ln=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){this.log("initPTS & initDTS reset"),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=it(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,f,g,p=n,y=n;const v=e.pid>-1,E=t.pid>-1,T=t.samples.length,S=e.samples.length>0,A=o&&T>0||T>1;if((!v||S)&&(!E||A)||this.ISGenerated||o){if(this.ISGenerated){var L,x,I,_;const U=this.videoTrackConfig;(U&&(t.width!==U.width||t.height!==U.height||((L=t.pixelRatio)==null?void 0:L[0])!==((x=U.pixelRatio)==null?void 0:x[0])||((I=t.pixelRatio)==null?void 0:I[1])!==((_=U.pixelRatio)==null?void 0:_[1]))||!U&&A||this.nextAudioTs===null&&S)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,n,a));const C=this.isVideoContiguous;let F=-1,N;if(A&&(F=Yf(t.samples),!C&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,F>0){this.warn(`Dropped ${F} out of ${T} video samples due to a missing keyframe`);const U=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(F),t.dropped+=F,y+=(t.samples[0].pts-U)/t.inputTimeScale,N=y}else F===-1&&(this.warn(`No keyframe found out of ${T} video samples`),g=!1);if(this.ISGenerated){if(S&&A){const U=this.getVideoStartPts(t.samples),w=(it(e.samples[0].pts,U)-U)/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||A||c===V.AUDIO?y:void 0),A){const U=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,U)}}else A&&(l=this.remuxVideo(t,y,C,0));l&&(l.firstKeyFrame=F,l.independent=F!==-1,l.firstKeyFramePTS=N)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=Rl(s,n,this._initPTS,this._initDTS)),i.samples.length&&(d=bl(i,n,this._initPTS))),{audio:u,video:l,initSegment:h,independent:g,text:d,id3:f}}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,f,g,p=-1;if(u&&(d=f=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):R.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(p=e.id,g=e.inputTimeScale,!l||g!==l.timescale?d=f=n[0].pts-Math.round(g*s):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:R.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(p=t.id,g=t.inputTimeScale,!l||g!==l.timescale){const y=this.getVideoStartPts(a),v=Math.round(g*s);f=Math.min(f,it(a[0].dts,y)-v),d=Math.min(d,y-v)}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/g} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/g} (${d}/${g}) trackId: ${p}`),this._initPTS={baseTime:d,timescale:g,trackId:p},this._initDTS={baseTime:f,timescale:g,trackId:p}):d=g=void 0,{tracks:c,initPTS:d,timescale:g,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,f=this.videoSampleDuration,g,p,y=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,E=!1;if(!s||h===null){const M=u+t*n,k=a[0].pts-it(a[0].dts,a[0].pts);Os&&h!==null&&Math.abs(M-k-(h+u))<15e3?s=!0:h=M-k-u}const T=h+u;for(let M=0;M<c;M++){const k=a[M];k.pts=it(k.pts,T),k.dts=it(k.dts,T),k.dts<a[M>0?M-1:M].dts&&(E=!0)}E&&a.sort(function(M,k){const Y=M.dts-k.dts,Z=M.pts-k.pts;return Y||Z}),g=a[0].dts,p=a[a.length-1].dts;const S=p-g,A=S?Math.round(S/(c-1)):f||e.inputTimeScale/30;if(s){const M=g-T,k=M>A,Y=M<-1;if((k||Y)&&(k?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Qs(M,!0)} ms (${M}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Qs(-M,!0)} ms (${M}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!Y||T>=a[0].pts||Os)){g=T;const Z=a[0].pts-M;if(k)a[0].dts=g,a[0].pts=Z;else{let q=!0;for(let z=0;z<a.length&&!(a[z].dts>Z&&q);z++){const me=a[z].pts;if(a[z].dts-=M,a[z].pts-=M,z<a.length-1){const ue=a[z+1].pts,Ae=a[z].pts,Re=ue<=Ae,$e=ue<=me;q=Re==$e}}}this.log(`Video: Initial PTS/DTS adjusted: ${Qs(Z,!0)}/${Qs(g,!0)}, delta: ${Qs(M,!0)} ms`)}}g=Math.max(0,g);let D=0,L=0,x=g;for(let M=0;M<c;M++){const k=a[M],Y=k.units,Z=Y.length;let q=0;for(let z=0;z<Z;z++)q+=Y[z].data.length;L+=q,D+=Z,k.length=q,k.dts<x?(k.dts=x,x+=A/4|0||1):x=k.dts,y=Math.min(k.pts,y),v=Math.max(k.pts,v)}p=a[c-1].dts;const I=L+4*D+8;let _;try{_=new Uint8Array(I)}catch(M){this.observer.emit(m.ERROR,m.ERROR,{type:H.MUX_ERROR,details:b.REMUX_ALLOC_ERROR,fatal:!1,error:M,bytes:I,reason:`fail allocating video mdat ${I}`});return}const C=new DataView(_.buffer);C.setUint32(0,I),_.set(R.types.mdat,4);let F=!1,N=Number.POSITIVE_INFINITY,U=Number.POSITIVE_INFINITY,B=Number.NEGATIVE_INFINITY,w=Number.NEGATIVE_INFINITY;for(let M=0;M<c;M++){const k=a[M],Y=k.units;let Z=0;for(let me=0,ue=Y.length;me<ue;me++){const Ae=Y[me],Re=Ae.data,$e=Ae.data.byteLength;C.setUint32(d,$e),d+=4,_.set(Re,d),d+=$e,Z+=4+$e}let q;if(M<c-1)f=a[M+1].dts-k.dts,q=a[M+1].pts-k.pts;else{const me=this.config,ue=M>0?k.dts-a[M-1].dts:A;if(q=M>0?k.pts-a[M-1].pts:A,me.stretchShortVideoTrack&&this.nextAudioTs!==null){const Ae=Math.floor(me.maxBufferHole*n),Re=(i?y+i*n:this.nextAudioTs+u)-k.pts;Re>Ae?(f=Re-ue,f<0?f=ue:F=!0,this.log(`It is approximately ${Re/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=ue}else f=ue}const z=Math.round(k.pts-k.dts);N=Math.min(N,f),B=Math.max(B,f),U=Math.min(U,q),w=Math.max(w,q),o.push(_l(k.key,f,Z,z))}if(o.length){if(Os){if(Os<70){const M=o[0].flags;M.dependsOn=2,M.isNonSync=0}}else if(ln&&w-U<B-N&&A/B<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let M=g;for(let k=0,Y=o.length;k<Y;k++){const Z=M+o[k].duration,q=M+o[k].cts;if(k<Y-1){const z=Z+o[k+1].cts;o[k].duration=z-q}else o[k].duration=k?o[k-1].duration:A;o[k].cts=0,M=Z}}}f=F||!f?A:f;const G=p+f;this.nextVideoTs=h=G-u,this.videoSampleDuration=f,this.isVideoContiguous=!0;const W={data1:R.moof(e.sequenceNumber++,g,oe(e,{samples:o})),data2:_,startPTS:(y-u)/n,endPTS:(v+f-u)/n,startDTS:(g-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 Hf;case"ac3":return Wf;default:return Vf}}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,f=[],g=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(it(p[0].pts,T)-(v+E))<20*u),p.forEach(function(w){w.pts=it(w.pts,T)}),!s||v<0){if(p=p.filter(w=>w.pts>=0),!p.length)return;n===0?v=0:i&&!g?v=Math.max(0,T-E):v=p[0].pts-E}if(e.segmentCodec==="aac"){const w=this.config.maxAudioFramesDrift;for(let G=0,O=v+E;G<p.length;G++){const K=p[G],W=K.pts,M=W-O,k=Math.abs(1e3*M/a);if(M<=-w*u&&g)G===0&&(this.warn(`Audio frame @ ${(W/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*M/a)} ms.`),this.nextAudioTs=v=W-E,O=W);else if(M>=w*u&&k<Kf&&g){let Y=Math.round(M/u);for(O=W-Y*u;O<0&&Y&&u;)Y--,O+=u;G===0&&(this.nextAudioTs=v=O-E),this.warn(`Injecting ${Y} audio frames @ ${((O-E)/a).toFixed(3)}s due to ${Math.round(1e3*M/a)} ms gap.`);for(let Z=0;Z<Y;Z++){let q=Bf.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);q||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),q=K.unit.subarray()),p.splice(G,0,{unit:q,pts:O}),O+=u,G++}}K.pts=O,O+=u}}let S=null,A=null,D,L=0,x=p.length;for(;x--;)L+=p[x].unit.byteLength;for(let w=0,G=p.length;w<G;w++){const O=p[w],K=O.unit;let W=O.pts;if(A!==null){const k=f[w-1];k.duration=Math.round((W-A)/c)}else if(s&&e.segmentCodec==="aac"&&(W=v+E),S=W,L>0){L+=y;try{D=new Uint8Array(L)}catch(k){this.observer.emit(m.ERROR,m.ERROR,{type:H.MUX_ERROR,details:b.REMUX_ALLOC_ERROR,fatal:!1,error:k,bytes:L,reason:`fail allocating audio mdat ${L}`});return}d||(new DataView(D.buffer).setUint32(0,L),D.set(R.types.mdat,4))}else return;D.set(K,y);const M=K.byteLength;y+=M,f.push(_l(!0,l,M,0)),A=W}const I=f.length;if(!I)return;const _=f[f.length-1];v=A-E,this.nextAudioTs=v+c*_.duration;const C=d?new Uint8Array(0):R.moof(e.sequenceNumber++,S/c,oe({},e,{samples:f}));e.samples=[];const F=(S-E)/a,N=v/a,B={data1:C,data2:D,startPTS:F,endPTS:N,startDTS:F,endDTS:N,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,B}}function it(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 Yf(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function Rl(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=it(c.pts-t.baseTime*n/t.timescale,e*n)/n,c.dts=it(c.dts-s.baseTime*n/s.timescale,e*n)/n}const a=r.samples;return r.samples=[],{samples:a}}function bl(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=it(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 jf extends tt{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=Ja(e);if(t)wh(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=Dl(n,le.AUDIO,this)),a&&(i=Dl(a,le.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 f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(d),g=this.initData),!((c=g)!=null&&c.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const p=Oh(d,g,this),y=g.audio?p[g.audio.id]:null,v=g.video?p[g.video.id]:null,E=Ui(v,1/0),T=Ui(y,1/0),S=Ui(v,0,!0),A=Ui(y,0,!0);let D=n,L=0;const x=y&&(!v||!l&&T<E||l&&l.trackId===g.audio.id),I=x?y:v;if(I){const O=I.timescale,K=I.start-n*O,W=x?g.audio.id:g.video.id;D=I.start/O,L=x?A-T:S-E,(a||!l)&&(qf(l,D,n,L)||O!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${K/O} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${D-n} (${K}/${O}) trackId: ${W}`),l=null,f.initPTS=K,f.timescale=O,f.trackId=W)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);l?(f.initPTS=l.baseTime,f.timescale=l.timescale,f.trackId=l.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=D,f.timescale=1,f.trackId=-1),this.initPTS=l={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const _=D-l.baseTime/l.timescale,C=_+L;L>0?this.lastEndTime=C:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const F=!!g.audio,N=!!g.video;let U="";F&&(U+="audio"),N&&(U+="video");const B=(g.audio?g.audio.encrypted:!1)||(g.video?g.video.encrypted:!1),w={data1:d,startPTS:_,startDTS:_,endPTS:C,endDTS:C,type:U,hasAudio:F,hasVideo:N,nb:1,dropped:0,encrypted:B};h.audio=F&&!N?w:void 0,h.video=N?w:void 0;const G=v?.sampleCount;if(G){const O=v.keyFrameIndex,K=O!==-1;w.nb=G,w.dropped=O===0||this.isVideoContiguous?0:K?O:G,w.independent=K,w.firstKeyFrame=O,K&&v.keyFrameStart&&(w.firstKeyFramePTS=(v.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(h.independent=K),this.isVideoContiguous||(this.isVideoContiguous=K),w.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${O}/${G} dropped: ${w.dropped} start: ${w.firstKeyFramePTS||"NA"}`)}return h.initSegment=f,h.id3=Rl(s,n,l,l),i.samples.length&&(h.text=bl(i,n,l)),h}}function Ui(r,e,t=!1){return r?.start!==void 0?(r.start+(t?r.duration:0))/r.timescale:e}function qf(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 Dl(r,e,t){const s=r.codec;return s&&s.length>4?s:e===le.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?xi(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 Rt;try{Rt=self.performance.now.bind(self.performance)}catch{Rt=Date.now}const Gi=[{demux:wf,remux:jf},{demux:Ht,remux:Bi},{demux:Df,remux:Bi},{demux:Pf,remux:Bi}];Gi.splice(2,0,{demux:Cf,remux:Bi});class Cl{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=Rt();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:f,initSegmentChange:g}=i||o,{audioCodec:p,videoCodec:y,defaultInitPts:v,duration:E,initSegmentData:T}=c,S=Xf(a,t);if(S&&Ps(S.method)){const x=this.getDecrypter(),I=Ur(S.method);if(x.isSync()){let _=x.softwareDecrypt(a,S.key.buffer,S.iv.buffer,I);if(s.part>-1){const F=x.flush();_=F&&F.buffer}if(!_)return n.executeEnd=Rt(),cn(s);a=new Uint8Array(_)}else return this.asyncResult=!0,this.decryptionPromise=x.webCryptoDecrypt(a,S.key.buffer,S.iv.buffer,I).then(_=>{const C=this.push(_,null,s);return this.decryptionPromise=null,C}),this.decryptionPromise}const A=this.needsProbing(u,h);if(A){const x=this.configureTransmuxer(a);if(x)return this.logger.warn(`[transmuxer] ${x.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!1,error:x,reason:x.message}),n.executeEnd=Rt(),cn(s)}(u||h||g||A)&&this.resetInitSegment(T,p,y,E,t),(u||g||A)&&this.resetInitialTimestamp(v),l||this.resetContiguity();const D=this.transmux(a,S,f,d,s);this.asyncResult=Js(D);const L=this.currentTransmuxState;return L.contiguous=!0,L.discontinuity=!1,L.trackSwitch=!1,n.executeEnd=Rt(),D}flush(e){const t=e.transmuxing;t.executeStart=Rt();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=Rt();const h=[cn(e)];return this.asyncResult?Promise.resolve(h):h}const u=c.flush(o);return Js(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===V.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=Rt()}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=Gi.length;h<d;h++){var a;if((a=Gi[h].demux)!=null&&a.probe(e,this.logger)){n=Gi[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 Fr(this.config)),e}}function Xf(r,e){let t=null;return r.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const cn=r=>({remuxResult:{},chunkMeta:r});function Js(r){return"then"in r&&r.then instanceof Function}class zf{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 Qf{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 Pl=0;class kl{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Pl++,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:b.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 zr,this.observer.on(m.FRAG_DECRYPTED,a),this.observer.on(m.ERROR,a);const o=no(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(n.workerPath||ef()){try{n.workerPath?(c.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=sf(n.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=tf());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:ce(n)})}catch(u){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new Cl(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new Cl(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Pl++;const t=this.hls.config,s=no(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:ce(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),rf(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:f,transmuxer:g}=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,A=this.part?l.part-this.part.index:-1,D=S===0&&l.id>1&&l.id===v?.stats.chunkCount,L=!T&&(S===1||S===0&&(A===1||D&&A<=0)),x=self.performance.now();(T||S||n.stats.parsing.start===0)&&(n.stats.parsing.start=x),a&&(A||!L)&&(a.stats.parsing.start=x);const I=!(v&&((h=n.initSegment)==null?void 0:h.url)===((d=v.initSegment)==null?void 0:d.url)),_=new Qf(E,L,c,T,p,I);if(!L||E||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===V.MAIN?"level":"track"}: ${l.level} id: ${l.id}
|
|
17
|
+
${t.m3u8}`)}function ll(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;tn(e,a)}function tn(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 cl(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 ul(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 hl(r,e,t){return r?dl(r.partList,e,t):null}function dl(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 fl(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 lf(r,e){return r!==e&&e?gl(r)!==gl(e):!1}function gl(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 cf(r,e){return!!(r&&e.startCC<r.endCC&&e.endCC>r.startCC)}function ml(r,e){const t=r.start+e;r.startPTS=t,r.setStart(t),r.endPTS=t+r.duration}function pl(r,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)ml(t[s],r);e.fragmentHint&&ml(e.fragmentHint,r),e.alignedSliding=!0}function uf(r,e){r&&(yl(e,r),e.alignedSliding||ji(e,r),!e.alignedSliding&&!e.skippedSegments&&ll(r,e,!1))}function yl(r,e){if(!cf(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;ae.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const n=s.start-i.start;pl(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);pl(l,r)}function Ue(r,e,t){Ye(r,e,t),r.addEventListener(e,t)}function Ye(r,e,t){r.removeEventListener(e,t)}const hf={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 sn extends No{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=X.bufferInfo(l||c,h,a.maxBufferHole),f=!d.len;if(this.log(`Media seeking to ${$(h)?h.toFixed(3):h}, state: ${u}, ${f?"out of":"in"} buffer`),this.state===P.ENDED)this.resetLoadingState();else if(o){const g=a.maxFragLookUpTolerance,p=o.start-g,y=o.start+o.duration+g;if(f||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 g=this.lastCurrentTime;if(h>g&&(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 ${f?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,f&&(this.startPosition=h)),f&&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 $d(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Wr(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=X.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 X.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),Ye(i,"seeking",this.onMediaSeeking),Ye(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&&Fs(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,jr(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:b.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:b.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?hf.toString(X.getBuffered(s)):"(detached)"})`),xe(e)){var i;if(e.type!==V.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 Yr(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 f=this.getNextPart(d,e,s);if(f>-1){const g=d[f];e=this.fragCurrent=g.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${g.index} (${f}/${d.length-1}) of ${this.fragInfo(e,!1,g)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=g.start+g.duration,this.state=P.FRAG_LOADING;let p;return o?p=o.then(y=>!y||this.fragContextChanged(y.frag)?null:this.doFragPartsLoad(e,g,t,i)).catch(y=>this.handleFragLoadError(y)):p=this.doFragPartsLoad(e,g,t,i).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:g,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;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 f=d.part;this.hls.trigger(m.FRAG_LOADED,d);const g=hl(s.details,e.sn,h.index+1)||dl(l,e.sn,h.index+1);if(g)u(g);else return n({frag:e,part:f,partsLoaded:c})}).catch(a)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===b.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:b.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===V.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?hl(c,n,a):null,u=l?l.fragment:ul(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(!X.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=X.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=X.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 X.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=V.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,f=this.hls.liveSyncPosition,g=c?(d!==-1&&d>=a?d:f)||c.start:e;this.log(`Setting startPosition to ${g} to match start frag at live edge. mainStart: ${d} liveSyncPosition: ${f} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=g}}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(vl(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(vl(this.config)&&e.type!==V.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=Ld(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=bo(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 f;const p=e<this.lastCurrentTime||e>t-l||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:l;d=gs(n,a,e,p)}else d=a[a.length-1];if(d){const g=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[g+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){uf(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===b.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,f=d&&c===Ce.RetryRequest,g=d&&!o.resolved&&l===Je.MoveAllAlternatesMatchingHost,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!f&&g&&xe(i)&&!i.endList&&p&&!Co(t))this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((f||g)&&u<h.maxNumRetry){var y;const v=Hr((y=t.response)==null?void 0:y.code),E=Vr(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!==Ce.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${u})`);return}else c===Ce.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&&!Hr(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===V.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=X.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:al(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;if(s.fragmentError===0&&this.treatAsGap(e,s),((o=this.transmuxer)==null?void 0:o.error)===null){const c=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(c.message),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!1,error:c,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===V.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 vl(r){return!!r.interstitialsController&&r.enableInterstitialPlayback!==!1}class El{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=df(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function df(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 rn={exports:{}},Tl;function ff(){return Tl||(Tl=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 f=new i(u,h||c,d),g=t?t+l:l;return c._events[g]?c._events[g].fn?c._events[g]=[c._events[g],f]:c._events[g].push(f):(c._events[g]=f,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,f=h.length,g=new Array(f);d<f;d++)g[d]=h[d].fn;return g},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,f,g){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,f),!0;case 6:return y.fn.call(y.context,u,h,d,f,g),!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,A;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(A=1,E=new Array(v-1);A<v;A++)E[A-1]=arguments[A];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 f=t?t+l:l;if(!this._events[f])return this;if(!u)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===u&&(!d||g.once)&&(!h||g.context===h)&&a(this,f);else{for(var p=0,y=[],v=g.length;p<v;p++)(g[p].fn!==u||d&&!g[p].once||h&&g[p].context!==h)&&y.push(g[p]);y.length?this._events[f]=y.length===1?y[0]:y:a(this,f)}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})(rn)),rn.exports}var gf=ff(),nn=$h(gf);const ai="1.6.14",Ns={};function mf(){return typeof __HLS_WORKER_BUNDLE__=="function"}function pf(){const r=Ns[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 Ns[ai]=i,i}function yf(r){const e=Ns[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 Ns[r]=i,i}function vf(r){const e=Ns[r||ai];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete Ns[r||ai],i&&self.URL.revokeObjectURL(i),s.terminate()}}function Sl(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 an(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(;an(r,e);){s+=10;const i=Xi(r,e+6);s+=i,Sl(r,e+10)&&(s+=10),e+=s}if(s>0)return r.subarray(t,t+s)}function Ef(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 f=new Error(`invalid ADTS sampling index:${a}`);r.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.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 ae.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 xl(r,e){return r[e]===255&&(r[e+1]&246)===240}function Al(r,e){return r[e+1]&1?7:9}function on(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function Tf(r,e){return e+5<r.length}function zi(r,e){return e+1<r.length&&xl(r,e)}function Sf(r,e){return Tf(r,e)&&xl(r,e)&&on(r,e)<=r.length-e}function xf(r,e){if(zi(r,e)){const t=Al(r,e);if(e+t>=r.length)return!1;const s=on(r,e);if(s<=t)return!1;const i=e+s;return i===r.length||zi(r,i)}return!1}function _l(r,e,t,s,i){if(!r.samplerate){const n=Ef(e,t,s,i);if(!n)return;oe(r,n)}}function Il(r){return 1024*9e4/r}function Af(r,e){const t=Al(r,e);if(e+t<=r.length){const s=on(r,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function Ll(r,e,t,s,i){const n=Il(r.samplerate),a=s+i*n,o=Af(e,t);let c;if(o){const{frameLength:h,headerLength:d}=o,f=d+h,g=Math.max(0,t+f-e.length);g?(c=new Uint8Array(f-d),c.set(e.subarray(t+d,e.length),0)):c=e.subarray(t+d,t+f);const p={unit:c,pts:a};return g||r.samples.push(p),{sample:p,length:f,missing:g}}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 _f(r,e){return an(r,e)&&Xi(r,e+6)+10<=r.length-e}function If(r){return r instanceof ArrayBuffer?r:r.byteOffset==0&&r.byteLength==r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer}function ln(r,e=0,t=1/0){return Lf(r,e,t,Uint8Array)}function Lf(r,e,t,s){const i=Rf(r);let n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);const a=bf(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 Rf(r){return r instanceof ArrayBuffer?r:r.buffer}function bf(r){return r&&r.buffer instanceof ArrayBuffer&&r.byteLength!==void 0&&r.byteOffset!==void 0}function Df(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=Qe(ln(r.data,1,s)),n=r.data[2+s],a=r.data.subarray(3+s).indexOf(0);if(a===-1)return;const o=Qe(ln(r.data,3+s,a));let c;return i==="-->"?c=Qe(ln(r.data,4+s+a)):c=If(r.data.subarray(4+s+a)),e.mimeType=i,e.pictureType=n,e.description=o,e.data=c,e}function Cf(r){if(r.size<2)return;const e=Qe(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}}function Pf(r){if(r.size<2)return;if(r.type==="TXXX"){let t=1;const s=Qe(r.data.subarray(t),!0);t+=s.length+1;const i=Qe(r.data.subarray(t));return{key:r.type,info:s,data:i}}const e=Qe(r.data.subarray(1));return{key:r.type,info:"",data:e}}function kf(r){if(r.type==="WXXX"){if(r.size<2)return;let t=1;const s=Qe(r.data.subarray(t),!0);t+=s.length+1;const i=Qe(r.data.subarray(t));return{key:r.type,info:s,data:i}}const e=Qe(r.data);return{key:r.type,info:"",data:e}}function wf(r){return r.type==="PRIV"?Cf(r):r.type[0]==="W"?kf(r):r.type==="APIC"?Df(r):Pf(r)}function Of(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,Mf=10;function Rl(r){let e=0;const t=[];for(;an(r,e);){const s=Xi(r,e+6);r[e+5]>>6&1&&(e+=Qi),e+=Qi;const i=e+s;for(;e+Mf<i;){const n=Of(r.subarray(e)),a=wf(n);a&&t.push(a),e+=n.size+Qi}Sl(r,e)&&(e+=Qi)}return t}function bl(r){return r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp"}function Ff(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 cn(r){const e=Rl(r);for(let t=0;t<e.length;t++){const s=e[t];if(bl(s))return Ff(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 _t(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class un{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?cn(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&$(c))&&(this.basePTS=Nf(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 _f(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:_t(),id3Track:o,textTrack:_t()}}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:_t(),id3Track:this._id3Track,textTrack:_t()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Nf=(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 $f=[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],Bf=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Uf=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Gf=[0,1,1,4];function Dl(r,e,t,s,i){if(t+24>e.length)return;const n=Cl(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 Cl(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=$f[c*14+i-1]*1e3,h=Bf[(t===3?0:t===2?1:2)*3+n],d=o===3?1:2,f=Uf[t][s],g=Gf[s],p=f*8*g,y=Math.floor(f*l/h+a)*g;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 hn(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function Pl(r,e){return e+1<r.length&&hn(r,e)}function Kf(r,e){return hn(r,e)&&4<=r.length-e}function kl(r,e){if(e+1<r.length&&hn(r,e)){const s=Cl(r,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const n=e+i;return n===r.length||Pl(r,n)}return!1}class Vf extends un{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(kl(e,i))return!1;for(let n=e.length;i<n;i++)if(xf(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Sf(e,t)}appendFrame(e,t,s){_l(e,this.observer,t,s,e.manifestCodec);const i=Ll(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 Hf extends un{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=Ol(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&&cn(t)!==void 0&&wl(e,s)<16}}function Ol(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 f=(e[t+6]<<8|e[t+7])>>12-d&1,p=[2,1,2,3,3,4,4,5][h]+f,y=e[t+5]>>3,v=e[t+5]&7,E=new Uint8Array([n<<6|y<<1|v>>2,(v&3)<<6|h<<3|f<<2|c>>4,c<<4&224]),T=1536/o*9e4,S=s+i*T,A=e.subarray(t,t+u);return r.config=E,r.channelCount=p,r.samplerate=o,r.samples.push({unit:A,pts:S}),u}class Wf extends un{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&&cn(t)!==void 0&&wl(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(kl(e,s))return ae.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Kf(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return Dl(e,t,s,this.basePTS,this.frameIndex)}}const Yf=/\/emsg[-/]ID3/i;class qf{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=_t("video",1),a=this.audioTrack=_t("audio",1),o=this.txtTrack=_t("text",1);if(this.id3Track=_t("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=ao(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=so.text,n.sampleDuration=0,n.duration=a.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return Vh(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=zh(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const a=this.extractID3Track(i,t);return n.samples=co(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=co(e,t),{videoTrack:t,audioTrack:_t(),id3Track:i,textTrack:_t()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=J(e.samples,["emsg"]);i&&i.forEach(n=>{const a=Jh(n);if(Yf.test(a.schemeIdUri)){const o=Ml(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=Ml(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 Ml(r,e){return $(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale}class jf{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Wr(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Jt.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=uo(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 Fl{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,f=0;for(n===-1&&(d=0,f=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 g={data:t.subarray(d,u),type:f};o.push(g)}else{const g=this.getLastNalUnit(e.samples);g&&(a&&c<=4-a&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-a)),u>0&&(g.data=nt(g.data,t.subarray(0,u)),g.state=0))}c<i?(h=this.getNALuType(t,c),d=c,f=h,n=0):n=-1}else n=0}if(d>=0&&n>=0){const g={data:t.subarray(d,i),type:f,state:n};o.push(g)}if(o.length===0){const g=this.getLastNalUnit(e.samples);g&&(g.data=nt(g.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&&ae.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 Xf extends Fl{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,Nr(l.data,1,s.pts,t.samples);break}case 7:{var f,g;o=!0,c=!0;const p=l.data,y=this.readSPS(p);if(!e.sps||e.width!==y.width||e.height!==y.height||((f=e.pixelRatio)==null?void 0:f[0])!==y.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[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),f=t.readBoolean.bind(t),g=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),g(3),u(),y(),E===100||E===110||E===122||E===244||E===44||E===83||E===86||E===118||E===128){const x=d();if(x===3&&g(1),y(),y(),g(1),f())for(c=x!==3?8:12,l=0;l<c;l++)f()&&(l<6?v(16,t):v(64,t))}y();const T=d();if(T===0)d();else if(T===1)for(g(1),p(),p(),o=d(),l=0;l<o;l++)p();y(),g(1);const S=d(),A=d(),D=h(1);D===0&&g(1),g(1),f()&&(s=d(),i=d(),n=d(),a=d());let _=[1,1];if(f()&&f())switch(u()){case 1:_=[1,1];break;case 2:_=[12,11];break;case 3:_=[10,11];break;case 4:_=[16,11];break;case 5:_=[40,33];break;case 6:_=[24,11];break;case 7:_=[20,11];break;case 8:_=[32,11];break;case 9:_=[80,33];break;case 10:_=[18,11];break;case 11:_=[15,11];break;case 12:_=[64,33];break;case 13:_=[160,99];break;case 14:_=[4,3];break;case 15:_=[3,2];break;case 16:_=[2,1];break;case 255:{_=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((S+1)*16-s*2-i*2),height:(2-D)*(A+1)*16-(D?2:4)*(n+a),pixelRatio:_}}}class zf extends Fl{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,Nr(l.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=oe(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 f=this.readSPS(l.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const g in f.params)e.params[g]=f.params[g]}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 f=this.readPPS(l.data);for(const g in f)e.params[g]=f[g]}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(),f=t.readUByte(),g=t.readUByte(),p=t.readUByte(),y=t.readUByte(),v=t.readUByte(),E=[],T=[];for(let se=0;se<s;se++)E.push(t.readBoolean()),T.push(t.readBoolean());if(s>0)for(let se=s;se<8;se++)t.readBits(2);for(let se=0;se<s;se++)E[se]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),T[se]&&t.readUByte();t.readUEG();const S=t.readUEG();S==3&&t.skipBits(1);const A=t.readUEG(),D=t.readUEG(),_=t.readBoolean();let x=0,I=0,L=0,C=0;_&&(x+=t.readUEG(),I+=t.readUEG(),L+=t.readUEG(),C+=t.readUEG());const F=t.readUEG(),N=t.readUEG(),G=t.readUEG(),U=t.readBoolean();for(let se=U?0:s;se<=s;se++)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 Ne=0;Ne<4;Ne++)for(let ot=0;ot<(Ne===3?2:6);ot++)if(!t.readBoolean())t.readUEG();else{const ft=Math.min(64,1<<4+(Ne<<1));Ne>1&&t.readEG();for(let Hs=0;Hs<ft;Hs++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const O=t.readUEG();let K=0;for(let se=0;se<O;se++){let Ne=!1;if(se!==0&&(Ne=t.readBoolean()),Ne){se===O&&t.readUEG(),t.readBoolean(),t.readUEG();let ot=0;for(let vs=0;vs<=K;vs++){const ft=t.readBoolean();let Hs=!1;ft||(Hs=t.readBoolean()),(ft||Hs)&&ot++}K=ot}else{const ot=t.readUEG(),vs=t.readUEG();K=ot+vs;for(let ft=0;ft<ot;ft++)t.readUEG(),t.readBoolean();for(let ft=0;ft<vs;ft++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const se=t.readUEG();for(let Ne=0;Ne<se;Ne++){for(let ot=0;ot<G+4;ot++)t.readBits(1);t.readBits(1)}}let M=0,w=1,Y=1,Z=!0,j=1,z=0;t.readBoolean(),t.readBoolean();let pe=!1;if(t.readBoolean()){if(t.readBoolean()){const Es=t.readUByte(),ou=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],mr=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Es>0&&Es<16?(w=ou[Es-1],Y=mr[Es-1]):Es===255&&(w=t.readBits(16),Y=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(),pe=t.readBoolean(),pe&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(j=t.readBits(32),z=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const mr=t.readBoolean(),lu=t.readBoolean();let gi=!1;(mr||lu)&&(gi=t.readBoolean(),gi&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),gi&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let cu=0;cu<=s;cu++){Z=t.readBoolean();const B0=Z||t.readBoolean();let uu=!1;B0?t.readEG():uu=t.readBoolean();const hu=uu?1:t.readUEG()+1;if(mr)for(let mi=0;mi<hu;mi++)t.readUEG(),t.readUEG(),gi&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(lu)for(let mi=0;mi<hu;mi++)t.readUEG(),t.readUEG(),gi&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),M=t.readUEG())}let _e=A,De=D;if(_){let se=1,Ne=1;S===1?se=Ne=2:S==2&&(se=2),_e=A-se*I-se*x,De=D-Ne*C-Ne*L}const Ge=i?["A","B","C"][i]:"",Kt=o<<24|c<<16|l<<8|u;let Fe=0;for(let se=0;se<32;se++)Fe=(Fe|(Kt>>se&1)<<31-se)>>>0;let Vt=Fe.toString(16);return a===1&&Vt==="2"&&(Vt="6"),{codecString:`hvc1.${Ge}${a}.${Vt}.${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,f,g,p,y],general_level_idc:v,bit_depth:F+8,bit_depth_luma_minus8:F,bit_depth_chroma_minus8:N,min_spatial_segmentation_idc:M,chroma_format_idc:S,frame_rate:{fixed:Z,fps:z/j}},width:_e,height:De,pixelRatio:[w,Y]}}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 be=188;class Zt{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=Zt.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(be*5,t-be)+1,i=0;for(;i<s;){let n=!1,a=-1,o=0;for(let c=i;c<t;c+=be)if(e[c]===71&&(t-c===be||e[c+be]===71)){if(o++,a===-1&&(a=c,a!==0&&(s=Math.min(a+be*99,e.length-be)+1)),n||(n=dn(e,c)===0),n&&o>1&&(a===0&&o>2||c+be>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:so[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=Zt.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=Zt.createTrack("audio",i),this._id3Track=Zt.createTrack("id3"),this._txtTrack=Zt.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,f=c.pid,g=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<be&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};const S=Math.max(0,Zt.syncOffset(e));T-=(T-S)%be,T<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,T,e.buffer.byteLength-T));let A=0;for(let _=S;_<T;_+=be)if(e[_]===71){const x=!!(e[_+1]&64),I=dn(e,_),L=(e[_+3]&48)>>4;let C;if(L>1){if(C=_+5+e[_+4],C===_+be)continue}else C=_+4;switch(I){case u:x&&(h&&(n=$s(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,_+be)),h.size+=_+be-C);break;case d:if(x){if(g&&(n=$s(g,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}g={data:[],size:0}}g&&(g.data.push(e.subarray(C,_+be)),g.size+=_+be-C);break;case f:x&&(p&&(n=$s(p,this.logger))&&this.parseID3PES(c,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(C,_+be)),p.size+=_+be-C);break;case 0:x&&(C+=e[C]+1),E=this._pmtId=Qf(e,C);break;case E:{x&&(C+=e[C]+1);const F=Jf(e,C,this.typeSupported,s,this.observer,this.logger);u=F.videoPid,u>0&&(a.pid=u,a.segmentCodec=F.segmentVideoCodec),d=F.audioPid,d>0&&(o.pid=d,o.segmentCodec=F.segmentAudioCodec),f=F.id3Pid,f>0&&(c.pid=f),y!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${_} after unknown PID '${y}'. Backtracking to sync byte @${S} to parse all TS packets.`),y=null,_=S-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=I;break}}else A++;A>0&&fn(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=h,o.pesData=g,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=$s(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=$s(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=$s(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 jf(this.observer,this.config,t);return this.decrypt(i,n)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Xf:e==="hevc"&&(this.videoParser=new zf))}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 f=d-h;i.sample.unit.set(n.subarray(0,h),f),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",fn(this.observer,new Error(h),d,this.logger),!d)return}_l(e,this.observer,n,a,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){const h=Il(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=Ll(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(Pl(s,a)){const c=Dl(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=Ol(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=oe({},t,{type:this._videoTrack?Ze.emsg:Ze.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function dn(r,e){return((r[e+1]&31)<<8)+r[e+2]}function Qf(r,e){return(r[e+10]&31)<<8|r[e+11]}function Jf(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=dn(r,e),h=(r[e+3]&15)<<8|r[e+4];switch(r[e]){case 207:if(!s){gn("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){gn("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){gn("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,f=h;for(;f>2;){switch(r[d]){case 106:t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=u,a.segmentAudioCodec="ac3");break}const p=r[d+1]+2;d+=p,f-=p}}break;case 194:case 135:return fn(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 fn(r,e,t,s){s.warn(`parsing error: ${e.message}`),r.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function gn(r,e){e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function $s(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 f=0,g=c.length;f<g;f++){s=c[f];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 Zf{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 es=Math.pow(2,32)-1;class R{static init(){R.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 R.types)R.types.hasOwnProperty(e)&&(R.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]);R.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]);R.STTS=R.STSC=R.STCO=n,R.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),R.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),R.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),R.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]);R.FTYP=R.box(R.types.ftyp,a,c,a,o),R.DINF=R.box(R.types.dinf,R.box(R.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 R.box(R.types.hdlr,R.HDLR_TYPES[e])}static mdat(e){return R.box(R.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(es+1)),i=Math.floor(t%(es+1));return R.box(R.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 R.box(R.types.mdia,R.mdhd(e.timescale||0,e.duration||0),R.hdlr(e.type),R.minf(e))}static mfhd(e){return R.box(R.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"?R.box(R.types.minf,R.box(R.types.smhd,R.SMHD),R.DINF,R.stbl(e)):R.box(R.types.minf,R.box(R.types.vmhd,R.VMHD),R.DINF,R.stbl(e))}static moof(e,t,s){return R.box(R.types.moof,R.mfhd(e),R.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=R.trak(e[t]);return R.box.apply(null,[R.types.moov,R.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(R.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=R.trex(e[t]);return R.box.apply(null,[R.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(es+1)),i=Math.floor(t%(es+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 R.box(R.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 R.box(R.types.sdtp,s)}static stbl(e){return R.box(R.types.stbl,R.stsd(e),R.box(R.types.stts,R.STTS),R.box(R.types.stsc,R.STSC),R.box(R.types.stsz,R.STSZ),R.box(R.types.stco,R.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=R.box(R.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 R.box(R.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,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.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 R.box(R.types.mp4a,R.audioStsd(e),R.box(R.types.esds,R.esds(e)))}static mp3(e){return R.box(R.types[".mp3"],R.audioStsd(e))}static ac3(e){return R.box(R.types["ac-3"],R.audioStsd(e),R.box(R.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return R.box(R.types.stsd,R.STSD,R.mp4a(e));if(t==="ac3"&&e.config)return R.box(R.types.stsd,R.STSD,R.ac3(e));if(t==="mp3"&&e.codec==="mp3")return R.box(R.types.stsd,R.STSD,R.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return R.box(R.types.stsd,R.STSD,R.avc1(e));if(t==="hevc"&&e.vps)return R.box(R.types.stsd,R.STSD,R.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/(es+1)),o=Math.floor(s%(es+1));return R.box(R.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=R.sdtp(e),i=e.id,n=Math.floor(t/(es+1)),a=Math.floor(t%(es+1));return R.box(R.types.traf,R.box(R.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),R.box(R.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])),R.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,R.box(R.types.trak,R.tkhd(e),R.mdia(e))}static trex(e){const t=e.id;return R.box(R.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 R.box(R.types.trun,a)}static initSegment(e){R.types||R.init();const t=R.moov(e);return nt(R.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 g=0;g<s.length;g+=1){a+=3;for(let p=0;p<s[g].length;p+=1)a+=2+s[g][p].length}const o=new Uint8Array(a);o.set(n,0),a=n.length;const c=s.length-1;for(let g=0;g<s.length;g+=1){o.set(new Uint8Array([32+g|(g===c?128:0),0,s[g].length]),a),a+=3;for(let p=0;p<s[g].length;p+=1)o.set(new Uint8Array([s[g][p].length>>8,s[g][p].length&255]),a),a+=2,o.set(s[g][p],a),a+=s[g][p].length}const l=R.box(R.types.hvcC,o),u=e.width,h=e.height,d=e.pixelRatio[0],f=e.pixelRatio[1];return R.box(R.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,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}}R.types=void 0,R.HDLR_TYPES=void 0,R.STTS=void 0,R.STSC=void 0,R.STCO=void 0,R.STSZ=void 0,R.VMHD=void 0,R.SMHD=void 0,R.STSD=void 0,R.FTYP=void 0,R.DINF=void 0;const Nl=9e4;function mn(r,e,t=1,s=!1){const i=r*e*t;return s?Math.round(i):i}function eg(r,e,t=1,s=!1){return mn(r,e,1/t,s)}function ci(r,e=!1){return mn(r,1e3,1/Nl,e)}function tg(r,e=1){return mn(r,Nl,1/e)}function $l(r){const{baseTime:e,timescale:t,trackId:s}=r;return`${e/t} (${e}/${t}) trackId: ${s}`}const sg=10*1e3,ig=1024,rg=1152,ng=1536;let Bs=null,pn=null;function Bl(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,Bs===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Bs=a?parseInt(a[1]):0}if(pn===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);pn=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&&$l(t)} > ${e&&$l(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=et(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,f,g,p=n,y=n;const v=e.pid>-1,E=t.pid>-1,T=t.samples.length,S=e.samples.length>0,A=o&&T>0||T>1;if((!v||S)&&(!E||A)||this.ISGenerated||o){if(this.ISGenerated){var _,x,I,L;const G=this.videoTrackConfig;(G&&(t.width!==G.width||t.height!==G.height||((_=t.pixelRatio)==null?void 0:_[0])!==((x=G.pixelRatio)==null?void 0:x[0])||((I=t.pixelRatio)==null?void 0:I[1])!==((L=G.pixelRatio)==null?void 0:L[1]))||!G&&A||this.nextAudioTs===null&&S)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,n,a));const C=this.isVideoContiguous;let F=-1,N;if(A&&(F=ag(t.samples),!C&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,F>0){this.warn(`Dropped ${F} out of ${T} video samples due to a missing keyframe`);const G=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(F),t.dropped+=F,y+=(t.samples[0].pts-G)/t.inputTimeScale,N=y}else F===-1&&(this.warn(`No keyframe found out of ${T} video samples`),g=!1);if(this.ISGenerated){if(S&&A){const G=this.getVideoStartPts(t.samples),k=(et(e.samples[0].pts,G)-G)/t.inputTimeScale;p+=Math.max(0,k),y+=Math.max(0,-k)}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||A||c===V.AUDIO?y:void 0),A){const G=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,G)}}else A&&(l=this.remuxVideo(t,y,C,0));l&&(l.firstKeyFrame=F,l.independent=F!==-1,l.firstKeyFramePTS=N)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=Ul(s,n,this._initPTS,this._initDTS)),i.samples.length&&(d=Gl(i,n,this._initPTS))),{audio:u,video:l,initSegment:h,independent:g,text:d,id3:f}}computeInitPts(e,t,s,i){const n=Math.round(s*t);let a=et(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,f,g,p=-1;if(u&&(d=f=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):R.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(p=e.id,g=e.inputTimeScale,!l||g!==l.timescale?d=f=this.computeInitPts(n[0].pts,g,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:R.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(p=t.id,g=t.inputTimeScale,!l||g!==l.timescale){const y=this.getVideoStartPts(a),v=et(a[0].dts,y),E=this.computeInitPts(v,g,s,"video"),T=this.computeInitPts(y,g,s,"video");f=Math.min(f,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/g} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/g} (${d}/${g}) trackId: ${p}`),this._initPTS={baseTime:d,timescale:g,trackId:p},this._initDTS={baseTime:f,timescale:g,trackId:p}):d=g=void 0,{tracks:c,initPTS:d,timescale:g,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,f=this.videoSampleDuration,g,p,y=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,E=!1;if(!s||h===null){const M=u+t*n,w=a[0].pts-et(a[0].dts,a[0].pts);Bs&&h!==null&&Math.abs(M-w-(h+u))<15e3?s=!0:h=M-w-u}const T=h+u;for(let M=0;M<c;M++){const w=a[M];w.pts=et(w.pts,T),w.dts=et(w.dts,T),w.dts<a[M>0?M-1:M].dts&&(E=!0)}E&&a.sort(function(M,w){const Y=M.dts-w.dts,Z=M.pts-w.pts;return Y||Z}),g=a[0].dts,p=a[a.length-1].dts;const S=p-g,A=S?Math.round(S/(c-1)):f||e.inputTimeScale/30;if(s){const M=g-T,w=M>A,Y=M<-1;if((w||Y)&&(w?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ci(M,!0)} ms (${M}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ci(-M,!0)} ms (${M}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!Y||T>=a[0].pts||Bs)){g=T;const Z=a[0].pts-M;if(w)a[0].dts=g,a[0].pts=Z;else{let j=!0;for(let z=0;z<a.length&&!(a[z].dts>Z&&j);z++){const pe=a[z].pts;if(a[z].dts-=M,a[z].pts-=M,z<a.length-1){const he=a[z+1].pts,_e=a[z].pts,De=he<=_e,Ge=he<=pe;j=De==Ge}}}this.log(`Video: Initial PTS/DTS adjusted: ${ci(Z,!0)}/${ci(g,!0)}, delta: ${ci(M,!0)} ms`)}}g=Math.max(0,g);let D=0,_=0,x=g;for(let M=0;M<c;M++){const w=a[M],Y=w.units,Z=Y.length;let j=0;for(let z=0;z<Z;z++)j+=Y[z].data.length;_+=j,D+=Z,w.length=j,w.dts<x?(w.dts=x,x+=A/4|0||1):x=w.dts,y=Math.min(w.pts,y),v=Math.max(w.pts,v)}p=a[c-1].dts;const I=_+4*D+8;let L;try{L=new Uint8Array(I)}catch(M){this.observer.emit(m.ERROR,m.ERROR,{type:H.MUX_ERROR,details:b.REMUX_ALLOC_ERROR,fatal:!1,error:M,bytes:I,reason:`fail allocating video mdat ${I}`});return}const C=new DataView(L.buffer);C.setUint32(0,I),L.set(R.types.mdat,4);let F=!1,N=Number.POSITIVE_INFINITY,G=Number.POSITIVE_INFINITY,U=Number.NEGATIVE_INFINITY,k=Number.NEGATIVE_INFINITY;for(let M=0;M<c;M++){const w=a[M],Y=w.units;let Z=0;for(let pe=0,he=Y.length;pe<he;pe++){const _e=Y[pe],De=_e.data,Ge=_e.data.byteLength;C.setUint32(d,Ge),d+=4,L.set(De,d),d+=Ge,Z+=4+Ge}let j;if(M<c-1)f=a[M+1].dts-w.dts,j=a[M+1].pts-w.pts;else{const pe=this.config,he=M>0?w.dts-a[M-1].dts:A;if(j=M>0?w.pts-a[M-1].pts:A,pe.stretchShortVideoTrack&&this.nextAudioTs!==null){const _e=Math.floor(pe.maxBufferHole*n),De=(i?y+i*n:this.nextAudioTs+u)-w.pts;De>_e?(f=De-he,f<0?f=he:F=!0,this.log(`It is approximately ${De/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=he}else f=he}const z=Math.round(w.pts-w.dts);N=Math.min(N,f),U=Math.max(U,f),G=Math.min(G,j),k=Math.max(k,j),o.push(Bl(w.key,f,Z,z))}if(o.length){if(Bs){if(Bs<70){const M=o[0].flags;M.dependsOn=2,M.isNonSync=0}}else if(pn&&k-G<U-N&&A/U<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let M=g;for(let w=0,Y=o.length;w<Y;w++){const Z=M+o[w].duration,j=M+o[w].cts;if(w<Y-1){const z=Z+o[w+1].cts;o[w].duration=z-j}else o[w].duration=w?o[w-1].duration:A;o[w].cts=0,M=Z}}}f=F||!f?A:f;const B=p+f;this.nextVideoTs=h=B-u,this.videoSampleDuration=f,this.isVideoContiguous=!0;const W={data1:R.moof(e.sequenceNumber++,g,oe(e,{samples:o})),data2:L,startPTS:(y-u)/n,endPTS:(v+f-u)/n,startDTS:(g-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 rg;case"ac3":return ng;default:return ig}}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,f=[],g=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(et(p[0].pts,T)-(v+E))<20*u),p.forEach(function(k){k.pts=et(k.pts,T)}),!s||v<0){const k=p.length;if(p=p.filter(B=>B.pts>=0),k!==p.length&&this.warn(`Removed ${p.length-k} of ${k} samples (initPTS ${E} / ${a})`),!p.length)return;n===0?v=0:i&&!g?v=Math.max(0,T-E):v=p[0].pts-E}if(e.segmentCodec==="aac"){const k=this.config.maxAudioFramesDrift;for(let B=0,O=v+E;B<p.length;B++){const K=p[B],W=K.pts,M=W-O,w=Math.abs(1e3*M/a);if(M<=-k*u&&g)B===0&&(this.warn(`Audio frame @ ${(W/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*M/a)} ms.`),this.nextAudioTs=v=W-E,O=W);else if(M>=k*u&&w<sg&&g){let Y=Math.round(M/u);for(O=W-Y*u;O<0&&Y&&u;)Y--,O+=u;B===0&&(this.nextAudioTs=v=O-E),this.warn(`Injecting ${Y} audio frames @ ${((O-E)/a).toFixed(3)}s due to ${Math.round(1e3*M/a)} ms gap.`);for(let Z=0;Z<Y;Z++){let j=Zf.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);j||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),j=K.unit.subarray()),p.splice(B,0,{unit:j,pts:O}),O+=u,B++}}K.pts=O,O+=u}}let S=null,A=null,D,_=0,x=p.length;for(;x--;)_+=p[x].unit.byteLength;for(let k=0,B=p.length;k<B;k++){const O=p[k],K=O.unit;let W=O.pts;if(A!==null){const w=f[k-1];w.duration=Math.round((W-A)/c)}else if(s&&e.segmentCodec==="aac"&&(W=v+E),S=W,_>0){_+=y;try{D=new Uint8Array(_)}catch(w){this.observer.emit(m.ERROR,m.ERROR,{type:H.MUX_ERROR,details:b.REMUX_ALLOC_ERROR,fatal:!1,error:w,bytes:_,reason:`fail allocating audio mdat ${_}`});return}d||(new DataView(D.buffer).setUint32(0,_),D.set(R.types.mdat,4))}else return;D.set(K,y);const M=K.byteLength;y+=M,f.push(Bl(!0,l,M,0)),A=W}const I=f.length;if(!I)return;const L=f[f.length-1];v=A-E,this.nextAudioTs=v+c*L.duration;const C=d?new Uint8Array(0):R.moof(e.sequenceNumber++,S/c,oe({},e,{samples:f}));e.samples=[];const F=(S-E)/a,N=v/a,U={data1:C,data2:D,startPTS:F,endPTS:N,startDTS:F,endDTS:N,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,U}}function et(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 ag(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function Ul(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=et(c.pts-t.baseTime*n/t.timescale,e*n)/n,c.dts=et(c.dts-s.baseTime*n/s.timescale,e*n)/n}const a=r.samples;return r.samples=[],{samples:a}}function Gl(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=et(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 og 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=ao(e);if(t)qh(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=Kl(n,ce.AUDIO,this)),a&&(i=Kl(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 f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(d),g=this.initData),!((c=g)!=null&&c.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const p=Xh(d,g,this),y=g.audio?p[g.audio.id]:null,v=g.video?p[g.video.id]:null,E=er(v,1/0),T=er(y,1/0),S=er(v,0,!0),A=er(y,0,!0);let D=n,_=0;const x=y&&(!v||!l&&T<E||l&&l.trackId===g.audio.id),I=x?y:v;if(I){const O=I.timescale,K=I.start-n*O,W=x?g.audio.id:g.video.id;D=I.start/O,_=x?A-T:S-E,(a||!l)&&(lg(l,D,n,_)||O!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${K/O} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${D-n} (${K}/${O}) trackId: ${W}`),l=null,f.initPTS=K,f.timescale=O,f.trackId=W)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);l?(f.initPTS=l.baseTime,f.timescale=l.timescale,f.trackId=l.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=D,f.timescale=1,f.trackId=-1),this.initPTS=l={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const L=D-l.baseTime/l.timescale,C=L+_;_>0?this.lastEndTime=C:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const F=!!g.audio,N=!!g.video;let G="";F&&(G+="audio"),N&&(G+="video");const U=(g.audio?g.audio.encrypted:!1)||(g.video?g.video.encrypted:!1),k={data1:d,startPTS:L,startDTS:L,endPTS:C,endDTS:C,type:G,hasAudio:F,hasVideo:N,nb:1,dropped:0,encrypted:U};h.audio=F&&!N?k:void 0,h.video=N?k:void 0;const B=v?.sampleCount;if(B){const O=v.keyFrameIndex,K=O!==-1;k.nb=B,k.dropped=O===0||this.isVideoContiguous?0:K?O:B,k.independent=K,k.firstKeyFrame=O,K&&v.keyFrameStart&&(k.firstKeyFramePTS=(v.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(h.independent=K),this.isVideoContiguous||(this.isVideoContiguous=K),k.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${O}/${B} dropped: ${k.dropped} start: ${k.firstKeyFramePTS||"NA"}`)}return h.initSegment=f,h.id3=Ul(s,n,l,l),i.samples.length&&(h.text=Gl(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 lg(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 Kl(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"?Mi(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 Ut;try{Ut=self.performance.now.bind(self.performance)}catch{Ut=Date.now}const tr=[{demux:qf,remux:og},{demux:Zt,remux:Zi},{demux:Vf,remux:Zi},{demux:Wf,remux:Zi}];tr.splice(2,0,{demux:Hf,remux:Zi});class Vl{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=Ut();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:f,initSegmentChange:g}=i||o,{audioCodec:p,videoCodec:y,defaultInitPts:v,duration:E,initSegmentData:T}=c,S=cg(a,t);if(S&&Fs(S.method)){const x=this.getDecrypter(),I=jr(S.method);if(x.isSync()){let L=x.softwareDecrypt(a,S.key.buffer,S.iv.buffer,I);if(s.part>-1){const F=x.flush();L=F&&F.buffer}if(!L)return n.executeEnd=Ut(),yn(s);a=new Uint8Array(L)}else return this.asyncResult=!0,this.decryptionPromise=x.webCryptoDecrypt(a,S.key.buffer,S.iv.buffer,I).then(L=>{const C=this.push(L,null,s);return this.decryptionPromise=null,C}),this.decryptionPromise}const A=this.needsProbing(u,h);if(A){const x=this.configureTransmuxer(a);if(x)return this.logger.warn(`[transmuxer] ${x.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!1,error:x,reason:x.message}),n.executeEnd=Ut(),yn(s)}(u||h||g||A)&&this.resetInitSegment(T,p,y,E,t),(u||g||A)&&this.resetInitialTimestamp(v),l||this.resetContiguity();const D=this.transmux(a,S,f,d,s);this.asyncResult=ui(D);const _=this.currentTransmuxState;return _.contiguous=!0,_.discontinuity=!1,_.trackSwitch=!1,n.executeEnd=Ut(),D}flush(e){const t=e.transmuxing;t.executeStart=Ut();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=Ut();const h=[yn(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===V.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=Ut()}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 Wr(this.config)),e}}function cg(r,e){let t=null;return r.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const yn=r=>({remuxResult:{},chunkMeta:r});function ui(r){return"then"in r&&r.then instanceof Function}class ug{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 hg{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 Hl=0;class Wl{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Hl++,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:b.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 nn,this.observer.on(m.FRAG_DECRYPTED,a),this.observer.on(m.ERROR,a);const o=mo(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=yf(n.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=pf());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 Vl(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new Vl(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Hl++;const t=this.hls.config,s=mo(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),vf(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:f,transmuxer:g}=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,A=this.part?l.part-this.part.index:-1,D=S===0&&l.id>1&&l.id===v?.stats.chunkCount,_=!T&&(S===1||S===0&&(A===1||D&&A<=0)),x=self.performance.now();(T||S||n.stats.parsing.start===0)&&(n.stats.parsing.start=x),a&&(A||!_)&&(a.stats.parsing.start=x);const I=!(v&&((h=n.initSegment)==null?void 0:h.url)===((d=v.initSegment)==null?void 0:d.url)),L=new hg(E,_,c,T,p,I);if(!_||E||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===V.MAIN?"level":"track"}: ${l.level} id: ${l.id}
|
|
18
18
|
discontinuity: ${E}
|
|
19
19
|
trackSwitch: ${T}
|
|
20
|
-
contiguous: ${
|
|
20
|
+
contiguous: ${_}
|
|
21
21
|
accurateTimeOffset: ${c}
|
|
22
22
|
timeOffset: ${p}
|
|
23
|
-
initSegmentChange: ${I}`);const C=new zf(s,i,t,o,u);this.configureTransmuxer(C)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:y,chunkMeta:l,state:_},e instanceof ArrayBuffer?[e]:[]);else if(g){const C=g.push(e,y,l,_);Js(C)?C.then(F=>{this.handleTransmuxComplete(F)}).catch(F=>{this.transmuxerError(F,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);Js(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:b.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 wl=100;class Jf extends qr{constructor(e,t,s){super(e,t,s,"audio-stream-controller",V.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===V.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=Eo(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(wl),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,le.AUDIO,V.AUDIO));const u=this.getFwdBufferInfo(l,V.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,f=c.fragments,g=f[0].start,p=this.getLoadPosition(),y=this.flushing?p:u.end;if(this.switchingTrack&&i){const T=p;c.PTSKnown&&T<g&&(u.end>g||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=g+.05)}if(h>=d&&!this.switchingTrack&&y<f[f.length-1].start)return;let v=this.getNextFragment(y,c);if(v&&this.isLoopLoading(v,y)&&(v=this.getNextFragmentLoopLoading(v,c,u,V.MAIN,d)),!v){this.bufferFlushed=!0;return}let E=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&E&&Se(v)&&!v.endList&&(!c.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(E)===Ie.OK&&(this.mainFragLoading=E=null),E&&Se(E))){if(v.start>E.end){const S=this.fragmentTracker.getFragAtPos(y,V.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 Hs(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(wl),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||(nl(n,l),n.alignedSliding||Oi(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 kl(this.hls,V.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[s.cc],g=(t=s.initSegment)==null?void 0:t.data;if(f!==void 0){const y=i?i.index:-1,v=y!==-1,E=new Nr(s.level,s.sn,s.stats.chunkCount,n.byteLength,y,v);d.push(n,g,h,"",s,i,u.totalduration,!1,E,f)}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 ol,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===V.MAIN&&Se(t.frag)&&(this.mainFragLoading=t,this.state===P.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==V.AUDIO){!this.audioOnly&&s.type===V.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(Se(s)){this.fragPrevious=s;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,re({},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 b.FRAG_GAP:case b.FRAG_PARSING_ERROR:case b.FRAG_DECRYPT_ERROR:case b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(V.AUDIO,t);break;case b.AUDIO_TRACK_LOAD_ERROR:case b.AUDIO_TRACK_LOAD_TIMEOUT:case b.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 b.BUFFER_ADD_CODEC_ERROR:case b.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case b.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case b.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==le.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==le.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,V.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:f,id3:g,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[le.AUDIO]={startPTS:y,endPTS:v,startDTS:E,endDTS:T}),c.setElementaryStreamInfo(le.AUDIO,y,v,E,T),this.bufferFragmentData(d,c,l,a)}if(g!=null&&(t=g.samples)!=null&&t.length){const y=oe({id:s,frag:c,details:h},g);i.trigger(m.FRAG_PARSING_METADATA,y)}if(f){const y=oe({id:s,frag:c,details:h},f);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=V.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===Ie.NOT_LOADED||i===Ie.PARTIAL){var n;if(!Se(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&&Oi(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;as({name:t,lang:s,assocLang:i,characteristics:n,audioCodec:a,channels:o},e,os)||(_i(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,re({},e))}}class un extends tt{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&&uo(s);return new ho(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){Vd(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:b.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,f=(i.edge-d)*1e3,g=Qo(i,f);if(i.requestScheduled+g<a?i.requestScheduled=a:i.requestScheduled+=g,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,A=i.lastPartIndex,D=A!==-1,L=T===S;D?L?(y=S+1,v=E?0:A):(y=T,v=E?A+1:i.maxPartIndex):y=S+1;const x=i.age,I=x+i.ageHeader;let _=Math.min(I-i.partTarget,i.targetduration*1.5);if(_>0){if(I>i.targetduration*3)this.log(`Playlist last advanced ${x.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,v=void 0;else if(s!=null&&s.tuneInGoal&&I-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${_} with playlist age: ${i.age}`),_=0;else{const C=Math.floor(_/i.targetduration);if(y+=C,v!==void 0){const F=Math.round(_%i.targetduration/i.partTarget);v+=F}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${x.toFixed(2)}s goal: ${_} skip sn ${C} to part ${v}`)}i.tuneInGoal=_}if(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,v),E||!L){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(g-o*2,g/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=uo(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,n=Ii.No),new ho(s,i,n)}checkRetry(e){const t=e.details,s=Ri(e),i=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=i||{},c=!!i&&!!o&&(n===Pe.RetryRequest||!i.resolved&&n===Pe.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=Or(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 Ol(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!Zs(r[t].attrs,e[t].attrs))return!1;return!0}function Zs(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 hn(r,e){return e.label.toLowerCase()===r.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(r.lang||"").toLowerCase())}class Zf extends un{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,f)=>{d.id=f});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!n&&c){const d=ft(c,o,os);if(d>-1)n=o[d];else{const f=ft(c,this.tracks);n=this.tracks[f]}}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:b.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&&as(e,i,os))return i;const n=ft(e,this.tracksInGroup,os);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=cd(e,t.levels,s,a,os);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=ft(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,re({},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||as(e,i,os)))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(as({name:s,lang:i,assocLang:n,characteristics:a,audioCodec:o,channels:c},u,os))return l}for(let l=0;l<t.length;l++){const u=t[l];if(Zs(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const u=t[l];if(Zs(e.attrs,u.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&_i(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 eg{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>":`
|
|
23
|
+
initSegmentChange: ${I}`);const C=new ug(s,i,t,o,u);this.configureTransmuxer(C)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:y,chunkMeta:l,state:L},e instanceof ArrayBuffer?[e]:[]);else if(g){const C=g.push(e,y,l,L);ui(C)?C.then(F=>{this.handleTransmuxComplete(F)}).catch(F=>{this.transmuxerError(F,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:b.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 Yl=100;class dg extends sn{constructor(e,t,s){super(e,t,s,"audio-stream-controller",V.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===V.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=bo(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(Yl),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,V.AUDIO));const u=this.getFwdBufferInfo(l,V.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,f=c.fragments,g=f[0].start,p=this.getLoadPosition(),y=this.flushing?p:u.end;if(this.switchingTrack&&i){const T=p;c.PTSKnown&&T<g&&(u.end>g||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=g+.05)}if(h>=d&&!this.switchingTrack&&y<f[f.length-1].start)return;let v=this.getNextFragment(y,c);if(v&&this.isLoopLoading(v,y)&&(v=this.getNextFragmentLoopLoading(v,c,u,V.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,V.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(Yl),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||(yl(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 Wl(this.hls,V.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[s.cc],g=(t=s.initSegment)==null?void 0:t.data;if(f!==void 0){const y=i?i.index:-1,v=y!==-1,E=new Yr(s.level,s.sn,s.stats.chunkCount,n.byteLength,y,v);d.push(n,g,h,"",s,i,u.totalduration,!1,E,f)}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 El,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===V.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!==V.AUDIO){!this.audioOnly&&s.type===V.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,ne({},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 b.FRAG_GAP:case b.FRAG_PARSING_ERROR:case b.FRAG_DECRYPT_ERROR:case b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(V.AUDIO,t);break;case b.AUDIO_TRACK_LOAD_ERROR:case b.AUDIO_TRACK_LOAD_TIMEOUT:case b.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 b.BUFFER_ADD_CODEC_ERROR:case b.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case b.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case b.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,V.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:f,id3:g,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(g!=null&&(t=g.samples)!=null&&t.length){const y=oe({id:s,frag:c,details:h},g);i.trigger(m.FRAG_PARSING_METADATA,y)}if(f){const y=oe({id:s,frag:c,details:h},f);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=V.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)||(Bi(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,ne({},e))}}class vn 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&&To(s);return new So(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){rf(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:b.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,f=(i.edge-d)*1e3,g=cl(i,f);if(i.requestScheduled+g<a?i.requestScheduled=a:i.requestScheduled+=g,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,A=i.lastPartIndex,D=A!==-1,_=T===S;D?_?(y=S+1,v=E?0:A):(y=T,v=E?A+1:i.maxPartIndex):y=S+1;const x=i.age,I=x+i.ageHeader;let L=Math.min(I-i.partTarget,i.targetduration*1.5);if(L>0){if(I>i.targetduration*3)this.log(`Playlist last advanced ${x.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,v=void 0;else if(s!=null&&s.tuneInGoal&&I-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${L} with playlist age: ${i.age}`),L=0;else{const C=Math.floor(L/i.targetduration);if(y+=C,v!==void 0){const F=Math.round(L%i.targetduration/i.partTarget);v+=F}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${x.toFixed(2)}s goal: ${L} skip sn ${C} to part ${v}`)}i.tuneInGoal=L}if(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,v),E||!_){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(g-o*2,g/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=To(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,n=$i.No),new So(s,i,n)}checkRetry(e){const t=e.details,s=Ui(e),i=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=i||{},c=!!i&&!!o&&(n===Ce.RetryRequest||!i.resolved&&n===Ce.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=Vr(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 ql(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 En(r,e){return e.label.toLowerCase()===r.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(r.lang||"").toLowerCase())}class fg extends vn{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,f)=>{d.id=f});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!n&&c){const d=xt(c,o,fs);if(d>-1)n=o[d];else{const f=xt(c,this.tracks);n=this.tracks[f]}}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:b.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=xt(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=_d(e,t.levels,s,a,fs);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=xt(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,ne({},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)&&Bi(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 gg{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
24
|
${this.list("video")}
|
|
25
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
|
|
27
|
-
required tracks: ${
|
|
28
|
-
transfer tracks: ${ce(i,(c,l)=>c==="initSegment"?void 0:l)}}`),!Ka(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,f=u.id;if(d.hasFragments(f)||d.hasParts(f)){const y=X.getBuffered(h);d.detectEvictedFragments(l,y,f,null,!0)}const g=dn(l),p=[l,h];this.sourceBuffers[g]=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&&Nl(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[dn(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new eg(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:f,levelCodec:g,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,A=S?.pendingCodec||S?.codec,D=S?.levelCodec;E||(E=i[c]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:p,levelCodec:g,metadata:y,id:d});const L=Ai(A,D),x=L?.replace(Ml,"$1");let I=Ai(f,g);const _=(u=I)==null?void 0:u.replace(Ml,"$1");I&&L&&x!==_&&(c.slice(0,5)==="audio"&&(I=xi(I,this.appendSource)),this.log(`switching codec ${A} to ${I}`),I!==(E.pendingCodec||E.codec)&&(E.pendingCodec=I),E.container=p,this.appendChangeType(c,p,I))}),(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,V.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&&X.isBuffered(c.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,V.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:f}=o,g=self.performance.now();h.start=g;const p=o.stats.buffering,y=c?c.stats.buffering:null;p.start===0&&(p.start=g),y&&y.start===0&&(y.start=g);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 L=c||o,x=this.blockedAudioAppend;if(n==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(T.ending||T.ended)){const _=L.start+L.duration*.05,C=S.buffered,F=this.currentOp("video");!C.length&&!F?this.blockAudio(L):!F&&!X.isBuffered(S,_)&&this.lastVideoAppendEnd<_&&this.blockAudio(L)}else if(n==="video"){const I=L.end;if(x){const _=x.frag.start;(I>_||I<this.lastVideoAppendEnd||X.isBuffered(S,_))&&this.unblockAudio()}this.lastVideoAppendEnd=I}}const A=(c||o).start,D={label:`append-${n}`,execute:()=>{var L;h.executeStart=self.performance.now();const x=(L=this.tracks[n])==null?void 0:L.buffer;x&&(E?this.updateTimestampOffset(x,A,.1,n,d,f):u!==void 0&&$(u)&&this.updateTimestampOffset(x,u,1e-6,n,d,f)),this.appendExecutor(i,n)},onStart:()=>{},onComplete:()=>{const L=self.performance.now();h.executeEnd=h.end=L,p.first===0&&(p.first=L),y&&y.first===0&&(y.first=L);const x={};this.sourceBuffers.forEach(([I,_])=>{I&&(x[I]=X.getBuffered(_))}),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:x})},onError:L=>{var x;const I={type:H.MEDIA_ERROR,parent:o.type,details:b.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:c,chunkMeta:l,error:L,err:L,fatal:!1},_=(x=this.media)==null?void 0:x.error;if(L.code===DOMException.QUOTA_EXCEEDED_ERR||L.name=="QuotaExceededError"||"quota"in L)I.details=b.BUFFER_FULL_ERROR;else if(L.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!_)I.errorAction=Ds(!0);else if(L.name===Fl&&this.sourceBufferCount===0)I.errorAction=Ds(!0);else{const C=++this.appendErrors[n];this.warn(`Failed ${C}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${_||"no media error"})`),(C>=this.hls.config.appendErrorMaxRetry||_)&&(I.fatal=!0)}this.hls.trigger(m.ERROR,I)}};this.log(`queuing "${n}" append sn: ${d}${c?" p: "+c.index:""} of ${o.type===V.MAIN?"level":"track"} ${o.level} cc: ${f}`),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[le.AUDIOVIDEO]?n.push("audiovideo"):(a[le.AUDIO]&&n.push("audio"),a[le.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===b.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=X.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=X.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}) ${ce(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:b.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":""} ${ce(o)}`);try{const u=s.addSourceBuffer(l),h=dn(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:b.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")&&Ks(s,"video")&&(i=Hh(i,s));const n=Ai(i,e.levelCodec);return n?t.slice(0,5)==="audio"?xi(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:b.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 tg(`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 Nl(r){const e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function ig(r,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}function dn(r){return r==="audio"?1:0}class fn{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,fn.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 Ke={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},rg={HLS:"h"};class pt{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof pt?s:new pt(s))),this.value=e,this.params=t}}const ng="Dict";function ag(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 og(r,e,t,s){return new Error(`failed to ${r} "${ag(e)}" as ${t}`,{cause:s})}function yt(r,e,t){return og("serialize",r,e,t)}class $l{constructor(e){this.description=e}}const Bl="Bare Item",lg="Boolean";function cg(r){if(typeof r!="boolean")throw yt(r,lg);return r?"?1":"?0"}function ug(r){return btoa(String.fromCharCode(...r))}const hg="Byte Sequence";function dg(r){if(ArrayBuffer.isView(r)===!1)throw yt(r,hg);return`:${ug(r)}:`}const fg="Integer";function gg(r){return r<-999999999999999||999999999999999<r}function Ul(r){if(gg(r))throw yt(r,fg);return r.toString()}function mg(r){return`@${Ul(r.getTime()/1e3)}`}function Gl(r,e){if(r<0)return-Gl(-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 pg="Decimal";function yg(r){const e=Gl(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw yt(r,pg);const t=e.toString();return t.includes(".")?t:`${t}.0`}const vg="String",Eg=/[\x00-\x1f\x7f]+/;function Tg(r){if(Eg.test(r))throw yt(r,vg);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Sg(r){return r.description||r.toString().slice(7,-1)}const xg="Token";function Kl(r){const e=Sg(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw yt(e,xg);return e}function gn(r){switch(typeof r){case"number":if(!$(r))throw yt(r,Bl);return Number.isInteger(r)?Ul(r):yg(r);case"string":return Tg(r);case"symbol":return Kl(r);case"boolean":return cg(r);case"object":if(r instanceof Date)return mg(r);if(r instanceof Uint8Array)return dg(r);if(r instanceof $l)return Kl(r);default:throw yt(r,Bl)}}const Ag="Key";function mn(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw yt(r,Ag);return r}function pn(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${mn(e)}`:`;${mn(e)}=${gn(t)}`).join("")}function Vl(r){return r instanceof pt?`${gn(r.value)}${pn(r.params)}`:gn(r)}function Lg(r){return`(${r.value.map(Vl).join(" ")})${pn(r.params)}`}function Ig(r,e={whitespace:!0}){if(typeof r!="object"||r==null)throw yt(r,ng);const t=r instanceof Map?r.entries():Object.entries(r),s=e?.whitespace?" ":"";return Array.from(t).map(([i,n])=>{n instanceof pt||(n=new pt(n));let a=mn(i);return n.value===!0?a+=pn(n.params):(a+="=",Array.isArray(n.value)?a+=Lg(n):a+=Vl(n)),a}).join(`,${s}`)}function Hl(r,e){return Ig(r,e)}const vt="CMCD-Object",Ee="CMCD-Request",cs="CMCD-Session",Yt="CMCD-Status",_g={br:vt,ab:vt,d:vt,ot:vt,tb:vt,tpb:vt,lb:vt,tab:vt,lab:vt,url:vt,pb:Ee,bl:Ee,tbl:Ee,dl:Ee,ltc:Ee,mtp:Ee,nor:Ee,nrr:Ee,rc:Ee,sn:Ee,sta:Ee,su:Ee,ttfb:Ee,ttfbb:Ee,ttlb:Ee,cmsdd:Ee,cmsds:Ee,smrt:Ee,df:Ee,cs:Ee,ts:Ee,cid:cs,pr:cs,sf:cs,sid:cs,st:cs,v:cs,msd:cs,bs:Yt,bsd:Yt,cdn:Yt,rtp:Yt,bg:Yt,pt:Yt,ec:Yt,e:Yt},Rg={REQUEST:Ee};function bg(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 Dg(r,e){const t={};if(!r)return t;const s=Object.keys(r),i=e?bg(e):{};return s.reduce((n,a)=>{var o;const c=_g[a]||i[a]||Rg.REQUEST,l=(o=n[c])!==null&&o!==void 0?o:n[c]={};return l[a]=r[a],n},t)}function Cg(r){return["ot","sf","st","e","sta"].includes(r)}function Pg(r){return typeof r=="number"?$(r):r!=null&&r!==""&&r!==!1}const Wl="event";function kg(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 Ki=r=>Math.round(r),yn=(r,e)=>Array.isArray(r)?r.map(t=>yn(t,e)):r instanceof pt&&typeof r.value=="string"?new pt(yn(r.value,e),r.params):(e.baseUrl&&(r=kg(r,e.baseUrl)),e.version===1?encodeURIComponent(r):r),Vi=r=>Ki(r/100)*100,wg={br:Ki,d:Ki,bl:Vi,dl:Vi,mtp:Vi,nor:(r,e)=>{let t=r;return e.version>=2&&(r instanceof pt&&typeof r.value=="string"?t=new pt([r]):typeof r=="string"&&(t=[r])),yn(t,e)},rtp:Vi,tb:Ki},Yl="request",jl="response",vn=["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"],Og=["e"],Mg=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Hi(r){return Mg.test(r)}function Fg(r){return vn.includes(r)||Og.includes(r)||Hi(r)}const ql=["d","dl","nor","ot","rtp","su"];function Ng(r){return vn.includes(r)||ql.includes(r)||Hi(r)}const $g=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function Bg(r){return vn.includes(r)||ql.includes(r)||$g.includes(r)||Hi(r)}const Ug=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Gg(r){return Ug.includes(r)||Hi(r)}const Kg={[jl]:Bg,[Wl]:Fg,[Yl]:Ng};function Xl(r,e={}){const t={};if(r==null||typeof r!="object")return t;const s=e.version||r.v||1,i=e.reportingMode||Yl,n=s===1?Gg:Kg[i];let a=Object.keys(r).filter(n);const o=e.filter;typeof o=="function"&&(a=a.filter(o));const c=i===jl||i===Wl;c&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");const l=oe({},wg,e.formatters),u={version:s,reportingMode:i,baseUrl:e.baseUrl};return a.sort().forEach(h=>{let d=r[h];const f=l[h];if(typeof f=="function"&&(d=f(d,u)),h==="v"){if(s===1)return;d=s}h=="pr"&&d===1||(c&&h==="ts"&&!$(d)&&(d=Date.now()),Pg(d)&&(Cg(h)&&typeof d=="string"&&(d=new $l(d)),t[h]=d))}),t}function Vg(r,e={}){const t={};if(!r)return t;const s=Xl(r,e),i=Dg(s,e?.customHeaderMap);return Object.entries(i).reduce((n,[a,o])=>{const c=Hl(o,{whitespace:!1});return c&&(n[a]=c),n},t)}function Hg(r,e,t){return oe(r,Vg(e,t))}const Wg="CMCD";function Yg(r,e={}){return r?Hl(Xl(r,e),{whitespace:!1}):""}function jg(r,e={}){if(!r)return"";const t=Yg(r,e);return encodeURIComponent(t)}function qg(r,e={}){if(!r)return"";const t=jg(r,e);return`${Wg}=${t}`}const zl=/CMCD=[^&#]+/;function Xg(r,e,t){const s=qg(e,t);if(!s)return r;if(zl.test(r))return r.replace(zl,s);const i=r.includes("?")?"&":"?";return`${r}${i}${s}`}class zg{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:Ke.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===Ke.VIDEO||c===Ke.AUDIO||c==Ke.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:rg.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){oe(t,this.createData());const s=t.ot===Ke.INIT||t.ot===Ke.VIDEO||t.ot===Ke.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={}),Hg(e.headers,t,n)):e.url=Xg(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 Ke.TIMED_TEXT;if(e.sn==="initSegment")return Ke.INIT;if(t==="audio")return Ke.AUDIO;if(t==="main")return this.hls.audioTracks.length?Ke.VIDEO:Ke.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===Ke.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===Ke.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:X.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 Qg=3e5;class Jg extends tt{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===Pe.SendAlternateToPenaltyBox&&s.flags===je.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===b.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: ${ce(n)} penalized: ${ce(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]>Qg&&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,tl(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}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;d&&(s[h.AUDIO]=d,h.AUDIO=d),f&&(i[h.SUBTITLES]=f,h.SUBTITLES=f);const g=Jl(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),p=new Hs({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:g,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),Ql(this.audioTracks,s,c,a),Ql(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,f)=>{this.log(`Loaded steering manifest: "${i}"`);const g=u.data;if(g?.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":v}=g;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:g,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,E),v&&this.updatePathwayPriority(v)},onError:(u,h,d,f)=>{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 g=this.timeToLoad*1e3;if(u.code===429){const p=this.loader;if(typeof p?.getResponseHeader=="function"){const y=p.getResponseHeader("Retry-After");y&&(g=parseFloat(y)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},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 Ql(r,e,t,s){r&&Object.keys(e).forEach(i=>{const n=r.filter(a=>a.groupId===i).map(a=>{const o=oe({},a);return o.details=void 0,o.attrs=new pe(o.attrs),o.url=o.attrs.URI=Jl(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 Jl(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 Ms extends tt{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=Ms.CDMCleanupPromise?[Ms.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=Ws(this.config));const o=a.map(Vr).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=ki(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 f=Le(new Uint8Array(i)),g=Gr(JSON.parse(f).sinf),p=Za(g);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(p.subarray(8,24))}catch(f){this.warn(`${n} Failed to parse sinf: ${f}`);return}const l=Ue(c),{keyIdToKeySessionPromise:u,mediaKeySessions:h}=this;let d=u[l];for(let f=0;f<h.length;f++){const g=h[f],p=g.decryptdata;if(!p.keyId)continue;const y=Ue(p.keyId);if(Br(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(g,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 Xe?o(h):o(new Xe({type:H.KEY_SYSTEM_ERROR,details:b.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 No===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=Od(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: ${ce(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(f=>f?this.setMediaKeysServerCertificate(d,e,f):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: ${Ue(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=Wi(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 ${Ue(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})=>Vr(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=Vr(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=Ws(this.config),s=e.map(ki).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=Zg(e,t[s]);if(i)return i}}loadKey(e){const t=e.keyInfo.decryptdata,s=Wi(t),i=this.bannedKeyIds[s];if(i||this.getKeyStatus(t)==="internal-error"){const o=Zl(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 Xe){const c=re({},o.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const l=new Xe(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 Xe){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Ue(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:b.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=Wi(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=ki(e.keyFormat),n=i?[i]:Ws(this.config);return this.attemptKeySystemAccess(n)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Ws(this.config)),e.length===0)throw new Xe({type:H.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ce({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>{if(!this.media)throw this.mediaKeys=null,new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});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 g=a.call(this.hls,t,s,e);if(!g)throw new Error("Invalid response from configured generateRequest filter");t=g.initDataType,s=g.initData?g.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(g){if(this.warn(g.message),this.hls&&this.hls.config.debug)throw g}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const o=Wi(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 zr,u=e._onmessage=g=>{const p=e.mediaKeysSession;if(!p){l.emit("error",new Error("invalid state"));return}const{messageType:y,message:v}=g;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,Kr("acknowledged")).then(()=>this.removeSession(e)).catch(E=>this.handleError(E)):this.warn(`unhandled media key message type "${y}"`)},h=(g,p)=>{p.keyStatus=g;let y;g.startsWith("usable")?l.emit("resolved"):g==="internal-error"||g==="output-restricted"||g==="output-downscaled"?y=Zl(g,p.decryptdata):g==="expired"?y=new Error(`key expired (keyId: ${o})`):g==="released"?y=new Error("key released"):g==="status-pending"||this.warn(`unhandled key status change "${g}" (keyId: ${o})`),y&&(l.eventNames().length?l.emit("error",y):this.handleError(y))},d=e._onkeystatuseschange=g=>{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 ${ce(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 A=this.getKeyStatus(e.decryptdata);if(A&&A!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${A} from other session.`),h(A,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 0ms`),E="internal-error",h(E,e)},0)),this.log(`No status for keyId ${o} (${ce(y)}).`)}};Ne(e.mediaKeysSession,"message",u),Ne(e.mediaKeysSession,"keystatuseschange",d);const f=new Promise((g,p)=>{l.on("error",p),l.on("resolved",g)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(g=>{throw new Xe({type:H.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_NO_SESSION,error:g,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw g}))).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);e.keySystem===ye.PLAYREADY&&n.length===16&&Fo(n);const a=Ue(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,f,g,p)=>{a(d.data)},onError:(d,f,g,p)=>{o(new Xe({type:H.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:re({url:c.url,data:void 0},d)},`"${e}" certificate request failed (${n}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,g)=>{o(new Xe({type:H.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(d,f,g)=>{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 Xe({type:H.KEY_SYSTEM_ERROR,details:b.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 Xe({type:H.KEY_SYSTEM_ERROR,details:b.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 f=(a=u.querySelector("name"))==null?void 0:a.textContent,g=(o=u.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}const c=i.querySelector("Challenge"),l=c?.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Kr(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 Xe({type:H.KEY_SYSTEM_ERROR,details:b.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,Ne(s,"encrypted",this.onMediaEncrypted),Ne(s,"waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media;e&&(Ge(e,"encrypted",this.onMediaEncrypted),Ge(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={},!this.mediaKeys&&!this.mediaKeySessions.length)return;const t=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Ys.clearKeyUriToKeyIdMap();const i=s.length;Ms.CDMCleanupPromise=Promise.all(s.map(n=>this.removeSession(n)).concat((t==null||(e=t.setMediaKeys(null))==null?void 0:e.catch(n=>{this.log(`Could not clear media keys: ${n}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:b.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${n}`)})}))||Promise.resolve())).catch(n=>{this.log(`Could not close sessions and clear media keys: ${n}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:b.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${n}`)})}).then(()=>{i&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this.keyFormatPromise=null,this.bannedKeyIds={}}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: ${Ue(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(Fd(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:b.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:b.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}}Ms.CDMCleanupPromise=void 0;function Wi(r){if(!r)throw new Error("Could not read keyId of undefined decryptdata");if(r.keyId===null)throw new Error("keyId is null");return Ue(r.keyId)}function Zg(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 Xe 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 Zl(r,e){const t=r==="output-restricted",s=t?b.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:b.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Xe({type:H.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${r}"`)}class em{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 ec(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 tc(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){ne.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){ne.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(r.mode=t)}function Fs(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 En(r,e,t,s){const i=r.mode;if(i==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){const n=sm(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 tm(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 sm(r,e,t){const s=[],i=tm(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 Yi(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 im extends un{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=Yi(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;Yi(s.textTracks).forEach(a=>{Fs(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=ft(o,a);if(u>-1)n=a[u];else{const h=ft(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||as(n,e)))return i}if(e){for(let i=0;i<t.length;i++){const n=t[i];if(Zs(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const n=t[i];if(Zs(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(hn(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&&as(e,s))return s;const i=ft(e,this.tracksInGroup);if(i>-1){const n=this.tracksInGroup[i];return this.setSubtitleTrack(i),n}else{if(s)return null;{const n=ft(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=Yi(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(n=>hn(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 rm(){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 ei(r){let e=5381,t=r.length;for(;t;)e=e*33^r.charCodeAt(--t);return(e>>>0).toString()}const Ns=.025;let ji=(function(r){return r[r.Point=0]="Point",r[r.Range=1]="Range",r})({});function nm(r,e,t){return`${r.identifier}-${t+1}-${ei(e)}`}class am{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 Tn(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=Tn(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 Tn(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)<Ns))}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"?ji.Range:ji.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 om(this)}}function Tn(r,e){return r-e.start<e.duration/2&&!(Math.abs(r-(e.start+e.duration))<Ns)?e.start:e.start+e.duration}function sc(r,e,t){const s=new self.URL(r,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function Sn(r,e){for(;(t=r.assetList[++e])!=null&&t.error;)var t;return e}function om(r){return`["${r.identifier}" ${r.cue.pre?"<pre>":r.cue.post?"<post>":""}${r.timelineStart.toFixed(2)}-${r.resumeTime.toFixed(2)}]`}function $s(r){const e=r.timelineStart,t=r.duration||0;return`["${r.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class lm{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=sc(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=X.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=X.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: ${$s(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const ic=.033;class cm extends tt{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,f=u.cue.pre,g=u.cue.post;if(h&&!f)return-1;if(f&&!h||d&&!g)return 1;if(g&&!d)return-1;if(!h&&!f&&!d&&!g){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 am(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,f=u.cue.post,g=e[h-1]||null,p=u.appendInPlace,y=f?n:u.startOffset,v=u.duration,E=u.timelineOccupancy===ji.Range?v:0,T=u.resumptionOffset,S=g?.startTime===y,A=y+u.cumulativeDuration;let D=p?A+v:y+T;if(d||!f&&y<=0){const x=l;l+=E,u.timelineStart=A;const I=a;a+=v,s.push({event:u,start:A,end:D,playout:{start:I,end:a},integrated:{start:x,end:l}})}else if(y<=n){if(!S){const _=y-c;if(_>ic){const C=c,F=l;l+=_;const N=a;a+=_;const U={previousEvent:e[h-1]||null,nextEvent:u,start:C,end:C+_,playout:{start:N,end:a},integrated:{start:F,end:l}};s.push(U)}else _>0&&g&&(g.cumulativeDuration+=_,s[s.length-1].end=y)}f&&(D=A),u.timelineStart=A;const x=l;l+=E;const I=a;a+=v,s.push({event:u,start:A,end:D,playout:{start:I,end:a},integrated:{start:x,end:l}})}else return;const L=u.resumeTime;f||L>n?c=n:c=L}),c<n){var o;const u=c,h=l,d=n-c;l+=d;const f=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:f,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=ls(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<ic&&(e[c+1].appendInPlace=!1,e[c+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=$(o.resumeOffset)?o.resumeOffset:o.duration;n+=f})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>Ns?(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=ls(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)<Ns+u||Math.abs(l.end-s)<Ns+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 at(r){return`[${r.event?'"'+r.event.identifier+'"':"primary"}: ${r.start.toFixed(2)}-${r.end.toFixed(2)}]`}class um{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=sc(s,this.hls.sessionId,e.baseUrl)}catch(d){const f=this.assignAssetListError(e,b.ASSET_LIST_LOAD_ERROR,d,s);this.hls.trigger(m.ERROR,f);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,f,g,p)=>{const y=d.data,v=y?.ASSETS;if(!Array.isArray(v)){const E=this.assignAssetListError(e,b.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,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,f,g,p)=>{const y=this.assignAssetListError(e,b.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${f.url})`),f.url,p,g);this.hls.trigger(m.ERROR,y)},onTimeout:(d,f,g)=>{const p=this.assignAssetListError(e,b.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,d,g);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 rc(r){r?.play().catch(()=>{})}function qi(r,e){return`[${r}] Advancing timeline position to ${e}`}class hm extends tt{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 f=this.findItemIndex(o);let g=this.schedule.findItemIndexAtTime(s);if(g===-1&&(g=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${s} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!a&&g>f){const p=this.schedule.findJumpRestrictedIndex(f+1,g);if(p>f){this.setSchedulePosition(p);return}}this.setSchedulePosition(g);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}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.clearInterstitial(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=>at(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let d=null,f=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 g=this.bufferingItem;if(g&&(f=this.updateItem(g,this.bufferedPos),this.itemsMatch(g,f)?this.bufferingItem=f:g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.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)>Ns&&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),g&&f!==d&&this.trimInPlace(f,g),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new um(e),this.schedule=new cm(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){Ge(e,"play",this.onPlay),Ge(e,"pause",this.onPause),Ge(e,"seeking",this.onSeeking),Ge(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;Ne(s,"seeking",this.onSeeking),Ne(s,"timeupdate",this.onTimeupdate),Ne(s,"play",this.onPlay),Ne(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,f,g,p)=>{if(h){let y=h[d].start;const v=h.event;if(v){if(d==="playout"||v.timelineOccupancy!==ji.Point){const E=s(f);E?.interstitial===v&&(y+=E.assetItem.startOffset+E[p])}}else{const E=g==="bufferedPos"?a():e[g];y+=E-h.start}return y}return 0},n=(h,d)=>{var f;if(h!==0&&d!=="primary"&&(f=e.schedule)!=null&&f.length){var g;const p=e.schedule.findItemIndexAtTime(h),y=(g=e.schedule.items)==null?void 0:g[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,f;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[h])||0},c=(h,d)=>{var f,g;const p=e.effectivePlayingItem;if(p!=null&&(f=p.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${h} "${d}"`);const y=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(h,d),E=(g=e.schedule.items)==null?void 0:g[v],T=e.getBufferingPlayer(),S=T?.interstitial,A=S?.appendInPlace,D=y&&e.itemsMatch(y,E);if(y&&(A||D)){const L=s(e.playingAsset),x=L?.media||e.primaryMedia;if(x){const I=d==="primary"?x.currentTime:i(y,d,e.playingAsset,"timelinePos","currentTime"),_=h-I,C=(A?I:x.currentTime)+_;if(C>=0&&(!L||A||C<=L.duration)){x.currentTime=C;return}}}if(E){let L=h;if(d!=="primary"){const I=E[d].start,_=h-I;L=E.start+_}const x=!e.isInterstitial(E);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(x||E.event.appendInPlace)){const I=e.media||(A?T?.media:null);I&&(I.currentTime=L)}else if(y){const I=e.findItemIndex(y);if(v>I){const C=e.schedule.findJumpRestrictedIndex(I+1,v);if(C>I){e.setSchedulePosition(C);return}}let _=0;if(x)e.timelinePos=L,e.checkBuffer();else{const C=E.event.assetList,F=h-(E[d]||E).start;for(let N=C.length;N--;){const U=C[N];if(U.duration&&F>=U.startOffset&&F<U.startOffset+U.duration){_=N;break}}}e.setSchedulePosition(v,_)}}},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 f;return i(d,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((f=e.bufferingAsset)==null?void 0:f.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(),f=e.effectivePlayingItem;f&&f===d&&c(h+f.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(f=>e.getAssetPlayer(f.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 f=e.findItemIndex(h);if(d.appendInPlace){const g=h.playout.start+h.event.duration;c(g+.001,"playout")}else e.advanceAfterAssetEnded(d,f,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} ${ce(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 g=this.getBufferingPlayer();g?(n=g.transferMedia(),u=`${g}`):u="detached MediaSource"}else u="detached media";if(!n){if(l)n=this.detachedData,this.log(`using detachedData: MediaSource ${ce(n)}`);else if(!this.detachedData||a.media===t){const g=this.playerQueue;g.length>1&&g.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 f=this.schedule;if(d===n&&f){const g=o&&e.assetId===f.assetIdAtEnd;d.overrides={duration:f.duration,endOfStream:!o||g,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(qi("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=Sn(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=Sn(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(qi("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&&at(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,f=d?this.getAssetPlayer(d):null;if(f&&d&&(!this.eventItemsMatch(a,n)||t!==void 0&&d!==u.assetList[t].identifier)){var c;const g=u.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${g+1}/${u.assetList.length} ${$s(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:g,event:u,schedule:i.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),g);return}this.retreiveMediaSource(d,n),f.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${at(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 g=(l=this.schedule)==null?void 0:l.items;if(n&&g){const p=this.findItemIndex(n);this.advanceSchedule(p,g,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 g=Sn(u,s-1);if(u.isAssetPastPlayoutLimit(g)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,e,s);return}s=g}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 ${at(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 f=u.assetList[s];if(!f){this.advanceAfterAssetEnded(u,e,s||0);return}if(d||(d=this.getAssetPlayer(f.identifier)),d===null||d.destroyed){const g=u.assetList.length;this.warn(`asset ${s+1}/${g} player destroyed ${u}`),d=this.createAssetPlayer(u,f,s),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(d,s,t,e,c),this.shouldPlay&&rc(d.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&rc(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 ${at(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(qi("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 ${at(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:X.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(qi("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=re(re({},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=re(re({},this.altSelection),{},{audio:s});return}const n=re(re({},i),{},{audio:s});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=re(re({},this.altSelection),{},{subtitles:s});return}const n=re(re({},i),{},{subtitles:s});this.mediaSelection=n}onAudioTrackSwitching(e,t){const s=mo(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=mo(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=X.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${at(e)} (was ${at(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=X.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 f=n.event;if(h-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,c>u&&c>o)this.bufferedToItem(d);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.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 ${at(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:nm(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=oe({},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 A=t.duration;A&&S<A&&(u=S)}}const h=t.identifier,d=re(re({},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 f=d.cmcd;f!=null&&f.sessionId&&f.contentId&&(d.cmcd=oe({},f,{contentId:ei(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);const g=new lm(this.HlsPlayerClass,d,e,t);this.playerQueue.push(g),e.assetList[s]=t;let p=!0;const y=S=>{if(S.live){var A;const x=new Error(`Interstitials MUST be VOD assets ${e}`),I={fatal:!0,type:H.OTHER_ERROR,details:b.INTERSTITIAL_ASSET_ITEM_ERROR,error:x},_=((A=this.schedule)==null?void 0:A.findEventIndex(e.identifier))||-1;this.handleAssetItemError(I,e,_,s,x.message);return}const D=S.edge-S.fragmentStart,L=t.duration;(p||L===null||D>L)&&(p=!1,this.log(`Interstitial asset "${h}" duration change ${L} > ${D}`),t.duration=D,this.updateSchedule())};g.on(m.LEVEL_UPDATED,(S,{details:A})=>y(A)),g.on(m.LEVEL_PTS_UPDATED,(S,{details:A})=>y(A)),g.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const v=(S,A)=>{const D=this.getAssetPlayer(h);if(D&&A.tracks){D.off(m.BUFFER_CODECS,v),D.tracks=A.tracks;const L=this.primaryMedia;this.bufferingAsset===D.assetItem&&L&&!D.media&&this.bufferAssetPlayer(D,L)}};g.on(m.BUFFER_CODECS,v);const E=()=>{var S;const A=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${A}`),!A||!this.schedule)return;const D=this.schedule.findEventIndex(e.identifier),L=(S=this.schedule.items)==null?void 0:S[D];this.isInterstitial(L)&&this.advanceAssetBuffering(L,t)};g.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 g.once(m.MEDIA_ENDED,T(s)),g.once(m.PLAYOUT_LIMIT_REACHED,T(1/0)),g.on(m.ERROR,(S,A)=>{if(!this.schedule)return;const D=this.getAssetPlayer(h);if(A.details===b.BUFFER_STALLED_ERROR){if(D!=null&&D.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(A,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${A.error} ${e}`)}),g.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const A=new Error(`Asset player destroyed unexpectedly ${h}`),D={fatal:!0,type:H.OTHER_ERROR,details:b.INTERSTITIAL_ASSET_ITEM_ERROR,error:A};this.handleAssetItemError(D,e,this.schedule.findEventIndex(e.identifier),s,A.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${$s(t)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:g}),g}clearInterstitial(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)}),e.reset()}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&&at(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} ${$s(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&&!Ka(h,e.tracks)){const d=new Error(`Asset ${$s(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),f={fatal:!0,type:H.OTHER_ERROR,details:b.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},g=n.findAssetIndex(a);this.handleAssetItemError(f,n,o,g,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===b.BUFFER_STALLED_ERROR)return;const a=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&$s(a)} ${e.error}`),!this.schedule)return;const o=a?.identifier||"",c=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[c]||null,u=this.schedule.items,h=oe({},e,{fatal:!1,errorAction:Ds(!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,f=this.bufferingAsset,g=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=g),!t.assetList.some(p=>!p.error))t.error=g;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):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${at(s)} error: ${e.error}`);let i=this.timelinePos;i===-1&&(i=this.hls.startPosition);const n=this.updateItem(s,i);if(this.itemsMatch(s,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;const a=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(a)}else this.checkStart()}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 f=(i=this.bufferingItem)==null?void 0:i.event;if(d){var g;const p=this.schedule.findEventIndex(a),y=(g=this.schedule.items)==null?void 0:g[p];if(y){if(!this.playingItem&&this.timelinePos>y.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){n.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${n}`),this.updateSchedule(!0),this.primaryFallback(n);return}this.setBufferingItem(y)}this.setSchedulePosition(p)}else if(f?.identifier===a){const p=n.assetList[0];if(p){const y=this.getAssetPlayer(p.identifier);if(f.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 b.ASSET_LIST_PARSING_ERROR:case b.ASSET_LIST_LOAD_ERROR:case b.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case b.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 nc=500;class dm extends qr{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",V.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(nc),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)||(Se(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,V.SUBTITLE)}}onError(e,t){const s=t.frag;s?.type===V.SUBTITLE&&(t.details===b.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&&Ol(this.levels,t)){this.levels=t.map(s=>new Hs(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new Hs(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,V.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(nc)}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?(Oi(a,h),l=a.fragmentStart):d&&(l=d.start,jr(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,jr(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&&(ls(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&&Ps(i.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,Ur(i.method)).catch(o=>{throw n.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:b.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=X.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,f=l.edge;let g=null;const p=this.fragPrevious;if(o<f){const E=i.maxFragLookUpTolerance,T=o>f-E?0:E;g=ls(p,h,Math.max(h[0].start,o),T),!g&&p&&p.start<h[0].start&&(g=h[0])}else g=h[d-1];if(g=this.filterReplacedPrimary(g,s.details),!g)return;const y=g.sn-l.startSN,v=h[y-1];if(v&&v.cc===g.cc&&this.fragmentTracker.getState(v)===Ie.NOT_LOADED&&(g=v),this.fragmentTracker.getState(g)===Ie.NOT_LOADED){const E=this.mapToInitFragWhenRequired(g);E&&this.loadFragment(E,s,o)}}}loadFragment(e,t,s){Se(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new fm(this.tracksBuffered[this.currentTrackId]||[])}}class fm{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 gm={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},ac=r=>String.fromCharCode(gm[r]||r),ot=15,bt=100,mm={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},pm={17:2,18:4,21:6,22:8,23:10,19:13,20:15},ym={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},vm={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Em=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Tm{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;ne.log(`${this.time} [${e}] ${s}`)}}}const us=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class oc{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 Sm{constructor(){this.uchar=" ",this.penState=new oc}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 xm{constructor(e){this.chars=[],this.pos=0,this.currPenState=new oc,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<bt;t++)this.chars.push(new Sm);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=ac(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 xn{constructor(e){this.rows=[],this.currRow=ot-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<ot;t++)this.rows.push(new xm(e));this.logger=e}reset(){for(let e=0;e<ot;e++)this.rows[e].clear();this.currRow=ot-1}equals(e){let t=!0;for(let s=0;s<ot;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<ot;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<ot;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 = "+ce(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<ot;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 = "+ce(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<ot;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 lc{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 xn(s),this.nonDisplayedMemory=new xn(s),this.lastOutputScreen=new xn(s),this.currRollUpRow=this.displayedMemory.rows[ot-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[ot-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: "+ce(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 cc{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Lm(),this.logger=void 0;const i=this.logger=new Tm;this.channels=[null,new lc(e,t,i),new lc(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,()=>"["+us([t[s],t[s+1]])+"] -> ("+us([i,n])+")");const c=this.cmdHistory;if(i>=16&&i<=31){if(Am(i,n,c)){Xi(null,null,c),this.logger.log(3,()=>"Repeated command ("+us([i,n])+") is dropped");continue}Xi(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 Xi(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 "+us([i,n])+" orig: "+us([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 ("+us([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?mm[e]:ym[e]:s=a===1?pm[e]:vm[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 '"+ac(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 = "+us(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=Em[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()}Xi(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 Xi(r,e,t){t.a=r,t.b=e}function Am(r,e,t){return t.a===r&&t.b===e}function Lm(){return{a:null,b:null}}var An=(function(){if(Pi!=null&&Pi.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="",f=!1,g=o,p=c,y=l,v=null,E="",T=!0,S="auto",A="start",D=50,L="middle",x=50,I="middle";Object.defineProperty(u,"id",n({},h,{get:function(){return d},set:function(_){d=""+_}})),Object.defineProperty(u,"pauseOnExit",n({},h,{get:function(){return f},set:function(_){f=!!_}})),Object.defineProperty(u,"startTime",n({},h,{get:function(){return g},set:function(_){if(typeof _!="number")throw new TypeError("Start time must be set to a number.");g=_,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",n({},h,{get:function(){return p},set:function(_){if(typeof _!="number")throw new TypeError("End time must be set to a number.");p=_,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",n({},h,{get:function(){return y},set:function(_){y=""+_,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",n({},h,{get:function(){return v},set:function(_){v=_,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",n({},h,{get:function(){return E},set:function(_){const C=s(_);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(_){T=!!_,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",n({},h,{get:function(){return S},set:function(_){if(typeof _!="number"&&_!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=_,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",n({},h,{get:function(){return A},set:function(_){const C=i(_);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");A=C,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",n({},h,{get:function(){return D},set:function(_){if(_<0||_>100)throw new Error("Position must be between 0 and 100.");D=_,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",n({},h,{get:function(){return L},set:function(_){const C=i(_);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");L=C,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",n({},h,{get:function(){return x},set:function(_){if(_<0||_>100)throw new Error("Size must be between 0 and 100.");x=_,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",n({},h,{get:function(){return I},set:function(_){const C=i(_);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");I=C,this.hasBeenReset=!0}})),u.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})();class Im{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function uc(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 _m{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 hc(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 Ln=new An(0,0,""),zi=Ln.align==="middle"?"middle":"center";function Rm(r,e,t){const s=r;function i(){const o=uc(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 _m;hc(o,function(d,f){let g;switch(d){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){l.set(d,t[p].region);break}break;case"vertical":l.alt(d,f,["rl","lr"]);break;case"line":g=f.split(","),l.integer(d,g[0]),l.percent(d,g[0])&&l.set("snapToLines",!1),l.alt(d,g[0],["auto"]),g.length===2&&l.alt("lineAlign",g[1],["start",zi,"end"]);break;case"position":g=f.split(","),l.percent(d,g[0]),g.length===2&&l.alt("positionAlign",g[1],["start",zi,"end","line-left","line-right","auto"]);break;case"size":l.percent(d,f);break;case"align":l.alt(d,f,["start",zi,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let u=l.get("line","auto");u==="auto"&&Ln.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",zi);let h=l.get("position","auto");h==="auto"&&Ln.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 dc(r){return r.replace(/<br(?: \/)?>/gi,`
|
|
32
|
-
`)}class
|
|
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 jl=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Xl="HlsJsTrackRemovedError";class mg extends Error{constructor(e){super(e),this.name=Xl}}class pg 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=Nh(Qt(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?oe(s,i.tracks):this.sourceBuffers.forEach(n=>{const[a]=n;a&&(s[a]=oe({},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=Qt(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,zl(s),yg(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)}}`),!za(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,f=u.id;if(d.hasFragments(f)||d.hasParts(f)){const y=X.getBuffered(h);d.detectEvictedFragments(l,y,f,null,!0)}const g=Tn(l),p=[l,h];this.sourceBuffers[g]=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&&zl(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[Tn(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new gg(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:f,levelCodec:g,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,A=S?.pendingCodec||S?.codec,D=S?.levelCodec;E||(E=i[c]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:p,levelCodec:g,metadata:y,id:d});const _=Fi(A,D),x=_?.replace(jl,"$1");let I=Fi(f,g);const L=(u=I)==null?void 0:u.replace(jl,"$1");I&&_&&x!==L&&(c.slice(0,5)==="audio"&&(I=Mi(I,this.appendSource)),this.log(`switching codec ${A} to ${I}`),I!==(E.pendingCodec||E.codec)&&(E.pendingCodec=I),E.container=p,this.appendChangeType(c,p,I))}),(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,V.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&&X.isBuffered(c.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,V.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:f}=o,g=self.performance.now();h.start=g;const p=o.stats.buffering,y=c?c.stats.buffering:null;p.start===0&&(p.start=g),y&&y.start===0&&(y.start=g);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 _=c||o,x=this.blockedAudioAppend;if(n==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(T.ending||T.ended)){const L=_.start+_.duration*.05,C=S.buffered,F=this.currentOp("video");!C.length&&!F?this.blockAudio(_):!F&&!X.isBuffered(S,L)&&this.lastVideoAppendEnd<L&&this.blockAudio(_)}else if(n==="video"){const I=_.end;if(x){const L=x.frag.start;(I>L||I<this.lastVideoAppendEnd||X.isBuffered(S,L))&&this.unblockAudio()}this.lastVideoAppendEnd=I}}const A=(c||o).start,D={label:`append-${n}`,execute:()=>{var _;h.executeStart=self.performance.now();const x=(_=this.tracks[n])==null?void 0:_.buffer;x&&(E?this.updateTimestampOffset(x,A,.1,n,d,f):u!==void 0&&$(u)&&this.updateTimestampOffset(x,u,1e-6,n,d,f)),this.appendExecutor(i,n)},onStart:()=>{},onComplete:()=>{const _=self.performance.now();h.executeEnd=h.end=_,p.first===0&&(p.first=_),y&&y.first===0&&(y.first=_);const x={};this.sourceBuffers.forEach(([I,L])=>{I&&(x[I]=X.getBuffered(L))}),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:x})},onError:_=>{var x;const I={type:H.MEDIA_ERROR,parent:o.type,details:b.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:c,chunkMeta:l,error:_,err:_,fatal:!1},L=(x=this.media)==null?void 0:x.error;if(_.code===DOMException.QUOTA_EXCEEDED_ERR||_.name=="QuotaExceededError"||"quota"in _)I.details=b.BUFFER_FULL_ERROR;else if(_.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!L)I.errorAction=Os(!0);else if(_.name===Xl&&this.sourceBufferCount===0)I.errorAction=Os(!0);else{const C=++this.appendErrors[n];this.warn(`Failed ${C}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${L||"no media error"})`),(C>=this.hls.config.appendErrorMaxRetry||L)&&(I.fatal=!0)}this.hls.trigger(m.ERROR,I)}};this.log(`queuing "${n}" append sn: ${d}${c?" p: "+c.index:""} of ${o.type===V.MAIN?"level":"track"} ${o.level} cc: ${f}`),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===b.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=X.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=X.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:b.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=Tn(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:b.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=nd(i,s));const n=Fi(i,e.levelCodec);return n?t.slice(0,5)==="audio"?Mi(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:b.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 zl(r){const e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function yg(r,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}function Tn(r){return r==="audio"?1:0}class Sn{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,Sn.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 qe={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},vg={HLS:"h"};class It{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof It?s:new It(s))),this.value=e,this.params=t}}const Eg="Dict";function Tg(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 Sg(r,e,t,s){return new Error(`failed to ${r} "${Tg(e)}" as ${t}`,{cause:s})}function Lt(r,e,t){return Sg("serialize",r,e,t)}class Ql{constructor(e){this.description=e}}const Jl="Bare Item",xg="Boolean";function Ag(r){if(typeof r!="boolean")throw Lt(r,xg);return r?"?1":"?0"}function _g(r){return btoa(String.fromCharCode(...r))}const Ig="Byte Sequence";function Lg(r){if(ArrayBuffer.isView(r)===!1)throw Lt(r,Ig);return`:${_g(r)}:`}const Rg="Integer";function bg(r){return r<-999999999999999||999999999999999<r}function Zl(r){if(bg(r))throw Lt(r,Rg);return r.toString()}function Dg(r){return`@${Zl(r.getTime()/1e3)}`}function ec(r,e){if(r<0)return-ec(-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 Cg="Decimal";function Pg(r){const e=ec(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Lt(r,Cg);const t=e.toString();return t.includes(".")?t:`${t}.0`}const kg="String",wg=/[\x00-\x1f\x7f]+/;function Og(r){if(wg.test(r))throw Lt(r,kg);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Mg(r){return r.description||r.toString().slice(7,-1)}const Fg="Token";function tc(r){const e=Mg(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Lt(e,Fg);return e}function xn(r){switch(typeof r){case"number":if(!$(r))throw Lt(r,Jl);return Number.isInteger(r)?Zl(r):Pg(r);case"string":return Og(r);case"symbol":return tc(r);case"boolean":return Ag(r);case"object":if(r instanceof Date)return Dg(r);if(r instanceof Uint8Array)return Lg(r);if(r instanceof Ql)return tc(r);default:throw Lt(r,Jl)}}const Ng="Key";function An(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw Lt(r,Ng);return r}function _n(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${An(e)}`:`;${An(e)}=${xn(t)}`).join("")}function sc(r){return r instanceof It?`${xn(r.value)}${_n(r.params)}`:xn(r)}function $g(r){return`(${r.value.map(sc).join(" ")})${_n(r.params)}`}function Bg(r,e={whitespace:!0}){if(typeof r!="object"||r==null)throw Lt(r,Eg);const t=r instanceof Map?r.entries():Object.entries(r),s=e?.whitespace?" ":"";return Array.from(t).map(([i,n])=>{n instanceof It||(n=new It(n));let a=An(i);return n.value===!0?a+=_n(n.params):(a+="=",Array.isArray(n.value)?a+=$g(n):a+=sc(n)),a}).join(`,${s}`)}function ic(r,e){return Bg(r,e)}const Rt="CMCD-Object",Se="CMCD-Request",ps="CMCD-Session",ts="CMCD-Status",Ug={br:Rt,ab:Rt,d:Rt,ot:Rt,tb:Rt,tpb:Rt,lb:Rt,tab:Rt,lab:Rt,url:Rt,pb:Se,bl:Se,tbl:Se,dl:Se,ltc:Se,mtp:Se,nor:Se,nrr:Se,rc:Se,sn:Se,sta:Se,su:Se,ttfb:Se,ttfbb:Se,ttlb:Se,cmsdd:Se,cmsds:Se,smrt:Se,df:Se,cs:Se,ts:Se,cid:ps,pr:ps,sf:ps,sid:ps,st:ps,v:ps,msd:ps,bs:ts,bsd:ts,cdn:ts,rtp:ts,bg:ts,pt:ts,ec:ts,e:ts},Gg={REQUEST:Se};function Kg(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 Vg(r,e){const t={};if(!r)return t;const s=Object.keys(r),i=e?Kg(e):{};return s.reduce((n,a)=>{var o;const c=Ug[a]||i[a]||Gg.REQUEST,l=(o=n[c])!==null&&o!==void 0?o:n[c]={};return l[a]=r[a],n},t)}function Hg(r){return["ot","sf","st","e","sta"].includes(r)}function Wg(r){return typeof r=="number"?$(r):r!=null&&r!==""&&r!==!1}const rc="event";function Yg(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),In=(r,e)=>Array.isArray(r)?r.map(t=>In(t,e)):r instanceof It&&typeof r.value=="string"?new It(In(r.value,e),r.params):(e.baseUrl&&(r=Yg(r,e.baseUrl)),e.version===1?encodeURIComponent(r):r),ir=r=>sr(r/100)*100,qg={br:sr,d:sr,bl:ir,dl:ir,mtp:ir,nor:(r,e)=>{let t=r;return e.version>=2&&(r instanceof It&&typeof r.value=="string"?t=new It([r]):typeof r=="string"&&(t=[r])),In(t,e)},rtp:ir,tb:sr},nc="request",ac="response",Ln=["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"],jg=["e"],Xg=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function rr(r){return Xg.test(r)}function zg(r){return Ln.includes(r)||jg.includes(r)||rr(r)}const oc=["d","dl","nor","ot","rtp","su"];function Qg(r){return Ln.includes(r)||oc.includes(r)||rr(r)}const Jg=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function Zg(r){return Ln.includes(r)||oc.includes(r)||Jg.includes(r)||rr(r)}const em=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function tm(r){return em.includes(r)||rr(r)}const sm={[ac]:Zg,[rc]:zg,[nc]:Qg};function lc(r,e={}){const t={};if(r==null||typeof r!="object")return t;const s=e.version||r.v||1,i=e.reportingMode||nc,n=s===1?tm:sm[i];let a=Object.keys(r).filter(n);const o=e.filter;typeof o=="function"&&(a=a.filter(o));const c=i===ac||i===rc;c&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");const l=oe({},qg,e.formatters),u={version:s,reportingMode:i,baseUrl:e.baseUrl};return a.sort().forEach(h=>{let d=r[h];const f=l[h];if(typeof f=="function"&&(d=f(d,u)),h==="v"){if(s===1)return;d=s}h=="pr"&&d===1||(c&&h==="ts"&&!$(d)&&(d=Date.now()),Wg(d)&&(Hg(h)&&typeof d=="string"&&(d=new Ql(d)),t[h]=d))}),t}function im(r,e={}){const t={};if(!r)return t;const s=lc(r,e),i=Vg(s,e?.customHeaderMap);return Object.entries(i).reduce((n,[a,o])=>{const c=ic(o,{whitespace:!1});return c&&(n[a]=c),n},t)}function rm(r,e,t){return oe(r,im(e,t))}const nm="CMCD";function am(r,e={}){return r?ic(lc(r,e),{whitespace:!1}):""}function om(r,e={}){if(!r)return"";const t=am(r,e);return encodeURIComponent(t)}function lm(r,e={}){if(!r)return"";const t=om(r,e);return`${nm}=${t}`}const cc=/CMCD=[^&#]+/;function cm(r,e,t){const s=lm(e,t);if(!s)return r;if(cc.test(r))return r.replace(cc,s);const i=r.includes("?")?"&":"?";return`${r}${i}${s}`}class um{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:qe.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===qe.VIDEO||c===qe.AUDIO||c==qe.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:vg.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){oe(t,this.createData());const s=t.ot===qe.INIT||t.ot===qe.VIDEO||t.ot===qe.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={}),rm(e.headers,t,n)):e.url=cm(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 qe.TIMED_TEXT;if(e.sn==="initSegment")return qe.INIT;if(t==="audio")return qe.AUDIO;if(t==="main")return this.hls.audioTracks.length?qe.VIDEO:qe.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===qe.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===qe.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:X.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 hm=3e5;class dm 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===Ce.SendAlternateToPenaltyBox&&s.flags===Je.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===b.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]>hm&&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,fl(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 ye(u.attrs);h["PATHWAY-ID"]=a;const d=h.AUDIO&&`${h.AUDIO}_clone_${a}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;d&&(s[h.AUDIO]=d,h.AUDIO=d),f&&(i[h.SUBTITLES]=f,h.SUBTITLES=f);const g=hc(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:g,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),uc(this.audioTracks,s,c,a),uc(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,f)=>{this.log(`Loaded steering manifest: "${i}"`);const g=u.data;if(g?.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":v}=g;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:g,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,E),v&&this.updatePathwayPriority(v)},onError:(u,h,d,f)=>{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 g=this.timeToLoad*1e3;if(u.code===429){const p=this.loader;if(typeof p?.getResponseHeader=="function"){const y=p.getResponseHeader("Retry-After");y&&(g=parseFloat(y)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},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 uc(r,e,t,s){r&&Object.keys(e).forEach(i=>{const n=r.filter(a=>a.groupId===i).map(a=>{const o=oe({},a);return o.details=void 0,o.attrs=new ye(o.attrs),o.url=o.attrs.URI=hc(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 hc(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 Us 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=Us.CDMCleanupPromise?[Us.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(Qr).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=Yi(a);if(s!=="sinf"||o!==ve.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let c;try{const f=Le(new Uint8Array(i)),g=Xr(JSON.parse(f).sinf),p=lo(g);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(p.subarray(8,24))}catch(f){this.warn(`${n} Failed to parse sinf: ${f}`);return}const l=Be(c),{keyIdToKeySessionPromise:u,mediaKeySessions:h}=this;let d=u[l];for(let f=0;f<h.length;f++){const g=h[f],p=g.decryptdata;if(!p.keyId)continue;const y=Be(p.keyId);if(Hi(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(g,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===ve.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 tt?o(h):o(new tt({type:H.KEY_SYSTEM_ERROR,details:b.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 qo===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=jd(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(f=>f?this.setMediaKeysServerCertificate(d,e,f):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: ${Be(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 ${Be(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})=>Qr(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=Qr(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(Yi).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=fm(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=dc(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 tt){const c=ne({},o.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const l=new tt(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 tt){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Be(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:b.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=nr(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=Yi(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 tt({type:H.KEY_SYSTEM_ERROR,details:b.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 g=a.call(this.hls,t,s,e);if(!g)throw new Error("Invalid response from configured generateRequest filter");t=g.initDataType,s=g.initData?g.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(g){if(this.warn(g.message),this.hls&&this.hls.config.debug)throw g}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 nn,u=e._onmessage=g=>{const p=e.mediaKeysSession;if(!p){l.emit("error",new Error("invalid state"));return}const{messageType:y,message:v}=g;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===ve.FAIRPLAY&&this.updateKeySession(e,zr("acknowledged")).then(()=>this.removeSession(e)).catch(E=>this.handleError(E)):this.warn(`unhandled media key message type "${y}"`)},h=(g,p)=>{p.keyStatus=g;let y;g.startsWith("usable")?l.emit("resolved"):g==="internal-error"||g==="output-restricted"||g==="output-downscaled"?y=dc(g,p.decryptdata):g==="expired"?y=new Error(`key expired (keyId: ${o})`):g==="released"?y=new Error("key released"):g==="status-pending"||this.warn(`unhandled key status change "${g}" (keyId: ${o})`),y&&(l.eventNames().length?l.emit("error",y):this.handleError(y))},d=e._onkeystatuseschange=g=>{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 A=this.getKeyStatus(e.decryptdata);if(A&&A!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${A} from other session.`),h(A,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 f=new Promise((g,p)=>{l.on("error",p),l.on("resolved",g)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(g=>{throw new tt({type:H.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_NO_SESSION,error:g,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw g}))).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);e.keySystem===ve.PLAYREADY&&n.length===16&&Wo(n);const a=Be(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,f,g,p)=>{a(d.data)},onError:(d,f,g,p)=>{o(new tt({type:H.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:ne({url:c.url,data:void 0},d)},`"${e}" certificate request failed (${n}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,g)=>{o(new tt({type:H.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(d,f,g)=>{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 tt({type:H.KEY_SYSTEM_ERROR,details:b.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 tt({type:H.KEY_SYSTEM_ERROR,details:b.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 f=(a=u.querySelector("name"))==null?void 0:a.textContent,g=(o=u.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}const c=i.querySelector("Challenge"),l=c?.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return zr(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 tt({type:H.KEY_SYSTEM_ERROR,details:b.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==ve.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&&(Ye(e,"encrypted",this.onMediaEncrypted),Ye(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,ms.clearKeyUriToKeyIdMap();const n=i.length;Us.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:b.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:b.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: ${Be(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(zd(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:b.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:b.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}}Us.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 Be(r.keyId)}function fm(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 tt 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 dc(r,e){const t=r==="output-restricted",s=t?b.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:b.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new tt({type:H.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${r}"`)}class gm{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 fc(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 gc(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){ae.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){ae.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(r.mode=t)}function Gs(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 Rn(r,e,t,s){const i=r.mode;if(i==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){const n=pm(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 pm(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 ym extends vn{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=>{Gs(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=xt(o,a);if(u>-1)n=a[u];else{const h=xt(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(En(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=xt(e,this.tracksInGroup);if(i>-1){const n=this.tracksInGroup[i];return this.setSubtitleTrack(i),n}else{if(s)return null;{const n=xt(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=>En(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 vm(){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 Ks=.025;let or=(function(r){return r[r.Point=0]="Point",r[r.Range=1]="Range",r})({});function Em(r,e,t){return`${r.identifier}-${t+1}-${di(e)}`}class Tm{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 bn(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=bn(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 bn(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)<Ks))}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 Sm(this)}}function bn(r,e){return r-e.start<e.duration/2&&!(Math.abs(r-(e.start+e.duration))<Ks)?e.start:e.start+e.duration}function mc(r,e,t){const s=new self.URL(r,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function Dn(r,e){for(;(t=r.assetList[++e])!=null&&t.error;)var t;return e}function Sm(r){return`["${r.identifier}" ${r.cue.pre?"<pre>":r.cue.post?"<post>":""}${r.timelineStart.toFixed(2)}-${r.resumeTime.toFixed(2)}]`}function Vs(r){const e=r.timelineStart,t=r.duration||0;return`["${r.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class xm{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=mc(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=X.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=X.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: ${Vs(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const pc=.033;class Am 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,f=u.cue.pre,g=u.cue.post;if(h&&!f)return-1;if(f&&!h||d&&!g)return 1;if(g&&!d)return-1;if(!h&&!f&&!d&&!g){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 Tm(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,f=u.cue.post,g=e[h-1]||null,p=u.appendInPlace,y=f?n:u.startOffset,v=u.duration,E=u.timelineOccupancy===or.Range?v:0,T=u.resumptionOffset,S=g?.startTime===y,A=y+u.cumulativeDuration;let D=p?A+v:y+T;if(d||!f&&y<=0){const x=l;l+=E,u.timelineStart=A;const I=a;a+=v,s.push({event:u,start:A,end:D,playout:{start:I,end:a},integrated:{start:x,end:l}})}else if(y<=n){if(!S){const L=y-c;if(L>pc){const C=c,F=l;l+=L;const N=a;a+=L;const G={previousEvent:e[h-1]||null,nextEvent:u,start:C,end:C+L,playout:{start:N,end:a},integrated:{start:F,end:l}};s.push(G)}else L>0&&g&&(g.cumulativeDuration+=L,s[s.length-1].end=y)}f&&(D=A),u.timelineStart=A;const x=l;l+=E;const I=a;a+=v,s.push({event:u,start:A,end:D,playout:{start:I,end:a},integrated:{start:x,end:l}})}else return;const _=u.resumeTime;f||_>n?c=n:c=_}),c<n){var o;const u=c,h=l,d=n-c;l+=d;const f=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:f,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<pc&&(e[c+1].appendInPlace=!1,e[c+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=$(o.resumeOffset)?o.resumeOffset:o.duration;n+=f})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>Ks?(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)<Ks+u||Math.abs(l.end-s)<Ks+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 ht(r){return`[${r.event?'"'+r.event.identifier+'"':"primary"}: ${r.start.toFixed(2)}-${r.end.toFixed(2)}]`}class _m{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=mc(s,this.hls.sessionId,e.baseUrl)}catch(d){const f=this.assignAssetListError(e,b.ASSET_LIST_LOAD_ERROR,d,s);this.hls.trigger(m.ERROR,f);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,f,g,p)=>{const y=d.data,v=y?.ASSETS;if(!Array.isArray(v)){const E=this.assignAssetListError(e,b.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,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,f,g,p)=>{const y=this.assignAssetListError(e,b.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${f.url})`),f.url,p,g);this.hls.trigger(m.ERROR,y)},onTimeout:(d,f,g)=>{const p=this.assignAssetListError(e,b.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,d,g);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 yc(r){var e;r==null||(e=r.play())==null||e.catch(()=>{})}function lr(r,e){return`[${r}] Advancing timeline position to ${e}`}class Im 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 f=this.findItemIndex(o);let g=this.schedule.findItemIndexAtTime(s);if(g===-1&&(g=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${s} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!a&&g>f){const p=this.schedule.findJumpRestrictedIndex(f+1,g);if(p>f){this.setSchedulePosition(p);return}}this.setSchedulePosition(g);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}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.clearInterstitial(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=>ht(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let d=null,f=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 g=this.bufferingItem;if(g&&(f=this.updateItem(g,this.bufferedPos),this.itemsMatch(g,f)?this.bufferingItem=f:g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.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)>Ks&&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),g&&f!==d&&this.trimInPlace(f,g),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new _m(e),this.schedule=new Am(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){Ye(e,"play",this.onPlay),Ye(e,"pause",this.onPause),Ye(e,"seeking",this.onSeeking),Ye(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,f,g,p)=>{if(h){let y=h[d].start;const v=h.event;if(v){if(d==="playout"||v.timelineOccupancy!==or.Point){const E=s(f);E?.interstitial===v&&(y+=E.assetItem.startOffset+E[p])}}else{const E=g==="bufferedPos"?a():e[g];y+=E-h.start}return y}return 0},n=(h,d)=>{var f;if(h!==0&&d!=="primary"&&(f=e.schedule)!=null&&f.length){var g;const p=e.schedule.findItemIndexAtTime(h),y=(g=e.schedule.items)==null?void 0:g[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,f;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[h])||0},c=(h,d)=>{var f,g;const p=e.effectivePlayingItem;if(p!=null&&(f=p.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${h} "${d}"`);const y=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(h,d),E=(g=e.schedule.items)==null?void 0:g[v],T=e.getBufferingPlayer(),S=T?.interstitial,A=S?.appendInPlace,D=y&&e.itemsMatch(y,E);if(y&&(A||D)){const _=s(e.playingAsset),x=_?.media||e.primaryMedia;if(x){const I=d==="primary"?x.currentTime:i(y,d,e.playingAsset,"timelinePos","currentTime"),L=h-I,C=(A?I:x.currentTime)+L;if(C>=0&&(!_||A||C<=_.duration)){x.currentTime=C;return}}}if(E){let _=h;if(d!=="primary"){const I=E[d].start,L=h-I;_=E.start+L}const x=!e.isInterstitial(E);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(x||E.event.appendInPlace)){const I=e.media||(A?T?.media:null);I&&(I.currentTime=_)}else if(y){const I=e.findItemIndex(y);if(v>I){const C=e.schedule.findJumpRestrictedIndex(I+1,v);if(C>I){e.setSchedulePosition(C);return}}let L=0;if(x)e.timelinePos=_,e.checkBuffer();else{const C=E.event.assetList,F=h-(E[d]||E).start;for(let N=C.length;N--;){const G=C[N];if(G.duration&&F>=G.startOffset&&F<G.startOffset+G.duration){L=N;break}}}e.setSchedulePosition(v,L)}}},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 f;return i(d,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((f=e.bufferingAsset)==null?void 0:f.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(),f=e.effectivePlayingItem;f&&f===d&&c(h+f.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(f=>e.getAssetPlayer(f.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 f=e.findItemIndex(h);if(d.appendInPlace){const g=h.playout.start+h.event.duration;c(g+.001,"playout")}else e.advanceAfterAssetEnded(d,f,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 g=this.getBufferingPlayer();g?(n=g.transferMedia(),u=`${g}`):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 g=this.playerQueue;g.length>1&&g.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 f=this.schedule;if(d===n&&f){const g=o&&e.assetId===f.assetIdAtEnd;d.overrides={duration:f.duration,endOfStream:!o||g,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=Dn(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=Dn(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&&ht(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,f=d?this.getAssetPlayer(d):null;if(f&&d&&(!this.eventItemsMatch(a,n)||t!==void 0&&d!==u.assetList[t].identifier)){var c;const g=u.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${g+1}/${u.assetList.length} ${Vs(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:g,event:u,schedule:i.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),g);return}this.retreiveMediaSource(d,n),f.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${ht(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 g=(l=this.schedule)==null?void 0:l.items;if(n&&g){const p=this.findItemIndex(n);this.advanceSchedule(p,g,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 g=Dn(u,s-1);if(u.isAssetPastPlayoutLimit(g)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,e,s);return}s=g}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 ${ht(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 f=u.assetList[s];if(!f){this.advanceAfterAssetEnded(u,e,s||0);return}if(d||(d=this.getAssetPlayer(f.identifier)),d===null||d.destroyed){const g=u.assetList.length;this.warn(`asset ${s+1}/${g} player destroyed ${u}`),d=this.createAssetPlayer(u,f,s),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(d,s,t,e,c),this.shouldPlay&&yc(d.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&yc(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 ${ht(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 ${ht(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:X.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=ne(ne({},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=ne(ne({},this.altSelection),{},{audio:s});return}const n=ne(ne({},i),{},{audio:s});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=ne(ne({},this.altSelection),{},{subtitles:s});return}const n=ne(ne({},i),{},{subtitles:s});this.mediaSelection=n}onAudioTrackSwitching(e,t){const s=_o(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=_o(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=X.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${ht(e)} (was ${ht(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=X.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 f=n.event;if(h-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,c>u&&c>o)this.bufferedToItem(d);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.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 ${ht(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:Em(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=oe({},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 A=t.duration;A&&S<A&&(u=S)}}const h=t.identifier,d=ne(ne({},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 f=d.cmcd;f!=null&&f.sessionId&&f.contentId&&(d.cmcd=oe({},f,{contentId:di(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);const g=new xm(this.HlsPlayerClass,d,e,t);this.playerQueue.push(g),e.assetList[s]=t;let p=!0;const y=S=>{if(S.live){var A;const x=new Error(`Interstitials MUST be VOD assets ${e}`),I={fatal:!0,type:H.OTHER_ERROR,details:b.INTERSTITIAL_ASSET_ITEM_ERROR,error:x},L=((A=this.schedule)==null?void 0:A.findEventIndex(e.identifier))||-1;this.handleAssetItemError(I,e,L,s,x.message);return}const D=S.edge-S.fragmentStart,_=t.duration;(p||_===null||D>_)&&(p=!1,this.log(`Interstitial asset "${h}" duration change ${_} > ${D}`),t.duration=D,this.updateSchedule())};g.on(m.LEVEL_UPDATED,(S,{details:A})=>y(A)),g.on(m.LEVEL_PTS_UPDATED,(S,{details:A})=>y(A)),g.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const v=(S,A)=>{const D=this.getAssetPlayer(h);if(D&&A.tracks){D.off(m.BUFFER_CODECS,v),D.tracks=A.tracks;const _=this.primaryMedia;this.bufferingAsset===D.assetItem&&_&&!D.media&&this.bufferAssetPlayer(D,_)}};g.on(m.BUFFER_CODECS,v);const E=()=>{var S;const A=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${A}`),!A||!this.schedule)return;const D=this.schedule.findEventIndex(e.identifier),_=(S=this.schedule.items)==null?void 0:S[D];this.isInterstitial(_)&&this.advanceAssetBuffering(_,t)};g.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 g.once(m.MEDIA_ENDED,T(s)),g.once(m.PLAYOUT_LIMIT_REACHED,T(1/0)),g.on(m.ERROR,(S,A)=>{if(!this.schedule)return;const D=this.getAssetPlayer(h);if(A.details===b.BUFFER_STALLED_ERROR){if(D!=null&&D.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(A,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${A.error} ${e}`)}),g.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const A=new Error(`Asset player destroyed unexpectedly ${h}`),D={fatal:!0,type:H.OTHER_ERROR,details:b.INTERSTITIAL_ASSET_ITEM_ERROR,error:A};this.handleAssetItemError(D,e,this.schedule.findEventIndex(e.identifier),s,A.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Vs(t)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:g}),g}clearInterstitial(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)}),e.reset()}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&&ht(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} ${Vs(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&&!za(h,e.tracks)){const d=new Error(`Asset ${Vs(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),f={fatal:!0,type:H.OTHER_ERROR,details:b.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},g=n.findAssetIndex(a);this.handleAssetItemError(f,n,o,g,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===b.BUFFER_STALLED_ERROR)return;const a=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Vs(a)} ${e.error}`),!this.schedule)return;const o=a?.identifier||"",c=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[c]||null,u=this.schedule.items,h=oe({},e,{fatal:!1,errorAction:Os(!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,f=this.bufferingAsset,g=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=g),!t.assetList.some(p=>!p.error))t.error=g;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):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${ht(s)} error: ${e.error}`);let i=this.timelinePos;i===-1&&(i=this.hls.startPosition);const n=this.updateItem(s,i);if(this.itemsMatch(s,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;const a=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(a)}else this.checkStart()}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 f=(i=this.bufferingItem)==null?void 0:i.event;if(d){var g;const p=this.schedule.findEventIndex(a),y=(g=this.schedule.items)==null?void 0:g[p];if(y){if(!this.playingItem&&this.timelinePos>y.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){n.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${n}`),this.updateSchedule(!0),this.primaryFallback(n);return}this.setBufferingItem(y)}this.setSchedulePosition(p)}else if(f?.identifier===a){const p=n.assetList[0];if(p){const y=this.getAssetPlayer(p.identifier);if(f.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 b.ASSET_LIST_PARSING_ERROR:case b.ASSET_LIST_LOAD_ERROR:case b.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case b.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 vc=500;class Lm extends sn{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",V.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(vc),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,V.SUBTITLE)}}onError(e,t){const s=t.frag;s?.type===V.SUBTITLE&&(t.details===b.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&&ql(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,V.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(vc)}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,tn(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,tn(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&&Fs(i.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,jr(i.method)).catch(o=>{throw n.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:b.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=X.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,f=l.edge;let g=null;const p=this.fragPrevious;if(o<f){const E=i.maxFragLookUpTolerance,T=o>f-E?0:E;g=gs(p,h,Math.max(h[0].start,o),T),!g&&p&&p.start<h[0].start&&(g=h[0])}else g=h[d-1];if(g=this.filterReplacedPrimary(g,s.details),!g)return;const y=g.sn-l.startSN,v=h[y-1];if(v&&v.cc===g.cc&&this.fragmentTracker.getState(v)===Re.NOT_LOADED&&(g=v),this.fragmentTracker.getState(g)===Re.NOT_LOADED){const E=this.mapToInitFragWhenRequired(g);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 Rm(this.tracksBuffered[this.currentTrackId]||[])}}class Rm{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 bm={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},Ec=r=>String.fromCharCode(bm[r]||r),dt=15,Gt=100,Dm={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Cm={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Pm={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},km={25:2,26:4,29:6,30:8,31:10,27:13,28:15},wm=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Om{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;ae.log(`${this.time} [${e}] ${s}`)}}}const ys=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class Tc{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 Mm{constructor(){this.uchar=" ",this.penState=new Tc}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 Fm{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Tc,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Gt;t++)this.chars.push(new Mm);this.logger=e}equals(e){for(let t=0;t<Gt;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Gt;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Gt;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>Gt&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Gt)}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=Ec(e);if(this.pos>=Gt){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<Gt;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<Gt;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 Cn{constructor(e){this.rows=[],this.currRow=dt-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<dt;t++)this.rows.push(new Fm(e));this.logger=e}reset(){for(let e=0;e<dt;e++)this.rows[e].clear();this.currRow=dt-1}equals(e){let t=!0;for(let s=0;s<dt;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<dt;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<dt;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<dt;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<dt;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 Sc{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 Cn(s),this.nonDisplayedMemory=new Cn(s),this.lastOutputScreen=new Cn(s),this.currRollUpRow=this.displayedMemory.rows[dt-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[dt-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 xc{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=$m(),this.logger=void 0;const i=this.logger=new Om;this.channels=[null,new Sc(e,t,i),new Sc(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,()=>"["+ys([t[s],t[s+1]])+"] -> ("+ys([i,n])+")");const c=this.cmdHistory;if(i>=16&&i<=31){if(Nm(i,n,c)){cr(null,null,c),this.logger.log(3,()=>"Repeated command ("+ys([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 "+ys([i,n])+" orig: "+ys([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 ("+ys([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?Dm[e]:Pm[e]:s=a===1?Cm[e]:km[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 '"+Ec(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 = "+ys(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=wm[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 Nm(r,e,t){return t.a===r&&t.b===e}function $m(){return{a:null,b:null}}var Pn=(function(){if(Wi!=null&&Wi.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="",f=!1,g=o,p=c,y=l,v=null,E="",T=!0,S="auto",A="start",D=50,_="middle",x=50,I="middle";Object.defineProperty(u,"id",n({},h,{get:function(){return d},set:function(L){d=""+L}})),Object.defineProperty(u,"pauseOnExit",n({},h,{get:function(){return f},set:function(L){f=!!L}})),Object.defineProperty(u,"startTime",n({},h,{get:function(){return g},set:function(L){if(typeof L!="number")throw new TypeError("Start time must be set to a number.");g=L,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",n({},h,{get:function(){return p},set:function(L){if(typeof L!="number")throw new TypeError("End time must be set to a number.");p=L,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",n({},h,{get:function(){return y},set:function(L){y=""+L,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",n({},h,{get:function(){return v},set:function(L){v=L,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",n({},h,{get:function(){return E},set:function(L){const C=s(L);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(L){T=!!L,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",n({},h,{get:function(){return S},set:function(L){if(typeof L!="number"&&L!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=L,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",n({},h,{get:function(){return A},set:function(L){const C=i(L);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");A=C,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",n({},h,{get:function(){return D},set:function(L){if(L<0||L>100)throw new Error("Position must be between 0 and 100.");D=L,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",n({},h,{get:function(){return _},set:function(L){const C=i(L);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");_=C,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",n({},h,{get:function(){return x},set:function(L){if(L<0||L>100)throw new Error("Size must be between 0 and 100.");x=L,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",n({},h,{get:function(){return I},set:function(L){const C=i(L);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");I=C,this.hasBeenReset=!0}})),u.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})();class Bm{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Ac(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 Um{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 _c(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 kn=new Pn(0,0,""),ur=kn.align==="middle"?"middle":"center";function Gm(r,e,t){const s=r;function i(){const o=Ac(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 Um;_c(o,function(d,f){let g;switch(d){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){l.set(d,t[p].region);break}break;case"vertical":l.alt(d,f,["rl","lr"]);break;case"line":g=f.split(","),l.integer(d,g[0]),l.percent(d,g[0])&&l.set("snapToLines",!1),l.alt(d,g[0],["auto"]),g.length===2&&l.alt("lineAlign",g[1],["start",ur,"end"]);break;case"position":g=f.split(","),l.percent(d,g[0]),g.length===2&&l.alt("positionAlign",g[1],["start",ur,"end","line-left","line-right","auto"]);break;case"size":l.percent(d,f);break;case"align":l.alt(d,f,["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"&&kn.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"&&kn.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 Ic(r){return r.replace(/<br(?: \/)?>/gi,`
|
|
32
|
+
`)}class Km{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Bm,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=Ic(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
|
|
33
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){
|
|
34
|
+
`&&++a,t.buffer=n.slice(a),o}function i(n){_c(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 Pn(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Gm(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
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+=`
|
|
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
|
|
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 Vm=/\r\n|\n\r|\n|\r/g,wn=function(e,t,s=0){return e.slice(s,s+t.length)===t},Hm=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 On(r,e,t){return di(r.toString())+di(e.toString())+di(t)}const Wm=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 Ym(r,e,t,s,i,n,a){const o=new Km,c=Qe(new Uint8Array(r)).trim().replace(Vm,`
|
|
38
38
|
`).split(`
|
|
39
|
-
`),l=[],u=e?
|
|
40
|
-
`)}),o.flush()}const
|
|
41
|
-
`:(n=s.childNodes)!=null&&n.length?yc(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function Mm(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=Dn(e,s,c)||Dn(r,s,c)||Dn(i,s,c);return l&&(o[c]=l),o},{})}function Dn(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 Cn(r,e){if(!r)return null;let t=uc(r);return t===null&&(fc.test(r)?t=Fm(r,e):gc.test(r)&&(t=Nm(r,e))),t}function Fm(r,e){const t=fc.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 Nm(r,e){const t=gc.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 Qi{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 $m{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=Sc(),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 Qi(this,"textTrack1"),t=new Qi(this,"textTrack2"),s=new Qi(this,"textTrack3"),i=new Qi(this,"textTrack4");this.cea608Parser1=new cc(1,e,t),this.cea608Parser2=new cc(3,s,i)}addCues(e,t,s,i,n){let a=!1;for(let o=n.length;o--;){const c=n[o],l=Bm(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===V.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(Tc(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,Fs(s[e]),ec(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=>{Fs(i[n]),delete i[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Sc(),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++)Fs(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(n=>n.textCodec===Rn);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(Ol(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const a=this.media,o=a?Yi(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]&&Tc(o[d],c)){h=o[d],o[d]=null;break}h&&(u=h)}if(u)Fs(u);else{const h=Ec(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===V.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===V.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===Rn?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;mc(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?st(s.initSegment.data,new Uint8Array(i)).buffer:i;km(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||mc(t,this.initPTS[e.cc],()=>{s.textCodec=Rn,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=>tc(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===V.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===V.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=>En(o[c],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>En(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 Ec(r){return r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function Tc(r,e){return!!r&&r.kind===Ec(e)&&hn(e,r)}function Bm(r,e,t,s){return Math.min(e,s)-Math.max(r,t)}function Sc(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const Um=/\s/,Gm={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++)Um.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 f=dc(l.trim()),g=_n(e,t,f);r!=null&&(h=r.cues)!=null&&h.getCueById(g)||(a=new u(e,t,f),a.id=g,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,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),i.forEach(d=>tc(r,d))),i}};function Km(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Vm=/(\d+)-(\d+)\/(\d+)/;class xc{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||jm,this.controller=new self.AbortController,this.stats=new Ir}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=Hm(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),(Js(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var d;this.response=this.loader=h;const f=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-(f-i.loading.start)),!h.ok){const{status:p,statusText:y}=h;throw new qm(y||"fetch, bad network response",p,h)}i.loading.first=f,i.total=Ym(h.headers)||i.total;const g=(d=this.callbacks)==null?void 0:d.onProgress;return g&&$(t.highWaterMark)?this.loadProgressively(h,i,e,t.highWaterMark,g):a?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{var d,f;const g=this.response;if(!g)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:g.url,data:h,code:g.status},v=(d=this.callbacks)==null?void 0:d.onProgress;v&&!$(t.highWaterMark)&&v(i,e,h,g),(f=this.callbacks)==null||f.onSuccess(y,i,e,g)}).catch(h=>{var d;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const f=h&&h.code||0,g=h?h.message:null;(d=this.callbacks)==null||d.onError({code:f,text:g},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 ol,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 Hm(r,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(oe({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function Wm(r){const e=Vm.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Ym(r){const e=r.get("Content-Range");if(e){const s=Wm(e);if($(s))return s}const t=r.get("Content-Length");if(t)return parseInt(t)}function jm(r,e){return new self.Request(r.url,e)}class qm extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const Xm=/^age:\s*[\d.]+\s*$/im;class Ac{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 Ir,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 g=u??t.response;if(g!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=t.responseType==="arraybuffer"?g.byteLength:g.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,g,t);const v={url:t.responseURL,data:g,code:l};(o=this.callbacks)==null||o.onSuccess(v,s,e,t);return}}const h=n.loadPolicy.errorRetry,d=s.retry,f={url:e.url,data:void 0,code:l};if(bi(h,d,!1,f))this.retry(h);else{var c;ne.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(bi(e,t,!0))this.retry(e);else{var s;ne.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=Or(e,s.retry),s.retry++,ne.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&&Xm.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 zm={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Qm=re(re({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:Ac,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:ud,bufferController:sg,capLevelController:fn,errorController:md,fpsController:em,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:No,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:zm},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},Jm()),{},{subtitleStreamController:dm,subtitleTrackController:im,timelineController:$m,audioStreamController:Jf,audioTrackController:Zf,emeController:Ms,cmcdController:zg,contentSteeringController:Jg,interstitialsController:hm});function Jm(){return{cueHandler:Gm,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 Zm(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=Pn(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 f=s[o].default;switch(e[o]={default:f},u){case"TimeOut":f.maxLoadTimeMs=d,f.maxTimeToFirstByteMs=d;break;case"MaxRetry":f.errorRetry.maxNumRetry=d,f.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":f.errorRetry.retryDelayMs=d,f.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=d,f.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${ce(e[o])}`)}),re(re({},s),e)}function Pn(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(Pn):Object.keys(r).reduce((e,t)=>(e[t]=Pn(r[t]),e),{}):r}function e0(r,e){const t=r.loader;t!==xc&&t!==Ac?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):Km()&&(r.loader=xc,r.progressive=!0,r.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Ji=2,t0=.1,s0=.05,i0=100;class r0 extends bo{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(i0),this.mediaSource=t.mediaSource;const s=this.media=t.media;Ne(s,"playing",this.onMediaPlaying),Ne(s,"waiting",this.onMediaWaiting),Ne(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(Ge(s,"playing",this.onMediaPlaying),Ge(s,"waiting",this.onMediaWaiting),Ge(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(!X.getBuffered(a).length){this.nudgeRetry=0;return}const h=X.bufferInfo(a,e,0),d=h.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const D=Lc(this.hls.inFlightFragments,e),L=h.len>Ji,x=!d||D||d-e>Ji&&!f.getPartialFragment(e);if(L||x)return;this.moved=!1}const g=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(h.len>0)&&!d)return;const L=Math.max(d,h.start||0)-e,I=!!(g!=null&&g.live)?g.targetduration*2:Ji,_=Zi(e,f);if(L>0&&(L<=I||_)){a.paused||this._trySkipBufferHole(_);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"&&!(g!=null&&g.live)&&Math.abs(e-(g?.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 A=X.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(A,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=X.bufferedInfo(X.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){const a=X.timeRangesToArray(i),o=X.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const c=X.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=Zi(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);const f=X.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:b.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:d,buffer:f.len,bufferInfo:f})}}}}}_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=Zi(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,V.MAIN),a=s.getFragAtPos(i,V.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 (${ce(e)})`);this.warn(a.message),t.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:b.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=X.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 g=!1;if(a===0){const p=s.getAppendedFrag(0,V.MAIN);p&&c<p.end&&(g=!0)}if(!g&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||Lc(this.hls.inFlightFragments,c))return 0;let y=!1,v=e.end;for(;v<c;){const E=Zi(v,s);if(E)v+=E.duration;else{y=!0;break}}if(y)return 0}}const f=Math.max(c+s0,a+t0);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,i.currentTime=f,!(e!=null&&e.gap)){const g=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),p={type:H.MEDIA_ERROR,details:b.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:g,reason:g.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(m.ERROR,p)}return f}}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:b.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:b.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Lc(r,e){const t=Ic(r.main);if(t&&t.start<=e)return t;const s=Ic(r.audio);return s&&s.start<=e?s:null}function Ic(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 Zi(r,e){return e.getAppendedFrag(r,V.MAIN)||e.getPartialFragment(r)}const n0=.25;function kn(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function wn(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,ce(i?re({type:i},s):s))}return n}const er=(()=>{const r=kn();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class a0{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&&Fs(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 ec(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=kn();if(a)for(let o=0;o<n.length;o++){const c=n[o].type;if(c===qe.emsg&&!s||!i)continue;const l=ml(n[o].data),u=n[o].pts;let h=u+n[o].duration;h>er&&(h=er),h-u<=0&&(h=u+n0);for(let f=0;f<l.length;f++){const g=l[f];if(!pl(g)){this.updateId3CueEnds(u,c);const p=wn(a,u,h,g,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===er&&(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===qe.audioId3&&c:i==="video"?l=u=>u.type===qe.emsg&&o:l=u=>u.type===qe.audioId3&&c||u.type===qe.emsg&&o,En(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=kn();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=wn(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 f;const v=p[y],E=(f=h[v])==null?void 0:f.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 g=e.fragments[e.fragments.length-1];if(!(u.length===0||!$(g?.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 A=T?.durationKnown||!1,D=er;const{duration:L,endDate:x}=v;if(x&&L!==null)D=E+L,A=!0;else if(v.endOnNext&&!A){const _=u.reduce((C,F)=>{if(F!==v.id){const N=l[F];if(N.class===v.class&&N.startDate>v.startDate&&(!C||v.startDate<C.startDate))return N}return C},null);_&&(D=_.startTime,A=!0)}const I=Object.keys(v.attr);for(let _=0;_<I.length;_++){const C=I[_];if(!bd(C))continue;const F=S[C];if(F)A&&!(T!=null&&T.durationKnown)?F.endTime=D:Math.abs(F.startTime-E)>.01&&(F.startTime=E,F.endTime=D);else if(o){let N=v.attr[C];Dd(C)&&(N=Va(N));const B=wn(o,E,D,{key:C,data:N},qe.dateRange);B&&(B.id=y,this.id3Track.addCue(B),S[C]=B,a&&(C==="X-ASSET-LIST"||C==="X-ASSET-URL")&&B.addEventListener("enter",this.onEventCueEnter))}}h[y]={cues:S,dateRange:v,durationKnown:A}}}}}class o0{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,f=Math.min(h,Math.max(1,d));this.changeMediaPlaybackRate(t,f)}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===b.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 l0 extends un{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:f}=u;d&&(u.audioCodec=d=xi(d,s)||void 0),f&&(f=u.videoCodec=Wh(f));const{width:g,height:p,unknownCodecs:y}=u,v=y?.length||0;if(o||(o=!!(g&&p)),c||(c=!!f),l||(l=!!d),v||d&&!this.isAudioSupported(d)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:E,"FRAME-RATE":T,"HDCP-LEVEL":S,"PATHWAY-ID":A,RESOLUTION:D,"VIDEO-RANGE":L}=h,I=`${`${A||"."}-`}${u.bitrate}-${D}-${T}-${E}-${L}-${S}`;if(n[I])if(n[I].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const _=a[I]+=1;u.attrs["PATHWAY-ID"]=new Array(_+1).join(".");const C=this.createLevel(u);n[I]=C,i.push(C)}else n[I].addGroupId("audio",h.AUDIO),n[I].addGroupId("text",h.SUBTITLES);else{const _=this.createLevel(u);n[I]=_,a[I]=1,i.push(_)}}),this.filterAndSortMediaOptions(i,t,o,c,l)}createLevel(e){const t=new Hs(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=oo(i,[])}return t}isAudioSupported(e){return Ks(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Ks(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:A})=>(!!E||!!(S&&A))&&td(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: ${ce(t.levels.map(A=>A.attrs.CODECS).filter((A,D,L)=>L.indexOf(A)===D))}`,this.warn(T),E+=` (${T})`);const S=new Error(E);this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:b.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)),_c(o)),t.subtitles&&(c=t.subtitles,_c(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 Li.indexOf(E.videoRange)-Li.indexOf(T.videoRange);if(E.videoCodec!==T.videoCodec){const S=io(E.videoCodec),A=io(T.videoCodec);if(S!==A)return A-S}if(E.uri===T.uri&&E.codecSet!==T.codecSet){const S=Si(E.codecSet),A=Si(T.codecSet);if(S!==A)return A-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 f;this._firstLevel=E;const T=d.bitrate,S=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${T}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){const A=Math.min(T,this.hls.config.abrEwmaDefaultEstimateMax);A>S&&S===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=A)}break}const g=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&&!g&&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:b.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===V.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));tl(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 _c(r){const e={};r.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function Rc(){return self.SourceBuffer||self.WebKitSourceBuffer}function bc(){if(!Kt())return!1;const e=Rc();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function c0(){if(!bc())return!1;const r=Kt();return typeof r?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>r.isTypeSupported(Vs(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(Vs(e,"audio"))))}function u0(){var r;const e=Rc();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}const h0=100;class d0 extends qr{constructor(e,t,s){super(e,t,s,"stream-controller",V.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,V.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(h0),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 f=this.getNextFragment(d,l);if(this.couldBacktrack&&!this.fragPrevious&&f&&Se(f)&&this.fragmentTracker.getState(f)!==Ie.OK){var g;const y=((g=this.backtrackFragment)!=null?g:f).sn-l.startSN,v=l.fragments[y-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,d)){if(!f.gap){const y=this.audioOnly&&!this.altAudio?le.AUDIO:le.VIDEO,v=(y===le.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,y,V.MAIN)}f=this.getNextFragmentLoopLoading(f,l,o,V.MAIN,h)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,d))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===Ie.NOT_LOADED||i===Ie.PARTIAL?Se(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,V.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;Ne(s,"playing",this.onMediaPlaying),Ne(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(Ge(s,"playing",this.onMediaPlaying),Ge(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&&!u0(),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=X.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:f}=X.bufferedInfo(h.buffered,n,0);f&&(s.currentTime=f)}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),f=this.transmuxer=this.transmuxer||new kl(this.hls,V.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=i?i.index:-1,p=g!==-1,y=new Nr(s.level,s.sn,s.stats.chunkCount,n.byteLength,g,p),v=this.initPTS[s.cc];f.push(n,h,d,l,s,i,c.totalduration,u,y,v)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio===2;if(_i(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.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=_i(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===V.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)),Se(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const a=this.media;a&&(!this._hasEnoughToStart&&X.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 b.FRAG_GAP:case b.FRAG_PARSING_ERROR:case b.FRAG_DECRYPT_ERROR:case b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(V.MAIN,t);break;case b.LEVEL_LOAD_ERROR:case b.LEVEL_LOAD_TIMEOUT:case b.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 b.BUFFER_ADD_CODEC_ERROR:case b.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case b.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 b.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!==le.AUDIO||!this.altAudio){const s=(t===le.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,V.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=X.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:f}=i,{details:g}=l,p=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=P.PARSING,f){const y=f.tracks;if(y){const S=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(l,y,S,n),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:t,tracks:y})}const v=f.initPTS,E=f.timescale,T=this.initPTS[o.cc];if($(v)&&(!T||T.baseTime!==v||T.timescale!==E)){const S=f.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&&g){p&&u.type==="audiovideo"&&this.logMuxedErr(o);const y=g.fragments[o.sn-1-g.startSN],v=o.sn===g.startSN,E=!y||o.cc>y.cc;if(i.independent!==!1){const{startPTS:T,endPTS:S,startDTS:A,endDTS:D}=u;if(c)c.elementaryStreams[u.type]={startPTS:T,endPTS:S,startDTS:A,endDTS:D};else if(u.firstKeyFrame&&u.independent&&n.id===1&&!E&&(this.couldBacktrack=!0),u.dropped&&u.independent){const L=this.getMainFwdBufferInfo(),x=(L?L.end:this.getLoadPosition())+this.config.maxBufferHole,I=u.firstKeyFramePTS?u.firstKeyFramePTS:T;if(!v&&x<I-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-(g.appliedTimelineOffset||0)>Ji&&(o.gap=!0);o.setElementaryStreamInfo(u.type,T,S,A,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[le.AUDIO]={startPTS:y,endPTS:v,startDTS:E,endDTS:T}),o.setElementaryStreamInfo(le.AUDIO,y,v,E,T),this.bufferFragmentData(p,o,c,n)}if(g&&d!=null&&d.samples.length){const y={id:t,frag:o,details:g,samples:d.samples};s.trigger(m.FRAG_PARSING_METADATA,y)}if(g&&h){const y={id:t,frag:o,details:g,samples:h.samples};s.trigger(m.FRAG_PARSING_USERDATA,y)}}logMuxedErr(e){this.warn(`${Se(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=Ai(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=V.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=V.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,V.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(X.isBuffered(e,s)?t=this.getAppendedFrag(s):X.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?ls(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 f0 extends tt{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=b.KEY_LOAD_ERROR,s,i,n){return new It({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&&(!Se(e)||!Se(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=ki(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const i=Ws(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,b.KEY_LOAD_ERROR,l))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,b.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=On(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: "+Ue(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,b.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){const i=this.emeController.loadKey(s);return(e.keyLoadPromise=i.then(n=>(e.mediaKeySessionContext=n,s))).catch(n=>{throw e.keyLoadPromise=null,"data"in n&&(n.data.frag=t),n})}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,f,g,p)=>{const{frag:y,keyInfo:v}=g,E=On(v.decryptdata);if(!y.decryptdata||v!==this.keyIdToKeyInfo[E])return o(this.createKeyLoadError(y,b.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,f,g,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,b.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),g,re({url:c.url,data:void 0},d)))},onTimeout:(d,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,b.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(d,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,b.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};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=On(s.decryptdata)||i;delete this.keyIdToKeyInfo[a],n&&n.destroy()}}function On(r){if(r.keyFormat!==Fe.FAIRPLAY){const e=r.keyId;if(e)return Ue(e)}return r.uri}function Dc(r){const{type:e}=r;switch(e){case ee.AUDIO_TRACK:return V.AUDIO;case ee.SUBTITLE_TRACK:return V.SUBTITLE;default:return V.MAIN}}function Mn(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class g0{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=oe({},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=oe({},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 f=this.getInternalLoader(h);this.resetInternalLoader(h.type);const g=l.data;u.parsing.start=performance.now(),gt.isMediaPlaylist(g)||h.type!==ee.MANIFEST?this.handleTrackOrLevelPlaylist(l,u,h,d||null,f):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=Mn(e,s),c=gt.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:f,variableList:g}=c;this.variableList=g,u.forEach(E=>{const{unknownCodecs:T}=E;if(T){const{preferManagedMediaSource:S}=this.hls.config;let{audioCodec:A,videoCodec:D}=E;for(let L=T.length;L--;){const x=T[L];Ks(x,"audio",S)?(E.audioCodec=A=A?`${A},${x}`:x,bs.audio[A.substring(0,4)]=2,T.splice(L,1)):Ks(x,"video",S)&&(E.videoCodec=D=D?`${D},${x}`:x,bs.video[D.substring(0,4)]=2,T.splice(L,1))}}});const{AUDIO:p=[],SUBTITLES:y,"CLOSED-CAPTIONS":v}=gt.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:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,s,i,n){const a=this.hls,{id:o,level:c,type:l}=s,u=Mn(e,s),h=$(c)?c:$(o)?o:0,d=Dc(s),f=gt.parseLevelPlaylist(e.data,u,h,d,0,this.variableList);if(l===ee.MANIFEST){const g={attrs:new pe({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=t.loading.start+Qo(f,0),a.trigger(m.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:u,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,i,n)}handleManifestParsingError(e,t,s,i,n){this.hls.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:b.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=b.UNKNOWN,l=!1;const u=this.getInternalLoader(e);switch(e.type){case ee.MANIFEST:c=s?b.MANIFEST_LOAD_TIMEOUT:b.MANIFEST_LOAD_ERROR,l=!0;break;case ee.LEVEL:c=s?b.LEVEL_LOAD_TIMEOUT:b.LEVEL_LOAD_ERROR,l=!1;break;case ee.AUDIO_TRACK:c=s?b.AUDIO_TRACK_LOAD_TIMEOUT:b.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ee.SUBTITLE_TRACK:c=s?b.SUBTITLE_TRACK_LOAD_TIMEOUT:b.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=re({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:f}=i,g=Mn(t,i),p=Dc(i);let y=typeof i.level=="number"&&p===V.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:b.LEVEL_PARSING_ERROR,fatal:!1,url:g,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:b.LEVEL_EMPTY_ERROR,fatal:!1,url:g,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:f,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:f});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:f});break}}}class Et{static get version(){return qs}static isMSESupported(){return bc()}static isSupported(){return c0()}static getMediaSource(){return Kt()}static get Events(){return m}static get MetadataSchema(){return qe}static get ErrorTypes(){return H}static get ErrorDetails(){return b}static get DefaultConfig(){return Et.defaultConfig?Et.defaultConfig:Qm}static set DefaultConfig(e){Et.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 zr,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=xh(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=Zm(Et.DefaultConfig,e,t);this.userConfig=e,s.progressive&&e0(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 pd(this),d=s.interstitialsController,f=d?this.interstitialsController=new d(this,Et):null,g=this.bufferController=new n(this,h),p=this.capLevelController=new a(this),y=new c(this),v=new g0(this),E=s.contentSteeringController,T=E?new E(this):null,S=this.levelController=new l0(this,T),A=new a0(this),D=new f0(this.config,this.logger),L=this.streamController=new d0(this,h,D),x=this.gapController=new r0(this,h);p.setStreamController(L),y.setStreamController(L);const I=[v,S,L];f&&I.splice(1,0,f),T&&I.splice(1,0,T),this.networkControllers=I;const _=[u,g,x,p,y,A,h];this.audioTrackController=this.createController(s.audioTrackController,I);const C=s.audioStreamController;C&&I.push(this.audioStreamController=new C(this,h,D)),this.subtitleTrackController=this.createController(s.subtitleTrackController,I);const F=s.subtitleStreamController;F&&I.push(this.subtititleStreamController=new F(this,h,D)),this.createController(s.timelineController,_),D.emeController=this.emeController=this.createController(s.emeController,_),this.cmcdController=this.createController(s.cmcdController,_),this.latencyController=this.createController(o0,_),this.coreComponents=_,I.push(l);const N=l.onErrorOut;typeof N=="function"&&this.on(m.ERROR,N,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:b.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:b.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=Lr.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={[V.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[V.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[V.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=rm()),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){ed(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=go(t);return lo(e,s,navigator.mediaCapabilities)}}Et.defaultConfig=void 0;class m0{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)},xe,ge,Cc,Fn,Pc,kc,ze,wc,Oc,Mc,Fc,Nc,$c,ti,Bc,Nn,$n,Uc,Gc,Kc,Vc,Hc,Bn,Wc,Yc;class rt{constructor(e){xe.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,xe,"m",Bc).call(this)}close(){this.state="closed",this.pc!==null&&this.pc.close(),this.restartTimeout!==null&&clearTimeout(this.restartTimeout)}}ge=rt,xe=new WeakSet,Cc=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,
|
|
39
|
+
`),l=[],u=e?tg(e.baseTime,e.timescale):0;let h="00:00.000",d=0,f=0,g,p=!0;o.oncue=function(y){const v=t[s];let E=t.ccOffset;const T=(d-u)/9e4;if(v!=null&&v.new&&(f!==void 0?E=t.ccOffset=v.start:Wm(t,s,T)),T){if(!e){g=new Error("Missing initPTS for VTT MPEGTS");return}E=T-t.presentationOffset}const S=y.endTime-y.startTime,A=et((y.startTime+E-f)*9e4,i*9e4)/9e4;y.startTime=Math.max(A,0),y.endTime=Math.max(A+S,0);const D=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(D)),y.id||(y.id=On(y.startTime,y.endTime,D)),y.endTime>0&&l.push(y)},o.onparsingerror=function(y){g=y},o.onflush=function(){if(g){a(g);return}n(l)},c.forEach(y=>{if(p)if(wn(y,"X-TIMESTAMP-MAP=")){p=!1,y.slice(16).split(",").forEach(v=>{wn(v,"LOCAL:")?h=v.slice(6):wn(v,"MPEGTS:")&&(d=parseInt(v.slice(7)))});try{f=Hm(h)/1e3}catch(v){g=v}return}else y===""&&(p=!1);o.parse(y+`
|
|
40
|
+
`)}),o.flush()}const Mn="stpp.ttml.im1t",Lc=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Rc=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,qm={left:"start",center:"center",right:"end",start:"start",end:"end"};function bc(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=>Qe(o)),a=eg(e.baseTime,1,e.timescale);try{n.forEach(o=>t(jm(o,a)))}catch(o){s(o)}}function jm(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=Dc(Fn(i,"styling","style")),l=Dc(Fn(i,"layout","region")),u=Fn(i,"body","[begin]");return[].map.call(u,h=>{const d=Cc(h,o);if(!d||!h.hasAttribute("begin"))return null;const f=$n(h.getAttribute("begin"),a),g=$n(h.getAttribute("dur"),a);let p=$n(h.getAttribute("end"),a);if(f===null)throw Pc(h);if(p===null){if(g===null)throw Pc(h);p=f+g}const y=new Pn(f-e,p-e,d);y.id=On(y.startTime,y.endTime,y.text);const v=l[h.getAttribute("region")],E=c[h.getAttribute("style")],T=Xm(v,E,c),{textAlign:S}=T;if(S){const A=qm[S];A&&(y.lineAlign=A),y.align=S}return oe(y,T),y}).filter(h=>h!==null)}function Fn(r,e,t){const s=r.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Dc(r){return r.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Cc(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?Cc(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function Xm(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=Nn(e,s,c)||Nn(r,s,c)||Nn(i,s,c);return l&&(o[c]=l),o},{})}function Nn(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function Pc(r){return new Error(`Could not parse ttml timestamp ${r}`)}function $n(r,e){if(!r)return null;let t=Ac(r);return t===null&&(Lc.test(r)?t=zm(r,e):Rc.test(r)&&(t=Qm(r,e))),t}function zm(r,e){const t=Lc.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 Qm(r,e){const t=Rc.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 Jm{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=Oc(),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 xc(1,e,t),this.cea608Parser2=new xc(3,s,i)}addCues(e,t,s,i,n){let a=!1;for(let o=n.length;o--;){const c=n[o],l=Zm(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===V.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,Gs(s[e]),fc(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=>{Gs(i[n]),delete i[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Oc(),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++)Gs(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(n=>n.textCodec===Mn);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(ql(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)Gs(u);else{const h=kc(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===V.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===V.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===Mn?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;bc(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;Ym(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||bc(t,this.initPTS[e.cc],()=>{s.textCodec=Mn,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=>gc(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===V.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===V.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=>Rn(o[c],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>Rn(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 kc(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===kc(e)&&En(e,r)}function Zm(r,e,t,s){return Math.min(e,s)-Math.max(r,t)}function Oc(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const e0=/\s/,t0={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++)e0.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 f=Ic(l.trim()),g=On(e,t,f);r!=null&&(h=r.cues)!=null&&h.getCueById(g)||(a=new u(e,t,f),a.id=g,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,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),i.forEach(d=>gc(r,d))),i}};function s0(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const i0=/(\d+)-(\d+)\/(\d+)/;class Mc{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||o0,this.controller=new self.AbortController,this.stats=new Or}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=r0(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 f=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-(f-i.loading.start)),!h.ok){const{status:p,statusText:y}=h;throw new l0(y||"fetch, bad network response",p,h)}i.loading.first=f,i.total=a0(h.headers)||i.total;const g=(d=this.callbacks)==null?void 0:d.onProgress;return g&&$(t.highWaterMark)?this.loadProgressively(h,i,e,t.highWaterMark,g):a?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{var d,f;const g=this.response;if(!g)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:g.url,data:h,code:g.status},v=(d=this.callbacks)==null?void 0:d.onProgress;v&&!$(t.highWaterMark)&&v(i,e,h,g),(f=this.callbacks)==null||f.onSuccess(y,i,e,g)}).catch(h=>{var d;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const f=h&&h.code||0,g=h?h.message:null;(d=this.callbacks)==null||d.onError({code:f,text:g},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 El,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 r0(r,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(oe({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function n0(r){const e=i0.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function a0(r){const e=r.get("Content-Range");if(e){const s=n0(e);if($(s))return s}const t=r.get("Content-Length");if(t)return parseInt(t)}function o0(r,e){return new self.Request(r.url,e)}class l0 extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const c0=/^age:\s*[\d.]+\s*$/im;class Fc{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 Or,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 g=u??t.response;if(g!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=t.responseType==="arraybuffer"?g.byteLength:g.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,g,t);const v={url:t.responseURL,data:g,code:l};(o=this.callbacks)==null||o.onSuccess(v,s,e,t);return}}const h=n.loadPolicy.errorRetry,d=s.retry,f={url:e.url,data:void 0,code:l};if(Gi(h,d,!1,f))this.retry(h);else{var c;ae.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(Gi(e,t,!0))this.retry(e);else{var s;ae.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=Vr(e,s.retry),s.retry++,ae.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&&c0.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 u0={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},h0=ne(ne({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:Fc,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Id,bufferController:pg,capLevelController:Sn,errorController:Cd,fpsController:gm,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:qo,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:u0},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},d0()),{},{subtitleStreamController:Lm,subtitleTrackController:ym,timelineController:Jm,audioStreamController:dg,audioTrackController:fg,emeController:Us,cmcdController:um,contentSteeringController:dm,interstitialsController:Im});function d0(){return{cueHandler:t0,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 f0(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=Bn(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 f=s[o].default;switch(e[o]={default:f},u){case"TimeOut":f.maxLoadTimeMs=d,f.maxTimeToFirstByteMs=d;break;case"MaxRetry":f.errorRetry.maxNumRetry=d,f.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":f.errorRetry.retryDelayMs=d,f.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=d,f.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${ue(e[o])}`)}),ne(ne({},s),e)}function Bn(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(Bn):Object.keys(r).reduce((e,t)=>(e[t]=Bn(r[t]),e),{}):r}function g0(r,e){const t=r.loader;t!==Mc&&t!==Fc?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):s0()&&(r.loader=Mc,r.progressive=!0,r.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const dr=2,m0=.1,p0=.05,y0=100;class v0 extends No{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(y0),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&&(Ye(s,"playing",this.onMediaPlaying),Ye(s,"waiting",this.onMediaWaiting),Ye(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(!X.getBuffered(a).length){this.nudgeRetry=0;return}const h=X.bufferInfo(a,e,0),d=h.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const D=Nc(this.hls.inFlightFragments,e),_=h.len>dr,x=!d||D||d-e>dr&&!f.getPartialFragment(e);if(_||x)return;this.moved=!1}const g=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(h.len>0)&&!d)return;const _=Math.max(d,h.start||0)-e,I=!!(g!=null&&g.live)?g.targetduration*2:dr,L=fr(e,f);if(_>0&&(_<=I||L)){a.paused||this._trySkipBufferHole(L);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"&&!(g!=null&&g.live)&&Math.abs(e-(g?.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 A=X.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(A,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=X.bufferedInfo(X.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){const a=X.timeRangesToArray(i),o=X.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const c=X.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 f=X.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:b.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:d,buffer:f.len,bufferInfo:f})}}}}}_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,V.MAIN),a=s.getFragAtPos(i,V.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:b.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=X.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 g=!1;if(a===0){const p=s.getAppendedFrag(0,V.MAIN);p&&c<p.end&&(g=!0)}if(!g&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||Nc(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 f=Math.max(c+p0,a+m0);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,i.currentTime=f,!(e!=null&&e.gap)){const g=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),p={type:H.MEDIA_ERROR,details:b.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:g,reason:g.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(m.ERROR,p)}return f}}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:b.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:b.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Nc(r,e){const t=$c(r.main);if(t&&t.start<=e)return t;const s=$c(r.audio);return s&&s.start<=e?s:null}function $c(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,V.MAIN)||e.getPartialFragment(r)}const E0=.25;function Un(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Gn(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?ne({type:i},s):s))}return n}const gr=(()=>{const r=Un();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class T0{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&&Gs(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 fc(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=Un();if(a)for(let o=0;o<n.length;o++){const c=n[o].type;if(c===Ze.emsg&&!s||!i)continue;const l=Rl(n[o].data),u=n[o].pts;let h=u+n[o].duration;h>gr&&(h=gr),h-u<=0&&(h=u+E0);for(let f=0;f<l.length;f++){const g=l[f];if(!bl(g)){this.updateId3CueEnds(u,c);const p=Gn(a,u,h,g,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,Rn(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=Un();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=Gn(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 f;const v=p[y],E=(f=h[v])==null?void 0:f.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 g=e.fragments[e.fragments.length-1];if(!(u.length===0||!$(g?.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 A=T?.durationKnown||!1,D=gr;const{duration:_,endDate:x}=v;if(x&&_!==null)D=E+_,A=!0;else if(v.endOnNext&&!A){const L=u.reduce((C,F)=>{if(F!==v.id){const N=l[F];if(N.class===v.class&&N.startDate>v.startDate&&(!C||v.startDate<C.startDate))return N}return C},null);L&&(D=L.startTime,A=!0)}const I=Object.keys(v.attr);for(let L=0;L<I.length;L++){const C=I[L];if(!Vd(C))continue;const F=S[C];if(F)A&&!(T!=null&&T.durationKnown)?F.endTime=D:Math.abs(F.startTime-E)>.01&&(F.startTime=E,F.endTime=D);else if(o){let N=v.attr[C];Hd(C)&&(N=Qa(N));const U=Gn(o,E,D,{key:C,data:N},Ze.dateRange);U&&(U.id=y,this.id3Track.addCue(U),S[C]=U,a&&(C==="X-ASSET-LIST"||C==="X-ASSET-URL")&&U.addEventListener("enter",this.onEventCueEnter))}}h[y]={cues:S,dateRange:v,durationKnown:A}}}}}class S0{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,f=Math.min(h,Math.max(1,d));this.changeMediaPlaybackRate(t,f)}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===b.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 x0 extends vn{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:f}=u;d&&(u.audioCodec=d=Mi(d,s)||void 0),f&&(f=u.videoCodec=ad(f));const{width:g,height:p,unknownCodecs:y}=u,v=y?.length||0;if(o||(o=!!(g&&p)),c||(c=!!f),l||(l=!!d),v||d&&!this.isAudioSupported(d)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:E,"FRAME-RATE":T,"HDCP-LEVEL":S,"PATHWAY-ID":A,RESOLUTION:D,"VIDEO-RANGE":_}=h,I=`${`${A||"."}-`}${u.bitrate}-${D}-${T}-${E}-${_}-${S}`;if(n[I])if(n[I].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const L=a[I]+=1;u.attrs["PATHWAY-ID"]=new Array(L+1).join(".");const C=this.createLevel(u);n[I]=C,i.push(C)}else n[I].addGroupId("audio",h.AUDIO),n[I].addGroupId("text",h.SUBTITLES);else{const L=this.createLevel(u);n[I]=L,a[I]=1,i.push(L)}}),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=yo(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:A})=>(!!E||!!(S&&A))&&pd(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(A=>A.attrs.CODECS).filter((A,D,_)=>_.indexOf(A)===D))}`,this.warn(T),E+=` (${T})`);const S=new Error(E);this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:b.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)),Bc(o)),t.subtitles&&(c=t.subtitles,Bc(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 Ni.indexOf(E.videoRange)-Ni.indexOf(T.videoRange);if(E.videoCodec!==T.videoCodec){const S=fo(E.videoCodec),A=fo(T.videoCodec);if(S!==A)return A-S}if(E.uri===T.uri&&E.codecSet!==T.codecSet){const S=Oi(E.codecSet),A=Oi(T.codecSet);if(S!==A)return A-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 f;this._firstLevel=E;const T=d.bitrate,S=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${T}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){const A=Math.min(T,this.hls.config.abrEwmaDefaultEstimateMax);A>S&&S===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=A)}break}const g=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&&!g&&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:b.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===V.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));fl(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 Bc(r){const e={};r.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function Uc(){return self.SourceBuffer||self.WebKitSourceBuffer}function Gc(){if(!Qt())return!1;const e=Uc();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function A0(){if(!Gc())return!1;const r=Qt();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 _0(){var r;const e=Uc();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}const I0=100;class L0 extends sn{constructor(e,t,s){super(e,t,s,"stream-controller",V.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,V.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(I0),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 f=this.getNextFragment(d,l);if(this.couldBacktrack&&!this.fragPrevious&&f&&xe(f)&&this.fragmentTracker.getState(f)!==Re.OK){var g;const y=((g=this.backtrackFragment)!=null?g:f).sn-l.startSN,v=l.fragments[y-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,d)){if(!f.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,V.MAIN)}f=this.getNextFragmentLoopLoading(f,l,o,V.MAIN,h)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,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,V.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&&(Ye(s,"playing",this.onMediaPlaying),Ye(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&&!_0(),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=X.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:f}=X.bufferedInfo(h.buffered,n,0);f&&(s.currentTime=f)}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),f=this.transmuxer=this.transmuxer||new Wl(this.hls,V.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=i?i.index:-1,p=g!==-1,y=new Yr(s.level,s.sn,s.stats.chunkCount,n.byteLength,g,p),v=this.initPTS[s.cc];f.push(n,h,d,l,s,i,c.totalduration,u,y,v)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio===2;if(Bi(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.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=Bi(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===V.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&&X.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 b.FRAG_GAP:case b.FRAG_PARSING_ERROR:case b.FRAG_DECRYPT_ERROR:case b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(V.MAIN,t);break;case b.LEVEL_LOAD_ERROR:case b.LEVEL_LOAD_TIMEOUT:case b.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 b.BUFFER_ADD_CODEC_ERROR:case b.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case b.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 b.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,V.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=X.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:f}=i,{details:g}=l,p=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=P.PARSING,f){const y=f.tracks;if(y){const S=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(l,y,S,n),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:t,tracks:y})}const v=f.initPTS,E=f.timescale,T=this.initPTS[o.cc];if($(v)&&(!T||T.baseTime!==v||T.timescale!==E)){const S=f.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&&g){p&&u.type==="audiovideo"&&this.logMuxedErr(o);const y=g.fragments[o.sn-1-g.startSN],v=o.sn===g.startSN,E=!y||o.cc>y.cc;if(i.independent!==!1){const{startPTS:T,endPTS:S,startDTS:A,endDTS:D}=u;if(c)c.elementaryStreams[u.type]={startPTS:T,endPTS:S,startDTS:A,endDTS:D};else if(u.firstKeyFrame&&u.independent&&n.id===1&&!E&&(this.couldBacktrack=!0),u.dropped&&u.independent){const _=this.getMainFwdBufferInfo(),x=(_?_.end:this.getLoadPosition())+this.config.maxBufferHole,I=u.firstKeyFramePTS?u.firstKeyFramePTS:T;if(!v&&x<I-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-(g.appliedTimelineOffset||0)>dr&&(o.gap=!0);o.setElementaryStreamInfo(u.type,T,S,A,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(g&&d!=null&&d.samples.length){const y={id:t,frag:o,details:g,samples:d.samples};s.trigger(m.FRAG_PARSING_METADATA,y)}if(g&&h){const y={id:t,frag:o,details:g,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=Fi(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=V.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=V.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,V.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(X.isBuffered(e,s)?t=this.getAppendedFrag(s):X.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 R0 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=b.KEY_LOAD_ERROR,s,i,n){return new $t({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=Yi(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,b.KEY_LOAD_ERROR,l))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,b.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=Kn(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: "+Be(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,b.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=jh(t.initSegment.data);if(a.length){const o=a[0];o.some(c=>c!==0)&&(this.log(`Using keyId found in init segment ${Be(o)}`),e.decryptdata.keyId=o,ms.setKeyIdForUri(e.decryptdata.uri,o))}}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,f,g,p)=>{const{frag:y,keyInfo:v}=g,E=Kn(v.decryptdata);if(!y.decryptdata||v!==this.keyIdToKeyInfo[E])return o(this.createKeyLoadError(y,b.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,f,g,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,b.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),g,ne({url:c.url,data:void 0},d)))},onTimeout:(d,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,b.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(d,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,b.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};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=Kn(s.decryptdata)||i;delete this.keyIdToKeyInfo[a],n&&n.destroy()}}function Kn(r){if(r.keyFormat!==Pe.FAIRPLAY){const e=r.keyId;if(e)return Be(e)}return r.uri}function Kc(r){const{type:e}=r;switch(e){case ee.AUDIO_TRACK:return V.AUDIO;case ee.SUBTITLE_TRACK:return V.SUBTITLE;default:return V.MAIN}}function Vn(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class b0{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=oe({},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=oe({},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 f=this.getInternalLoader(h);this.resetInternalLoader(h.type);const g=l.data;u.parsing.start=performance.now(),At.isMediaPlaylist(g)||h.type!==ee.MANIFEST?this.handleTrackOrLevelPlaylist(l,u,h,d||null,f):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=Vn(e,s),c=At.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:f,variableList:g}=c;this.variableList=g,u.forEach(E=>{const{unknownCodecs:T}=E;if(T){const{preferManagedMediaSource:S}=this.hls.config;let{audioCodec:A,videoCodec:D}=E;for(let _=T.length;_--;){const x=T[_];ti(x,"audio",S)?(E.audioCodec=A=A?`${A},${x}`:x,ws.audio[A.substring(0,4)]=2,T.splice(_,1)):ti(x,"video",S)&&(E.videoCodec=D=D?`${D},${x}`:x,ws.video[D.substring(0,4)]=2,T.splice(_,1))}}});const{AUDIO:p=[],SUBTITLES:y,"CLOSED-CAPTIONS":v}=At.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 ye({}),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:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,s,i,n){const a=this.hls,{id:o,level:c,type:l}=s,u=Vn(e,s),h=$(c)?c:$(o)?o:0,d=Kc(s),f=At.parseLevelPlaylist(e.data,u,h,d,0,this.variableList);if(l===ee.MANIFEST){const g={attrs:new ye({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=t.loading.start+cl(f,0),a.trigger(m.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:u,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,i,n)}handleManifestParsingError(e,t,s,i,n){this.hls.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:b.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=b.UNKNOWN,l=!1;const u=this.getInternalLoader(e);switch(e.type){case ee.MANIFEST:c=s?b.MANIFEST_LOAD_TIMEOUT:b.MANIFEST_LOAD_ERROR,l=!0;break;case ee.LEVEL:c=s?b.LEVEL_LOAD_TIMEOUT:b.LEVEL_LOAD_ERROR,l=!1;break;case ee.AUDIO_TRACK:c=s?b.AUDIO_TRACK_LOAD_TIMEOUT:b.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ee.SUBTITLE_TRACK:c=s?b.SUBTITLE_TRACK_LOAD_TIMEOUT:b.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=ne({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:f}=i,g=Vn(t,i),p=Kc(i);let y=typeof i.level=="number"&&p===V.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:b.LEVEL_PARSING_ERROR,fatal:!1,url:g,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:b.LEVEL_EMPTY_ERROR,fatal:!1,url:g,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:f,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:f});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:f});break}}}class bt{static get version(){return ai}static isMSESupported(){return Gc()}static isSupported(){return A0()}static getMediaSource(){return Qt()}static get Events(){return m}static get MetadataSchema(){return Ze}static get ErrorTypes(){return H}static get ErrorDetails(){return b}static get DefaultConfig(){return bt.defaultConfig?bt.defaultConfig:h0}static set DefaultConfig(e){bt.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 nn,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=Fh(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=f0(bt.DefaultConfig,e,t);this.userConfig=e,s.progressive&&g0(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 Pd(this),d=s.interstitialsController,f=d?this.interstitialsController=new d(this,bt):null,g=this.bufferController=new n(this,h),p=this.capLevelController=new a(this),y=new c(this),v=new b0(this),E=s.contentSteeringController,T=E?new E(this):null,S=this.levelController=new x0(this,T),A=new T0(this),D=new R0(this.config,this.logger),_=this.streamController=new L0(this,h,D),x=this.gapController=new v0(this,h);p.setStreamController(_),y.setStreamController(_);const I=[v,S,_];f&&I.splice(1,0,f),T&&I.splice(1,0,T),this.networkControllers=I;const L=[u,g,x,p,y,A,h];this.audioTrackController=this.createController(s.audioTrackController,I);const C=s.audioStreamController;C&&I.push(this.audioStreamController=new C(this,h,D)),this.subtitleTrackController=this.createController(s.subtitleTrackController,I);const F=s.subtitleStreamController;F&&I.push(this.subtititleStreamController=new F(this,h,D)),this.createController(s.timelineController,L),D.emeController=this.emeController=this.createController(s.emeController,L),this.cmcdController=this.createController(s.cmcdController,L),this.latencyController=this.createController(S0,L),this.coreComponents=L,I.push(l);const N=l.onErrorOut;typeof N=="function"&&this.on(m.ERROR,N,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:b.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:b.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=wr.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={[V.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[V.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[V.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=vm()),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=Ao(t);return vo(e,s,navigator.mediaCapabilities)}}bt.defaultConfig=void 0;class D0{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)},Ae,me,Vc,Hn,Hc,Wc,st,Yc,qc,jc,Xc,zc,Qc,fi,Jc,Wn,Yn,Zc,eu,tu,su,iu,qn,ru,nu;class at{constructor(e){Ae.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,Ae,"m",Jc).call(this)}close(){this.state="closed",this.pc!==null&&this.pc.close(),this.restartTimeout!==null&&clearTimeout(this.restartTimeout)}}me=at,Ae=new WeakSet,Vc=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",st).call(this,l);const u=c[1].split(`\r
|
|
43
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
44
|
`),o.sdp=c.join(`m=${n}`),i.setLocalDescription(o)}).then(()=>i.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:`v=0\r
|
|
45
45
|
o=- 6539324223450680508 0 IN IP4 0.0.0.0\r
|
|
@@ -54,28 +54,20 @@ a=sendonly\r
|
|
|
54
54
|
a=rtcp-mux\r
|
|
55
55
|
a=rtpmap:${a} ${e}\r
|
|
56
56
|
`+(t!==void 0?`a=fmtp:${a} ${t}\r
|
|
57
|
-
`:"")}))).then(()=>{s(!0)}).catch(()=>{s(!1)}).finally(()=>{i.close()})})},
|
|
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},
|
|
59
|
-
`);let i=Q(this,
|
|
60
|
-
`)},
|
|
61
|
-
`);let i=Q(this,
|
|
62
|
-
`)},
|
|
63
|
-
`);let i=Q(this,
|
|
64
|
-
`)},
|
|
57
|
+
`:"")}))).then(()=>{s(!0)}).catch(()=>{s(!1)}).finally(()=>{i.close()})})},Hn=function(e){return JSON.parse(`"${e}"`)},Hc=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",Hn).call(this,s[3]),i.credential=Q(this,me,"m",Hn).call(this,s[4]),i.credentialType="password"),i}):[]},Wc=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},st=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")},Yc=function(e,t){const s=t.split(`\r
|
|
59
|
+
`);let i=Q(this,me,"m",st).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",st).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
|
+
`)},qc=function(e,t){const s=t.split(`\r
|
|
61
|
+
`);let i=Q(this,me,"m",st).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",st).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",st).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",st).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",st).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",st).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
|
+
`)},jc=function(e,t){const s=t.split(`\r
|
|
63
|
+
`);let i=Q(this,me,"m",st).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",st).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",st).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
|
+
`)},Xc=function(e){let t="";const s=e.split(`\r
|
|
65
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
|
-
`)},
|
|
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,
|
|
66
|
+
`)},zc=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",Xc).call(this,s[n]),t.includes("pcma/8000/2")&&(s[n]=Q(this,me,"m",Yc).call(this,i,s[n])),t.includes("multiopus/48000/6")&&(s[n]=Q(this,me,"m",qc).call(this,i,s[n])),t.includes("L16/48000/2")&&(s[n]=Q(this,me,"m",jc).call(this,i,s[n]));break}return s.join("m=")},Qc=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
68
|
a=ice-pwd:${e.icePwd}\r
|
|
69
69
|
`,n=0;for(const a of e.medias){if(s[n]!==void 0){i+=`m=${a}\r
|
|
70
70
|
a=mid:${n}\r
|
|
71
71
|
`;for(const o of s[n])i+=`a=${o.candidate}\r
|
|
72
|
-
`}n++}return i},ti=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,xe,"m",Nn).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))},Bc=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(rt,ge,"m",Cc).call(rt,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,xe,"m",Nn).call(this)}).catch(e=>{Q(this,xe,"m",ti).call(this,e)})},Nn=function(){Q(this,xe,"m",Uc).call(this).then(e=>Q(this,xe,"m",Gc).call(this,e)).then(e=>Q(this,xe,"m",Kc).call(this,e)).then(e=>Q(this,xe,"m",Vc).call(this,e)).catch(e=>{Q(this,xe,"m",ti).call(this,e.toString())})},$n=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}`}:{}},Uc=function(){return fetch(this.conf.url,{method:"OPTIONS",headers:Q(this,xe,"m",$n).call(this)}).then(e=>Q(rt,ge,"m",Pc).call(rt,e.headers.get("Link")))},Gc=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,xe,"m",Hc).call(this,s),this.pc.onconnectionstatechange=()=>Q(this,xe,"m",Wc).call(this),this.pc.ontrack=s=>Q(this,xe,"m",Yc).call(this,s),this.pc.createOffer().then(s=>{if(!s.sdp)throw new Error("SDP not present");return s.sdp=Q(rt,ge,"m",Nc).call(rt,s.sdp,this.nonAdvertisedCodecs),this.offerData=Q(rt,ge,"m",kc).call(rt,s.sdp),this.pc.setLocalDescription(s).then(()=>s.sdp)})},Kc=function(e){if(this.state!=="running")throw new Error("closed");return fetch(this.conf.url,{method:"POST",headers:{...Q(this,xe,"m",$n).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()})},Vc=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,xe,"m",Bn).call(this,this.queuedCandidates),this.queuedCandidates=[])})},Hc=function(e){this.state==="running"&&e.candidate!==null&&(this.sessionUrl===null?this.queuedCandidates.push(e.candidate):Q(this,xe,"m",Bn).call(this,[e.candidate]))},Bn=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(rt,ge,"m",$c).call(rt,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,xe,"m",ti).call(this,t.toString())})},Wc=function(){this.state==="running"&&this.pc&&(this.pc.connectionState==="failed"||this.pc.connectionState==="closed")&&Q(this,xe,"m",ti).call(this,"peer connection closed")},Yc=function(e){this.conf.onTrack!==void 0&&this.conf.onTrack(e)};var p0=Ut('<video id="video" part="video" class="video svelte-1ci041j" autoplay><track kind="captions" src="" srclang="en" label="English" default/></video>',2),y0=Ut('<div style="flex: 1"><div class="subsection svelte-1ci041j"><div><!></div></div></div> <div style="flex:1"><div class="subsection svelte-1ci041j"><div style="flex:1"><div class="subsection svelte-1ci041j"><div><!></div></div></div> <div style="flex:1"><div class="subsection svelte-1ci041j"><div><!></div></div></div></div></div>',1),v0=Ut('<div style="flex: 1"><div class="subsection svelte-1ci041j"><div><!></div></div></div> <div style="flex:1"><div class="subsection svelte-1ci041j"><div style="flex:1"><div class="subsection svelte-1ci041j"><div><!></div></div></div></div></div>',1),E0=Ut('<div style="flex: 1"><div class="subsection svelte-1ci041j"><div><!></div></div></div>'),T0=Ut('<div part="replacewithtext" class="replacetext video svelte-1ci041j"><!></div>'),S0=Ut('<div class="replacetext video svelte-1ci041j" part="replacewithtext">offline</div>'),x0=Ut('<div class="replacetext video svelte-1ci041j" part="replacewithtext">nouri</div>'),A0=Ut('<div part="container" style="width: 100%;position:relative"><!> <!></div>');const L0={hash:"svelte-1ci041j",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-1ci041j {position:absolute;width:100%;height:100%;top:0px;}.video.svelte-1ci041j {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-1ci041j {display:flex;height:100%;align-items:center;justify-content:center;flex-direction:column;}'};function jc(r,e){Zn(e,!0),lh(r,L0);/**
|
|
73
|
-
* Svelte Video Gallery WebComponent
|
|
74
|
-
* =====================
|
|
75
|
-
*
|
|
76
|
-
* @contributors: Dario Caruso <dev@dariocaruso.info> (https://dariocaruso.info)
|
|
77
|
-
*
|
|
78
|
-
* @license: MIT License
|
|
79
|
-
*
|
|
80
|
-
*/let t=_s(e,"id",7,""),s=_s(e,"mediauri"),i=_s(e,"forcecover",7,void 0),n=_s(e,"media_type",7,"auto"),a=_s(e,"no_controls",7,!1),o=_s(e,"replacewithtext",7,void 0),c=Be(void 0),l=Be(!1),u=Be(void 0),h=Be(void 0),d=Be(void 0),f=Be(void 0);ya(()=>{if(a()&&a()!=="no"&&a()!=="false"&&a(!0),typeof o()=="string")try{o(JSON.parse(o()))}catch{}s()&&ae(f)&&s()!==ae(f)&&(he(f,s(),!0),ae(h)&&(ae(h).close(),he(h,void 0)),he(l,!1),he(c,void 0),ae(d)&&p(ae(d)),y().catch(()=>{console.error("merr")}).then(()=>{console.log("start live checker")}))});function g(x,I){e.$$host.dispatchEvent(new CustomEvent(x,{detail:I}))}function p(x){if(console.log("setttviiiii",n()),he(d,x,!0),g("htmlVideoInit",{htmlVideoElement:ae(d),id:t()}),n()==="hls")if(x&&Et.isSupported()){const I=new Et({});I.loadSource(s()),I.attachMedia(x),I.on(Et.Events.MEDIA_ATTACHED,function(){x.muted=!0;try{x.play()}catch(_){console.error("cannot autoplay",_)}})}else x?.canPlayType("application/vnd.apple.mpegurl")?(console.log("without Media Source Extensions"),x.src=s(),x.muted=!0,x.addEventListener("canplay",function(){try{x.play()}catch(I){console.error("cannot autoplay",I)}})):console.error("no hls support");else if(n()==="whep"){console.info("whep",s());try{let I=function(){console.info("offline whep"),g("liveStatus",{live:!1,id:t()}),he(l,!1)},_=function(C){console.info("online whep"),x.srcObject=C?.streams?.[0],g("liveStatus",{live:!0,id:t()}),he(l,!0)};console.info("whep",s()),he(h,new rt({url:s(),onTrack:_,onError:I}),!0);try{x.muted=!0,x.play()}catch(C){console.error("cannot autoplay whep",C)}}catch(I){console.error("whep error ....",I)}}else if(n()==="webrtc"){console.info("webrtc",s());try{let I=function(){g("liveStatus",{live:!1,id:t()}),he(l,!1)},_=function(){g("liveStatus",{live:!0,id:t()}),he(l,!0)};he(u,new m0({videoElement:x,wsUri:s(),onOnline:_,onOffline:I}),!0),ae(u).start();try{x.muted=!0,x.play()}catch(C){console.error("cannot autoplay webrtc",C)}}catch(I){console.error("webrtc error ....",I)}}else console.error("unknown media type",n())}async function y(){function x(){console.log("reloading",ae(l),s()),(!ae(l)||!s())&&y().catch(I=>{console.error("reload uri",I)})}try{if(!s()){he(c,setTimeout(x,5e3),!0);return}if(n()==="hls"){console.info("checking live");const I=await fetch(s());if(!I||I.status&&(I.status>299||I.status<199))throw new Error("wrong uri");he(l,!0),g("liveStatus",{live:!0,id:t()})}else throw new Error("wrong media type")}catch{ae(l)!==!1&&g("liveStatus",{live:!1,id:t()}),he(l,!1),he(c,setTimeout(x,5e3),!0)}}e.$$host.getVideoElement=()=>{if(ae(d))return ae(d)},oh(()=>(he(f,s(),!0),y().catch(()=>{console.error("merr")}).then(()=>{console.log("start live checker")}),()=>{console.log("destroying player"),ae(c)&&(console.log("destroy live checker"),clearTimeout(ae(c))),ae(h)&&ae(h).close()}));var v={get id(){return t()},set id(x=""){t(x),Qt()},get mediauri(){return s()},set mediauri(x){s(x),Qt()},get forcecover(){return i()},set forcecover(x=void 0){i(x),Qt()},get media_type(){return n()},set media_type(x="auto"){n(x),Qt()},get no_controls(){return a()},set no_controls(x=!1){a(x),Qt()},get replacewithtext(){return o()},set replacewithtext(x=void 0){o(x),Qt()}},E=A0(),T=fe(E);{var S=x=>{var I=p0();ch(I,_=>p?.(_)),ts(()=>I.controls=!a()),ve(x,I)};ns(T,x=>{s()&&n()&&x(S)})}var A=fi(T,2);{var D=x=>{var I=T0(),_=fe(I);{var C=N=>{var U=rs(),B=St(U);Lt(B,e,"replacewithtext",{},w=>{var G=y0(),O=St(G),K=fe(O),W=fe(K),M=fe(W);Lt(M,e,"replacetitle",{},Dt=>{var ke=As();ts(()=>Ls(ke,o()?.title||"")),ve(Dt,ke)}),de(W),de(K),de(O);var k=fi(O,2),Y=fe(k),Z=fe(Y),q=fe(Z),z=fe(q),me=fe(z);Lt(me,e,"replacesubtitle",{},Dt=>{var ke=As();ts(()=>Ls(ke,o()?.subtitle||"")),ve(Dt,ke)}),de(z),de(q),de(Z);var ue=fi(Z,2),Ae=fe(ue),Re=fe(Ae),$e=fe(Re);Lt($e,e,"replacetext",{},Dt=>{var ke=As();ts(()=>Ls(ke,o()?.text||"")),ve(Dt,ke)}),de(Re),de(Ae),de(ue),de(Y),de(k),ve(w,G)}),ve(N,U)},F=N=>{var U=rs(),B=St(U);{var w=O=>{var K=rs(),W=St(K);Lt(W,e,"replacewithtext",{},M=>{var k=v0(),Y=St(k),Z=fe(Y),q=fe(Z),z=fe(q);Lt(z,e,"replacetitle",{},ke=>{var Ct=As();ts(()=>Ls(Ct,o()?.title||"")),ve(ke,Ct)}),de(q),de(Z),de(Y);var me=fi(Y,2),ue=fe(me),Ae=fe(ue),Re=fe(Ae),$e=fe(Re),Dt=fe($e);Lt(Dt,e,"replacesubtitle",{},ke=>{var Ct=As();ts(()=>Ls(Ct,o()?.subtitle||"")),ve(ke,Ct)}),de($e),de(Re),de(Ae),de(ue),de(me),ve(M,k)}),ve(O,K)},G=O=>{var K=rs(),W=St(K);{var M=k=>{var Y=rs(),Z=St(Y);Lt(Z,e,"replacewithtext",{},q=>{var z=E0(),me=fe(z),ue=fe(me),Ae=fe(ue);Lt(Ae,e,"replacetitle",{},Re=>{var $e=As();ts(()=>Ls($e,o()?.title||"")),ve(Re,$e)}),de(ue),de(me),de(z),ve(q,z)}),ve(k,Y)};ns(W,k=>{o()?.title&&k(M)},!0)}ve(O,K)};ns(B,O=>{o()?.title&&o()?.subtitle?O(w):O(G,!1)},!0)}ve(N,U)};ns(_,N=>{o()?.title&&o()?.subtitle&&o()?.text?N(C):N(F,!1)})}de(I),ve(x,I)},L=x=>{var I=rs(),_=St(I);{var C=N=>{var U=S0();ve(N,U)},F=N=>{var U=rs(),B=St(U);{var w=G=>{var O=x0();ve(G,O)};ns(B,G=>{s()||G(w)},!0)}ve(N,U)};ns(_,N=>{s()&&!ae(l)&&(!o()||!o().title&&!o().subtitle&&!o().text)?N(C):N(F,!1)},!0)}ve(x,I)};ns(A,x=>{i()||s()&&!ae(l)&&(o()?.title||o()?.subtitle||o()?.text)?x(D):x(L,!1)})}return de(E),ve(r,E),ea(v)}customElements.define("hb-player-live",fh(jc,{id:{},mediauri:{},forcecover:{},media_type:{},no_controls:{},replacewithtext:{}},["replacewithtext","replacetitle","replacesubtitle","replacetext"],[],!0)),Un.Component=jc,Object.defineProperty(Un,Symbol.toStringTag,{value:"Module"})})(this["player-live"]=this["player-live"]||{});
|
|
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,Ae,"m",Wn).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))},Jc=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",Vc).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,Ae,"m",Wn).call(this)}).catch(e=>{Q(this,Ae,"m",fi).call(this,e)})},Wn=function(){Q(this,Ae,"m",Zc).call(this).then(e=>Q(this,Ae,"m",eu).call(this,e)).then(e=>Q(this,Ae,"m",tu).call(this,e)).then(e=>Q(this,Ae,"m",su).call(this,e)).catch(e=>{Q(this,Ae,"m",fi).call(this,e.toString())})},Yn=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}`}:{}},Zc=function(){return fetch(this.conf.url,{method:"OPTIONS",headers:Q(this,Ae,"m",Yn).call(this)}).then(e=>Q(at,me,"m",Hc).call(at,e.headers.get("Link")))},eu=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,Ae,"m",iu).call(this,s),this.pc.onconnectionstatechange=()=>Q(this,Ae,"m",ru).call(this),this.pc.ontrack=s=>Q(this,Ae,"m",nu).call(this,s),this.pc.createOffer().then(s=>{if(!s.sdp)throw new Error("SDP not present");return s.sdp=Q(at,me,"m",zc).call(at,s.sdp,this.nonAdvertisedCodecs),this.offerData=Q(at,me,"m",Wc).call(at,s.sdp),this.pc.setLocalDescription(s).then(()=>s.sdp)})},tu=function(e){if(this.state!=="running")throw new Error("closed");return fetch(this.conf.url,{method:"POST",headers:{...Q(this,Ae,"m",Yn).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()})},su=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,Ae,"m",qn).call(this,this.queuedCandidates),this.queuedCandidates=[])})},iu=function(e){this.state==="running"&&e.candidate!==null&&(this.sessionUrl===null?this.queuedCandidates.push(e.candidate):Q(this,Ae,"m",qn).call(this,[e.candidate]))},qn=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",Qc).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,Ae,"m",fi).call(this,t.toString())})},ru=function(){this.state==="running"&&this.pc&&(this.pc.connectionState==="failed"||this.pc.connectionState==="closed")&&Q(this,Ae,"m",fi).call(this,"peer connection closed")},nu=function(e){this.conf.onTrack!==void 0&&this.conf.onTrack(e)};var C0=Xt('<video id="video" part="video" class="video svelte-8tcri8" autoplay><track kind="captions" src="" srclang="en" label="English" default/></video>',2),P0=Xt('<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),k0=Xt('<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),w0=Xt('<div style="flex: 1"><div class="subsection svelte-8tcri8"><div><!></div></div></div>'),O0=Xt('<div part="replacewithtext" class="replacetext video svelte-8tcri8"><!></div>'),M0=Xt('<div class="replacetext video svelte-8tcri8" part="replacewithtext">offline</div>'),F0=Xt('<div class="replacetext video svelte-8tcri8" part="replacewithtext">nouri</div>'),N0=Xt('<div part="container" style="width: 100%;position:relative"><!> <!></div>');const $0={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 au(r,e){ra(e,!0),xh(r,$0);let t=Ps(e,"id",7,""),s=Ps(e,"mediauri"),i=Ps(e,"forcecover",7,void 0),n=Ps(e,"media_type",7,"auto"),a=Ps(e,"no_controls",7,!1),o=Ps(e,"replacewithtext",7,void 0),c=Ve(void 0),l=Ve(!1),u=Ve(void 0),h=Ve(void 0),d=Ve(void 0),f=Ve(void 0);Aa(()=>{if(a()&&a()!=="no"&&a()!=="false"&&a(!0),typeof o()=="string")try{o(JSON.parse(o()))}catch{}s()&&re(f)&&s()!==re(f)&&(de(f,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 g(x,I){e.$$host.dispatchEvent(new CustomEvent(x,{detail:I}))}function p(x){if(console.log("setttviiiii",n()),de(d,x,!0),g("htmlVideoInit",{htmlVideoElement:re(d),id:t()}),n()==="hls")if(x&&bt.isSupported()){const I=new bt({});I.loadSource(s()),I.attachMedia(x),I.on(bt.Events.MEDIA_ATTACHED,function(){x.muted=!0;try{x.play()}catch(L){console.error("cannot autoplay",L)}})}else x?.canPlayType("application/vnd.apple.mpegurl")?(console.log("without Media Source Extensions"),x.src=s(),x.muted=!0,x.addEventListener("canplay",function(){try{x.play()}catch(I){console.error("cannot autoplay",I)}})):console.error("no hls support");else if(n()==="whep"){console.info("whep",s());try{let I=function(){console.info("offline whep"),g("liveStatus",{live:!1,id:t()}),de(l,!1)},L=function(C){console.info("online whep"),x.srcObject=C?.streams?.[0],g("liveStatus",{live:!0,id:t()}),de(l,!0)};console.info("whep",s()),de(h,new at({url:s(),onTrack:L,onError:I}),!0);try{x.muted=!0,x.play()}catch(C){console.error("cannot autoplay whep",C)}}catch(I){console.error("whep error ....",I)}}else if(n()==="webrtc"){console.info("webrtc",s());try{let I=function(){g("liveStatus",{live:!1,id:t()}),de(l,!1)},L=function(){g("liveStatus",{live:!0,id:t()}),de(l,!0)};de(u,new D0({videoElement:x,wsUri:s(),onOnline:L,onOffline:I}),!0),re(u).start();try{x.muted=!0,x.play()}catch(C){console.error("cannot autoplay webrtc",C)}}catch(I){console.error("webrtc error ....",I)}}else console.error("unknown media type",n())}async function y(){function x(){console.log("reloading",re(l),s()),(!re(l)||!s())&&y().catch(I=>{console.error("reload uri",I)})}try{if(!s()){de(c,setTimeout(x,5e3),!0);return}if(n()==="hls"){console.info("checking live");const I=await fetch(s());if(!I||I.status&&(I.status>299||I.status<199))throw new Error("wrong uri");de(l,!0),g("liveStatus",{live:!0,id:t()})}else throw new Error("wrong media type")}catch{re(l)!==!1&&g("liveStatus",{live:!1,id:t()}),de(l,!1),de(c,setTimeout(x,5e3),!0)}}e.$$host.getVideoElement=()=>{if(re(d))return re(d)},Sh(()=>(de(f,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(x=""){t(x),rs()},get mediauri(){return s()},set mediauri(x){s(x),rs()},get forcecover(){return i()},set forcecover(x=void 0){i(x),rs()},get media_type(){return n()},set media_type(x="auto"){n(x),rs()},get no_controls(){return a()},set no_controls(x=!1){a(x),rs()},get replacewithtext(){return o()},set replacewithtext(x=void 0){o(x),rs()}},E=N0(),T=ge(E);{var S=x=>{var I=C0();Ah(I,L=>p?.(L)),as(()=>I.controls=!a()),Te(x,I)};hs(T,x=>{s()&&n()&&x(S)})}var A=Li(T,2);{var D=x=>{var I=O0(),L=ge(I);{var C=N=>{var G=us(),U=Ot(G);Nt(U,e,"replacewithtext",{},k=>{var B=P0(),O=Ot(B),K=ge(O),W=ge(K),M=ge(W);Nt(M,e,"replacetitle",{},Kt=>{var Fe=bs();as(()=>Ds(Fe,o()?.title||"")),Te(Kt,Fe)}),fe(W),fe(K),fe(O);var w=Li(O,2),Y=ge(w),Z=ge(Y),j=ge(Z),z=ge(j),pe=ge(z);Nt(pe,e,"replacesubtitle",{},Kt=>{var Fe=bs();as(()=>Ds(Fe,o()?.subtitle||"")),Te(Kt,Fe)}),fe(z),fe(j),fe(Z);var he=Li(Z,2),_e=ge(he),De=ge(_e),Ge=ge(De);Nt(Ge,e,"replacetext",{},Kt=>{var Fe=bs();as(()=>Ds(Fe,o()?.text||"")),Te(Kt,Fe)}),fe(De),fe(_e),fe(he),fe(Y),fe(w),Te(k,B)}),Te(N,G)},F=N=>{var G=us(),U=Ot(G);{var k=O=>{var K=us(),W=Ot(K);Nt(W,e,"replacewithtext",{},M=>{var w=k0(),Y=Ot(w),Z=ge(Y),j=ge(Z),z=ge(j);Nt(z,e,"replacetitle",{},Fe=>{var Vt=bs();as(()=>Ds(Vt,o()?.title||"")),Te(Fe,Vt)}),fe(j),fe(Z),fe(Y);var pe=Li(Y,2),he=ge(pe),_e=ge(he),De=ge(_e),Ge=ge(De),Kt=ge(Ge);Nt(Kt,e,"replacesubtitle",{},Fe=>{var Vt=bs();as(()=>Ds(Vt,o()?.subtitle||"")),Te(Fe,Vt)}),fe(Ge),fe(De),fe(_e),fe(he),fe(pe),Te(M,w)}),Te(O,K)},B=O=>{var K=us(),W=Ot(K);{var M=w=>{var Y=us(),Z=Ot(Y);Nt(Z,e,"replacewithtext",{},j=>{var z=w0(),pe=ge(z),he=ge(pe),_e=ge(he);Nt(_e,e,"replacetitle",{},De=>{var Ge=bs();as(()=>Ds(Ge,o()?.title||"")),Te(De,Ge)}),fe(he),fe(pe),fe(z),Te(j,z)}),Te(w,Y)};hs(W,w=>{o()?.title&&w(M)},!0)}Te(O,K)};hs(U,O=>{o()?.title&&o()?.subtitle?O(k):O(B,!1)},!0)}Te(N,G)};hs(L,N=>{o()?.title&&o()?.subtitle&&o()?.text?N(C):N(F,!1)})}fe(I),Te(x,I)},_=x=>{var I=us(),L=Ot(I);{var C=N=>{var G=M0();Te(N,G)},F=N=>{var G=us(),U=Ot(G);{var k=B=>{var O=F0();Te(B,O)};hs(U,B=>{s()||B(k)},!0)}Te(N,G)};hs(L,N=>{s()&&!re(l)&&(!o()||!o().title&&!o().subtitle&&!o().text)?N(C):N(F,!1)},!0)}Te(x,I)};hs(A,x=>{i()||s()&&!re(l)&&(o()?.title||o()?.subtitle||o()?.text)?x(D):x(_,!1)})}return fe(E),Te(r,E),na(v)}customElements.define("hb-player-live",Rh(au,{id:{},mediauri:{},forcecover:{},media_type:{},no_controls:{},replacewithtext:{}},["replacewithtext","replacetitle","replacesubtitle","replacetext"],[],!0)),jn.Component=au,Object.defineProperty(jn,Symbol.toStringTag,{value:"Module"})})(this["player-live"]=this["player-live"]||{});
|
|
81
73
|
//# sourceMappingURL=main.iife.js.map
|