@evercam/ui 0.0.55-beta.8 → 0.0.55-beta.9

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/dist/index.umd.js CHANGED
@@ -1,17 +1,17 @@
1
- (function(Z,Ee){typeof exports=="object"&&typeof module!="undefined"?Ee(exports,require("vue"),require("d3"),require("moment-timezone")):typeof define=="function"&&define.amd?define(["exports","vue","d3","moment-timezone"],Ee):(Z=typeof globalThis!="undefined"?globalThis:Z||self,Ee(Z.EvercamUI={},Z.Vue,Z.d3,Z.moment))})(this,function(Z,Ee,_a,We){var Ea,Sa,ba,Aa,La,Ra,Ca,Da;"use strict";function Ia(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const I=Ia(_a);var z=(s=>(s.dot="dot",s.xs="xs",s.sm="sm",s.md="base",s.base="base",s.lg="lg",s.xl="xl",s["2xl"]="2xl",s["3xl"]="3xl",s["4xl"]="4xl",s["5xl"]="5xl",s["6xl"]="6xl",s["7xl"]="7xl",s["8xl"]="8xl",s["9xl"]="9xl",s))(z||{}),ue=(s=>(s.warning="warning",s.error="error",s.info="info",s.success="success",s.primary="primary",s.brand="brand",s.default="default",s))(ue||{}),mt=(s=>(s.overview="overview",s.detailed="detailed",s.detailedBackground="detailedBackground",s))(mt||{}),Se=(s=>(s.bars="bars",s.dots="dots",s.lineGraph="lineGraph",s.barChart="barGraph",s.milestones="milestones",s))(Se||{}),gt=(s=>(s.zoom="zoom",s.autoPan="autoPan",s.initial="initial",s))(gt||{});const wa=Ee.extend({name:"EBadge",props:{text:{type:String,default:""},color:{type:String,default:ue.default},size:{type:String,default:z.base}},data(){return{colors:{[ue.error]:"e-bg-rose-500 e-text-white",[ue.info]:"e-bg-cyan-500 e-text-white",[ue.warning]:"e-bg-amber-500 e-text-white",[ue.primary]:"e-bg-sky-500 e-text-white",[ue.default]:"e-bg-slate-300 e-text-white",[ue.success]:"e-bg-lime-500 e-text-white"},sizes:{[z.dot]:"e-w-2 e-h-2",[z.xs]:"e-w-3 e-h-3",[z.sm]:"e-w-4 e-h-4",[z.md]:"e-w-5 e-h-5",[z.lg]:"e-min-w-[2rem] e-max-w-[4rem] e-px-1 e-h-6 e-text-sm e-font-medium",[z.xl]:"e-min-w-[3rem] e-max-w-[5rem] e-px-1 e-h-8 e-text-base e-font-medium"}}},computed:{badgeClasses(){const s=this.colors[this.color]||this.colors[ue.default],e=this.sizes[this.size]||this.sizes[z.md];return["e-flex e-items-center e-justify-center e-rounded-full",s,e]},showText(){return[z.lg,z.xl].includes(this.size)}}});function Ie(s,e,t,i,r,n,a,o){var l=typeof s=="function"?s.options:s;e&&(l.render=e,l.staticRenderFns=t,l._compiled=!0),i&&(l.functional=!0),n&&(l._scopeId="data-v-"+n);var c;if(a?(c=function(d){d=d||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext,!d&&typeof __VUE_SSR_CONTEXT__!="undefined"&&(d=__VUE_SSR_CONTEXT__),r&&r.call(this,d),d&&d._registeredComponents&&d._registeredComponents.add(a)},l._ssrRegister=c):r&&(c=o?function(){r.call(this,(l.functional?this.parent:this).$root.$options.shadowRoot)}:r),c)if(l.functional){l._injectStyles=c;var u=l.render;l.render=function(f,m){return c.call(m),u(f,m)}}else{var h=l.beforeCreate;l.beforeCreate=h?[].concat(h,c):[c]}return{exports:s,options:l}}var ka=function(){var e=this,t=e._self._c;return t("span",{staticClass:"e-badge",class:e.badgeClasses},[e.showText?t("span",[e._v(e._s(e.text))]):e._e()])},Pa=[],Oa=Ie(wa,ka,Pa,!1,null,null,null,null);const ni=Oa.exports,Fa=Ee.extend({name:"EAvatar",components:{Badge:ni},props:{size:{type:String,default:z.md},showBadge:{type:Boolean,default:!1},badgeColor:{type:String,default:ue.error},badgeText:{type:String,default:""},badgeSize:{type:String,default:z.md},image:{type:String,default:""}},data(){return{sizes:{[z.xs]:"e-w-8 e-h-8 e-text-xs",[z.sm]:"e-w-10 e-h-10 e-text-sm",[z.md]:"e-w-14 e-h-14 e-text-base",[z.lg]:"e-w-20 e-h-20 e-text-2xl",[z.xl]:"e-w-28 e-h-28 e-text-3xl",[z["2xl"]]:"e-w-36 e-h-36 e-text-5xl"}}},computed:{avatarClasses(){return["e-flex e-items-center e-justify-center e-rounded-full e-bg-purple-500 e-text-white e-font-medium",this.sizes[this.size]||this.sizes[z.xs]]}}});var Ma=function(){var e=this,t=e._self._c;return t("div",{staticClass:"e-avatar e-relative",class:e.avatarClasses},[e._t("default",function(){return[e.image?t("img",{staticClass:"e-avatar__image e-w-full e-h-full e-object-cover e-rounded-full",attrs:{src:e.image}}):e._e()]}),e.showBadge?t("div",{staticClass:"e-avatar__badge e-absolute e-top-0 e-right-0"},[e._t("badge",function(){return[t("Badge",{attrs:{text:e.badgeText,color:e.badgeColor,size:e.badgeSize}})]})],2):e._e()],2)},Na=[],Ba=Ie(Fa,Ma,Na,!1,null,null,null,null);const Ls=Ba.exports;function $a(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Rs={},Cs={},ai={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return e}});function e(t){if(t=`${t}`,t==="0")return"0";if(/^[+-]?(\d+|\d*\.\d+)(e[+-]?\d+)?(%|\w+)?$/.test(t))return t.replace(/^[+-]?/,r=>r==="-"?"":"-");let i=["var","calc","min","max","clamp"];for(const r of i)if(t.includes(`${r}(`))return`calc(${t} * -1)`}})(ai);var Ds={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return e}});const e=["preflight","container","accessibility","pointerEvents","visibility","position","inset","isolation","zIndex","order","gridColumn","gridColumnStart","gridColumnEnd","gridRow","gridRowStart","gridRowEnd","float","clear","margin","boxSizing","lineClamp","display","aspectRatio","height","maxHeight","minHeight","width","minWidth","maxWidth","flex","flexShrink","flexGrow","flexBasis","tableLayout","captionSide","borderCollapse","borderSpacing","transformOrigin","translate","rotate","skew","scale","transform","animation","cursor","touchAction","userSelect","resize","scrollSnapType","scrollSnapAlign","scrollSnapStop","scrollMargin","scrollPadding","listStylePosition","listStyleType","listStyleImage","appearance","columns","breakBefore","breakInside","breakAfter","gridAutoColumns","gridAutoFlow","gridAutoRows","gridTemplateColumns","gridTemplateRows","flexDirection","flexWrap","placeContent","placeItems","alignContent","alignItems","justifyContent","justifyItems","gap","space","divideWidth","divideStyle","divideColor","divideOpacity","placeSelf","alignSelf","justifySelf","overflow","overscrollBehavior","scrollBehavior","textOverflow","hyphens","whitespace","wordBreak","borderRadius","borderWidth","borderStyle","borderColor","borderOpacity","backgroundColor","backgroundOpacity","backgroundImage","gradientColorStops","boxDecorationBreak","backgroundSize","backgroundAttachment","backgroundClip","backgroundPosition","backgroundRepeat","backgroundOrigin","fill","stroke","strokeWidth","objectFit","objectPosition","padding","textAlign","textIndent","verticalAlign","fontFamily","fontSize","fontWeight","textTransform","fontStyle","fontVariantNumeric","lineHeight","letterSpacing","textColor","textOpacity","textDecoration","textDecorationColor","textDecorationStyle","textDecorationThickness","textUnderlineOffset","fontSmoothing","placeholderColor","placeholderOpacity","caretColor","accentColor","opacity","backgroundBlendMode","mixBlendMode","boxShadow","boxShadowColor","outlineStyle","outlineWidth","outlineOffset","outlineColor","ringWidth","ringColor","ringOpacity","ringOffsetWidth","ringOffsetColor","blur","brightness","contrast","dropShadow","grayscale","hueRotate","invert","saturate","sepia","filter","backdropBlur","backdropBrightness","backdropContrast","backdropGrayscale","backdropHueRotate","backdropInvert","backdropOpacity","backdropSaturate","backdropSepia","backdropFilter","transitionProperty","transitionDelay","transitionDuration","transitionTimingFunction","willChange","content"]})(Ds);var _s={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return e}});function e(t,i){return t===void 0?i:Array.isArray(t)?t:[...new Set(i.filter(n=>t!==!1&&t[n]!==!1).concat(Object.keys(t).filter(n=>t[n]!==!1)))]}})(_s);var oi={},Lt={},li={exports:{}},re=String,Is=function(){return{isColorSupported:!1,reset:re,bold:re,dim:re,italic:re,underline:re,inverse:re,hidden:re,strikethrough:re,black:re,red:re,green:re,yellow:re,blue:re,magenta:re,cyan:re,white:re,gray:re,bgBlack:re,bgRed:re,bgGreen:re,bgYellow:re,bgBlue:re,bgMagenta:re,bgCyan:re,bgWhite:re}};li.exports=Is(),li.exports.createColors=Is;var ws=li.exports;(function(s){Object.defineProperty(s,"__esModule",{value:!0});function e(l,c){for(var u in c)Object.defineProperty(l,u,{enumerable:!0,get:c[u]})}e(s,{dim:function(){return a},default:function(){return o}});const t=i(ws);function i(l){return l&&l.__esModule?l:{default:l}}let r=new Set;function n(l,c,u){typeof process!="undefined"&&process.env.JEST_WORKER_ID||u&&r.has(u)||(u&&r.add(u),console.warn(""),c.forEach(h=>console.warn(l,"-",h)))}function a(l){return t.default.dim(l)}const o={info(l,c){n(t.default.bold(t.default.cyan("info")),...Array.isArray(l)?[l]:[c,l])},warn(l,c){n(t.default.bold(t.default.yellow("warn")),...Array.isArray(l)?[l]:[c,l])},risk(l,c){n(t.default.bold(t.default.magenta("risk")),...Array.isArray(l)?[l]:[c,l])}}})(Lt),function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return r}});const e=t(Lt);function t(n){return n&&n.__esModule?n:{default:n}}function i({version:n,from:a,to:o}){e.default.warn(`${a}-color-renamed`,[`As of Tailwind CSS ${n}, \`${a}\` has been renamed to \`${o}\`.`,"Update your configuration file to silence this warning."])}const r={inherit:"inherit",current:"currentColor",transparent:"transparent",black:"#000",white:"#fff",slate:{50:"#f8fafc",100:"#f1f5f9",200:"#e2e8f0",300:"#cbd5e1",400:"#94a3b8",500:"#64748b",600:"#475569",700:"#334155",800:"#1e293b",900:"#0f172a",950:"#020617"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},zinc:{50:"#fafafa",100:"#f4f4f5",200:"#e4e4e7",300:"#d4d4d8",400:"#a1a1aa",500:"#71717a",600:"#52525b",700:"#3f3f46",800:"#27272a",900:"#18181b",950:"#09090b"},neutral:{50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},stone:{50:"#fafaf9",100:"#f5f5f4",200:"#e7e5e4",300:"#d6d3d1",400:"#a8a29e",500:"#78716c",600:"#57534e",700:"#44403c",800:"#292524",900:"#1c1917",950:"#0c0a09"},red:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d",950:"#450a0a"},orange:{50:"#fff7ed",100:"#ffedd5",200:"#fed7aa",300:"#fdba74",400:"#fb923c",500:"#f97316",600:"#ea580c",700:"#c2410c",800:"#9a3412",900:"#7c2d12",950:"#431407"},amber:{50:"#fffbeb",100:"#fef3c7",200:"#fde68a",300:"#fcd34d",400:"#fbbf24",500:"#f59e0b",600:"#d97706",700:"#b45309",800:"#92400e",900:"#78350f",950:"#451a03"},yellow:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12",950:"#422006"},lime:{50:"#f7fee7",100:"#ecfccb",200:"#d9f99d",300:"#bef264",400:"#a3e635",500:"#84cc16",600:"#65a30d",700:"#4d7c0f",800:"#3f6212",900:"#365314",950:"#1a2e05"},green:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d",950:"#052e16"},emerald:{50:"#ecfdf5",100:"#d1fae5",200:"#a7f3d0",300:"#6ee7b7",400:"#34d399",500:"#10b981",600:"#059669",700:"#047857",800:"#065f46",900:"#064e3b",950:"#022c22"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"},cyan:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},sky:{50:"#f0f9ff",100:"#e0f2fe",200:"#bae6fd",300:"#7dd3fc",400:"#38bdf8",500:"#0ea5e9",600:"#0284c7",700:"#0369a1",800:"#075985",900:"#0c4a6e",950:"#082f49"},blue:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},indigo:{50:"#eef2ff",100:"#e0e7ff",200:"#c7d2fe",300:"#a5b4fc",400:"#818cf8",500:"#6366f1",600:"#4f46e5",700:"#4338ca",800:"#3730a3",900:"#312e81",950:"#1e1b4b"},violet:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},fuchsia:{50:"#fdf4ff",100:"#fae8ff",200:"#f5d0fe",300:"#f0abfc",400:"#e879f9",500:"#d946ef",600:"#c026d3",700:"#a21caf",800:"#86198f",900:"#701a75",950:"#4a044e"},pink:{50:"#fdf2f8",100:"#fce7f3",200:"#fbcfe8",300:"#f9a8d4",400:"#f472b6",500:"#ec4899",600:"#db2777",700:"#be185d",800:"#9d174d",900:"#831843",950:"#500724"},rose:{50:"#fff1f2",100:"#ffe4e6",200:"#fecdd3",300:"#fda4af",400:"#fb7185",500:"#f43f5e",600:"#e11d48",700:"#be123c",800:"#9f1239",900:"#881337",950:"#4c0519"},get lightBlue(){return i({version:"v2.2",from:"lightBlue",to:"sky"}),this.sky},get warmGray(){return i({version:"v3.0",from:"warmGray",to:"stone"}),this.stone},get trueGray(){return i({version:"v3.0",from:"trueGray",to:"neutral"}),this.neutral},get coolGray(){return i({version:"v3.0",from:"coolGray",to:"gray"}),this.gray},get blueGray(){return i({version:"v3.0",from:"blueGray",to:"slate"}),this.slate}}}(oi);var ks={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"defaults",{enumerable:!0,get:function(){return e}});function e(t,...i){for(let a of i){for(let o in a){var r;!(t==null||(r=t.hasOwnProperty)===null||r===void 0)&&r.call(t,o)||(t[o]=a[o])}for(let o of Object.getOwnPropertySymbols(a)){var n;!(t==null||(n=t.hasOwnProperty)===null||n===void 0)&&n.call(t,o)||(t[o]=a[o])}}return t}})(ks);var Ps={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"toPath",{enumerable:!0,get:function(){return e}});function e(t){if(Array.isArray(t))return t;let i=t.split("[").length-1,r=t.split("]").length-1;if(i!==r)throw new Error(`Path is invalid. Has unbalanced brackets: ${t}`);return t.split(/\.(?![^\[]*\])|[\[\]]/g).filter(Boolean)}})(Ps);var Os={},Rt={};(function(s){Object.defineProperty(s,"__esModule",{value:!0});function e(h,d){for(var f in d)Object.defineProperty(h,f,{enumerable:!0,get:d[f]})}e(s,{flagEnabled:function(){return o},issueFlagNotices:function(){return c},default:function(){return u}});const t=r(ws),i=r(Lt);function r(h){return h&&h.__esModule?h:{default:h}}let n={optimizeUniversalDefaults:!1,generalizedModifiers:!0,get disableColorOpacityUtilitiesByDefault(){return!1},get relativeContentPathsByDefault(){return!1}},a={future:["hoverOnlyWhenSupported","respectDefaultRingColorOpacity","disableColorOpacityUtilitiesByDefault","relativeContentPathsByDefault"],experimental:["optimizeUniversalDefaults","generalizedModifiers"]};function o(h,d){if(a.future.includes(d)){var f,m,g;return h.future==="all"||((g=(m=h==null||(f=h.future)===null||f===void 0?void 0:f[d])!==null&&m!==void 0?m:n[d])!==null&&g!==void 0?g:!1)}if(a.experimental.includes(d)){var y,v,T;return h.experimental==="all"||((T=(v=h==null||(y=h.experimental)===null||y===void 0?void 0:y[d])!==null&&v!==void 0?v:n[d])!==null&&T!==void 0?T:!1)}return!1}function l(h){if(h.experimental==="all")return a.experimental;var d;return Object.keys((d=h==null?void 0:h.experimental)!==null&&d!==void 0?d:{}).filter(f=>a.experimental.includes(f)&&h.experimental[f])}function c(h){if(process.env.JEST_WORKER_ID===void 0&&l(h).length>0){let d=l(h).map(f=>t.default.yellow(f)).join(", ");i.default.warn("experimental-flags-enabled",[`You have enabled experimental features: ${d}`,"Experimental features in Tailwind CSS are not covered by semver, may introduce breaking changes, and can change at any time."])}}const u=a})(Rt),function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"normalizeConfig",{enumerable:!0,get:function(){return n}});const e=Rt,t=r(Lt);function i(a){if(typeof WeakMap!="function")return null;var o=new WeakMap,l=new WeakMap;return(i=function(c){return c?l:o})(a)}function r(a,o){if(!o&&a&&a.__esModule)return a;if(a===null||typeof a!="object"&&typeof a!="function")return{default:a};var l=i(o);if(l&&l.has(a))return l.get(a);var c={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var h in a)if(h!=="default"&&Object.prototype.hasOwnProperty.call(a,h)){var d=u?Object.getOwnPropertyDescriptor(a,h):null;d&&(d.get||d.set)?Object.defineProperty(c,h,d):c[h]=a[h]}return c.default=a,l&&l.set(a,c),c}function n(a){if((()=>{if(a.purge||!a.content||!Array.isArray(a.content)&&!(typeof a.content=="object"&&a.content!==null))return!1;if(Array.isArray(a.content))return a.content.every(c=>typeof c=="string"?!0:!(typeof(c==null?void 0:c.raw)!="string"||c!=null&&c.extension&&typeof(c==null?void 0:c.extension)!="string"));if(typeof a.content=="object"&&a.content!==null){if(Object.keys(a.content).some(c=>!["files","relative","extract","transform"].includes(c)))return!1;if(Array.isArray(a.content.files)){if(!a.content.files.every(c=>typeof c=="string"?!0:!(typeof(c==null?void 0:c.raw)!="string"||c!=null&&c.extension&&typeof(c==null?void 0:c.extension)!="string")))return!1;if(typeof a.content.extract=="object"){for(let c of Object.values(a.content.extract))if(typeof c!="function")return!1}else if(!(a.content.extract===void 0||typeof a.content.extract=="function"))return!1;if(typeof a.content.transform=="object"){for(let c of Object.values(a.content.transform))if(typeof c!="function")return!1}else if(!(a.content.transform===void 0||typeof a.content.transform=="function"))return!1;if(typeof a.content.relative!="boolean"&&typeof a.content.relative!="undefined")return!1}return!0}return!1})()||t.default.warn("purge-deprecation",["The `purge`/`content` options have changed in Tailwind CSS v3.0.","Update your configuration file to eliminate this warning.","https://tailwindcss.com/docs/upgrade-guide#configure-content-sources"]),a.safelist=(()=>{var c;let{content:u,purge:h,safelist:d}=a;return Array.isArray(d)?d:Array.isArray(u==null?void 0:u.safelist)?u.safelist:Array.isArray(h==null?void 0:h.safelist)?h.safelist:Array.isArray(h==null||(c=h.options)===null||c===void 0?void 0:c.safelist)?h.options.safelist:[]})(),a.blocklist=(()=>{let{blocklist:c}=a;if(Array.isArray(c)){if(c.every(u=>typeof u=="string"))return c;t.default.warn("blocklist-invalid",["The `blocklist` option must be an array of strings.","https://tailwindcss.com/docs/content-configuration#discarding-classes"])}return[]})(),typeof a.prefix=="function")t.default.warn("prefix-function",["As of Tailwind CSS v3.0, `prefix` cannot be a function.","Update `prefix` in your configuration to be a string to eliminate this warning.","https://tailwindcss.com/docs/upgrade-guide#prefix-cannot-be-a-function"]),a.prefix="";else{var l;a.prefix=(l=a.prefix)!==null&&l!==void 0?l:""}a.content={relative:(()=>{let{content:c}=a;return c!=null&&c.relative?c.relative:(0,e.flagEnabled)(a,"relativeContentPathsByDefault")})(),files:(()=>{let{content:c,purge:u}=a;return Array.isArray(u)?u:Array.isArray(u==null?void 0:u.content)?u.content:Array.isArray(c)?c:Array.isArray(c==null?void 0:c.content)?c.content:Array.isArray(c==null?void 0:c.files)?c.files:[]})(),extract:(()=>{let c=(()=>{var d,f,m,g,y,v,T,x,L,E;return!((d=a.purge)===null||d===void 0)&&d.extract?a.purge.extract:!((f=a.content)===null||f===void 0)&&f.extract?a.content.extract:!((m=a.purge)===null||m===void 0||(g=m.extract)===null||g===void 0)&&g.DEFAULT?a.purge.extract.DEFAULT:!((y=a.content)===null||y===void 0||(v=y.extract)===null||v===void 0)&&v.DEFAULT?a.content.extract.DEFAULT:!((T=a.purge)===null||T===void 0||(x=T.options)===null||x===void 0)&&x.extractors?a.purge.options.extractors:!((L=a.content)===null||L===void 0||(E=L.options)===null||E===void 0)&&E.extractors?a.content.options.extractors:{}})(),u={},h=(()=>{var d,f,m,g;if(!((d=a.purge)===null||d===void 0||(f=d.options)===null||f===void 0)&&f.defaultExtractor)return a.purge.options.defaultExtractor;if(!((m=a.content)===null||m===void 0||(g=m.options)===null||g===void 0)&&g.defaultExtractor)return a.content.options.defaultExtractor})();if(h!==void 0&&(u.DEFAULT=h),typeof c=="function")u.DEFAULT=c;else if(Array.isArray(c))for(let{extensions:d,extractor:f}of c!=null?c:[])for(let m of d)u[m]=f;else typeof c=="object"&&c!==null&&Object.assign(u,c);return u})(),transform:(()=>{let c=(()=>{var h,d,f,m,g,y;return!((h=a.purge)===null||h===void 0)&&h.transform?a.purge.transform:!((d=a.content)===null||d===void 0)&&d.transform?a.content.transform:!((f=a.purge)===null||f===void 0||(m=f.transform)===null||m===void 0)&&m.DEFAULT?a.purge.transform.DEFAULT:!((g=a.content)===null||g===void 0||(y=g.transform)===null||y===void 0)&&y.DEFAULT?a.content.transform.DEFAULT:{}})(),u={};return typeof c=="function"&&(u.DEFAULT=c),typeof c=="object"&&c!==null&&Object.assign(u,c),u})()};for(let c of a.content.files)if(typeof c=="string"&&/{([^,]*?)}/g.test(c)){t.default.warn("invalid-glob-braces",[`The glob pattern ${(0,t.dim)(c)} in your Tailwind CSS configuration is invalid.`,`Update it to ${(0,t.dim)(c.replace(/{([^,]*?)}/g,"$1"))} to silence this warning.`]);break}return a}}(Os);var Fs={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return e}});function e(t){if(Object.prototype.toString.call(t)!=="[object Object]")return!1;const i=Object.getPrototypeOf(t);return i===null||i===Object.prototype}})(Fs);var Ms={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"cloneDeep",{enumerable:!0,get:function(){return e}});function e(t){return Array.isArray(t)?t.map(i=>e(i)):typeof t=="object"&&t!==null?Object.fromEntries(Object.entries(t).map(([i,r])=>[i,e(r)])):t}})(Ms);var Ns={},Bs={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return e}});function e(t){return t.replace(/\\,/g,"\\2c ")}})(Bs);var ci={},ui={},$s={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return e}});const e={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}})($s),function(s){Object.defineProperty(s,"__esModule",{value:!0});function e(m,g){for(var y in g)Object.defineProperty(m,y,{enumerable:!0,get:g[y]})}e(s,{parseColor:function(){return d},formatColor:function(){return f}});const t=i($s);function i(m){return m&&m.__esModule?m:{default:m}}let r=/^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i,n=/^#([a-f\d])([a-f\d])([a-f\d])([a-f\d])?$/i,a=/(?:\d+|\d*\.\d+)%?/,o=/(?:\s*,\s*|\s+)/,l=/\s*[,/]\s*/,c=/var\(--(?:[^ )]*?)\)/,u=new RegExp(`^(rgba?)\\(\\s*(${a.source}|${c.source})(?:${o.source}(${a.source}|${c.source}))?(?:${o.source}(${a.source}|${c.source}))?(?:${l.source}(${a.source}|${c.source}))?\\s*\\)$`),h=new RegExp(`^(hsla?)\\(\\s*((?:${a.source})(?:deg|rad|grad|turn)?|${c.source})(?:${o.source}(${a.source}|${c.source}))?(?:${o.source}(${a.source}|${c.source}))?(?:${l.source}(${a.source}|${c.source}))?\\s*\\)$`);function d(m,{loose:g=!1}={}){var y,v;if(typeof m!="string")return null;if(m=m.trim(),m==="transparent")return{mode:"rgb",color:["0","0","0"],alpha:"0"};if(m in t.default)return{mode:"rgb",color:t.default[m].map(k=>k.toString())};let T=m.replace(n,(k,R,B,C,b)=>["#",R,R,B,B,C,C,b?b+b:""].join("")).match(r);if(T!==null)return{mode:"rgb",color:[parseInt(T[1],16),parseInt(T[2],16),parseInt(T[3],16)].map(k=>k.toString()),alpha:T[4]?(parseInt(T[4],16)/255).toString():void 0};var x;let L=(x=m.match(u))!==null&&x!==void 0?x:m.match(h);if(L===null)return null;let E=[L[2],L[3],L[4]].filter(Boolean).map(k=>k.toString());return E.length===2&&E[0].startsWith("var(")?{mode:L[1],color:[E[0]],alpha:E[1]}:!g&&E.length!==3||E.length<3&&!E.some(k=>/^var\(.*?\)$/.test(k))?null:{mode:L[1],color:E,alpha:(y=L[5])===null||y===void 0||(v=y.toString)===null||v===void 0?void 0:v.call(y)}}function f({mode:m,color:g,alpha:y}){let v=y!==void 0;return m==="rgba"||m==="hsla"?`${m}(${g.join(", ")}${v?`, ${y}`:""})`:`${m}(${g.join(" ")}${v?` / ${y}`:""})`}}(ui),function(s){Object.defineProperty(s,"__esModule",{value:!0});function e(n,a){for(var o in a)Object.defineProperty(n,o,{enumerable:!0,get:a[o]})}e(s,{withAlphaValue:function(){return i},default:function(){return r}});const t=ui;function i(n,a,o){if(typeof n=="function")return n({opacityValue:a});let l=(0,t.parseColor)(n,{loose:!0});return l===null?o:(0,t.formatColor)({...l,alpha:a})}function r({color:n,property:a,variable:o}){let l=[].concat(a);if(typeof n=="function")return{[o]:"1",...Object.fromEntries(l.map(u=>[u,n({opacityVariable:o,opacityValue:`var(${o})`})]))};const c=(0,t.parseColor)(n);return c===null?Object.fromEntries(l.map(u=>[u,n])):c.alpha!==void 0?Object.fromEntries(l.map(u=>[u,n])):{[o]:"1",...Object.fromEntries(l.map(u=>[u,(0,t.formatColor)({...c,alpha:`var(${o})`})]))}}}(ci);var hi={},Us={},Ct={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"splitAtTopLevelOnly",{enumerable:!0,get:function(){return e}});function e(t,i){let r=[],n=[],a=0,o=!1;for(let l=0;l<t.length;l++){let c=t[l];r.length===0&&c===i[0]&&!o&&(i.length===1||t.slice(l,l+i.length)===i)&&(n.push(t.slice(a,l)),a=l+i.length),o?o=!1:c==="\\"&&(o=!0),c==="("||c==="["||c==="{"?r.push(c):(c===")"&&r[r.length-1]==="("||c==="]"&&r[r.length-1]==="["||c==="}"&&r[r.length-1]==="{")&&r.pop()}return n.push(t.slice(a)),n}})(Ct),function(s){Object.defineProperty(s,"__esModule",{value:!0});function e(l,c){for(var u in c)Object.defineProperty(l,u,{enumerable:!0,get:c[u]})}e(s,{parseBoxShadowValue:function(){return a},formatBoxShadowValue:function(){return o}});const t=Ct;let i=new Set(["inset","inherit","initial","revert","unset"]),r=/\ +(?![^(]*\))/g,n=/^-?(\d+|\.\d+)(.*?)$/g;function a(l){return(0,t.splitAtTopLevelOnly)(l,",").map(u=>{let h=u.trim(),d={raw:h},f=h.split(r),m=new Set;for(let g of f)n.lastIndex=0,!m.has("KEYWORD")&&i.has(g)?(d.keyword=g,m.add("KEYWORD")):n.test(g)?m.has("X")?m.has("Y")?m.has("BLUR")?m.has("SPREAD")||(d.spread=g,m.add("SPREAD")):(d.blur=g,m.add("BLUR")):(d.y=g,m.add("Y")):(d.x=g,m.add("X")):d.color?(d.unknown||(d.unknown=[]),d.unknown.push(g)):d.color=g;return d.valid=d.x!==void 0&&d.y!==void 0,d})}function o(l){return l.map(c=>c.valid?[c.keyword,c.x,c.y,c.blur,c.spread,c.color].filter(Boolean).join(" "):c.raw).join(", ")}}(Us),function(s){Object.defineProperty(s,"__esModule",{value:!0});function e(F,V){for(var H in V)Object.defineProperty(F,H,{enumerable:!0,get:V[H]})}e(s,{normalize:function(){return c},url:function(){return h},number:function(){return d},percentage:function(){return f},length:function(){return y},lineWidth:function(){return T},shadow:function(){return x},color:function(){return L},image:function(){return E},gradient:function(){return R},position:function(){return C},familyName:function(){return b},genericName:function(){return P},absoluteSize:function(){return U},relativeSize:function(){return G}});const t=ui,i=Us,r=Ct;let n=["min","max","clamp","calc"];function a(F){return n.some(V=>new RegExp(`^${V}\\(.*\\)`).test(F))}const o="--tw-placeholder",l=new RegExp(o,"g");function c(F,V=!0){return F.startsWith("--")?`var(${F})`:F.includes("url(")?F.split(/(url\(.*?\))/g).filter(Boolean).map(H=>/^url\(.*?\)$/.test(H)?H:c(H,!1)).join(""):(F=F.replace(/([^\\])_+/g,(H,N)=>N+" ".repeat(H.length-1)).replace(/^_/g," ").replace(/\\_/g,"_"),V&&(F=F.trim()),F=u(F),F)}function u(F){return F.replace(/(calc|min|max|clamp)\(.+\)/g,V=>{let H=[];return V.replace(/var\((--.+?)[,)]/g,(N,J)=>(H.push(J),N.replace(J,o))).replace(/(-?\d*\.?\d(?!\b-\d.+[,)](?![^+\-/*])\D)(?:%|[a-z]+)?|\))([+\-/*])/g,"$1 $2 ").replace(l,()=>H.shift())})}function h(F){return F.startsWith("url(")}function d(F){return!isNaN(Number(F))||a(F)}function f(F){return F.endsWith("%")&&d(F.slice(0,-1))||a(F)}let g=`(?:${["cm","mm","Q","in","pc","pt","px","em","ex","ch","rem","lh","rlh","vw","vh","vmin","vmax","vb","vi","svw","svh","lvw","lvh","dvw","dvh","cqw","cqh","cqi","cqb","cqmin","cqmax"].join("|")})`;function y(F){return F==="0"||new RegExp(`^[+-]?[0-9]*.?[0-9]+(?:[eE][+-]?[0-9]+)?${g}$`).test(F)||a(F)}let v=new Set(["thin","medium","thick"]);function T(F){return v.has(F)}function x(F){let V=(0,i.parseBoxShadowValue)(c(F));for(let H of V)if(!H.valid)return!1;return!0}function L(F){let V=0;return(0,r.splitAtTopLevelOnly)(F,"_").every(N=>(N=c(N),N.startsWith("var(")?!0:(0,t.parseColor)(N,{loose:!0})!==null?(V++,!0):!1))?V>0:!1}function E(F){let V=0;return(0,r.splitAtTopLevelOnly)(F,",").every(N=>(N=c(N),N.startsWith("var(")?!0:h(N)||R(N)||["element(","image(","cross-fade(","image-set("].some(J=>N.startsWith(J))?(V++,!0):!1))?V>0:!1}let k=new Set(["conic-gradient","linear-gradient","radial-gradient","repeating-conic-gradient","repeating-linear-gradient","repeating-radial-gradient"]);function R(F){F=c(F);for(let V of k)if(F.startsWith(`${V}(`))return!0;return!1}let B=new Set(["center","top","right","bottom","left"]);function C(F){let V=0;return(0,r.splitAtTopLevelOnly)(F,"_").every(N=>(N=c(N),N.startsWith("var(")?!0:B.has(N)||y(N)||f(N)?(V++,!0):!1))?V>0:!1}function b(F){let V=0;return(0,r.splitAtTopLevelOnly)(F,",").every(N=>(N=c(N),N.startsWith("var(")?!0:N.includes(" ")&&!/(['"])([^"']+)\1/g.test(N)||/^\d/g.test(N)?!1:(V++,!0)))?V>0:!1}let D=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]);function P(F){return D.has(F)}let w=new Set(["xx-small","x-small","small","medium","large","x-large","x-large","xxx-large"]);function U(F){return w.has(F)}let O=new Set(["larger","smaller"]);function G(F){return O.has(F)}}(hi);var Gs={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"backgroundSize",{enumerable:!0,get:function(){return i}});const e=hi,t=Ct;function i(r){let n=["cover","contain"];return(0,t.splitAtTopLevelOnly)(r,",").every(a=>{let o=(0,t.splitAtTopLevelOnly)(a,"_").filter(Boolean);return o.length===1&&n.includes(o[0])?!0:o.length!==1&&o.length!==2?!1:o.every(l=>(0,e.length)(l)||(0,e.percentage)(l)||l==="auto")})}})(Gs),function(s){Object.defineProperty(s,"__esModule",{value:!0});function e(C,b){for(var D in b)Object.defineProperty(C,D,{enumerable:!0,get:b[D]})}e(s,{updateAllClasses:function(){return c},asValue:function(){return d},parseColorFormat:function(){return g},asColor:function(){return v},asLookupValue:function(){return T},typeMap:function(){return L},coerceValue:function(){return R},getMatchingTypes:function(){return B}});const t=l(Bs),i=ci,r=hi,n=l(ai),a=Gs,o=Rt;function l(C){return C&&C.__esModule?C:{default:C}}function c(C,b){C.walkClasses(D=>{D.value=b(D.value),D.raws&&D.raws.value&&(D.raws.value=(0,t.default)(D.raws.value))})}function u(C,b){if(!f(C))return;let D=C.slice(1,-1);if(b(D))return(0,r.normalize)(D)}function h(C,b={},D){let P=b[C];if(P!==void 0)return(0,n.default)(P);if(f(C)){let w=u(C,D);return w===void 0?void 0:(0,n.default)(w)}}function d(C,b={},{validate:D=()=>!0}={}){var P;let w=(P=b.values)===null||P===void 0?void 0:P[C];return w!==void 0?w:b.supportsNegativeValues&&C.startsWith("-")?h(C.slice(1),b.values,D):u(C,D)}function f(C){return C.startsWith("[")&&C.endsWith("]")}function m(C){let b=C.lastIndexOf("/");return b===-1||b===C.length-1?[C,void 0]:f(C)&&!C.includes("]/[")?[C,void 0]:[C.slice(0,b),C.slice(b+1)]}function g(C){if(typeof C=="string"&&C.includes("<alpha-value>")){let b=C;return({opacityValue:D=1})=>b.replace("<alpha-value>",D)}return C}function y(C){return(0,r.normalize)(C.slice(1,-1))}function v(C,b={},{tailwindConfig:D={}}={}){var P;if(((P=b.values)===null||P===void 0?void 0:P[C])!==void 0){var w;return g((w=b.values)===null||w===void 0?void 0:w[C])}let[U,O]=m(C);if(O!==void 0){var G,F,V,H;let N=(H=(G=b.values)===null||G===void 0?void 0:G[U])!==null&&H!==void 0?H:f(U)?U.slice(1,-1):void 0;return N===void 0?void 0:(N=g(N),f(O)?(0,i.withAlphaValue)(N,y(O)):((F=D.theme)===null||F===void 0||(V=F.opacity)===null||V===void 0?void 0:V[O])===void 0?void 0:(0,i.withAlphaValue)(N,D.theme.opacity[O]))}return d(C,b,{validate:r.color})}function T(C,b={}){var D;return(D=b.values)===null||D===void 0?void 0:D[C]}function x(C){return(b,D)=>d(b,D,{validate:C})}let L={any:d,color:v,url:x(r.url),image:x(r.image),length:x(r.length),percentage:x(r.percentage),position:x(r.position),lookup:T,"generic-name":x(r.genericName),"family-name":x(r.familyName),number:x(r.number),"line-width":x(r.lineWidth),"absolute-size":x(r.absoluteSize),"relative-size":x(r.relativeSize),shadow:x(r.shadow),size:x(a.backgroundSize)},E=Object.keys(L);function k(C,b){let D=C.indexOf(b);return D===-1?[void 0,C]:[C.slice(0,D),C.slice(D+1)]}function R(C,b,D,P){if(D.values&&b in D.values)for(let{type:U}of C!=null?C:[]){let O=L[U](b,D,{tailwindConfig:P});if(O!==void 0)return[O,U,null]}if(f(b)){let U=b.slice(1,-1),[O,G]=k(U,":");if(!/^[\w-_]+$/g.test(O))G=U;else if(O!==void 0&&!E.includes(O))return[];if(G.length>0&&E.includes(O))return[d(`[${G}]`,D),O,null]}let w=B(C,b,D,P);for(let U of w)return U;return[]}function*B(C,b,D,P){let w=(0,o.flagEnabled)(P,"generalizedModifiers"),[U,O]=m(b);if(w&&D.modifiers!=null&&(D.modifiers==="any"||typeof D.modifiers=="object"&&(O&&f(O)||O in D.modifiers))||(U=b,O=void 0),O!==void 0&&U===""&&(U="DEFAULT"),O!==void 0&&typeof D.modifiers=="object"){var F,V;let H=(V=(F=D.modifiers)===null||F===void 0?void 0:F[O])!==null&&V!==void 0?V:null;H!==null?O=H:f(O)&&(O=y(O))}for(let{type:H}of C!=null?C:[]){let N=L[H](U,D,{tailwindConfig:P});N!==void 0&&(yield[N,H,O!=null?O:null])}}}(Ns);var Hs={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return e}});function e(t){return typeof t=="function"?t({}):t}})(Hs),function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return D}});const e=f(ai),t=f(Ds),i=f(_s),r=f(oi),n=ks,a=Ps,o=Os,l=f(Fs),c=Ms,u=Ns,h=ci,d=f(Hs);function f(P){return P&&P.__esModule?P:{default:P}}function m(P){return typeof P=="function"}function g(P,...w){let U=w.pop();for(let O of w)for(let G in O){let F=U(P[G],O[G]);F===void 0?(0,l.default)(P[G])&&(0,l.default)(O[G])?P[G]=g({},P[G],O[G],U):P[G]=O[G]:P[G]=F}return P}const y={colors:r.default,negative(P){return Object.keys(P).filter(w=>P[w]!=="0").reduce((w,U)=>{let O=(0,e.default)(P[U]);return O!==void 0&&(w[`-${U}`]=O),w},{})},breakpoints(P){return Object.keys(P).filter(w=>typeof P[w]=="string").reduce((w,U)=>({...w,[`screen-${U}`]:P[U]}),{})}};function v(P,...w){return m(P)?P(...w):P}function T(P){return P.reduce((w,{extend:U})=>g(w,U,(O,G)=>O===void 0?[G]:Array.isArray(O)?[G,...O]:[G,O]),{})}function x(P){return{...P.reduce((w,U)=>(0,n.defaults)(w,U),{}),extend:T(P)}}function L(P,w){if(Array.isArray(P)&&(0,l.default)(P[0]))return P.concat(w);if(Array.isArray(w)&&(0,l.default)(w[0])&&(0,l.default)(P))return[P,...w];if(Array.isArray(w))return w}function E({extend:P,...w}){return g(w,P,(U,O)=>!m(U)&&!O.some(m)?g({},U,...O,L):(G,F)=>g({},...[U,...O].map(V=>v(V,G,F)),L))}function*k(P){let w=(0,a.toPath)(P);if(w.length===0||(yield w,Array.isArray(P)))return;let U=/^(.*?)\s*\/\s*([^/]+)$/,O=P.match(U);if(O!==null){let[,G,F]=O,V=(0,a.toPath)(G);V.alpha=F,yield V}}function R(P){const w=(U,O)=>{for(const G of k(U)){let F=0,V=P;for(;V!=null&&F<G.length;)V=V[G[F++]],V=m(V)&&(G.alpha===void 0||F<=G.length-1)?V(w,y):V;if(V!==void 0){if(G.alpha!==void 0){let H=(0,u.parseColorFormat)(V);return(0,h.withAlphaValue)(H,G.alpha,(0,d.default)(H))}return(0,l.default)(V)?(0,c.cloneDeep)(V):V}}return O};return Object.assign(w,{theme:w,...y}),Object.keys(P).reduce((U,O)=>(U[O]=m(P[O])?P[O](w,y):P[O],U),{})}function B(P){let w=[];return P.forEach(U=>{w=[...w,U];var O;const G=(O=U==null?void 0:U.plugins)!==null&&O!==void 0?O:[];G.length!==0&&G.forEach(F=>{F.__isOptionsFunction&&(F=F());var V;w=[...w,...B([(V=F==null?void 0:F.config)!==null&&V!==void 0?V:{}])]})}),w}function C(P){return[...P].reduceRight((U,O)=>m(O)?O({corePlugins:U}):(0,i.default)(O,U),t.default)}function b(P){return[...P].reduceRight((U,O)=>[...U,...O],[])}function D(P){let w=[...B(P),{prefix:"",important:!1,separator:":"}];var U,O;return(0,o.normalizeConfig)((0,n.defaults)({theme:R(E(x(w.map(G=>(U=G==null?void 0:G.theme)!==null&&U!==void 0?U:{})))),corePlugins:C(w.map(G=>G.corePlugins)),plugins:b(P.map(G=>(O=G==null?void 0:G.plugins)!==null&&O!==void 0?O:[]))},...w))}}(Cs);var Vs={},Ua={content:[],presets:[],darkMode:"media",theme:{accentColor:({theme:s})=>({...s("colors"),auto:"auto"}),animation:{none:"none",spin:"spin 1s linear infinite",ping:"ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",bounce:"bounce 1s infinite"},aria:{busy:'busy="true"',checked:'checked="true"',disabled:'disabled="true"',expanded:'expanded="true"',hidden:'hidden="true"',pressed:'pressed="true"',readonly:'readonly="true"',required:'required="true"',selected:'selected="true"'},aspectRatio:{auto:"auto",square:"1 / 1",video:"16 / 9"},backdropBlur:({theme:s})=>s("blur"),backdropBrightness:({theme:s})=>s("brightness"),backdropContrast:({theme:s})=>s("contrast"),backdropGrayscale:({theme:s})=>s("grayscale"),backdropHueRotate:({theme:s})=>s("hueRotate"),backdropInvert:({theme:s})=>s("invert"),backdropOpacity:({theme:s})=>s("opacity"),backdropSaturate:({theme:s})=>s("saturate"),backdropSepia:({theme:s})=>s("sepia"),backgroundColor:({theme:s})=>s("colors"),backgroundImage:{none:"none","gradient-to-t":"linear-gradient(to top, var(--tw-gradient-stops))","gradient-to-tr":"linear-gradient(to top right, var(--tw-gradient-stops))","gradient-to-r":"linear-gradient(to right, var(--tw-gradient-stops))","gradient-to-br":"linear-gradient(to bottom right, var(--tw-gradient-stops))","gradient-to-b":"linear-gradient(to bottom, var(--tw-gradient-stops))","gradient-to-bl":"linear-gradient(to bottom left, var(--tw-gradient-stops))","gradient-to-l":"linear-gradient(to left, var(--tw-gradient-stops))","gradient-to-tl":"linear-gradient(to top left, var(--tw-gradient-stops))"},backgroundOpacity:({theme:s})=>s("opacity"),backgroundPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},backgroundSize:{auto:"auto",cover:"cover",contain:"contain"},blur:{0:"0",none:"0",sm:"4px",DEFAULT:"8px",md:"12px",lg:"16px",xl:"24px","2xl":"40px","3xl":"64px"},borderColor:({theme:s})=>({...s("colors"),DEFAULT:s("colors.gray.200","currentColor")}),borderOpacity:({theme:s})=>s("opacity"),borderRadius:{none:"0px",sm:"0.125rem",DEFAULT:"0.25rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem","3xl":"1.5rem",full:"9999px"},borderSpacing:({theme:s})=>({...s("spacing")}),borderWidth:{DEFAULT:"1px",0:"0px",2:"2px",4:"4px",8:"8px"},boxShadow:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",DEFAULT:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)",inner:"inset 0 2px 4px 0 rgb(0 0 0 / 0.05)",none:"none"},boxShadowColor:({theme:s})=>s("colors"),brightness:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",200:"2"},caretColor:({theme:s})=>s("colors"),colors:({colors:s})=>({inherit:s.inherit,current:s.current,transparent:s.transparent,black:s.black,white:s.white,slate:s.slate,gray:s.gray,zinc:s.zinc,neutral:s.neutral,stone:s.stone,red:s.red,orange:s.orange,amber:s.amber,yellow:s.yellow,lime:s.lime,green:s.green,emerald:s.emerald,teal:s.teal,cyan:s.cyan,sky:s.sky,blue:s.blue,indigo:s.indigo,violet:s.violet,purple:s.purple,fuchsia:s.fuchsia,pink:s.pink,rose:s.rose}),columns:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12","3xs":"16rem","2xs":"18rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem"},container:{},content:{none:"none"},contrast:{0:"0",50:".5",75:".75",100:"1",125:"1.25",150:"1.5",200:"2"},cursor:{auto:"auto",default:"default",pointer:"pointer",wait:"wait",text:"text",move:"move",help:"help","not-allowed":"not-allowed",none:"none","context-menu":"context-menu",progress:"progress",cell:"cell",crosshair:"crosshair","vertical-text":"vertical-text",alias:"alias",copy:"copy","no-drop":"no-drop",grab:"grab",grabbing:"grabbing","all-scroll":"all-scroll","col-resize":"col-resize","row-resize":"row-resize","n-resize":"n-resize","e-resize":"e-resize","s-resize":"s-resize","w-resize":"w-resize","ne-resize":"ne-resize","nw-resize":"nw-resize","se-resize":"se-resize","sw-resize":"sw-resize","ew-resize":"ew-resize","ns-resize":"ns-resize","nesw-resize":"nesw-resize","nwse-resize":"nwse-resize","zoom-in":"zoom-in","zoom-out":"zoom-out"},divideColor:({theme:s})=>s("borderColor"),divideOpacity:({theme:s})=>s("borderOpacity"),divideWidth:({theme:s})=>s("borderWidth"),dropShadow:{sm:"0 1px 1px rgb(0 0 0 / 0.05)",DEFAULT:["0 1px 2px rgb(0 0 0 / 0.1)","0 1px 1px rgb(0 0 0 / 0.06)"],md:["0 4px 3px rgb(0 0 0 / 0.07)","0 2px 2px rgb(0 0 0 / 0.06)"],lg:["0 10px 8px rgb(0 0 0 / 0.04)","0 4px 3px rgb(0 0 0 / 0.1)"],xl:["0 20px 13px rgb(0 0 0 / 0.03)","0 8px 5px rgb(0 0 0 / 0.08)"],"2xl":"0 25px 25px rgb(0 0 0 / 0.15)",none:"0 0 #0000"},fill:({theme:s})=>({none:"none",...s("colors")}),flex:{1:"1 1 0%",auto:"1 1 auto",initial:"0 1 auto",none:"none"},flexBasis:({theme:s})=>({auto:"auto",...s("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%"}),flexGrow:{0:"0",DEFAULT:"1"},flexShrink:{0:"0",DEFAULT:"1"},fontFamily:{sans:["ui-sans-serif","system-ui","-apple-system","BlinkMacSystemFont",'"Segoe UI"',"Roboto",'"Helvetica Neue"',"Arial",'"Noto Sans"',"sans-serif",'"Apple Color Emoji"','"Segoe UI Emoji"','"Segoe UI Symbol"','"Noto Color Emoji"'],serif:["ui-serif","Georgia","Cambria",'"Times New Roman"',"Times","serif"],mono:["ui-monospace","SFMono-Regular","Menlo","Monaco","Consolas",'"Liberation Mono"','"Courier New"',"monospace"]},fontSize:{xs:["0.75rem",{lineHeight:"1rem"}],sm:["0.875rem",{lineHeight:"1.25rem"}],base:["1rem",{lineHeight:"1.5rem"}],lg:["1.125rem",{lineHeight:"1.75rem"}],xl:["1.25rem",{lineHeight:"1.75rem"}],"2xl":["1.5rem",{lineHeight:"2rem"}],"3xl":["1.875rem",{lineHeight:"2.25rem"}],"4xl":["2.25rem",{lineHeight:"2.5rem"}],"5xl":["3rem",{lineHeight:"1"}],"6xl":["3.75rem",{lineHeight:"1"}],"7xl":["4.5rem",{lineHeight:"1"}],"8xl":["6rem",{lineHeight:"1"}],"9xl":["8rem",{lineHeight:"1"}]},fontWeight:{thin:"100",extralight:"200",light:"300",normal:"400",medium:"500",semibold:"600",bold:"700",extrabold:"800",black:"900"},gap:({theme:s})=>s("spacing"),gradientColorStops:({theme:s})=>s("colors"),gradientColorStopPositions:{"0%":"0%","5%":"5%","10%":"10%","15%":"15%","20%":"20%","25%":"25%","30%":"30%","35%":"35%","40%":"40%","45%":"45%","50%":"50%","55%":"55%","60%":"60%","65%":"65%","70%":"70%","75%":"75%","80%":"80%","85%":"85%","90%":"90%","95%":"95%","100%":"100%"},grayscale:{0:"0",DEFAULT:"100%"},gridAutoColumns:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridAutoRows:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridColumn:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridColumnEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13"},gridColumnStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13"},gridRow:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-full":"1 / -1"},gridRowEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7"},gridRowStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7"},gridTemplateColumns:{none:"none",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))"},gridTemplateRows:{none:"none",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))"},height:({theme:s})=>({auto:"auto",...s("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%",full:"100%",screen:"100vh",min:"min-content",max:"max-content",fit:"fit-content"}),hueRotate:{0:"0deg",15:"15deg",30:"30deg",60:"60deg",90:"90deg",180:"180deg"},inset:({theme:s})=>({auto:"auto",...s("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%"}),invert:{0:"0",DEFAULT:"100%"},keyframes:{spin:{to:{transform:"rotate(360deg)"}},ping:{"75%, 100%":{transform:"scale(2)",opacity:"0"}},pulse:{"50%":{opacity:".5"}},bounce:{"0%, 100%":{transform:"translateY(-25%)",animationTimingFunction:"cubic-bezier(0.8,0,1,1)"},"50%":{transform:"none",animationTimingFunction:"cubic-bezier(0,0,0.2,1)"}}},letterSpacing:{tighter:"-0.05em",tight:"-0.025em",normal:"0em",wide:"0.025em",wider:"0.05em",widest:"0.1em"},lineHeight:{none:"1",tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625",loose:"2",3:".75rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem"},listStyleType:{none:"none",disc:"disc",decimal:"decimal"},listStyleImage:{none:"none"},margin:({theme:s})=>({auto:"auto",...s("spacing")}),lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6"},maxHeight:({theme:s})=>({...s("spacing"),none:"none",full:"100%",screen:"100vh",min:"min-content",max:"max-content",fit:"fit-content"}),maxWidth:({theme:s,breakpoints:e})=>({none:"none",0:"0rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",prose:"65ch",...e(s("screens"))}),minHeight:{0:"0px",full:"100%",screen:"100vh",min:"min-content",max:"max-content",fit:"fit-content"},minWidth:{0:"0px",full:"100%",min:"min-content",max:"max-content",fit:"fit-content"},objectPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},opacity:{0:"0",5:"0.05",10:"0.1",20:"0.2",25:"0.25",30:"0.3",40:"0.4",50:"0.5",60:"0.6",70:"0.7",75:"0.75",80:"0.8",90:"0.9",95:"0.95",100:"1"},order:{first:"-9999",last:"9999",none:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12"},outlineColor:({theme:s})=>s("colors"),outlineOffset:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},outlineWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},padding:({theme:s})=>s("spacing"),placeholderColor:({theme:s})=>s("colors"),placeholderOpacity:({theme:s})=>s("opacity"),ringColor:({theme:s})=>({DEFAULT:s("colors.blue.500","#3b82f6"),...s("colors")}),ringOffsetColor:({theme:s})=>s("colors"),ringOffsetWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},ringOpacity:({theme:s})=>({DEFAULT:"0.5",...s("opacity")}),ringWidth:{DEFAULT:"3px",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},rotate:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",45:"45deg",90:"90deg",180:"180deg"},saturate:{0:"0",50:".5",100:"1",150:"1.5",200:"2"},scale:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5"},screens:{sm:"640px",md:"768px",lg:"1024px",xl:"1280px","2xl":"1536px"},scrollMargin:({theme:s})=>({...s("spacing")}),scrollPadding:({theme:s})=>s("spacing"),sepia:{0:"0",DEFAULT:"100%"},skew:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg"},space:({theme:s})=>({...s("spacing")}),spacing:{px:"1px",0:"0px",.5:"0.125rem",1:"0.25rem",1.5:"0.375rem",2:"0.5rem",2.5:"0.625rem",3:"0.75rem",3.5:"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",11:"2.75rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"},stroke:({theme:s})=>({none:"none",...s("colors")}),strokeWidth:{0:"0",1:"1",2:"2"},supports:{},data:{},textColor:({theme:s})=>s("colors"),textDecorationColor:({theme:s})=>s("colors"),textDecorationThickness:{auto:"auto","from-font":"from-font",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},textIndent:({theme:s})=>({...s("spacing")}),textOpacity:({theme:s})=>s("opacity"),textUnderlineOffset:{auto:"auto",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},transformOrigin:{center:"center",top:"top","top-right":"top right",right:"right","bottom-right":"bottom right",bottom:"bottom","bottom-left":"bottom left",left:"left","top-left":"top left"},transitionDelay:{0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms"},transitionDuration:{DEFAULT:"150ms",0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms"},transitionProperty:{none:"none",all:"all",DEFAULT:"color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter",colors:"color, background-color, border-color, text-decoration-color, fill, stroke",opacity:"opacity",shadow:"box-shadow",transform:"transform"},transitionTimingFunction:{DEFAULT:"cubic-bezier(0.4, 0, 0.2, 1)",linear:"linear",in:"cubic-bezier(0.4, 0, 1, 1)",out:"cubic-bezier(0, 0, 0.2, 1)","in-out":"cubic-bezier(0.4, 0, 0.2, 1)"},translate:({theme:s})=>({...s("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%"}),width:({theme:s})=>({auto:"auto",...s("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",screen:"100vw",min:"min-content",max:"max-content",fit:"fit-content"}),willChange:{auto:"auto",scroll:"scroll-position",contents:"contents",transform:"transform"},zIndex:{auto:"auto",0:"0",10:"10",20:"20",30:"30",40:"40",50:"50"}},plugins:[]};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return r}});const e=i(Ua),t=Rt;function i(n){return n&&n.__esModule?n:{default:n}}function r(n){var a;const o=((a=n==null?void 0:n.presets)!==null&&a!==void 0?a:[e.default]).slice().reverse().flatMap(u=>r(u instanceof Function?u():u)),l={respectDefaultRingColorOpacity:{theme:{ringColor:({theme:u})=>({DEFAULT:"#3b82f67f",...u("colors")})}},disableColorOpacityUtilitiesByDefault:{corePlugins:{backgroundOpacity:!1,borderOpacity:!1,divideOpacity:!1,placeholderOpacity:!1,ringOpacity:!1,textOpacity:!1}}},c=Object.keys(l).filter(u=>(0,t.flagEnabled)(n,u)).map(u=>l[u]);return[n,...c,...o]}})(Vs),function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return r}});const e=i(Cs),t=i(Vs);function i(n){return n&&n.__esModule?n:{default:n}}function r(...n){let[,...a]=(0,t.default)(n[0]);return(0,e.default)([...n,...a])}}(Rs);let di=Rs;var Ga=(di.__esModule?di:{default:di}).default;const Ha=$a(Ga);let fi=oi;var we=(fi.__esModule?fi:{default:fi}).default;const Va={50:"#FCE3E4",100:"#F9CDCE",200:"#F39699",300:"#ED6368",400:"#E72C32",500:"#C4161C",600:"#9C1216",700:"#770D11",800:"#4E090B",900:"#290506"},ye={onprimary:we.white,warning:we.amber,error:we.rose,info:we.cyan,success:we.lime,primary:we.sky,brand:Va},Ka={...ye,warning:ye.warning[500],"warning-darken":ye.warning[600],"warning-lighten":ye.warning[400],success:ye.success[500],"success-darken":ye.success[600],"success-lighten":ye.success[400],error:ye.error[500],"error-darken":ye.error[600],"error-lighten":ye.error[400],info:ye.info[500],"info-darken":ye.info[600],"info-lighten":ye.info[400],primary:ye.primary[500],"primary-darken":ye.primary[600],"primary-lighten":ye.primary[400],onsurface:we.slate[500],onbackground:we.slate[700],surface:we.slate[50],background:we.white},mi=Ha({prefix:"e-",corePlugins:{preflight:!1},content:["./src/**/*.{html,js,vue,ts}"],theme:{extend:{colors:Ka,maxWidth:{"1/12":"8.333333333%","2/12":"16.666666666%","3/12":"25%","4/12":"33.333333333%","5/12":"41.666666667%","6/12":"50%","7/12":"58.333333334%","8/12":"66.666666666%","9/12":"75%","10/12":"83.333333334%","11/12":"91.666666666%","12/12":"100%"}},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem","5xl":"3rem","6xl":"3.75rem","7xl":"4.5rem","8xl":"6rem","9xl":"8rem"}},plugins:[],safelist:[{pattern:/e-w-(full|auto)/,variants:["lg","md","sm","xs","xl"]},{pattern:/e-grow/,variants:["lg","md","sm","xs","xl"]},{pattern:/e-basis-(\d{1,2}\/\d{1,2}|full|auto|0)/,variants:["lg","md","sm","xs","xl"]},{pattern:/^!?e-max-w-(\d{1,2}\/\d{1,2})/,variants:["lg","md","sm","xs","xl"]},{pattern:/e-offset-(1[0-2]|[1-9])/,variants:["lg","md","sm","xs","xl"]},{pattern:/e-items-(start|center|end|baseline|stretch)/},{pattern:/e-self-(start|center|end|baseline|stretch)/},{pattern:/e-justify-(around|between|center|end|evenly|normal|start|stretch)/,variants:["lg","md","sm","xs","xl"]},{pattern:/e-content-(around|baseline|between|center|end|evenly|normal|start|stretch)/}]}),Ks=mi.theme.fontSize,Ws=mi.theme.colors,Wa=[z.dot,z.xs,z.sm,z.md,z.lg,z.xl],za=[z.xs,z.sm,z.md,z.lg,z.xl,z["2xl"]],zs=[z.xs,z.sm,z.md,z.base,z.lg,z.xl,z["2xl"],z["3xl"],z["4xl"],z["5xl"],z["6xl"],z["7xl"],z["8xl"],z["9xl"]],Ya=[ue.warning,ue.error,ue.info,ue.success,ue.primary,ue.default],ja=["play","pause","ended","loadeddata","waiting","playing","timeupdate","canplay","canplaythrough","statechanged"],qa=Ee.extend({name:"EIcon",props:{icon:{type:String,default:""},color:{type:String,default:ue.default},size:{type:String,default:z.sm}},computed:{sizes(){return zs.reduce((s,e)=>({...s,[e]:`e-text-${e}`}),{})},iconClasses(){var i,r;const s=this.sizes[this.size]||this.sizes[z.sm],e=`${((r=(i=this.icon)==null?void 0:i.split(" "))==null?void 0:r.length)>1?this.icon:`fa fa-${this.icon}`}`;return["e-inline-flex e-items-center e-justify-center e-rounded-full",this.color,e,s]}}});var Xa=function(){var e=this,t=e._self._c;return t("div",{staticClass:"e-icon"},[t("i",{class:e.iconClasses})])},Za=[],Qa=Ie(qa,Xa,Za,!1,null,null,null,null);const Ys=Qa.exports,Ja=Ee.extend({name:"ESpinner",props:{dark:{type:Boolean,default:!1},color:{type:Boolean,default:!0},animationDuration:{type:[Number,String],default:1e3},size:{type:String,default:z.base},opacity:{type:[String,Number],default:1}},data(){return{sizes:Ks,colors:Ws}},computed:{computedSize(){return this.sizes[z[this.size]]||this.size||this.sizes[z.base]},fill(){let s={primary:this.colors.brand[500],secondary:this.colors.neutral[300]};return this.dark&&!this.color&&(s={primary:this.colors.neutral[100],secondary:this.colors.neutral[100]}),!this.dark&&this.color&&(s={primary:this.colors.brand[500],secondary:this.colors.neutral[950]}),!this.dark&&!this.color&&(s={primary:this.colors.neutral[200],secondary:this.colors.neutral[200]}),s}},methods:{getNthPathStyle(s){const e=typeof this.animationDuration=="string"?Number.parseInt(this.animationDuration):this.animationDuration;return{animationDuration:`${this.animationDuration}ms`,animationDelay:`${s/10*e}ms`,fill:`${this.fill[s%2===0?"primary":"secondary"]}`}}}}),qh="";var eo=function(){var e=this,t=e._self._c;return t("svg",{staticClass:"e-spinner e-block",class:{"e-spinner--dark":e.dark,"e-spinner--grey":!e.color},style:{opacity:e.opacity},attrs:{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 1629.32 1608.86",width:e.computedSize,height:e.computedSize}},[t("path",{staticClass:"e-spinner__primary",style:e.getNthPathStyle(0),attrs:{d:"m1254.12,591.61C992.01,401.11,439.78,0,439.78,0h601.2c14.3,0,48.95,9.02,62.54,38.01,55.27,117.88,111.32,235.46,170.48,351.43,33.16,70.9-8.99,170.35-19.87,202.16"}}),t("path",{staticClass:"e-spinner__secondary",style:e.getNthPathStyle(1),attrs:{d:"m1404.65,131.67c-29.37,89.94-55.8,170.95-82.25,251.93-4.05.87-8.1,1.73-12.15,2.61-40.61-83.95-81.21-167.9-123.12-254.54h217.51Z"}}),t("path",{staticClass:"e-spinner__primary",style:e.getNthPathStyle(2),attrs:{d:"m1129.06,1093.51c100.75-307.98,312.75-956.75,312.75-956.75,0,0,180.36,558.53,184.75,572.14,4.39,13.59,6.45,49.34-16.96,71.19-95.21,88.81-189.88,178.28-282.06,270.2-57.29,53.34-164.86,43.8-198.48,43.21"}}),t("path",{staticClass:"e-spinner__secondary",style:e.getNthPathStyle(3),attrs:{d:"m1342.3,1083.06c66.6-63.43,133.22-126.86,207.93-197.98,21.51,73.55,40.3,137.81,60.64,207.37h-263.35c-1.75-3.13-3.48-6.27-5.22-9.39"}}),t("path",{staticClass:"e-spinner__primary",style:e.getNthPathStyle(4),attrs:{d:"m610.27,1137.17c324.03-.53,1006.55-1.85,1006.55-1.85,0,0-474.19,345.83-485.74,354.25-11.55,8.42-44.87,21.56-72.94,6.14-114.11-62.68-228.69-124.66-344.81-183.5-68.56-37.76-93.12-142.93-103.06-175.04"}}),t("path",{staticClass:"e-spinner__secondary",style:e.getNthPathStyle(5),attrs:{d:"m938.58,1468.29c-62.81,42.58-118.35,80.24-180.28,122.23-28.35-87.22-54.62-168.03-80.89-248.86,2.62-2.92,5.26-5.85,7.9-8.76,81.89,43.78,163.79,87.56,253.26,135.39"}}),t("path",{staticClass:"e-spinner__primary",style:e.getNthPathStyle(6),attrs:{d:"m413.07,652.86c101.35,307.77,314.99,956,314.99,956,0,0-476.23-343.04-487.83-351.39-11.58-8.36-34.44-35.93-28.52-67.4,24.07-127.96,47.3-256.13,67.09-384.8,14.54-76.9,106.84-132.96,134.28-152.42"}}),t("path",{staticClass:"e-spinner__secondary",style:e.getNthPathStyle(7),attrs:{d:"m197.48,1068.8c-62.36-47.73-115.99-88.79-176.78-135.33,75.54-54.91,146.18-106.24,216.83-157.57,3.73,2.24,7.45,4.47,11.19,6.71-16.36,91.3-32.7,182.61-51.25,286.19"}}),t("path",{staticClass:"e-spinner__primary",style:e.getNthPathStyle(8),attrs:{d:"m813.58,314.41C551.63,505.15,0,907.07,0,907.07c0,0,180.68-558.4,185.09-572.01,4.39-13.59,23.65-43.78,55.41-47.8,129.19-16.29,258.32-33.41,386.86-53.99,77.67-9.72,159.3,60.97,186.22,81.13"}}),t("path",{staticClass:"e-spinner__secondary",style:e.getNthPathStyle(9),attrs:{d:"m635.14,199.78c-91.99,12.38-183.97,24.77-288.07,38.76,25.77-73.18,48.3-137.14,73.8-209.53,76.56,55.41,147.27,106.58,217.97,157.75-1.23,4.34-2.46,8.68-3.69,13.02"}})])},to=[],io=Ie(Ja,eo,to,!1,null,"29711f67",null,null);const gi=io.exports,so=Ee.extend({props:{align:{type:String,default:void 0},alignContent:{type:String,default:void 0},justify:{type:String,default:void 0},justifyXs:{type:String,default:void 0},justifySm:{type:String,default:void 0},justifyMd:{type:String,default:void 0},justifyLg:{type:String,default:void 0},justifyXl:{type:String,default:void 0},noGutters:{type:Boolean,default:!1}},computed:{justifyClasses(){return{[`e-justify-${this.justify}`]:!!this.justify,[`xs:e-justify-${this.justifySm}`]:!!this.justifySm,[`sm:e-justify-${this.justifySm}`]:!!this.justifySm,[`md:e-justify-${this.justifyMd}`]:!!this.justifyMd,[`lg:e-justify-${this.justifyLg}`]:!!this.justifyLg,[`xl:e-justify-${this.justifyXl}`]:!!this.justifyXl}},rowClasses(){return{...this.align?{[`e-items-${this.align}`]:!0}:{},...this.alignContent?{[`e-content-${this.alignContent}`]:!0}:{},...this.noGutters?{"e-row--no-gutters":!0}:{},...this.justifyClasses}}}}),Xh="";var ro=function(){var e=this,t=e._self._c;return e._self._setupProxy,t("div",{staticClass:"e-row e-flex e-flex-wrap",class:e.rowClasses},[e._t("default")],2)},no=[],ao=Ie(so,ro,no,!1,null,null,null,null);const js=ao.exports,oo=Ee.extend({props:{alignSelf:{type:String,default:"auto"},cols:{type:[Boolean,String,Number],default:void 0},lg:{type:[Boolean,String,Number],default:void 0},md:{type:[Boolean,String,Number],default:void 0},offset:{type:[String,Number],default:void 0},offsetLg:{type:[String,Number],default:void 0},offsetMd:{type:[String,Number],default:void 0},offsetSm:{type:[String,Number],default:void 0},offsetXs:{type:[String,Number],default:void 0},offsetXl:{type:[String,Number],default:void 0},sm:{type:[Boolean,String,Number],default:void 0},xs:{type:[Boolean,String,Number],default:void 0},xl:{type:[Boolean,String,Number],default:void 0}},computed:{colClasses(){return{...this.alignSelf?{[`e-self-${this.alignSelf}`]:!0}:{},[this.autoClasses("xs:",this.xs)]:this.isSizePropAuto(this.xs),[this.autoClasses("sm:",this.sm)]:this.isSizePropAuto(this.sm),[this.autoClasses("md:",this.md)]:this.isSizePropAuto(this.md),[this.autoClasses("lg:",this.lg)]:this.isSizePropAuto(this.lg),[this.autoClasses("xl:e",this.xl)]:this.isSizePropAuto(this.xl),[this.autoClasses("",this.cols)]:this.isSizePropAuto(this.cols,!0),"xs:e-basis-full xs:!e-max-w-12/12":this.xs===12||this.xs==="12","sm:e-basis-full sm:!e-max-w-12/12":this.sm===12||this.sm==="12","md:e-basis-full md:!e-max-w-12/12":this.md===12||this.md==="12","lg:e-basis-full lg:!e-max-w-12/12":this.lg===12||this.lg==="12","xl:e-basis-full xl:!e-max-w-12/12":this.xl===12||this.xl==="12","e-basis-full e-max-w-12/12":this.cols===12||this.cols==="12",[`xs:e-basis-${this.xs}/12 xs:!e-max-w-${this.xs}/12`]:this.isSizePropertyNumeric(this.xs),[`sm:e-basis-${this.sm}/12 sm:!e-max-w-${this.sm}/12`]:this.isSizePropertyNumeric(this.sm),[`md:e-basis-${this.md}/12 md:!e-max-w-${this.md}/12`]:this.isSizePropertyNumeric(this.md),[`lg:e-basis-${this.lg}/12 lg:!e-max-w-${this.lg}/12`]:this.isSizePropertyNumeric(this.lg),[`xl:e-basis-${this.xl}/12 xl:!e-max-w-${this.xl}/12`]:this.isSizePropertyNumeric(this.xl),[`e-basis-${this.cols}/12 !e-max-w-${this.cols}/12`]:this.isSizePropertyNumeric(this.cols),[`xs:e-offset-${this.offsetXs}`]:this.offsetXs!==void 0,[`sm:e-offset-${this.offsetSm}`]:this.offsetSm!==void 0,[`md:e-offset-${this.offsetMd}`]:this.offsetMd!==void 0,[`lg:e-offset-${this.offsetLg}`]:this.offsetLg!==void 0,[`xl:e-offset-${this.offsetXl}`]:this.offsetXl!==void 0,[`e-offset-${this.offset}`]:this.offset!==void 0}}},methods:{autoClasses(s,e){return`${s}e-basis-${e==="auto"?"auto":"0"} ${s}e-grow${e==="auto"?"-0":""} ${s}e-w-${e==="auto"?"auto":"full"}`},isSizePropAuto(s,e=!1){return s==="auto"||s===0||s==="0"||e&&!s},isSizePropertyNumeric(s){const e=Number.parseInt(s);return s!=="auto"&&!isNaN(e)&&e>=1&&e<12}}}),Zh="";var lo=function(){var e=this,t=e._self._c;return t("div",{staticClass:"e-col",class:e.colClasses},[e._t("default")],2)},co=[],uo=Ie(oo,lo,co,!1,null,null,null,null);const qs=uo.exports;function ho(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Xs={exports:{}};(function(s,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,c,u){if(u=u||{},l=l.trim(),c=c.trim(),!c){if(!u.alwaysNormalize)return l;var h=o.parseURL(l);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(c);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)):c;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var m=r.exec(f.path);f.netLoc=m[1],f.path=m[2]}f.netLoc&&!f.path&&(f.path="/");var g={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(g.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)g.path=f.path,d.params||(g.params=f.params,d.query||(g.query=f.query));else{var y=f.path,v=y.substring(0,y.lastIndexOf("/")+1)+d.path;g.path=o.normalizePath(v)}return g.path===null&&(g.path=u.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(g)},parseURL:function(l){var c=i.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};s.exports=o})()})(Xs);var pi=Xs.exports;function Zs(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(s,r).enumerable})),t.push.apply(t,i)}return t}function he(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Zs(Object(t),!0).forEach(function(i){go(s,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):Zs(Object(t)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(t,i))})}return s}function fo(s,e){if(typeof s!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e||"default");if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function mo(s){var e=fo(s,"string");return typeof e=="symbol"?e:String(e)}function go(s,e,t){return e=mo(e),e in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function oe(){return oe=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(s[i]=t[i])}return s},oe.apply(this,arguments)}const W=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},po=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=yo},yo=Number.MAX_SAFE_INTEGER||9007199254740991;let p=function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.BUFFER_RESET="hlsBufferReset",s.BUFFER_CODECS="hlsBufferCodecs",s.BUFFER_CREATED="hlsBufferCreated",s.BUFFER_APPENDING="hlsBufferAppending",s.BUFFER_APPENDED="hlsBufferAppended",s.BUFFER_EOS="hlsBufferEos",s.BUFFER_FLUSHING="hlsBufferFlushing",s.BUFFER_FLUSHED="hlsBufferFlushed",s.MANIFEST_LOADING="hlsManifestLoading",s.MANIFEST_LOADED="hlsManifestLoaded",s.MANIFEST_PARSED="hlsManifestParsed",s.LEVEL_SWITCHING="hlsLevelSwitching",s.LEVEL_SWITCHED="hlsLevelSwitched",s.LEVEL_LOADING="hlsLevelLoading",s.LEVEL_LOADED="hlsLevelLoaded",s.LEVEL_UPDATED="hlsLevelUpdated",s.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",s.LEVELS_UPDATED="hlsLevelsUpdated",s.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",s.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",s.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",s.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",s.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",s.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",s.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",s.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",s.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",s.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",s.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",s.CUES_PARSED="hlsCuesParsed",s.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",s.INIT_PTS_FOUND="hlsInitPtsFound",s.FRAG_LOADING="hlsFragLoading",s.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",s.FRAG_LOADED="hlsFragLoaded",s.FRAG_DECRYPTED="hlsFragDecrypted",s.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",s.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",s.FRAG_PARSING_METADATA="hlsFragParsingMetadata",s.FRAG_PARSED="hlsFragParsed",s.FRAG_BUFFERED="hlsFragBuffered",s.FRAG_CHANGED="hlsFragChanged",s.FPS_DROP="hlsFpsDrop",s.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",s.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",s.ERROR="hlsError",s.DESTROYING="hlsDestroying",s.KEY_LOADING="hlsKeyLoading",s.KEY_LOADED="hlsKeyLoaded",s.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",s.BACK_BUFFER_REACHED="hlsBackBufferReached",s.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",s}({}),q=function(s){return s.NETWORK_ERROR="networkError",s.MEDIA_ERROR="mediaError",s.KEY_SYSTEM_ERROR="keySystemError",s.MUX_ERROR="muxError",s.OTHER_ERROR="otherError",s}({}),_=function(s){return s.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",s.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",s.KEY_SYSTEM_NO_SESSION="keySystemNoSession",s.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",s.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",s.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",s.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",s.MANIFEST_LOAD_ERROR="manifestLoadError",s.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",s.MANIFEST_PARSING_ERROR="manifestParsingError",s.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",s.LEVEL_EMPTY_ERROR="levelEmptyError",s.LEVEL_LOAD_ERROR="levelLoadError",s.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",s.LEVEL_PARSING_ERROR="levelParsingError",s.LEVEL_SWITCH_ERROR="levelSwitchError",s.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",s.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",s.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",s.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",s.FRAG_LOAD_ERROR="fragLoadError",s.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",s.FRAG_DECRYPT_ERROR="fragDecryptError",s.FRAG_PARSING_ERROR="fragParsingError",s.FRAG_GAP="fragGap",s.REMUX_ALLOC_ERROR="remuxAllocError",s.KEY_LOAD_ERROR="keyLoadError",s.KEY_LOAD_TIMEOUT="keyLoadTimeOut",s.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",s.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",s.BUFFER_APPEND_ERROR="bufferAppendError",s.BUFFER_APPENDING_ERROR="bufferAppendingError",s.BUFFER_STALLED_ERROR="bufferStalledError",s.BUFFER_FULL_ERROR="bufferFullError",s.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",s.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.UNKNOWN="unknown",s}({});const Xe=function(){},yi={trace:Xe,debug:Xe,log:Xe,warn:Xe,info:Xe,error:Xe};let pt=yi;function vo(s){const e=self.console[s];return e?e.bind(self.console,`[${s}] >`):Xe}function xo(s,...e){e.forEach(function(t){pt[t]=s[t]?s[t].bind(s):vo(t)})}function To(s,e){if(typeof console=="object"&&s===!0||typeof s=="object"){xo(s,"debug","log","info","warn","error");try{pt.log(`Debug logs enabled for "${e}" in hls.js version 1.5.6`)}catch{pt=yi}}else pt=yi}const S=pt,Eo=/^(\d+)x(\d+)$/,Qs=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ae{constructor(e){typeof e=="string"&&(e=ae.parseAttrList(e)),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 i=new Uint8Array(t.length/2);for(let r=0;r<t.length/2;r++)i[r]=parseInt(t.slice(r*2,r*2+2),16);return i}else 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 i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}bool(e){return this[e]==="YES"}decimalResolution(e){const t=Eo.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const i={},r='"';for(Qs.lastIndex=0;(t=Qs.exec(e))!==null;){let n=t[2];n.indexOf(r)===0&&n.lastIndexOf(r)===n.length-1&&(n=n.slice(1,-1));const a=t[1].trim();i[a]=n}return i}}function So(s){return s!=="ID"&&s!=="CLASS"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function bo(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"}class Js{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const i=t.attr;for(const r in i)if(Object.prototype.hasOwnProperty.call(e,r)&&e[r]!==i[r]){S.warn(`DATERANGE tag attribute: "${r}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=r;break}e=oe(new ae({}),i,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const i=new Date(this.attr["END-DATE"]);W(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return e!==null?new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(W(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 isValid(){return!!this.id&&!this._badValueForSameId&&W(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class Dt{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 te={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class er{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[te.AUDIO]:null,[te.VIDEO]:null,[te.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,t){const i=e.split("@",2);let r;i.length===1?r=(t==null?void 0:t.byteRangeEndOffset)||0:r=parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=pi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class vi extends er{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=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.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new Dt,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 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 i=Object.keys(this.levelkeys);if(i.length===1)return this._decryptdata=this.levelkeys[i[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!W(this.programDateTime))return null;const e=W(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){const t=Object.keys(this.levelkeys),i=t.length;if(i>1||i===1&&this.levelkeys[t[0]].encrypted)return!0}return!1}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,i,r,n,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,n)}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[te.AUDIO]=null,e[te.VIDEO]=null,e[te.AUDIOVIDEO]=null}}class Ao extends er{constructor(e,t,i,r,n){super(i),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.stats=new Dt,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;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)}}const Lo=10;class Ro{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.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 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.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,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?W(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Lo}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(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end: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 lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function xi(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function Co(s){const e=Ti(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Do(s){const e=function(i,r,n){const a=i[r];i[r]=i[n],i[n]=a};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7)}function _o(s){const e=s.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),r=i[i.length-1].split(",");if(r.length===2){const n=r[0]==="base64",a=r[1];n?(i.splice(-1,1),t=xi(a)):t=Co(a)}}return t}function Ti(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}const et=typeof self!="undefined"?self:void 0;var ne={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},xe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function tr(s){switch(s){case xe.FAIRPLAY:return ne.FAIRPLAY;case xe.PLAYREADY:return ne.PLAYREADY;case xe.WIDEVINE:return ne.WIDEVINE;case xe.CLEARKEY:return ne.CLEARKEY}}var ir={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Io(s){if(s===ir.WIDEVINE)return ne.WIDEVINE}function sr(s){switch(s){case ne.FAIRPLAY:return xe.FAIRPLAY;case ne.PLAYREADY:return xe.PLAYREADY;case ne.WIDEVINE:return xe.WIDEVINE;case ne.CLEARKEY:return xe.CLEARKEY}}function Ei(s){const{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[ne.FAIRPLAY,ne.WIDEVINE,ne.PLAYREADY,ne.CLEARKEY].filter(r=>!!e[r]):[];return!i[ne.WIDEVINE]&&t&&i.push(ne.WIDEVINE),i}const rr=function(s){return et!=null&&(s=et.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function wo(s,e,t,i){let r;switch(s){case ne.FAIRPLAY:r=["cenc","sinf"];break;case ne.WIDEVINE:case ne.PLAYREADY:r=["cenc"];break;case ne.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return ko(r,e,t,i)}function ko(s,e,t,i){return[{initDataTypes:s,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs="${n}"`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs="${n}"`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function Ze(s,e,t){return Uint8Array.prototype.slice?s.slice(e,t):new Uint8Array(Array.prototype.slice.call(s,e,t))}const Si=(s,e)=>e+10<=s.length&&s[e]===73&&s[e+1]===68&&s[e+2]===51&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128,nr=(s,e)=>e+10<=s.length&&s[e]===51&&s[e+1]===68&&s[e+2]===73&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128,yt=(s,e)=>{const t=e;let i=0;for(;Si(s,e);){i+=10;const r=_t(s,e+6);i+=r,nr(s,e+10)&&(i+=10),e+=i}if(i>0)return s.subarray(t,t+i)},_t=(s,e)=>{let t=0;return t=(s[e]&127)<<21,t|=(s[e+1]&127)<<14,t|=(s[e+2]&127)<<7,t|=s[e+3]&127,t},Po=(s,e)=>Si(s,e)&&_t(s,e+6)+10<=s.length-e,bi=s=>{const e=or(s);for(let t=0;t<e.length;t++){const i=e[t];if(ar(i))return $o(i)}},ar=s=>s&&s.key==="PRIV"&&s.info==="com.apple.streaming.transportStreamTimestamp",Oo=s=>{const e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=_t(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}},or=s=>{let e=0;const t=[];for(;Si(s,e);){const i=_t(s,e+6);e+=10;const r=e+i;for(;e+8<r;){const n=Oo(s.subarray(e)),a=Fo(n);a&&t.push(a),e+=n.size+10}nr(s,e)&&(e+=10)}return t},Fo=s=>s.type==="PRIV"?Mo(s):s.type[0]==="W"?Bo(s):No(s),Mo=s=>{if(s.size<2)return;const e=ke(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}},No=s=>{if(s.size<2)return;if(s.type==="TXXX"){let t=1;const i=ke(s.data.subarray(t),!0);t+=i.length+1;const r=ke(s.data.subarray(t));return{key:s.type,info:i,data:r}}const e=ke(s.data.subarray(1));return{key:s.type,data:e}},Bo=s=>{if(s.type==="WXXX"){if(s.size<2)return;let t=1;const i=ke(s.data.subarray(t),!0);t+=i.length+1;const r=ke(s.data.subarray(t));return{key:s.type,info:i,data:r}}const e=ke(s.data);return{key:s.type,data:e}},$o=s=>{if(s.data.byteLength===8){const e=new Uint8Array(s.data),t=e[3]&1;let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}},ke=(s,e=!1)=>{const t=Uo();if(t){const c=t.decode(s);if(e){const u=c.indexOf("\0");return u!==-1?c.substring(0,u):c}return c.replace(/\0/g,"")}const i=s.length;let r,n,a,o="",l=0;for(;l<i;){if(r=s[l++],r===0&&e)return o;if(r===0||r===3)continue;switch(r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(r);break;case 12:case 13:n=s[l++],o+=String.fromCharCode((r&31)<<6|n&63);break;case 14:n=s[l++],a=s[l++],o+=String.fromCharCode((r&15)<<12|(n&63)<<6|(a&63)<<0);break}}return o};let Ai;function Uo(){if(!navigator.userAgent.includes("PlayStation 4"))return!Ai&&typeof self.TextDecoder!="undefined"&&(Ai=new self.TextDecoder("utf-8")),Ai}const Pe={hexDump:function(s){let e="";for(let t=0;t<s.length;t++){let i=s[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}},It=Math.pow(2,32)-1,Go=[].push,lr={video:1,audio:2,id3:3,text:4};function ce(s){return String.fromCharCode.apply(null,s)}function cr(s,e){const t=s[e]<<8|s[e+1];return t<0?65536+t:t}function Y(s,e){const t=hr(s,e);return t<0?4294967296+t:t}function ur(s,e){let t=Y(s,e);return t*=Math.pow(2,32),t+=Y(s,e+4),t}function hr(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function Li(s,e,t){s[e]=t>>24,s[e+1]=t>>16&255,s[e+2]=t>>8&255,s[e+3]=t&255}function Ho(s){const e=s.byteLength;for(let t=0;t<e;){const i=Y(s,t);if(i>8&&s[t+4]===109&&s[t+5]===111&&s[t+6]===111&&s[t+7]===102)return!0;t=i>1?t+i:e}return!1}function X(s,e){const t=[];if(!e.length)return t;const i=s.byteLength;for(let r=0;r<i;){const n=Y(s,r),a=ce(s.subarray(r+4,r+8)),o=n>1?r+n:i;if(a===e[0])if(e.length===1)t.push(s.subarray(r+8,o));else{const l=X(s.subarray(r+8,o),e.slice(1));l.length&&Go.apply(t,l)}r=o}return t}function Vo(s){const e=[],t=s[0];let i=8;const r=Y(s,i);i+=4;let n=0,a=0;t===0?(n=Y(s,i),a=Y(s,i+4),i+=8):(n=ur(s,i),a=ur(s,i+8),i+=16),i+=2;let o=s.length+a;const l=cr(s,i);i+=2;for(let c=0;c<l;c++){let u=i;const h=Y(s,u);u+=4;const d=h&2147483647;if((h&2147483648)>>>31===1)return S.warn("SIDX has hierarchical references (not supported)"),null;const m=Y(s,u);u+=4,e.push({referenceSize:d,subsegmentDuration:m,info:{duration:m/r,start:o,end:o+d-1}}),o+=d,u+=4,i=u}return{earliestPresentationTime:n,timescale:r,version:t,referencesCount:l,references:e}}function dr(s){const e=[],t=X(s,["moov","trak"]);for(let r=0;r<t.length;r++){const n=t[r],a=X(n,["tkhd"])[0];if(a){let o=a[0];const l=Y(a,o===0?12:20),c=X(n,["mdia","mdhd"])[0];if(c){o=c[0];const u=Y(c,o===0?12:20),h=X(n,["mdia","hdlr"])[0];if(h){const d=ce(h.subarray(8,12)),f={soun:te.AUDIO,vide:te.VIDEO}[d];if(f){const m=X(n,["mdia","minf","stbl","stsd"])[0],g=Ko(m);e[l]={timescale:u,type:f},e[f]=he({timescale:u,id:l},g)}}}}}return X(s,["moov","mvex","trex"]).forEach(r=>{const n=Y(r,4),a=e[n];a&&(a.default={duration:Y(r,12),flags:Y(r,20)})}),e}function Ko(s){const e=s.subarray(8),t=e.subarray(8+78),i=ce(e.subarray(4,8));let r=i;const n=i==="enca"||i==="encv";if(n){const o=X(e,[i])[0].subarray(i==="enca"?28:78);X(o,["sinf"]).forEach(c=>{const u=X(c,["schm"])[0];if(u){const h=ce(u.subarray(4,8));if(h==="cbcs"||h==="cenc"){const d=X(c,["frma"])[0];d&&(r=ce(d))}}})}switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const a=X(t,["avcC"])[0];r+="."+wt(a[1])+wt(a[2])+wt(a[3]);break}case"mp4a":{const a=X(e,[i])[0],o=X(a.subarray(28),["esds"])[0];if(o&&o.length>12){let l=4;if(o[l++]!==3)break;l=Ri(o,l),l+=2;const c=o[l++];if(c&128&&(l+=2),c&64&&(l+=o[l++]),o[l++]!==4)break;l=Ri(o,l);const u=o[l++];if(u===64)r+="."+wt(u);else break;if(l+=12,o[l++]!==5)break;l=Ri(o,l);const h=o[l++];let d=(h&248)>>3;d===31&&(d+=1+((h&7)<<3)+((o[l]&224)>>5)),r+="."+d}break}case"hvc1":case"hev1":{const a=X(t,["hvcC"])[0],o=a[1],l=["","A","B","C"][o>>6],c=o&31,u=Y(a,2),h=(o&32)>>5?"H":"L",d=a[12],f=a.subarray(6,12);r+="."+l+c,r+="."+u.toString(16).toUpperCase(),r+="."+h+d;let m="";for(let g=f.length;g--;){const y=f[g];(y||m)&&(m="."+y.toString(16).toUpperCase()+m)}r+=m;break}case"dvh1":case"dvhe":{const a=X(t,["dvcC"])[0],o=a[2]>>1&127,l=a[2]<<5&32|a[3]>>3&31;r+="."+Oe(o)+"."+Oe(l);break}case"vp09":{const a=X(t,["vpcC"])[0],o=a[4],l=a[5],c=a[6]>>4&15;r+="."+Oe(o)+"."+Oe(l)+"."+Oe(c);break}case"av01":{const a=X(t,["av1C"])[0],o=a[1]>>>5,l=a[1]&31,c=a[2]>>>7?"H":"M",u=(a[2]&64)>>6,h=(a[2]&32)>>5,d=o===2&&u?h?12:10:u?10:8,f=(a[2]&16)>>4,m=(a[2]&8)>>3,g=(a[2]&4)>>2,y=a[2]&3,v=1,T=1,x=1,L=0;r+="."+o+"."+Oe(l)+c+"."+Oe(d)+"."+f+"."+m+g+y+"."+Oe(v)+"."+Oe(T)+"."+Oe(x)+"."+L;break}}return{codec:r,encrypted:n}}function Ri(s,e){const t=e+5;for(;s[e++]&128&&e<t;);return e}function wt(s){return("0"+s.toString(16).toUpperCase()).slice(-2)}function Oe(s){return(s<10?"0":"")+s}function Wo(s,e){if(!s||!e)return s;const t=e.keyId;return t&&e.isCommonEncryption&&X(s,["moov","trak"]).forEach(r=>{const a=X(r,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=X(a,["enca"]);const l=o.length>0;l||(o=X(a,["encv"])),o.forEach(c=>{const u=l?c.subarray(28):c.subarray(78);X(u,["sinf"]).forEach(d=>{const f=fr(d);if(f){const m=f.subarray(8,24);m.some(g=>g!==0)||(S.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${Pe.hexDump(m)} -> ${Pe.hexDump(t)}`),f.set(t,8))}})})}),s}function fr(s){const e=X(s,["schm"])[0];if(e){const t=ce(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return X(s,["schi","tenc"])[0]}return S.error("[eme] missing 'schm' box"),null}function zo(s,e){return X(e,["moof","traf"]).reduce((t,i)=>{const r=X(i,["tfdt"])[0],n=r[0],a=X(i,["tfhd"]).reduce((o,l)=>{const c=Y(l,4),u=s[c];if(u){let h=Y(r,4);if(n===1){if(h===It)return S.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;h*=It+1,h+=Y(r,8)}const d=u.timescale||9e4,f=h/d;if(W(f)&&(o===null||f<o))return f}return o},null);return a!==null&&W(a)&&(t===null||a<t)?a:t},null)}function Yo(s,e){let t=0,i=0,r=0;const n=X(s,["moof","traf"]);for(let a=0;a<n.length;a++){const o=n[a],l=X(o,["tfhd"])[0],c=Y(l,4),u=e[c];if(!u)continue;const h=u.default,d=Y(l,0)|(h==null?void 0:h.flags);let f=h==null?void 0:h.duration;d&8&&(d&2?f=Y(l,12):f=Y(l,8));const m=u.timescale||9e4,g=X(o,["trun"]);for(let y=0;y<g.length;y++){if(t=jo(g[y]),!t&&f){const v=Y(g[y],4);t=f*v}u.type===te.VIDEO?i+=t/m:u.type===te.AUDIO&&(r+=t/m)}}if(i===0&&r===0){let a=1/0,o=0,l=0;const c=X(s,["sidx"]);for(let u=0;u<c.length;u++){const h=Vo(c[u]);if(h!=null&&h.references){a=Math.min(a,h.earliestPresentationTime/h.timescale);const d=h.references.reduce((f,m)=>f+m.info.duration||0,0);o=Math.max(o,d+h.earliestPresentationTime/h.timescale),l=o-a}}if(l&&W(l))return l}return i||r}function jo(s){const e=Y(s,0);let t=8;e&1&&(t+=4),e&4&&(t+=4);let i=0;const r=Y(s,4);for(let n=0;n<r;n++){if(e&256){const a=Y(s,t);i+=a,t+=4}e&512&&(t+=4),e&1024&&(t+=4),e&2048&&(t+=4)}return i}function qo(s,e,t){X(e,["moof","traf"]).forEach(i=>{X(i,["tfhd"]).forEach(r=>{const n=Y(r,4),a=s[n];if(!a)return;const o=a.timescale||9e4;X(i,["tfdt"]).forEach(l=>{const c=l[0],u=t*o;if(u){let h=Y(l,4);if(c===0)h-=u,h=Math.max(h,0),Li(l,4,h);else{h*=Math.pow(2,32),h+=Y(l,8),h-=u,h=Math.max(h,0);const d=Math.floor(h/(It+1)),f=Math.floor(h%(It+1));Li(l,4,d),Li(l,8,f)}}})})})}function Xo(s){const e={valid:null,remainder:null},t=X(s,["moof"]);if(t.length<2)return e.remainder=s,e;const i=t[t.length-1];return e.valid=Ze(s,0,i.byteOffset-8),e.remainder=Ze(s,i.byteOffset-8),e}function be(s,e){const t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function mr(s,e){const t=[],i=e.samples,r=e.timescale,n=e.id;let a=!1;return X(i,["moof"]).map(l=>{const c=l.byteOffset-8;X(l,["traf"]).map(h=>{const d=X(h,["tfdt"]).map(f=>{const m=f[0];let g=Y(f,4);return m===1&&(g*=Math.pow(2,32),g+=Y(f,8)),g/r})[0];return d!==void 0&&(s=d),X(h,["tfhd"]).map(f=>{const m=Y(f,4),g=Y(f,0)&16777215,y=(g&1)!==0,v=(g&2)!==0,T=(g&8)!==0;let x=0;const L=(g&16)!==0;let E=0;const k=(g&32)!==0;let R=8;m===n&&(y&&(R+=8),v&&(R+=4),T&&(x=Y(f,R),R+=4),L&&(E=Y(f,R),R+=4),k&&(R+=4),e.type==="video"&&(a=Zo(e.codec)),X(h,["trun"]).map(B=>{const C=B[0],b=Y(B,0)&16777215,D=(b&1)!==0;let P=0;const w=(b&4)!==0,U=(b&256)!==0;let O=0;const G=(b&512)!==0;let F=0;const V=(b&1024)!==0,H=(b&2048)!==0;let N=0;const J=Y(B,4);let Q=8;D&&(P=Y(B,Q),Q+=4),w&&(Q+=4);let ie=P+c;for(let le=0;le<J;le++){if(U?(O=Y(B,Q),Q+=4):O=x,G?(F=Y(B,Q),Q+=4):F=E,V&&(Q+=4),H&&(C===0?N=Y(B,Q):N=hr(B,Q),Q+=4),e.type===te.VIDEO){let me=0;for(;me<F;){const pe=Y(i,ie);if(ie+=4,Qo(a,i[ie])){const Re=i.subarray(ie,ie+pe);gr(Re,a?2:1,s+N/r,t)}ie+=pe,me+=pe+4}}s+=O/r}}))})})}),t}function Zo(s){if(!s)return!1;const e=s.indexOf("."),t=e<0?s:s.substring(0,e);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function Qo(s,e){if(s){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function gr(s,e,t,i){const r=pr(s);let n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(l===255);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(l===255);const c=r.length-n;let u=n;if(o<c)n+=o;else if(o>c){S.error(`Malformed SEI payload. ${o} is too small, only ${c} bytes left to parse.`);break}if(a===4){if(r[u++]===181){const d=cr(r,u);if(u+=2,d===49){const f=Y(r,u);if(u+=4,f===1195456820){const m=r[u++];if(m===3){const g=r[u++],y=31&g,v=64&g,T=v?2+y*3:0,x=new Uint8Array(T);if(v){x[0]=g;for(let L=1;L<T;L++)x[L]=r[u++]}i.push({type:m,payloadType:a,pts:t,bytes:x})}}}}}else if(a===5&&o>16){const h=[];for(let m=0;m<16;m++){const g=r[u++].toString(16);h.push(g.length==1?"0"+g:g),(m===3||m===5||m===7||m===9)&&h.push("-")}const d=o-16,f=new Uint8Array(d);for(let m=0;m<d;m++)f[m]=r[u++];i.push({payloadType:a,pts:t,uuid:h.join(""),userData:ke(f),userDataBytes:f})}}}function pr(s){const e=s.byteLength,t=[];let i=1;for(;i<e-2;)s[i]===0&&s[i+1]===0&&s[i+2]===3?(t.push(i+2),i+=2):i++;if(t.length===0)return s;const r=e-t.length,n=new Uint8Array(r);let a=0;for(i=0;i<r;a++,i++)a===t[0]&&(a++,t.shift()),n[i]=s[a];return n}function Jo(s){const e=s[0];let t="",i="",r=0,n=0,a=0,o=0,l=0,c=0;if(e===0){for(;ce(s.subarray(c,c+1))!=="\0";)t+=ce(s.subarray(c,c+1)),c+=1;for(t+=ce(s.subarray(c,c+1)),c+=1;ce(s.subarray(c,c+1))!=="\0";)i+=ce(s.subarray(c,c+1)),c+=1;i+=ce(s.subarray(c,c+1)),c+=1,r=Y(s,12),n=Y(s,16),o=Y(s,20),l=Y(s,24),c=28}else if(e===1){c+=4,r=Y(s,c),c+=4;const h=Y(s,c);c+=4;const d=Y(s,c);for(c+=4,a=2**32*h+d,po(a)||(a=Number.MAX_SAFE_INTEGER,S.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Y(s,c),c+=4,l=Y(s,c),c+=4;ce(s.subarray(c,c+1))!=="\0";)t+=ce(s.subarray(c,c+1)),c+=1;for(t+=ce(s.subarray(c,c+1)),c+=1;ce(s.subarray(c,c+1))!=="\0";)i+=ce(s.subarray(c,c+1)),c+=1;i+=ce(s.subarray(c,c+1)),c+=1}const u=s.subarray(c,s.byteLength);return{schemeIdUri:t,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:u}}function el(s,...e){const t=e.length;let i=8,r=t;for(;r--;)i+=e[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=i&255,n.set(s,4),r=0,i=8;r<t;r++)n.set(e[r],i),i+=e[r].byteLength;return n}function tl(s,e,t){if(s.byteLength!==16)throw new RangeError("Invalid system id");let i,r;if(e){i=1,r=new Uint8Array(e.length*16);for(let o=0;o<e.length;o++){const l=e[o];if(l.byteLength!==16)throw new RangeError("Invalid key");r.set(l,o*16)}}else i=0,r=new Uint8Array;let n;i>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&&t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),el([112,115,115,104],new Uint8Array([i,0,0,0]),s,n,r,a,t||new Uint8Array)}function il(s){if(!(s instanceof ArrayBuffer)||s.byteLength<32)return null;const e={version:0,systemId:"",kids:null,data:null},t=new DataView(s),i=t.getUint32(0);if(s.byteLength!==i&&i>44||t.getUint32(4)!==1886614376||(e.version=t.getUint32(8)>>>24,e.version>1))return null;e.systemId=Pe.hexDump(new Uint8Array(s,12,16));const n=t.getUint32(28);if(e.version===0){if(i-32<n)return null;e.data=new Uint8Array(s,32,n)}else if(e.version===1){e.kids=[];for(let a=0;a<n;a++)e.kids.push(new Uint8Array(s,32+a*16,16))}return e}let kt={};class vt{static clearKeyUriToKeyIdMap(){kt={}}constructor(e,t,i,r=[1],n=null){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=i,this.keyFormatVersions=r,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&e!=="AES-128"}isSupported(){if(this.method){if(this.method==="AES-128"||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case xe.FAIRPLAY:case xe.WIDEVINE:case xe.PLAYREADY:case xe.CLEARKEY:return["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(this.method==="AES-128"&&this.uri&&!this.iv){typeof e!="number"&&(this.method==="AES-128"&&!this.iv&&S.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const i=sl(e);return new vt(this.method,this.uri,"identity",this.keyFormatVersions,i)}const t=_o(this.uri);if(t)switch(this.keyFormat){case xe.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case xe.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=tl(i,null,t);const r=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),n=String.fromCharCode.apply(null,Array.from(r)),a=n.substring(n.indexOf("<"),n.length),c=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("KID")[0];if(c){const u=c.childNodes[0]?c.childNodes[0].nodeValue:c.getAttribute("VALUE");if(u){const h=xi(u).subarray(0,16);Do(h),this.keyId=h}}break}default:{let i=t.subarray(0,16);if(i.length!==16){const r=new Uint8Array(16);r.set(i,16-i.length),i=r}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=kt[this.uri];if(!i){const r=Object.keys(kt).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,r),kt[this.uri]=i}this.keyId=i}return this}}function sl(s){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}const yr=/\{\$([a-zA-Z0-9-_]+)\}/g;function vr(s){return yr.test(s)}function Te(s,e,t){if(s.variableList!==null||s.hasVariableRefs)for(let i=t.length;i--;){const r=t[i],n=e[r];n&&(e[r]=Ci(s,n))}}function Ci(s,e){if(s.variableList!==null||s.hasVariableRefs){const t=s.variableList;return e.replace(yr,i=>{const r=i.substring(2,i.length-1),n=t==null?void 0:t[r];return n===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),i):n})}return e}function xr(s,e,t){let i=s.variableList;i||(s.variableList=i={});let r,n;if("QUERYPARAM"in e){r=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(r))n=a.get(r);else throw new Error(`"${r}" does not match any query parameter in URI: "${t}"`)}catch(a){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else r=e.NAME,n=e.VALUE;r in i?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):i[r]=n||""}function rl(s,e,t){const i=e.IMPORT;if(t&&i in t){let r=s.variableList;r||(s.variableList=r={}),r[i]=t[i]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function tt(s=!0){return typeof self=="undefined"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const Pt={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,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 nl(s,e){const t=Pt[e];return!!t&&!!t[s.slice(0,4)]}function Di(s,e,t=!0){return!s.split(",").some(i=>!Tr(i,e,t))}function Tr(s,e,t=!0){var i;const r=tt(t);return(i=r==null?void 0:r.isTypeSupported(xt(s,e)))!=null?i:!1}function xt(s,e){return`${e}/mp4;codecs="${s}"`}function Er(s){if(s){const e=s.substring(0,4);return Pt.video[e]}return 2}function Ot(s){return s.split(",").reduce((e,t)=>{const i=Pt.video[t];return i?(i*2+e)/(e?3:2):(Pt.audio[t]+e)/(e?2:1)},0)}const _i={};function al(s,e=!0){if(_i[s])return _i[s];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[s];for(let i=0;i<t.length;i++)if(Tr(t[i],"audio",e))return _i[s]=t[i],t[i];return s}const ol=/flac|opus/i;function Ft(s,e=!0){return s.replace(ol,t=>al(t.toLowerCase(),e))}function Sr(s,e){return s&&s!=="mp4a"?s:e}function ll(s){const e=s.split(".");if(e.length>2){let t=e.shift()+".";return t+=parseInt(e.shift()).toString(16),t+=("000"+parseInt(e.shift()).toString(16)).slice(-4),t}return s}const br=/#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,Ar=/#EXT-X-MEDIA:(.*)/g,cl=/^#EXT(?:INF|-X-TARGETDURATION):/m,Lr=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),ul=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(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 Fe{static findGroup(e,t){for(let i=0;i<e.length;i++){const r=e[i];if(r.id===t)return r}}static resolve(e,t){return pi.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return cl.test(e)}static parseMasterPlaylist(e,t){const i=vr(e),r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];br.lastIndex=0;let a;for(;(a=br.exec(e))!=null;)if(a[1]){var o;const c=new ae(a[1]);Te(r,c,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const u=Ci(r,a[2]),h={attrs:c,bitrate:c.decimalInteger("BANDWIDTH")||c.decimalInteger("AVERAGE-BANDWIDTH"),name:c.NAME,url:Fe.resolve(u,t)},d=c.decimalResolution("RESOLUTION");d&&(h.width=d.width,h.height=d.height),hl(c.CODECS,h),(o=h.unknownCodecs)!=null&&o.length||n.push(h),r.levels.push(h)}else if(a[3]){const c=a[3],u=a[4];switch(c){case"SESSION-DATA":{const h=new ae(u);Te(r,h,["DATA-ID","LANGUAGE","VALUE","URI"]);const d=h["DATA-ID"];d&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[d]=h);break}case"SESSION-KEY":{const h=Rr(u,t,r);h.encrypted&&h.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(h)):S.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const h=new ae(u);Te(r,h,["NAME","VALUE","QUERYPARAM"]),xr(r,h,t)}break}case"CONTENT-STEERING":{const h=new ae(u);Te(r,h,["SERVER-URI","PATHWAY-ID"]),r.contentSteering={uri:Fe.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{r.startTimeOffset=Cr(u);break}}}const l=n.length>0&&n.length<r.levels.length;return r.levels=l?n:r.levels,r.levels.length===0&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,i){let r;const n={},a=i.levels,o={AUDIO:a.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:a.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Ar.lastIndex=0;(r=Ar.exec(e))!==null;){const c=new ae(r[1]),u=c.TYPE;if(u){const h=o[u],d=n[u]||[];n[u]=d,Te(i,c,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const f=c.LANGUAGE,m=c["ASSOC-LANGUAGE"],g=c.CHANNELS,y=c.CHARACTERISTICS,v=c["INSTREAM-ID"],T={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",name:c.NAME||f||"",type:u,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:f,url:c.URI?Fe.resolve(c.URI,t):""};if(m&&(T.assocLang=m),g&&(T.channels=g),y&&(T.characteristics=y),v&&(T.instreamId=v),h!=null&&h.length){const x=Fe.findGroup(h,T.groupId)||h[0];Dr(T,x,"audioCodec"),Dr(T,x,"textCodec")}d.push(T)}}return n}static parseLevelPlaylist(e,t,i,r,n,a){const o=new Ro(t),l=o.fragments;let c=null,u=0,h=0,d=0,f=0,m=null,g=new vi(r,t),y,v,T,x=-1,L=!1,E=null;for(Lr.lastIndex=0,o.m3u8=e,o.hasVariableRefs=vr(e);(y=Lr.exec(e))!==null;){L&&(L=!1,g=new vi(r,t),g.start=d,g.sn=u,g.cc=f,g.level=i,c&&(g.initSegment=c,g.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null,E&&(g.setByteRange(E),E=null)));const C=y[1];if(C){g.duration=parseFloat(C);const b=(" "+y[2]).slice(1);g.title=b||null,g.tagList.push(b?["INF",C,b]:["INF",C])}else if(y[3]){if(W(g.duration)){g.start=d,T&&wr(g,T,o),g.sn=u,g.level=i,g.cc=f,l.push(g);const b=(" "+y[3]).slice(1);g.relurl=Ci(o,b),_r(g,m),m=g,d+=g.duration,u++,h=0,L=!0}}else if(y[4]){const b=(" "+y[4]).slice(1);m?g.setByteRange(b,m):g.setByteRange(b)}else if(y[5])g.rawProgramDateTime=(" "+y[5]).slice(1),g.tagList.push(["PROGRAM-DATE-TIME",g.rawProgramDateTime]),x===-1&&(x=l.length);else{if(y=y[0].match(ul),!y){S.warn("No matches on slow regex match for level playlist!");continue}for(v=1;v<y.length&&typeof y[v]=="undefined";v++);const b=(" "+y[v]).slice(1),D=(" "+y[v+1]).slice(1),P=y[v+2]?(" "+y[v+2]).slice(1):"";switch(b){case"PLAYLIST-TYPE":o.type=D.toUpperCase();break;case"MEDIA-SEQUENCE":u=o.startSN=parseInt(D);break;case"SKIP":{const w=new ae(D);Te(o,w,["RECENTLY-REMOVED-DATERANGES"]);const U=w.decimalInteger("SKIPPED-SEGMENTS");if(W(U)){o.skippedSegments=U;for(let G=U;G--;)l.unshift(null);u+=U}const O=w.enumeratedString("RECENTLY-REMOVED-DATERANGES");O&&(o.recentlyRemovedDateranges=O.split(" "));break}case"TARGETDURATION":o.targetduration=Math.max(parseInt(D),1);break;case"VERSION":o.version=parseInt(D);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":o.live=!1;break;case"#":(D||P)&&g.tagList.push(P?[D,P]:[D]);break;case"DISCONTINUITY":f++,g.tagList.push(["DIS"]);break;case"GAP":g.gap=!0,g.tagList.push([b]);break;case"BITRATE":g.tagList.push([b,D]);break;case"DATERANGE":{const w=new ae(D);Te(o,w,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),Te(o,w,w.clientAttrs);const U=new Js(w,o.dateRanges[w.ID]);U.isValid||o.skippedSegments?o.dateRanges[U.id]=U:S.warn(`Ignoring invalid DATERANGE tag: "${D}"`),g.tagList.push(["EXT-X-DATERANGE",D]);break}case"DEFINE":{{const w=new ae(D);Te(o,w,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in w?rl(o,w,a):xr(o,w,t)}break}case"DISCONTINUITY-SEQUENCE":f=parseInt(D);break;case"KEY":{const w=Rr(D,t,o);if(w.isSupported()){if(w.method==="NONE"){T=void 0;break}T||(T={}),T[w.keyFormat]&&(T=oe({},T)),T[w.keyFormat]=w}else S.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${D}"`);break}case"START":o.startTimeOffset=Cr(D);break;case"MAP":{const w=new ae(D);if(Te(o,w,["BYTERANGE","URI"]),g.duration){const U=new vi(r,t);Ir(U,w,i,T),c=U,g.initSegment=c,c.rawProgramDateTime&&!g.rawProgramDateTime&&(g.rawProgramDateTime=c.rawProgramDateTime)}else{const U=g.byteRangeEndOffset;if(U){const O=g.byteRangeStartOffset;E=`${U-O}@${O}`}else E=null;Ir(g,w,i,T),c=g,L=!0}break}case"SERVER-CONTROL":{const w=new ae(D);o.canBlockReload=w.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=w.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&w.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=w.optionalFloat("PART-HOLD-BACK",0),o.holdBack=w.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const w=new ae(D);o.partTarget=w.decimalFloatingPoint("PART-TARGET");break}case"PART":{let w=o.partList;w||(w=o.partList=[]);const U=h>0?w[w.length-1]:void 0,O=h++,G=new ae(D);Te(o,G,["BYTERANGE","URI"]);const F=new Ao(G,g,t,O,U);w.push(F),g.duration+=F.duration;break}case"PRELOAD-HINT":{const w=new ae(D);Te(o,w,["URI"]),o.preloadHint=w;break}case"RENDITION-REPORT":{const w=new ae(D);Te(o,w,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(w);break}default:S.warn(`line parsed but not handled: ${y}`);break}}}m&&!m.relurl?(l.pop(),d-=m.duration,o.partList&&(o.fragmentHint=m)):o.partList&&(_r(g,m),g.cc=f,o.fragmentHint=g,T&&wr(g,T,o));const k=l.length,R=l[0],B=l[k-1];if(d+=o.skippedSegments*o.targetduration,d>0&&k&&B){o.averagetargetduration=d/k;const C=B.sn;o.endSN=C!=="initSegment"?C:0,o.live||(B.endList=!0),R&&(o.startCC=R.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(d+=o.fragmentHint.duration),o.totalduration=d,o.endCC=f,x>0&&dl(l,x),o}}function Rr(s,e,t){var i,r;const n=new ae(s);Te(t,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=(i=n.METHOD)!=null?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),c=n.KEYFORMATVERSIONS,u=(r=n.KEYFORMAT)!=null?r:"identity";o&&n.IV&&!l&&S.error(`Invalid IV: ${n.IV}`);const h=o?Fe.resolve(o,e):"",d=(c||"1").split("/").map(Number).filter(Number.isFinite);return new vt(a,h,u,d,l)}function Cr(s){const t=new ae(s).decimalFloatingPoint("TIME-OFFSET");return W(t)?t:null}function hl(s,e){let t=(s||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const r=t.filter(n=>nl(n,i));r.length&&(e[`${i}Codec`]=r.join(","),t=t.filter(n=>r.indexOf(n)===-1))}),e.unknownCodecs=t}function Dr(s,e,t){const i=e[t];i&&(s[t]=i)}function dl(s,e){let t=s[e];for(let i=e;i--;){const r=s[i];if(!r)return;r.programDateTime=t.programDateTime-r.duration*1e3,t=r}}function _r(s,e){s.rawProgramDateTime?s.programDateTime=Date.parse(s.rawProgramDateTime):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime),W(s.programDateTime)||(s.programDateTime=null,s.rawProgramDateTime=null)}function Ir(s,e,t,i){s.relurl=e.URI,e.BYTERANGE&&s.setByteRange(e.BYTERANGE),s.level=t,s.sn="initSegment",i&&(s.levelkeys=i),s.initSegment=null}function wr(s,e,t){s.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(r=>e[r].isCommonEncryption)&&i.push(s)}var ee={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},j={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function kr(s){const{type:e}=s;switch(e){case ee.AUDIO_TRACK:return j.AUDIO;case ee.SUBTITLE_TRACK:return j.SUBTITLE;default:return j.MAIN}}function Ii(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class fl{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,r=t.loader,n=i||r,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:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ee.MANIFEST,url:i,deliveryDirectives:null})}onLevelLoading(e,t){const{id:i,level:r,pathwayId:n,url:a,deliveryDirectives:o}=t;this.load({id:i,level:r,pathwayId:n,responseType:"text",type:ee.LEVEL,url:a,deliveryDirectives:o})}onAudioTrackLoading(e,t){const{id:i,groupId:r,url:n,deliveryDirectives:a}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:ee.AUDIO_TRACK,url:n,deliveryDirectives:a})}onSubtitleTrackLoading(e,t){const{id:i,groupId:r,url:n,deliveryDirectives:a}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:ee.SUBTITLE_TRACK,url:n,deliveryDirectives:a})}load(e){var t;const i=this.hls.config;let r=this.getInternalLoader(e);if(r){const c=r.context;if(c&&c.url===e.url&&c.level===e.level){S.trace("[playlist-loader]: playlist request ongoing");return}S.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}let n;if(e.type===ee.MANIFEST?n=i.manifestLoadPolicy.default:n=oe({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),W((t=e.deliveryDirectives)==null?void 0:t.part)){let c;if(e.type===ee.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===ee.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===ee.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const u=c.partTarget,h=c.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},l={onSuccess:(c,u,h,d)=>{const f=this.getInternalLoader(h);this.resetInternalLoader(h.type);const m=c.data;if(m.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(c,h,new Error("no EXTM3U delimiter"),d||null,u);return}u.parsing.start=performance.now(),Fe.isMediaPlaylist(m)?this.handleTrackOrLevelPlaylist(c,u,h,d||null,f):this.handleMasterPlaylist(c,u,h,d)},onError:(c,u,h,d)=>{this.handleNetworkError(u,h,!1,c,d)},onTimeout:(c,u,h)=>{this.handleNetworkError(u,h,!0,void 0,c)}};r.load(e,o,l)}handleMasterPlaylist(e,t,i,r){const n=this.hls,a=e.data,o=Ii(e,i),l=Fe.parseMasterPlaylist(a,o);if(l.playlistParsingError){this.handleManifestParsingError(e,i,l.playlistParsingError,r,t);return}const{contentSteering:c,levels:u,sessionData:h,sessionKeys:d,startTimeOffset:f,variableList:m}=l;this.variableList=m;const{AUDIO:g=[],SUBTITLES:y,"CLOSED-CAPTIONS":v}=Fe.parseMasterPlaylistMedia(a,o,l);g.length&&!g.some(x=>!x.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(S.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ae({}),bitrate:0,url:""})),n.trigger(p.MANIFEST_LOADED,{levels:u,audioTracks:g,subtitles:y,captions:v,contentSteering:c,url:o,stats:t,networkDetails:r,sessionData:h,sessionKeys:d,startTimeOffset:f,variableList:m})}handleTrackOrLevelPlaylist(e,t,i,r,n){const a=this.hls,{id:o,level:l,type:c}=i,u=Ii(e,i),h=0,d=W(l)?l:W(o)?o:0,f=kr(i),m=Fe.parseLevelPlaylist(e.data,u,d,f,h,this.variableList);if(c===ee.MANIFEST){const g={attrs:new ae({}),bitrate:0,details:m,name:"",url:u};a.trigger(p.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:u,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=m,this.handlePlaylistLoaded(m,e,t,i,r,n)}handleManifestParsingError(e,t,i,r,n){this.hls.trigger(p.ERROR,{type:q.NETWORK_ERROR,details:_.MANIFEST_PARSING_ERROR,fatal:t.type===ee.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:n})}handleNetworkError(e,t,i=!1,r,n){let a=`A network ${i?"timeout":"error"+(r?" (status "+r.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);S.warn(`[playlist-loader]: ${a}`);let l=_.UNKNOWN,c=!1;const u=this.getInternalLoader(e);switch(e.type){case ee.MANIFEST:l=i?_.MANIFEST_LOAD_TIMEOUT:_.MANIFEST_LOAD_ERROR,c=!0;break;case ee.LEVEL:l=i?_.LEVEL_LOAD_TIMEOUT:_.LEVEL_LOAD_ERROR,c=!1;break;case ee.AUDIO_TRACK:l=i?_.AUDIO_TRACK_LOAD_TIMEOUT:_.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case ee.SUBTITLE_TRACK:l=i?_.SUBTITLE_TRACK_LOAD_TIMEOUT:_.SUBTITLE_LOAD_ERROR,c=!1;break}u&&this.resetInternalLoader(e.type);const h={type:q.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:n};if(r){const d=(t==null?void 0:t.url)||e.url;h.response=he({url:d,data:void 0},r)}this.hls.trigger(p.ERROR,h)}handlePlaylistLoaded(e,t,i,r,n,a){const o=this.hls,{type:l,level:c,id:u,groupId:h,deliveryDirectives:d}=r,f=Ii(t,r),m=kr(r),g=typeof r.level=="number"&&m===j.MAIN?c:void 0;if(!e.fragments.length){const v=new Error("No Segments found in Playlist");o.trigger(p.ERROR,{type:q.NETWORK_ERROR,details:_.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:r,level:g,parent:m,networkDetails:n,stats:i});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const y=e.playlistParsingError;if(y){o.trigger(p.ERROR,{type:q.NETWORK_ERROR,details:_.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:r,level:g,parent:m,networkDetails:n,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case ee.MANIFEST:case ee.LEVEL:o.trigger(p.LEVEL_LOADED,{details:e,level:g||0,id:u||0,stats:i,networkDetails:n,deliveryDirectives:d});break;case ee.AUDIO_TRACK:o.trigger(p.AUDIO_TRACK_LOADED,{details:e,id:u||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:d});break;case ee.SUBTITLE_TRACK:o.trigger(p.SUBTITLE_TRACK_LOADED,{details:e,id:u||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:d});break}}}function Pr(s,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=s,e.dispatchEvent(t)}function Or(s,e){const t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(e.id))try{if(s.addCue(e),!s.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){S.debug(`[texttrack-utils]: ${i}`);try{const r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,s.addCue(r)}catch(r){S.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}t==="disabled"&&(s.mode=t)}function it(s){const e=s.mode;if(e==="disabled"&&(s.mode="hidden"),s.cues)for(let t=s.cues.length;t--;)s.removeCue(s.cues[t]);e==="disabled"&&(s.mode=e)}function wi(s,e,t,i){const r=s.mode;if(r==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const n=gl(s.cues,e,t);for(let a=0;a<n.length;a++)(!i||i(n[a]))&&s.removeCue(n[a])}r==="disabled"&&(s.mode=r)}function ml(s,e){if(e<s[0].startTime)return 0;const t=s.length-1;if(e>s[t].endTime)return-1;let i=0,r=t;for(;i<=r;){const n=Math.floor((r+i)/2);if(e<s[n].startTime)r=n-1;else if(e>s[n].startTime&&i<t)i=n+1;else return n}return s[i].startTime-e<e-s[r].startTime?i:r}function gl(s,e,t){const i=[],r=ml(s,e);if(r>-1)for(let n=r,a=s.length;n<a;n++){const o=s[n];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}function Mt(s){const e=[];for(let t=0;t<s.length;t++){const i=s[t];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&e.push(s[t])}return e}var Ce={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const pl=.25;function ki(){if(typeof self!="undefined")return self.VTTCue||self.TextTrackCue}function Fr(s,e,t,i,r){let n=new s(e,t,"");try{n.value=i,r&&(n.type=r)}catch{n=new s(e,t,JSON.stringify(r?he({type:r},i):i))}return n}const Nt=(()=>{const s=ki();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Pi(s,e){return s.getTime()/1e3-e}function yl(s){return Uint8Array.from(s.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class vl{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(it(this.id3Track),this.id3Track=null,this.media=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 i=e[t];if(i.kind==="metadata"&&i.label==="id3")return Pr(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:r}}}=this;if(!i&&!r)return;const{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=ki();if(a)for(let o=0;o<n.length;o++){const l=n[o].type;if(l===Ce.emsg&&!i||!r)continue;const c=or(n[o].data);if(c){const u=n[o].pts;let h=u+n[o].duration;h>Nt&&(h=Nt),h-u<=0&&(h=u+pl);for(let f=0;f<c.length;f++){const m=c[f];if(!ar(m)){this.updateId3CueEnds(u,l);const g=Fr(a,u,h,m,l);g&&this.id3Track.addCue(g)}}}}}updateId3CueEnds(e,t){var i;const r=(i=this.id3Track)==null?void 0:i.cues;if(r)for(let n=r.length;n--;){const a=r[n];a.type===t&&a.startTime<e&&a.endTime===Nt&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:r}){const{id3Track:n,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let c;r==="audio"?c=u=>u.type===Ce.audioId3&&l:r==="video"?c=u=>u.type===Ce.emsg&&o:c=u=>u.type===Ce.audioId3&&l||u.type===Ce.emsg&&o,wi(n,t,i,c)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:r}=this,{dateRanges:n}=t,a=Object.keys(n);if(r){const u=Object.keys(i).filter(h=>!a.includes(h));for(let h=u.length;h--;){const d=u[h];Object.keys(i[d].cues).forEach(f=>{r.removeCue(i[d].cues[f])}),delete i[d]}}const o=t.fragments[t.fragments.length-1];if(a.length===0||!W(o==null?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,c=ki();for(let u=0;u<a.length;u++){const h=a[u],d=n[h],f=Pi(d.startDate,l),m=i[h],g=(m==null?void 0:m.cues)||{};let y=(m==null?void 0:m.durationKnown)||!1,v=Nt;const T=d.endDate;if(T)v=Pi(T,l),y=!0;else if(d.endOnNext&&!y){const L=a.reduce((E,k)=>{if(k!==d.id){const R=n[k];if(R.class===d.class&&R.startDate>d.startDate&&(!E||d.startDate<E.startDate))return R}return E},null);L&&(v=Pi(L.startDate,l),y=!0)}const x=Object.keys(d.attr);for(let L=0;L<x.length;L++){const E=x[L];if(!So(E))continue;const k=g[E];if(k)y&&!m.durationKnown&&(k.endTime=v);else if(c){let R=d.attr[E];bo(E)&&(R=yl(R));const B=Fr(c,f,v,{key:E,data:R},Ce.dateRange);B&&(B.id=h,this.id3Track.addCue(B),g[E]=B)}}i[h]={cues:g,dateRange:d,durationKnown:y}}}}class xl{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(e===null)return null;const{holdBack:t,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let c=o&&i||t;(l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=n!==void 0?n:a*r);const u=r,h=1;return c+Math.min(this.stallCount*h,u)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,i=this.levelDetails;if(e===null||t===null||i===null)return null;const r=i.edge,n=e-t-this.edgeStalled,a=r-i.totalduration,o=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){const{levelDetails:e}=this;return e===null?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;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,levelDetails:t}=this;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(p.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(p.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var i;t.details===_.BUFFER_STALLED_ERROR&&(this.stallCount++,(i=this.levelDetails)!=null&&i.live&&S.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:n}=this.config;if(!r||n===1||!t.live)return;const a=this.targetLatency;if(a===null)return;const o=i-a,l=Math.min(this.maxLatency,a+t.targetduration);if(o<l&&o>.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,n)),h=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(u,Math.max(1,h))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const Oi=["NONE","TYPE-0","TYPE-1",null];function Tl(s){return Oi.indexOf(s)>-1}const Bt=["SDR","PQ","HLG"];function El(s){return!!s&&Bt.indexOf(s)>-1}var Tt={No:"",Yes:"YES",v2:"v2"};function Sl(s,e){const{canSkipUntil:t,canSkipDateRanges:i,endSN:r}=s,n=e!==void 0?e-r:0;return t&&n<t?i?Tt.v2:Tt.Yes:Tt.No}class Mr{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}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 st{constructor(e){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.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(t=>!!t).map(t=>t.substring(0,4)).join(","),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 Nr(this._audioGroups,e)}hasSubtitleGroup(e){return Nr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.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 Nr(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function Fi(s,e){const t=e.startPTS;if(W(t)){let i=0,r;e.sn>s.sn?(i=t-s.start,r=s):(i=s.start-t,r=e),r.duration!==i&&(r.duration=i)}else e.sn>s.sn?s.cc===e.cc&&s.minEndPTS?e.start=s.start+(s.minEndPTS-s.start):e.start=s.start+s.duration:e.start=Math.max(s.start-e.duration,0)}function Br(s,e,t,i,r,n){i-t<=0&&(S.warn("Fragment should have a positive duration",e),i=t+e.duration,n=r+e.duration);let o=t,l=i;const c=e.startPTS,u=e.endPTS;if(W(c)){const y=Math.abs(c-t);W(e.deltaPTS)?e.deltaPTS=Math.max(y,e.deltaPTS):e.deltaPTS=y,o=Math.max(t,c),t=Math.min(t,c),r=Math.min(r,e.startDTS),l=Math.min(i,u),i=Math.max(i,u),n=Math.max(n,e.endDTS)}const h=t-e.start;e.start!==0&&(e.start=t),e.duration=i-e.start,e.startPTS=t,e.maxStartPTS=o,e.startDTS=r,e.endPTS=i,e.minEndPTS=l,e.endDTS=n;const d=e.sn;if(!s||d<s.startSN||d>s.endSN)return 0;let f;const m=d-s.startSN,g=s.fragments;for(g[m]=e,f=m;f>0;f--)Fi(g[f],g[f-1]);for(f=m;f<g.length-1;f++)Fi(g[f],g[f+1]);return s.fragmentHint&&Fi(g[g.length-1],s.fragmentHint),s.PTSKnown=s.alignedSliding=!0,h}function bl(s,e){let t=null;const i=s.fragments;for(let l=i.length-1;l>=0;l--){const c=i[l].initSegment;if(c){t=c;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let r=0,n;if(Rl(s,e,(l,c)=>{l.relurl&&(r=l.cc-c.cc),W(l.startPTS)&&W(l.endPTS)&&(c.start=c.startPTS=l.startPTS,c.startDTS=l.startDTS,c.maxStartPTS=l.maxStartPTS,c.endPTS=l.endPTS,c.endDTS=l.endDTS,c.minEndPTS=l.minEndPTS,c.duration=l.endPTS-l.startPTS,c.duration&&(n=c),e.PTSKnown=e.alignedSliding=!0),c.elementaryStreams=l.elementaryStreams,c.loader=l.loader,c.stats=l.stats,l.initSegment&&(c.initSegment=l.initSegment,t=l.initSegment)}),t&&(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(c=>{var u;c&&(!c.initSegment||c.initSegment.relurl===((u=t)==null?void 0:u.relurl))&&(c.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some(l=>!l),e.deltaUpdateFailed){S.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=Al(s.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(r){S.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l<a.length;l++)a[l].cc+=r}e.skippedSegments&&(e.startCC=e.fragments[0].cc),Ll(s.partList,e.partList,(l,c)=>{c.elementaryStreams=l.elementaryStreams,c.stats=l.stats}),n?Br(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):$r(s,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const l=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=l),e.driftEndTime=o,e.driftEnd=l}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime}function Al(s,e,t){const i=oe({},s);return t&&t.forEach(r=>{delete i[r]}),Object.keys(e).forEach(r=>{const n=new Js(e[r].attr,i[r]);n.isValid?i[r]=n:S.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[r].attr)}"`)}),i}function Ll(s,e,t){if(s&&e){let i=0;for(let r=0,n=s.length;r<=n;r++){const a=s[r],o=e[r+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--}}}function Rl(s,e,t){const i=e.skippedSegments,r=Math.max(s.startSN,e.startSN)-e.startSN,n=(s.fragmentHint?1:0)+(i?e.endSN:Math.min(s.endSN,e.endSN))-e.startSN,a=e.startSN-s.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let c=r;c<=n;c++){const u=l[a+c];let h=o[c];i&&!h&&c<i&&(h=e.fragments[c]=u),u&&h&&t(u,h)}}function $r(s,e){const t=e.startSN+e.skippedSegments-s.startSN,i=s.fragments;t<0||t>=i.length||Mi(e,i[t].start)}function Mi(s,e){if(e){const t=s.fragments;for(let i=s.skippedSegments;i<t.length;i++)t[i].start+=e;s.fragmentHint&&(s.fragmentHint.start+=e)}}function Cl(s,e=1/0){let t=1e3*s.targetduration;if(s.updated){const i=s.fragments,r=4;if(i.length&&t*r>e){const n=i[i.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function Dl(s,e,t){if(!(s!=null&&s.details))return null;const i=s.details;let r=i.fragments[e-i.startSN];return r||(r=i.fragmentHint,r&&r.sn===e)?r:e<i.startSN&&t&&t.sn===e?t:null}function Ur(s,e,t){var i;return s!=null&&s.details?Gr((i=s.details)==null?void 0:i.partList,e,t):null}function Gr(s,e,t){if(s)for(let i=s.length;i--;){const r=s[i];if(r.index===t&&r.fragment.sn===e)return r}return null}function Hr(s){s.forEach((e,t)=>{const{details:i}=e;i!=null&&i.fragments&&i.fragments.forEach(r=>{r.level=t})})}function $t(s){switch(s.details){case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_TIMEOUT:case _.LEVEL_LOAD_TIMEOUT:case _.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Vr(s,e){const t=$t(e);return s.default[`${t?"timeout":"error"}Retry`]}function Ni(s,e){const t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function Kr(s){return he(he({},s),{errorRetry:null,timeoutRetry:null})}function Ut(s,e,t,i){if(!s)return!1;const r=i==null?void 0:i.code,n=e<s.maxNumRetry&&(_l(r)||!!t);return s.shouldRetry?s.shouldRetry(s,e,t,i,n):n}function _l(s){return s===0&&navigator.onLine===!1||!!s&&(s<400||s>499)}const Wr={search:function(s,e){let t=0,i=s.length-1,r=null,n=null;for(;t<=i;){r=(t+i)/2|0,n=s[r];const a=e(n);if(a>0)t=r+1;else if(a<0)i=r-1;else return n}return null}};function Il(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!W(e))return null;const i=s[0].programDateTime;if(e<(i||0))return null;const r=s[s.length-1].endProgramDateTime;if(e>=(r||0))return null;t=t||0;for(let n=0;n<s.length;++n){const a=s[n];if(wl(e,t,a))return a}return null}function Gt(s,e,t=0,i=0){let r=null;if(s){r=e[s.sn-e[0].sn+1]||null;const a=s.endDTS-t;a>0&&a<15e-7&&(t+=15e-7)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&(!s||s.level===r.level)&&Bi(t,i,r)===0)return r;const n=Wr.search(e,Bi.bind(null,t,i));return n&&(n!==s||!r)?n:r}function Bi(s=0,e=0,t){if(t.start<=s&&t.start+t.duration>s)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=s?1:t.start-i>s&&t.start?-1:0}function wl(s,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function kl(s,e){return Wr.search(s,t=>t.cc<e?1:t.cc>e?-1:0)}var ge={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},De={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class Pl{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=S.log.bind(S,"[info]:"),this.warn=S.warn.bind(S,"[warning]:"),this.error=S.error.bind(S,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.ERROR,this.onError,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.ERROR,this.onError,this),e.off(p.ERROR,this.onErrorOut,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===j.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,r;if(t.fatal)return;const n=this.hls,a=t.context;switch(t.details){case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case _.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction={action:ge.DoNothing,flags:De.None};return}case _.FRAG_GAP:case _.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ge.SendAlternateToPenaltyBox;return}case _.LEVEL_EMPTY_ERROR:case _.LEVEL_PARSING_ERROR:{var o,l;const c=t.parent===j.MAIN?t.level:n.loadLevel;t.details===_.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(l=o.levelDetails)!=null&&l.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:typeof(a==null?void 0:a.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a.level));return;case _.AUDIO_TRACK_LOAD_ERROR:case _.AUDIO_TRACK_LOAD_TIMEOUT:case _.SUBTITLE_LOAD_ERROR:case _.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const c=n.levels[n.loadLevel];if(c&&(a.type===ee.AUDIO_TRACK&&c.hasAudioGroup(a.groupId)||a.type===ee.SUBTITLE_TRACK&&c.hasSubtitleGroup(a.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=ge.SendAlternateToPenaltyBox,t.errorAction.flags=De.MoveAllAlternatesMatchingHost;return}}return;case _.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const c=n.levels[n.loadLevel],u=c==null?void 0:c.attrs["HDCP-LEVEL"];u?t.errorAction={action:ge.SendAlternateToPenaltyBox,flags:De.MoveAllAlternatesMatchingHDCP,hdcpLevel:u}:this.keySystemError(t)}return;case _.BUFFER_ADD_CODEC_ERROR:case _.REMUX_ALLOC_ERROR:case _.BUFFER_APPEND_ERROR:t.errorAction=this.getLevelSwitchAction(t,(r=t.level)!=null?r:n.loadLevel);return;case _.INTERNAL_EXCEPTION:case _.BUFFER_APPENDING_ERROR:case _.BUFFER_FULL_ERROR:case _.LEVEL_SWITCH_ERROR:case _.BUFFER_STALLED_ERROR:case _.BUFFER_SEEK_OVER_HOLE:case _.BUFFER_NUDGE_ON_STALL:t.errorAction={action:ge.DoNothing,flags:De.None};return}t.type===q.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,r=Vr(i.config.playlistLoadPolicy,e),n=this.playlistError++;if(Ut(r,n,$t(e),e.response))return{action:ge.RetryRequest,flags:De.None,retryConfig:r,retryCount:n};const o=this.getLevelSwitchAction(e,t);return r&&(o.retryConfig=r,o.retryCount=n),o}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=Vr(e.details.startsWith("key")?a:n,e),l=t.levels.reduce((u,h)=>u+h.fragmentError,0);if(r&&(e.details!==_.FRAG_GAP&&r.fragmentError++,Ut(o,l,$t(e),e.response)))return{action:ge.RetryRequest,flags:De.None,retryConfig:o,retryCount:l};const c=this.getLevelSwitchAction(e,i);return o&&(c.retryConfig=o,c.retryCount=l),c}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const r=this.hls.levels[t];if(r){var n,a;const c=e.details;r.loadError++,c===_.BUFFER_APPEND_ERROR&&r.fragmentError++;let u=-1;const{levels:h,loadLevel:d,minAutoLevel:f,maxAutoLevel:m}=i;i.autoLevelEnabled||(i.loadLevel=-1);const g=(n=e.frag)==null?void 0:n.type,v=(g===j.AUDIO&&c===_.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(c===_.BUFFER_ADD_CODEC_ERROR||c===_.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:k})=>r.audioCodec!==k),x=e.sourceBufferName==="video"&&(c===_.BUFFER_ADD_CODEC_ERROR||c===_.BUFFER_APPEND_ERROR)&&h.some(({codecSet:k,audioCodec:R})=>r.codecSet!==k&&r.audioCodec===R),{type:L,groupId:E}=(a=e.context)!=null?a:{};for(let k=h.length;k--;){const R=(k+d)%h.length;if(R!==d&&R>=f&&R<=m&&h[R].loadError===0){var o,l;const B=h[R];if(c===_.FRAG_GAP&&e.frag){const C=h[R].details;if(C){const b=Gt(e.frag,C.fragments,e.frag.start);if(b!=null&&b.gap)continue}}else{if(L===ee.AUDIO_TRACK&&B.hasAudioGroup(E)||L===ee.SUBTITLE_TRACK&&B.hasSubtitleGroup(E))continue;if(g===j.AUDIO&&(o=r.audioGroups)!=null&&o.some(C=>B.hasAudioGroup(C))||g===j.SUBTITLE&&(l=r.subtitleGroups)!=null&&l.some(C=>B.hasSubtitleGroup(C))||v&&r.audioCodec===B.audioCodec||!v&&r.audioCodec!==B.audioCodec||x&&r.codecSet===B.codecSet)continue}u=R;break}}if(u>-1&&i.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:ge.SendAlternateToPenaltyBox,flags:De.None,nextAutoLevel:u}}return{action:ge.SendAlternateToPenaltyBox,flags:De.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case ge.DoNothing:break;case ge.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==_.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,i=e.errorAction;if(!i)return;const{flags:r,hdcpLevel:n,nextAutoLevel:a}=i;switch(r){case De.None:this.switchLevel(e,a);break;case De.MoveAllAlternatesMatchingHDCP:n&&(t.maxHdcpLevel=Oi[Oi.indexOf(n)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(e,a)}switchLevel(e,t){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)}}class $i{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=S.log.bind(S,`${t}:`),this.warn=S.warn.bind(S,`${t}:`),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.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t){const i=t==null?void 0:t.renditionReports;if(i){let r=-1;for(let n=0;n<i.length;n++){const a=i[n];let o;try{o=new self.URL(a.URI,t.url).href}catch(l){S.warn(`Could not construct new URL for Rendition Report: ${l}`),o=a.URI||""}if(o===e){r=n;break}else o===e.substring(0,o.length)&&(r=n)}if(r!==-1){const n=i[r],a=parseInt(n["LAST-MSN"])||(t==null?void 0:t.lastPartSn);let o=parseInt(n["LAST-PART"])||(t==null?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const l=Math.min(t.age-t.partTarget,t.targetduration);o>=0&&l>t.partTarget&&(o+=1)}return new Mr(a,o>=0?o:void 0,Tt.No)}}}loadPlaylist(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,i){const{details:r,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;if(r.advancedDateTime=Date.now()-o,r.live||i!=null&&i.live){if(r.reloaded(i),i&&this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),i&&r.fragments.length>0&&bl(i,r),!this.canLoad||!r.live)return;let l,c,u;if(r.canBlockReload&&r.endSN&&r.advanced){const y=this.hls.config.lowLatencyMode,v=r.lastPartSn,T=r.endSN,x=r.lastPartIndex,L=x!==-1,E=v===T,k=y?0:x;L?(c=E?T+1:v,u=E?k:x+1):c=T+1;const R=r.age,B=R+r.ageHeader;let C=Math.min(B-r.partTarget,r.targetduration*1.5);if(C>0){if(i&&C>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${C} with playlist age: ${r.age}`),C=0;else{const b=Math.floor(C/r.targetduration);if(c+=b,u!==void 0){const D=Math.round(C%r.targetduration/r.partTarget);u+=D}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${R.toFixed(2)}s goal: ${C} skip sn ${b} to part ${u}`)}r.tuneInGoal=C}if(l=this.getDeliveryDirectives(r,t.deliveryDirectives,c,u),y||!E){this.loadPlaylist(l);return}}else(r.canBlockReload||r.canSkipUntil)&&(l=this.getDeliveryDirectives(r,t.deliveryDirectives,c,u));const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,f=(r.edge-d)*1e3,m=Cl(r,f);r.updated&&a>this.requestScheduled+m&&(this.requestScheduled=n.loading.start),c!==void 0&&r.canBlockReload?this.requestScheduled=n.loading.first+m-(r.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+m<a?this.requestScheduled=a:this.requestScheduled-a<=0&&(this.requestScheduled+=m);let g=this.requestScheduled-a;g=Math.max(0,g),this.log(`reload live playlist ${e} in ${Math.round(g)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(l),g)}else this.clearTimer()}getDeliveryDirectives(e,t,i,r){let n=Sl(e,i);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,n=Tt.No),new Mr(i,r,n)}checkRetry(e){const t=e.details,i=$t(e),r=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=r||{},l=!!r&&!!o&&(n===ge.RetryRequest||!r.resolved&&n===ge.SendAlternateToPenaltyBox);if(l){var c;if(this.requestScheduled=-1,a>=o.maxNumRetry)return!1;if(i&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const u=Ni(o,a);this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${u}ms`)}e.levelRetry=!0,r.resolved=!0}return l}}class rt{constructor(e,t=0,i=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_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*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 Ol{constructor(e,t,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new rt(e),this.fast_=new rt(t),this.defaultTTFB_=r,this.ttfb_=new rt(e)}update(e,t){const{slow_:i,fast_:r,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new rt(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new rt(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new rt(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,r=e/1e3,n=i/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,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_}destroy(){}}const zr={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Yr={};function Fl(s,e,t,i,r,n){const a=s.audioCodec?s.audioGroups:null,o=n==null?void 0:n.audioCodec,l=n==null?void 0:n.channels,c=l?parseInt(l):o?1/0:2;let u=null;if(a!=null&&a.length)try{a.length===1&&a[0]?u=e.groups[a[0]].channels:u=a.reduce((h,d)=>{if(d){const f=e.groups[d];if(!f)throw new Error(`Audio track group ${d} not found`);Object.keys(f.channels).forEach(m=>{h[m]=(h[m]||0)+f.channels[m]})}return h},{2:0})}catch{return!0}return s.videoCodec!==void 0&&(s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(i,30)||s.videoRange!=="SDR"&&s.videoRange!==t||s.bitrate>Math.max(r,8e6))||!!u&&W(c)&&Object.keys(u).some(h=>parseInt(h)>c)}function Ml(s,e,t){const i=s.videoCodec,r=s.audioCodec;if(!i||!r||!t)return Promise.resolve(zr);const n={width:s.width,height:s.height,bitrate:Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)),framerate:s.frameRate||30},a=s.videoRange;a!=="SDR"&&(n.transferFunction=a.toLowerCase());const o=i.split(",").map(l=>({type:"media-source",video:he(he({},n),{},{contentType:xt(l,"video")})}));return r&&s.audioGroups&&s.audioGroups.forEach(l=>{var c;l&&((c=e.groups[l])==null||c.tracks.forEach(u=>{if(u.groupId===l){const h=u.channels||"",d=parseFloat(h);W(d)&&d>2&&o.push.apply(o,r.split(",").map(f=>({type:"media-source",audio:{contentType:xt(f,"audio"),channels:""+d}})))}}))}),Promise.all(o.map(l=>{const c=Nl(l);return Yr[c]||(Yr[c]=t.decodingInfo(l))})).then(l=>({supported:!l.some(c=>!c.supported),configurations:o,decodingInfoResults:l})).catch(l=>({supported:!1,configurations:o,decodingInfoResults:[],error:l}))}function Nl(s){const{audio:e,video:t}=s,i=t||e;if(i){const r=i.contentType.split('"')[1];if(t)return`r${t.height}x${t.width}f${Math.ceil(t.framerate)}${t.transferFunction||"sd"}_${r}_${Math.ceil(t.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${r}`}return""}function Bl(){if(typeof matchMedia=="function"){const s=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(s.media!==e.media)return s.matches===!0}return!1}function $l(s,e){let t=!1,i=[];return s&&(t=s!=="SDR",i=[s]),e&&(i=e.allowedVideoRanges||Bt.slice(0),t=e.preferHDR!==void 0?e.preferHDR:Bl(),t?i=i.filter(r=>r!=="SDR"):i=["SDR"]),{preferHDR:t,allowedVideoRanges:i}}function Ul(s,e,t,i,r){const n=Object.keys(s),a=i==null?void 0:i.channels,o=i==null?void 0:i.audioCodec,l=a&&parseInt(a)===2;let c=!0,u=!1,h=1/0,d=1/0,f=1/0,m=0,g=[];const{preferHDR:y,allowedVideoRanges:v}=$l(e,r);for(let E=n.length;E--;){const k=s[n[E]];c=k.channels[2]>0,h=Math.min(h,k.minHeight),d=Math.min(d,k.minFramerate),f=Math.min(f,k.minBitrate);const R=v.filter(B=>k.videoRanges[B]>0);R.length>0&&(u=!0,g=R)}h=W(h)?h:0,d=W(d)?d:0;const T=Math.max(1080,h),x=Math.max(30,d);return f=W(f)?f:t,t=Math.max(f,t),u||(e=void 0,g=[]),{codecSet:n.reduce((E,k)=>{const R=s[k];if(k===E)return E;if(R.minBitrate>t)return Ge(k,`min bitrate of ${R.minBitrate} > current estimate of ${t}`),E;if(!R.hasDefaultAudio)return Ge(k,"no renditions with default or auto-select sound found"),E;if(o&&k.indexOf(o.substring(0,4))%5!==0)return Ge(k,`audio codec preference "${o}" not found`),E;if(a&&!l){if(!R.channels[a])return Ge(k,`no renditions with ${a} channel sound found (channels options: ${Object.keys(R.channels)})`),E}else if((!o||l)&&c&&R.channels[2]===0)return Ge(k,"no renditions with stereo sound found"),E;return R.minHeight>T?(Ge(k,`min resolution of ${R.minHeight} > maximum of ${T}`),E):R.minFramerate>x?(Ge(k,`min framerate of ${R.minFramerate} > maximum of ${x}`),E):g.some(B=>R.videoRanges[B]>0)?R.maxScore<m?(Ge(k,`max score of ${R.maxScore} < selected max of ${m}`),E):E&&(Ot(k)>=Ot(E)||R.fragmentError>s[E].fragmentError)?E:(m=R.maxScore,k):(Ge(k,`no variants with VIDEO-RANGE of ${JSON.stringify(g)} found`),E)},void 0),videoRanges:g,preferHDR:y,minFramerate:d,minBitrate:f}}function Ge(s,e){S.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function Gl(s){return s.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Hl(s,e,t,i){return s.slice(t,i+1).reduce((r,n)=>{if(!n.codecSet)return r;const a=n.audioGroups;let o=r[n.codecSet];o||(r[n.codecSet]=o={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!a,fragmentError:0}),o.minBitrate=Math.min(o.minBitrate,n.bitrate);const l=Math.min(n.height,n.width);return o.minHeight=Math.min(o.minHeight,l),o.minFramerate=Math.min(o.minFramerate,n.frameRate),o.maxScore=Math.max(o.maxScore,n.score),o.fragmentError+=n.fragmentError,o.videoRanges[n.videoRange]=(o.videoRanges[n.videoRange]||0)+1,a&&a.forEach(c=>{if(!c)return;const u=e.groups[c];o.hasDefaultAudio=o.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(h=>{o.channels[h]=(o.channels[h]||0)+u.channels[h]})}),r},{})}function Me(s,e,t){if("attrs"in s){const i=e.indexOf(s);if(i!==-1)return i}for(let i=0;i<e.length;i++){const r=e[i];if(nt(s,r,t))return i}return-1}function nt(s,e,t){const{groupId:i,name:r,lang:n,assocLang:a,characteristics:o,default:l}=s,c=s.forced;return(i===void 0||e.groupId===i)&&(r===void 0||e.name===r)&&(n===void 0||e.lang===n)&&(n===void 0||e.assocLang===a)&&(l===void 0||e.default===l)&&(c===void 0||e.forced===c)&&(o===void 0||Vl(o,e.characteristics))&&(t===void 0||t(s,e))}function Vl(s,e=""){const t=s.split(","),i=e.split(",");return t.length===i.length&&!t.some(r=>i.indexOf(r)===-1)}function at(s,e){const{audioCodec:t,channels:i}=s;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function Kl(s,e,t,i,r){const n=e[i],o=e.reduce((d,f,m)=>{const g=f.uri;return(d[g]||(d[g]=[])).push(m),d},{})[n.uri];o.length>1&&(i=Math.max.apply(Math,o));const l=n.videoRange,c=n.frameRate,u=n.codecSet.substring(0,4),h=jr(e,i,d=>{if(d.videoRange!==l||d.frameRate!==c||d.codecSet.substring(0,4)!==u)return!1;const f=d.audioGroups,m=t.filter(g=>!f||f.indexOf(g.groupId)!==-1);return Me(s,m,r)>-1});return h>-1?h:jr(e,i,d=>{const f=d.audioGroups,m=t.filter(g=>!f||f.indexOf(g.groupId)!==-1);return Me(s,m,r)>-1})}function jr(s,e,t){for(let i=e;i;i--)if(t(s[i]))return i;for(let i=e+1;i<s.length;i++)if(t(s[i]))return i;return-1}class Wl{constructor(e){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.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:t,partCurrent:i,hls:r}=this,{autoLevelEnabled:n,media:a}=r;if(!t||!a)return;const o=performance.now(),l=i?i.stats:t.stats,c=i?i.duration:t.duration,u=o-l.loading.start,h=r.minAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||t.level<=h){this.clearTimer(),this._nextAutoLevel=-1;return}if(!n||a.paused||!a.playbackRate||!a.readyState)return;const d=r.mainForwardBufferInfo;if(d===null)return;const f=this.bwEstimator.getEstimateTTFB(),m=Math.abs(a.playbackRate);if(u<=Math.max(f,1e3*(c/(m*2))))return;const g=d.len/m,y=l.loading.first?l.loading.first-l.loading.start:-1,v=l.loaded&&y>-1,T=this.getBwEstimate(),x=r.levels,L=x[t.level],E=l.total||Math.max(l.loaded,Math.round(c*L.averageBitrate/8));let k=v?u-y:u;k<1&&v&&(k=Math.min(u,l.loaded*8/T));const R=v?l.loaded*1e3/k:0,B=R?(E-l.loaded)/R:E*8/T+f/1e3;if(B<=g)return;const C=R?R*8:T;let b=Number.POSITIVE_INFINITY,D;for(D=t.level-1;D>h;D--){const w=x[D].maxBitrate;if(b=this.getTimeToLoadFrag(f/1e3,C,c*w,!x[D].details),b<g)break}if(b>=B||b>c*10)return;r.nextLoadLevel=r.nextAutoLevel=D,v?this.bwEstimator.sample(u-Math.min(f,y),l.loaded):this.bwEstimator.sampleTTFB(u);const P=x[D].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>P&&this.resetEstimator(P),this.clearTimer(),S.warn(`[abr] Fragment ${t.sn}${i?" part "+i.index:""} of level ${t.level} is loading too slowly;
1
+ (function(Z,Ee){typeof exports=="object"&&typeof module!="undefined"?Ee(exports,require("vue"),require("d3"),require("moment-timezone")):typeof define=="function"&&define.amd?define(["exports","vue","d3","moment-timezone"],Ee):(Z=typeof globalThis!="undefined"?globalThis:Z||self,Ee(Z.EvercamUI={},Z.Vue,Z.d3,Z.moment))})(this,function(Z,Ee,_a,We){var Ea,Sa,ba,Aa,La,Ra,Ca,Da;"use strict";function Ia(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const I=Ia(_a);var z=(s=>(s.dot="dot",s.xs="xs",s.sm="sm",s.md="base",s.base="base",s.lg="lg",s.xl="xl",s["2xl"]="2xl",s["3xl"]="3xl",s["4xl"]="4xl",s["5xl"]="5xl",s["6xl"]="6xl",s["7xl"]="7xl",s["8xl"]="8xl",s["9xl"]="9xl",s))(z||{}),ue=(s=>(s.warning="warning",s.error="error",s.info="info",s.success="success",s.primary="primary",s.brand="brand",s.default="default",s))(ue||{}),mt=(s=>(s.overview="overview",s.detailed="detailed",s.detailedBackground="detailedBackground",s))(mt||{}),Se=(s=>(s.bars="bars",s.dots="dots",s.lineGraph="lineGraph",s.barChart="barGraph",s.milestones="milestones",s.exclusion="exclusion",s))(Se||{}),gt=(s=>(s.zoom="zoom",s.autoPan="autoPan",s.initial="initial",s))(gt||{});const wa=Ee.extend({name:"EBadge",props:{text:{type:String,default:""},color:{type:String,default:ue.default},size:{type:String,default:z.base}},data(){return{colors:{[ue.error]:"e-bg-rose-500 e-text-white",[ue.info]:"e-bg-cyan-500 e-text-white",[ue.warning]:"e-bg-amber-500 e-text-white",[ue.primary]:"e-bg-sky-500 e-text-white",[ue.default]:"e-bg-slate-300 e-text-white",[ue.success]:"e-bg-lime-500 e-text-white"},sizes:{[z.dot]:"e-w-2 e-h-2",[z.xs]:"e-w-3 e-h-3",[z.sm]:"e-w-4 e-h-4",[z.md]:"e-w-5 e-h-5",[z.lg]:"e-min-w-[2rem] e-max-w-[4rem] e-px-1 e-h-6 e-text-sm e-font-medium",[z.xl]:"e-min-w-[3rem] e-max-w-[5rem] e-px-1 e-h-8 e-text-base e-font-medium"}}},computed:{badgeClasses(){const s=this.colors[this.color]||this.colors[ue.default],e=this.sizes[this.size]||this.sizes[z.md];return["e-flex e-items-center e-justify-center e-rounded-full",s,e]},showText(){return[z.lg,z.xl].includes(this.size)}}});function Ie(s,e,t,i,r,n,a,o){var l=typeof s=="function"?s.options:s;e&&(l.render=e,l.staticRenderFns=t,l._compiled=!0),i&&(l.functional=!0),n&&(l._scopeId="data-v-"+n);var c;if(a?(c=function(d){d=d||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext,!d&&typeof __VUE_SSR_CONTEXT__!="undefined"&&(d=__VUE_SSR_CONTEXT__),r&&r.call(this,d),d&&d._registeredComponents&&d._registeredComponents.add(a)},l._ssrRegister=c):r&&(c=o?function(){r.call(this,(l.functional?this.parent:this).$root.$options.shadowRoot)}:r),c)if(l.functional){l._injectStyles=c;var u=l.render;l.render=function(f,m){return c.call(m),u(f,m)}}else{var h=l.beforeCreate;l.beforeCreate=h?[].concat(h,c):[c]}return{exports:s,options:l}}var ka=function(){var e=this,t=e._self._c;return t("span",{staticClass:"e-badge",class:e.badgeClasses},[e.showText?t("span",[e._v(e._s(e.text))]):e._e()])},Pa=[],Oa=Ie(wa,ka,Pa,!1,null,null,null,null);const ni=Oa.exports,Fa=Ee.extend({name:"EAvatar",components:{Badge:ni},props:{size:{type:String,default:z.md},showBadge:{type:Boolean,default:!1},badgeColor:{type:String,default:ue.error},badgeText:{type:String,default:""},badgeSize:{type:String,default:z.md},image:{type:String,default:""}},data(){return{sizes:{[z.xs]:"e-w-8 e-h-8 e-text-xs",[z.sm]:"e-w-10 e-h-10 e-text-sm",[z.md]:"e-w-14 e-h-14 e-text-base",[z.lg]:"e-w-20 e-h-20 e-text-2xl",[z.xl]:"e-w-28 e-h-28 e-text-3xl",[z["2xl"]]:"e-w-36 e-h-36 e-text-5xl"}}},computed:{avatarClasses(){return["e-flex e-items-center e-justify-center e-rounded-full e-bg-purple-500 e-text-white e-font-medium",this.sizes[this.size]||this.sizes[z.xs]]}}});var Ma=function(){var e=this,t=e._self._c;return t("div",{staticClass:"e-avatar e-relative",class:e.avatarClasses},[e._t("default",function(){return[e.image?t("img",{staticClass:"e-avatar__image e-w-full e-h-full e-object-cover e-rounded-full",attrs:{src:e.image}}):e._e()]}),e.showBadge?t("div",{staticClass:"e-avatar__badge e-absolute e-top-0 e-right-0"},[e._t("badge",function(){return[t("Badge",{attrs:{text:e.badgeText,color:e.badgeColor,size:e.badgeSize}})]})],2):e._e()],2)},Na=[],Ba=Ie(Fa,Ma,Na,!1,null,null,null,null);const Ls=Ba.exports;function $a(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Rs={},Cs={},ai={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return e}});function e(t){if(t=`${t}`,t==="0")return"0";if(/^[+-]?(\d+|\d*\.\d+)(e[+-]?\d+)?(%|\w+)?$/.test(t))return t.replace(/^[+-]?/,r=>r==="-"?"":"-");let i=["var","calc","min","max","clamp"];for(const r of i)if(t.includes(`${r}(`))return`calc(${t} * -1)`}})(ai);var Ds={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return e}});const e=["preflight","container","accessibility","pointerEvents","visibility","position","inset","isolation","zIndex","order","gridColumn","gridColumnStart","gridColumnEnd","gridRow","gridRowStart","gridRowEnd","float","clear","margin","boxSizing","lineClamp","display","aspectRatio","height","maxHeight","minHeight","width","minWidth","maxWidth","flex","flexShrink","flexGrow","flexBasis","tableLayout","captionSide","borderCollapse","borderSpacing","transformOrigin","translate","rotate","skew","scale","transform","animation","cursor","touchAction","userSelect","resize","scrollSnapType","scrollSnapAlign","scrollSnapStop","scrollMargin","scrollPadding","listStylePosition","listStyleType","listStyleImage","appearance","columns","breakBefore","breakInside","breakAfter","gridAutoColumns","gridAutoFlow","gridAutoRows","gridTemplateColumns","gridTemplateRows","flexDirection","flexWrap","placeContent","placeItems","alignContent","alignItems","justifyContent","justifyItems","gap","space","divideWidth","divideStyle","divideColor","divideOpacity","placeSelf","alignSelf","justifySelf","overflow","overscrollBehavior","scrollBehavior","textOverflow","hyphens","whitespace","wordBreak","borderRadius","borderWidth","borderStyle","borderColor","borderOpacity","backgroundColor","backgroundOpacity","backgroundImage","gradientColorStops","boxDecorationBreak","backgroundSize","backgroundAttachment","backgroundClip","backgroundPosition","backgroundRepeat","backgroundOrigin","fill","stroke","strokeWidth","objectFit","objectPosition","padding","textAlign","textIndent","verticalAlign","fontFamily","fontSize","fontWeight","textTransform","fontStyle","fontVariantNumeric","lineHeight","letterSpacing","textColor","textOpacity","textDecoration","textDecorationColor","textDecorationStyle","textDecorationThickness","textUnderlineOffset","fontSmoothing","placeholderColor","placeholderOpacity","caretColor","accentColor","opacity","backgroundBlendMode","mixBlendMode","boxShadow","boxShadowColor","outlineStyle","outlineWidth","outlineOffset","outlineColor","ringWidth","ringColor","ringOpacity","ringOffsetWidth","ringOffsetColor","blur","brightness","contrast","dropShadow","grayscale","hueRotate","invert","saturate","sepia","filter","backdropBlur","backdropBrightness","backdropContrast","backdropGrayscale","backdropHueRotate","backdropInvert","backdropOpacity","backdropSaturate","backdropSepia","backdropFilter","transitionProperty","transitionDelay","transitionDuration","transitionTimingFunction","willChange","content"]})(Ds);var _s={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return e}});function e(t,i){return t===void 0?i:Array.isArray(t)?t:[...new Set(i.filter(n=>t!==!1&&t[n]!==!1).concat(Object.keys(t).filter(n=>t[n]!==!1)))]}})(_s);var oi={},Lt={},li={exports:{}},re=String,Is=function(){return{isColorSupported:!1,reset:re,bold:re,dim:re,italic:re,underline:re,inverse:re,hidden:re,strikethrough:re,black:re,red:re,green:re,yellow:re,blue:re,magenta:re,cyan:re,white:re,gray:re,bgBlack:re,bgRed:re,bgGreen:re,bgYellow:re,bgBlue:re,bgMagenta:re,bgCyan:re,bgWhite:re}};li.exports=Is(),li.exports.createColors=Is;var ws=li.exports;(function(s){Object.defineProperty(s,"__esModule",{value:!0});function e(l,c){for(var u in c)Object.defineProperty(l,u,{enumerable:!0,get:c[u]})}e(s,{dim:function(){return a},default:function(){return o}});const t=i(ws);function i(l){return l&&l.__esModule?l:{default:l}}let r=new Set;function n(l,c,u){typeof process!="undefined"&&process.env.JEST_WORKER_ID||u&&r.has(u)||(u&&r.add(u),console.warn(""),c.forEach(h=>console.warn(l,"-",h)))}function a(l){return t.default.dim(l)}const o={info(l,c){n(t.default.bold(t.default.cyan("info")),...Array.isArray(l)?[l]:[c,l])},warn(l,c){n(t.default.bold(t.default.yellow("warn")),...Array.isArray(l)?[l]:[c,l])},risk(l,c){n(t.default.bold(t.default.magenta("risk")),...Array.isArray(l)?[l]:[c,l])}}})(Lt),function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return r}});const e=t(Lt);function t(n){return n&&n.__esModule?n:{default:n}}function i({version:n,from:a,to:o}){e.default.warn(`${a}-color-renamed`,[`As of Tailwind CSS ${n}, \`${a}\` has been renamed to \`${o}\`.`,"Update your configuration file to silence this warning."])}const r={inherit:"inherit",current:"currentColor",transparent:"transparent",black:"#000",white:"#fff",slate:{50:"#f8fafc",100:"#f1f5f9",200:"#e2e8f0",300:"#cbd5e1",400:"#94a3b8",500:"#64748b",600:"#475569",700:"#334155",800:"#1e293b",900:"#0f172a",950:"#020617"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},zinc:{50:"#fafafa",100:"#f4f4f5",200:"#e4e4e7",300:"#d4d4d8",400:"#a1a1aa",500:"#71717a",600:"#52525b",700:"#3f3f46",800:"#27272a",900:"#18181b",950:"#09090b"},neutral:{50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},stone:{50:"#fafaf9",100:"#f5f5f4",200:"#e7e5e4",300:"#d6d3d1",400:"#a8a29e",500:"#78716c",600:"#57534e",700:"#44403c",800:"#292524",900:"#1c1917",950:"#0c0a09"},red:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d",950:"#450a0a"},orange:{50:"#fff7ed",100:"#ffedd5",200:"#fed7aa",300:"#fdba74",400:"#fb923c",500:"#f97316",600:"#ea580c",700:"#c2410c",800:"#9a3412",900:"#7c2d12",950:"#431407"},amber:{50:"#fffbeb",100:"#fef3c7",200:"#fde68a",300:"#fcd34d",400:"#fbbf24",500:"#f59e0b",600:"#d97706",700:"#b45309",800:"#92400e",900:"#78350f",950:"#451a03"},yellow:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12",950:"#422006"},lime:{50:"#f7fee7",100:"#ecfccb",200:"#d9f99d",300:"#bef264",400:"#a3e635",500:"#84cc16",600:"#65a30d",700:"#4d7c0f",800:"#3f6212",900:"#365314",950:"#1a2e05"},green:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d",950:"#052e16"},emerald:{50:"#ecfdf5",100:"#d1fae5",200:"#a7f3d0",300:"#6ee7b7",400:"#34d399",500:"#10b981",600:"#059669",700:"#047857",800:"#065f46",900:"#064e3b",950:"#022c22"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"},cyan:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},sky:{50:"#f0f9ff",100:"#e0f2fe",200:"#bae6fd",300:"#7dd3fc",400:"#38bdf8",500:"#0ea5e9",600:"#0284c7",700:"#0369a1",800:"#075985",900:"#0c4a6e",950:"#082f49"},blue:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},indigo:{50:"#eef2ff",100:"#e0e7ff",200:"#c7d2fe",300:"#a5b4fc",400:"#818cf8",500:"#6366f1",600:"#4f46e5",700:"#4338ca",800:"#3730a3",900:"#312e81",950:"#1e1b4b"},violet:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},fuchsia:{50:"#fdf4ff",100:"#fae8ff",200:"#f5d0fe",300:"#f0abfc",400:"#e879f9",500:"#d946ef",600:"#c026d3",700:"#a21caf",800:"#86198f",900:"#701a75",950:"#4a044e"},pink:{50:"#fdf2f8",100:"#fce7f3",200:"#fbcfe8",300:"#f9a8d4",400:"#f472b6",500:"#ec4899",600:"#db2777",700:"#be185d",800:"#9d174d",900:"#831843",950:"#500724"},rose:{50:"#fff1f2",100:"#ffe4e6",200:"#fecdd3",300:"#fda4af",400:"#fb7185",500:"#f43f5e",600:"#e11d48",700:"#be123c",800:"#9f1239",900:"#881337",950:"#4c0519"},get lightBlue(){return i({version:"v2.2",from:"lightBlue",to:"sky"}),this.sky},get warmGray(){return i({version:"v3.0",from:"warmGray",to:"stone"}),this.stone},get trueGray(){return i({version:"v3.0",from:"trueGray",to:"neutral"}),this.neutral},get coolGray(){return i({version:"v3.0",from:"coolGray",to:"gray"}),this.gray},get blueGray(){return i({version:"v3.0",from:"blueGray",to:"slate"}),this.slate}}}(oi);var ks={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"defaults",{enumerable:!0,get:function(){return e}});function e(t,...i){for(let a of i){for(let o in a){var r;!(t==null||(r=t.hasOwnProperty)===null||r===void 0)&&r.call(t,o)||(t[o]=a[o])}for(let o of Object.getOwnPropertySymbols(a)){var n;!(t==null||(n=t.hasOwnProperty)===null||n===void 0)&&n.call(t,o)||(t[o]=a[o])}}return t}})(ks);var Ps={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"toPath",{enumerable:!0,get:function(){return e}});function e(t){if(Array.isArray(t))return t;let i=t.split("[").length-1,r=t.split("]").length-1;if(i!==r)throw new Error(`Path is invalid. Has unbalanced brackets: ${t}`);return t.split(/\.(?![^\[]*\])|[\[\]]/g).filter(Boolean)}})(Ps);var Os={},Rt={};(function(s){Object.defineProperty(s,"__esModule",{value:!0});function e(h,d){for(var f in d)Object.defineProperty(h,f,{enumerable:!0,get:d[f]})}e(s,{flagEnabled:function(){return o},issueFlagNotices:function(){return c},default:function(){return u}});const t=r(ws),i=r(Lt);function r(h){return h&&h.__esModule?h:{default:h}}let n={optimizeUniversalDefaults:!1,generalizedModifiers:!0,get disableColorOpacityUtilitiesByDefault(){return!1},get relativeContentPathsByDefault(){return!1}},a={future:["hoverOnlyWhenSupported","respectDefaultRingColorOpacity","disableColorOpacityUtilitiesByDefault","relativeContentPathsByDefault"],experimental:["optimizeUniversalDefaults","generalizedModifiers"]};function o(h,d){if(a.future.includes(d)){var f,m,g;return h.future==="all"||((g=(m=h==null||(f=h.future)===null||f===void 0?void 0:f[d])!==null&&m!==void 0?m:n[d])!==null&&g!==void 0?g:!1)}if(a.experimental.includes(d)){var y,v,T;return h.experimental==="all"||((T=(v=h==null||(y=h.experimental)===null||y===void 0?void 0:y[d])!==null&&v!==void 0?v:n[d])!==null&&T!==void 0?T:!1)}return!1}function l(h){if(h.experimental==="all")return a.experimental;var d;return Object.keys((d=h==null?void 0:h.experimental)!==null&&d!==void 0?d:{}).filter(f=>a.experimental.includes(f)&&h.experimental[f])}function c(h){if(process.env.JEST_WORKER_ID===void 0&&l(h).length>0){let d=l(h).map(f=>t.default.yellow(f)).join(", ");i.default.warn("experimental-flags-enabled",[`You have enabled experimental features: ${d}`,"Experimental features in Tailwind CSS are not covered by semver, may introduce breaking changes, and can change at any time."])}}const u=a})(Rt),function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"normalizeConfig",{enumerable:!0,get:function(){return n}});const e=Rt,t=r(Lt);function i(a){if(typeof WeakMap!="function")return null;var o=new WeakMap,l=new WeakMap;return(i=function(c){return c?l:o})(a)}function r(a,o){if(!o&&a&&a.__esModule)return a;if(a===null||typeof a!="object"&&typeof a!="function")return{default:a};var l=i(o);if(l&&l.has(a))return l.get(a);var c={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var h in a)if(h!=="default"&&Object.prototype.hasOwnProperty.call(a,h)){var d=u?Object.getOwnPropertyDescriptor(a,h):null;d&&(d.get||d.set)?Object.defineProperty(c,h,d):c[h]=a[h]}return c.default=a,l&&l.set(a,c),c}function n(a){if((()=>{if(a.purge||!a.content||!Array.isArray(a.content)&&!(typeof a.content=="object"&&a.content!==null))return!1;if(Array.isArray(a.content))return a.content.every(c=>typeof c=="string"?!0:!(typeof(c==null?void 0:c.raw)!="string"||c!=null&&c.extension&&typeof(c==null?void 0:c.extension)!="string"));if(typeof a.content=="object"&&a.content!==null){if(Object.keys(a.content).some(c=>!["files","relative","extract","transform"].includes(c)))return!1;if(Array.isArray(a.content.files)){if(!a.content.files.every(c=>typeof c=="string"?!0:!(typeof(c==null?void 0:c.raw)!="string"||c!=null&&c.extension&&typeof(c==null?void 0:c.extension)!="string")))return!1;if(typeof a.content.extract=="object"){for(let c of Object.values(a.content.extract))if(typeof c!="function")return!1}else if(!(a.content.extract===void 0||typeof a.content.extract=="function"))return!1;if(typeof a.content.transform=="object"){for(let c of Object.values(a.content.transform))if(typeof c!="function")return!1}else if(!(a.content.transform===void 0||typeof a.content.transform=="function"))return!1;if(typeof a.content.relative!="boolean"&&typeof a.content.relative!="undefined")return!1}return!0}return!1})()||t.default.warn("purge-deprecation",["The `purge`/`content` options have changed in Tailwind CSS v3.0.","Update your configuration file to eliminate this warning.","https://tailwindcss.com/docs/upgrade-guide#configure-content-sources"]),a.safelist=(()=>{var c;let{content:u,purge:h,safelist:d}=a;return Array.isArray(d)?d:Array.isArray(u==null?void 0:u.safelist)?u.safelist:Array.isArray(h==null?void 0:h.safelist)?h.safelist:Array.isArray(h==null||(c=h.options)===null||c===void 0?void 0:c.safelist)?h.options.safelist:[]})(),a.blocklist=(()=>{let{blocklist:c}=a;if(Array.isArray(c)){if(c.every(u=>typeof u=="string"))return c;t.default.warn("blocklist-invalid",["The `blocklist` option must be an array of strings.","https://tailwindcss.com/docs/content-configuration#discarding-classes"])}return[]})(),typeof a.prefix=="function")t.default.warn("prefix-function",["As of Tailwind CSS v3.0, `prefix` cannot be a function.","Update `prefix` in your configuration to be a string to eliminate this warning.","https://tailwindcss.com/docs/upgrade-guide#prefix-cannot-be-a-function"]),a.prefix="";else{var l;a.prefix=(l=a.prefix)!==null&&l!==void 0?l:""}a.content={relative:(()=>{let{content:c}=a;return c!=null&&c.relative?c.relative:(0,e.flagEnabled)(a,"relativeContentPathsByDefault")})(),files:(()=>{let{content:c,purge:u}=a;return Array.isArray(u)?u:Array.isArray(u==null?void 0:u.content)?u.content:Array.isArray(c)?c:Array.isArray(c==null?void 0:c.content)?c.content:Array.isArray(c==null?void 0:c.files)?c.files:[]})(),extract:(()=>{let c=(()=>{var d,f,m,g,y,v,T,x,L,E;return!((d=a.purge)===null||d===void 0)&&d.extract?a.purge.extract:!((f=a.content)===null||f===void 0)&&f.extract?a.content.extract:!((m=a.purge)===null||m===void 0||(g=m.extract)===null||g===void 0)&&g.DEFAULT?a.purge.extract.DEFAULT:!((y=a.content)===null||y===void 0||(v=y.extract)===null||v===void 0)&&v.DEFAULT?a.content.extract.DEFAULT:!((T=a.purge)===null||T===void 0||(x=T.options)===null||x===void 0)&&x.extractors?a.purge.options.extractors:!((L=a.content)===null||L===void 0||(E=L.options)===null||E===void 0)&&E.extractors?a.content.options.extractors:{}})(),u={},h=(()=>{var d,f,m,g;if(!((d=a.purge)===null||d===void 0||(f=d.options)===null||f===void 0)&&f.defaultExtractor)return a.purge.options.defaultExtractor;if(!((m=a.content)===null||m===void 0||(g=m.options)===null||g===void 0)&&g.defaultExtractor)return a.content.options.defaultExtractor})();if(h!==void 0&&(u.DEFAULT=h),typeof c=="function")u.DEFAULT=c;else if(Array.isArray(c))for(let{extensions:d,extractor:f}of c!=null?c:[])for(let m of d)u[m]=f;else typeof c=="object"&&c!==null&&Object.assign(u,c);return u})(),transform:(()=>{let c=(()=>{var h,d,f,m,g,y;return!((h=a.purge)===null||h===void 0)&&h.transform?a.purge.transform:!((d=a.content)===null||d===void 0)&&d.transform?a.content.transform:!((f=a.purge)===null||f===void 0||(m=f.transform)===null||m===void 0)&&m.DEFAULT?a.purge.transform.DEFAULT:!((g=a.content)===null||g===void 0||(y=g.transform)===null||y===void 0)&&y.DEFAULT?a.content.transform.DEFAULT:{}})(),u={};return typeof c=="function"&&(u.DEFAULT=c),typeof c=="object"&&c!==null&&Object.assign(u,c),u})()};for(let c of a.content.files)if(typeof c=="string"&&/{([^,]*?)}/g.test(c)){t.default.warn("invalid-glob-braces",[`The glob pattern ${(0,t.dim)(c)} in your Tailwind CSS configuration is invalid.`,`Update it to ${(0,t.dim)(c.replace(/{([^,]*?)}/g,"$1"))} to silence this warning.`]);break}return a}}(Os);var Fs={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return e}});function e(t){if(Object.prototype.toString.call(t)!=="[object Object]")return!1;const i=Object.getPrototypeOf(t);return i===null||i===Object.prototype}})(Fs);var Ms={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"cloneDeep",{enumerable:!0,get:function(){return e}});function e(t){return Array.isArray(t)?t.map(i=>e(i)):typeof t=="object"&&t!==null?Object.fromEntries(Object.entries(t).map(([i,r])=>[i,e(r)])):t}})(Ms);var Ns={},Bs={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return e}});function e(t){return t.replace(/\\,/g,"\\2c ")}})(Bs);var ci={},ui={},$s={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return e}});const e={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}})($s),function(s){Object.defineProperty(s,"__esModule",{value:!0});function e(m,g){for(var y in g)Object.defineProperty(m,y,{enumerable:!0,get:g[y]})}e(s,{parseColor:function(){return d},formatColor:function(){return f}});const t=i($s);function i(m){return m&&m.__esModule?m:{default:m}}let r=/^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i,n=/^#([a-f\d])([a-f\d])([a-f\d])([a-f\d])?$/i,a=/(?:\d+|\d*\.\d+)%?/,o=/(?:\s*,\s*|\s+)/,l=/\s*[,/]\s*/,c=/var\(--(?:[^ )]*?)\)/,u=new RegExp(`^(rgba?)\\(\\s*(${a.source}|${c.source})(?:${o.source}(${a.source}|${c.source}))?(?:${o.source}(${a.source}|${c.source}))?(?:${l.source}(${a.source}|${c.source}))?\\s*\\)$`),h=new RegExp(`^(hsla?)\\(\\s*((?:${a.source})(?:deg|rad|grad|turn)?|${c.source})(?:${o.source}(${a.source}|${c.source}))?(?:${o.source}(${a.source}|${c.source}))?(?:${l.source}(${a.source}|${c.source}))?\\s*\\)$`);function d(m,{loose:g=!1}={}){var y,v;if(typeof m!="string")return null;if(m=m.trim(),m==="transparent")return{mode:"rgb",color:["0","0","0"],alpha:"0"};if(m in t.default)return{mode:"rgb",color:t.default[m].map(k=>k.toString())};let T=m.replace(n,(k,R,B,C,b)=>["#",R,R,B,B,C,C,b?b+b:""].join("")).match(r);if(T!==null)return{mode:"rgb",color:[parseInt(T[1],16),parseInt(T[2],16),parseInt(T[3],16)].map(k=>k.toString()),alpha:T[4]?(parseInt(T[4],16)/255).toString():void 0};var x;let L=(x=m.match(u))!==null&&x!==void 0?x:m.match(h);if(L===null)return null;let E=[L[2],L[3],L[4]].filter(Boolean).map(k=>k.toString());return E.length===2&&E[0].startsWith("var(")?{mode:L[1],color:[E[0]],alpha:E[1]}:!g&&E.length!==3||E.length<3&&!E.some(k=>/^var\(.*?\)$/.test(k))?null:{mode:L[1],color:E,alpha:(y=L[5])===null||y===void 0||(v=y.toString)===null||v===void 0?void 0:v.call(y)}}function f({mode:m,color:g,alpha:y}){let v=y!==void 0;return m==="rgba"||m==="hsla"?`${m}(${g.join(", ")}${v?`, ${y}`:""})`:`${m}(${g.join(" ")}${v?` / ${y}`:""})`}}(ui),function(s){Object.defineProperty(s,"__esModule",{value:!0});function e(n,a){for(var o in a)Object.defineProperty(n,o,{enumerable:!0,get:a[o]})}e(s,{withAlphaValue:function(){return i},default:function(){return r}});const t=ui;function i(n,a,o){if(typeof n=="function")return n({opacityValue:a});let l=(0,t.parseColor)(n,{loose:!0});return l===null?o:(0,t.formatColor)({...l,alpha:a})}function r({color:n,property:a,variable:o}){let l=[].concat(a);if(typeof n=="function")return{[o]:"1",...Object.fromEntries(l.map(u=>[u,n({opacityVariable:o,opacityValue:`var(${o})`})]))};const c=(0,t.parseColor)(n);return c===null?Object.fromEntries(l.map(u=>[u,n])):c.alpha!==void 0?Object.fromEntries(l.map(u=>[u,n])):{[o]:"1",...Object.fromEntries(l.map(u=>[u,(0,t.formatColor)({...c,alpha:`var(${o})`})]))}}}(ci);var hi={},Us={},Ct={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"splitAtTopLevelOnly",{enumerable:!0,get:function(){return e}});function e(t,i){let r=[],n=[],a=0,o=!1;for(let l=0;l<t.length;l++){let c=t[l];r.length===0&&c===i[0]&&!o&&(i.length===1||t.slice(l,l+i.length)===i)&&(n.push(t.slice(a,l)),a=l+i.length),o?o=!1:c==="\\"&&(o=!0),c==="("||c==="["||c==="{"?r.push(c):(c===")"&&r[r.length-1]==="("||c==="]"&&r[r.length-1]==="["||c==="}"&&r[r.length-1]==="{")&&r.pop()}return n.push(t.slice(a)),n}})(Ct),function(s){Object.defineProperty(s,"__esModule",{value:!0});function e(l,c){for(var u in c)Object.defineProperty(l,u,{enumerable:!0,get:c[u]})}e(s,{parseBoxShadowValue:function(){return a},formatBoxShadowValue:function(){return o}});const t=Ct;let i=new Set(["inset","inherit","initial","revert","unset"]),r=/\ +(?![^(]*\))/g,n=/^-?(\d+|\.\d+)(.*?)$/g;function a(l){return(0,t.splitAtTopLevelOnly)(l,",").map(u=>{let h=u.trim(),d={raw:h},f=h.split(r),m=new Set;for(let g of f)n.lastIndex=0,!m.has("KEYWORD")&&i.has(g)?(d.keyword=g,m.add("KEYWORD")):n.test(g)?m.has("X")?m.has("Y")?m.has("BLUR")?m.has("SPREAD")||(d.spread=g,m.add("SPREAD")):(d.blur=g,m.add("BLUR")):(d.y=g,m.add("Y")):(d.x=g,m.add("X")):d.color?(d.unknown||(d.unknown=[]),d.unknown.push(g)):d.color=g;return d.valid=d.x!==void 0&&d.y!==void 0,d})}function o(l){return l.map(c=>c.valid?[c.keyword,c.x,c.y,c.blur,c.spread,c.color].filter(Boolean).join(" "):c.raw).join(", ")}}(Us),function(s){Object.defineProperty(s,"__esModule",{value:!0});function e(F,V){for(var H in V)Object.defineProperty(F,H,{enumerable:!0,get:V[H]})}e(s,{normalize:function(){return c},url:function(){return h},number:function(){return d},percentage:function(){return f},length:function(){return y},lineWidth:function(){return T},shadow:function(){return x},color:function(){return L},image:function(){return E},gradient:function(){return R},position:function(){return C},familyName:function(){return b},genericName:function(){return P},absoluteSize:function(){return $},relativeSize:function(){return U}});const t=ui,i=Us,r=Ct;let n=["min","max","clamp","calc"];function a(F){return n.some(V=>new RegExp(`^${V}\\(.*\\)`).test(F))}const o="--tw-placeholder",l=new RegExp(o,"g");function c(F,V=!0){return F.startsWith("--")?`var(${F})`:F.includes("url(")?F.split(/(url\(.*?\))/g).filter(Boolean).map(H=>/^url\(.*?\)$/.test(H)?H:c(H,!1)).join(""):(F=F.replace(/([^\\])_+/g,(H,N)=>N+" ".repeat(H.length-1)).replace(/^_/g," ").replace(/\\_/g,"_"),V&&(F=F.trim()),F=u(F),F)}function u(F){return F.replace(/(calc|min|max|clamp)\(.+\)/g,V=>{let H=[];return V.replace(/var\((--.+?)[,)]/g,(N,J)=>(H.push(J),N.replace(J,o))).replace(/(-?\d*\.?\d(?!\b-\d.+[,)](?![^+\-/*])\D)(?:%|[a-z]+)?|\))([+\-/*])/g,"$1 $2 ").replace(l,()=>H.shift())})}function h(F){return F.startsWith("url(")}function d(F){return!isNaN(Number(F))||a(F)}function f(F){return F.endsWith("%")&&d(F.slice(0,-1))||a(F)}let g=`(?:${["cm","mm","Q","in","pc","pt","px","em","ex","ch","rem","lh","rlh","vw","vh","vmin","vmax","vb","vi","svw","svh","lvw","lvh","dvw","dvh","cqw","cqh","cqi","cqb","cqmin","cqmax"].join("|")})`;function y(F){return F==="0"||new RegExp(`^[+-]?[0-9]*.?[0-9]+(?:[eE][+-]?[0-9]+)?${g}$`).test(F)||a(F)}let v=new Set(["thin","medium","thick"]);function T(F){return v.has(F)}function x(F){let V=(0,i.parseBoxShadowValue)(c(F));for(let H of V)if(!H.valid)return!1;return!0}function L(F){let V=0;return(0,r.splitAtTopLevelOnly)(F,"_").every(N=>(N=c(N),N.startsWith("var(")?!0:(0,t.parseColor)(N,{loose:!0})!==null?(V++,!0):!1))?V>0:!1}function E(F){let V=0;return(0,r.splitAtTopLevelOnly)(F,",").every(N=>(N=c(N),N.startsWith("var(")?!0:h(N)||R(N)||["element(","image(","cross-fade(","image-set("].some(J=>N.startsWith(J))?(V++,!0):!1))?V>0:!1}let k=new Set(["conic-gradient","linear-gradient","radial-gradient","repeating-conic-gradient","repeating-linear-gradient","repeating-radial-gradient"]);function R(F){F=c(F);for(let V of k)if(F.startsWith(`${V}(`))return!0;return!1}let B=new Set(["center","top","right","bottom","left"]);function C(F){let V=0;return(0,r.splitAtTopLevelOnly)(F,"_").every(N=>(N=c(N),N.startsWith("var(")?!0:B.has(N)||y(N)||f(N)?(V++,!0):!1))?V>0:!1}function b(F){let V=0;return(0,r.splitAtTopLevelOnly)(F,",").every(N=>(N=c(N),N.startsWith("var(")?!0:N.includes(" ")&&!/(['"])([^"']+)\1/g.test(N)||/^\d/g.test(N)?!1:(V++,!0)))?V>0:!1}let D=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]);function P(F){return D.has(F)}let w=new Set(["xx-small","x-small","small","medium","large","x-large","x-large","xxx-large"]);function $(F){return w.has(F)}let O=new Set(["larger","smaller"]);function U(F){return O.has(F)}}(hi);var Gs={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"backgroundSize",{enumerable:!0,get:function(){return i}});const e=hi,t=Ct;function i(r){let n=["cover","contain"];return(0,t.splitAtTopLevelOnly)(r,",").every(a=>{let o=(0,t.splitAtTopLevelOnly)(a,"_").filter(Boolean);return o.length===1&&n.includes(o[0])?!0:o.length!==1&&o.length!==2?!1:o.every(l=>(0,e.length)(l)||(0,e.percentage)(l)||l==="auto")})}})(Gs),function(s){Object.defineProperty(s,"__esModule",{value:!0});function e(C,b){for(var D in b)Object.defineProperty(C,D,{enumerable:!0,get:b[D]})}e(s,{updateAllClasses:function(){return c},asValue:function(){return d},parseColorFormat:function(){return g},asColor:function(){return v},asLookupValue:function(){return T},typeMap:function(){return L},coerceValue:function(){return R},getMatchingTypes:function(){return B}});const t=l(Bs),i=ci,r=hi,n=l(ai),a=Gs,o=Rt;function l(C){return C&&C.__esModule?C:{default:C}}function c(C,b){C.walkClasses(D=>{D.value=b(D.value),D.raws&&D.raws.value&&(D.raws.value=(0,t.default)(D.raws.value))})}function u(C,b){if(!f(C))return;let D=C.slice(1,-1);if(b(D))return(0,r.normalize)(D)}function h(C,b={},D){let P=b[C];if(P!==void 0)return(0,n.default)(P);if(f(C)){let w=u(C,D);return w===void 0?void 0:(0,n.default)(w)}}function d(C,b={},{validate:D=()=>!0}={}){var P;let w=(P=b.values)===null||P===void 0?void 0:P[C];return w!==void 0?w:b.supportsNegativeValues&&C.startsWith("-")?h(C.slice(1),b.values,D):u(C,D)}function f(C){return C.startsWith("[")&&C.endsWith("]")}function m(C){let b=C.lastIndexOf("/");return b===-1||b===C.length-1?[C,void 0]:f(C)&&!C.includes("]/[")?[C,void 0]:[C.slice(0,b),C.slice(b+1)]}function g(C){if(typeof C=="string"&&C.includes("<alpha-value>")){let b=C;return({opacityValue:D=1})=>b.replace("<alpha-value>",D)}return C}function y(C){return(0,r.normalize)(C.slice(1,-1))}function v(C,b={},{tailwindConfig:D={}}={}){var P;if(((P=b.values)===null||P===void 0?void 0:P[C])!==void 0){var w;return g((w=b.values)===null||w===void 0?void 0:w[C])}let[$,O]=m(C);if(O!==void 0){var U,F,V,H;let N=(H=(U=b.values)===null||U===void 0?void 0:U[$])!==null&&H!==void 0?H:f($)?$.slice(1,-1):void 0;return N===void 0?void 0:(N=g(N),f(O)?(0,i.withAlphaValue)(N,y(O)):((F=D.theme)===null||F===void 0||(V=F.opacity)===null||V===void 0?void 0:V[O])===void 0?void 0:(0,i.withAlphaValue)(N,D.theme.opacity[O]))}return d(C,b,{validate:r.color})}function T(C,b={}){var D;return(D=b.values)===null||D===void 0?void 0:D[C]}function x(C){return(b,D)=>d(b,D,{validate:C})}let L={any:d,color:v,url:x(r.url),image:x(r.image),length:x(r.length),percentage:x(r.percentage),position:x(r.position),lookup:T,"generic-name":x(r.genericName),"family-name":x(r.familyName),number:x(r.number),"line-width":x(r.lineWidth),"absolute-size":x(r.absoluteSize),"relative-size":x(r.relativeSize),shadow:x(r.shadow),size:x(a.backgroundSize)},E=Object.keys(L);function k(C,b){let D=C.indexOf(b);return D===-1?[void 0,C]:[C.slice(0,D),C.slice(D+1)]}function R(C,b,D,P){if(D.values&&b in D.values)for(let{type:$}of C!=null?C:[]){let O=L[$](b,D,{tailwindConfig:P});if(O!==void 0)return[O,$,null]}if(f(b)){let $=b.slice(1,-1),[O,U]=k($,":");if(!/^[\w-_]+$/g.test(O))U=$;else if(O!==void 0&&!E.includes(O))return[];if(U.length>0&&E.includes(O))return[d(`[${U}]`,D),O,null]}let w=B(C,b,D,P);for(let $ of w)return $;return[]}function*B(C,b,D,P){let w=(0,o.flagEnabled)(P,"generalizedModifiers"),[$,O]=m(b);if(w&&D.modifiers!=null&&(D.modifiers==="any"||typeof D.modifiers=="object"&&(O&&f(O)||O in D.modifiers))||($=b,O=void 0),O!==void 0&&$===""&&($="DEFAULT"),O!==void 0&&typeof D.modifiers=="object"){var F,V;let H=(V=(F=D.modifiers)===null||F===void 0?void 0:F[O])!==null&&V!==void 0?V:null;H!==null?O=H:f(O)&&(O=y(O))}for(let{type:H}of C!=null?C:[]){let N=L[H]($,D,{tailwindConfig:P});N!==void 0&&(yield[N,H,O!=null?O:null])}}}(Ns);var Hs={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return e}});function e(t){return typeof t=="function"?t({}):t}})(Hs),function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return D}});const e=f(ai),t=f(Ds),i=f(_s),r=f(oi),n=ks,a=Ps,o=Os,l=f(Fs),c=Ms,u=Ns,h=ci,d=f(Hs);function f(P){return P&&P.__esModule?P:{default:P}}function m(P){return typeof P=="function"}function g(P,...w){let $=w.pop();for(let O of w)for(let U in O){let F=$(P[U],O[U]);F===void 0?(0,l.default)(P[U])&&(0,l.default)(O[U])?P[U]=g({},P[U],O[U],$):P[U]=O[U]:P[U]=F}return P}const y={colors:r.default,negative(P){return Object.keys(P).filter(w=>P[w]!=="0").reduce((w,$)=>{let O=(0,e.default)(P[$]);return O!==void 0&&(w[`-${$}`]=O),w},{})},breakpoints(P){return Object.keys(P).filter(w=>typeof P[w]=="string").reduce((w,$)=>({...w,[`screen-${$}`]:P[$]}),{})}};function v(P,...w){return m(P)?P(...w):P}function T(P){return P.reduce((w,{extend:$})=>g(w,$,(O,U)=>O===void 0?[U]:Array.isArray(O)?[U,...O]:[U,O]),{})}function x(P){return{...P.reduce((w,$)=>(0,n.defaults)(w,$),{}),extend:T(P)}}function L(P,w){if(Array.isArray(P)&&(0,l.default)(P[0]))return P.concat(w);if(Array.isArray(w)&&(0,l.default)(w[0])&&(0,l.default)(P))return[P,...w];if(Array.isArray(w))return w}function E({extend:P,...w}){return g(w,P,($,O)=>!m($)&&!O.some(m)?g({},$,...O,L):(U,F)=>g({},...[$,...O].map(V=>v(V,U,F)),L))}function*k(P){let w=(0,a.toPath)(P);if(w.length===0||(yield w,Array.isArray(P)))return;let $=/^(.*?)\s*\/\s*([^/]+)$/,O=P.match($);if(O!==null){let[,U,F]=O,V=(0,a.toPath)(U);V.alpha=F,yield V}}function R(P){const w=($,O)=>{for(const U of k($)){let F=0,V=P;for(;V!=null&&F<U.length;)V=V[U[F++]],V=m(V)&&(U.alpha===void 0||F<=U.length-1)?V(w,y):V;if(V!==void 0){if(U.alpha!==void 0){let H=(0,u.parseColorFormat)(V);return(0,h.withAlphaValue)(H,U.alpha,(0,d.default)(H))}return(0,l.default)(V)?(0,c.cloneDeep)(V):V}}return O};return Object.assign(w,{theme:w,...y}),Object.keys(P).reduce(($,O)=>($[O]=m(P[O])?P[O](w,y):P[O],$),{})}function B(P){let w=[];return P.forEach($=>{w=[...w,$];var O;const U=(O=$==null?void 0:$.plugins)!==null&&O!==void 0?O:[];U.length!==0&&U.forEach(F=>{F.__isOptionsFunction&&(F=F());var V;w=[...w,...B([(V=F==null?void 0:F.config)!==null&&V!==void 0?V:{}])]})}),w}function C(P){return[...P].reduceRight(($,O)=>m(O)?O({corePlugins:$}):(0,i.default)(O,$),t.default)}function b(P){return[...P].reduceRight(($,O)=>[...$,...O],[])}function D(P){let w=[...B(P),{prefix:"",important:!1,separator:":"}];var $,O;return(0,o.normalizeConfig)((0,n.defaults)({theme:R(E(x(w.map(U=>($=U==null?void 0:U.theme)!==null&&$!==void 0?$:{})))),corePlugins:C(w.map(U=>U.corePlugins)),plugins:b(P.map(U=>(O=U==null?void 0:U.plugins)!==null&&O!==void 0?O:[]))},...w))}}(Cs);var Vs={},Ua={content:[],presets:[],darkMode:"media",theme:{accentColor:({theme:s})=>({...s("colors"),auto:"auto"}),animation:{none:"none",spin:"spin 1s linear infinite",ping:"ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",bounce:"bounce 1s infinite"},aria:{busy:'busy="true"',checked:'checked="true"',disabled:'disabled="true"',expanded:'expanded="true"',hidden:'hidden="true"',pressed:'pressed="true"',readonly:'readonly="true"',required:'required="true"',selected:'selected="true"'},aspectRatio:{auto:"auto",square:"1 / 1",video:"16 / 9"},backdropBlur:({theme:s})=>s("blur"),backdropBrightness:({theme:s})=>s("brightness"),backdropContrast:({theme:s})=>s("contrast"),backdropGrayscale:({theme:s})=>s("grayscale"),backdropHueRotate:({theme:s})=>s("hueRotate"),backdropInvert:({theme:s})=>s("invert"),backdropOpacity:({theme:s})=>s("opacity"),backdropSaturate:({theme:s})=>s("saturate"),backdropSepia:({theme:s})=>s("sepia"),backgroundColor:({theme:s})=>s("colors"),backgroundImage:{none:"none","gradient-to-t":"linear-gradient(to top, var(--tw-gradient-stops))","gradient-to-tr":"linear-gradient(to top right, var(--tw-gradient-stops))","gradient-to-r":"linear-gradient(to right, var(--tw-gradient-stops))","gradient-to-br":"linear-gradient(to bottom right, var(--tw-gradient-stops))","gradient-to-b":"linear-gradient(to bottom, var(--tw-gradient-stops))","gradient-to-bl":"linear-gradient(to bottom left, var(--tw-gradient-stops))","gradient-to-l":"linear-gradient(to left, var(--tw-gradient-stops))","gradient-to-tl":"linear-gradient(to top left, var(--tw-gradient-stops))"},backgroundOpacity:({theme:s})=>s("opacity"),backgroundPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},backgroundSize:{auto:"auto",cover:"cover",contain:"contain"},blur:{0:"0",none:"0",sm:"4px",DEFAULT:"8px",md:"12px",lg:"16px",xl:"24px","2xl":"40px","3xl":"64px"},borderColor:({theme:s})=>({...s("colors"),DEFAULT:s("colors.gray.200","currentColor")}),borderOpacity:({theme:s})=>s("opacity"),borderRadius:{none:"0px",sm:"0.125rem",DEFAULT:"0.25rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem","3xl":"1.5rem",full:"9999px"},borderSpacing:({theme:s})=>({...s("spacing")}),borderWidth:{DEFAULT:"1px",0:"0px",2:"2px",4:"4px",8:"8px"},boxShadow:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",DEFAULT:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)",inner:"inset 0 2px 4px 0 rgb(0 0 0 / 0.05)",none:"none"},boxShadowColor:({theme:s})=>s("colors"),brightness:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",200:"2"},caretColor:({theme:s})=>s("colors"),colors:({colors:s})=>({inherit:s.inherit,current:s.current,transparent:s.transparent,black:s.black,white:s.white,slate:s.slate,gray:s.gray,zinc:s.zinc,neutral:s.neutral,stone:s.stone,red:s.red,orange:s.orange,amber:s.amber,yellow:s.yellow,lime:s.lime,green:s.green,emerald:s.emerald,teal:s.teal,cyan:s.cyan,sky:s.sky,blue:s.blue,indigo:s.indigo,violet:s.violet,purple:s.purple,fuchsia:s.fuchsia,pink:s.pink,rose:s.rose}),columns:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12","3xs":"16rem","2xs":"18rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem"},container:{},content:{none:"none"},contrast:{0:"0",50:".5",75:".75",100:"1",125:"1.25",150:"1.5",200:"2"},cursor:{auto:"auto",default:"default",pointer:"pointer",wait:"wait",text:"text",move:"move",help:"help","not-allowed":"not-allowed",none:"none","context-menu":"context-menu",progress:"progress",cell:"cell",crosshair:"crosshair","vertical-text":"vertical-text",alias:"alias",copy:"copy","no-drop":"no-drop",grab:"grab",grabbing:"grabbing","all-scroll":"all-scroll","col-resize":"col-resize","row-resize":"row-resize","n-resize":"n-resize","e-resize":"e-resize","s-resize":"s-resize","w-resize":"w-resize","ne-resize":"ne-resize","nw-resize":"nw-resize","se-resize":"se-resize","sw-resize":"sw-resize","ew-resize":"ew-resize","ns-resize":"ns-resize","nesw-resize":"nesw-resize","nwse-resize":"nwse-resize","zoom-in":"zoom-in","zoom-out":"zoom-out"},divideColor:({theme:s})=>s("borderColor"),divideOpacity:({theme:s})=>s("borderOpacity"),divideWidth:({theme:s})=>s("borderWidth"),dropShadow:{sm:"0 1px 1px rgb(0 0 0 / 0.05)",DEFAULT:["0 1px 2px rgb(0 0 0 / 0.1)","0 1px 1px rgb(0 0 0 / 0.06)"],md:["0 4px 3px rgb(0 0 0 / 0.07)","0 2px 2px rgb(0 0 0 / 0.06)"],lg:["0 10px 8px rgb(0 0 0 / 0.04)","0 4px 3px rgb(0 0 0 / 0.1)"],xl:["0 20px 13px rgb(0 0 0 / 0.03)","0 8px 5px rgb(0 0 0 / 0.08)"],"2xl":"0 25px 25px rgb(0 0 0 / 0.15)",none:"0 0 #0000"},fill:({theme:s})=>({none:"none",...s("colors")}),flex:{1:"1 1 0%",auto:"1 1 auto",initial:"0 1 auto",none:"none"},flexBasis:({theme:s})=>({auto:"auto",...s("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%"}),flexGrow:{0:"0",DEFAULT:"1"},flexShrink:{0:"0",DEFAULT:"1"},fontFamily:{sans:["ui-sans-serif","system-ui","-apple-system","BlinkMacSystemFont",'"Segoe UI"',"Roboto",'"Helvetica Neue"',"Arial",'"Noto Sans"',"sans-serif",'"Apple Color Emoji"','"Segoe UI Emoji"','"Segoe UI Symbol"','"Noto Color Emoji"'],serif:["ui-serif","Georgia","Cambria",'"Times New Roman"',"Times","serif"],mono:["ui-monospace","SFMono-Regular","Menlo","Monaco","Consolas",'"Liberation Mono"','"Courier New"',"monospace"]},fontSize:{xs:["0.75rem",{lineHeight:"1rem"}],sm:["0.875rem",{lineHeight:"1.25rem"}],base:["1rem",{lineHeight:"1.5rem"}],lg:["1.125rem",{lineHeight:"1.75rem"}],xl:["1.25rem",{lineHeight:"1.75rem"}],"2xl":["1.5rem",{lineHeight:"2rem"}],"3xl":["1.875rem",{lineHeight:"2.25rem"}],"4xl":["2.25rem",{lineHeight:"2.5rem"}],"5xl":["3rem",{lineHeight:"1"}],"6xl":["3.75rem",{lineHeight:"1"}],"7xl":["4.5rem",{lineHeight:"1"}],"8xl":["6rem",{lineHeight:"1"}],"9xl":["8rem",{lineHeight:"1"}]},fontWeight:{thin:"100",extralight:"200",light:"300",normal:"400",medium:"500",semibold:"600",bold:"700",extrabold:"800",black:"900"},gap:({theme:s})=>s("spacing"),gradientColorStops:({theme:s})=>s("colors"),gradientColorStopPositions:{"0%":"0%","5%":"5%","10%":"10%","15%":"15%","20%":"20%","25%":"25%","30%":"30%","35%":"35%","40%":"40%","45%":"45%","50%":"50%","55%":"55%","60%":"60%","65%":"65%","70%":"70%","75%":"75%","80%":"80%","85%":"85%","90%":"90%","95%":"95%","100%":"100%"},grayscale:{0:"0",DEFAULT:"100%"},gridAutoColumns:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridAutoRows:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridColumn:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridColumnEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13"},gridColumnStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13"},gridRow:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-full":"1 / -1"},gridRowEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7"},gridRowStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7"},gridTemplateColumns:{none:"none",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))"},gridTemplateRows:{none:"none",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))"},height:({theme:s})=>({auto:"auto",...s("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%",full:"100%",screen:"100vh",min:"min-content",max:"max-content",fit:"fit-content"}),hueRotate:{0:"0deg",15:"15deg",30:"30deg",60:"60deg",90:"90deg",180:"180deg"},inset:({theme:s})=>({auto:"auto",...s("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%"}),invert:{0:"0",DEFAULT:"100%"},keyframes:{spin:{to:{transform:"rotate(360deg)"}},ping:{"75%, 100%":{transform:"scale(2)",opacity:"0"}},pulse:{"50%":{opacity:".5"}},bounce:{"0%, 100%":{transform:"translateY(-25%)",animationTimingFunction:"cubic-bezier(0.8,0,1,1)"},"50%":{transform:"none",animationTimingFunction:"cubic-bezier(0,0,0.2,1)"}}},letterSpacing:{tighter:"-0.05em",tight:"-0.025em",normal:"0em",wide:"0.025em",wider:"0.05em",widest:"0.1em"},lineHeight:{none:"1",tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625",loose:"2",3:".75rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem"},listStyleType:{none:"none",disc:"disc",decimal:"decimal"},listStyleImage:{none:"none"},margin:({theme:s})=>({auto:"auto",...s("spacing")}),lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6"},maxHeight:({theme:s})=>({...s("spacing"),none:"none",full:"100%",screen:"100vh",min:"min-content",max:"max-content",fit:"fit-content"}),maxWidth:({theme:s,breakpoints:e})=>({none:"none",0:"0rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",prose:"65ch",...e(s("screens"))}),minHeight:{0:"0px",full:"100%",screen:"100vh",min:"min-content",max:"max-content",fit:"fit-content"},minWidth:{0:"0px",full:"100%",min:"min-content",max:"max-content",fit:"fit-content"},objectPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},opacity:{0:"0",5:"0.05",10:"0.1",20:"0.2",25:"0.25",30:"0.3",40:"0.4",50:"0.5",60:"0.6",70:"0.7",75:"0.75",80:"0.8",90:"0.9",95:"0.95",100:"1"},order:{first:"-9999",last:"9999",none:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12"},outlineColor:({theme:s})=>s("colors"),outlineOffset:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},outlineWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},padding:({theme:s})=>s("spacing"),placeholderColor:({theme:s})=>s("colors"),placeholderOpacity:({theme:s})=>s("opacity"),ringColor:({theme:s})=>({DEFAULT:s("colors.blue.500","#3b82f6"),...s("colors")}),ringOffsetColor:({theme:s})=>s("colors"),ringOffsetWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},ringOpacity:({theme:s})=>({DEFAULT:"0.5",...s("opacity")}),ringWidth:{DEFAULT:"3px",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},rotate:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",45:"45deg",90:"90deg",180:"180deg"},saturate:{0:"0",50:".5",100:"1",150:"1.5",200:"2"},scale:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5"},screens:{sm:"640px",md:"768px",lg:"1024px",xl:"1280px","2xl":"1536px"},scrollMargin:({theme:s})=>({...s("spacing")}),scrollPadding:({theme:s})=>s("spacing"),sepia:{0:"0",DEFAULT:"100%"},skew:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg"},space:({theme:s})=>({...s("spacing")}),spacing:{px:"1px",0:"0px",.5:"0.125rem",1:"0.25rem",1.5:"0.375rem",2:"0.5rem",2.5:"0.625rem",3:"0.75rem",3.5:"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",11:"2.75rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"},stroke:({theme:s})=>({none:"none",...s("colors")}),strokeWidth:{0:"0",1:"1",2:"2"},supports:{},data:{},textColor:({theme:s})=>s("colors"),textDecorationColor:({theme:s})=>s("colors"),textDecorationThickness:{auto:"auto","from-font":"from-font",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},textIndent:({theme:s})=>({...s("spacing")}),textOpacity:({theme:s})=>s("opacity"),textUnderlineOffset:{auto:"auto",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},transformOrigin:{center:"center",top:"top","top-right":"top right",right:"right","bottom-right":"bottom right",bottom:"bottom","bottom-left":"bottom left",left:"left","top-left":"top left"},transitionDelay:{0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms"},transitionDuration:{DEFAULT:"150ms",0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms"},transitionProperty:{none:"none",all:"all",DEFAULT:"color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter",colors:"color, background-color, border-color, text-decoration-color, fill, stroke",opacity:"opacity",shadow:"box-shadow",transform:"transform"},transitionTimingFunction:{DEFAULT:"cubic-bezier(0.4, 0, 0.2, 1)",linear:"linear",in:"cubic-bezier(0.4, 0, 1, 1)",out:"cubic-bezier(0, 0, 0.2, 1)","in-out":"cubic-bezier(0.4, 0, 0.2, 1)"},translate:({theme:s})=>({...s("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%"}),width:({theme:s})=>({auto:"auto",...s("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",screen:"100vw",min:"min-content",max:"max-content",fit:"fit-content"}),willChange:{auto:"auto",scroll:"scroll-position",contents:"contents",transform:"transform"},zIndex:{auto:"auto",0:"0",10:"10",20:"20",30:"30",40:"40",50:"50"}},plugins:[]};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return r}});const e=i(Ua),t=Rt;function i(n){return n&&n.__esModule?n:{default:n}}function r(n){var a;const o=((a=n==null?void 0:n.presets)!==null&&a!==void 0?a:[e.default]).slice().reverse().flatMap(u=>r(u instanceof Function?u():u)),l={respectDefaultRingColorOpacity:{theme:{ringColor:({theme:u})=>({DEFAULT:"#3b82f67f",...u("colors")})}},disableColorOpacityUtilitiesByDefault:{corePlugins:{backgroundOpacity:!1,borderOpacity:!1,divideOpacity:!1,placeholderOpacity:!1,ringOpacity:!1,textOpacity:!1}}},c=Object.keys(l).filter(u=>(0,t.flagEnabled)(n,u)).map(u=>l[u]);return[n,...c,...o]}})(Vs),function(s){Object.defineProperty(s,"__esModule",{value:!0}),Object.defineProperty(s,"default",{enumerable:!0,get:function(){return r}});const e=i(Cs),t=i(Vs);function i(n){return n&&n.__esModule?n:{default:n}}function r(...n){let[,...a]=(0,t.default)(n[0]);return(0,e.default)([...n,...a])}}(Rs);let di=Rs;var Ga=(di.__esModule?di:{default:di}).default;const Ha=$a(Ga);let fi=oi;var we=(fi.__esModule?fi:{default:fi}).default;const Va={50:"#FCE3E4",100:"#F9CDCE",200:"#F39699",300:"#ED6368",400:"#E72C32",500:"#C4161C",600:"#9C1216",700:"#770D11",800:"#4E090B",900:"#290506"},ye={onprimary:we.white,warning:we.amber,error:we.rose,info:we.cyan,success:we.lime,primary:we.sky,brand:Va},Ka={...ye,warning:ye.warning[500],"warning-darken":ye.warning[600],"warning-lighten":ye.warning[400],success:ye.success[500],"success-darken":ye.success[600],"success-lighten":ye.success[400],error:ye.error[500],"error-darken":ye.error[600],"error-lighten":ye.error[400],info:ye.info[500],"info-darken":ye.info[600],"info-lighten":ye.info[400],primary:ye.primary[500],"primary-darken":ye.primary[600],"primary-lighten":ye.primary[400],onsurface:we.slate[500],onbackground:we.slate[700],surface:we.slate[50],background:we.white},mi=Ha({prefix:"e-",corePlugins:{preflight:!1},content:["./src/**/*.{html,js,vue,ts}"],theme:{extend:{colors:Ka,maxWidth:{"1/12":"8.333333333%","2/12":"16.666666666%","3/12":"25%","4/12":"33.333333333%","5/12":"41.666666667%","6/12":"50%","7/12":"58.333333334%","8/12":"66.666666666%","9/12":"75%","10/12":"83.333333334%","11/12":"91.666666666%","12/12":"100%"}},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem","5xl":"3rem","6xl":"3.75rem","7xl":"4.5rem","8xl":"6rem","9xl":"8rem"}},plugins:[],safelist:[{pattern:/e-w-(full|auto)/,variants:["lg","md","sm","xs","xl"]},{pattern:/e-grow/,variants:["lg","md","sm","xs","xl"]},{pattern:/e-basis-(\d{1,2}\/\d{1,2}|full|auto|0)/,variants:["lg","md","sm","xs","xl"]},{pattern:/^!?e-max-w-(\d{1,2}\/\d{1,2})/,variants:["lg","md","sm","xs","xl"]},{pattern:/e-offset-(1[0-2]|[1-9])/,variants:["lg","md","sm","xs","xl"]},{pattern:/e-items-(start|center|end|baseline|stretch)/},{pattern:/e-self-(start|center|end|baseline|stretch)/},{pattern:/e-justify-(around|between|center|end|evenly|normal|start|stretch)/,variants:["lg","md","sm","xs","xl"]},{pattern:/e-content-(around|baseline|between|center|end|evenly|normal|start|stretch)/}]}),Ks=mi.theme.fontSize,Ws=mi.theme.colors,Wa=[z.dot,z.xs,z.sm,z.md,z.lg,z.xl],za=[z.xs,z.sm,z.md,z.lg,z.xl,z["2xl"]],zs=[z.xs,z.sm,z.md,z.base,z.lg,z.xl,z["2xl"],z["3xl"],z["4xl"],z["5xl"],z["6xl"],z["7xl"],z["8xl"],z["9xl"]],Ya=[ue.warning,ue.error,ue.info,ue.success,ue.primary,ue.default],ja=["play","pause","ended","loadeddata","waiting","playing","timeupdate","canplay","canplaythrough","statechanged"],qa=Ee.extend({name:"EIcon",props:{icon:{type:String,default:""},color:{type:String,default:ue.default},size:{type:String,default:z.sm}},computed:{sizes(){return zs.reduce((s,e)=>({...s,[e]:`e-text-${e}`}),{})},iconClasses(){var i,r;const s=this.sizes[this.size]||this.sizes[z.sm],e=`${((r=(i=this.icon)==null?void 0:i.split(" "))==null?void 0:r.length)>1?this.icon:`fa fa-${this.icon}`}`;return["e-inline-flex e-items-center e-justify-center e-rounded-full",this.color,e,s]}}});var Xa=function(){var e=this,t=e._self._c;return t("div",{staticClass:"e-icon"},[t("i",{class:e.iconClasses})])},Za=[],Qa=Ie(qa,Xa,Za,!1,null,null,null,null);const Ys=Qa.exports,Ja=Ee.extend({name:"ESpinner",props:{dark:{type:Boolean,default:!1},color:{type:Boolean,default:!0},animationDuration:{type:[Number,String],default:1e3},size:{type:String,default:z.base},opacity:{type:[String,Number],default:1}},data(){return{sizes:Ks,colors:Ws}},computed:{computedSize(){return this.sizes[z[this.size]]||this.size||this.sizes[z.base]},fill(){let s={primary:this.colors.brand[500],secondary:this.colors.neutral[300]};return this.dark&&!this.color&&(s={primary:this.colors.neutral[100],secondary:this.colors.neutral[100]}),!this.dark&&this.color&&(s={primary:this.colors.brand[500],secondary:this.colors.neutral[950]}),!this.dark&&!this.color&&(s={primary:this.colors.neutral[200],secondary:this.colors.neutral[200]}),s}},methods:{getNthPathStyle(s){const e=typeof this.animationDuration=="string"?Number.parseInt(this.animationDuration):this.animationDuration;return{animationDuration:`${this.animationDuration}ms`,animationDelay:`${s/10*e}ms`,fill:`${this.fill[s%2===0?"primary":"secondary"]}`}}}}),qh="";var eo=function(){var e=this,t=e._self._c;return t("svg",{staticClass:"e-spinner e-block",class:{"e-spinner--dark":e.dark,"e-spinner--grey":!e.color},style:{opacity:e.opacity},attrs:{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 1629.32 1608.86",width:e.computedSize,height:e.computedSize}},[t("path",{staticClass:"e-spinner__primary",style:e.getNthPathStyle(0),attrs:{d:"m1254.12,591.61C992.01,401.11,439.78,0,439.78,0h601.2c14.3,0,48.95,9.02,62.54,38.01,55.27,117.88,111.32,235.46,170.48,351.43,33.16,70.9-8.99,170.35-19.87,202.16"}}),t("path",{staticClass:"e-spinner__secondary",style:e.getNthPathStyle(1),attrs:{d:"m1404.65,131.67c-29.37,89.94-55.8,170.95-82.25,251.93-4.05.87-8.1,1.73-12.15,2.61-40.61-83.95-81.21-167.9-123.12-254.54h217.51Z"}}),t("path",{staticClass:"e-spinner__primary",style:e.getNthPathStyle(2),attrs:{d:"m1129.06,1093.51c100.75-307.98,312.75-956.75,312.75-956.75,0,0,180.36,558.53,184.75,572.14,4.39,13.59,6.45,49.34-16.96,71.19-95.21,88.81-189.88,178.28-282.06,270.2-57.29,53.34-164.86,43.8-198.48,43.21"}}),t("path",{staticClass:"e-spinner__secondary",style:e.getNthPathStyle(3),attrs:{d:"m1342.3,1083.06c66.6-63.43,133.22-126.86,207.93-197.98,21.51,73.55,40.3,137.81,60.64,207.37h-263.35c-1.75-3.13-3.48-6.27-5.22-9.39"}}),t("path",{staticClass:"e-spinner__primary",style:e.getNthPathStyle(4),attrs:{d:"m610.27,1137.17c324.03-.53,1006.55-1.85,1006.55-1.85,0,0-474.19,345.83-485.74,354.25-11.55,8.42-44.87,21.56-72.94,6.14-114.11-62.68-228.69-124.66-344.81-183.5-68.56-37.76-93.12-142.93-103.06-175.04"}}),t("path",{staticClass:"e-spinner__secondary",style:e.getNthPathStyle(5),attrs:{d:"m938.58,1468.29c-62.81,42.58-118.35,80.24-180.28,122.23-28.35-87.22-54.62-168.03-80.89-248.86,2.62-2.92,5.26-5.85,7.9-8.76,81.89,43.78,163.79,87.56,253.26,135.39"}}),t("path",{staticClass:"e-spinner__primary",style:e.getNthPathStyle(6),attrs:{d:"m413.07,652.86c101.35,307.77,314.99,956,314.99,956,0,0-476.23-343.04-487.83-351.39-11.58-8.36-34.44-35.93-28.52-67.4,24.07-127.96,47.3-256.13,67.09-384.8,14.54-76.9,106.84-132.96,134.28-152.42"}}),t("path",{staticClass:"e-spinner__secondary",style:e.getNthPathStyle(7),attrs:{d:"m197.48,1068.8c-62.36-47.73-115.99-88.79-176.78-135.33,75.54-54.91,146.18-106.24,216.83-157.57,3.73,2.24,7.45,4.47,11.19,6.71-16.36,91.3-32.7,182.61-51.25,286.19"}}),t("path",{staticClass:"e-spinner__primary",style:e.getNthPathStyle(8),attrs:{d:"m813.58,314.41C551.63,505.15,0,907.07,0,907.07c0,0,180.68-558.4,185.09-572.01,4.39-13.59,23.65-43.78,55.41-47.8,129.19-16.29,258.32-33.41,386.86-53.99,77.67-9.72,159.3,60.97,186.22,81.13"}}),t("path",{staticClass:"e-spinner__secondary",style:e.getNthPathStyle(9),attrs:{d:"m635.14,199.78c-91.99,12.38-183.97,24.77-288.07,38.76,25.77-73.18,48.3-137.14,73.8-209.53,76.56,55.41,147.27,106.58,217.97,157.75-1.23,4.34-2.46,8.68-3.69,13.02"}})])},to=[],io=Ie(Ja,eo,to,!1,null,"29711f67",null,null);const gi=io.exports,so=Ee.extend({props:{align:{type:String,default:void 0},alignContent:{type:String,default:void 0},justify:{type:String,default:void 0},justifyXs:{type:String,default:void 0},justifySm:{type:String,default:void 0},justifyMd:{type:String,default:void 0},justifyLg:{type:String,default:void 0},justifyXl:{type:String,default:void 0},noGutters:{type:Boolean,default:!1}},computed:{justifyClasses(){return{[`e-justify-${this.justify}`]:!!this.justify,[`xs:e-justify-${this.justifySm}`]:!!this.justifySm,[`sm:e-justify-${this.justifySm}`]:!!this.justifySm,[`md:e-justify-${this.justifyMd}`]:!!this.justifyMd,[`lg:e-justify-${this.justifyLg}`]:!!this.justifyLg,[`xl:e-justify-${this.justifyXl}`]:!!this.justifyXl}},rowClasses(){return{...this.align?{[`e-items-${this.align}`]:!0}:{},...this.alignContent?{[`e-content-${this.alignContent}`]:!0}:{},...this.noGutters?{"e-row--no-gutters":!0}:{},...this.justifyClasses}}}}),Xh="";var ro=function(){var e=this,t=e._self._c;return e._self._setupProxy,t("div",{staticClass:"e-row e-flex e-flex-wrap",class:e.rowClasses},[e._t("default")],2)},no=[],ao=Ie(so,ro,no,!1,null,null,null,null);const js=ao.exports,oo=Ee.extend({props:{alignSelf:{type:String,default:"auto"},cols:{type:[Boolean,String,Number],default:void 0},lg:{type:[Boolean,String,Number],default:void 0},md:{type:[Boolean,String,Number],default:void 0},offset:{type:[String,Number],default:void 0},offsetLg:{type:[String,Number],default:void 0},offsetMd:{type:[String,Number],default:void 0},offsetSm:{type:[String,Number],default:void 0},offsetXs:{type:[String,Number],default:void 0},offsetXl:{type:[String,Number],default:void 0},sm:{type:[Boolean,String,Number],default:void 0},xs:{type:[Boolean,String,Number],default:void 0},xl:{type:[Boolean,String,Number],default:void 0}},computed:{colClasses(){return{...this.alignSelf?{[`e-self-${this.alignSelf}`]:!0}:{},[this.autoClasses("xs:",this.xs)]:this.isSizePropAuto(this.xs),[this.autoClasses("sm:",this.sm)]:this.isSizePropAuto(this.sm),[this.autoClasses("md:",this.md)]:this.isSizePropAuto(this.md),[this.autoClasses("lg:",this.lg)]:this.isSizePropAuto(this.lg),[this.autoClasses("xl:e",this.xl)]:this.isSizePropAuto(this.xl),[this.autoClasses("",this.cols)]:this.isSizePropAuto(this.cols,!0),"xs:e-basis-full xs:!e-max-w-12/12":this.xs===12||this.xs==="12","sm:e-basis-full sm:!e-max-w-12/12":this.sm===12||this.sm==="12","md:e-basis-full md:!e-max-w-12/12":this.md===12||this.md==="12","lg:e-basis-full lg:!e-max-w-12/12":this.lg===12||this.lg==="12","xl:e-basis-full xl:!e-max-w-12/12":this.xl===12||this.xl==="12","e-basis-full e-max-w-12/12":this.cols===12||this.cols==="12",[`xs:e-basis-${this.xs}/12 xs:!e-max-w-${this.xs}/12`]:this.isSizePropertyNumeric(this.xs),[`sm:e-basis-${this.sm}/12 sm:!e-max-w-${this.sm}/12`]:this.isSizePropertyNumeric(this.sm),[`md:e-basis-${this.md}/12 md:!e-max-w-${this.md}/12`]:this.isSizePropertyNumeric(this.md),[`lg:e-basis-${this.lg}/12 lg:!e-max-w-${this.lg}/12`]:this.isSizePropertyNumeric(this.lg),[`xl:e-basis-${this.xl}/12 xl:!e-max-w-${this.xl}/12`]:this.isSizePropertyNumeric(this.xl),[`e-basis-${this.cols}/12 !e-max-w-${this.cols}/12`]:this.isSizePropertyNumeric(this.cols),[`xs:e-offset-${this.offsetXs}`]:this.offsetXs!==void 0,[`sm:e-offset-${this.offsetSm}`]:this.offsetSm!==void 0,[`md:e-offset-${this.offsetMd}`]:this.offsetMd!==void 0,[`lg:e-offset-${this.offsetLg}`]:this.offsetLg!==void 0,[`xl:e-offset-${this.offsetXl}`]:this.offsetXl!==void 0,[`e-offset-${this.offset}`]:this.offset!==void 0}}},methods:{autoClasses(s,e){return`${s}e-basis-${e==="auto"?"auto":"0"} ${s}e-grow${e==="auto"?"-0":""} ${s}e-w-${e==="auto"?"auto":"full"}`},isSizePropAuto(s,e=!1){return s==="auto"||s===0||s==="0"||e&&!s},isSizePropertyNumeric(s){const e=Number.parseInt(s);return s!=="auto"&&!isNaN(e)&&e>=1&&e<12}}}),Zh="";var lo=function(){var e=this,t=e._self._c;return t("div",{staticClass:"e-col",class:e.colClasses},[e._t("default")],2)},co=[],uo=Ie(oo,lo,co,!1,null,null,null,null);const qs=uo.exports;function ho(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Xs={exports:{}};(function(s,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,c,u){if(u=u||{},l=l.trim(),c=c.trim(),!c){if(!u.alwaysNormalize)return l;var h=o.parseURL(l);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(c);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)):c;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var m=r.exec(f.path);f.netLoc=m[1],f.path=m[2]}f.netLoc&&!f.path&&(f.path="/");var g={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(g.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)g.path=f.path,d.params||(g.params=f.params,d.query||(g.query=f.query));else{var y=f.path,v=y.substring(0,y.lastIndexOf("/")+1)+d.path;g.path=o.normalizePath(v)}return g.path===null&&(g.path=u.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(g)},parseURL:function(l){var c=i.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};s.exports=o})()})(Xs);var pi=Xs.exports;function Zs(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(s,r).enumerable})),t.push.apply(t,i)}return t}function he(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Zs(Object(t),!0).forEach(function(i){go(s,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):Zs(Object(t)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(t,i))})}return s}function fo(s,e){if(typeof s!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e||"default");if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function mo(s){var e=fo(s,"string");return typeof e=="symbol"?e:String(e)}function go(s,e,t){return e=mo(e),e in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function oe(){return oe=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(s[i]=t[i])}return s},oe.apply(this,arguments)}const W=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},po=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=yo},yo=Number.MAX_SAFE_INTEGER||9007199254740991;let p=function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.BUFFER_RESET="hlsBufferReset",s.BUFFER_CODECS="hlsBufferCodecs",s.BUFFER_CREATED="hlsBufferCreated",s.BUFFER_APPENDING="hlsBufferAppending",s.BUFFER_APPENDED="hlsBufferAppended",s.BUFFER_EOS="hlsBufferEos",s.BUFFER_FLUSHING="hlsBufferFlushing",s.BUFFER_FLUSHED="hlsBufferFlushed",s.MANIFEST_LOADING="hlsManifestLoading",s.MANIFEST_LOADED="hlsManifestLoaded",s.MANIFEST_PARSED="hlsManifestParsed",s.LEVEL_SWITCHING="hlsLevelSwitching",s.LEVEL_SWITCHED="hlsLevelSwitched",s.LEVEL_LOADING="hlsLevelLoading",s.LEVEL_LOADED="hlsLevelLoaded",s.LEVEL_UPDATED="hlsLevelUpdated",s.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",s.LEVELS_UPDATED="hlsLevelsUpdated",s.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",s.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",s.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",s.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",s.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",s.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",s.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",s.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",s.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",s.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",s.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",s.CUES_PARSED="hlsCuesParsed",s.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",s.INIT_PTS_FOUND="hlsInitPtsFound",s.FRAG_LOADING="hlsFragLoading",s.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",s.FRAG_LOADED="hlsFragLoaded",s.FRAG_DECRYPTED="hlsFragDecrypted",s.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",s.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",s.FRAG_PARSING_METADATA="hlsFragParsingMetadata",s.FRAG_PARSED="hlsFragParsed",s.FRAG_BUFFERED="hlsFragBuffered",s.FRAG_CHANGED="hlsFragChanged",s.FPS_DROP="hlsFpsDrop",s.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",s.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",s.ERROR="hlsError",s.DESTROYING="hlsDestroying",s.KEY_LOADING="hlsKeyLoading",s.KEY_LOADED="hlsKeyLoaded",s.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",s.BACK_BUFFER_REACHED="hlsBackBufferReached",s.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",s}({}),q=function(s){return s.NETWORK_ERROR="networkError",s.MEDIA_ERROR="mediaError",s.KEY_SYSTEM_ERROR="keySystemError",s.MUX_ERROR="muxError",s.OTHER_ERROR="otherError",s}({}),_=function(s){return s.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",s.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",s.KEY_SYSTEM_NO_SESSION="keySystemNoSession",s.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",s.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",s.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",s.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",s.MANIFEST_LOAD_ERROR="manifestLoadError",s.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",s.MANIFEST_PARSING_ERROR="manifestParsingError",s.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",s.LEVEL_EMPTY_ERROR="levelEmptyError",s.LEVEL_LOAD_ERROR="levelLoadError",s.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",s.LEVEL_PARSING_ERROR="levelParsingError",s.LEVEL_SWITCH_ERROR="levelSwitchError",s.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",s.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",s.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",s.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",s.FRAG_LOAD_ERROR="fragLoadError",s.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",s.FRAG_DECRYPT_ERROR="fragDecryptError",s.FRAG_PARSING_ERROR="fragParsingError",s.FRAG_GAP="fragGap",s.REMUX_ALLOC_ERROR="remuxAllocError",s.KEY_LOAD_ERROR="keyLoadError",s.KEY_LOAD_TIMEOUT="keyLoadTimeOut",s.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",s.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",s.BUFFER_APPEND_ERROR="bufferAppendError",s.BUFFER_APPENDING_ERROR="bufferAppendingError",s.BUFFER_STALLED_ERROR="bufferStalledError",s.BUFFER_FULL_ERROR="bufferFullError",s.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",s.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.UNKNOWN="unknown",s}({});const Xe=function(){},yi={trace:Xe,debug:Xe,log:Xe,warn:Xe,info:Xe,error:Xe};let pt=yi;function vo(s){const e=self.console[s];return e?e.bind(self.console,`[${s}] >`):Xe}function xo(s,...e){e.forEach(function(t){pt[t]=s[t]?s[t].bind(s):vo(t)})}function To(s,e){if(typeof console=="object"&&s===!0||typeof s=="object"){xo(s,"debug","log","info","warn","error");try{pt.log(`Debug logs enabled for "${e}" in hls.js version 1.5.6`)}catch{pt=yi}}else pt=yi}const S=pt,Eo=/^(\d+)x(\d+)$/,Qs=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ae{constructor(e){typeof e=="string"&&(e=ae.parseAttrList(e)),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 i=new Uint8Array(t.length/2);for(let r=0;r<t.length/2;r++)i[r]=parseInt(t.slice(r*2,r*2+2),16);return i}else 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 i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}bool(e){return this[e]==="YES"}decimalResolution(e){const t=Eo.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const i={},r='"';for(Qs.lastIndex=0;(t=Qs.exec(e))!==null;){let n=t[2];n.indexOf(r)===0&&n.lastIndexOf(r)===n.length-1&&(n=n.slice(1,-1));const a=t[1].trim();i[a]=n}return i}}function So(s){return s!=="ID"&&s!=="CLASS"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function bo(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"}class Js{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const i=t.attr;for(const r in i)if(Object.prototype.hasOwnProperty.call(e,r)&&e[r]!==i[r]){S.warn(`DATERANGE tag attribute: "${r}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=r;break}e=oe(new ae({}),i,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const i=new Date(this.attr["END-DATE"]);W(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return e!==null?new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(W(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 isValid(){return!!this.id&&!this._badValueForSameId&&W(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class Dt{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 te={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class er{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[te.AUDIO]:null,[te.VIDEO]:null,[te.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,t){const i=e.split("@",2);let r;i.length===1?r=(t==null?void 0:t.byteRangeEndOffset)||0:r=parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=pi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class vi extends er{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=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.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new Dt,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 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 i=Object.keys(this.levelkeys);if(i.length===1)return this._decryptdata=this.levelkeys[i[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!W(this.programDateTime))return null;const e=W(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){const t=Object.keys(this.levelkeys),i=t.length;if(i>1||i===1&&this.levelkeys[t[0]].encrypted)return!0}return!1}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,i,r,n,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,n)}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[te.AUDIO]=null,e[te.VIDEO]=null,e[te.AUDIOVIDEO]=null}}class Ao extends er{constructor(e,t,i,r,n){super(i),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.stats=new Dt,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;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)}}const Lo=10;class Ro{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.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 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.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,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?W(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Lo}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(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end: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 lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function xi(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function Co(s){const e=Ti(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Do(s){const e=function(i,r,n){const a=i[r];i[r]=i[n],i[n]=a};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7)}function _o(s){const e=s.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),r=i[i.length-1].split(",");if(r.length===2){const n=r[0]==="base64",a=r[1];n?(i.splice(-1,1),t=xi(a)):t=Co(a)}}return t}function Ti(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}const et=typeof self!="undefined"?self:void 0;var ne={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},xe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function tr(s){switch(s){case xe.FAIRPLAY:return ne.FAIRPLAY;case xe.PLAYREADY:return ne.PLAYREADY;case xe.WIDEVINE:return ne.WIDEVINE;case xe.CLEARKEY:return ne.CLEARKEY}}var ir={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Io(s){if(s===ir.WIDEVINE)return ne.WIDEVINE}function sr(s){switch(s){case ne.FAIRPLAY:return xe.FAIRPLAY;case ne.PLAYREADY:return xe.PLAYREADY;case ne.WIDEVINE:return xe.WIDEVINE;case ne.CLEARKEY:return xe.CLEARKEY}}function Ei(s){const{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[ne.FAIRPLAY,ne.WIDEVINE,ne.PLAYREADY,ne.CLEARKEY].filter(r=>!!e[r]):[];return!i[ne.WIDEVINE]&&t&&i.push(ne.WIDEVINE),i}const rr=function(s){return et!=null&&(s=et.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function wo(s,e,t,i){let r;switch(s){case ne.FAIRPLAY:r=["cenc","sinf"];break;case ne.WIDEVINE:case ne.PLAYREADY:r=["cenc"];break;case ne.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return ko(r,e,t,i)}function ko(s,e,t,i){return[{initDataTypes:s,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs="${n}"`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs="${n}"`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function Ze(s,e,t){return Uint8Array.prototype.slice?s.slice(e,t):new Uint8Array(Array.prototype.slice.call(s,e,t))}const Si=(s,e)=>e+10<=s.length&&s[e]===73&&s[e+1]===68&&s[e+2]===51&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128,nr=(s,e)=>e+10<=s.length&&s[e]===51&&s[e+1]===68&&s[e+2]===73&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128,yt=(s,e)=>{const t=e;let i=0;for(;Si(s,e);){i+=10;const r=_t(s,e+6);i+=r,nr(s,e+10)&&(i+=10),e+=i}if(i>0)return s.subarray(t,t+i)},_t=(s,e)=>{let t=0;return t=(s[e]&127)<<21,t|=(s[e+1]&127)<<14,t|=(s[e+2]&127)<<7,t|=s[e+3]&127,t},Po=(s,e)=>Si(s,e)&&_t(s,e+6)+10<=s.length-e,bi=s=>{const e=or(s);for(let t=0;t<e.length;t++){const i=e[t];if(ar(i))return $o(i)}},ar=s=>s&&s.key==="PRIV"&&s.info==="com.apple.streaming.transportStreamTimestamp",Oo=s=>{const e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=_t(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}},or=s=>{let e=0;const t=[];for(;Si(s,e);){const i=_t(s,e+6);e+=10;const r=e+i;for(;e+8<r;){const n=Oo(s.subarray(e)),a=Fo(n);a&&t.push(a),e+=n.size+10}nr(s,e)&&(e+=10)}return t},Fo=s=>s.type==="PRIV"?Mo(s):s.type[0]==="W"?Bo(s):No(s),Mo=s=>{if(s.size<2)return;const e=ke(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}},No=s=>{if(s.size<2)return;if(s.type==="TXXX"){let t=1;const i=ke(s.data.subarray(t),!0);t+=i.length+1;const r=ke(s.data.subarray(t));return{key:s.type,info:i,data:r}}const e=ke(s.data.subarray(1));return{key:s.type,data:e}},Bo=s=>{if(s.type==="WXXX"){if(s.size<2)return;let t=1;const i=ke(s.data.subarray(t),!0);t+=i.length+1;const r=ke(s.data.subarray(t));return{key:s.type,info:i,data:r}}const e=ke(s.data);return{key:s.type,data:e}},$o=s=>{if(s.data.byteLength===8){const e=new Uint8Array(s.data),t=e[3]&1;let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}},ke=(s,e=!1)=>{const t=Uo();if(t){const c=t.decode(s);if(e){const u=c.indexOf("\0");return u!==-1?c.substring(0,u):c}return c.replace(/\0/g,"")}const i=s.length;let r,n,a,o="",l=0;for(;l<i;){if(r=s[l++],r===0&&e)return o;if(r===0||r===3)continue;switch(r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(r);break;case 12:case 13:n=s[l++],o+=String.fromCharCode((r&31)<<6|n&63);break;case 14:n=s[l++],a=s[l++],o+=String.fromCharCode((r&15)<<12|(n&63)<<6|(a&63)<<0);break}}return o};let Ai;function Uo(){if(!navigator.userAgent.includes("PlayStation 4"))return!Ai&&typeof self.TextDecoder!="undefined"&&(Ai=new self.TextDecoder("utf-8")),Ai}const Pe={hexDump:function(s){let e="";for(let t=0;t<s.length;t++){let i=s[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}},It=Math.pow(2,32)-1,Go=[].push,lr={video:1,audio:2,id3:3,text:4};function ce(s){return String.fromCharCode.apply(null,s)}function cr(s,e){const t=s[e]<<8|s[e+1];return t<0?65536+t:t}function Y(s,e){const t=hr(s,e);return t<0?4294967296+t:t}function ur(s,e){let t=Y(s,e);return t*=Math.pow(2,32),t+=Y(s,e+4),t}function hr(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function Li(s,e,t){s[e]=t>>24,s[e+1]=t>>16&255,s[e+2]=t>>8&255,s[e+3]=t&255}function Ho(s){const e=s.byteLength;for(let t=0;t<e;){const i=Y(s,t);if(i>8&&s[t+4]===109&&s[t+5]===111&&s[t+6]===111&&s[t+7]===102)return!0;t=i>1?t+i:e}return!1}function X(s,e){const t=[];if(!e.length)return t;const i=s.byteLength;for(let r=0;r<i;){const n=Y(s,r),a=ce(s.subarray(r+4,r+8)),o=n>1?r+n:i;if(a===e[0])if(e.length===1)t.push(s.subarray(r+8,o));else{const l=X(s.subarray(r+8,o),e.slice(1));l.length&&Go.apply(t,l)}r=o}return t}function Vo(s){const e=[],t=s[0];let i=8;const r=Y(s,i);i+=4;let n=0,a=0;t===0?(n=Y(s,i),a=Y(s,i+4),i+=8):(n=ur(s,i),a=ur(s,i+8),i+=16),i+=2;let o=s.length+a;const l=cr(s,i);i+=2;for(let c=0;c<l;c++){let u=i;const h=Y(s,u);u+=4;const d=h&2147483647;if((h&2147483648)>>>31===1)return S.warn("SIDX has hierarchical references (not supported)"),null;const m=Y(s,u);u+=4,e.push({referenceSize:d,subsegmentDuration:m,info:{duration:m/r,start:o,end:o+d-1}}),o+=d,u+=4,i=u}return{earliestPresentationTime:n,timescale:r,version:t,referencesCount:l,references:e}}function dr(s){const e=[],t=X(s,["moov","trak"]);for(let r=0;r<t.length;r++){const n=t[r],a=X(n,["tkhd"])[0];if(a){let o=a[0];const l=Y(a,o===0?12:20),c=X(n,["mdia","mdhd"])[0];if(c){o=c[0];const u=Y(c,o===0?12:20),h=X(n,["mdia","hdlr"])[0];if(h){const d=ce(h.subarray(8,12)),f={soun:te.AUDIO,vide:te.VIDEO}[d];if(f){const m=X(n,["mdia","minf","stbl","stsd"])[0],g=Ko(m);e[l]={timescale:u,type:f},e[f]=he({timescale:u,id:l},g)}}}}}return X(s,["moov","mvex","trex"]).forEach(r=>{const n=Y(r,4),a=e[n];a&&(a.default={duration:Y(r,12),flags:Y(r,20)})}),e}function Ko(s){const e=s.subarray(8),t=e.subarray(8+78),i=ce(e.subarray(4,8));let r=i;const n=i==="enca"||i==="encv";if(n){const o=X(e,[i])[0].subarray(i==="enca"?28:78);X(o,["sinf"]).forEach(c=>{const u=X(c,["schm"])[0];if(u){const h=ce(u.subarray(4,8));if(h==="cbcs"||h==="cenc"){const d=X(c,["frma"])[0];d&&(r=ce(d))}}})}switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const a=X(t,["avcC"])[0];r+="."+wt(a[1])+wt(a[2])+wt(a[3]);break}case"mp4a":{const a=X(e,[i])[0],o=X(a.subarray(28),["esds"])[0];if(o&&o.length>12){let l=4;if(o[l++]!==3)break;l=Ri(o,l),l+=2;const c=o[l++];if(c&128&&(l+=2),c&64&&(l+=o[l++]),o[l++]!==4)break;l=Ri(o,l);const u=o[l++];if(u===64)r+="."+wt(u);else break;if(l+=12,o[l++]!==5)break;l=Ri(o,l);const h=o[l++];let d=(h&248)>>3;d===31&&(d+=1+((h&7)<<3)+((o[l]&224)>>5)),r+="."+d}break}case"hvc1":case"hev1":{const a=X(t,["hvcC"])[0],o=a[1],l=["","A","B","C"][o>>6],c=o&31,u=Y(a,2),h=(o&32)>>5?"H":"L",d=a[12],f=a.subarray(6,12);r+="."+l+c,r+="."+u.toString(16).toUpperCase(),r+="."+h+d;let m="";for(let g=f.length;g--;){const y=f[g];(y||m)&&(m="."+y.toString(16).toUpperCase()+m)}r+=m;break}case"dvh1":case"dvhe":{const a=X(t,["dvcC"])[0],o=a[2]>>1&127,l=a[2]<<5&32|a[3]>>3&31;r+="."+Oe(o)+"."+Oe(l);break}case"vp09":{const a=X(t,["vpcC"])[0],o=a[4],l=a[5],c=a[6]>>4&15;r+="."+Oe(o)+"."+Oe(l)+"."+Oe(c);break}case"av01":{const a=X(t,["av1C"])[0],o=a[1]>>>5,l=a[1]&31,c=a[2]>>>7?"H":"M",u=(a[2]&64)>>6,h=(a[2]&32)>>5,d=o===2&&u?h?12:10:u?10:8,f=(a[2]&16)>>4,m=(a[2]&8)>>3,g=(a[2]&4)>>2,y=a[2]&3,v=1,T=1,x=1,L=0;r+="."+o+"."+Oe(l)+c+"."+Oe(d)+"."+f+"."+m+g+y+"."+Oe(v)+"."+Oe(T)+"."+Oe(x)+"."+L;break}}return{codec:r,encrypted:n}}function Ri(s,e){const t=e+5;for(;s[e++]&128&&e<t;);return e}function wt(s){return("0"+s.toString(16).toUpperCase()).slice(-2)}function Oe(s){return(s<10?"0":"")+s}function Wo(s,e){if(!s||!e)return s;const t=e.keyId;return t&&e.isCommonEncryption&&X(s,["moov","trak"]).forEach(r=>{const a=X(r,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=X(a,["enca"]);const l=o.length>0;l||(o=X(a,["encv"])),o.forEach(c=>{const u=l?c.subarray(28):c.subarray(78);X(u,["sinf"]).forEach(d=>{const f=fr(d);if(f){const m=f.subarray(8,24);m.some(g=>g!==0)||(S.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${Pe.hexDump(m)} -> ${Pe.hexDump(t)}`),f.set(t,8))}})})}),s}function fr(s){const e=X(s,["schm"])[0];if(e){const t=ce(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return X(s,["schi","tenc"])[0]}return S.error("[eme] missing 'schm' box"),null}function zo(s,e){return X(e,["moof","traf"]).reduce((t,i)=>{const r=X(i,["tfdt"])[0],n=r[0],a=X(i,["tfhd"]).reduce((o,l)=>{const c=Y(l,4),u=s[c];if(u){let h=Y(r,4);if(n===1){if(h===It)return S.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;h*=It+1,h+=Y(r,8)}const d=u.timescale||9e4,f=h/d;if(W(f)&&(o===null||f<o))return f}return o},null);return a!==null&&W(a)&&(t===null||a<t)?a:t},null)}function Yo(s,e){let t=0,i=0,r=0;const n=X(s,["moof","traf"]);for(let a=0;a<n.length;a++){const o=n[a],l=X(o,["tfhd"])[0],c=Y(l,4),u=e[c];if(!u)continue;const h=u.default,d=Y(l,0)|(h==null?void 0:h.flags);let f=h==null?void 0:h.duration;d&8&&(d&2?f=Y(l,12):f=Y(l,8));const m=u.timescale||9e4,g=X(o,["trun"]);for(let y=0;y<g.length;y++){if(t=jo(g[y]),!t&&f){const v=Y(g[y],4);t=f*v}u.type===te.VIDEO?i+=t/m:u.type===te.AUDIO&&(r+=t/m)}}if(i===0&&r===0){let a=1/0,o=0,l=0;const c=X(s,["sidx"]);for(let u=0;u<c.length;u++){const h=Vo(c[u]);if(h!=null&&h.references){a=Math.min(a,h.earliestPresentationTime/h.timescale);const d=h.references.reduce((f,m)=>f+m.info.duration||0,0);o=Math.max(o,d+h.earliestPresentationTime/h.timescale),l=o-a}}if(l&&W(l))return l}return i||r}function jo(s){const e=Y(s,0);let t=8;e&1&&(t+=4),e&4&&(t+=4);let i=0;const r=Y(s,4);for(let n=0;n<r;n++){if(e&256){const a=Y(s,t);i+=a,t+=4}e&512&&(t+=4),e&1024&&(t+=4),e&2048&&(t+=4)}return i}function qo(s,e,t){X(e,["moof","traf"]).forEach(i=>{X(i,["tfhd"]).forEach(r=>{const n=Y(r,4),a=s[n];if(!a)return;const o=a.timescale||9e4;X(i,["tfdt"]).forEach(l=>{const c=l[0],u=t*o;if(u){let h=Y(l,4);if(c===0)h-=u,h=Math.max(h,0),Li(l,4,h);else{h*=Math.pow(2,32),h+=Y(l,8),h-=u,h=Math.max(h,0);const d=Math.floor(h/(It+1)),f=Math.floor(h%(It+1));Li(l,4,d),Li(l,8,f)}}})})})}function Xo(s){const e={valid:null,remainder:null},t=X(s,["moof"]);if(t.length<2)return e.remainder=s,e;const i=t[t.length-1];return e.valid=Ze(s,0,i.byteOffset-8),e.remainder=Ze(s,i.byteOffset-8),e}function be(s,e){const t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function mr(s,e){const t=[],i=e.samples,r=e.timescale,n=e.id;let a=!1;return X(i,["moof"]).map(l=>{const c=l.byteOffset-8;X(l,["traf"]).map(h=>{const d=X(h,["tfdt"]).map(f=>{const m=f[0];let g=Y(f,4);return m===1&&(g*=Math.pow(2,32),g+=Y(f,8)),g/r})[0];return d!==void 0&&(s=d),X(h,["tfhd"]).map(f=>{const m=Y(f,4),g=Y(f,0)&16777215,y=(g&1)!==0,v=(g&2)!==0,T=(g&8)!==0;let x=0;const L=(g&16)!==0;let E=0;const k=(g&32)!==0;let R=8;m===n&&(y&&(R+=8),v&&(R+=4),T&&(x=Y(f,R),R+=4),L&&(E=Y(f,R),R+=4),k&&(R+=4),e.type==="video"&&(a=Zo(e.codec)),X(h,["trun"]).map(B=>{const C=B[0],b=Y(B,0)&16777215,D=(b&1)!==0;let P=0;const w=(b&4)!==0,$=(b&256)!==0;let O=0;const U=(b&512)!==0;let F=0;const V=(b&1024)!==0,H=(b&2048)!==0;let N=0;const J=Y(B,4);let Q=8;D&&(P=Y(B,Q),Q+=4),w&&(Q+=4);let ie=P+c;for(let le=0;le<J;le++){if($?(O=Y(B,Q),Q+=4):O=x,U?(F=Y(B,Q),Q+=4):F=E,V&&(Q+=4),H&&(C===0?N=Y(B,Q):N=hr(B,Q),Q+=4),e.type===te.VIDEO){let me=0;for(;me<F;){const pe=Y(i,ie);if(ie+=4,Qo(a,i[ie])){const Re=i.subarray(ie,ie+pe);gr(Re,a?2:1,s+N/r,t)}ie+=pe,me+=pe+4}}s+=O/r}}))})})}),t}function Zo(s){if(!s)return!1;const e=s.indexOf("."),t=e<0?s:s.substring(0,e);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function Qo(s,e){if(s){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function gr(s,e,t,i){const r=pr(s);let n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(l===255);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(l===255);const c=r.length-n;let u=n;if(o<c)n+=o;else if(o>c){S.error(`Malformed SEI payload. ${o} is too small, only ${c} bytes left to parse.`);break}if(a===4){if(r[u++]===181){const d=cr(r,u);if(u+=2,d===49){const f=Y(r,u);if(u+=4,f===1195456820){const m=r[u++];if(m===3){const g=r[u++],y=31&g,v=64&g,T=v?2+y*3:0,x=new Uint8Array(T);if(v){x[0]=g;for(let L=1;L<T;L++)x[L]=r[u++]}i.push({type:m,payloadType:a,pts:t,bytes:x})}}}}}else if(a===5&&o>16){const h=[];for(let m=0;m<16;m++){const g=r[u++].toString(16);h.push(g.length==1?"0"+g:g),(m===3||m===5||m===7||m===9)&&h.push("-")}const d=o-16,f=new Uint8Array(d);for(let m=0;m<d;m++)f[m]=r[u++];i.push({payloadType:a,pts:t,uuid:h.join(""),userData:ke(f),userDataBytes:f})}}}function pr(s){const e=s.byteLength,t=[];let i=1;for(;i<e-2;)s[i]===0&&s[i+1]===0&&s[i+2]===3?(t.push(i+2),i+=2):i++;if(t.length===0)return s;const r=e-t.length,n=new Uint8Array(r);let a=0;for(i=0;i<r;a++,i++)a===t[0]&&(a++,t.shift()),n[i]=s[a];return n}function Jo(s){const e=s[0];let t="",i="",r=0,n=0,a=0,o=0,l=0,c=0;if(e===0){for(;ce(s.subarray(c,c+1))!=="\0";)t+=ce(s.subarray(c,c+1)),c+=1;for(t+=ce(s.subarray(c,c+1)),c+=1;ce(s.subarray(c,c+1))!=="\0";)i+=ce(s.subarray(c,c+1)),c+=1;i+=ce(s.subarray(c,c+1)),c+=1,r=Y(s,12),n=Y(s,16),o=Y(s,20),l=Y(s,24),c=28}else if(e===1){c+=4,r=Y(s,c),c+=4;const h=Y(s,c);c+=4;const d=Y(s,c);for(c+=4,a=2**32*h+d,po(a)||(a=Number.MAX_SAFE_INTEGER,S.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Y(s,c),c+=4,l=Y(s,c),c+=4;ce(s.subarray(c,c+1))!=="\0";)t+=ce(s.subarray(c,c+1)),c+=1;for(t+=ce(s.subarray(c,c+1)),c+=1;ce(s.subarray(c,c+1))!=="\0";)i+=ce(s.subarray(c,c+1)),c+=1;i+=ce(s.subarray(c,c+1)),c+=1}const u=s.subarray(c,s.byteLength);return{schemeIdUri:t,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:u}}function el(s,...e){const t=e.length;let i=8,r=t;for(;r--;)i+=e[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=i&255,n.set(s,4),r=0,i=8;r<t;r++)n.set(e[r],i),i+=e[r].byteLength;return n}function tl(s,e,t){if(s.byteLength!==16)throw new RangeError("Invalid system id");let i,r;if(e){i=1,r=new Uint8Array(e.length*16);for(let o=0;o<e.length;o++){const l=e[o];if(l.byteLength!==16)throw new RangeError("Invalid key");r.set(l,o*16)}}else i=0,r=new Uint8Array;let n;i>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&&t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),el([112,115,115,104],new Uint8Array([i,0,0,0]),s,n,r,a,t||new Uint8Array)}function il(s){if(!(s instanceof ArrayBuffer)||s.byteLength<32)return null;const e={version:0,systemId:"",kids:null,data:null},t=new DataView(s),i=t.getUint32(0);if(s.byteLength!==i&&i>44||t.getUint32(4)!==1886614376||(e.version=t.getUint32(8)>>>24,e.version>1))return null;e.systemId=Pe.hexDump(new Uint8Array(s,12,16));const n=t.getUint32(28);if(e.version===0){if(i-32<n)return null;e.data=new Uint8Array(s,32,n)}else if(e.version===1){e.kids=[];for(let a=0;a<n;a++)e.kids.push(new Uint8Array(s,32+a*16,16))}return e}let kt={};class vt{static clearKeyUriToKeyIdMap(){kt={}}constructor(e,t,i,r=[1],n=null){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=i,this.keyFormatVersions=r,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&e!=="AES-128"}isSupported(){if(this.method){if(this.method==="AES-128"||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case xe.FAIRPLAY:case xe.WIDEVINE:case xe.PLAYREADY:case xe.CLEARKEY:return["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(this.method==="AES-128"&&this.uri&&!this.iv){typeof e!="number"&&(this.method==="AES-128"&&!this.iv&&S.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const i=sl(e);return new vt(this.method,this.uri,"identity",this.keyFormatVersions,i)}const t=_o(this.uri);if(t)switch(this.keyFormat){case xe.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case xe.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=tl(i,null,t);const r=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),n=String.fromCharCode.apply(null,Array.from(r)),a=n.substring(n.indexOf("<"),n.length),c=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("KID")[0];if(c){const u=c.childNodes[0]?c.childNodes[0].nodeValue:c.getAttribute("VALUE");if(u){const h=xi(u).subarray(0,16);Do(h),this.keyId=h}}break}default:{let i=t.subarray(0,16);if(i.length!==16){const r=new Uint8Array(16);r.set(i,16-i.length),i=r}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=kt[this.uri];if(!i){const r=Object.keys(kt).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,r),kt[this.uri]=i}this.keyId=i}return this}}function sl(s){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}const yr=/\{\$([a-zA-Z0-9-_]+)\}/g;function vr(s){return yr.test(s)}function Te(s,e,t){if(s.variableList!==null||s.hasVariableRefs)for(let i=t.length;i--;){const r=t[i],n=e[r];n&&(e[r]=Ci(s,n))}}function Ci(s,e){if(s.variableList!==null||s.hasVariableRefs){const t=s.variableList;return e.replace(yr,i=>{const r=i.substring(2,i.length-1),n=t==null?void 0:t[r];return n===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),i):n})}return e}function xr(s,e,t){let i=s.variableList;i||(s.variableList=i={});let r,n;if("QUERYPARAM"in e){r=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(r))n=a.get(r);else throw new Error(`"${r}" does not match any query parameter in URI: "${t}"`)}catch(a){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else r=e.NAME,n=e.VALUE;r in i?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):i[r]=n||""}function rl(s,e,t){const i=e.IMPORT;if(t&&i in t){let r=s.variableList;r||(s.variableList=r={}),r[i]=t[i]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function tt(s=!0){return typeof self=="undefined"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const Pt={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,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 nl(s,e){const t=Pt[e];return!!t&&!!t[s.slice(0,4)]}function Di(s,e,t=!0){return!s.split(",").some(i=>!Tr(i,e,t))}function Tr(s,e,t=!0){var i;const r=tt(t);return(i=r==null?void 0:r.isTypeSupported(xt(s,e)))!=null?i:!1}function xt(s,e){return`${e}/mp4;codecs="${s}"`}function Er(s){if(s){const e=s.substring(0,4);return Pt.video[e]}return 2}function Ot(s){return s.split(",").reduce((e,t)=>{const i=Pt.video[t];return i?(i*2+e)/(e?3:2):(Pt.audio[t]+e)/(e?2:1)},0)}const _i={};function al(s,e=!0){if(_i[s])return _i[s];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[s];for(let i=0;i<t.length;i++)if(Tr(t[i],"audio",e))return _i[s]=t[i],t[i];return s}const ol=/flac|opus/i;function Ft(s,e=!0){return s.replace(ol,t=>al(t.toLowerCase(),e))}function Sr(s,e){return s&&s!=="mp4a"?s:e}function ll(s){const e=s.split(".");if(e.length>2){let t=e.shift()+".";return t+=parseInt(e.shift()).toString(16),t+=("000"+parseInt(e.shift()).toString(16)).slice(-4),t}return s}const br=/#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,Ar=/#EXT-X-MEDIA:(.*)/g,cl=/^#EXT(?:INF|-X-TARGETDURATION):/m,Lr=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),ul=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(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 Fe{static findGroup(e,t){for(let i=0;i<e.length;i++){const r=e[i];if(r.id===t)return r}}static resolve(e,t){return pi.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return cl.test(e)}static parseMasterPlaylist(e,t){const i=vr(e),r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];br.lastIndex=0;let a;for(;(a=br.exec(e))!=null;)if(a[1]){var o;const c=new ae(a[1]);Te(r,c,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const u=Ci(r,a[2]),h={attrs:c,bitrate:c.decimalInteger("BANDWIDTH")||c.decimalInteger("AVERAGE-BANDWIDTH"),name:c.NAME,url:Fe.resolve(u,t)},d=c.decimalResolution("RESOLUTION");d&&(h.width=d.width,h.height=d.height),hl(c.CODECS,h),(o=h.unknownCodecs)!=null&&o.length||n.push(h),r.levels.push(h)}else if(a[3]){const c=a[3],u=a[4];switch(c){case"SESSION-DATA":{const h=new ae(u);Te(r,h,["DATA-ID","LANGUAGE","VALUE","URI"]);const d=h["DATA-ID"];d&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[d]=h);break}case"SESSION-KEY":{const h=Rr(u,t,r);h.encrypted&&h.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(h)):S.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const h=new ae(u);Te(r,h,["NAME","VALUE","QUERYPARAM"]),xr(r,h,t)}break}case"CONTENT-STEERING":{const h=new ae(u);Te(r,h,["SERVER-URI","PATHWAY-ID"]),r.contentSteering={uri:Fe.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{r.startTimeOffset=Cr(u);break}}}const l=n.length>0&&n.length<r.levels.length;return r.levels=l?n:r.levels,r.levels.length===0&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,i){let r;const n={},a=i.levels,o={AUDIO:a.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:a.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Ar.lastIndex=0;(r=Ar.exec(e))!==null;){const c=new ae(r[1]),u=c.TYPE;if(u){const h=o[u],d=n[u]||[];n[u]=d,Te(i,c,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const f=c.LANGUAGE,m=c["ASSOC-LANGUAGE"],g=c.CHANNELS,y=c.CHARACTERISTICS,v=c["INSTREAM-ID"],T={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",name:c.NAME||f||"",type:u,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:f,url:c.URI?Fe.resolve(c.URI,t):""};if(m&&(T.assocLang=m),g&&(T.channels=g),y&&(T.characteristics=y),v&&(T.instreamId=v),h!=null&&h.length){const x=Fe.findGroup(h,T.groupId)||h[0];Dr(T,x,"audioCodec"),Dr(T,x,"textCodec")}d.push(T)}}return n}static parseLevelPlaylist(e,t,i,r,n,a){const o=new Ro(t),l=o.fragments;let c=null,u=0,h=0,d=0,f=0,m=null,g=new vi(r,t),y,v,T,x=-1,L=!1,E=null;for(Lr.lastIndex=0,o.m3u8=e,o.hasVariableRefs=vr(e);(y=Lr.exec(e))!==null;){L&&(L=!1,g=new vi(r,t),g.start=d,g.sn=u,g.cc=f,g.level=i,c&&(g.initSegment=c,g.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null,E&&(g.setByteRange(E),E=null)));const C=y[1];if(C){g.duration=parseFloat(C);const b=(" "+y[2]).slice(1);g.title=b||null,g.tagList.push(b?["INF",C,b]:["INF",C])}else if(y[3]){if(W(g.duration)){g.start=d,T&&wr(g,T,o),g.sn=u,g.level=i,g.cc=f,l.push(g);const b=(" "+y[3]).slice(1);g.relurl=Ci(o,b),_r(g,m),m=g,d+=g.duration,u++,h=0,L=!0}}else if(y[4]){const b=(" "+y[4]).slice(1);m?g.setByteRange(b,m):g.setByteRange(b)}else if(y[5])g.rawProgramDateTime=(" "+y[5]).slice(1),g.tagList.push(["PROGRAM-DATE-TIME",g.rawProgramDateTime]),x===-1&&(x=l.length);else{if(y=y[0].match(ul),!y){S.warn("No matches on slow regex match for level playlist!");continue}for(v=1;v<y.length&&typeof y[v]=="undefined";v++);const b=(" "+y[v]).slice(1),D=(" "+y[v+1]).slice(1),P=y[v+2]?(" "+y[v+2]).slice(1):"";switch(b){case"PLAYLIST-TYPE":o.type=D.toUpperCase();break;case"MEDIA-SEQUENCE":u=o.startSN=parseInt(D);break;case"SKIP":{const w=new ae(D);Te(o,w,["RECENTLY-REMOVED-DATERANGES"]);const $=w.decimalInteger("SKIPPED-SEGMENTS");if(W($)){o.skippedSegments=$;for(let U=$;U--;)l.unshift(null);u+=$}const O=w.enumeratedString("RECENTLY-REMOVED-DATERANGES");O&&(o.recentlyRemovedDateranges=O.split(" "));break}case"TARGETDURATION":o.targetduration=Math.max(parseInt(D),1);break;case"VERSION":o.version=parseInt(D);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":o.live=!1;break;case"#":(D||P)&&g.tagList.push(P?[D,P]:[D]);break;case"DISCONTINUITY":f++,g.tagList.push(["DIS"]);break;case"GAP":g.gap=!0,g.tagList.push([b]);break;case"BITRATE":g.tagList.push([b,D]);break;case"DATERANGE":{const w=new ae(D);Te(o,w,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),Te(o,w,w.clientAttrs);const $=new Js(w,o.dateRanges[w.ID]);$.isValid||o.skippedSegments?o.dateRanges[$.id]=$:S.warn(`Ignoring invalid DATERANGE tag: "${D}"`),g.tagList.push(["EXT-X-DATERANGE",D]);break}case"DEFINE":{{const w=new ae(D);Te(o,w,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in w?rl(o,w,a):xr(o,w,t)}break}case"DISCONTINUITY-SEQUENCE":f=parseInt(D);break;case"KEY":{const w=Rr(D,t,o);if(w.isSupported()){if(w.method==="NONE"){T=void 0;break}T||(T={}),T[w.keyFormat]&&(T=oe({},T)),T[w.keyFormat]=w}else S.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${D}"`);break}case"START":o.startTimeOffset=Cr(D);break;case"MAP":{const w=new ae(D);if(Te(o,w,["BYTERANGE","URI"]),g.duration){const $=new vi(r,t);Ir($,w,i,T),c=$,g.initSegment=c,c.rawProgramDateTime&&!g.rawProgramDateTime&&(g.rawProgramDateTime=c.rawProgramDateTime)}else{const $=g.byteRangeEndOffset;if($){const O=g.byteRangeStartOffset;E=`${$-O}@${O}`}else E=null;Ir(g,w,i,T),c=g,L=!0}break}case"SERVER-CONTROL":{const w=new ae(D);o.canBlockReload=w.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=w.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&w.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=w.optionalFloat("PART-HOLD-BACK",0),o.holdBack=w.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const w=new ae(D);o.partTarget=w.decimalFloatingPoint("PART-TARGET");break}case"PART":{let w=o.partList;w||(w=o.partList=[]);const $=h>0?w[w.length-1]:void 0,O=h++,U=new ae(D);Te(o,U,["BYTERANGE","URI"]);const F=new Ao(U,g,t,O,$);w.push(F),g.duration+=F.duration;break}case"PRELOAD-HINT":{const w=new ae(D);Te(o,w,["URI"]),o.preloadHint=w;break}case"RENDITION-REPORT":{const w=new ae(D);Te(o,w,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(w);break}default:S.warn(`line parsed but not handled: ${y}`);break}}}m&&!m.relurl?(l.pop(),d-=m.duration,o.partList&&(o.fragmentHint=m)):o.partList&&(_r(g,m),g.cc=f,o.fragmentHint=g,T&&wr(g,T,o));const k=l.length,R=l[0],B=l[k-1];if(d+=o.skippedSegments*o.targetduration,d>0&&k&&B){o.averagetargetduration=d/k;const C=B.sn;o.endSN=C!=="initSegment"?C:0,o.live||(B.endList=!0),R&&(o.startCC=R.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(d+=o.fragmentHint.duration),o.totalduration=d,o.endCC=f,x>0&&dl(l,x),o}}function Rr(s,e,t){var i,r;const n=new ae(s);Te(t,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=(i=n.METHOD)!=null?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),c=n.KEYFORMATVERSIONS,u=(r=n.KEYFORMAT)!=null?r:"identity";o&&n.IV&&!l&&S.error(`Invalid IV: ${n.IV}`);const h=o?Fe.resolve(o,e):"",d=(c||"1").split("/").map(Number).filter(Number.isFinite);return new vt(a,h,u,d,l)}function Cr(s){const t=new ae(s).decimalFloatingPoint("TIME-OFFSET");return W(t)?t:null}function hl(s,e){let t=(s||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const r=t.filter(n=>nl(n,i));r.length&&(e[`${i}Codec`]=r.join(","),t=t.filter(n=>r.indexOf(n)===-1))}),e.unknownCodecs=t}function Dr(s,e,t){const i=e[t];i&&(s[t]=i)}function dl(s,e){let t=s[e];for(let i=e;i--;){const r=s[i];if(!r)return;r.programDateTime=t.programDateTime-r.duration*1e3,t=r}}function _r(s,e){s.rawProgramDateTime?s.programDateTime=Date.parse(s.rawProgramDateTime):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime),W(s.programDateTime)||(s.programDateTime=null,s.rawProgramDateTime=null)}function Ir(s,e,t,i){s.relurl=e.URI,e.BYTERANGE&&s.setByteRange(e.BYTERANGE),s.level=t,s.sn="initSegment",i&&(s.levelkeys=i),s.initSegment=null}function wr(s,e,t){s.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(r=>e[r].isCommonEncryption)&&i.push(s)}var ee={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},j={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function kr(s){const{type:e}=s;switch(e){case ee.AUDIO_TRACK:return j.AUDIO;case ee.SUBTITLE_TRACK:return j.SUBTITLE;default:return j.MAIN}}function Ii(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class fl{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,r=t.loader,n=i||r,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:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ee.MANIFEST,url:i,deliveryDirectives:null})}onLevelLoading(e,t){const{id:i,level:r,pathwayId:n,url:a,deliveryDirectives:o}=t;this.load({id:i,level:r,pathwayId:n,responseType:"text",type:ee.LEVEL,url:a,deliveryDirectives:o})}onAudioTrackLoading(e,t){const{id:i,groupId:r,url:n,deliveryDirectives:a}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:ee.AUDIO_TRACK,url:n,deliveryDirectives:a})}onSubtitleTrackLoading(e,t){const{id:i,groupId:r,url:n,deliveryDirectives:a}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:ee.SUBTITLE_TRACK,url:n,deliveryDirectives:a})}load(e){var t;const i=this.hls.config;let r=this.getInternalLoader(e);if(r){const c=r.context;if(c&&c.url===e.url&&c.level===e.level){S.trace("[playlist-loader]: playlist request ongoing");return}S.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}let n;if(e.type===ee.MANIFEST?n=i.manifestLoadPolicy.default:n=oe({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),W((t=e.deliveryDirectives)==null?void 0:t.part)){let c;if(e.type===ee.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===ee.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===ee.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const u=c.partTarget,h=c.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},l={onSuccess:(c,u,h,d)=>{const f=this.getInternalLoader(h);this.resetInternalLoader(h.type);const m=c.data;if(m.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(c,h,new Error("no EXTM3U delimiter"),d||null,u);return}u.parsing.start=performance.now(),Fe.isMediaPlaylist(m)?this.handleTrackOrLevelPlaylist(c,u,h,d||null,f):this.handleMasterPlaylist(c,u,h,d)},onError:(c,u,h,d)=>{this.handleNetworkError(u,h,!1,c,d)},onTimeout:(c,u,h)=>{this.handleNetworkError(u,h,!0,void 0,c)}};r.load(e,o,l)}handleMasterPlaylist(e,t,i,r){const n=this.hls,a=e.data,o=Ii(e,i),l=Fe.parseMasterPlaylist(a,o);if(l.playlistParsingError){this.handleManifestParsingError(e,i,l.playlistParsingError,r,t);return}const{contentSteering:c,levels:u,sessionData:h,sessionKeys:d,startTimeOffset:f,variableList:m}=l;this.variableList=m;const{AUDIO:g=[],SUBTITLES:y,"CLOSED-CAPTIONS":v}=Fe.parseMasterPlaylistMedia(a,o,l);g.length&&!g.some(x=>!x.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(S.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ae({}),bitrate:0,url:""})),n.trigger(p.MANIFEST_LOADED,{levels:u,audioTracks:g,subtitles:y,captions:v,contentSteering:c,url:o,stats:t,networkDetails:r,sessionData:h,sessionKeys:d,startTimeOffset:f,variableList:m})}handleTrackOrLevelPlaylist(e,t,i,r,n){const a=this.hls,{id:o,level:l,type:c}=i,u=Ii(e,i),h=0,d=W(l)?l:W(o)?o:0,f=kr(i),m=Fe.parseLevelPlaylist(e.data,u,d,f,h,this.variableList);if(c===ee.MANIFEST){const g={attrs:new ae({}),bitrate:0,details:m,name:"",url:u};a.trigger(p.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:u,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=m,this.handlePlaylistLoaded(m,e,t,i,r,n)}handleManifestParsingError(e,t,i,r,n){this.hls.trigger(p.ERROR,{type:q.NETWORK_ERROR,details:_.MANIFEST_PARSING_ERROR,fatal:t.type===ee.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:n})}handleNetworkError(e,t,i=!1,r,n){let a=`A network ${i?"timeout":"error"+(r?" (status "+r.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);S.warn(`[playlist-loader]: ${a}`);let l=_.UNKNOWN,c=!1;const u=this.getInternalLoader(e);switch(e.type){case ee.MANIFEST:l=i?_.MANIFEST_LOAD_TIMEOUT:_.MANIFEST_LOAD_ERROR,c=!0;break;case ee.LEVEL:l=i?_.LEVEL_LOAD_TIMEOUT:_.LEVEL_LOAD_ERROR,c=!1;break;case ee.AUDIO_TRACK:l=i?_.AUDIO_TRACK_LOAD_TIMEOUT:_.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case ee.SUBTITLE_TRACK:l=i?_.SUBTITLE_TRACK_LOAD_TIMEOUT:_.SUBTITLE_LOAD_ERROR,c=!1;break}u&&this.resetInternalLoader(e.type);const h={type:q.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:n};if(r){const d=(t==null?void 0:t.url)||e.url;h.response=he({url:d,data:void 0},r)}this.hls.trigger(p.ERROR,h)}handlePlaylistLoaded(e,t,i,r,n,a){const o=this.hls,{type:l,level:c,id:u,groupId:h,deliveryDirectives:d}=r,f=Ii(t,r),m=kr(r),g=typeof r.level=="number"&&m===j.MAIN?c:void 0;if(!e.fragments.length){const v=new Error("No Segments found in Playlist");o.trigger(p.ERROR,{type:q.NETWORK_ERROR,details:_.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:r,level:g,parent:m,networkDetails:n,stats:i});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const y=e.playlistParsingError;if(y){o.trigger(p.ERROR,{type:q.NETWORK_ERROR,details:_.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:r,level:g,parent:m,networkDetails:n,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case ee.MANIFEST:case ee.LEVEL:o.trigger(p.LEVEL_LOADED,{details:e,level:g||0,id:u||0,stats:i,networkDetails:n,deliveryDirectives:d});break;case ee.AUDIO_TRACK:o.trigger(p.AUDIO_TRACK_LOADED,{details:e,id:u||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:d});break;case ee.SUBTITLE_TRACK:o.trigger(p.SUBTITLE_TRACK_LOADED,{details:e,id:u||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:d});break}}}function Pr(s,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=s,e.dispatchEvent(t)}function Or(s,e){const t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(e.id))try{if(s.addCue(e),!s.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){S.debug(`[texttrack-utils]: ${i}`);try{const r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,s.addCue(r)}catch(r){S.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}t==="disabled"&&(s.mode=t)}function it(s){const e=s.mode;if(e==="disabled"&&(s.mode="hidden"),s.cues)for(let t=s.cues.length;t--;)s.removeCue(s.cues[t]);e==="disabled"&&(s.mode=e)}function wi(s,e,t,i){const r=s.mode;if(r==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const n=gl(s.cues,e,t);for(let a=0;a<n.length;a++)(!i||i(n[a]))&&s.removeCue(n[a])}r==="disabled"&&(s.mode=r)}function ml(s,e){if(e<s[0].startTime)return 0;const t=s.length-1;if(e>s[t].endTime)return-1;let i=0,r=t;for(;i<=r;){const n=Math.floor((r+i)/2);if(e<s[n].startTime)r=n-1;else if(e>s[n].startTime&&i<t)i=n+1;else return n}return s[i].startTime-e<e-s[r].startTime?i:r}function gl(s,e,t){const i=[],r=ml(s,e);if(r>-1)for(let n=r,a=s.length;n<a;n++){const o=s[n];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}function Mt(s){const e=[];for(let t=0;t<s.length;t++){const i=s[t];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&e.push(s[t])}return e}var Ce={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const pl=.25;function ki(){if(typeof self!="undefined")return self.VTTCue||self.TextTrackCue}function Fr(s,e,t,i,r){let n=new s(e,t,"");try{n.value=i,r&&(n.type=r)}catch{n=new s(e,t,JSON.stringify(r?he({type:r},i):i))}return n}const Nt=(()=>{const s=ki();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Pi(s,e){return s.getTime()/1e3-e}function yl(s){return Uint8Array.from(s.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class vl{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(it(this.id3Track),this.id3Track=null,this.media=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 i=e[t];if(i.kind==="metadata"&&i.label==="id3")return Pr(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:r}}}=this;if(!i&&!r)return;const{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=ki();if(a)for(let o=0;o<n.length;o++){const l=n[o].type;if(l===Ce.emsg&&!i||!r)continue;const c=or(n[o].data);if(c){const u=n[o].pts;let h=u+n[o].duration;h>Nt&&(h=Nt),h-u<=0&&(h=u+pl);for(let f=0;f<c.length;f++){const m=c[f];if(!ar(m)){this.updateId3CueEnds(u,l);const g=Fr(a,u,h,m,l);g&&this.id3Track.addCue(g)}}}}}updateId3CueEnds(e,t){var i;const r=(i=this.id3Track)==null?void 0:i.cues;if(r)for(let n=r.length;n--;){const a=r[n];a.type===t&&a.startTime<e&&a.endTime===Nt&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:r}){const{id3Track:n,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let c;r==="audio"?c=u=>u.type===Ce.audioId3&&l:r==="video"?c=u=>u.type===Ce.emsg&&o:c=u=>u.type===Ce.audioId3&&l||u.type===Ce.emsg&&o,wi(n,t,i,c)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:r}=this,{dateRanges:n}=t,a=Object.keys(n);if(r){const u=Object.keys(i).filter(h=>!a.includes(h));for(let h=u.length;h--;){const d=u[h];Object.keys(i[d].cues).forEach(f=>{r.removeCue(i[d].cues[f])}),delete i[d]}}const o=t.fragments[t.fragments.length-1];if(a.length===0||!W(o==null?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,c=ki();for(let u=0;u<a.length;u++){const h=a[u],d=n[h],f=Pi(d.startDate,l),m=i[h],g=(m==null?void 0:m.cues)||{};let y=(m==null?void 0:m.durationKnown)||!1,v=Nt;const T=d.endDate;if(T)v=Pi(T,l),y=!0;else if(d.endOnNext&&!y){const L=a.reduce((E,k)=>{if(k!==d.id){const R=n[k];if(R.class===d.class&&R.startDate>d.startDate&&(!E||d.startDate<E.startDate))return R}return E},null);L&&(v=Pi(L.startDate,l),y=!0)}const x=Object.keys(d.attr);for(let L=0;L<x.length;L++){const E=x[L];if(!So(E))continue;const k=g[E];if(k)y&&!m.durationKnown&&(k.endTime=v);else if(c){let R=d.attr[E];bo(E)&&(R=yl(R));const B=Fr(c,f,v,{key:E,data:R},Ce.dateRange);B&&(B.id=h,this.id3Track.addCue(B),g[E]=B)}}i[h]={cues:g,dateRange:d,durationKnown:y}}}}class xl{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(e===null)return null;const{holdBack:t,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let c=o&&i||t;(l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=n!==void 0?n:a*r);const u=r,h=1;return c+Math.min(this.stallCount*h,u)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,i=this.levelDetails;if(e===null||t===null||i===null)return null;const r=i.edge,n=e-t-this.edgeStalled,a=r-i.totalduration,o=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){const{levelDetails:e}=this;return e===null?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;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,levelDetails:t}=this;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(p.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(p.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var i;t.details===_.BUFFER_STALLED_ERROR&&(this.stallCount++,(i=this.levelDetails)!=null&&i.live&&S.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:n}=this.config;if(!r||n===1||!t.live)return;const a=this.targetLatency;if(a===null)return;const o=i-a,l=Math.min(this.maxLatency,a+t.targetduration);if(o<l&&o>.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,n)),h=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(u,Math.max(1,h))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const Oi=["NONE","TYPE-0","TYPE-1",null];function Tl(s){return Oi.indexOf(s)>-1}const Bt=["SDR","PQ","HLG"];function El(s){return!!s&&Bt.indexOf(s)>-1}var Tt={No:"",Yes:"YES",v2:"v2"};function Sl(s,e){const{canSkipUntil:t,canSkipDateRanges:i,endSN:r}=s,n=e!==void 0?e-r:0;return t&&n<t?i?Tt.v2:Tt.Yes:Tt.No}class Mr{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}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 st{constructor(e){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.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(t=>!!t).map(t=>t.substring(0,4)).join(","),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 Nr(this._audioGroups,e)}hasSubtitleGroup(e){return Nr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.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 Nr(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function Fi(s,e){const t=e.startPTS;if(W(t)){let i=0,r;e.sn>s.sn?(i=t-s.start,r=s):(i=s.start-t,r=e),r.duration!==i&&(r.duration=i)}else e.sn>s.sn?s.cc===e.cc&&s.minEndPTS?e.start=s.start+(s.minEndPTS-s.start):e.start=s.start+s.duration:e.start=Math.max(s.start-e.duration,0)}function Br(s,e,t,i,r,n){i-t<=0&&(S.warn("Fragment should have a positive duration",e),i=t+e.duration,n=r+e.duration);let o=t,l=i;const c=e.startPTS,u=e.endPTS;if(W(c)){const y=Math.abs(c-t);W(e.deltaPTS)?e.deltaPTS=Math.max(y,e.deltaPTS):e.deltaPTS=y,o=Math.max(t,c),t=Math.min(t,c),r=Math.min(r,e.startDTS),l=Math.min(i,u),i=Math.max(i,u),n=Math.max(n,e.endDTS)}const h=t-e.start;e.start!==0&&(e.start=t),e.duration=i-e.start,e.startPTS=t,e.maxStartPTS=o,e.startDTS=r,e.endPTS=i,e.minEndPTS=l,e.endDTS=n;const d=e.sn;if(!s||d<s.startSN||d>s.endSN)return 0;let f;const m=d-s.startSN,g=s.fragments;for(g[m]=e,f=m;f>0;f--)Fi(g[f],g[f-1]);for(f=m;f<g.length-1;f++)Fi(g[f],g[f+1]);return s.fragmentHint&&Fi(g[g.length-1],s.fragmentHint),s.PTSKnown=s.alignedSliding=!0,h}function bl(s,e){let t=null;const i=s.fragments;for(let l=i.length-1;l>=0;l--){const c=i[l].initSegment;if(c){t=c;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let r=0,n;if(Rl(s,e,(l,c)=>{l.relurl&&(r=l.cc-c.cc),W(l.startPTS)&&W(l.endPTS)&&(c.start=c.startPTS=l.startPTS,c.startDTS=l.startDTS,c.maxStartPTS=l.maxStartPTS,c.endPTS=l.endPTS,c.endDTS=l.endDTS,c.minEndPTS=l.minEndPTS,c.duration=l.endPTS-l.startPTS,c.duration&&(n=c),e.PTSKnown=e.alignedSliding=!0),c.elementaryStreams=l.elementaryStreams,c.loader=l.loader,c.stats=l.stats,l.initSegment&&(c.initSegment=l.initSegment,t=l.initSegment)}),t&&(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(c=>{var u;c&&(!c.initSegment||c.initSegment.relurl===((u=t)==null?void 0:u.relurl))&&(c.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some(l=>!l),e.deltaUpdateFailed){S.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=Al(s.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(r){S.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l<a.length;l++)a[l].cc+=r}e.skippedSegments&&(e.startCC=e.fragments[0].cc),Ll(s.partList,e.partList,(l,c)=>{c.elementaryStreams=l.elementaryStreams,c.stats=l.stats}),n?Br(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):$r(s,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const l=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=l),e.driftEndTime=o,e.driftEnd=l}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime}function Al(s,e,t){const i=oe({},s);return t&&t.forEach(r=>{delete i[r]}),Object.keys(e).forEach(r=>{const n=new Js(e[r].attr,i[r]);n.isValid?i[r]=n:S.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[r].attr)}"`)}),i}function Ll(s,e,t){if(s&&e){let i=0;for(let r=0,n=s.length;r<=n;r++){const a=s[r],o=e[r+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--}}}function Rl(s,e,t){const i=e.skippedSegments,r=Math.max(s.startSN,e.startSN)-e.startSN,n=(s.fragmentHint?1:0)+(i?e.endSN:Math.min(s.endSN,e.endSN))-e.startSN,a=e.startSN-s.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let c=r;c<=n;c++){const u=l[a+c];let h=o[c];i&&!h&&c<i&&(h=e.fragments[c]=u),u&&h&&t(u,h)}}function $r(s,e){const t=e.startSN+e.skippedSegments-s.startSN,i=s.fragments;t<0||t>=i.length||Mi(e,i[t].start)}function Mi(s,e){if(e){const t=s.fragments;for(let i=s.skippedSegments;i<t.length;i++)t[i].start+=e;s.fragmentHint&&(s.fragmentHint.start+=e)}}function Cl(s,e=1/0){let t=1e3*s.targetduration;if(s.updated){const i=s.fragments,r=4;if(i.length&&t*r>e){const n=i[i.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function Dl(s,e,t){if(!(s!=null&&s.details))return null;const i=s.details;let r=i.fragments[e-i.startSN];return r||(r=i.fragmentHint,r&&r.sn===e)?r:e<i.startSN&&t&&t.sn===e?t:null}function Ur(s,e,t){var i;return s!=null&&s.details?Gr((i=s.details)==null?void 0:i.partList,e,t):null}function Gr(s,e,t){if(s)for(let i=s.length;i--;){const r=s[i];if(r.index===t&&r.fragment.sn===e)return r}return null}function Hr(s){s.forEach((e,t)=>{const{details:i}=e;i!=null&&i.fragments&&i.fragments.forEach(r=>{r.level=t})})}function $t(s){switch(s.details){case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_TIMEOUT:case _.LEVEL_LOAD_TIMEOUT:case _.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Vr(s,e){const t=$t(e);return s.default[`${t?"timeout":"error"}Retry`]}function Ni(s,e){const t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function Kr(s){return he(he({},s),{errorRetry:null,timeoutRetry:null})}function Ut(s,e,t,i){if(!s)return!1;const r=i==null?void 0:i.code,n=e<s.maxNumRetry&&(_l(r)||!!t);return s.shouldRetry?s.shouldRetry(s,e,t,i,n):n}function _l(s){return s===0&&navigator.onLine===!1||!!s&&(s<400||s>499)}const Wr={search:function(s,e){let t=0,i=s.length-1,r=null,n=null;for(;t<=i;){r=(t+i)/2|0,n=s[r];const a=e(n);if(a>0)t=r+1;else if(a<0)i=r-1;else return n}return null}};function Il(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!W(e))return null;const i=s[0].programDateTime;if(e<(i||0))return null;const r=s[s.length-1].endProgramDateTime;if(e>=(r||0))return null;t=t||0;for(let n=0;n<s.length;++n){const a=s[n];if(wl(e,t,a))return a}return null}function Gt(s,e,t=0,i=0){let r=null;if(s){r=e[s.sn-e[0].sn+1]||null;const a=s.endDTS-t;a>0&&a<15e-7&&(t+=15e-7)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&(!s||s.level===r.level)&&Bi(t,i,r)===0)return r;const n=Wr.search(e,Bi.bind(null,t,i));return n&&(n!==s||!r)?n:r}function Bi(s=0,e=0,t){if(t.start<=s&&t.start+t.duration>s)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=s?1:t.start-i>s&&t.start?-1:0}function wl(s,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function kl(s,e){return Wr.search(s,t=>t.cc<e?1:t.cc>e?-1:0)}var ge={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},De={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class Pl{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=S.log.bind(S,"[info]:"),this.warn=S.warn.bind(S,"[warning]:"),this.error=S.error.bind(S,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.ERROR,this.onError,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.ERROR,this.onError,this),e.off(p.ERROR,this.onErrorOut,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===j.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,r;if(t.fatal)return;const n=this.hls,a=t.context;switch(t.details){case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case _.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction={action:ge.DoNothing,flags:De.None};return}case _.FRAG_GAP:case _.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ge.SendAlternateToPenaltyBox;return}case _.LEVEL_EMPTY_ERROR:case _.LEVEL_PARSING_ERROR:{var o,l;const c=t.parent===j.MAIN?t.level:n.loadLevel;t.details===_.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(l=o.levelDetails)!=null&&l.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:typeof(a==null?void 0:a.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a.level));return;case _.AUDIO_TRACK_LOAD_ERROR:case _.AUDIO_TRACK_LOAD_TIMEOUT:case _.SUBTITLE_LOAD_ERROR:case _.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const c=n.levels[n.loadLevel];if(c&&(a.type===ee.AUDIO_TRACK&&c.hasAudioGroup(a.groupId)||a.type===ee.SUBTITLE_TRACK&&c.hasSubtitleGroup(a.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=ge.SendAlternateToPenaltyBox,t.errorAction.flags=De.MoveAllAlternatesMatchingHost;return}}return;case _.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const c=n.levels[n.loadLevel],u=c==null?void 0:c.attrs["HDCP-LEVEL"];u?t.errorAction={action:ge.SendAlternateToPenaltyBox,flags:De.MoveAllAlternatesMatchingHDCP,hdcpLevel:u}:this.keySystemError(t)}return;case _.BUFFER_ADD_CODEC_ERROR:case _.REMUX_ALLOC_ERROR:case _.BUFFER_APPEND_ERROR:t.errorAction=this.getLevelSwitchAction(t,(r=t.level)!=null?r:n.loadLevel);return;case _.INTERNAL_EXCEPTION:case _.BUFFER_APPENDING_ERROR:case _.BUFFER_FULL_ERROR:case _.LEVEL_SWITCH_ERROR:case _.BUFFER_STALLED_ERROR:case _.BUFFER_SEEK_OVER_HOLE:case _.BUFFER_NUDGE_ON_STALL:t.errorAction={action:ge.DoNothing,flags:De.None};return}t.type===q.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,r=Vr(i.config.playlistLoadPolicy,e),n=this.playlistError++;if(Ut(r,n,$t(e),e.response))return{action:ge.RetryRequest,flags:De.None,retryConfig:r,retryCount:n};const o=this.getLevelSwitchAction(e,t);return r&&(o.retryConfig=r,o.retryCount=n),o}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=Vr(e.details.startsWith("key")?a:n,e),l=t.levels.reduce((u,h)=>u+h.fragmentError,0);if(r&&(e.details!==_.FRAG_GAP&&r.fragmentError++,Ut(o,l,$t(e),e.response)))return{action:ge.RetryRequest,flags:De.None,retryConfig:o,retryCount:l};const c=this.getLevelSwitchAction(e,i);return o&&(c.retryConfig=o,c.retryCount=l),c}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const r=this.hls.levels[t];if(r){var n,a;const c=e.details;r.loadError++,c===_.BUFFER_APPEND_ERROR&&r.fragmentError++;let u=-1;const{levels:h,loadLevel:d,minAutoLevel:f,maxAutoLevel:m}=i;i.autoLevelEnabled||(i.loadLevel=-1);const g=(n=e.frag)==null?void 0:n.type,v=(g===j.AUDIO&&c===_.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(c===_.BUFFER_ADD_CODEC_ERROR||c===_.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:k})=>r.audioCodec!==k),x=e.sourceBufferName==="video"&&(c===_.BUFFER_ADD_CODEC_ERROR||c===_.BUFFER_APPEND_ERROR)&&h.some(({codecSet:k,audioCodec:R})=>r.codecSet!==k&&r.audioCodec===R),{type:L,groupId:E}=(a=e.context)!=null?a:{};for(let k=h.length;k--;){const R=(k+d)%h.length;if(R!==d&&R>=f&&R<=m&&h[R].loadError===0){var o,l;const B=h[R];if(c===_.FRAG_GAP&&e.frag){const C=h[R].details;if(C){const b=Gt(e.frag,C.fragments,e.frag.start);if(b!=null&&b.gap)continue}}else{if(L===ee.AUDIO_TRACK&&B.hasAudioGroup(E)||L===ee.SUBTITLE_TRACK&&B.hasSubtitleGroup(E))continue;if(g===j.AUDIO&&(o=r.audioGroups)!=null&&o.some(C=>B.hasAudioGroup(C))||g===j.SUBTITLE&&(l=r.subtitleGroups)!=null&&l.some(C=>B.hasSubtitleGroup(C))||v&&r.audioCodec===B.audioCodec||!v&&r.audioCodec!==B.audioCodec||x&&r.codecSet===B.codecSet)continue}u=R;break}}if(u>-1&&i.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:ge.SendAlternateToPenaltyBox,flags:De.None,nextAutoLevel:u}}return{action:ge.SendAlternateToPenaltyBox,flags:De.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case ge.DoNothing:break;case ge.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==_.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,i=e.errorAction;if(!i)return;const{flags:r,hdcpLevel:n,nextAutoLevel:a}=i;switch(r){case De.None:this.switchLevel(e,a);break;case De.MoveAllAlternatesMatchingHDCP:n&&(t.maxHdcpLevel=Oi[Oi.indexOf(n)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(e,a)}switchLevel(e,t){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)}}class $i{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=S.log.bind(S,`${t}:`),this.warn=S.warn.bind(S,`${t}:`),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.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t){const i=t==null?void 0:t.renditionReports;if(i){let r=-1;for(let n=0;n<i.length;n++){const a=i[n];let o;try{o=new self.URL(a.URI,t.url).href}catch(l){S.warn(`Could not construct new URL for Rendition Report: ${l}`),o=a.URI||""}if(o===e){r=n;break}else o===e.substring(0,o.length)&&(r=n)}if(r!==-1){const n=i[r],a=parseInt(n["LAST-MSN"])||(t==null?void 0:t.lastPartSn);let o=parseInt(n["LAST-PART"])||(t==null?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const l=Math.min(t.age-t.partTarget,t.targetduration);o>=0&&l>t.partTarget&&(o+=1)}return new Mr(a,o>=0?o:void 0,Tt.No)}}}loadPlaylist(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,i){const{details:r,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;if(r.advancedDateTime=Date.now()-o,r.live||i!=null&&i.live){if(r.reloaded(i),i&&this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),i&&r.fragments.length>0&&bl(i,r),!this.canLoad||!r.live)return;let l,c,u;if(r.canBlockReload&&r.endSN&&r.advanced){const y=this.hls.config.lowLatencyMode,v=r.lastPartSn,T=r.endSN,x=r.lastPartIndex,L=x!==-1,E=v===T,k=y?0:x;L?(c=E?T+1:v,u=E?k:x+1):c=T+1;const R=r.age,B=R+r.ageHeader;let C=Math.min(B-r.partTarget,r.targetduration*1.5);if(C>0){if(i&&C>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${C} with playlist age: ${r.age}`),C=0;else{const b=Math.floor(C/r.targetduration);if(c+=b,u!==void 0){const D=Math.round(C%r.targetduration/r.partTarget);u+=D}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${R.toFixed(2)}s goal: ${C} skip sn ${b} to part ${u}`)}r.tuneInGoal=C}if(l=this.getDeliveryDirectives(r,t.deliveryDirectives,c,u),y||!E){this.loadPlaylist(l);return}}else(r.canBlockReload||r.canSkipUntil)&&(l=this.getDeliveryDirectives(r,t.deliveryDirectives,c,u));const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,f=(r.edge-d)*1e3,m=Cl(r,f);r.updated&&a>this.requestScheduled+m&&(this.requestScheduled=n.loading.start),c!==void 0&&r.canBlockReload?this.requestScheduled=n.loading.first+m-(r.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+m<a?this.requestScheduled=a:this.requestScheduled-a<=0&&(this.requestScheduled+=m);let g=this.requestScheduled-a;g=Math.max(0,g),this.log(`reload live playlist ${e} in ${Math.round(g)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(l),g)}else this.clearTimer()}getDeliveryDirectives(e,t,i,r){let n=Sl(e,i);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,n=Tt.No),new Mr(i,r,n)}checkRetry(e){const t=e.details,i=$t(e),r=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=r||{},l=!!r&&!!o&&(n===ge.RetryRequest||!r.resolved&&n===ge.SendAlternateToPenaltyBox);if(l){var c;if(this.requestScheduled=-1,a>=o.maxNumRetry)return!1;if(i&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const u=Ni(o,a);this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${u}ms`)}e.levelRetry=!0,r.resolved=!0}return l}}class rt{constructor(e,t=0,i=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_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*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 Ol{constructor(e,t,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new rt(e),this.fast_=new rt(t),this.defaultTTFB_=r,this.ttfb_=new rt(e)}update(e,t){const{slow_:i,fast_:r,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new rt(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new rt(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new rt(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,r=e/1e3,n=i/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,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_}destroy(){}}const zr={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Yr={};function Fl(s,e,t,i,r,n){const a=s.audioCodec?s.audioGroups:null,o=n==null?void 0:n.audioCodec,l=n==null?void 0:n.channels,c=l?parseInt(l):o?1/0:2;let u=null;if(a!=null&&a.length)try{a.length===1&&a[0]?u=e.groups[a[0]].channels:u=a.reduce((h,d)=>{if(d){const f=e.groups[d];if(!f)throw new Error(`Audio track group ${d} not found`);Object.keys(f.channels).forEach(m=>{h[m]=(h[m]||0)+f.channels[m]})}return h},{2:0})}catch{return!0}return s.videoCodec!==void 0&&(s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(i,30)||s.videoRange!=="SDR"&&s.videoRange!==t||s.bitrate>Math.max(r,8e6))||!!u&&W(c)&&Object.keys(u).some(h=>parseInt(h)>c)}function Ml(s,e,t){const i=s.videoCodec,r=s.audioCodec;if(!i||!r||!t)return Promise.resolve(zr);const n={width:s.width,height:s.height,bitrate:Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)),framerate:s.frameRate||30},a=s.videoRange;a!=="SDR"&&(n.transferFunction=a.toLowerCase());const o=i.split(",").map(l=>({type:"media-source",video:he(he({},n),{},{contentType:xt(l,"video")})}));return r&&s.audioGroups&&s.audioGroups.forEach(l=>{var c;l&&((c=e.groups[l])==null||c.tracks.forEach(u=>{if(u.groupId===l){const h=u.channels||"",d=parseFloat(h);W(d)&&d>2&&o.push.apply(o,r.split(",").map(f=>({type:"media-source",audio:{contentType:xt(f,"audio"),channels:""+d}})))}}))}),Promise.all(o.map(l=>{const c=Nl(l);return Yr[c]||(Yr[c]=t.decodingInfo(l))})).then(l=>({supported:!l.some(c=>!c.supported),configurations:o,decodingInfoResults:l})).catch(l=>({supported:!1,configurations:o,decodingInfoResults:[],error:l}))}function Nl(s){const{audio:e,video:t}=s,i=t||e;if(i){const r=i.contentType.split('"')[1];if(t)return`r${t.height}x${t.width}f${Math.ceil(t.framerate)}${t.transferFunction||"sd"}_${r}_${Math.ceil(t.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${r}`}return""}function Bl(){if(typeof matchMedia=="function"){const s=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(s.media!==e.media)return s.matches===!0}return!1}function $l(s,e){let t=!1,i=[];return s&&(t=s!=="SDR",i=[s]),e&&(i=e.allowedVideoRanges||Bt.slice(0),t=e.preferHDR!==void 0?e.preferHDR:Bl(),t?i=i.filter(r=>r!=="SDR"):i=["SDR"]),{preferHDR:t,allowedVideoRanges:i}}function Ul(s,e,t,i,r){const n=Object.keys(s),a=i==null?void 0:i.channels,o=i==null?void 0:i.audioCodec,l=a&&parseInt(a)===2;let c=!0,u=!1,h=1/0,d=1/0,f=1/0,m=0,g=[];const{preferHDR:y,allowedVideoRanges:v}=$l(e,r);for(let E=n.length;E--;){const k=s[n[E]];c=k.channels[2]>0,h=Math.min(h,k.minHeight),d=Math.min(d,k.minFramerate),f=Math.min(f,k.minBitrate);const R=v.filter(B=>k.videoRanges[B]>0);R.length>0&&(u=!0,g=R)}h=W(h)?h:0,d=W(d)?d:0;const T=Math.max(1080,h),x=Math.max(30,d);return f=W(f)?f:t,t=Math.max(f,t),u||(e=void 0,g=[]),{codecSet:n.reduce((E,k)=>{const R=s[k];if(k===E)return E;if(R.minBitrate>t)return Ue(k,`min bitrate of ${R.minBitrate} > current estimate of ${t}`),E;if(!R.hasDefaultAudio)return Ue(k,"no renditions with default or auto-select sound found"),E;if(o&&k.indexOf(o.substring(0,4))%5!==0)return Ue(k,`audio codec preference "${o}" not found`),E;if(a&&!l){if(!R.channels[a])return Ue(k,`no renditions with ${a} channel sound found (channels options: ${Object.keys(R.channels)})`),E}else if((!o||l)&&c&&R.channels[2]===0)return Ue(k,"no renditions with stereo sound found"),E;return R.minHeight>T?(Ue(k,`min resolution of ${R.minHeight} > maximum of ${T}`),E):R.minFramerate>x?(Ue(k,`min framerate of ${R.minFramerate} > maximum of ${x}`),E):g.some(B=>R.videoRanges[B]>0)?R.maxScore<m?(Ue(k,`max score of ${R.maxScore} < selected max of ${m}`),E):E&&(Ot(k)>=Ot(E)||R.fragmentError>s[E].fragmentError)?E:(m=R.maxScore,k):(Ue(k,`no variants with VIDEO-RANGE of ${JSON.stringify(g)} found`),E)},void 0),videoRanges:g,preferHDR:y,minFramerate:d,minBitrate:f}}function Ue(s,e){S.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function Gl(s){return s.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Hl(s,e,t,i){return s.slice(t,i+1).reduce((r,n)=>{if(!n.codecSet)return r;const a=n.audioGroups;let o=r[n.codecSet];o||(r[n.codecSet]=o={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!a,fragmentError:0}),o.minBitrate=Math.min(o.minBitrate,n.bitrate);const l=Math.min(n.height,n.width);return o.minHeight=Math.min(o.minHeight,l),o.minFramerate=Math.min(o.minFramerate,n.frameRate),o.maxScore=Math.max(o.maxScore,n.score),o.fragmentError+=n.fragmentError,o.videoRanges[n.videoRange]=(o.videoRanges[n.videoRange]||0)+1,a&&a.forEach(c=>{if(!c)return;const u=e.groups[c];o.hasDefaultAudio=o.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(h=>{o.channels[h]=(o.channels[h]||0)+u.channels[h]})}),r},{})}function Me(s,e,t){if("attrs"in s){const i=e.indexOf(s);if(i!==-1)return i}for(let i=0;i<e.length;i++){const r=e[i];if(nt(s,r,t))return i}return-1}function nt(s,e,t){const{groupId:i,name:r,lang:n,assocLang:a,characteristics:o,default:l}=s,c=s.forced;return(i===void 0||e.groupId===i)&&(r===void 0||e.name===r)&&(n===void 0||e.lang===n)&&(n===void 0||e.assocLang===a)&&(l===void 0||e.default===l)&&(c===void 0||e.forced===c)&&(o===void 0||Vl(o,e.characteristics))&&(t===void 0||t(s,e))}function Vl(s,e=""){const t=s.split(","),i=e.split(",");return t.length===i.length&&!t.some(r=>i.indexOf(r)===-1)}function at(s,e){const{audioCodec:t,channels:i}=s;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function Kl(s,e,t,i,r){const n=e[i],o=e.reduce((d,f,m)=>{const g=f.uri;return(d[g]||(d[g]=[])).push(m),d},{})[n.uri];o.length>1&&(i=Math.max.apply(Math,o));const l=n.videoRange,c=n.frameRate,u=n.codecSet.substring(0,4),h=jr(e,i,d=>{if(d.videoRange!==l||d.frameRate!==c||d.codecSet.substring(0,4)!==u)return!1;const f=d.audioGroups,m=t.filter(g=>!f||f.indexOf(g.groupId)!==-1);return Me(s,m,r)>-1});return h>-1?h:jr(e,i,d=>{const f=d.audioGroups,m=t.filter(g=>!f||f.indexOf(g.groupId)!==-1);return Me(s,m,r)>-1})}function jr(s,e,t){for(let i=e;i;i--)if(t(s[i]))return i;for(let i=e+1;i<s.length;i++)if(t(s[i]))return i;return-1}class Wl{constructor(e){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.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:t,partCurrent:i,hls:r}=this,{autoLevelEnabled:n,media:a}=r;if(!t||!a)return;const o=performance.now(),l=i?i.stats:t.stats,c=i?i.duration:t.duration,u=o-l.loading.start,h=r.minAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||t.level<=h){this.clearTimer(),this._nextAutoLevel=-1;return}if(!n||a.paused||!a.playbackRate||!a.readyState)return;const d=r.mainForwardBufferInfo;if(d===null)return;const f=this.bwEstimator.getEstimateTTFB(),m=Math.abs(a.playbackRate);if(u<=Math.max(f,1e3*(c/(m*2))))return;const g=d.len/m,y=l.loading.first?l.loading.first-l.loading.start:-1,v=l.loaded&&y>-1,T=this.getBwEstimate(),x=r.levels,L=x[t.level],E=l.total||Math.max(l.loaded,Math.round(c*L.averageBitrate/8));let k=v?u-y:u;k<1&&v&&(k=Math.min(u,l.loaded*8/T));const R=v?l.loaded*1e3/k:0,B=R?(E-l.loaded)/R:E*8/T+f/1e3;if(B<=g)return;const C=R?R*8:T;let b=Number.POSITIVE_INFINITY,D;for(D=t.level-1;D>h;D--){const w=x[D].maxBitrate;if(b=this.getTimeToLoadFrag(f/1e3,C,c*w,!x[D].details),b<g)break}if(b>=B||b>c*10)return;r.nextLoadLevel=r.nextAutoLevel=D,v?this.bwEstimator.sample(u-Math.min(f,y),l.loaded):this.bwEstimator.sampleTTFB(u);const P=x[D].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>P&&this.resetEstimator(P),this.clearTimer(),S.warn(`[abr] Fragment ${t.sn}${i?" part "+i.index:""} of level ${t.level} is loading too slowly;
2
2
  Time to underbuffer: ${g.toFixed(3)} s
3
3
  Estimated load time for current fragment: ${B.toFixed(3)} s
4
4
  Estimated load time for down switch fragment: ${b.toFixed(3)} s
5
5
  TTFB estimate: ${y|0} ms
6
6
  Current BW estimate: ${W(T)?T|0:"Unknown"} bps
7
7
  New BW estimate: ${this.getBwEstimate()|0} bps
8
- Switching to level ${D} @ ${P|0} bps`),r.trigger(p.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:i,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(S.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 Ol(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(p.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,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 i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var r;this.fragCurrent=i,this.partCurrent=(r=t.part)!=null?r: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 _.BUFFER_ADD_CODEC_ERROR:case _.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case _.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:r,partCurrent:n}=this;if(i&&r&&i.sn===r.sn&&i.level===r.level){const a=performance.now(),o=n?n.stats:i.stats,l=a-o.loading.start,c=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&c>-1){const h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(h,c),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,r){const n=e+i/t,a=r?this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){const i=this.hls.config,{loading:r}=t.stats,n=r.end-r.start;W(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}onFragLoaded(e,{frag:t,part:i}){const r=i?i.stats:t.stats;if(t.type===j.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const n=i?i.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+r.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){const n={stats:r,frag:t,part:i,id:t.type};this.onFragBuffered(p.FRAG_BUFFERED,n),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:r}=t,n=r!=null&&r.stats.loaded?r.stats:i.stats;if(n.aborted||this.ignoreFragment(i))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(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==j.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,n=this.findBestLevel(i,t,e,0,r,1,1);if(n>-1)return n;const a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return S.warn(`[abr] 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,i=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const n=i&&r?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:i}=this,{maxAutoLevel:r,config:n,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let u=n.abrBandWidthFactor,h=n.abrBandWidthUpFactor;if(c){const y=this.findBestLevel(l,a,r,c,0,u,h);if(y>=0)return y}let d=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!c){const y=this.bitrateTestDelay;y&&(d=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-y,S.info(`[abr] 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(l,a,r,c,d,u,h);if(S.info(`[abr] ${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`),f>-1)return f;const m=i.levels[a],g=i.levels[i.loadLevel];return(m==null?void 0:m.bitrate)<(g==null?void 0:g.bitrate)?a:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,r,n,a,o){var l;const c=r+n,u=this.lastLoadedFragLevel,h=u===-1?this.hls.firstLevel:u,{fragCurrent:d,partCurrent:f}=this,{levels:m,allAudioTracks:g,loadLevel:y,config:v}=this.hls;if(m.length===1)return 0;const T=m[h],x=!!(T!=null&&(l=T.details)!=null&&l.live),L=y===-1||u===-1;let E,k="SDR",R=(T==null?void 0:T.frameRate)||0;const{audioPreference:B,videoPreference:C}=v,b=this.audioTracksByGroup||(this.audioTracksByGroup=Gl(g));if(L){if(this.firstSelection!==-1)return this.firstSelection;const O=this.codecTiers||(this.codecTiers=Hl(m,b,t,i)),G=Ul(O,k,e,B,C),{codecSet:F,videoRanges:V,minFramerate:H,minBitrate:N,preferHDR:J}=G;E=F,k=J?V[V.length-1]:V[0],R=H,e=Math.max(e,N),S.log(`[abr] picked start tier ${JSON.stringify(G)}`)}else E=T==null?void 0:T.codecSet,k=T==null?void 0:T.videoRange;const D=f?f.duration:d?d.duration:0,P=this.bwEstimator.getEstimateTTFB()/1e3,w=[];for(let O=i;O>=t;O--){var U;const G=m[O],F=O>h;if(!G)continue;if(v.useMediaCapabilities&&!G.supportedResult&&!G.supportedPromise){const le=navigator.mediaCapabilities;typeof(le==null?void 0:le.decodingInfo)=="function"&&Fl(G,b,k,R,e,B)?(G.supportedPromise=Ml(G,b,le),G.supportedPromise.then(me=>{if(!this.hls)return;G.supportedResult=me;const pe=this.hls.levels,Re=pe.indexOf(G);me.error?S.warn(`[abr] MediaCapabilities decodingInfo error: "${me.error}" for level ${Re} ${JSON.stringify(me)}`):me.supported||(S.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${Re} ${JSON.stringify(me)}`),Re>-1&&pe.length>1&&(S.log(`[abr] Removing unsupported level ${Re}`),this.hls.removeLevel(Re)))})):G.supportedResult=zr}if(E&&G.codecSet!==E||k&&G.videoRange!==k||F&&R>G.frameRate||!F&&R>0&&R<G.frameRate||G.supportedResult&&!((U=G.supportedResult.decodingInfoResults)!=null&&U[0].smooth)){w.push(O);continue}const V=G.details,H=(f?V==null?void 0:V.partTarget:V==null?void 0:V.averagetargetduration)||D;let N;F?N=o*e:N=a*e;const J=D&&r>=D*2&&n===0?m[O].averageBitrate:m[O].maxBitrate,Q=this.getTimeToLoadFrag(P,N,J*H,V===void 0);if(N>=J&&(O===u||G.loadError===0&&G.fragmentError===0)&&(Q<=P||!W(Q)||x&&!this.bitrateTestDelay||Q<c)){const le=this.forcedAutoLevel;return O!==y&&(le===-1||le!==y)&&(w.length&&S.trace(`[abr] Skipped level(s) ${w.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${m[w[0]].codecs}" ${m[w[0]].videoRange}; not compatible with "${T.codecs}" ${k}`),S.info(`[abr] switch candidate:${h}->${O} adjustedbw(${Math.round(N)})-bitrate=${Math.round(N-J)} ttfb:${P.toFixed(1)} avgDuration:${H.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${Q.toFixed(1)} firstSelection:${L} codecSet:${E} videoRange:${k} hls.loadLevel:${y}`)),L&&(this.firstSelection=O),O}}return-1}set nextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls,r=Math.min(Math.max(e,i),t);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}}class zl{constructor(){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(){}}var de={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Yl{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.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let r=i.length;r--;){const n=i[r];if(!n)break;const a=n.end;if(n.start<=e&&a!==null&&e<=a)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const a=i[r[n]];if((a==null?void 0:a.body.type)===t&&a.buffered){const o=a.body;if(o.start<=e&&e<=o.end)return o}}return null}detectEvictedFragments(e,t,i,r){this.timeRanges&&(this.timeRanges[e]=t);const n=(r==null?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o||n>=o.body.sn)return;if(!o.buffered&&!o.loaded){o.body.type===i&&this.removeFragment(o.body);return}const l=o.range[e];l&&l.time.some(c=>{const u=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return u&&this.removeFragment(o.body),u})})}detectPartialFragments(e){const t=this.timeRanges,{frag:i,part:r}=e;if(!t||i.sn==="initSegment")return;const n=ot(i),a=this.fragments[n];if(!a||a.buffered&&i.gap)return;const o=!i.relurl;Object.keys(t).forEach(l=>{const c=i.elementaryStreams[l];if(!c)return;const u=t[l],h=o||c.partial===!0;a.range[l]=this.getBufferedTimes(i,r,h,u)}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=i.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),Ht(a)||this.removeParts(i.sn-1,i.type)):this.removeFragment(a.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=i.filter(r=>r.fragment.sn>=e))}fragBuffered(e,t){const i=ot(e);let r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(e,t,i,r){const n={time:[],partial:i},a=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||a;for(let u=0;u<r.length;u++){const h=r.start(u)-this.bufferPadding,d=r.end(u)+this.bufferPadding;if(c>=h&&l<=d){n.time.push({startPTS:Math.max(a,r.start(u)),endPTS:Math.min(o,r.end(u))});break}else if(a<d&&o>h){const f=Math.max(a,r.start(u)),m=Math.min(o,r.end(u));m>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:m}))}else if(o<=h)break}return n}getPartialFragment(e){let t=null,i,r,n,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{const u=l[c];u&&Ht(u)&&(r=u.body.start-o,n=u.body.end+o,e>=r&&e<=n&&(i=Math.min(e-r,n-e),a<=i&&(t=u.body,a=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Ht(t))}getState(e){const t=ot(e),i=this.fragments[t];return i?i.buffered?Ht(i)?de.PARTIAL:de.OK:de.APPENDING:de.NOT_LOADED}isTimeBuffered(e,t,i){let r,n;for(let a=0;a<i.length;a++){if(r=i.start(a)-this.bufferPadding,n=i.end(a)+this.bufferPadding,e>=r&&t<=n)return!0;if(t<=r)return!1}return!1}onFragLoaded(e,t){const{frag:i,part:r}=t;if(i.sn==="initSegment"||i.bitrateTest)return;const n=r?null:t,a=ot(i);this.fragments[a]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:r,timeRanges:n}=t;if(i.sn==="initSegment")return;const a=i.type;if(r){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(r)}this.timeRanges=n,Object.keys(n).forEach(o=>{const l=n[o];this.detectEvictedFragments(o,l,a,r)})}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=ot(e);return!!this.fragments[t]}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,r,n){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==i||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(e){const t=ot(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const r=e.sn;this.activePartLists[e.type]=i.filter(n=>n.fragment.sn!==r)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function Ht(s){var e,t,i;return s.buffered&&(s.body.gap||((e=s.range.video)==null?void 0:e.partial)||((t=s.range.audio)==null?void 0:t.partial)||((i=s.range.audiovideo)==null?void 0:i.partial))}function ot(s){return`${s.type}_${s.level}_${s.sn}`}const jl={length:0,start:()=>0,end:()=>0};class se{static isBuffered(e,t){try{if(e){const i=se.getBuffered(e);for(let r=0;r<i.length;r++)if(t>=i.start(r)&&t<=i.end(r))return!0}}catch{}return!1}static bufferInfo(e,t,i){try{if(e){const r=se.getBuffered(e),n=[];let a;for(a=0;a<r.length;a++)n.push({start:r.start(a),end:r.end(a)});return this.bufferedInfo(n,t,i)}}catch{}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.sort(function(c,u){const h=c.start-u.start;return h||u.end-c.end});let r=[];if(i)for(let c=0;c<e.length;c++){const u=r.length;if(u){const h=r[u-1].end;e[c].start-h<i?e[c].end>h&&(r[u-1].end=e[c].end):r.push(e[c])}else r.push(e[c])}else r=e;let n=0,a,o=t,l=t;for(let c=0;c<r.length;c++){const u=r[c].start,h=r[c].end;if(t+i>=u&&t<h)o=u,l=h,n=l-t;else if(t+i<u){a=u;break}}return{len:n,start:o||0,end:l||0,nextStart:a}}static getBuffered(e){try{return e.buffered}catch(t){return S.log("failed to get media.buffered",t),jl}}}class Ui{constructor(e,t,i,r=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=Vt(),this.buffering={audio:Vt(),video:Vt(),audiovideo:Vt()},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=n,this.partial=a}}function Vt(){return{start:0,executeStart:0,executeEnd:0,end:0}}function Kt(s,e){for(let i=0,r=s.length;i<r;i++){var t;if(((t=s[i])==null?void 0:t.cc)===e)return s[i]}return null}function ql(s,e,t){return!!(e&&(t.endCC>t.startCC||s&&s.cc<t.startCC))}function Xl(s,e){const t=s.fragments,i=e.fragments;if(!i.length||!t.length){S.log("No fragments to align");return}const r=Kt(t,i[0].cc);if(!r||r&&!r.startPTS){S.log("No frag in previous level to align on");return}return r}function qr(s,e){if(s){const t=s.start+e;s.start=s.startPTS=t,s.endPTS=t+s.duration}}function Xr(s,e){const t=e.fragments;for(let i=0,r=t.length;i<r;i++)qr(t[i],s);e.fragmentHint&&qr(e.fragmentHint,s),e.alignedSliding=!0}function Zl(s,e,t){e&&(Ql(s,t,e),!t.alignedSliding&&e&&Wt(t,e),!t.alignedSliding&&e&&!t.skippedSegments&&$r(e,t))}function Ql(s,e,t){if(ql(s,t,e)){const i=Xl(t,e);i&&W(i.start)&&(S.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),Xr(i.start,e))}}function Wt(s,e){if(!s.hasProgramDateTime||!e.hasProgramDateTime)return;const t=s.fragments,i=e.fragments;if(!t.length||!i.length)return;let r,n;const a=Math.min(e.endCC,s.endCC);e.startCC<a&&s.startCC<a&&(r=Kt(i,a),n=Kt(t,a)),(!r||!n)&&(r=i[Math.floor(i.length/2)],n=Kt(t,r.cc)||t[Math.floor(t.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;const c=(l-o)/1e3-(n.start-r.start);Xr(c,s)}const Zr=Math.pow(2,17);class Jl{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 i=e.url;if(!i)return Promise.reject(new He({type:q.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){l(Jr(e));return}else e.gap=!1;const c=this.loader=e.loader=n?new n(r):new a(r),u=Qr(e),h=Kr(r.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Zr};e.stats=c.stats,c.load(u,d,{onSuccess:(f,m,g,y)=>{this.resetLoader(e,c);let v=f.data;g.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),o({frag:e,part:null,payload:v,networkDetails:y})},onError:(f,m,g,y)=>{this.resetLoader(e,c),l(new He({type:q.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:he({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:y}))},onAbort:(f,m,g)=>{this.resetLoader(e,c),l(new He({type:q.NETWORK_ERROR,details:_.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,m,g)=>{this.resetLoader(e,c),l(new He({type:q.NETWORK_ERROR,details:_.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:g,stats:f}))},onProgress:(f,m,g,y)=>{t&&t({frag:e,part:null,payload:g,networkDetails:y})}})})}loadPart(e,t,i){this.abort();const r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Jr(e,t));return}const c=this.loader=e.loader=n?new n(r):new a(r),u=Qr(e,t),h=Kr(r.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Zr};t.stats=c.stats,c.load(u,d,{onSuccess:(f,m,g,y)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:f.data,networkDetails:y};i(v),o(v)},onError:(f,m,g,y)=>{this.resetLoader(e,c),l(new He({type:q.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:he({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:y}))},onAbort:(f,m,g)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new He({type:q.NETWORK_ERROR,details:_.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,m,g)=>{this.resetLoader(e,c),l(new He({type:q.NETWORK_ERROR,details:_.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:g,stats:f}))}})})}updateStatsFromPart(e,t){const i=e.stats,r=t.stats,n=r.total;if(i.loaded+=r.loaded,n){const l=Math.round(e.duration/t.duration),c=Math.min(Math.round(i.loaded/n),l),h=(l-c)*Math.round(i.loaded/c);i.total=i.loaded+h}else i.total=Math.max(i.loaded,i.total);const a=i.loading,o=r.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Qr(s,e=null){const t=e||s,i={frag:s,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},r=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(W(r)&&W(n)){var a;let o=r,l=n;if(s.sn==="initSegment"&&((a=s.decryptdata)==null?void 0:a.method)==="AES-128"){const c=n-r;c%16&&(l=n+(16-c%16)),r!==0&&(i.resetIV=!0,o=r-16)}i.rangeStart=o,i.rangeEnd=l}return i}function Jr(s,e){const t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:q.MEDIA_ERROR,details:_.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=!0,new He(i)}class He extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class ec{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class tc{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function ic(s){const e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?Ze(s,0,e-t):s}class sc{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),i=new Uint32Array(4);for(let r=0;r<4;r++)i[r]=t.getUint32(r*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],n=i[1],a=i[2],o=i[3],l=this.invSubMix,c=l[0],u=l[1],h=l[2],d=l[3],f=new Uint32Array(256);let m=0,g=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=g^g<<1^g<<2^g<<3^g<<4;v=v>>>8^v&255^99,e[m]=v,t[v]=m;const T=f[m],x=f[T],L=f[x];let E=f[v]*257^v*16843008;r[m]=E<<24|E>>>8,n[m]=E<<16|E>>>16,a[m]=E<<8|E>>>24,o[m]=E,E=L*16843009^x*65537^T*257^m*16843008,c[v]=E<<24|E>>>8,u[v]=E<<16|E>>>16,h[v]=E<<8|E>>>24,d[v]=E,m?(m=T^f[f[f[L^T]]],g^=f[f[g]]):m=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,r=0;for(;r<t.length&&i;)i=t[r]===this.key[r],r++;if(i)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,l;const c=this.keySchedule=new Uint32Array(a),u=this.invKeySchedule=new Uint32Array(a),h=this.sBox,d=this.rcon,f=this.invSubMix,m=f[0],g=f[1],y=f[2],v=f[3];let T,x;for(o=0;o<a;o++){if(o<n){T=c[o]=t[o];continue}x=T,o%n===0?(x=x<<8|x>>>24,x=h[x>>>24]<<24|h[x>>>16&255]<<16|h[x>>>8&255]<<8|h[x&255],x^=d[o/n|0]<<24):n>6&&o%n===4&&(x=h[x>>>24]<<24|h[x>>>16&255]<<16|h[x>>>8&255]<<8|h[x&255]),c[o]=T=(c[o-n]^x)>>>0}for(l=0;l<a;l++)o=a-l,l&3?x=c[o]:x=c[o-4],l<4||o<=4?u[l]=x:u[l]=m[h[x>>>24]]^g[h[x>>>16&255]]^y[h[x>>>8&255]]^v[h[x&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const r=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],c=o[1],u=o[2],h=o[3],d=this.uint8ArrayToUint32Array_(i);let f=d[0],m=d[1],g=d[2],y=d[3];const v=new Int32Array(e),T=new Int32Array(v.length);let x,L,E,k,R,B,C,b,D,P,w,U,O,G;const F=this.networkToHostOrderSwap;for(;t<v.length;){for(D=F(v[t]),P=F(v[t+1]),w=F(v[t+2]),U=F(v[t+3]),R=D^n[0],B=U^n[1],C=w^n[2],b=P^n[3],O=4,G=1;G<r;G++)x=l[R>>>24]^c[B>>16&255]^u[C>>8&255]^h[b&255]^n[O],L=l[B>>>24]^c[C>>16&255]^u[b>>8&255]^h[R&255]^n[O+1],E=l[C>>>24]^c[b>>16&255]^u[R>>8&255]^h[B&255]^n[O+2],k=l[b>>>24]^c[R>>16&255]^u[B>>8&255]^h[C&255]^n[O+3],R=x,B=L,C=E,b=k,O=O+4;x=a[R>>>24]<<24^a[B>>16&255]<<16^a[C>>8&255]<<8^a[b&255]^n[O],L=a[B>>>24]<<24^a[C>>16&255]<<16^a[b>>8&255]<<8^a[R&255]^n[O+1],E=a[C>>>24]<<24^a[b>>16&255]<<16^a[R>>8&255]<<8^a[B&255]^n[O+2],k=a[b>>>24]<<24^a[R>>16&255]<<16^a[B>>8&255]<<8^a[C&255]^n[O+3],T[t]=F(x^f),T[t+1]=F(k^m),T[t+2]=F(E^g),T[t+3]=F(L^y),f=D,m=P,g=w,y=U,t=t+4}return T.buffer}}const rc=16;class Gi{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.useSoftware=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.subtle===null&&(this.useSoftware=!0)}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 i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?ic(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i){return this.useSoftware?new Promise((r,n)=>{this.softwareDecrypt(new Uint8Array(e),t,i);const a=this.flush();a?r(a.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i)}softwareDecrypt(e,t,i){const{currentIV:r,currentResult:n,remainderData:a}=this;this.logOnce("JS AES decrypt"),a&&(e=be(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;r&&(i=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new sc),l.expandKey(t);const c=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=Ze(o,-16).buffer,c||null}webCryptoDecrypt(e,t,i){const r=this.subtle;return(this.key!==t||!this.fastAesKey)&&(this.key=t,this.fastAesKey=new tc(r,t)),this.fastAesKey.expandKey().then(n=>r?(this.logOnce("WebCrypto AES decrypt"),new ec(r,new Uint8Array(i)).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(S.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i)))}onWebCryptoError(e,t,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i);const r=this.flush();if(r)return r.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%rc;return i!==e.length&&(t=Ze(e,0,i),this.remainderData=Ze(e,i)),t}logOnce(e){this.logEnabled&&(S.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const nc={toString:function(s){let e="";const t=s.length;for(let i=0;i<t;i++)e+=`[${s.start(i).toFixed(3)}-${s.end(i).toFixed(3)}]`;return e}},M={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 Hi extends zl{constructor(e,t,i,r,n){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=M.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.loadedmetadata=!1,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.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=n,this.logPrefix=r,this.log=S.log.bind(S,`${r}:`),this.warn=S.warn.bind(S,`${r}:`),this.hls=e,this.fragmentLoader=new Jl(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Gi(e.config),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){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=M.STOPPED}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;const i=t.partList;if(i!=null&&i.length){const n=i[i.length-1];return se.isBuffered(this.media,n.start+n.duration/2)}const r=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(r)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levelLastLoaded)==null?void 0:e.details}}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),i.addEventListener("seeking",this.onvseeking),i.addEventListener("ended",this.onvended);const r=this.config;this.levels&&r.autoStartLoad&&this.state===M.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(){const e=this.media;e!=null&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:t,media:i,mediaBuffer:r,state:n}=this,a=i?i.currentTime:0,o=se.bufferInfo(r||i,a,e.maxBufferHole);if(this.log(`media seeking to ${W(a)?a.toFixed(3):a}, state: ${n}`),this.state===M.ENDED)this.resetLoadingState();else if(t){const l=e.maxFragLookUpTolerance,c=t.start-l,u=t.start+t.duration+l;if(!o.len||u<o.start||c>o.end){const h=a>u;(a<c||h)&&(h&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}i&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),this.lastCurrentTime=a),!this.loadedmetadata&&!o.len&&(this.nextLoadPosition=this.startPosition=a),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=M.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,i){this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const r=n=>{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${n.part?" p: "+n.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,i,r).then(n=>{if(!n)return;const a=this.state;if(this.fragContextChanged(e)){(a===M.FRAG_LOADING||!this.fragCurrent&&a===M.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=M.IDLE);return}"payload"in n&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(p.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===M.STOPPED||this.state===M.ERROR||(this.warn(n),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===de.APPENDING){const n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength);this.reduceMaxBufferLength(o)&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===de.PARTIAL&&i.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)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const r={startOffset:e,endOffset:t,type:i};this.hls.trigger(p.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{if(!i||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:r}=this,{payload:n}=i,a=e.decryptdata;if(n&&n.byteLength>0&&a!=null&&a.key&&a.iv&&a.method==="AES-128"){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer).catch(l=>{throw r.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:e}),l}).then(l=>{const c=self.performance.now();return r.trigger(p.FRAG_DECRYPTED,{frag:e,payload:l,stats:{tstart:o,tdecrypt:c}}),i.payload=l,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===M.STOPPED||this.state===M.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state=M.IDLE,e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){var i,r,n,a;const o=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===j.MAIN?"level":"track"} ${e.level} (frag:[${((i=e.startPTS)!=null?i:NaN).toFixed(3)}-${((r=e.endPTS)!=null?r:NaN).toFixed(3)}] > buffer:${o?nc.toString(se.getBuffered(o)):"(detached)"})`),e.sn!=="initSegment"){var l;if(e.type!==j.SUBTITLE){const u=e.elementaryStreams;if(!Object.keys(u).some(h=>!!u[h])){this.state=M.IDLE;return}}const c=(l=this.levels)==null?void 0:l[e.level];c!=null&&c.fragmentError&&(this.log(`Resetting level fragment error count of ${c.fragmentError} on frag buffered`),c.fragmentError=0)}this.state=M.IDLE,o&&(!this.loadedmetadata&&e.type==j.MAIN&&o.buffered.length&&((n=this.fragCurrent)==null?void 0:n.sn)===((a=this.fragPrevious)==null?void 0:a.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:r,partsLoaded:n}=e,a=!n||n.length===0||n.some(l=>!l),o=new Ui(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,r){var n;const a=t==null?void 0: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)?(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${e.level}`),this.state=M.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(u=>{if(!this.fragContextChanged(u.frag))return this.hls.trigger(p.KEY_LOADED,u),this.state===M.KEY_LOADING&&(this.state=M.IDLE),u}),this.hls.trigger(p.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(e,a.encryptedFragments),i=Math.max(e.start,i||0),this.config.lowLatencyMode&&e.sn!=="initSegment"){const u=a.partList;if(u&&r){i>e.end&&a.fragmentHint&&(e=a.fragmentHint);const h=this.getNextPart(u,e,i);if(h>-1){const d=u[h];this.log(`Loading part sn: ${e.sn} p: ${d.index} cc: ${e.cc} of playlist [${a.startSN}-${a.endSN}] parts [0-${h}-${u.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=d.start+d.duration,this.state=M.FRAG_LOADING;let f;return o?f=o.then(m=>!m||this.fragContextChanged(m.frag)?null:this.doFragPartsLoad(e,d,t,r)).catch(m=>this.handleFragLoadError(m)):f=this.doFragPartsLoad(e,d,t,r).catch(m=>this.handleFragLoadError(m)),this.hls.trigger(p.FRAG_LOADING,{frag:e,part:d,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!e.url||this.loadedEndOfParts(u,i))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${a?"of ["+a.startSN+"-"+a.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),W(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=M.FRAG_LOADING;const l=this.config.progressive;let c;return l&&o?c=o.then(u=>!u||this.fragContextChanged(u==null?void 0:u.frag)?null:this.fragmentLoader.load(e,r)).catch(u=>this.handleFragLoadError(u)):c=Promise.all([this.fragmentLoader.load(e,l?r:void 0),o]).then(([u])=>(!l&&u&&r&&r(u),u)).catch(u=>this.handleFragLoadError(u)),this.hls.trigger(p.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,i,r){return new Promise((n,a)=>{var o;const l=[],c=(o=i.details)==null?void 0:o.partList,u=h=>{this.fragmentLoader.loadPart(e,h,r).then(d=>{l[h.index]=d;const f=d.part;this.hls.trigger(p.FRAG_LOADED,d);const m=Ur(i,e.sn,h.index+1)||Gr(c,e.sn,h.index+1);if(m)u(m);else return n({frag:e,part:f,partsLoaded:l})}).catch(a)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===_.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(p.ERROR,t)}else this.hls.trigger(p.ERROR,{type:q.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==M.PARSING){!this.fragCurrent&&this.state!==M.STOPPED&&this.state!==M.ERROR&&(this.state=M.IDLE);return}const{frag:i,part:r,level:n}=t,a=self.performance.now();i.stats.parsing.end=a,r&&(r.stats.parsing.end=a),this.updateLevelTiming(i,r,n,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:r,sn:n,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${n} of level ${r}. The current chunk will not be buffered.`),null;const o=t[r],l=a>-1?Ur(o,n,a):null,c=l?l.fragment:Dl(o,n,i);return c?(i&&i!==c&&(c.stats=i.stats),{frag:c,part:l,level:o}):null}bufferFragmentData(e,t,i,r,n){var a;if(!e||this.state!==M.PARSING)return;const{data1:o,data2:l}=e;let c=o;if(o&&l&&(c=be(o,l)),!((a=c)!=null&&a.length))return;const u={type:e.type,frag:t,part:i,chunkMeta:r,parent:t.type,data:c};if(this.hls.trigger(p.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!se.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,r=se.bufferInfo(t,i,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,r.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){const i=this.getLoadPosition();return W(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){const{config:{maxBufferHole:r}}=this,n=se.bufferInfo(e,t,r);if(n.len===0&&n.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&n.nextStart<a.end)return se.bufferInfo(e,t,Math.max(n.nextStart,r))}return n}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e){const t=this.config,i=e||t.maxBufferLength;return t.maxMaxBufferLength>=i?(t.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${t.maxMaxBufferLength}s`),!0):!1}getAppendedFrag(e,t=j.MAIN){const i=this.fragmentTracker.getAppendedFrag(e,j.MAIN);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,r=i.length;if(!r)return null;const{config:n}=this,a=i[0].start;let o;if(t.live){const l=n.initialLiveManifestSize;if(r<l)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${l})`),null;(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a)&&(o=this.getInitialLiveFragment(t,i),this.startPosition=this.nextLoadPosition=o?this.hls.liveSyncPosition||o.start:e)}else e<=a&&(o=i[0]);if(!o){const l=n.lowLatencyMode?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,l,t)}return this.mapToInitFragWhenRequired(o)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===de.OK||i===de.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,r,n){const a=e.gap,o=this.getNextFragment(this.nextLoadPosition,t);if(o===null)return o;if(e=o,a&&e&&!e.gap&&i.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r);if(l!==null&&i.len+l.len>=n)return this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let r=-1,n=!1,a=!0;for(let o=0,l=e.length;o<l;o++){const c=e[o];if(a=a&&!c.independent,r>-1&&i<c.start)break;const u=c.loaded;u?r=-1:(n||c.independent||a)&&c.fragment===t&&(r=o),n=u}return r}loadedEndOfParts(e,t){const i=e[e.length-1];return i&&t>i.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let r=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=Il(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){const a=t[n-e.startSN];i.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=kl(t,i.cc),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const n=this.hls.liveSyncPosition;n!==null&&(r=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,i){const{config:r}=this;let{fragPrevious:n}=this,{fragments:a,endSN:o}=i;const{fragmentHint:l}=i,c=r.maxFragLookUpTolerance,u=i.partList,h=!!(r.lowLatencyMode&&u!=null&&u.length&&l);h&&l&&!this.bitrateTest&&(a=a.concat(l),o=l.sn);let d;if(e<t){const f=e>t-c?0:c;d=Gt(n,a,e,f)}else d=a[a.length-1];if(d){const f=d.sn-i.startSN,m=this.fragmentTracker.getState(d);if((m===de.OK||m===de.PARTIAL&&d.gap)&&(n=d),n&&d.sn===n.sn&&(!h||u[0].fragment.sn>d.sn)&&n&&d.level===n.level){const y=a[f+1];d.sn<o&&this.fragmentTracker.getState(y)!==de.OK?d=y:d=null}}return d}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const r=this.hls.liveSyncPosition,n=i.currentTime,a=e.fragments[0].start,o=e.edge,l=n>=a-t.maxFragLookUpTolerance&&n<=o;if(r!==null&&i.duration>r&&(n<r||!l)){const c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!l&&i.readyState<4||n<o-c)&&(this.loadedmetadata||(this.nextLoadPosition=r),i.readyState&&(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r.toFixed(3)}`),i.currentTime=r))}}alignPlaylists(e,t,i){const r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const n=e.fragments[0].start,a=!t,o=e.alignedSliding&&W(n);if(a||!o&&!n){const{fragPrevious:l}=this;Zl(l,i,e);const c=e.fragments[0].start;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${l?l.sn:"na"} fragments: ${r}`),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 i=this.startPosition;if(i<t&&(i=-1),i===-1||this.lastCurrentTime===-1){const r=this.startTimeOffset!==null,n=r?this.startTimeOffset:e.startTimeOffset;n!==null&&W(n)?(i=t+n,n<0&&(i+=e.totalduration),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Start time offset ${n} found in ${r?"multivariant":"media"} playlist, adjust startPosition to ${i}`),this.startPosition=i):e.live?i=this.hls.liveSyncPosition||t:this.startPosition=i=0,this.lastCurrentTime=i}this.nextLoadPosition=i}getLoadPosition(){const{media:e}=this;let t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&e.sn!=="initSegment"&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==M.FRAG_LOADING_WAITING_RETRY)&&(this.state=M.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const u=this.getCurrentContext(t.chunkMeta);u&&(t.frag=u.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var r;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const n=t.details===_.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const a=t.errorAction,{action:o,retryCount:l=0,retryConfig:c}=a||{};if(a&&o===ge.RetryRequest&&c){this.resetStartWhenNotLoaded(this.levelLastLoaded);const u=Ni(c,l);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${l+1}/${c.maxNumRetry} in ${u}ms`),a.resolved=!0,this.retryDate=self.performance.now()+u,this.state=M.FRAG_LOADING_WAITING_RETRY}else if(c&&a)if(this.resetFragmentErrors(e),l<c.maxNumRetry)!n&&o!==ge.RemoveAlternatePermanently&&(a.resolved=!0);else{S.warn(`${t.details} reached or exceeded max retry (${l})`);return}else(a==null?void 0:a.action)===ge.SendAlternateToPenaltyBox?this.state=M.WAITING_LEVEL:this.state=M.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===M.PARSING||this.state===M.PARSED){const t=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,t),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${t} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===j.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==M.STOPPED&&(this.state=M.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const r=se.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===M.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=M.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=e?e.details:null;t!=null&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,r){var n;const a=i.details;if(!a){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,c)=>{const u=e.elementaryStreams[c];if(u){const h=u.endPTS-u.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${h})`),l||!1;const d=r?0:Br(a,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS);return this.hls.trigger(p.LEVEL_PTS_UPDATED,{details:a,level:i,drift:d,type:c,frag:e,start:u.startPTS,end:u.endPTS}),!0}return l},!1)&&((n=this.transmuxer)==null?void 0:n.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(i.fragmentError===0&&(i.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(l.message),this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=M.PARSED,this.hls.trigger(p.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}class en{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=ac(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function ac(s,e){const t=new Uint8Array(e);let i=0;for(let r=0;r<s.length;r++){const n=s[r];t.set(n,i),i+=n.length}return t}function oc(){return typeof __HLS_WORKER_BUNDLE__=="function"}function lc(){const s=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(s);return{worker:new self.Worker(e),objectURL:e}}function cc(s){const e=new self.URL(s,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}function Ne(s="",e=9e4){return{type:s,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Vi{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,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=be(this.cachedData,e),this.cachedData=null);let i=yt(e,0),r=i?i.length:0,n;const a=this._audioTrack,o=this._id3Track,l=i?bi(i):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&W(l))&&(this.basePTS=uc(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Ce.audioId3,duration:Number.POSITIVE_INFINITY});r<c;){if(this.canParse(e,r)){const u=this.appendFrame(a,e,r);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r+=u.length,n=r):r=c}else Po(e,r)?(i=yt(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Ce.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,n=r):r++;if(r===c&&n!==c){const u=Ze(e,n);this.cachedData?this.cachedData=be(this.cachedData,u):this.cachedData=u}}return{audioTrack:a,videoTrack:Ne(),id3Track:o,textTrack:Ne()}}demuxSampleAes(e,t,i){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:Ne(),id3Track:this._id3Track,textTrack:Ne()}}destroy(){}}const uc=(s,e,t)=>{if(W(s))return s*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};function hc(s,e,t,i){let r,n,a,o;const l=navigator.userAgent.toLowerCase(),c=i,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];r=((e[t+2]&192)>>>6)+1;const h=(e[t+2]&60)>>>2;if(h>u.length-1){const d=new Error(`invalid ADTS sampling index:${h}`);s.emit(p.ERROR,p.ERROR,{type:q.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!0,error:d,reason:d.message});return}return a=(e[t+2]&1)<<2,a|=(e[t+3]&192)>>>6,S.log(`manifest codec:${i}, ADTS type:${r}, samplingIndex:${h}`),/firefox/i.test(l)?h>=6?(r=5,o=new Array(4),n=h-3):(r=2,o=new Array(2),n=h):l.indexOf("android")!==-1?(r=2,o=new Array(2),n=h):(r=5,o=new Array(4),i&&(i.indexOf("mp4a.40.29")!==-1||i.indexOf("mp4a.40.5")!==-1)||!i&&h>=6?n=h-3:((i&&i.indexOf("mp4a.40.2")!==-1&&(h>=6&&a===1||/vivaldi/i.test(l))||!i&&a===1)&&(r=2,o=new Array(2)),n=h)),o[0]=r<<3,o[0]|=(h&14)>>1,o[1]|=(h&1)<<7,o[1]|=a<<3,r===5&&(o[1]|=(n&14)>>1,o[2]=(n&1)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:u[h],channelCount:a,codec:"mp4a.40."+r,manifestCodec:c}}function tn(s,e){return s[e]===255&&(s[e+1]&246)===240}function sn(s,e){return s[e+1]&1?7:9}function Ki(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function dc(s,e){return e+5<s.length}function zt(s,e){return e+1<s.length&&tn(s,e)}function fc(s,e){return dc(s,e)&&tn(s,e)&&Ki(s,e)<=s.length-e}function mc(s,e){if(zt(s,e)){const t=sn(s,e);if(e+t>=s.length)return!1;const i=Ki(s,e);if(i<=t)return!1;const r=e+i;return r===s.length||zt(s,r)}return!1}function rn(s,e,t,i,r){if(!s.samplerate){const n=hc(e,t,i,r);if(!n)return;s.config=n.config,s.samplerate=n.samplerate,s.channelCount=n.channelCount,s.codec=n.codec,s.manifestCodec=n.manifestCodec,S.log(`parsed codec:${s.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function nn(s){return 1024*9e4/s}function gc(s,e){const t=sn(s,e);if(e+t<=s.length){const i=Ki(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function an(s,e,t,i,r){const n=nn(s.samplerate),a=i+r*n,o=gc(e,t);let l;if(o){const{frameLength:h,headerLength:d}=o,f=d+h,m=Math.max(0,t+f-e.length);m?(l=new Uint8Array(f-d),l.set(e.subarray(t+d,e.length),0)):l=e.subarray(t+d,t+f);const g={unit:l,pts:a};return m||s.samples.push(g),{sample:g,length:f,missing:m}}const c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:c,missing:-1}}let Yt=null;const pc=[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],yc=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],vc=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],xc=[0,1,1,4];function on(s,e,t,i,r){if(t+24>e.length)return;const n=ln(e,t);if(n&&t+n.frameLength<=e.length){const a=n.samplesPerFrame*9e4/n.sampleRate,o=i+r*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return s.config=[],s.channelCount=n.channelCount,s.samplerate=n.sampleRate,s.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function ln(s,e){const t=s[e+1]>>3&3,i=s[e+1]>>1&3,r=s[e+2]>>4&15,n=s[e+2]>>2&3;if(t!==1&&r!==0&&r!==15&&n!==3){const a=s[e+2]>>1&1,o=s[e+3]>>6,l=t===3?3-i:i===3?3:4,c=pc[l*14+r-1]*1e3,h=yc[(t===3?0:t===2?1:2)*3+n],d=o===3?1:2,f=vc[t][i],m=xc[i],g=f*8*m,y=Math.floor(f*c/h+a)*m;if(Yt===null){const x=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Yt=x?parseInt(x[1]):0}return!!Yt&&Yt<=87&&i===2&&c>=224e3&&o===0&&(s[e+3]=s[e+3]|128),{sampleRate:h,channelCount:d,frameLength:y,samplesPerFrame:g}}}function Wi(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function cn(s,e){return e+1<s.length&&Wi(s,e)}function Tc(s,e){return Wi(s,e)&&4<=s.length-e}function un(s,e){if(e+1<s.length&&Wi(s,e)){const i=ln(s,e);let r=4;i!=null&&i.frameLength&&(r=i.frameLength);const n=e+r;return n===s.length||cn(s,n)}return!1}class Ec extends Vi{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=yt(e,0);let i=(t==null?void 0:t.length)||0;if(un(e,i))return!1;for(let r=e.length;i<r;i++)if(mc(e,i))return S.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return fc(e,t)}appendFrame(e,t,i){rn(e,this.observer,t,i,e.manifestCodec);const r=an(e,t,i,this.basePTS,this.frameIndex);if(r&&r.missing===0)return r}}const Sc=/\/emsg[-/]ID3/i;class bc{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,i,r){const n=this.videoTrack=Ne("video",1),a=this.audioTrack=Ne("audio",1),o=this.txtTrack=Ne("text",1);if(this.id3Track=Ne("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=dr(e);if(l.video){const{id:c,timescale:u,codec:h}=l.video;n.id=c,n.timescale=o.timescale=u,n.codec=h}if(l.audio){const{id:c,timescale:u,codec:h}=l.audio;a.id=c,a.timescale=u,a.codec=h}o.id=lr.text,n.sampleDuration=0,n.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return Ho(e)}demux(e,t){this.timeOffset=t;let i=e;const r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=be(this.remainderData,e));const o=Xo(i);this.remainderData=o.remainder,r.samples=o.valid||new Uint8Array}else r.samples=i;const a=this.extractID3Track(r,t);return n.samples=mr(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(t,this.timeOffset);return i.samples=mr(e,t),{videoTrack:t,audioTrack:Ne(),id3Track:r,textTrack:Ne()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const r=X(e.samples,["emsg"]);r&&r.forEach(n=>{const a=Jo(n);if(Sc.test(a.schemeIdUri)){const o=W(a.presentationTime)?a.presentationTime/a.timeScale:t+a.presentationTimeDelta/a.timeScale;let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=a.payload;i.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:Ce.emsg,duration:l})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}const hn=(s,e)=>{let t=0,i=5;e+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=s[e];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,t=t?t<<o|r[0]:r[0],e+=1,i-=o}return t};class Ac extends Vi{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const r=dn(e,t,i,this.basePTS,this.frameIndex);if(r!==-1)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;const t=yt(e,0);if(!t)return!1;const i=t.length;return e[i]===11&&e[i+1]===119&&bi(t)!==void 0&&hn(e,i)<16}}function dn(s,e,t,i,r){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],l=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][l*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,g=[2,1,2,3,3,4,4,5][h]+f,y=e[t+5]>>3,v=e[t+5]&7,T=new Uint8Array([n<<6|y<<1|v>>2,(v&3)<<6|h<<3|f<<2|l>>4,l<<4&224]),x=1536/o*9e4,L=i+r*x,E=e.subarray(t,t+u);return s.config=T,s.channelCount=g,s.samplerate=o,s.samples.push({unit:E,pts:L}),u}class Lc{constructor(){this.VideoSample=null}createVideoSample(e,t,i,r){return{key:e,frame:!1,pts:t,dts:i,units:[],debug:r,length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,r;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const n=i.units;r=n[n.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,r=i.length;if(r){const n=i[r-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}e.debug.length&&S.log(e.pts+"/"+e.dts+":"+e.debug)}}class fn{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,i=e.byteLength-t,r=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");r.set(e.subarray(i,i+n)),this.word=new DataView(r.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 i=this.word>>>32-t;if(e>32&&S.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?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){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)}skipScalingList(e){let t=8,i=8,r;for(let n=0;n<e;n++)i!==0&&(r=this.readEG(),i=(t+r+256)%256),t=i===0?t:i}readSPS(){let e=0,t=0,i=0,r=0,n,a,o;const l=this.readUByte.bind(this),c=this.readBits.bind(this),u=this.readUEG.bind(this),h=this.readBoolean.bind(this),d=this.skipBits.bind(this),f=this.skipEG.bind(this),m=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);l();const y=l();if(c(5),d(3),l(),m(),y===100||y===110||y===122||y===244||y===44||y===83||y===86||y===118||y===128){const k=u();if(k===3&&d(1),m(),m(),d(1),h())for(a=k!==3?8:12,o=0;o<a;o++)h()&&(o<6?g(16):g(64))}m();const v=u();if(v===0)u();else if(v===1)for(d(1),f(),f(),n=u(),o=0;o<n;o++)f();m(),d(1);const T=u(),x=u(),L=c(1);L===0&&d(1),d(1),h()&&(e=u(),t=u(),i=u(),r=u());let E=[1,1];if(h()&&h())switch(l()){case 1:E=[1,1];break;case 2:E=[12,11];break;case 3:E=[10,11];break;case 4:E=[16,11];break;case 5:E=[40,33];break;case 6:E=[24,11];break;case 7:E=[20,11];break;case 8:E=[32,11];break;case 9:E=[80,33];break;case 10:E=[18,11];break;case 11:E=[15,11];break;case 12:E=[64,33];break;case 13:E=[160,99];break;case 14:E=[4,3];break;case 15:E=[3,2];break;case 16:E=[2,1];break;case 255:{E=[l()<<8|l(),l()<<8|l()];break}}return{width:Math.ceil((T+1)*16-e*2-t*2),height:(2-L)*(x+1)*16-(L?2:4)*(i+r),pixelRatio:E}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class Rc extends Lc{parseAVCPES(e,t,i,r,n){const a=this.parseAVCNALu(e,i.data);let o=this.VideoSample,l,c=!1;i.data=null,o&&a.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"")),a.forEach(u=>{var h;switch(u.type){case 1:{let g=!1;l=!0;const y=u.data;if(c&&y.length>4){const v=new fn(y).readSliceType();(v===2||v===4||v===7||v===9)&&(g=!0)}if(g){var d;(d=o)!=null&&d.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.frame=!0,o.key=g;break}case 5:l=!0,(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.key=!0,o.frame=!0;break;case 6:{l=!0,gr(u.data,1,i.pts,t.samples);break}case 7:{var f,m;l=!0,c=!0;const g=u.data,v=new fn(g).readSPS();if(!e.sps||e.width!==v.width||e.height!==v.height||((f=e.pixelRatio)==null?void 0:f[0])!==v.pixelRatio[0]||((m=e.pixelRatio)==null?void 0:m[1])!==v.pixelRatio[1]){e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.sps=[g],e.duration=n;const T=g.subarray(1,4);let x="avc1.";for(let L=0;L<3;L++){let E=T[L].toString(16);E.length<2&&(E="0"+E),x+=E}e.codec=x}break}case 8:l=!0,e.pps=[u.data];break;case 9:l=!0,e.audFound=!0,o&&this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"");break;case 12:l=!0;break;default:l=!1,o&&(o.debug+="unknown NAL "+u.type+" ");break}o&&l&&o.units.push(u)}),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}parseAVCNALu(e,t){const i=t.byteLength;let r=e.naluState||0;const n=r,a=[];let o=0,l,c,u,h=-1,d=0;for(r===-1&&(h=0,d=t[0]&31,r=0,o=1);o<i;){if(l=t[o++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(c=o-r-1,h>=0){const f={data:t.subarray(h,c),type:d};a.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(n&&o<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),c>0&&(f.data=be(f.data,t.subarray(0,c)),f.state=0))}o<i?(u=t[o]&31,h=o,d=u,r=0):r=-1}else r=0}if(h>=0&&r>=0){const f={data:t.subarray(h,i),type:d,state:r};a.push(f)}if(a.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=be(f.data,t))}return e.naluState=r,a}}class Cc{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Gi(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,i){const r=e[t].unit;if(r.length<=16)return;const n=r.subarray(16,r.length-r.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);r.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)})}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let r=0;for(let n=32;n<e.length-16;n+=160,r+=16)i.set(e.subarray(n,n+16),r);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let r=0;for(let n=32;n<e.length-16;n+=160,r+=16)e.set(i.subarray(r,r+16),n);return e}decryptAvcSample(e,t,i,r,n){const a=pr(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r)})}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){r();return}const n=e[t].units;for(;!(i>=n.length);i++){const a=n[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,r,a),!this.decrypter.isSync()))return}}}}const fe=188;class ze{constructor(e,t,i){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._duration=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=i,this.videoParser=new Rc}static probe(e){const t=ze.syncOffset(e);return t>0&&S.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),t!==-1}static syncOffset(e){const t=e.length;let i=Math.min(fe*5,t-fe)+1,r=0;for(;r<i;){let n=!1,a=-1,o=0;for(let l=r;l<t;l+=fe)if(e[l]===71&&(t-l===fe||e[l+fe]===71)){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+fe*99,e.length-fe)+1)),n||(n=zi(e,l)===0),n&&o>1&&(a===0&&o>2||l+fe>i))return a}else{if(o)return-1;break}r++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:lr[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=ze.createTrack("video"),this._audioTrack=ze.createTrack("audio",r),this._id3Track=ze.createTrack("id3"),this._txtTrack=ze.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,this._duration=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,r=!1){i||(this.sampleAes=null);let n;const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,c=this._txtTrack;let u=a.pid,h=a.pesData,d=o.pid,f=l.pid,m=o.pesData,g=l.pesData,y=null,v=this.pmtParsed,T=this._pmtId,x=e.length;if(this.remainderData&&(e=be(this.remainderData,e),x=e.length,this.remainderData=null),x<fe&&!r)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};const L=Math.max(0,ze.syncOffset(e));x-=(x-L)%fe,x<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,x,e.buffer.byteLength-x));let E=0;for(let R=L;R<x;R+=fe)if(e[R]===71){const B=!!(e[R+1]&64),C=zi(e,R),b=(e[R+3]&48)>>4;let D;if(b>1){if(D=R+5+e[R+4],D===R+fe)continue}else D=R+4;switch(C){case u:B&&(h&&(n=lt(h))&&this.videoParser.parseAVCPES(a,c,n,!1,this._duration),h={data:[],size:0}),h&&(h.data.push(e.subarray(D,R+fe)),h.size+=R+fe-D);break;case d:if(B){if(m&&(n=lt(m)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n);break}m={data:[],size:0}}m&&(m.data.push(e.subarray(D,R+fe)),m.size+=R+fe-D);break;case f:B&&(g&&(n=lt(g))&&this.parseID3PES(l,n),g={data:[],size:0}),g&&(g.data.push(e.subarray(D,R+fe)),g.size+=R+fe-D);break;case 0:B&&(D+=e[D]+1),T=this._pmtId=Dc(e,D);break;case T:{B&&(D+=e[D]+1);const P=_c(e,D,this.typeSupported,i);u=P.videoPid,u>0&&(a.pid=u,a.segmentCodec=P.segmentVideoCodec),d=P.audioPid,d>0&&(o.pid=d,o.segmentCodec=P.segmentAudioCodec),f=P.id3Pid,f>0&&(l.pid=f),y!==null&&!v&&(S.warn(`MPEG-TS PMT found at ${R} after unknown PID '${y}'. Backtracking to sync byte @${L} to parse all TS packets.`),y=null,R=L-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=C;break}}else E++;if(E>0){const R=new Error(`Found ${E} TS packet/s that do not start with 0x47`);this.observer.emit(p.ERROR,p.ERROR,{type:q.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message})}a.pesData=h,o.pesData=m,l.pesData=g;const k={audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};return r&&this.extractRemainingSamples(k),k}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:i,id3Track:r,textTrack:n}=e,a=i.pesData,o=t.pesData,l=r.pesData;let c;if(a&&(c=lt(a))?(this.videoParser.parseAVCPES(i,n,c,!0,this._duration),i.pesData=null):i.pesData=a,o&&(c=lt(o))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,c);break;case"mp3":this.parseMPEGPES(t,c);break;case"ac3":this.parseAC3PES(t,c);break}t.pesData=null}else o!=null&&o.size&&S.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(c=lt(l))?(this.parseID3PES(r,c),r.pesData=null):r.pesData=l}demuxSampleAes(e,t,i){const r=this.demux(e,i,!0,!this.config.progressive),n=this.sampleAes=new Cc(this.observer,this.config,t);return this.decrypt(r,n)}decrypt(e,t){return new Promise(i=>{const{audioTrack:r,videoTrack:n}=e;r.samples&&r.segmentCodec==="aac"?t.decryptAacSamples(r.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{i(e)}):i(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{i(e)})})}destroy(){this._duration=0}parseAACPES(e,t){let i=0;const r=this.aacOverFlow;let n=t.data;if(r){this.aacOverFlow=null;const h=r.missing,d=r.sample.unit.byteLength;if(h===-1)n=be(r.sample.unit,n);else{const f=d-h;r.sample.unit.set(n.subarray(0,h),f),e.samples.push(r.sample),i=r.missing}}let a,o;for(a=i,o=n.length;a<o-1&&!zt(n,a);a++);if(a!==i){let h;const d=a<o-1;d?h=`AAC PES did not start with ADTS header,offset:${a}`:h="No ADTS header found in AAC PES";const f=new Error(h);if(S.warn(`parsing error: ${h}`),this.observer.emit(p.ERROR,p.ERROR,{type:q.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,levelRetry:d,error:f,reason:h}),!d)return}rn(e,this.observer,n,a,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(r){const h=nn(e.samplerate);l=r.sample.pts+h}else{S.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,u;for(;a<o;)if(u=an(e,n,a,l,c),a+=u.length,u.missing){this.aacOverFlow=u;break}else for(c++;a<o-1&&!zt(n,a);a++);}parseMPEGPES(e,t){const i=t.data,r=i.length;let n=0,a=0;const o=t.pts;if(o===void 0){S.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<r;)if(cn(i,a)){const l=on(e,i,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(e,t){{const i=t.data,r=t.pts;if(r===void 0){S.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const n=i.length;let a=0,o=0,l;for(;o<n&&(l=dn(e,i,o,r,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){S.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=oe({},t,{type:this._videoTrack?Ce.emsg:Ce.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function zi(s,e){return((s[e+1]&31)<<8)+s[e+2]}function Dc(s,e){return(s[e+10]&31)<<8|s[e+11]}function _c(s,e,t,i){const r={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},n=(s[e+1]&15)<<8|s[e+2],a=e+3+n-4,o=(s[e+10]&15)<<8|s[e+11];for(e+=12+o;e<a;){const l=zi(s,e),c=(s[e+3]&15)<<8|s[e+4];switch(s[e]){case 207:if(!i){Yi("ADTS AAC");break}case 15:r.audioPid===-1&&(r.audioPid=l);break;case 21:r.id3Pid===-1&&(r.id3Pid=l);break;case 219:if(!i){Yi("H.264");break}case 27:r.videoPid===-1&&(r.videoPid=l,r.segmentVideoCodec="avc");break;case 3:case 4:!t.mpeg&&!t.mp3?S.log("MPEG audio found, not supported in this browser"):r.audioPid===-1&&(r.audioPid=l,r.segmentAudioCodec="mp3");break;case 193:if(!i){Yi("AC-3");break}case 129:t.ac3?r.audioPid===-1&&(r.audioPid=l,r.segmentAudioCodec="ac3"):S.log("AC-3 audio found, not supported in this browser");break;case 6:if(r.audioPid===-1&&c>0){let u=e+5,h=c;for(;h>2;){switch(s[u]){case 106:t.ac3!==!0?S.log("AC-3 audio found, not supported in this browser for now"):(r.audioPid=l,r.segmentAudioCodec="ac3");break}const f=s[u+1]+2;u+=f,h-=f}}break;case 194:case 135:S.warn("Unsupported EC-3 in M2TS found");break;case 36:S.warn("Unsupported HEVC in M2TS found");break}e+=c+5}return r}function Yi(s){S.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function lt(s){let e=0,t,i,r,n,a;const o=s.data;if(!s||s.size===0)return null;for(;o[0].length<19&&o.length>1;)o[0]=be(o[0],o[1]),o.splice(1,1);if(t=o[0],(t[0]<<16)+(t[1]<<8)+t[2]===1){if(i=(t[4]<<8)+t[5],i&&i>s.size-6)return null;const c=t[7];c&192&&(n=(t[9]&14)*536870912+(t[10]&255)*4194304+(t[11]&254)*16384+(t[12]&255)*128+(t[13]&254)/2,c&64?(a=(t[14]&14)*536870912+(t[15]&255)*4194304+(t[16]&254)*16384+(t[17]&255)*128+(t[18]&254)/2,n-a>60*9e4&&(S.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=t[8];let u=r+9;if(s.size<=u)return null;s.size-=u;const h=new Uint8Array(s.size);for(let d=0,f=o.length;d<f;d++){t=o[d];let m=t.byteLength;if(u)if(u>m){u-=m;continue}else t=t.subarray(u),m-=u,u=0;h.set(t,e),e+=m}return i&&(i-=r+3),{data:h,pts:n,dts:a,len:i}}return null}class Ic extends Vi{resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=yt(e,0);let i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&bi(t)!==void 0&&hn(e,i)<=16)return!1;for(let r=e.length;i<r;i++)if(un(e,i))return S.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Tc(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return on(e,t,i,this.basePTS,this.frameIndex)}}class mn{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 Ye=Math.pow(2,32)-1;class A{static init(){A.types={avc1:[],avcC:[],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 A.types)A.types.hasOwnProperty(e)&&(A.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]),i=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]);A.HDLR_TYPES={video:t,audio:i};const r=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]);A.STTS=A.STSC=A.STCO=n,A.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),A.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),A.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),A.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]),l=new Uint8Array([0,0,0,1]);A.FTYP=A.box(A.types.ftyp,a,l,a,o),A.DINF=A.box(A.types.dinf,A.box(A.types.dref,r))}static box(e,...t){let i=8,r=t.length;const n=r;for(;r--;)i+=t[r].byteLength;const a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.set(e,4),r=0,i=8;r<n;r++)a.set(t[r],i),i+=t[r].byteLength;return a}static hdlr(e){return A.box(A.types.hdlr,A.HDLR_TYPES[e])}static mdat(e){return A.box(A.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(Ye+1)),r=Math.floor(t%(Ye+1));return A.box(A.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,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(e){return A.box(A.types.mdia,A.mdhd(e.timescale,e.duration),A.hdlr(e.type),A.minf(e))}static mfhd(e){return A.box(A.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"?A.box(A.types.minf,A.box(A.types.smhd,A.SMHD),A.DINF,A.stbl(e)):A.box(A.types.minf,A.box(A.types.vmhd,A.VMHD),A.DINF,A.stbl(e))}static moof(e,t,i){return A.box(A.types.moof,A.mfhd(e),A.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=A.trak(e[t]);return A.box.apply(null,[A.types.moov,A.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(A.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=A.trex(e[t]);return A.box.apply(null,[A.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(Ye+1)),r=Math.floor(t%(Ye+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,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&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 A.box(A.types.mvhd,n)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let r,n;for(r=0;r<t.length;r++)n=t[r].flags,i[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return A.box(A.types.sdtp,i)}static stbl(e){return A.box(A.types.stbl,A.stsd(e),A.box(A.types.stts,A.STTS),A.box(A.types.stsc,A.STSC),A.box(A.types.stsz,A.STSZ),A.box(A.types.stco,A.STCO))}static avc1(e){let t=[],i=[],r,n,a;for(r=0;r<e.sps.length;r++)n=e.sps[r],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(r=0;r<e.pps.length;r++)n=e.pps[r],a=n.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));const o=A.box(A.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,c=e.height,u=e.pixelRatio[0],h=e.pixelRatio[1];return A.box(A.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,l>>8&255,l&255,c>>8&255,c&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,A.box(A.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),A.box(A.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.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static audioStsd(e){const t=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return A.box(A.types.mp4a,A.audioStsd(e),A.box(A.types.esds,A.esds(e)))}static mp3(e){return A.box(A.types[".mp3"],A.audioStsd(e))}static ac3(e){return A.box(A.types["ac-3"],A.audioStsd(e),A.box(A.types.dac3,e.config))}static stsd(e){return e.type==="audio"?e.segmentCodec==="mp3"&&e.codec==="mp3"?A.box(A.types.stsd,A.STSD,A.mp3(e)):e.segmentCodec==="ac3"?A.box(A.types.stsd,A.STSD,A.ac3(e)):A.box(A.types.stsd,A.STSD,A.mp4a(e)):A.box(A.types.stsd,A.STSD,A.avc1(e))}static tkhd(e){const t=e.id,i=e.duration*e.timescale,r=e.width,n=e.height,a=Math.floor(i/(Ye+1)),o=Math.floor(i%(Ye+1));return A.box(A.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,r>>8&255,r&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){const i=A.sdtp(e),r=e.id,n=Math.floor(t/(Ye+1)),a=Math.floor(t%(Ye+1));return A.box(A.types.traf,A.box(A.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),A.box(A.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])),A.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,A.box(A.types.trak,A.tkhd(e),A.mdia(e))}static trex(e){const t=e.id;return A.box(A.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 i=e.samples||[],r=i.length,n=12+16*r,a=new Uint8Array(n);let o,l,c,u,h,d;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<r;o++)l=i[o],c=l.duration,u=l.size,h=l.flags,d=l.cts,a.set([c>>>24&255,c>>>16&255,c>>>8&255,c&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 A.box(A.types.trun,a)}static initSegment(e){A.types||A.init();const t=A.moov(e);return be(A.FTYP,t)}}A.types=void 0,A.HDLR_TYPES=void 0,A.STTS=void 0,A.STSC=void 0,A.STCO=void 0,A.STSZ=void 0,A.VMHD=void 0,A.SMHD=void 0,A.STSD=void 0,A.FTYP=void 0,A.DINF=void 0;const gn=9e4;function ji(s,e,t=1,i=!1){const r=s*e*t;return i?Math.round(r):r}function wc(s,e,t=1,i=!1){return ji(s,e,1/t,i)}function Et(s,e=!1){return ji(s,1e3,1/gn,e)}function kc(s,e=1){return ji(s,gn,1/e)}const Pc=10*1e3,pn=1024,Oc=1152,Fc=1536;let ct=null,qi=null;class jt{constructor(e,t,i,r=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,ct===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ct=a?parseInt(a[1]):0}if(qi===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);qi=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){S.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){S.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){S.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e.reduce((r,n)=>{const a=n.pts-r;return a<-4294967296?(t=!0,Ae(r,n.pts)):a>0?r:n.pts},e[0].pts);return t&&S.debug("PTS rollover detected"),i}remux(e,t,i,r,n,a,o,l){let c,u,h,d,f,m,g=n,y=n;const v=e.pid>-1,T=t.pid>-1,x=t.samples.length,L=e.samples.length>0,E=o&&x>0||x>1;if((!v||L)&&(!T||E)||this.ISGenerated||o){if(this.ISGenerated){var R,B,C,b;const U=this.videoTrackConfig;U&&(t.width!==U.width||t.height!==U.height||((R=t.pixelRatio)==null?void 0:R[0])!==((B=U.pixelRatio)==null?void 0:B[0])||((C=t.pixelRatio)==null?void 0:C[1])!==((b=U.pixelRatio)==null?void 0:b[1]))&&this.resetInitSegment()}else h=this.generateIS(e,t,n,a);const D=this.isVideoContiguous;let P=-1,w;if(E&&(P=Mc(t.samples),!D&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,P>0){S.warn(`[mp4-remuxer]: Dropped ${P} out of ${x} video samples due to a missing keyframe`);const U=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(P),t.dropped+=P,y+=(t.samples[0].pts-U)/t.inputTimeScale,w=y}else P===-1&&(S.warn(`[mp4-remuxer]: No keyframe found out of ${x} video samples`),m=!1);if(this.ISGenerated){if(L&&E){const U=this.getVideoStartPts(t.samples),G=(Ae(e.samples[0].pts,U)-U)/t.inputTimeScale;g+=Math.max(0,G),y+=Math.max(0,-G)}if(L){if(e.samplerate||(S.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),h=this.generateIS(e,t,n,a)),u=this.remuxAudio(e,g,this.isAudioContiguous,a,T||E||l===j.AUDIO?y:void 0),E){const U=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(S.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),h=this.generateIS(e,t,n,a)),c=this.remuxVideo(t,y,D,U)}}else E&&(c=this.remuxVideo(t,y,D,0));c&&(c.firstKeyFrame=P,c.independent=P!==-1,c.firstKeyFramePTS=w)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=yn(i,n,this._initPTS,this._initDTS)),r.samples.length&&(d=vn(r,n,this._initPTS))),{audio:u,video:c,initSegment:h,independent:m,text:d,id3:f}}generateIS(e,t,i,r){const n=e.samples,a=t.samples,o=this.typeSupported,l={},c=this._initPTS;let u=!c||r,h="audio/mp4",d,f,m;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}l.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):A.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(m=e.inputTimeScale,!c||m!==c.timescale?d=f=n[0].pts-Math.round(m*i):u=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:A.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(m=t.inputTimeScale,!c||m!==c.timescale){const g=this.getVideoStartPts(a),y=Math.round(m*i);f=Math.min(f,Ae(a[0].dts,g)-y),d=Math.min(d,g-y)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:d,timescale:m},this._initDTS={baseTime:f,timescale:m}):d=m=void 0,{tracks:l,initPTS:d,timescale:m}}remuxVideo(e,t,i,r){const n=e.inputTimeScale,a=e.samples,o=[],l=a.length,c=this._initPTS;let u=this.nextAvcDts,h=8,d=this.videoSampleDuration,f,m,g=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,v=!1;if(!i||u===null){const H=t*n,N=a[0].pts-Ae(a[0].dts,a[0].pts);ct&&u!==null&&Math.abs(H-N-u)<15e3?i=!0:u=H-N}const T=c.baseTime*n/c.timescale;for(let H=0;H<l;H++){const N=a[H];N.pts=Ae(N.pts-T,u),N.dts=Ae(N.dts-T,u),N.dts<a[H>0?H-1:H].dts&&(v=!0)}v&&a.sort(function(H,N){const J=H.dts-N.dts,Q=H.pts-N.pts;return J||Q}),f=a[0].dts,m=a[a.length-1].dts;const x=m-f,L=x?Math.round(x/(l-1)):d||e.inputTimeScale/30;if(i){const H=f-u,N=H>L,J=H<-1;if((N||J)&&(N?S.warn(`AVC: ${Et(H,!0)} ms (${H}dts) hole between fragments detected at ${t.toFixed(3)}`):S.warn(`AVC: ${Et(-H,!0)} ms (${H}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!J||u>=a[0].pts||ct)){f=u;const Q=a[0].pts-H;if(N)a[0].dts=f,a[0].pts=Q;else for(let ie=0;ie<a.length&&!(a[ie].dts>Q);ie++)a[ie].dts-=H,a[ie].pts-=H;S.log(`Video: Initial PTS/DTS adjusted: ${Et(Q,!0)}/${Et(f,!0)}, delta: ${Et(H,!0)} ms`)}}f=Math.max(0,f);let E=0,k=0,R=f;for(let H=0;H<l;H++){const N=a[H],J=N.units,Q=J.length;let ie=0;for(let le=0;le<Q;le++)ie+=J[le].data.length;k+=ie,E+=Q,N.length=ie,N.dts<R?(N.dts=R,R+=L/4|0||1):R=N.dts,g=Math.min(N.pts,g),y=Math.max(N.pts,y)}m=a[l-1].dts;const B=k+4*E+8;let C;try{C=new Uint8Array(B)}catch(H){this.observer.emit(p.ERROR,p.ERROR,{type:q.MUX_ERROR,details:_.REMUX_ALLOC_ERROR,fatal:!1,error:H,bytes:B,reason:`fail allocating video mdat ${B}`});return}const b=new DataView(C.buffer);b.setUint32(0,B),C.set(A.types.mdat,4);let D=!1,P=Number.POSITIVE_INFINITY,w=Number.POSITIVE_INFINITY,U=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let H=0;H<l;H++){const N=a[H],J=N.units;let Q=0;for(let me=0,pe=J.length;me<pe;me++){const Re=J[me],At=Re.data,As=Re.data.byteLength;b.setUint32(h,As),h+=4,C.set(At,h),h+=As,Q+=4+As}let ie;if(H<l-1)d=a[H+1].dts-N.dts,ie=a[H+1].pts-N.pts;else{const me=this.config,pe=H>0?N.dts-a[H-1].dts:L;if(ie=H>0?N.pts-a[H-1].pts:L,me.stretchShortVideoTrack&&this.nextAudioPts!==null){const Re=Math.floor(me.maxBufferHole*n),At=(r?g+r*n:this.nextAudioPts)-N.pts;At>Re?(d=At-pe,d<0?d=pe:D=!0,S.log(`[mp4-remuxer]: It is approximately ${At/90} ms to the next segment; using duration ${d/90} ms for the last video frame.`)):d=pe}else d=pe}const le=Math.round(N.pts-N.dts);P=Math.min(P,d),U=Math.max(U,d),w=Math.min(w,ie),O=Math.max(O,ie),o.push(new xn(N.key,d,Q,le))}if(o.length){if(ct){if(ct<70){const H=o[0].flags;H.dependsOn=2,H.isNonSync=0}}else if(qi&&O-w<U-P&&L/U<.025&&o[0].cts===0){S.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let H=f;for(let N=0,J=o.length;N<J;N++){const Q=H+o[N].duration,ie=H+o[N].cts;if(N<J-1){const le=Q+o[N+1].cts;o[N].duration=le-ie}else o[N].duration=N?o[N-1].duration:L;o[N].cts=0,H=Q}}}d=D||!d?L:d,this.nextAvcDts=u=m+d,this.videoSampleDuration=d,this.isVideoContiguous=!0;const G=A.moof(e.sequenceNumber++,f,oe({},e,{samples:o})),F="video",V={data1:G,data2:C,startPTS:g/n,endPTS:(y+d)/n,startDTS:f/n,endDTS:u/n,type:F,hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,V}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Oc;case"ac3":return Fc;default:return pn}}remuxAudio(e,t,i,r,n){const a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,l=a/o,c=this.getSamplesPerFrame(e),u=c*l,h=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],m=n!==void 0;let g=e.samples,y=d?0:8,v=this.nextAudioPts||-1;const T=t*a,x=h.baseTime*a/h.timescale;if(this.isAudioContiguous=i=i||g.length&&v>0&&(r&&Math.abs(T-v)<9e3||Math.abs(Ae(g[0].pts-x,T)-v)<20*u),g.forEach(function(G){G.pts=Ae(G.pts-x,T)}),!i||v<0){if(g=g.filter(G=>G.pts>=0),!g.length)return;n===0?v=0:r&&!m?v=Math.max(0,T):v=g[0].pts}if(e.segmentCodec==="aac"){const G=this.config.maxAudioFramesDrift;for(let F=0,V=v;F<g.length;F++){const H=g[F],N=H.pts,J=N-V,Q=Math.abs(1e3*J/a);if(J<=-G*u&&m)F===0&&(S.warn(`Audio frame @ ${(N/a).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*J/a)} ms.`),this.nextAudioPts=v=V=N);else if(J>=G*u&&Q<Pc&&m){let ie=Math.round(J/u);V=N-ie*u,V<0&&(ie--,V+=u),F===0&&(this.nextAudioPts=v=V),S.warn(`[mp4-remuxer]: Injecting ${ie} audio frame @ ${(V/a).toFixed(3)}s due to ${Math.round(1e3*J/a)} ms gap.`);for(let le=0;le<ie;le++){const me=Math.max(V,0);let pe=mn.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);pe||(S.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),pe=H.unit.subarray()),g.splice(F,0,{unit:pe,pts:me}),V+=u,F++}}H.pts=V,V+=u}}let L=null,E=null,k,R=0,B=g.length;for(;B--;)R+=g[B].unit.byteLength;for(let G=0,F=g.length;G<F;G++){const V=g[G],H=V.unit;let N=V.pts;if(E!==null){const Q=f[G-1];Q.duration=Math.round((N-E)/l)}else if(i&&e.segmentCodec==="aac"&&(N=v),L=N,R>0){R+=y;try{k=new Uint8Array(R)}catch(Q){this.observer.emit(p.ERROR,p.ERROR,{type:q.MUX_ERROR,details:_.REMUX_ALLOC_ERROR,fatal:!1,error:Q,bytes:R,reason:`fail allocating audio mdat ${R}`});return}d||(new DataView(k.buffer).setUint32(0,R),k.set(A.types.mdat,4))}else return;k.set(H,y);const J=H.byteLength;y+=J,f.push(new xn(!0,c,J,0)),E=N}const C=f.length;if(!C)return;const b=f[f.length-1];this.nextAudioPts=v=E+l*b.duration;const D=d?new Uint8Array(0):A.moof(e.sequenceNumber++,L/l,oe({},e,{samples:f}));e.samples=[];const P=L/a,w=v/a,O={data1:D,data2:k,startPTS:P,endPTS:w,startDTS:P,endDTS:w,type:"audio",hasAudio:!0,hasVideo:!1,nb:C};return this.isAudioContiguous=!0,O}remuxEmptyAudio(e,t,i,r){const n=e.inputTimeScale,a=e.samplerate?e.samplerate:n,o=n/a,l=this.nextAudioPts,c=this._initDTS,u=c.baseTime*9e4/c.timescale,h=(l!==null?l:r.startDTS*n)+u,d=r.endDTS*n+u,f=o*pn,m=Math.ceil((d-h)/f),g=mn.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(S.warn("[mp4-remuxer]: remux empty Audio"),!g){S.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const y=[];for(let v=0;v<m;v++){const T=h+v*f;y.push({unit:g,pts:T,dts:T})}return e.samples=y,this.remuxAudio(e,t,i,!1)}}function Ae(s,e){let t;if(e===null)return s;for(e<s?t=-8589934592:t=8589934592;Math.abs(s-e)>4294967296;)s+=t;return s}function Mc(s){for(let e=0;e<s.length;e++)if(s[e].key)return e;return-1}function yn(s,e,t,i){const r=s.samples.length;if(!r)return;const n=s.inputTimeScale;for(let o=0;o<r;o++){const l=s.samples[o];l.pts=Ae(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=Ae(l.dts-i.baseTime*n/i.timescale,e*n)/n}const a=s.samples;return s.samples=[],{samples:a}}function vn(s,e,t){const i=s.samples.length;if(!i)return;const r=s.inputTimeScale;for(let a=0;a<i;a++){const o=s.samples[a];o.pts=Ae(o.pts-t.baseTime*r/t.timescale,e*r)/r}s.samples.sort((a,o)=>a.pts-o.pts);const n=s.samples;return s.samples=[],{samples:n}}class xn{constructor(e,t,i,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=i,this.cts=r,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class Nc{constructor(){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}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(Wo(e,r)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const r=this.initData=dr(e);r.audio&&(t=Tn(r.audio,te.AUDIO)),r.video&&(i=Tn(r.video,te.VIDEO));const n={};r.audio&&r.video?n.audiovideo={container:"video/mp4",codec:t+","+i,initSegment:e,id:"main"}:r.audio?n.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:r.video?n.video={container:"video/mp4",codec:i,initSegment:e,id:"main"}:S.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(e,t,i,r,n,a){var o,l;let{initPTS:c,lastEndTime:u}=this;const h={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};W(u)||(u=this.lastEndTime=n||0);const d=t.samples;if(!(d!=null&&d.length))return h;const f={initPTS:void 0,timescale:1};let m=this.initData;if((o=m)!=null&&o.length||(this.generateInitSegment(d),m=this.initData),!((l=m)!=null&&l.length))return S.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),h;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const g=Yo(d,m),y=zo(m,d),v=y===null?n:y;(Bc(c,v,n,g)||f.timescale!==c.timescale&&a)&&(f.initPTS=v-n,c&&c.timescale===1&&S.warn(`Adjusting initPTS by ${f.initPTS-c.baseTime}`),this.initPTS=c={baseTime:f.initPTS,timescale:1});const T=e?v-c.baseTime/c.timescale:u,x=T+g;qo(m,d,c.baseTime/c.timescale),g>0?this.lastEndTime=x:(S.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const L=!!m.audio,E=!!m.video;let k="";L&&(k+="audio"),E&&(k+="video");const R={data1:d,startPTS:T,startDTS:T,endPTS:x,endDTS:x,type:k,hasAudio:L,hasVideo:E,nb:1,dropped:0};return h.audio=R.type==="audio"?R:void 0,h.video=R.type!=="audio"?R:void 0,h.initSegment=f,h.id3=yn(i,n,c,c),r.samples.length&&(h.text=vn(r,n,c)),h}}function Bc(s,e,t,i){if(s===null)return!0;const r=Math.max(i,1),n=e-s.baseTime/s.timescale;return Math.abs(n-t)>r}function Tn(s,e){const t=s==null?void 0:s.codec;if(t&&t.length>4)return t;if(e===te.AUDIO){if(t==="ec-3"||t==="ac-3"||t==="alac")return t;if(t==="fLaC"||t==="Opus")return Ft(t,!1);const i="mp4a.40.5";return S.info(`Parsed audio codec "${t}" or audio object type not handled. Using "${i}"`),i}return S.warn(`Unhandled video codec "${t}"`),t==="hvc1"||t==="hev1"?"hvc1.1.6.L120.90":t==="av01"?"av01.0.04M.08":"avc1.42e01e"}let Ve;try{Ve=self.performance.now.bind(self.performance)}catch{S.debug("Unable to use Performance API on this environment"),Ve=et==null?void 0:et.Date.now}const qt=[{demux:bc,remux:Nc},{demux:ze,remux:jt},{demux:Ec,remux:jt},{demux:Ic,remux:jt}];qt.splice(2,0,{demux:Ac,remux:jt});class En{constructor(e,t,i,r,n){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=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=i,this.vendor=r,this.id=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,r){const n=i.transmuxing;n.executeStart=Ve();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;r&&(this.currentTransmuxState=r);const{contiguous:c,discontinuity:u,trackSwitch:h,accurateTimeOffset:d,timeOffset:f,initSegmentChange:m}=r||o,{audioCodec:g,videoCodec:y,defaultInitPts:v,duration:T,initSegmentData:x}=l,L=$c(a,t);if(L&&L.method==="AES-128"){const B=this.getDecrypter();if(B.isSync()){let C=B.softwareDecrypt(a,L.key.buffer,L.iv.buffer);if(i.part>-1&&(C=B.flush()),!C)return n.executeEnd=Ve(),Xi(i);a=new Uint8Array(C)}else return this.decryptionPromise=B.webCryptoDecrypt(a,L.key.buffer,L.iv.buffer).then(C=>{const b=this.push(C,null,i);return this.decryptionPromise=null,b}),this.decryptionPromise}const E=this.needsProbing(u,h);if(E){const B=this.configureTransmuxer(a);if(B)return S.warn(`[transmuxer] ${B.message}`),this.observer.emit(p.ERROR,p.ERROR,{type:q.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:B,reason:B.message}),n.executeEnd=Ve(),Xi(i)}(u||h||m||E)&&this.resetInitSegment(x,g,y,T,t),(u||m||E)&&this.resetInitialTimestamp(v),c||this.resetContiguity();const k=this.transmux(a,L,f,d,i),R=this.currentTransmuxState;return R.contiguous=!0,R.discontinuity=!1,R.trackSwitch=!1,n.executeEnd=Ve(),k}flush(e){const t=e.transmuxing;t.executeStart=Ve();const{decrypter:i,currentTransmuxState:r,decryptionPromise:n}=this;if(n)return n.then(()=>this.flush(e));const a=[],{timeOffset:o}=r;if(i){const h=i.flush();h&&a.push(this.push(h,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c)return t.executeEnd=Ve(),[Xi(e)];const u=l.flush(o);return Xt(u)?u.then(h=>(this.flushRemux(a,h,e),a)):(this.flushRemux(a,u,e),a)}flushRemux(e,t,i){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;S.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const u=this.remuxer.remux(r,n,a,o,c,l,!0,this.id);e.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=Ve()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,r,n){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,i,r),o.resetInitSegment(e,t,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,r,n){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,r,n):a=this.transmuxUnencrypted(e,i,r,n),a}transmuxUnencrypted(e,t,i,r){const{audioTrack:n,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,a,o,l,t,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,i,r,n){return this.demuxer.demuxSampleAes(e,t,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,r,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:r,vendor:n}=this;let a;for(let d=0,f=qt.length;d<f;d++){var o;if((o=qt[d].demux)!=null&&o.probe(e)){a=qt[d];break}}if(!a)return new Error("Failed to find demuxer by probing fragment data");const l=this.demuxer,c=this.remuxer,u=a.remux,h=a.demux;(!c||!(c instanceof u))&&(this.remuxer=new u(i,t,r,n)),(!l||!(l instanceof h))&&(this.demuxer=new h(i,t,r),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Gi(this.config)),e}}function $c(s,e){let t=null;return s.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Xi=s=>({remuxResult:{},chunkMeta:s});function Xt(s){return"then"in s&&s.then instanceof Function}class Uc{constructor(e,t,i,r,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=i,this.duration=r,this.defaultInitPts=n||null}}class Gc{constructor(e,t,i,r,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=i,this.trackSwitch=r,this.timeOffset=n,this.initSegmentChange=a}}var Sn={exports:{}};(function(s){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function r(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function n(l,c,u,h,d){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new r(u,h||l,d),m=t?t+c:c;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],f]:l._events[m].push(f):(l._events[m]=f,l._eventsCount++),l}function a(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,h;if(this._eventsCount===0)return c;for(h in u=this._events)e.call(u,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var d=0,f=h.length,m=new Array(f);d<f;d++)m[d]=h[d].fn;return m},o.prototype.listenerCount=function(c){var u=t?t+c:c,h=this._events[u];return h?h.fn?1:h.length:0},o.prototype.emit=function(c,u,h,d,f,m){var g=t?t+c:c;if(!this._events[g])return!1;var y=this._events[g],v=arguments.length,T,x;if(y.fn){switch(y.once&&this.removeListener(c,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,m),!0}for(x=1,T=new Array(v-1);x<v;x++)T[x-1]=arguments[x];y.fn.apply(y.context,T)}else{var L=y.length,E;for(x=0;x<L;x++)switch(y[x].once&&this.removeListener(c,y[x].fn,void 0,!0),v){case 1:y[x].fn.call(y[x].context);break;case 2:y[x].fn.call(y[x].context,u);break;case 3:y[x].fn.call(y[x].context,u,h);break;case 4:y[x].fn.call(y[x].context,u,h,d);break;default:if(!T)for(E=1,T=new Array(v-1);E<v;E++)T[E-1]=arguments[E];y[x].fn.apply(y[x].context,T)}}return!0},o.prototype.on=function(c,u,h){return n(this,c,u,h,!1)},o.prototype.once=function(c,u,h){return n(this,c,u,h,!0)},o.prototype.removeListener=function(c,u,h,d){var f=t?t+c:c;if(!this._events[f])return this;if(!u)return a(this,f),this;var m=this._events[f];if(m.fn)m.fn===u&&(!d||m.once)&&(!h||m.context===h)&&a(this,f);else{for(var g=0,y=[],v=m.length;g<v;g++)(m[g].fn!==u||d&&!m[g].once||h&&m[g].context!==h)&&y.push(m[g]);y.length?this._events[f]=y.length===1?y[0]:y:a(this,f)}return this},o.prototype.removeAllListeners=function(c){var u;return c?(u=t?t+c:c,this._events[u]&&a(this,u)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,s.exports=o})(Sn);var Hc=Sn.exports,Zi=ho(Hc);class bn{constructor(e,t,i,r){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;const a=(u,h)=>{h=h||{},h.frag=this.frag,h.id=this.id,u===p.ERROR&&(this.error=h.error),this.hls.trigger(u,h)};this.observer=new Zi,this.observer.on(p.FRAG_DECRYPTED,a),this.observer.on(p.ERROR,a);const o=tt(n.preferManagedMediaSource)||{isTypeSupported:()=>!1},l={mpeg:o.isTypeSupported("audio/mpeg"),mp3:o.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:o.isTypeSupported('audio/mp4; codecs="ac-3"')},c=navigator.vendor;if(this.useWorker&&typeof Worker!="undefined"&&(n.workerPath||oc())){try{n.workerPath?(S.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=cc(n.workerPath)):(S.log(`injecting Web Worker for "${t}"`),this.workerContext=lc()),this.onwmsg=d=>this.onWorkerMessage(d);const{worker:h}=this.workerContext;h.addEventListener("message",this.onwmsg),h.onerror=d=>{const f=new Error(`${d.message} (${d.filename}:${d.lineno})`);n.enableWorker=!1,S.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(p.ERROR,{type:q.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:f})},h.postMessage({cmd:"init",typeSupported:l,vendor:c,id:t,config:JSON.stringify(n)})}catch(h){S.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.resetWorker(),this.error=null,this.transmuxer=new En(this.observer,l,n,c,t)}return}this.transmuxer=new En(this.observer,l,n,c,t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,i,r,n,a,o,l,c,u){var h,d;c.transmuxing.start=self.performance.now();const{transmuxer:f}=this,m=a?a.start:n.start,g=n.decryptdata,y=this.frag,v=!(y&&n.cc===y.cc),T=!(y&&c.level===y.level),x=y?c.sn-y.sn:-1,L=this.part?c.part-this.part.index:-1,E=x===0&&c.id>1&&c.id===(y==null?void 0:y.stats.chunkCount),k=!T&&(x===1||x===0&&(L===1||E&&L<=0)),R=self.performance.now();(T||x||n.stats.parsing.start===0)&&(n.stats.parsing.start=R),a&&(L||!k)&&(a.stats.parsing.start=R);const B=!(y&&((h=n.initSegment)==null?void 0:h.url)===((d=y.initSegment)==null?void 0:d.url)),C=new Gc(v,k,l,T,m,B);if(!k||v||B){S.log(`[transmuxer-interface, ${n.type}]: Starting new transmux session for sn: ${c.sn} p: ${c.part} level: ${c.level} id: ${c.id}
8
+ Switching to level ${D} @ ${P|0} bps`),r.trigger(p.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:i,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(S.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 Ol(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(p.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,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 i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var r;this.fragCurrent=i,this.partCurrent=(r=t.part)!=null?r: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 _.BUFFER_ADD_CODEC_ERROR:case _.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case _.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:r,partCurrent:n}=this;if(i&&r&&i.sn===r.sn&&i.level===r.level){const a=performance.now(),o=n?n.stats:i.stats,l=a-o.loading.start,c=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&c>-1){const h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(h,c),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,r){const n=e+i/t,a=r?this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){const i=this.hls.config,{loading:r}=t.stats,n=r.end-r.start;W(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}onFragLoaded(e,{frag:t,part:i}){const r=i?i.stats:t.stats;if(t.type===j.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const n=i?i.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+r.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){const n={stats:r,frag:t,part:i,id:t.type};this.onFragBuffered(p.FRAG_BUFFERED,n),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:r}=t,n=r!=null&&r.stats.loaded?r.stats:i.stats;if(n.aborted||this.ignoreFragment(i))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(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==j.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,n=this.findBestLevel(i,t,e,0,r,1,1);if(n>-1)return n;const a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return S.warn(`[abr] 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,i=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const n=i&&r?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:i}=this,{maxAutoLevel:r,config:n,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let u=n.abrBandWidthFactor,h=n.abrBandWidthUpFactor;if(c){const y=this.findBestLevel(l,a,r,c,0,u,h);if(y>=0)return y}let d=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!c){const y=this.bitrateTestDelay;y&&(d=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-y,S.info(`[abr] 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(l,a,r,c,d,u,h);if(S.info(`[abr] ${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`),f>-1)return f;const m=i.levels[a],g=i.levels[i.loadLevel];return(m==null?void 0:m.bitrate)<(g==null?void 0:g.bitrate)?a:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,r,n,a,o){var l;const c=r+n,u=this.lastLoadedFragLevel,h=u===-1?this.hls.firstLevel:u,{fragCurrent:d,partCurrent:f}=this,{levels:m,allAudioTracks:g,loadLevel:y,config:v}=this.hls;if(m.length===1)return 0;const T=m[h],x=!!(T!=null&&(l=T.details)!=null&&l.live),L=y===-1||u===-1;let E,k="SDR",R=(T==null?void 0:T.frameRate)||0;const{audioPreference:B,videoPreference:C}=v,b=this.audioTracksByGroup||(this.audioTracksByGroup=Gl(g));if(L){if(this.firstSelection!==-1)return this.firstSelection;const O=this.codecTiers||(this.codecTiers=Hl(m,b,t,i)),U=Ul(O,k,e,B,C),{codecSet:F,videoRanges:V,minFramerate:H,minBitrate:N,preferHDR:J}=U;E=F,k=J?V[V.length-1]:V[0],R=H,e=Math.max(e,N),S.log(`[abr] picked start tier ${JSON.stringify(U)}`)}else E=T==null?void 0:T.codecSet,k=T==null?void 0:T.videoRange;const D=f?f.duration:d?d.duration:0,P=this.bwEstimator.getEstimateTTFB()/1e3,w=[];for(let O=i;O>=t;O--){var $;const U=m[O],F=O>h;if(!U)continue;if(v.useMediaCapabilities&&!U.supportedResult&&!U.supportedPromise){const le=navigator.mediaCapabilities;typeof(le==null?void 0:le.decodingInfo)=="function"&&Fl(U,b,k,R,e,B)?(U.supportedPromise=Ml(U,b,le),U.supportedPromise.then(me=>{if(!this.hls)return;U.supportedResult=me;const pe=this.hls.levels,Re=pe.indexOf(U);me.error?S.warn(`[abr] MediaCapabilities decodingInfo error: "${me.error}" for level ${Re} ${JSON.stringify(me)}`):me.supported||(S.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${Re} ${JSON.stringify(me)}`),Re>-1&&pe.length>1&&(S.log(`[abr] Removing unsupported level ${Re}`),this.hls.removeLevel(Re)))})):U.supportedResult=zr}if(E&&U.codecSet!==E||k&&U.videoRange!==k||F&&R>U.frameRate||!F&&R>0&&R<U.frameRate||U.supportedResult&&!(($=U.supportedResult.decodingInfoResults)!=null&&$[0].smooth)){w.push(O);continue}const V=U.details,H=(f?V==null?void 0:V.partTarget:V==null?void 0:V.averagetargetduration)||D;let N;F?N=o*e:N=a*e;const J=D&&r>=D*2&&n===0?m[O].averageBitrate:m[O].maxBitrate,Q=this.getTimeToLoadFrag(P,N,J*H,V===void 0);if(N>=J&&(O===u||U.loadError===0&&U.fragmentError===0)&&(Q<=P||!W(Q)||x&&!this.bitrateTestDelay||Q<c)){const le=this.forcedAutoLevel;return O!==y&&(le===-1||le!==y)&&(w.length&&S.trace(`[abr] Skipped level(s) ${w.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${m[w[0]].codecs}" ${m[w[0]].videoRange}; not compatible with "${T.codecs}" ${k}`),S.info(`[abr] switch candidate:${h}->${O} adjustedbw(${Math.round(N)})-bitrate=${Math.round(N-J)} ttfb:${P.toFixed(1)} avgDuration:${H.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${Q.toFixed(1)} firstSelection:${L} codecSet:${E} videoRange:${k} hls.loadLevel:${y}`)),L&&(this.firstSelection=O),O}}return-1}set nextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls,r=Math.min(Math.max(e,i),t);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}}class zl{constructor(){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(){}}var de={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Yl{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.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let r=i.length;r--;){const n=i[r];if(!n)break;const a=n.end;if(n.start<=e&&a!==null&&e<=a)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const a=i[r[n]];if((a==null?void 0:a.body.type)===t&&a.buffered){const o=a.body;if(o.start<=e&&e<=o.end)return o}}return null}detectEvictedFragments(e,t,i,r){this.timeRanges&&(this.timeRanges[e]=t);const n=(r==null?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o||n>=o.body.sn)return;if(!o.buffered&&!o.loaded){o.body.type===i&&this.removeFragment(o.body);return}const l=o.range[e];l&&l.time.some(c=>{const u=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return u&&this.removeFragment(o.body),u})})}detectPartialFragments(e){const t=this.timeRanges,{frag:i,part:r}=e;if(!t||i.sn==="initSegment")return;const n=ot(i),a=this.fragments[n];if(!a||a.buffered&&i.gap)return;const o=!i.relurl;Object.keys(t).forEach(l=>{const c=i.elementaryStreams[l];if(!c)return;const u=t[l],h=o||c.partial===!0;a.range[l]=this.getBufferedTimes(i,r,h,u)}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=i.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),Ht(a)||this.removeParts(i.sn-1,i.type)):this.removeFragment(a.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=i.filter(r=>r.fragment.sn>=e))}fragBuffered(e,t){const i=ot(e);let r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(e,t,i,r){const n={time:[],partial:i},a=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||a;for(let u=0;u<r.length;u++){const h=r.start(u)-this.bufferPadding,d=r.end(u)+this.bufferPadding;if(c>=h&&l<=d){n.time.push({startPTS:Math.max(a,r.start(u)),endPTS:Math.min(o,r.end(u))});break}else if(a<d&&o>h){const f=Math.max(a,r.start(u)),m=Math.min(o,r.end(u));m>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:m}))}else if(o<=h)break}return n}getPartialFragment(e){let t=null,i,r,n,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{const u=l[c];u&&Ht(u)&&(r=u.body.start-o,n=u.body.end+o,e>=r&&e<=n&&(i=Math.min(e-r,n-e),a<=i&&(t=u.body,a=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Ht(t))}getState(e){const t=ot(e),i=this.fragments[t];return i?i.buffered?Ht(i)?de.PARTIAL:de.OK:de.APPENDING:de.NOT_LOADED}isTimeBuffered(e,t,i){let r,n;for(let a=0;a<i.length;a++){if(r=i.start(a)-this.bufferPadding,n=i.end(a)+this.bufferPadding,e>=r&&t<=n)return!0;if(t<=r)return!1}return!1}onFragLoaded(e,t){const{frag:i,part:r}=t;if(i.sn==="initSegment"||i.bitrateTest)return;const n=r?null:t,a=ot(i);this.fragments[a]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:r,timeRanges:n}=t;if(i.sn==="initSegment")return;const a=i.type;if(r){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(r)}this.timeRanges=n,Object.keys(n).forEach(o=>{const l=n[o];this.detectEvictedFragments(o,l,a,r)})}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=ot(e);return!!this.fragments[t]}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,r,n){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==i||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(e){const t=ot(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const r=e.sn;this.activePartLists[e.type]=i.filter(n=>n.fragment.sn!==r)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function Ht(s){var e,t,i;return s.buffered&&(s.body.gap||((e=s.range.video)==null?void 0:e.partial)||((t=s.range.audio)==null?void 0:t.partial)||((i=s.range.audiovideo)==null?void 0:i.partial))}function ot(s){return`${s.type}_${s.level}_${s.sn}`}const jl={length:0,start:()=>0,end:()=>0};class se{static isBuffered(e,t){try{if(e){const i=se.getBuffered(e);for(let r=0;r<i.length;r++)if(t>=i.start(r)&&t<=i.end(r))return!0}}catch{}return!1}static bufferInfo(e,t,i){try{if(e){const r=se.getBuffered(e),n=[];let a;for(a=0;a<r.length;a++)n.push({start:r.start(a),end:r.end(a)});return this.bufferedInfo(n,t,i)}}catch{}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.sort(function(c,u){const h=c.start-u.start;return h||u.end-c.end});let r=[];if(i)for(let c=0;c<e.length;c++){const u=r.length;if(u){const h=r[u-1].end;e[c].start-h<i?e[c].end>h&&(r[u-1].end=e[c].end):r.push(e[c])}else r.push(e[c])}else r=e;let n=0,a,o=t,l=t;for(let c=0;c<r.length;c++){const u=r[c].start,h=r[c].end;if(t+i>=u&&t<h)o=u,l=h,n=l-t;else if(t+i<u){a=u;break}}return{len:n,start:o||0,end:l||0,nextStart:a}}static getBuffered(e){try{return e.buffered}catch(t){return S.log("failed to get media.buffered",t),jl}}}class Ui{constructor(e,t,i,r=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=Vt(),this.buffering={audio:Vt(),video:Vt(),audiovideo:Vt()},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=n,this.partial=a}}function Vt(){return{start:0,executeStart:0,executeEnd:0,end:0}}function Kt(s,e){for(let i=0,r=s.length;i<r;i++){var t;if(((t=s[i])==null?void 0:t.cc)===e)return s[i]}return null}function ql(s,e,t){return!!(e&&(t.endCC>t.startCC||s&&s.cc<t.startCC))}function Xl(s,e){const t=s.fragments,i=e.fragments;if(!i.length||!t.length){S.log("No fragments to align");return}const r=Kt(t,i[0].cc);if(!r||r&&!r.startPTS){S.log("No frag in previous level to align on");return}return r}function qr(s,e){if(s){const t=s.start+e;s.start=s.startPTS=t,s.endPTS=t+s.duration}}function Xr(s,e){const t=e.fragments;for(let i=0,r=t.length;i<r;i++)qr(t[i],s);e.fragmentHint&&qr(e.fragmentHint,s),e.alignedSliding=!0}function Zl(s,e,t){e&&(Ql(s,t,e),!t.alignedSliding&&e&&Wt(t,e),!t.alignedSliding&&e&&!t.skippedSegments&&$r(e,t))}function Ql(s,e,t){if(ql(s,t,e)){const i=Xl(t,e);i&&W(i.start)&&(S.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),Xr(i.start,e))}}function Wt(s,e){if(!s.hasProgramDateTime||!e.hasProgramDateTime)return;const t=s.fragments,i=e.fragments;if(!t.length||!i.length)return;let r,n;const a=Math.min(e.endCC,s.endCC);e.startCC<a&&s.startCC<a&&(r=Kt(i,a),n=Kt(t,a)),(!r||!n)&&(r=i[Math.floor(i.length/2)],n=Kt(t,r.cc)||t[Math.floor(t.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;const c=(l-o)/1e3-(n.start-r.start);Xr(c,s)}const Zr=Math.pow(2,17);class Jl{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 i=e.url;if(!i)return Promise.reject(new Ge({type:q.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){l(Jr(e));return}else e.gap=!1;const c=this.loader=e.loader=n?new n(r):new a(r),u=Qr(e),h=Kr(r.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Zr};e.stats=c.stats,c.load(u,d,{onSuccess:(f,m,g,y)=>{this.resetLoader(e,c);let v=f.data;g.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),o({frag:e,part:null,payload:v,networkDetails:y})},onError:(f,m,g,y)=>{this.resetLoader(e,c),l(new Ge({type:q.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:he({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:y}))},onAbort:(f,m,g)=>{this.resetLoader(e,c),l(new Ge({type:q.NETWORK_ERROR,details:_.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,m,g)=>{this.resetLoader(e,c),l(new Ge({type:q.NETWORK_ERROR,details:_.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:g,stats:f}))},onProgress:(f,m,g,y)=>{t&&t({frag:e,part:null,payload:g,networkDetails:y})}})})}loadPart(e,t,i){this.abort();const r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Jr(e,t));return}const c=this.loader=e.loader=n?new n(r):new a(r),u=Qr(e,t),h=Kr(r.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Zr};t.stats=c.stats,c.load(u,d,{onSuccess:(f,m,g,y)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:f.data,networkDetails:y};i(v),o(v)},onError:(f,m,g,y)=>{this.resetLoader(e,c),l(new Ge({type:q.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:he({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:y}))},onAbort:(f,m,g)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new Ge({type:q.NETWORK_ERROR,details:_.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,m,g)=>{this.resetLoader(e,c),l(new Ge({type:q.NETWORK_ERROR,details:_.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:g,stats:f}))}})})}updateStatsFromPart(e,t){const i=e.stats,r=t.stats,n=r.total;if(i.loaded+=r.loaded,n){const l=Math.round(e.duration/t.duration),c=Math.min(Math.round(i.loaded/n),l),h=(l-c)*Math.round(i.loaded/c);i.total=i.loaded+h}else i.total=Math.max(i.loaded,i.total);const a=i.loading,o=r.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Qr(s,e=null){const t=e||s,i={frag:s,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},r=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(W(r)&&W(n)){var a;let o=r,l=n;if(s.sn==="initSegment"&&((a=s.decryptdata)==null?void 0:a.method)==="AES-128"){const c=n-r;c%16&&(l=n+(16-c%16)),r!==0&&(i.resetIV=!0,o=r-16)}i.rangeStart=o,i.rangeEnd=l}return i}function Jr(s,e){const t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:q.MEDIA_ERROR,details:_.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=!0,new Ge(i)}class Ge extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class ec{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class tc{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function ic(s){const e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?Ze(s,0,e-t):s}class sc{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),i=new Uint32Array(4);for(let r=0;r<4;r++)i[r]=t.getUint32(r*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],n=i[1],a=i[2],o=i[3],l=this.invSubMix,c=l[0],u=l[1],h=l[2],d=l[3],f=new Uint32Array(256);let m=0,g=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=g^g<<1^g<<2^g<<3^g<<4;v=v>>>8^v&255^99,e[m]=v,t[v]=m;const T=f[m],x=f[T],L=f[x];let E=f[v]*257^v*16843008;r[m]=E<<24|E>>>8,n[m]=E<<16|E>>>16,a[m]=E<<8|E>>>24,o[m]=E,E=L*16843009^x*65537^T*257^m*16843008,c[v]=E<<24|E>>>8,u[v]=E<<16|E>>>16,h[v]=E<<8|E>>>24,d[v]=E,m?(m=T^f[f[f[L^T]]],g^=f[f[g]]):m=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,r=0;for(;r<t.length&&i;)i=t[r]===this.key[r],r++;if(i)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,l;const c=this.keySchedule=new Uint32Array(a),u=this.invKeySchedule=new Uint32Array(a),h=this.sBox,d=this.rcon,f=this.invSubMix,m=f[0],g=f[1],y=f[2],v=f[3];let T,x;for(o=0;o<a;o++){if(o<n){T=c[o]=t[o];continue}x=T,o%n===0?(x=x<<8|x>>>24,x=h[x>>>24]<<24|h[x>>>16&255]<<16|h[x>>>8&255]<<8|h[x&255],x^=d[o/n|0]<<24):n>6&&o%n===4&&(x=h[x>>>24]<<24|h[x>>>16&255]<<16|h[x>>>8&255]<<8|h[x&255]),c[o]=T=(c[o-n]^x)>>>0}for(l=0;l<a;l++)o=a-l,l&3?x=c[o]:x=c[o-4],l<4||o<=4?u[l]=x:u[l]=m[h[x>>>24]]^g[h[x>>>16&255]]^y[h[x>>>8&255]]^v[h[x&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const r=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],c=o[1],u=o[2],h=o[3],d=this.uint8ArrayToUint32Array_(i);let f=d[0],m=d[1],g=d[2],y=d[3];const v=new Int32Array(e),T=new Int32Array(v.length);let x,L,E,k,R,B,C,b,D,P,w,$,O,U;const F=this.networkToHostOrderSwap;for(;t<v.length;){for(D=F(v[t]),P=F(v[t+1]),w=F(v[t+2]),$=F(v[t+3]),R=D^n[0],B=$^n[1],C=w^n[2],b=P^n[3],O=4,U=1;U<r;U++)x=l[R>>>24]^c[B>>16&255]^u[C>>8&255]^h[b&255]^n[O],L=l[B>>>24]^c[C>>16&255]^u[b>>8&255]^h[R&255]^n[O+1],E=l[C>>>24]^c[b>>16&255]^u[R>>8&255]^h[B&255]^n[O+2],k=l[b>>>24]^c[R>>16&255]^u[B>>8&255]^h[C&255]^n[O+3],R=x,B=L,C=E,b=k,O=O+4;x=a[R>>>24]<<24^a[B>>16&255]<<16^a[C>>8&255]<<8^a[b&255]^n[O],L=a[B>>>24]<<24^a[C>>16&255]<<16^a[b>>8&255]<<8^a[R&255]^n[O+1],E=a[C>>>24]<<24^a[b>>16&255]<<16^a[R>>8&255]<<8^a[B&255]^n[O+2],k=a[b>>>24]<<24^a[R>>16&255]<<16^a[B>>8&255]<<8^a[C&255]^n[O+3],T[t]=F(x^f),T[t+1]=F(k^m),T[t+2]=F(E^g),T[t+3]=F(L^y),f=D,m=P,g=w,y=$,t=t+4}return T.buffer}}const rc=16;class Gi{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.useSoftware=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.subtle===null&&(this.useSoftware=!0)}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 i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?ic(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i){return this.useSoftware?new Promise((r,n)=>{this.softwareDecrypt(new Uint8Array(e),t,i);const a=this.flush();a?r(a.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i)}softwareDecrypt(e,t,i){const{currentIV:r,currentResult:n,remainderData:a}=this;this.logOnce("JS AES decrypt"),a&&(e=be(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;r&&(i=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new sc),l.expandKey(t);const c=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=Ze(o,-16).buffer,c||null}webCryptoDecrypt(e,t,i){const r=this.subtle;return(this.key!==t||!this.fastAesKey)&&(this.key=t,this.fastAesKey=new tc(r,t)),this.fastAesKey.expandKey().then(n=>r?(this.logOnce("WebCrypto AES decrypt"),new ec(r,new Uint8Array(i)).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(S.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i)))}onWebCryptoError(e,t,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i);const r=this.flush();if(r)return r.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%rc;return i!==e.length&&(t=Ze(e,0,i),this.remainderData=Ze(e,i)),t}logOnce(e){this.logEnabled&&(S.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const nc={toString:function(s){let e="";const t=s.length;for(let i=0;i<t;i++)e+=`[${s.start(i).toFixed(3)}-${s.end(i).toFixed(3)}]`;return e}},M={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 Hi extends zl{constructor(e,t,i,r,n){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=M.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.loadedmetadata=!1,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.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=n,this.logPrefix=r,this.log=S.log.bind(S,`${r}:`),this.warn=S.warn.bind(S,`${r}:`),this.hls=e,this.fragmentLoader=new Jl(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Gi(e.config),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){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=M.STOPPED}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;const i=t.partList;if(i!=null&&i.length){const n=i[i.length-1];return se.isBuffered(this.media,n.start+n.duration/2)}const r=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(r)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levelLastLoaded)==null?void 0:e.details}}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),i.addEventListener("seeking",this.onvseeking),i.addEventListener("ended",this.onvended);const r=this.config;this.levels&&r.autoStartLoad&&this.state===M.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(){const e=this.media;e!=null&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:t,media:i,mediaBuffer:r,state:n}=this,a=i?i.currentTime:0,o=se.bufferInfo(r||i,a,e.maxBufferHole);if(this.log(`media seeking to ${W(a)?a.toFixed(3):a}, state: ${n}`),this.state===M.ENDED)this.resetLoadingState();else if(t){const l=e.maxFragLookUpTolerance,c=t.start-l,u=t.start+t.duration+l;if(!o.len||u<o.start||c>o.end){const h=a>u;(a<c||h)&&(h&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}i&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),this.lastCurrentTime=a),!this.loadedmetadata&&!o.len&&(this.nextLoadPosition=this.startPosition=a),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=M.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,i){this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const r=n=>{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${n.part?" p: "+n.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,i,r).then(n=>{if(!n)return;const a=this.state;if(this.fragContextChanged(e)){(a===M.FRAG_LOADING||!this.fragCurrent&&a===M.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=M.IDLE);return}"payload"in n&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(p.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===M.STOPPED||this.state===M.ERROR||(this.warn(n),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===de.APPENDING){const n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength);this.reduceMaxBufferLength(o)&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===de.PARTIAL&&i.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)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const r={startOffset:e,endOffset:t,type:i};this.hls.trigger(p.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{if(!i||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:r}=this,{payload:n}=i,a=e.decryptdata;if(n&&n.byteLength>0&&a!=null&&a.key&&a.iv&&a.method==="AES-128"){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer).catch(l=>{throw r.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:e}),l}).then(l=>{const c=self.performance.now();return r.trigger(p.FRAG_DECRYPTED,{frag:e,payload:l,stats:{tstart:o,tdecrypt:c}}),i.payload=l,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===M.STOPPED||this.state===M.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state=M.IDLE,e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){var i,r,n,a;const o=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===j.MAIN?"level":"track"} ${e.level} (frag:[${((i=e.startPTS)!=null?i:NaN).toFixed(3)}-${((r=e.endPTS)!=null?r:NaN).toFixed(3)}] > buffer:${o?nc.toString(se.getBuffered(o)):"(detached)"})`),e.sn!=="initSegment"){var l;if(e.type!==j.SUBTITLE){const u=e.elementaryStreams;if(!Object.keys(u).some(h=>!!u[h])){this.state=M.IDLE;return}}const c=(l=this.levels)==null?void 0:l[e.level];c!=null&&c.fragmentError&&(this.log(`Resetting level fragment error count of ${c.fragmentError} on frag buffered`),c.fragmentError=0)}this.state=M.IDLE,o&&(!this.loadedmetadata&&e.type==j.MAIN&&o.buffered.length&&((n=this.fragCurrent)==null?void 0:n.sn)===((a=this.fragPrevious)==null?void 0:a.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:r,partsLoaded:n}=e,a=!n||n.length===0||n.some(l=>!l),o=new Ui(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,r){var n;const a=t==null?void 0: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)?(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${e.level}`),this.state=M.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(u=>{if(!this.fragContextChanged(u.frag))return this.hls.trigger(p.KEY_LOADED,u),this.state===M.KEY_LOADING&&(this.state=M.IDLE),u}),this.hls.trigger(p.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(e,a.encryptedFragments),i=Math.max(e.start,i||0),this.config.lowLatencyMode&&e.sn!=="initSegment"){const u=a.partList;if(u&&r){i>e.end&&a.fragmentHint&&(e=a.fragmentHint);const h=this.getNextPart(u,e,i);if(h>-1){const d=u[h];this.log(`Loading part sn: ${e.sn} p: ${d.index} cc: ${e.cc} of playlist [${a.startSN}-${a.endSN}] parts [0-${h}-${u.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=d.start+d.duration,this.state=M.FRAG_LOADING;let f;return o?f=o.then(m=>!m||this.fragContextChanged(m.frag)?null:this.doFragPartsLoad(e,d,t,r)).catch(m=>this.handleFragLoadError(m)):f=this.doFragPartsLoad(e,d,t,r).catch(m=>this.handleFragLoadError(m)),this.hls.trigger(p.FRAG_LOADING,{frag:e,part:d,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!e.url||this.loadedEndOfParts(u,i))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${a?"of ["+a.startSN+"-"+a.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),W(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=M.FRAG_LOADING;const l=this.config.progressive;let c;return l&&o?c=o.then(u=>!u||this.fragContextChanged(u==null?void 0:u.frag)?null:this.fragmentLoader.load(e,r)).catch(u=>this.handleFragLoadError(u)):c=Promise.all([this.fragmentLoader.load(e,l?r:void 0),o]).then(([u])=>(!l&&u&&r&&r(u),u)).catch(u=>this.handleFragLoadError(u)),this.hls.trigger(p.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,i,r){return new Promise((n,a)=>{var o;const l=[],c=(o=i.details)==null?void 0:o.partList,u=h=>{this.fragmentLoader.loadPart(e,h,r).then(d=>{l[h.index]=d;const f=d.part;this.hls.trigger(p.FRAG_LOADED,d);const m=Ur(i,e.sn,h.index+1)||Gr(c,e.sn,h.index+1);if(m)u(m);else return n({frag:e,part:f,partsLoaded:l})}).catch(a)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===_.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(p.ERROR,t)}else this.hls.trigger(p.ERROR,{type:q.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==M.PARSING){!this.fragCurrent&&this.state!==M.STOPPED&&this.state!==M.ERROR&&(this.state=M.IDLE);return}const{frag:i,part:r,level:n}=t,a=self.performance.now();i.stats.parsing.end=a,r&&(r.stats.parsing.end=a),this.updateLevelTiming(i,r,n,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:r,sn:n,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${n} of level ${r}. The current chunk will not be buffered.`),null;const o=t[r],l=a>-1?Ur(o,n,a):null,c=l?l.fragment:Dl(o,n,i);return c?(i&&i!==c&&(c.stats=i.stats),{frag:c,part:l,level:o}):null}bufferFragmentData(e,t,i,r,n){var a;if(!e||this.state!==M.PARSING)return;const{data1:o,data2:l}=e;let c=o;if(o&&l&&(c=be(o,l)),!((a=c)!=null&&a.length))return;const u={type:e.type,frag:t,part:i,chunkMeta:r,parent:t.type,data:c};if(this.hls.trigger(p.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!se.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,r=se.bufferInfo(t,i,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,r.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){const i=this.getLoadPosition();return W(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){const{config:{maxBufferHole:r}}=this,n=se.bufferInfo(e,t,r);if(n.len===0&&n.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&n.nextStart<a.end)return se.bufferInfo(e,t,Math.max(n.nextStart,r))}return n}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e){const t=this.config,i=e||t.maxBufferLength;return t.maxMaxBufferLength>=i?(t.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${t.maxMaxBufferLength}s`),!0):!1}getAppendedFrag(e,t=j.MAIN){const i=this.fragmentTracker.getAppendedFrag(e,j.MAIN);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,r=i.length;if(!r)return null;const{config:n}=this,a=i[0].start;let o;if(t.live){const l=n.initialLiveManifestSize;if(r<l)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${l})`),null;(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a)&&(o=this.getInitialLiveFragment(t,i),this.startPosition=this.nextLoadPosition=o?this.hls.liveSyncPosition||o.start:e)}else e<=a&&(o=i[0]);if(!o){const l=n.lowLatencyMode?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,l,t)}return this.mapToInitFragWhenRequired(o)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===de.OK||i===de.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,r,n){const a=e.gap,o=this.getNextFragment(this.nextLoadPosition,t);if(o===null)return o;if(e=o,a&&e&&!e.gap&&i.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r);if(l!==null&&i.len+l.len>=n)return this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let r=-1,n=!1,a=!0;for(let o=0,l=e.length;o<l;o++){const c=e[o];if(a=a&&!c.independent,r>-1&&i<c.start)break;const u=c.loaded;u?r=-1:(n||c.independent||a)&&c.fragment===t&&(r=o),n=u}return r}loadedEndOfParts(e,t){const i=e[e.length-1];return i&&t>i.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let r=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=Il(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){const a=t[n-e.startSN];i.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=kl(t,i.cc),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const n=this.hls.liveSyncPosition;n!==null&&(r=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,i){const{config:r}=this;let{fragPrevious:n}=this,{fragments:a,endSN:o}=i;const{fragmentHint:l}=i,c=r.maxFragLookUpTolerance,u=i.partList,h=!!(r.lowLatencyMode&&u!=null&&u.length&&l);h&&l&&!this.bitrateTest&&(a=a.concat(l),o=l.sn);let d;if(e<t){const f=e>t-c?0:c;d=Gt(n,a,e,f)}else d=a[a.length-1];if(d){const f=d.sn-i.startSN,m=this.fragmentTracker.getState(d);if((m===de.OK||m===de.PARTIAL&&d.gap)&&(n=d),n&&d.sn===n.sn&&(!h||u[0].fragment.sn>d.sn)&&n&&d.level===n.level){const y=a[f+1];d.sn<o&&this.fragmentTracker.getState(y)!==de.OK?d=y:d=null}}return d}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const r=this.hls.liveSyncPosition,n=i.currentTime,a=e.fragments[0].start,o=e.edge,l=n>=a-t.maxFragLookUpTolerance&&n<=o;if(r!==null&&i.duration>r&&(n<r||!l)){const c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!l&&i.readyState<4||n<o-c)&&(this.loadedmetadata||(this.nextLoadPosition=r),i.readyState&&(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r.toFixed(3)}`),i.currentTime=r))}}alignPlaylists(e,t,i){const r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const n=e.fragments[0].start,a=!t,o=e.alignedSliding&&W(n);if(a||!o&&!n){const{fragPrevious:l}=this;Zl(l,i,e);const c=e.fragments[0].start;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${l?l.sn:"na"} fragments: ${r}`),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 i=this.startPosition;if(i<t&&(i=-1),i===-1||this.lastCurrentTime===-1){const r=this.startTimeOffset!==null,n=r?this.startTimeOffset:e.startTimeOffset;n!==null&&W(n)?(i=t+n,n<0&&(i+=e.totalduration),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Start time offset ${n} found in ${r?"multivariant":"media"} playlist, adjust startPosition to ${i}`),this.startPosition=i):e.live?i=this.hls.liveSyncPosition||t:this.startPosition=i=0,this.lastCurrentTime=i}this.nextLoadPosition=i}getLoadPosition(){const{media:e}=this;let t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&e.sn!=="initSegment"&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==M.FRAG_LOADING_WAITING_RETRY)&&(this.state=M.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const u=this.getCurrentContext(t.chunkMeta);u&&(t.frag=u.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var r;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const n=t.details===_.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const a=t.errorAction,{action:o,retryCount:l=0,retryConfig:c}=a||{};if(a&&o===ge.RetryRequest&&c){this.resetStartWhenNotLoaded(this.levelLastLoaded);const u=Ni(c,l);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${l+1}/${c.maxNumRetry} in ${u}ms`),a.resolved=!0,this.retryDate=self.performance.now()+u,this.state=M.FRAG_LOADING_WAITING_RETRY}else if(c&&a)if(this.resetFragmentErrors(e),l<c.maxNumRetry)!n&&o!==ge.RemoveAlternatePermanently&&(a.resolved=!0);else{S.warn(`${t.details} reached or exceeded max retry (${l})`);return}else(a==null?void 0:a.action)===ge.SendAlternateToPenaltyBox?this.state=M.WAITING_LEVEL:this.state=M.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===M.PARSING||this.state===M.PARSED){const t=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,t),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${t} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===j.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==M.STOPPED&&(this.state=M.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const r=se.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===M.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=M.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=e?e.details:null;t!=null&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,r){var n;const a=i.details;if(!a){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,c)=>{const u=e.elementaryStreams[c];if(u){const h=u.endPTS-u.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${h})`),l||!1;const d=r?0:Br(a,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS);return this.hls.trigger(p.LEVEL_PTS_UPDATED,{details:a,level:i,drift:d,type:c,frag:e,start:u.startPTS,end:u.endPTS}),!0}return l},!1)&&((n=this.transmuxer)==null?void 0:n.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(i.fragmentError===0&&(i.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(l.message),this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=M.PARSED,this.hls.trigger(p.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}class en{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=ac(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function ac(s,e){const t=new Uint8Array(e);let i=0;for(let r=0;r<s.length;r++){const n=s[r];t.set(n,i),i+=n.length}return t}function oc(){return typeof __HLS_WORKER_BUNDLE__=="function"}function lc(){const s=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(s);return{worker:new self.Worker(e),objectURL:e}}function cc(s){const e=new self.URL(s,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}function Ne(s="",e=9e4){return{type:s,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Vi{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,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=be(this.cachedData,e),this.cachedData=null);let i=yt(e,0),r=i?i.length:0,n;const a=this._audioTrack,o=this._id3Track,l=i?bi(i):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&W(l))&&(this.basePTS=uc(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Ce.audioId3,duration:Number.POSITIVE_INFINITY});r<c;){if(this.canParse(e,r)){const u=this.appendFrame(a,e,r);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r+=u.length,n=r):r=c}else Po(e,r)?(i=yt(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Ce.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,n=r):r++;if(r===c&&n!==c){const u=Ze(e,n);this.cachedData?this.cachedData=be(this.cachedData,u):this.cachedData=u}}return{audioTrack:a,videoTrack:Ne(),id3Track:o,textTrack:Ne()}}demuxSampleAes(e,t,i){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:Ne(),id3Track:this._id3Track,textTrack:Ne()}}destroy(){}}const uc=(s,e,t)=>{if(W(s))return s*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};function hc(s,e,t,i){let r,n,a,o;const l=navigator.userAgent.toLowerCase(),c=i,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];r=((e[t+2]&192)>>>6)+1;const h=(e[t+2]&60)>>>2;if(h>u.length-1){const d=new Error(`invalid ADTS sampling index:${h}`);s.emit(p.ERROR,p.ERROR,{type:q.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!0,error:d,reason:d.message});return}return a=(e[t+2]&1)<<2,a|=(e[t+3]&192)>>>6,S.log(`manifest codec:${i}, ADTS type:${r}, samplingIndex:${h}`),/firefox/i.test(l)?h>=6?(r=5,o=new Array(4),n=h-3):(r=2,o=new Array(2),n=h):l.indexOf("android")!==-1?(r=2,o=new Array(2),n=h):(r=5,o=new Array(4),i&&(i.indexOf("mp4a.40.29")!==-1||i.indexOf("mp4a.40.5")!==-1)||!i&&h>=6?n=h-3:((i&&i.indexOf("mp4a.40.2")!==-1&&(h>=6&&a===1||/vivaldi/i.test(l))||!i&&a===1)&&(r=2,o=new Array(2)),n=h)),o[0]=r<<3,o[0]|=(h&14)>>1,o[1]|=(h&1)<<7,o[1]|=a<<3,r===5&&(o[1]|=(n&14)>>1,o[2]=(n&1)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:u[h],channelCount:a,codec:"mp4a.40."+r,manifestCodec:c}}function tn(s,e){return s[e]===255&&(s[e+1]&246)===240}function sn(s,e){return s[e+1]&1?7:9}function Ki(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function dc(s,e){return e+5<s.length}function zt(s,e){return e+1<s.length&&tn(s,e)}function fc(s,e){return dc(s,e)&&tn(s,e)&&Ki(s,e)<=s.length-e}function mc(s,e){if(zt(s,e)){const t=sn(s,e);if(e+t>=s.length)return!1;const i=Ki(s,e);if(i<=t)return!1;const r=e+i;return r===s.length||zt(s,r)}return!1}function rn(s,e,t,i,r){if(!s.samplerate){const n=hc(e,t,i,r);if(!n)return;s.config=n.config,s.samplerate=n.samplerate,s.channelCount=n.channelCount,s.codec=n.codec,s.manifestCodec=n.manifestCodec,S.log(`parsed codec:${s.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function nn(s){return 1024*9e4/s}function gc(s,e){const t=sn(s,e);if(e+t<=s.length){const i=Ki(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function an(s,e,t,i,r){const n=nn(s.samplerate),a=i+r*n,o=gc(e,t);let l;if(o){const{frameLength:h,headerLength:d}=o,f=d+h,m=Math.max(0,t+f-e.length);m?(l=new Uint8Array(f-d),l.set(e.subarray(t+d,e.length),0)):l=e.subarray(t+d,t+f);const g={unit:l,pts:a};return m||s.samples.push(g),{sample:g,length:f,missing:m}}const c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:c,missing:-1}}let Yt=null;const pc=[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],yc=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],vc=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],xc=[0,1,1,4];function on(s,e,t,i,r){if(t+24>e.length)return;const n=ln(e,t);if(n&&t+n.frameLength<=e.length){const a=n.samplesPerFrame*9e4/n.sampleRate,o=i+r*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return s.config=[],s.channelCount=n.channelCount,s.samplerate=n.sampleRate,s.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function ln(s,e){const t=s[e+1]>>3&3,i=s[e+1]>>1&3,r=s[e+2]>>4&15,n=s[e+2]>>2&3;if(t!==1&&r!==0&&r!==15&&n!==3){const a=s[e+2]>>1&1,o=s[e+3]>>6,l=t===3?3-i:i===3?3:4,c=pc[l*14+r-1]*1e3,h=yc[(t===3?0:t===2?1:2)*3+n],d=o===3?1:2,f=vc[t][i],m=xc[i],g=f*8*m,y=Math.floor(f*c/h+a)*m;if(Yt===null){const x=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Yt=x?parseInt(x[1]):0}return!!Yt&&Yt<=87&&i===2&&c>=224e3&&o===0&&(s[e+3]=s[e+3]|128),{sampleRate:h,channelCount:d,frameLength:y,samplesPerFrame:g}}}function Wi(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function cn(s,e){return e+1<s.length&&Wi(s,e)}function Tc(s,e){return Wi(s,e)&&4<=s.length-e}function un(s,e){if(e+1<s.length&&Wi(s,e)){const i=ln(s,e);let r=4;i!=null&&i.frameLength&&(r=i.frameLength);const n=e+r;return n===s.length||cn(s,n)}return!1}class Ec extends Vi{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=yt(e,0);let i=(t==null?void 0:t.length)||0;if(un(e,i))return!1;for(let r=e.length;i<r;i++)if(mc(e,i))return S.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return fc(e,t)}appendFrame(e,t,i){rn(e,this.observer,t,i,e.manifestCodec);const r=an(e,t,i,this.basePTS,this.frameIndex);if(r&&r.missing===0)return r}}const Sc=/\/emsg[-/]ID3/i;class bc{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,i,r){const n=this.videoTrack=Ne("video",1),a=this.audioTrack=Ne("audio",1),o=this.txtTrack=Ne("text",1);if(this.id3Track=Ne("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=dr(e);if(l.video){const{id:c,timescale:u,codec:h}=l.video;n.id=c,n.timescale=o.timescale=u,n.codec=h}if(l.audio){const{id:c,timescale:u,codec:h}=l.audio;a.id=c,a.timescale=u,a.codec=h}o.id=lr.text,n.sampleDuration=0,n.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return Ho(e)}demux(e,t){this.timeOffset=t;let i=e;const r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=be(this.remainderData,e));const o=Xo(i);this.remainderData=o.remainder,r.samples=o.valid||new Uint8Array}else r.samples=i;const a=this.extractID3Track(r,t);return n.samples=mr(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(t,this.timeOffset);return i.samples=mr(e,t),{videoTrack:t,audioTrack:Ne(),id3Track:r,textTrack:Ne()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const r=X(e.samples,["emsg"]);r&&r.forEach(n=>{const a=Jo(n);if(Sc.test(a.schemeIdUri)){const o=W(a.presentationTime)?a.presentationTime/a.timeScale:t+a.presentationTimeDelta/a.timeScale;let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=a.payload;i.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:Ce.emsg,duration:l})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}const hn=(s,e)=>{let t=0,i=5;e+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=s[e];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,t=t?t<<o|r[0]:r[0],e+=1,i-=o}return t};class Ac extends Vi{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const r=dn(e,t,i,this.basePTS,this.frameIndex);if(r!==-1)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;const t=yt(e,0);if(!t)return!1;const i=t.length;return e[i]===11&&e[i+1]===119&&bi(t)!==void 0&&hn(e,i)<16}}function dn(s,e,t,i,r){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],l=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][l*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,g=[2,1,2,3,3,4,4,5][h]+f,y=e[t+5]>>3,v=e[t+5]&7,T=new Uint8Array([n<<6|y<<1|v>>2,(v&3)<<6|h<<3|f<<2|l>>4,l<<4&224]),x=1536/o*9e4,L=i+r*x,E=e.subarray(t,t+u);return s.config=T,s.channelCount=g,s.samplerate=o,s.samples.push({unit:E,pts:L}),u}class Lc{constructor(){this.VideoSample=null}createVideoSample(e,t,i,r){return{key:e,frame:!1,pts:t,dts:i,units:[],debug:r,length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,r;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const n=i.units;r=n[n.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,r=i.length;if(r){const n=i[r-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}e.debug.length&&S.log(e.pts+"/"+e.dts+":"+e.debug)}}class fn{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,i=e.byteLength-t,r=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");r.set(e.subarray(i,i+n)),this.word=new DataView(r.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 i=this.word>>>32-t;if(e>32&&S.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?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){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)}skipScalingList(e){let t=8,i=8,r;for(let n=0;n<e;n++)i!==0&&(r=this.readEG(),i=(t+r+256)%256),t=i===0?t:i}readSPS(){let e=0,t=0,i=0,r=0,n,a,o;const l=this.readUByte.bind(this),c=this.readBits.bind(this),u=this.readUEG.bind(this),h=this.readBoolean.bind(this),d=this.skipBits.bind(this),f=this.skipEG.bind(this),m=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);l();const y=l();if(c(5),d(3),l(),m(),y===100||y===110||y===122||y===244||y===44||y===83||y===86||y===118||y===128){const k=u();if(k===3&&d(1),m(),m(),d(1),h())for(a=k!==3?8:12,o=0;o<a;o++)h()&&(o<6?g(16):g(64))}m();const v=u();if(v===0)u();else if(v===1)for(d(1),f(),f(),n=u(),o=0;o<n;o++)f();m(),d(1);const T=u(),x=u(),L=c(1);L===0&&d(1),d(1),h()&&(e=u(),t=u(),i=u(),r=u());let E=[1,1];if(h()&&h())switch(l()){case 1:E=[1,1];break;case 2:E=[12,11];break;case 3:E=[10,11];break;case 4:E=[16,11];break;case 5:E=[40,33];break;case 6:E=[24,11];break;case 7:E=[20,11];break;case 8:E=[32,11];break;case 9:E=[80,33];break;case 10:E=[18,11];break;case 11:E=[15,11];break;case 12:E=[64,33];break;case 13:E=[160,99];break;case 14:E=[4,3];break;case 15:E=[3,2];break;case 16:E=[2,1];break;case 255:{E=[l()<<8|l(),l()<<8|l()];break}}return{width:Math.ceil((T+1)*16-e*2-t*2),height:(2-L)*(x+1)*16-(L?2:4)*(i+r),pixelRatio:E}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class Rc extends Lc{parseAVCPES(e,t,i,r,n){const a=this.parseAVCNALu(e,i.data);let o=this.VideoSample,l,c=!1;i.data=null,o&&a.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"")),a.forEach(u=>{var h;switch(u.type){case 1:{let g=!1;l=!0;const y=u.data;if(c&&y.length>4){const v=new fn(y).readSliceType();(v===2||v===4||v===7||v===9)&&(g=!0)}if(g){var d;(d=o)!=null&&d.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.frame=!0,o.key=g;break}case 5:l=!0,(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.key=!0,o.frame=!0;break;case 6:{l=!0,gr(u.data,1,i.pts,t.samples);break}case 7:{var f,m;l=!0,c=!0;const g=u.data,v=new fn(g).readSPS();if(!e.sps||e.width!==v.width||e.height!==v.height||((f=e.pixelRatio)==null?void 0:f[0])!==v.pixelRatio[0]||((m=e.pixelRatio)==null?void 0:m[1])!==v.pixelRatio[1]){e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.sps=[g],e.duration=n;const T=g.subarray(1,4);let x="avc1.";for(let L=0;L<3;L++){let E=T[L].toString(16);E.length<2&&(E="0"+E),x+=E}e.codec=x}break}case 8:l=!0,e.pps=[u.data];break;case 9:l=!0,e.audFound=!0,o&&this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"");break;case 12:l=!0;break;default:l=!1,o&&(o.debug+="unknown NAL "+u.type+" ");break}o&&l&&o.units.push(u)}),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}parseAVCNALu(e,t){const i=t.byteLength;let r=e.naluState||0;const n=r,a=[];let o=0,l,c,u,h=-1,d=0;for(r===-1&&(h=0,d=t[0]&31,r=0,o=1);o<i;){if(l=t[o++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(c=o-r-1,h>=0){const f={data:t.subarray(h,c),type:d};a.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(n&&o<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),c>0&&(f.data=be(f.data,t.subarray(0,c)),f.state=0))}o<i?(u=t[o]&31,h=o,d=u,r=0):r=-1}else r=0}if(h>=0&&r>=0){const f={data:t.subarray(h,i),type:d,state:r};a.push(f)}if(a.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=be(f.data,t))}return e.naluState=r,a}}class Cc{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Gi(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,i){const r=e[t].unit;if(r.length<=16)return;const n=r.subarray(16,r.length-r.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);r.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)})}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let r=0;for(let n=32;n<e.length-16;n+=160,r+=16)i.set(e.subarray(n,n+16),r);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let r=0;for(let n=32;n<e.length-16;n+=160,r+=16)e.set(i.subarray(r,r+16),n);return e}decryptAvcSample(e,t,i,r,n){const a=pr(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r)})}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){r();return}const n=e[t].units;for(;!(i>=n.length);i++){const a=n[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,r,a),!this.decrypter.isSync()))return}}}}const fe=188;class ze{constructor(e,t,i){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._duration=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=i,this.videoParser=new Rc}static probe(e){const t=ze.syncOffset(e);return t>0&&S.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),t!==-1}static syncOffset(e){const t=e.length;let i=Math.min(fe*5,t-fe)+1,r=0;for(;r<i;){let n=!1,a=-1,o=0;for(let l=r;l<t;l+=fe)if(e[l]===71&&(t-l===fe||e[l+fe]===71)){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+fe*99,e.length-fe)+1)),n||(n=zi(e,l)===0),n&&o>1&&(a===0&&o>2||l+fe>i))return a}else{if(o)return-1;break}r++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:lr[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=ze.createTrack("video"),this._audioTrack=ze.createTrack("audio",r),this._id3Track=ze.createTrack("id3"),this._txtTrack=ze.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,this._duration=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,r=!1){i||(this.sampleAes=null);let n;const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,c=this._txtTrack;let u=a.pid,h=a.pesData,d=o.pid,f=l.pid,m=o.pesData,g=l.pesData,y=null,v=this.pmtParsed,T=this._pmtId,x=e.length;if(this.remainderData&&(e=be(this.remainderData,e),x=e.length,this.remainderData=null),x<fe&&!r)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};const L=Math.max(0,ze.syncOffset(e));x-=(x-L)%fe,x<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,x,e.buffer.byteLength-x));let E=0;for(let R=L;R<x;R+=fe)if(e[R]===71){const B=!!(e[R+1]&64),C=zi(e,R),b=(e[R+3]&48)>>4;let D;if(b>1){if(D=R+5+e[R+4],D===R+fe)continue}else D=R+4;switch(C){case u:B&&(h&&(n=lt(h))&&this.videoParser.parseAVCPES(a,c,n,!1,this._duration),h={data:[],size:0}),h&&(h.data.push(e.subarray(D,R+fe)),h.size+=R+fe-D);break;case d:if(B){if(m&&(n=lt(m)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n);break}m={data:[],size:0}}m&&(m.data.push(e.subarray(D,R+fe)),m.size+=R+fe-D);break;case f:B&&(g&&(n=lt(g))&&this.parseID3PES(l,n),g={data:[],size:0}),g&&(g.data.push(e.subarray(D,R+fe)),g.size+=R+fe-D);break;case 0:B&&(D+=e[D]+1),T=this._pmtId=Dc(e,D);break;case T:{B&&(D+=e[D]+1);const P=_c(e,D,this.typeSupported,i);u=P.videoPid,u>0&&(a.pid=u,a.segmentCodec=P.segmentVideoCodec),d=P.audioPid,d>0&&(o.pid=d,o.segmentCodec=P.segmentAudioCodec),f=P.id3Pid,f>0&&(l.pid=f),y!==null&&!v&&(S.warn(`MPEG-TS PMT found at ${R} after unknown PID '${y}'. Backtracking to sync byte @${L} to parse all TS packets.`),y=null,R=L-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=C;break}}else E++;if(E>0){const R=new Error(`Found ${E} TS packet/s that do not start with 0x47`);this.observer.emit(p.ERROR,p.ERROR,{type:q.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message})}a.pesData=h,o.pesData=m,l.pesData=g;const k={audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};return r&&this.extractRemainingSamples(k),k}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:i,id3Track:r,textTrack:n}=e,a=i.pesData,o=t.pesData,l=r.pesData;let c;if(a&&(c=lt(a))?(this.videoParser.parseAVCPES(i,n,c,!0,this._duration),i.pesData=null):i.pesData=a,o&&(c=lt(o))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,c);break;case"mp3":this.parseMPEGPES(t,c);break;case"ac3":this.parseAC3PES(t,c);break}t.pesData=null}else o!=null&&o.size&&S.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(c=lt(l))?(this.parseID3PES(r,c),r.pesData=null):r.pesData=l}demuxSampleAes(e,t,i){const r=this.demux(e,i,!0,!this.config.progressive),n=this.sampleAes=new Cc(this.observer,this.config,t);return this.decrypt(r,n)}decrypt(e,t){return new Promise(i=>{const{audioTrack:r,videoTrack:n}=e;r.samples&&r.segmentCodec==="aac"?t.decryptAacSamples(r.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{i(e)}):i(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{i(e)})})}destroy(){this._duration=0}parseAACPES(e,t){let i=0;const r=this.aacOverFlow;let n=t.data;if(r){this.aacOverFlow=null;const h=r.missing,d=r.sample.unit.byteLength;if(h===-1)n=be(r.sample.unit,n);else{const f=d-h;r.sample.unit.set(n.subarray(0,h),f),e.samples.push(r.sample),i=r.missing}}let a,o;for(a=i,o=n.length;a<o-1&&!zt(n,a);a++);if(a!==i){let h;const d=a<o-1;d?h=`AAC PES did not start with ADTS header,offset:${a}`:h="No ADTS header found in AAC PES";const f=new Error(h);if(S.warn(`parsing error: ${h}`),this.observer.emit(p.ERROR,p.ERROR,{type:q.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,levelRetry:d,error:f,reason:h}),!d)return}rn(e,this.observer,n,a,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(r){const h=nn(e.samplerate);l=r.sample.pts+h}else{S.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,u;for(;a<o;)if(u=an(e,n,a,l,c),a+=u.length,u.missing){this.aacOverFlow=u;break}else for(c++;a<o-1&&!zt(n,a);a++);}parseMPEGPES(e,t){const i=t.data,r=i.length;let n=0,a=0;const o=t.pts;if(o===void 0){S.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<r;)if(cn(i,a)){const l=on(e,i,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(e,t){{const i=t.data,r=t.pts;if(r===void 0){S.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const n=i.length;let a=0,o=0,l;for(;o<n&&(l=dn(e,i,o,r,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){S.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=oe({},t,{type:this._videoTrack?Ce.emsg:Ce.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function zi(s,e){return((s[e+1]&31)<<8)+s[e+2]}function Dc(s,e){return(s[e+10]&31)<<8|s[e+11]}function _c(s,e,t,i){const r={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},n=(s[e+1]&15)<<8|s[e+2],a=e+3+n-4,o=(s[e+10]&15)<<8|s[e+11];for(e+=12+o;e<a;){const l=zi(s,e),c=(s[e+3]&15)<<8|s[e+4];switch(s[e]){case 207:if(!i){Yi("ADTS AAC");break}case 15:r.audioPid===-1&&(r.audioPid=l);break;case 21:r.id3Pid===-1&&(r.id3Pid=l);break;case 219:if(!i){Yi("H.264");break}case 27:r.videoPid===-1&&(r.videoPid=l,r.segmentVideoCodec="avc");break;case 3:case 4:!t.mpeg&&!t.mp3?S.log("MPEG audio found, not supported in this browser"):r.audioPid===-1&&(r.audioPid=l,r.segmentAudioCodec="mp3");break;case 193:if(!i){Yi("AC-3");break}case 129:t.ac3?r.audioPid===-1&&(r.audioPid=l,r.segmentAudioCodec="ac3"):S.log("AC-3 audio found, not supported in this browser");break;case 6:if(r.audioPid===-1&&c>0){let u=e+5,h=c;for(;h>2;){switch(s[u]){case 106:t.ac3!==!0?S.log("AC-3 audio found, not supported in this browser for now"):(r.audioPid=l,r.segmentAudioCodec="ac3");break}const f=s[u+1]+2;u+=f,h-=f}}break;case 194:case 135:S.warn("Unsupported EC-3 in M2TS found");break;case 36:S.warn("Unsupported HEVC in M2TS found");break}e+=c+5}return r}function Yi(s){S.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function lt(s){let e=0,t,i,r,n,a;const o=s.data;if(!s||s.size===0)return null;for(;o[0].length<19&&o.length>1;)o[0]=be(o[0],o[1]),o.splice(1,1);if(t=o[0],(t[0]<<16)+(t[1]<<8)+t[2]===1){if(i=(t[4]<<8)+t[5],i&&i>s.size-6)return null;const c=t[7];c&192&&(n=(t[9]&14)*536870912+(t[10]&255)*4194304+(t[11]&254)*16384+(t[12]&255)*128+(t[13]&254)/2,c&64?(a=(t[14]&14)*536870912+(t[15]&255)*4194304+(t[16]&254)*16384+(t[17]&255)*128+(t[18]&254)/2,n-a>60*9e4&&(S.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=t[8];let u=r+9;if(s.size<=u)return null;s.size-=u;const h=new Uint8Array(s.size);for(let d=0,f=o.length;d<f;d++){t=o[d];let m=t.byteLength;if(u)if(u>m){u-=m;continue}else t=t.subarray(u),m-=u,u=0;h.set(t,e),e+=m}return i&&(i-=r+3),{data:h,pts:n,dts:a,len:i}}return null}class Ic extends Vi{resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=yt(e,0);let i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&bi(t)!==void 0&&hn(e,i)<=16)return!1;for(let r=e.length;i<r;i++)if(un(e,i))return S.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Tc(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return on(e,t,i,this.basePTS,this.frameIndex)}}class mn{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 Ye=Math.pow(2,32)-1;class A{static init(){A.types={avc1:[],avcC:[],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 A.types)A.types.hasOwnProperty(e)&&(A.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]),i=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]);A.HDLR_TYPES={video:t,audio:i};const r=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]);A.STTS=A.STSC=A.STCO=n,A.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),A.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),A.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),A.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]),l=new Uint8Array([0,0,0,1]);A.FTYP=A.box(A.types.ftyp,a,l,a,o),A.DINF=A.box(A.types.dinf,A.box(A.types.dref,r))}static box(e,...t){let i=8,r=t.length;const n=r;for(;r--;)i+=t[r].byteLength;const a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.set(e,4),r=0,i=8;r<n;r++)a.set(t[r],i),i+=t[r].byteLength;return a}static hdlr(e){return A.box(A.types.hdlr,A.HDLR_TYPES[e])}static mdat(e){return A.box(A.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(Ye+1)),r=Math.floor(t%(Ye+1));return A.box(A.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,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(e){return A.box(A.types.mdia,A.mdhd(e.timescale,e.duration),A.hdlr(e.type),A.minf(e))}static mfhd(e){return A.box(A.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"?A.box(A.types.minf,A.box(A.types.smhd,A.SMHD),A.DINF,A.stbl(e)):A.box(A.types.minf,A.box(A.types.vmhd,A.VMHD),A.DINF,A.stbl(e))}static moof(e,t,i){return A.box(A.types.moof,A.mfhd(e),A.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=A.trak(e[t]);return A.box.apply(null,[A.types.moov,A.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(A.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=A.trex(e[t]);return A.box.apply(null,[A.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(Ye+1)),r=Math.floor(t%(Ye+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,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&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 A.box(A.types.mvhd,n)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let r,n;for(r=0;r<t.length;r++)n=t[r].flags,i[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return A.box(A.types.sdtp,i)}static stbl(e){return A.box(A.types.stbl,A.stsd(e),A.box(A.types.stts,A.STTS),A.box(A.types.stsc,A.STSC),A.box(A.types.stsz,A.STSZ),A.box(A.types.stco,A.STCO))}static avc1(e){let t=[],i=[],r,n,a;for(r=0;r<e.sps.length;r++)n=e.sps[r],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(r=0;r<e.pps.length;r++)n=e.pps[r],a=n.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));const o=A.box(A.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,c=e.height,u=e.pixelRatio[0],h=e.pixelRatio[1];return A.box(A.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,l>>8&255,l&255,c>>8&255,c&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,A.box(A.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),A.box(A.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.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static audioStsd(e){const t=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return A.box(A.types.mp4a,A.audioStsd(e),A.box(A.types.esds,A.esds(e)))}static mp3(e){return A.box(A.types[".mp3"],A.audioStsd(e))}static ac3(e){return A.box(A.types["ac-3"],A.audioStsd(e),A.box(A.types.dac3,e.config))}static stsd(e){return e.type==="audio"?e.segmentCodec==="mp3"&&e.codec==="mp3"?A.box(A.types.stsd,A.STSD,A.mp3(e)):e.segmentCodec==="ac3"?A.box(A.types.stsd,A.STSD,A.ac3(e)):A.box(A.types.stsd,A.STSD,A.mp4a(e)):A.box(A.types.stsd,A.STSD,A.avc1(e))}static tkhd(e){const t=e.id,i=e.duration*e.timescale,r=e.width,n=e.height,a=Math.floor(i/(Ye+1)),o=Math.floor(i%(Ye+1));return A.box(A.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,r>>8&255,r&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){const i=A.sdtp(e),r=e.id,n=Math.floor(t/(Ye+1)),a=Math.floor(t%(Ye+1));return A.box(A.types.traf,A.box(A.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),A.box(A.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])),A.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,A.box(A.types.trak,A.tkhd(e),A.mdia(e))}static trex(e){const t=e.id;return A.box(A.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 i=e.samples||[],r=i.length,n=12+16*r,a=new Uint8Array(n);let o,l,c,u,h,d;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<r;o++)l=i[o],c=l.duration,u=l.size,h=l.flags,d=l.cts,a.set([c>>>24&255,c>>>16&255,c>>>8&255,c&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 A.box(A.types.trun,a)}static initSegment(e){A.types||A.init();const t=A.moov(e);return be(A.FTYP,t)}}A.types=void 0,A.HDLR_TYPES=void 0,A.STTS=void 0,A.STSC=void 0,A.STCO=void 0,A.STSZ=void 0,A.VMHD=void 0,A.SMHD=void 0,A.STSD=void 0,A.FTYP=void 0,A.DINF=void 0;const gn=9e4;function ji(s,e,t=1,i=!1){const r=s*e*t;return i?Math.round(r):r}function wc(s,e,t=1,i=!1){return ji(s,e,1/t,i)}function Et(s,e=!1){return ji(s,1e3,1/gn,e)}function kc(s,e=1){return ji(s,gn,1/e)}const Pc=10*1e3,pn=1024,Oc=1152,Fc=1536;let ct=null,qi=null;class jt{constructor(e,t,i,r=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,ct===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ct=a?parseInt(a[1]):0}if(qi===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);qi=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){S.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){S.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){S.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e.reduce((r,n)=>{const a=n.pts-r;return a<-4294967296?(t=!0,Ae(r,n.pts)):a>0?r:n.pts},e[0].pts);return t&&S.debug("PTS rollover detected"),i}remux(e,t,i,r,n,a,o,l){let c,u,h,d,f,m,g=n,y=n;const v=e.pid>-1,T=t.pid>-1,x=t.samples.length,L=e.samples.length>0,E=o&&x>0||x>1;if((!v||L)&&(!T||E)||this.ISGenerated||o){if(this.ISGenerated){var R,B,C,b;const $=this.videoTrackConfig;$&&(t.width!==$.width||t.height!==$.height||((R=t.pixelRatio)==null?void 0:R[0])!==((B=$.pixelRatio)==null?void 0:B[0])||((C=t.pixelRatio)==null?void 0:C[1])!==((b=$.pixelRatio)==null?void 0:b[1]))&&this.resetInitSegment()}else h=this.generateIS(e,t,n,a);const D=this.isVideoContiguous;let P=-1,w;if(E&&(P=Mc(t.samples),!D&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,P>0){S.warn(`[mp4-remuxer]: Dropped ${P} out of ${x} video samples due to a missing keyframe`);const $=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(P),t.dropped+=P,y+=(t.samples[0].pts-$)/t.inputTimeScale,w=y}else P===-1&&(S.warn(`[mp4-remuxer]: No keyframe found out of ${x} video samples`),m=!1);if(this.ISGenerated){if(L&&E){const $=this.getVideoStartPts(t.samples),U=(Ae(e.samples[0].pts,$)-$)/t.inputTimeScale;g+=Math.max(0,U),y+=Math.max(0,-U)}if(L){if(e.samplerate||(S.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),h=this.generateIS(e,t,n,a)),u=this.remuxAudio(e,g,this.isAudioContiguous,a,T||E||l===j.AUDIO?y:void 0),E){const $=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(S.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),h=this.generateIS(e,t,n,a)),c=this.remuxVideo(t,y,D,$)}}else E&&(c=this.remuxVideo(t,y,D,0));c&&(c.firstKeyFrame=P,c.independent=P!==-1,c.firstKeyFramePTS=w)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=yn(i,n,this._initPTS,this._initDTS)),r.samples.length&&(d=vn(r,n,this._initPTS))),{audio:u,video:c,initSegment:h,independent:m,text:d,id3:f}}generateIS(e,t,i,r){const n=e.samples,a=t.samples,o=this.typeSupported,l={},c=this._initPTS;let u=!c||r,h="audio/mp4",d,f,m;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}l.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):A.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(m=e.inputTimeScale,!c||m!==c.timescale?d=f=n[0].pts-Math.round(m*i):u=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:A.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(m=t.inputTimeScale,!c||m!==c.timescale){const g=this.getVideoStartPts(a),y=Math.round(m*i);f=Math.min(f,Ae(a[0].dts,g)-y),d=Math.min(d,g-y)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:d,timescale:m},this._initDTS={baseTime:f,timescale:m}):d=m=void 0,{tracks:l,initPTS:d,timescale:m}}remuxVideo(e,t,i,r){const n=e.inputTimeScale,a=e.samples,o=[],l=a.length,c=this._initPTS;let u=this.nextAvcDts,h=8,d=this.videoSampleDuration,f,m,g=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,v=!1;if(!i||u===null){const H=t*n,N=a[0].pts-Ae(a[0].dts,a[0].pts);ct&&u!==null&&Math.abs(H-N-u)<15e3?i=!0:u=H-N}const T=c.baseTime*n/c.timescale;for(let H=0;H<l;H++){const N=a[H];N.pts=Ae(N.pts-T,u),N.dts=Ae(N.dts-T,u),N.dts<a[H>0?H-1:H].dts&&(v=!0)}v&&a.sort(function(H,N){const J=H.dts-N.dts,Q=H.pts-N.pts;return J||Q}),f=a[0].dts,m=a[a.length-1].dts;const x=m-f,L=x?Math.round(x/(l-1)):d||e.inputTimeScale/30;if(i){const H=f-u,N=H>L,J=H<-1;if((N||J)&&(N?S.warn(`AVC: ${Et(H,!0)} ms (${H}dts) hole between fragments detected at ${t.toFixed(3)}`):S.warn(`AVC: ${Et(-H,!0)} ms (${H}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!J||u>=a[0].pts||ct)){f=u;const Q=a[0].pts-H;if(N)a[0].dts=f,a[0].pts=Q;else for(let ie=0;ie<a.length&&!(a[ie].dts>Q);ie++)a[ie].dts-=H,a[ie].pts-=H;S.log(`Video: Initial PTS/DTS adjusted: ${Et(Q,!0)}/${Et(f,!0)}, delta: ${Et(H,!0)} ms`)}}f=Math.max(0,f);let E=0,k=0,R=f;for(let H=0;H<l;H++){const N=a[H],J=N.units,Q=J.length;let ie=0;for(let le=0;le<Q;le++)ie+=J[le].data.length;k+=ie,E+=Q,N.length=ie,N.dts<R?(N.dts=R,R+=L/4|0||1):R=N.dts,g=Math.min(N.pts,g),y=Math.max(N.pts,y)}m=a[l-1].dts;const B=k+4*E+8;let C;try{C=new Uint8Array(B)}catch(H){this.observer.emit(p.ERROR,p.ERROR,{type:q.MUX_ERROR,details:_.REMUX_ALLOC_ERROR,fatal:!1,error:H,bytes:B,reason:`fail allocating video mdat ${B}`});return}const b=new DataView(C.buffer);b.setUint32(0,B),C.set(A.types.mdat,4);let D=!1,P=Number.POSITIVE_INFINITY,w=Number.POSITIVE_INFINITY,$=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let H=0;H<l;H++){const N=a[H],J=N.units;let Q=0;for(let me=0,pe=J.length;me<pe;me++){const Re=J[me],At=Re.data,As=Re.data.byteLength;b.setUint32(h,As),h+=4,C.set(At,h),h+=As,Q+=4+As}let ie;if(H<l-1)d=a[H+1].dts-N.dts,ie=a[H+1].pts-N.pts;else{const me=this.config,pe=H>0?N.dts-a[H-1].dts:L;if(ie=H>0?N.pts-a[H-1].pts:L,me.stretchShortVideoTrack&&this.nextAudioPts!==null){const Re=Math.floor(me.maxBufferHole*n),At=(r?g+r*n:this.nextAudioPts)-N.pts;At>Re?(d=At-pe,d<0?d=pe:D=!0,S.log(`[mp4-remuxer]: It is approximately ${At/90} ms to the next segment; using duration ${d/90} ms for the last video frame.`)):d=pe}else d=pe}const le=Math.round(N.pts-N.dts);P=Math.min(P,d),$=Math.max($,d),w=Math.min(w,ie),O=Math.max(O,ie),o.push(new xn(N.key,d,Q,le))}if(o.length){if(ct){if(ct<70){const H=o[0].flags;H.dependsOn=2,H.isNonSync=0}}else if(qi&&O-w<$-P&&L/$<.025&&o[0].cts===0){S.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let H=f;for(let N=0,J=o.length;N<J;N++){const Q=H+o[N].duration,ie=H+o[N].cts;if(N<J-1){const le=Q+o[N+1].cts;o[N].duration=le-ie}else o[N].duration=N?o[N-1].duration:L;o[N].cts=0,H=Q}}}d=D||!d?L:d,this.nextAvcDts=u=m+d,this.videoSampleDuration=d,this.isVideoContiguous=!0;const U=A.moof(e.sequenceNumber++,f,oe({},e,{samples:o})),F="video",V={data1:U,data2:C,startPTS:g/n,endPTS:(y+d)/n,startDTS:f/n,endDTS:u/n,type:F,hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,V}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Oc;case"ac3":return Fc;default:return pn}}remuxAudio(e,t,i,r,n){const a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,l=a/o,c=this.getSamplesPerFrame(e),u=c*l,h=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],m=n!==void 0;let g=e.samples,y=d?0:8,v=this.nextAudioPts||-1;const T=t*a,x=h.baseTime*a/h.timescale;if(this.isAudioContiguous=i=i||g.length&&v>0&&(r&&Math.abs(T-v)<9e3||Math.abs(Ae(g[0].pts-x,T)-v)<20*u),g.forEach(function(U){U.pts=Ae(U.pts-x,T)}),!i||v<0){if(g=g.filter(U=>U.pts>=0),!g.length)return;n===0?v=0:r&&!m?v=Math.max(0,T):v=g[0].pts}if(e.segmentCodec==="aac"){const U=this.config.maxAudioFramesDrift;for(let F=0,V=v;F<g.length;F++){const H=g[F],N=H.pts,J=N-V,Q=Math.abs(1e3*J/a);if(J<=-U*u&&m)F===0&&(S.warn(`Audio frame @ ${(N/a).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*J/a)} ms.`),this.nextAudioPts=v=V=N);else if(J>=U*u&&Q<Pc&&m){let ie=Math.round(J/u);V=N-ie*u,V<0&&(ie--,V+=u),F===0&&(this.nextAudioPts=v=V),S.warn(`[mp4-remuxer]: Injecting ${ie} audio frame @ ${(V/a).toFixed(3)}s due to ${Math.round(1e3*J/a)} ms gap.`);for(let le=0;le<ie;le++){const me=Math.max(V,0);let pe=mn.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);pe||(S.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),pe=H.unit.subarray()),g.splice(F,0,{unit:pe,pts:me}),V+=u,F++}}H.pts=V,V+=u}}let L=null,E=null,k,R=0,B=g.length;for(;B--;)R+=g[B].unit.byteLength;for(let U=0,F=g.length;U<F;U++){const V=g[U],H=V.unit;let N=V.pts;if(E!==null){const Q=f[U-1];Q.duration=Math.round((N-E)/l)}else if(i&&e.segmentCodec==="aac"&&(N=v),L=N,R>0){R+=y;try{k=new Uint8Array(R)}catch(Q){this.observer.emit(p.ERROR,p.ERROR,{type:q.MUX_ERROR,details:_.REMUX_ALLOC_ERROR,fatal:!1,error:Q,bytes:R,reason:`fail allocating audio mdat ${R}`});return}d||(new DataView(k.buffer).setUint32(0,R),k.set(A.types.mdat,4))}else return;k.set(H,y);const J=H.byteLength;y+=J,f.push(new xn(!0,c,J,0)),E=N}const C=f.length;if(!C)return;const b=f[f.length-1];this.nextAudioPts=v=E+l*b.duration;const D=d?new Uint8Array(0):A.moof(e.sequenceNumber++,L/l,oe({},e,{samples:f}));e.samples=[];const P=L/a,w=v/a,O={data1:D,data2:k,startPTS:P,endPTS:w,startDTS:P,endDTS:w,type:"audio",hasAudio:!0,hasVideo:!1,nb:C};return this.isAudioContiguous=!0,O}remuxEmptyAudio(e,t,i,r){const n=e.inputTimeScale,a=e.samplerate?e.samplerate:n,o=n/a,l=this.nextAudioPts,c=this._initDTS,u=c.baseTime*9e4/c.timescale,h=(l!==null?l:r.startDTS*n)+u,d=r.endDTS*n+u,f=o*pn,m=Math.ceil((d-h)/f),g=mn.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(S.warn("[mp4-remuxer]: remux empty Audio"),!g){S.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const y=[];for(let v=0;v<m;v++){const T=h+v*f;y.push({unit:g,pts:T,dts:T})}return e.samples=y,this.remuxAudio(e,t,i,!1)}}function Ae(s,e){let t;if(e===null)return s;for(e<s?t=-8589934592:t=8589934592;Math.abs(s-e)>4294967296;)s+=t;return s}function Mc(s){for(let e=0;e<s.length;e++)if(s[e].key)return e;return-1}function yn(s,e,t,i){const r=s.samples.length;if(!r)return;const n=s.inputTimeScale;for(let o=0;o<r;o++){const l=s.samples[o];l.pts=Ae(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=Ae(l.dts-i.baseTime*n/i.timescale,e*n)/n}const a=s.samples;return s.samples=[],{samples:a}}function vn(s,e,t){const i=s.samples.length;if(!i)return;const r=s.inputTimeScale;for(let a=0;a<i;a++){const o=s.samples[a];o.pts=Ae(o.pts-t.baseTime*r/t.timescale,e*r)/r}s.samples.sort((a,o)=>a.pts-o.pts);const n=s.samples;return s.samples=[],{samples:n}}class xn{constructor(e,t,i,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=i,this.cts=r,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class Nc{constructor(){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}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(Wo(e,r)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const r=this.initData=dr(e);r.audio&&(t=Tn(r.audio,te.AUDIO)),r.video&&(i=Tn(r.video,te.VIDEO));const n={};r.audio&&r.video?n.audiovideo={container:"video/mp4",codec:t+","+i,initSegment:e,id:"main"}:r.audio?n.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:r.video?n.video={container:"video/mp4",codec:i,initSegment:e,id:"main"}:S.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(e,t,i,r,n,a){var o,l;let{initPTS:c,lastEndTime:u}=this;const h={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};W(u)||(u=this.lastEndTime=n||0);const d=t.samples;if(!(d!=null&&d.length))return h;const f={initPTS:void 0,timescale:1};let m=this.initData;if((o=m)!=null&&o.length||(this.generateInitSegment(d),m=this.initData),!((l=m)!=null&&l.length))return S.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),h;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const g=Yo(d,m),y=zo(m,d),v=y===null?n:y;(Bc(c,v,n,g)||f.timescale!==c.timescale&&a)&&(f.initPTS=v-n,c&&c.timescale===1&&S.warn(`Adjusting initPTS by ${f.initPTS-c.baseTime}`),this.initPTS=c={baseTime:f.initPTS,timescale:1});const T=e?v-c.baseTime/c.timescale:u,x=T+g;qo(m,d,c.baseTime/c.timescale),g>0?this.lastEndTime=x:(S.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const L=!!m.audio,E=!!m.video;let k="";L&&(k+="audio"),E&&(k+="video");const R={data1:d,startPTS:T,startDTS:T,endPTS:x,endDTS:x,type:k,hasAudio:L,hasVideo:E,nb:1,dropped:0};return h.audio=R.type==="audio"?R:void 0,h.video=R.type!=="audio"?R:void 0,h.initSegment=f,h.id3=yn(i,n,c,c),r.samples.length&&(h.text=vn(r,n,c)),h}}function Bc(s,e,t,i){if(s===null)return!0;const r=Math.max(i,1),n=e-s.baseTime/s.timescale;return Math.abs(n-t)>r}function Tn(s,e){const t=s==null?void 0:s.codec;if(t&&t.length>4)return t;if(e===te.AUDIO){if(t==="ec-3"||t==="ac-3"||t==="alac")return t;if(t==="fLaC"||t==="Opus")return Ft(t,!1);const i="mp4a.40.5";return S.info(`Parsed audio codec "${t}" or audio object type not handled. Using "${i}"`),i}return S.warn(`Unhandled video codec "${t}"`),t==="hvc1"||t==="hev1"?"hvc1.1.6.L120.90":t==="av01"?"av01.0.04M.08":"avc1.42e01e"}let He;try{He=self.performance.now.bind(self.performance)}catch{S.debug("Unable to use Performance API on this environment"),He=et==null?void 0:et.Date.now}const qt=[{demux:bc,remux:Nc},{demux:ze,remux:jt},{demux:Ec,remux:jt},{demux:Ic,remux:jt}];qt.splice(2,0,{demux:Ac,remux:jt});class En{constructor(e,t,i,r,n){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=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=i,this.vendor=r,this.id=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,r){const n=i.transmuxing;n.executeStart=He();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;r&&(this.currentTransmuxState=r);const{contiguous:c,discontinuity:u,trackSwitch:h,accurateTimeOffset:d,timeOffset:f,initSegmentChange:m}=r||o,{audioCodec:g,videoCodec:y,defaultInitPts:v,duration:T,initSegmentData:x}=l,L=$c(a,t);if(L&&L.method==="AES-128"){const B=this.getDecrypter();if(B.isSync()){let C=B.softwareDecrypt(a,L.key.buffer,L.iv.buffer);if(i.part>-1&&(C=B.flush()),!C)return n.executeEnd=He(),Xi(i);a=new Uint8Array(C)}else return this.decryptionPromise=B.webCryptoDecrypt(a,L.key.buffer,L.iv.buffer).then(C=>{const b=this.push(C,null,i);return this.decryptionPromise=null,b}),this.decryptionPromise}const E=this.needsProbing(u,h);if(E){const B=this.configureTransmuxer(a);if(B)return S.warn(`[transmuxer] ${B.message}`),this.observer.emit(p.ERROR,p.ERROR,{type:q.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:B,reason:B.message}),n.executeEnd=He(),Xi(i)}(u||h||m||E)&&this.resetInitSegment(x,g,y,T,t),(u||m||E)&&this.resetInitialTimestamp(v),c||this.resetContiguity();const k=this.transmux(a,L,f,d,i),R=this.currentTransmuxState;return R.contiguous=!0,R.discontinuity=!1,R.trackSwitch=!1,n.executeEnd=He(),k}flush(e){const t=e.transmuxing;t.executeStart=He();const{decrypter:i,currentTransmuxState:r,decryptionPromise:n}=this;if(n)return n.then(()=>this.flush(e));const a=[],{timeOffset:o}=r;if(i){const h=i.flush();h&&a.push(this.push(h,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c)return t.executeEnd=He(),[Xi(e)];const u=l.flush(o);return Xt(u)?u.then(h=>(this.flushRemux(a,h,e),a)):(this.flushRemux(a,u,e),a)}flushRemux(e,t,i){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;S.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const u=this.remuxer.remux(r,n,a,o,c,l,!0,this.id);e.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=He()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,r,n){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,i,r),o.resetInitSegment(e,t,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,r,n){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,r,n):a=this.transmuxUnencrypted(e,i,r,n),a}transmuxUnencrypted(e,t,i,r){const{audioTrack:n,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,a,o,l,t,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,i,r,n){return this.demuxer.demuxSampleAes(e,t,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,r,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:r,vendor:n}=this;let a;for(let d=0,f=qt.length;d<f;d++){var o;if((o=qt[d].demux)!=null&&o.probe(e)){a=qt[d];break}}if(!a)return new Error("Failed to find demuxer by probing fragment data");const l=this.demuxer,c=this.remuxer,u=a.remux,h=a.demux;(!c||!(c instanceof u))&&(this.remuxer=new u(i,t,r,n)),(!l||!(l instanceof h))&&(this.demuxer=new h(i,t,r),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Gi(this.config)),e}}function $c(s,e){let t=null;return s.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Xi=s=>({remuxResult:{},chunkMeta:s});function Xt(s){return"then"in s&&s.then instanceof Function}class Uc{constructor(e,t,i,r,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=i,this.duration=r,this.defaultInitPts=n||null}}class Gc{constructor(e,t,i,r,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=i,this.trackSwitch=r,this.timeOffset=n,this.initSegmentChange=a}}var Sn={exports:{}};(function(s){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function r(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function n(l,c,u,h,d){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new r(u,h||l,d),m=t?t+c:c;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],f]:l._events[m].push(f):(l._events[m]=f,l._eventsCount++),l}function a(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,h;if(this._eventsCount===0)return c;for(h in u=this._events)e.call(u,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var d=0,f=h.length,m=new Array(f);d<f;d++)m[d]=h[d].fn;return m},o.prototype.listenerCount=function(c){var u=t?t+c:c,h=this._events[u];return h?h.fn?1:h.length:0},o.prototype.emit=function(c,u,h,d,f,m){var g=t?t+c:c;if(!this._events[g])return!1;var y=this._events[g],v=arguments.length,T,x;if(y.fn){switch(y.once&&this.removeListener(c,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,m),!0}for(x=1,T=new Array(v-1);x<v;x++)T[x-1]=arguments[x];y.fn.apply(y.context,T)}else{var L=y.length,E;for(x=0;x<L;x++)switch(y[x].once&&this.removeListener(c,y[x].fn,void 0,!0),v){case 1:y[x].fn.call(y[x].context);break;case 2:y[x].fn.call(y[x].context,u);break;case 3:y[x].fn.call(y[x].context,u,h);break;case 4:y[x].fn.call(y[x].context,u,h,d);break;default:if(!T)for(E=1,T=new Array(v-1);E<v;E++)T[E-1]=arguments[E];y[x].fn.apply(y[x].context,T)}}return!0},o.prototype.on=function(c,u,h){return n(this,c,u,h,!1)},o.prototype.once=function(c,u,h){return n(this,c,u,h,!0)},o.prototype.removeListener=function(c,u,h,d){var f=t?t+c:c;if(!this._events[f])return this;if(!u)return a(this,f),this;var m=this._events[f];if(m.fn)m.fn===u&&(!d||m.once)&&(!h||m.context===h)&&a(this,f);else{for(var g=0,y=[],v=m.length;g<v;g++)(m[g].fn!==u||d&&!m[g].once||h&&m[g].context!==h)&&y.push(m[g]);y.length?this._events[f]=y.length===1?y[0]:y:a(this,f)}return this},o.prototype.removeAllListeners=function(c){var u;return c?(u=t?t+c:c,this._events[u]&&a(this,u)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,s.exports=o})(Sn);var Hc=Sn.exports,Zi=ho(Hc);class bn{constructor(e,t,i,r){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;const a=(u,h)=>{h=h||{},h.frag=this.frag,h.id=this.id,u===p.ERROR&&(this.error=h.error),this.hls.trigger(u,h)};this.observer=new Zi,this.observer.on(p.FRAG_DECRYPTED,a),this.observer.on(p.ERROR,a);const o=tt(n.preferManagedMediaSource)||{isTypeSupported:()=>!1},l={mpeg:o.isTypeSupported("audio/mpeg"),mp3:o.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:o.isTypeSupported('audio/mp4; codecs="ac-3"')},c=navigator.vendor;if(this.useWorker&&typeof Worker!="undefined"&&(n.workerPath||oc())){try{n.workerPath?(S.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=cc(n.workerPath)):(S.log(`injecting Web Worker for "${t}"`),this.workerContext=lc()),this.onwmsg=d=>this.onWorkerMessage(d);const{worker:h}=this.workerContext;h.addEventListener("message",this.onwmsg),h.onerror=d=>{const f=new Error(`${d.message} (${d.filename}:${d.lineno})`);n.enableWorker=!1,S.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(p.ERROR,{type:q.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:f})},h.postMessage({cmd:"init",typeSupported:l,vendor:c,id:t,config:JSON.stringify(n)})}catch(h){S.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.resetWorker(),this.error=null,this.transmuxer=new En(this.observer,l,n,c,t)}return}this.transmuxer=new En(this.observer,l,n,c,t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,i,r,n,a,o,l,c,u){var h,d;c.transmuxing.start=self.performance.now();const{transmuxer:f}=this,m=a?a.start:n.start,g=n.decryptdata,y=this.frag,v=!(y&&n.cc===y.cc),T=!(y&&c.level===y.level),x=y?c.sn-y.sn:-1,L=this.part?c.part-this.part.index:-1,E=x===0&&c.id>1&&c.id===(y==null?void 0:y.stats.chunkCount),k=!T&&(x===1||x===0&&(L===1||E&&L<=0)),R=self.performance.now();(T||x||n.stats.parsing.start===0)&&(n.stats.parsing.start=R),a&&(L||!k)&&(a.stats.parsing.start=R);const B=!(y&&((h=n.initSegment)==null?void 0:h.url)===((d=y.initSegment)==null?void 0:d.url)),C=new Gc(v,k,l,T,m,B);if(!k||v||B){S.log(`[transmuxer-interface, ${n.type}]: Starting new transmux session for sn: ${c.sn} p: ${c.part} level: ${c.level} id: ${c.id}
9
9
  discontinuity: ${v}
10
10
  trackSwitch: ${T}
11
11
  contiguous: ${k}
12
12
  accurateTimeOffset: ${l}
13
13
  timeOffset: ${m}
14
- initSegmentChange: ${B}`);const b=new Uc(i,r,t,o,u);this.configureTransmuxer(b)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:g,chunkMeta:c,state:C},e instanceof ArrayBuffer?[e]:[]);else if(f){const b=f.push(e,g,c,C);Xt(b)?(f.async=!0,b.then(D=>{this.handleTransmuxComplete(D)}).catch(D=>{this.transmuxerError(D,c,"transmuxer-interface push error")})):(f.async=!1,this.handleTransmuxComplete(b))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let i=t.flush(e);Xt(i)||t.async?(Xt(i)||(i=Promise.resolve(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,i){this.hls&&(this.error=e,this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}onWorkerMessage(e){const t=e.data,i=this.hls;switch(t.event){case"init":{var r;const n=(r=this.workerContext)==null?void 0:r.objectURL;n&&self.URL.revokeObjectURL(n);break}case"transmuxComplete":{this.handleTransmuxComplete(t.data);break}case"flush":{this.onFlush(t.data);break}case"workerLog":S[t.data.logType]&&S[t.data.logType](t.data.message);break;default:{t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,i.trigger(t.event,t.data);break}}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}function An(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(!ut(s[t].attrs,e[t].attrs))return!1;return!0}function ut(s,e,t){const i=s["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>s[r]!==e[r])}function Qi(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}const Ln=100;class Vc extends Hi{constructor(e,t,i){super(e,t,i,"[audio-stream-controller]",j.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-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.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.ERROR,this.onError,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:n}){if(i==="main"){const a=t.cc;this.initPTS[t.cc]={baseTime:r,timescale:n},this.log(`InitPTS for cc: ${a} found from main: ${r}`),this.videoTrackCC=a,this.state===M.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=M.STOPPED;return}const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(Ln),t>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=M.IDLE):(this.loadedmetadata=!1,this.state=M.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case M.IDLE:this.doTickIdle();break;case M.WAITING_TRACK:{var e;const{levels:i,trackId:r}=this,n=i==null||(e=i[r])==null?void 0:e.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=M.WAITING_INIT_PTS}break}case M.FRAG_LOADING_WAITING_RETRY:{var t;const i=performance.now(),r=this.retryDate;if(!r||i>=r||(t=this.media)!=null&&t.seeking){const{levels:n,trackId:a}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((n==null?void 0:n[a])||null),this.state=M.IDLE}break}case M.WAITING_INIT_PTS:{const i=this.waitingData;if(i){const{frag:r,part:n,cache:a,complete:o}=i;if(this.initPTS[r.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=M.FRAG_LOADING;const l=a.flush(),c={frag:r,part:n,payload:l,networkDetails:null};this._handleFragmentLoadProgress(c),o&&super._handleFragmentLoadComplete(c)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${r.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),c=se.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);Bi(c.end,this.config.maxFragLookUpTolerance,r)<0&&(this.log(`Waiting fragment cc (${r.cc}) @ ${r.start} cancelled because another fragment at ${c.end} is needed`),this.clearWaitingFragment())}}else this.state=M.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=M.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:i,trackId:r}=this,n=e.config;if(!i&&(this.startFragRequested||!n.startFragPrefetch)||!(t!=null&&t[r]))return;const a=t[r],o=a.details;if(!o||o.live&&this.levelLastLoaded!==a||this.waitForCdnTuneIn(o)){this.state=M.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,te.AUDIO,j.AUDIO));const c=this.getFwdBufferInfo(l,j.AUDIO);if(c===null)return;const{bufferedTrack:u,switchingTrack:h}=this;if(!h&&this._streamEnded(c,o)){e.trigger(p.BUFFER_EOS,{type:"audio"}),this.state=M.ENDED;return}const d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,j.MAIN),f=c.len,m=this.getMaxBufferLength(d==null?void 0:d.len),g=o.fragments,y=g[0].start;let v=this.flushing?this.getLoadPosition():c.end;if(h&&i){const E=this.getLoadPosition();u&&!ut(h.attrs,u.attrs)&&(v=E),o.PTSKnown&&E<y&&(c.end>y||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=y+.05)}if(f>=m&&!h&&v<g[g.length-1].start)return;let T=this.getNextFragment(v,o),x=!1;if(T&&this.isLoopLoading(T,v)&&(x=!!T.gap,T=this.getNextFragmentLoopLoading(T,o,c,j.MAIN,m)),!T){this.bufferFlushed=!0;return}const L=d&&T.start>d.end+o.targetduration;if(L||!(d!=null&&d.len)&&c.len){const E=this.getAppendedFrag(T.start,j.MAIN);if(E===null||(x||(x=!!E.gap||!!L&&d.len===0),L&&!x||x&&c.nextStart&&c.nextStart<E.end))return}this.loadFragment(T,a,v)}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new st(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?this.setInterval(Ln):this.resetTransmuxer(),i?(this.switchingTrack=t,this.state=M.IDLE,this.flushAudioIfNeeded(t)):(this.switchingTrack=null,this.bufferedTrack=t,this.state=M.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(p.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var i;if(this.mainDetails==null){this.cachedTrackLoadedData=t;return}const{levels:r}=this,{details:n,id:a}=t;if(!r){this.warn(`Audio tracks were reset while loading level ${a}`);return}this.log(`Audio track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const o=r[a];let l=0;if(n.live||(i=o.details)!=null&&i.live){this.checkLiveUpdate(n);const u=this.mainDetails;if(n.deltaUpdateFailed||!u)return;if(!o.details&&n.hasProgramDateTime&&u.hasProgramDateTime)Wt(n,u),l=n.fragments[0].start;else{var c;l=this.alignPlaylists(n,o.details,(c=this.levelLastLoaded)==null?void 0:c.details)}}o.details=n,this.levelLastLoaded=o,!this.startFragRequested&&(this.mainDetails||!n.live)&&this.setStartPosition(this.mainDetails||n,l),this.state===M.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=M.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:r,payload:n}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const c=l[o];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const u=c.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const h=a.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new bn(this.hls,j.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[i.cc],m=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){const y=r?r.index:-1,v=y!==-1,T=new Ui(i.level,i.sn,i.stats.chunkCount,n.byteLength,y,v);d.push(n,m,h,"",i,r,u.totalduration,!1,T,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:g}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new en,complete:!1};g.push(new Uint8Array(n)),this.waitingVideoCC=this.videoTrackCC,this.state=M.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:i,part:r}=t;if(i.type!==j.AUDIO){if(!this.loadedmetadata&&i.type===j.MAIN){const n=this.videoBuffer||this.media;n&&se.getBuffered(n).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(i.sn!=="initSegment"){this.fragPrevious=i;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(p.AUDIO_TRACK_SWITCHED,he({},n)))}this.fragBufferedComplete(i,r)}onError(e,t){var i;if(t.fatal){this.state=M.ERROR;return}switch(t.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(j.AUDIO,t);break;case _.AUDIO_TRACK_LOAD_ERROR:case _.AUDIO_TRACK_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===M.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===ee.AUDIO_TRACK&&(this.state=M.IDLE);break;case _.BUFFER_APPEND_ERROR:case _.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="audio")return;if(t.details===_.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case _.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==te.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==te.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===M.ENDED&&(this.state=M.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,j.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:u}=o,{details:h}=u,{audio:d,text:f,id3:m,initSegment:g}=n;if(this.fragContextChanged(l)||!h){this.fragmentTracker.removeFragment(l);return}if(this.state=M.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){const y=l.initSegment||l;this._bufferInitSegment(u,g.tracks,y,a),r.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:i,tracks:g.tracks})}if(d){const{startPTS:y,endPTS:v,startDTS:T,endDTS:x}=d;c&&(c.elementaryStreams[te.AUDIO]={startPTS:y,endPTS:v,startDTS:T,endDTS:x}),l.setElementaryStreamInfo(te.AUDIO,y,v,T,x),this.bufferFragmentData(d,l,c,a)}if(m!=null&&(t=m.samples)!=null&&t.length){const y=oe({id:i,frag:l,details:h},m);r.trigger(p.FRAG_PARSING_METADATA,y)}if(f){const y=oe({id:i,frag:l,details:h},f);r.trigger(p.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,i,r){if(this.state!==M.PARSING)return;t.video&&delete t.video;const n=t.audio;if(!n)return;n.id="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(p.BUFFER_CODECS,t);const o=n.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:o};this.hls.trigger(p.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){const r=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||r===de.NOT_LOADED||r===de.PARTIAL){var n;if(e.sn==="initSegment")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=M.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragments[0].start!==t.details.fragments[0].start&&Wt(t.details,a)}else this.startFragRequested=!0,super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){const{media:t,bufferedTrack:i}=this,r=i==null?void 0:i.attrs,n=e.attrs;t&&r&&(r.CHANNELS!==n.CHANNELS||i.name!==e.name||i.lang!==e.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(p.AUDIO_TRACK_SWITCHED,he({},e))}}class Kc extends $i{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(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.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:i,groupId:r,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Audio track with id:${i} and group:${r} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,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 i=t.audioGroups||null,r=this.groupIds;let n=this.currentTrack;if(!i||(r==null?void 0:r.length)!==(i==null?void 0:i.length)||i!=null&&i.some(o=>(r==null?void 0:r.indexOf(o))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!i||i.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 l=this.hls.config.audioPreference;if(!n&&l){const d=Me(l,o,at);if(d>-1)n=o[d];else{const f=Me(l,this.tracks);n=this.tracks[f]}}let c=this.findTrackId(n);c===-1&&n&&(c=this.findTrackId(null));const u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(p.AUDIO_TRACKS_UPDATED,u);const h=this.trackId;if(c!==-1&&h===-1)this.setAudioTrack(c);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(p.ERROR,{type:q.MEDIA_ERROR,details:_.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}else this.shouldReloadPlaylist(n)&&this.setAudioTrack(this.trackId)}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.requestScheduled=-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 i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const r=this.currentTrack;if(r&&nt(e,r,at))return r;const n=Me(e,this.tracksInGroup,at);if(n>-1){const a=this.tracksInGroup[n];return this.setAudioTrack(n),a}else if(r){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=Kl(e,t.levels,i,a,at);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=Me(e,i);if(a>-1)return i[a]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,r=t[e],n=r.details&&!r.details.live;if(e===this.trackId&&r===i&&n||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(p.AUDIO_TRACK_SWITCHING,he({},r)),n))return;const a=this.switchParams(r.url,i==null?void 0:i.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const r=t[i];if(!(this.selectDefaultTrack&&!r.default)&&(!e||nt(e,r,at)))return i}if(e){const{name:i,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l}=e;for(let c=0;c<t.length;c++){const u=t[c];if(nt({name:i,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l},u,at))return c}for(let c=0;c<t.length;c++){const u=t[c];if(ut(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<t.length;c++){const u=t[c];if(ut(e.attrs,u.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(e){const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){super.loadPlaylist();const i=t.id,r=t.groupId;let n=t.url;if(e)try{n=e.addDirectives(n)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`loading audio-track playlist ${i} "${t.name}" lang:${t.lang} group:${r}`),this.clearTimer(),this.hls.trigger(p.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:e||null})}}}const Rn=500;class Wc extends Hi{constructor(e,t,i){super(e,t,i,"[subtitle-stream-controller]",j.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.ERROR,this.onError,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.ERROR,this.onError,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=M.IDLE,this.setInterval(Rn),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:r}=t;if(this.fragPrevious=i,this.state=M.IDLE,!r)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a;const o=i.start;for(let c=0;c<n.length;c++)if(o>=n[c].start&&o<=n[c].end){a=n[c];break}const l=i.start+i.duration;a?a.end=l:(a={start:o,end:l},n.push(a)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null)}onBufferFlushing(e,t){const{startOffset:i,endOffset:r}=t;if(i===0&&r!==Number.POSITIVE_INFINITY){const n=r-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(i,n,j.SUBTITLE)}}onFragBuffered(e,t){if(!this.loadedmetadata&&t.frag.type===j.MAIN){var i;(i=this.media)!=null&&i.buffered.length&&(this.loadedmetadata=!0)}}onError(e,t){const i=t.frag;(i==null?void 0:i.type)===j.SUBTITLE&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==M.STOPPED&&(this.state=M.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&An(this.levels,t)){this.levels=t.map(i=>new st(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const r=new st(i);return this.tracksBuffered[r.id]=[],r}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,j.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}const r=this.levels[this.currentTrackId];r!=null&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.setInterval(Rn)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:r,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=n[r];if(o>=n.length||o!==r||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(a.live||(i=l.details)!=null&&i.live){const h=this.mainDetails;if(a.deltaUpdateFailed||!h)return;const d=h.fragments[0];if(!l.details)a.hasProgramDateTime&&h.hasProgramDateTime?(Wt(a,h),c=a.fragments[0].start):d&&(c=d.start,Mi(a,c));else{var u;c=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details),c===0&&d&&(c=d.start,Mi(a,c))}}l.details=a,this.levelLastLoaded=l,!this.startFragRequested&&(this.mainDetails||!a.live)&&this.setStartPosition(this.mainDetails||a,c),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===M.IDLE&&(Gt(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,r=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&r!=null&&r.key&&r.iv&&r.method==="AES-128"){const a=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer).catch(o=>{throw n.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const l=performance.now();n.trigger(p.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=M.IDLE})}}doTick(){if(!this.media){this.state=M.IDLE;return}if(this.state===M.IDLE){const{currentTrackId:e,levels:t}=this,i=t==null?void 0:t[e];if(!i||!t.length||!i.details)return;const{config:r}=this,n=this.getLoadPosition(),a=se.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,r.maxBufferHole),{end:o,len:l}=a,c=this.getFwdBufferInfo(this.media,j.MAIN),u=i.details,h=this.getMaxBufferLength(c==null?void 0:c.len)+u.levelTargetDuration;if(l>h)return;const d=u.fragments,f=d.length,m=u.edge;let g=null;const y=this.fragPrevious;if(o<m){const v=r.maxFragLookUpTolerance,T=o>m-v?0:v;g=Gt(y,d,Math.max(d[0].start,o),T),!g&&y&&y.start<d[0].start&&(g=d[0])}else g=d[f-1];if(!g)return;if(g=this.mapToInitFragWhenRequired(g),g.sn!=="initSegment"){const v=g.sn-u.startSN,T=d[v-1];T&&T.cc===g.cc&&this.fragmentTracker.getState(T)===de.NOT_LOADED&&(g=T)}this.fragmentTracker.getState(g)===de.NOT_LOADED&&this.loadFragment(g,i,o)}}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,i){this.fragCurrent=e,e.sn==="initSegment"?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,i))}get mediaBufferTimeRanges(){return new zc(this.tracksBuffered[this.currentTrackId]||[])}}class zc{constructor(e){this.buffered=void 0;const t=(i,r,n)=>{if(r=r>>>0,r>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}class Yc extends $i{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.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=Mt(this.media.textTracks);for(let n=0;n<i.length;n++)if(i[n].mode==="hidden")t=i[n];else if(i[n].mode==="showing"){t=i[n];break}const r=this.findTrackForTextTrack(t);this.subtitleTrack!==r&&this.setSubtitleTrack(r)},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(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.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(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),Mt(this.media.textTracks).forEach(t=>{it(t)}),this.subtitleTrack=-1,this.media=null}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:i,groupId:r,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,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 i=t.subtitleGroups||null,r=this.groupIds;let n=this.currentTrack;if(!i||(r==null?void 0:r.length)!==(i==null?void 0:i.length)||i!=null&&i.some(a=>(r==null?void 0:r.indexOf(a))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(u=>!i||i.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=Me(o,a);if(u>-1)n=a[u];else{const h=Me(o,this.tracks);n=this.tracks[h]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));const c={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i==null?void 0:i.join(",")}" group-id`),this.hls.trigger(p.SUBTITLE_TRACKS_UPDATED,c),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}else this.shouldReloadPlaylist(n)&&this.setSubtitleTrack(this.trackId)}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r<t.length;r++){const n=t[r];if(!(i&&!n.default||!i&&!e)&&(!e||nt(n,e)))return r}if(e){for(let r=0;r<t.length;r++){const n=t[r];if(ut(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){const n=t[r];if(ut(e.attrs,n.attrs,["LANGUAGE"]))return r}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const r=t[i];if(Qi(r,e))return i}}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){const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&nt(e,i))return i;const r=Me(e,this.tracksInGroup);if(r>-1){const n=this.tracksInGroup[r];return this.setSubtitleTrack(r),n}else{if(i)return null;{const n=Me(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){const i=t.id,r=t.groupId;let n=t.url;if(e)try{n=e.addDirectives(n)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(p.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:e||null})}}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Mt(e.textTracks),i=this.currentTrack;let r;if(i&&(r=t.filter(n=>Qi(i,n))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==r&&(n.mode="disabled")}),r){const n=this.subtitleDisplay?"showing":"hidden";r.mode!==n&&(r.mode=n)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!W(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r){this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:e});return}const n=!!r.details&&!r.details.live;if(e===this.trackId&&r===i&&n)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:a,groupId:o="",name:l,type:c,url:u}=r;this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:c,url:u});const h=this.switchParams(r.url,i==null?void 0:i.details);this.loadPlaylist(h)}}class jc{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t,i){const r=this.queues[t];r.push(e),r.length===1&&!i&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const i=new Promise(n=>{t=n}),r={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(r,e),i}executeNext(e){const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(r){S.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${r}`),i.onError(r);const n=this.buffers[e];n!=null&&n.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const Cn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;class qc{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=i=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:i,mediaSource:r}=this;this.log("Media source opened"),i&&(i.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(p.MEDIA_ATTACHED,{media:i,mediaSource:r})),r&&r.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:r}=this;i!==r&&S.error(`Media element src was set while attaching MediaSource (${r} > ${i})`)},this.hls=e;const t="[buffer-controller]";this.appendSource=e.config.preferManagedMediaSource,this.log=S.log.bind(S,t),this.warn=S.warn.bind(S,t),this.error=S.error.bind(S,t),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_APPENDING,this.onBufferAppending,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.BUFFER_EOS,this.onBufferEos,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.FRAG_PARSED,this.onFragParsed,this),e.on(p.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_APPENDING,this.onBufferAppending,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_EOS,this.onBufferEos,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.FRAG_PARSED,this.onFragParsed,this),e.off(p.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new jc(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const i=this.media=t.media,r=tt(this.appendSource);if(i&&r){var n;const a=this.mediaSource=new r;this.log(`created media source: ${(n=a.constructor)==null?void 0:n.name}`),a.addEventListener("sourceopen",this._onMediaSourceOpen),a.addEventListener("sourceended",this._onMediaSourceEnded),a.addEventListener("sourceclose",this._onMediaSourceClose),a.addEventListener("startstreaming",this._onStartStreaming),a.addEventListener("endstreaming",this._onEndStreaming);const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");const l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&a instanceof l,Dn(i),Xc(i,o),i.load()}catch{i.src=o}else i.src=o;i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:i}=this;if(t){if(this.log("media source detaching"),t.readyState==="open")try{t.endOfStream()}catch(r){this.warn(`onMediaDetaching: ${r.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),t.removeEventListener("startstreaming",this._onStartStreaming),t.removeEventListener("endstreaming",this._onEndStreaming),e&&(e.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(e.removeAttribute("src"),this.appendSource&&Dn(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(p.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{this.resetBuffer(e)}),this._initSourceBuffer()}resetBuffer(e){const t=this.sourceBuffer[e];try{if(t){var i;this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}}catch(r){this.warn(`onBufferReset ${e}`,r)}}onBufferCodecs(e,t){const i=this.getSourceBufferTypes().length,r=Object.keys(t);if(r.forEach(a=>{if(i){const l=this.tracks[a];if(l&&typeof l.buffer.changeType=="function"){var o;const{id:c,codec:u,levelCodec:h,container:d,metadata:f}=t[a],m=Sr(l.codec,l.levelCodec),g=m==null?void 0:m.replace(Cn,"$1");let y=Sr(u,h);const v=(o=y)==null?void 0:o.replace(Cn,"$1");if(y&&g!==v){a.slice(0,5)==="audio"&&(y=Ft(y,this.hls.config.preferManagedMediaSource));const T=`${d};codecs=${y}`;this.appendChangeType(a,T),this.log(`switching codec ${m} to ${y}`),this.tracks[a]={buffer:l.buffer,codec:u,container:d,levelCodec:h,metadata:f,id:c}}}}else this.pendingTracks[a]=t[a]}),i)return;const n=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==n&&(this.log(`${n} bufferCodec event(s) expected ${r.join(",")}`),this.bufferCodecEventsExpected=n),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks()}appendChangeType(e,t){const{operationQueue:i}=this,r={execute:()=>{const n=this.sourceBuffer[e];n&&(this.log(`changing ${e} sourceBuffer type to ${t}`),n.changeType(t)),i.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${e} SourceBuffer type`,n)}};i.append(r,e,!!this.pendingTracks[e])}onBufferAppending(e,t){const{hls:i,operationQueue:r,tracks:n}=this,{data:a,type:o,frag:l,part:c,chunkMeta:u}=t,h=u.buffering[o],d=self.performance.now();h.start=d;const f=l.stats.buffering,m=c?c.stats.buffering:null;f.start===0&&(f.start=d),m&&m.start===0&&(m.start=d);const g=n.audio;let y=!1;o==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(y=!this.lastMpegAudioChunk||u.id===1||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);const v=l.start,T={execute:()=>{if(h.executeStart=self.performance.now(),y){const x=this.sourceBuffer[o];if(x){const L=v-x.timestampOffset;Math.abs(L)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${v} (delta: ${L}) sn: ${l.sn})`),x.timestampOffset=v)}}this.appendExecutor(a,o)},onStart:()=>{},onComplete:()=>{const x=self.performance.now();h.executeEnd=h.end=x,f.first===0&&(f.first=x),m&&m.first===0&&(m.first=x);const{sourceBuffer:L}=this,E={};for(const k in L)E[k]=se.getBuffered(L[k]);this.appendErrors[o]=0,o==="audio"||o==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(p.BUFFER_APPENDED,{type:o,frag:l,part:c,chunkMeta:u,parent:l.type,timeRanges:E})},onError:x=>{const L={type:q.MEDIA_ERROR,parent:l.type,details:_.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:l,part:c,chunkMeta:u,error:x,err:x,fatal:!1};if(x.code===DOMException.QUOTA_EXCEEDED_ERR)L.details=_.BUFFER_FULL_ERROR;else{const E=++this.appendErrors[o];L.details=_.BUFFER_APPEND_ERROR,this.warn(`Failed ${E}/${i.config.appendErrorMaxRetry} times to append segment in "${o}" sourceBuffer`),E>=i.config.appendErrorMaxRetry&&(L.fatal=!0)}i.trigger(p.ERROR,L)}};r.append(T,o,!!this.pendingTracks[o])}onBufferFlushing(e,t){const{operationQueue:i}=this,r=n=>({execute:this.removeExecutor.bind(this,n,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(p.BUFFER_FLUSHED,{type:n})},onError:a=>{this.warn(`Failed to remove from ${n} SourceBuffer`,a)}});t.type?i.append(r(t.type),t.type):this.getSourceBufferTypes().forEach(n=>{i.append(r(n),n)})}onFragParsed(e,t){const{frag:i,part:r}=t,n=[],a=r?r.elementaryStreams:i.elementaryStreams;a[te.AUDIOVIDEO]?n.push("audiovideo"):(a[te.AUDIO]&&n.push("audio"),a[te.VIDEO]&&n.push("video"));const o=()=>{const l=self.performance.now();i.stats.buffering.end=l,r&&(r.stats.buffering.end=l);const c=r?r.stats:i.stats;this.hls.trigger(p.FRAG_BUFFERED,{frag:i,part:r,stats:c,id:i.type})};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,n)}onFragChanged(e,t){this.trimBuffers()}onBufferEos(e,t){this.getSourceBufferTypes().reduce((r,n)=>{const a=this.sourceBuffer[n];return a&&(!t.type||t.type===n)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${n} sourceBuffer now EOS`))),r&&!!(!a||a.ended)},!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(n=>{const a=this.sourceBuffer[n];a&&(a.ending=!1)});const{mediaSource:r}=this;if(!r||r.readyState!=="open"){r&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${r.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),r.endOfStream()}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.getSourceBufferTypes().length)return;const n=e.config,a=i.currentTime,o=t.levelTargetDuration,l=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(W(l)&&l>0){const c=Math.max(l,o),u=Math.floor(a/o)*o-c;this.flushBackBuffer(a,o,u)}if(W(n.frontBufferFlushThreshold)&&n.frontBufferFlushThreshold>0){const c=Math.max(n.maxBufferLength,n.frontBufferFlushThreshold),u=Math.max(c,o),h=Math.floor(a/o)*o+u;this.flushFrontBuffer(a,o,h)}}flushBackBuffer(e,t,i){const{details:r,sourceBuffer:n}=this;this.getSourceBufferTypes().forEach(o=>{const l=n[o];if(l){const c=se.getBuffered(l);if(c.length>0&&i>c.start(0)){if(this.hls.trigger(p.BACK_BUFFER_REACHED,{bufferEnd:i}),r!=null&&r.live)this.hls.trigger(p.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l.ended&&c.end(c.length-1)-e<t*2){this.log(`Cannot flush ${o} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:o})}}})}flushFrontBuffer(e,t,i){const{sourceBuffer:r}=this;this.getSourceBufferTypes().forEach(a=>{const o=r[a];if(o){const l=se.getBuffered(o),c=l.length;if(c<2)return;const u=l.start(c-1),h=l.end(c-1);if(i>u||e>=u&&e<=h)return;if(o.ended&&e-h<2*t){this.log(`Cannot flush ${a} front buffer while SourceBuffer is in ended state`);return}this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:a})}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:e,hls:t,media:i,mediaSource:r}=this,n=e.fragments[0].start+e.totalduration,a=i.duration,o=W(r.duration)?r.duration:0;e.live&&t.config.liveDurationInfinity?(r.duration=1/0,this.updateSeekableRange(e)):(n>o&&n>a||!W(a))&&(this.log(`Updating Media Source duration to ${n.toFixed(3)}`),r.duration=n)}updateSeekableRange(e){const t=this.mediaSource,i=e.fragments;if(i.length&&e.live&&t!=null&&t.setLiveSeekableRange){const n=Math.max(0,i[0].start),a=Math.max(n,n+e.totalduration);this.log(`Media Source duration is set to ${t.duration}. Setting seekable range to ${n}-${a}.`),t.setLiveSeekableRange(n,a)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:i}=this,r=Object.keys(i).length;if(r&&(!e||r===2||"audiovideo"in i)){this.createSourceBuffers(i),this.pendingTracks={};const n=this.getSourceBufferTypes();if(n.length)this.hls.trigger(p.BUFFER_CREATED,{tracks:this.tracks}),n.forEach(a=>{t.executeNext(a)});else{const a=new Error("could not create source buffer for media codec(s)");this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:a,reason:a.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const r in e)if(!t[r]){const n=e[r];if(!n)throw Error(`source buffer exists for track ${r}, however track does not`);let a=n.levelCodec||n.codec;a&&r.slice(0,5)==="audio"&&(a=Ft(a,this.hls.config.preferManagedMediaSource));const o=`${n.container};codecs=${a}`;this.log(`creating sourceBuffer(${o})`);try{const l=t[r]=i.addSourceBuffer(o),c=r;this.addBufferListener(c,"updatestart",this._onSBUpdateStart),this.addBufferListener(c,"updateend",this._onSBUpdateEnd),this.addBufferListener(c,"error",this._onSBUpdateError),this.addBufferListener(c,"bufferedchange",(u,h)=>{const d=h.removedRanges;d!=null&&d.length&&this.hls.trigger(p.BUFFER_FLUSHED,{type:r})}),this.tracks[r]={buffer:l,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(l){this.error(`error while trying to add sourceBuffer: ${l.message}`),this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:l,sourceBufferName:r,mimeType:o})}}}get mediaSrc(){var e;const t=((e=this.media)==null?void 0:e.firstChild)||this.media;return t==null?void 0:t.src}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const{operationQueue:i}=this;i.current(e).onComplete(),i.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){var i;const r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${r}`,t),this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});const n=this.operationQueue.current(e);n&&n.onError(r)}removeExecutor(e,t,i){const{media:r,mediaSource:n,operationQueue:a,sourceBuffer:o}=this,l=o[e];if(!r||!n||!l){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),a.shiftAndExecuteNext(e);return}const c=W(r.duration)?r.duration:1/0,u=W(n.duration)?n.duration:1/0,h=Math.max(0,t),d=Math.min(i,c,u);d>h&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${h},${d}] from the ${e} SourceBuffer`),l.remove(h,d)):a.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.sourceBuffer[t];if(!i){if(!this.pendingTracks[t])throw new Error(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);return}i.ended=!1,i.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length){this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}const{operationQueue:i}=this,r=t.map(n=>i.appendBlocker(n));Promise.all(r).then(()=>{e(),t.forEach(n=>{const a=this.sourceBuffer[n];a!=null&&a.updating||i.shiftAndExecuteNext(n)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,i){const r=this.sourceBuffer[e];if(!r)return;const n=i.bind(this,e);this.listeners[e].push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach(i=>{t.removeEventListener(i.event,i.listener)})}}function Dn(s){const e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function Xc(s,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}const _n={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},In=function(e){let t=e;return _n.hasOwnProperty(e)&&(t=_n[e]),String.fromCharCode(t)},_e=15,Ke=100,Zc={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Qc={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Jc={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},eu={25:2,26:4,29:6,30:8,31:10,27:13,28:15},tu=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class iu{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;S.log(`${this.time} [${e}] ${i}`)}}}const Qe=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class wn{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 i=0;i<t.length;i++){const r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class su{constructor(){this.uchar=" ",this.penState=new wn}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 ru{constructor(e){this.chars=[],this.pos=0,this.currPenState=new wn,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ke;t++)this.chars.push(new su);this.logger=e}equals(e){for(let t=0;t<Ke;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Ke;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Ke;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>Ke&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ke)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i<t+1;i++)this.chars[i].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=In(e);if(this.pos>=Ke){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<Ke;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 i=0;i<Ke;i++){const r=this.chars[i].uchar;r!==" "&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class Ji{constructor(e){this.rows=[],this.currRow=_e-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<_e;t++)this.rows.push(new ru(e));this.logger=e}reset(){for(let e=0;e<_e;e++)this.rows[e].clear();this.currRow=_e-1}equals(e){let t=!0;for(let i=0;i<_e;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<_e;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<_e;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 = "+JSON.stringify(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<_e;o++)this.rows[o].clear();const n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[n].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(a.rows[n+c])}}this.currRow=t;const i=this.rows[this.currRow];if(e.indent!==null){const n=e.indent,a=Math.max(n-1,0);i.setCursor(e.indent),e.color=i.chars[a].penState.foreground}const r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+JSON.stringify(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 i="",r=-1;for(let n=0;n<_e;n++){const a=this.rows[n].getTextString();a&&(r=n+1,e?t.push("Row "+r+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
14
+ initSegmentChange: ${B}`);const b=new Uc(i,r,t,o,u);this.configureTransmuxer(b)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:g,chunkMeta:c,state:C},e instanceof ArrayBuffer?[e]:[]);else if(f){const b=f.push(e,g,c,C);Xt(b)?(f.async=!0,b.then(D=>{this.handleTransmuxComplete(D)}).catch(D=>{this.transmuxerError(D,c,"transmuxer-interface push error")})):(f.async=!1,this.handleTransmuxComplete(b))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let i=t.flush(e);Xt(i)||t.async?(Xt(i)||(i=Promise.resolve(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,i){this.hls&&(this.error=e,this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}onWorkerMessage(e){const t=e.data,i=this.hls;switch(t.event){case"init":{var r;const n=(r=this.workerContext)==null?void 0:r.objectURL;n&&self.URL.revokeObjectURL(n);break}case"transmuxComplete":{this.handleTransmuxComplete(t.data);break}case"flush":{this.onFlush(t.data);break}case"workerLog":S[t.data.logType]&&S[t.data.logType](t.data.message);break;default:{t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,i.trigger(t.event,t.data);break}}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}function An(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(!ut(s[t].attrs,e[t].attrs))return!1;return!0}function ut(s,e,t){const i=s["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>s[r]!==e[r])}function Qi(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}const Ln=100;class Vc extends Hi{constructor(e,t,i){super(e,t,i,"[audio-stream-controller]",j.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-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.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.ERROR,this.onError,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:n}){if(i==="main"){const a=t.cc;this.initPTS[t.cc]={baseTime:r,timescale:n},this.log(`InitPTS for cc: ${a} found from main: ${r}`),this.videoTrackCC=a,this.state===M.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=M.STOPPED;return}const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(Ln),t>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=M.IDLE):(this.loadedmetadata=!1,this.state=M.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case M.IDLE:this.doTickIdle();break;case M.WAITING_TRACK:{var e;const{levels:i,trackId:r}=this,n=i==null||(e=i[r])==null?void 0:e.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=M.WAITING_INIT_PTS}break}case M.FRAG_LOADING_WAITING_RETRY:{var t;const i=performance.now(),r=this.retryDate;if(!r||i>=r||(t=this.media)!=null&&t.seeking){const{levels:n,trackId:a}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((n==null?void 0:n[a])||null),this.state=M.IDLE}break}case M.WAITING_INIT_PTS:{const i=this.waitingData;if(i){const{frag:r,part:n,cache:a,complete:o}=i;if(this.initPTS[r.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=M.FRAG_LOADING;const l=a.flush(),c={frag:r,part:n,payload:l,networkDetails:null};this._handleFragmentLoadProgress(c),o&&super._handleFragmentLoadComplete(c)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${r.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),c=se.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);Bi(c.end,this.config.maxFragLookUpTolerance,r)<0&&(this.log(`Waiting fragment cc (${r.cc}) @ ${r.start} cancelled because another fragment at ${c.end} is needed`),this.clearWaitingFragment())}}else this.state=M.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=M.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:i,trackId:r}=this,n=e.config;if(!i&&(this.startFragRequested||!n.startFragPrefetch)||!(t!=null&&t[r]))return;const a=t[r],o=a.details;if(!o||o.live&&this.levelLastLoaded!==a||this.waitForCdnTuneIn(o)){this.state=M.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,te.AUDIO,j.AUDIO));const c=this.getFwdBufferInfo(l,j.AUDIO);if(c===null)return;const{bufferedTrack:u,switchingTrack:h}=this;if(!h&&this._streamEnded(c,o)){e.trigger(p.BUFFER_EOS,{type:"audio"}),this.state=M.ENDED;return}const d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,j.MAIN),f=c.len,m=this.getMaxBufferLength(d==null?void 0:d.len),g=o.fragments,y=g[0].start;let v=this.flushing?this.getLoadPosition():c.end;if(h&&i){const E=this.getLoadPosition();u&&!ut(h.attrs,u.attrs)&&(v=E),o.PTSKnown&&E<y&&(c.end>y||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=y+.05)}if(f>=m&&!h&&v<g[g.length-1].start)return;let T=this.getNextFragment(v,o),x=!1;if(T&&this.isLoopLoading(T,v)&&(x=!!T.gap,T=this.getNextFragmentLoopLoading(T,o,c,j.MAIN,m)),!T){this.bufferFlushed=!0;return}const L=d&&T.start>d.end+o.targetduration;if(L||!(d!=null&&d.len)&&c.len){const E=this.getAppendedFrag(T.start,j.MAIN);if(E===null||(x||(x=!!E.gap||!!L&&d.len===0),L&&!x||x&&c.nextStart&&c.nextStart<E.end))return}this.loadFragment(T,a,v)}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new st(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?this.setInterval(Ln):this.resetTransmuxer(),i?(this.switchingTrack=t,this.state=M.IDLE,this.flushAudioIfNeeded(t)):(this.switchingTrack=null,this.bufferedTrack=t,this.state=M.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(p.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var i;if(this.mainDetails==null){this.cachedTrackLoadedData=t;return}const{levels:r}=this,{details:n,id:a}=t;if(!r){this.warn(`Audio tracks were reset while loading level ${a}`);return}this.log(`Audio track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const o=r[a];let l=0;if(n.live||(i=o.details)!=null&&i.live){this.checkLiveUpdate(n);const u=this.mainDetails;if(n.deltaUpdateFailed||!u)return;if(!o.details&&n.hasProgramDateTime&&u.hasProgramDateTime)Wt(n,u),l=n.fragments[0].start;else{var c;l=this.alignPlaylists(n,o.details,(c=this.levelLastLoaded)==null?void 0:c.details)}}o.details=n,this.levelLastLoaded=o,!this.startFragRequested&&(this.mainDetails||!n.live)&&this.setStartPosition(this.mainDetails||n,l),this.state===M.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=M.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:r,payload:n}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const c=l[o];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const u=c.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const h=a.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new bn(this.hls,j.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[i.cc],m=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){const y=r?r.index:-1,v=y!==-1,T=new Ui(i.level,i.sn,i.stats.chunkCount,n.byteLength,y,v);d.push(n,m,h,"",i,r,u.totalduration,!1,T,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:g}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new en,complete:!1};g.push(new Uint8Array(n)),this.waitingVideoCC=this.videoTrackCC,this.state=M.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:i,part:r}=t;if(i.type!==j.AUDIO){if(!this.loadedmetadata&&i.type===j.MAIN){const n=this.videoBuffer||this.media;n&&se.getBuffered(n).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(i.sn!=="initSegment"){this.fragPrevious=i;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(p.AUDIO_TRACK_SWITCHED,he({},n)))}this.fragBufferedComplete(i,r)}onError(e,t){var i;if(t.fatal){this.state=M.ERROR;return}switch(t.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(j.AUDIO,t);break;case _.AUDIO_TRACK_LOAD_ERROR:case _.AUDIO_TRACK_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===M.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===ee.AUDIO_TRACK&&(this.state=M.IDLE);break;case _.BUFFER_APPEND_ERROR:case _.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="audio")return;if(t.details===_.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case _.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==te.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==te.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===M.ENDED&&(this.state=M.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,j.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:u}=o,{details:h}=u,{audio:d,text:f,id3:m,initSegment:g}=n;if(this.fragContextChanged(l)||!h){this.fragmentTracker.removeFragment(l);return}if(this.state=M.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){const y=l.initSegment||l;this._bufferInitSegment(u,g.tracks,y,a),r.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:i,tracks:g.tracks})}if(d){const{startPTS:y,endPTS:v,startDTS:T,endDTS:x}=d;c&&(c.elementaryStreams[te.AUDIO]={startPTS:y,endPTS:v,startDTS:T,endDTS:x}),l.setElementaryStreamInfo(te.AUDIO,y,v,T,x),this.bufferFragmentData(d,l,c,a)}if(m!=null&&(t=m.samples)!=null&&t.length){const y=oe({id:i,frag:l,details:h},m);r.trigger(p.FRAG_PARSING_METADATA,y)}if(f){const y=oe({id:i,frag:l,details:h},f);r.trigger(p.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,i,r){if(this.state!==M.PARSING)return;t.video&&delete t.video;const n=t.audio;if(!n)return;n.id="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(p.BUFFER_CODECS,t);const o=n.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:o};this.hls.trigger(p.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){const r=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||r===de.NOT_LOADED||r===de.PARTIAL){var n;if(e.sn==="initSegment")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=M.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragments[0].start!==t.details.fragments[0].start&&Wt(t.details,a)}else this.startFragRequested=!0,super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){const{media:t,bufferedTrack:i}=this,r=i==null?void 0:i.attrs,n=e.attrs;t&&r&&(r.CHANNELS!==n.CHANNELS||i.name!==e.name||i.lang!==e.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(p.AUDIO_TRACK_SWITCHED,he({},e))}}class Kc extends $i{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(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.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:i,groupId:r,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Audio track with id:${i} and group:${r} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,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 i=t.audioGroups||null,r=this.groupIds;let n=this.currentTrack;if(!i||(r==null?void 0:r.length)!==(i==null?void 0:i.length)||i!=null&&i.some(o=>(r==null?void 0:r.indexOf(o))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!i||i.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 l=this.hls.config.audioPreference;if(!n&&l){const d=Me(l,o,at);if(d>-1)n=o[d];else{const f=Me(l,this.tracks);n=this.tracks[f]}}let c=this.findTrackId(n);c===-1&&n&&(c=this.findTrackId(null));const u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(p.AUDIO_TRACKS_UPDATED,u);const h=this.trackId;if(c!==-1&&h===-1)this.setAudioTrack(c);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(p.ERROR,{type:q.MEDIA_ERROR,details:_.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}else this.shouldReloadPlaylist(n)&&this.setAudioTrack(this.trackId)}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.requestScheduled=-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 i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const r=this.currentTrack;if(r&&nt(e,r,at))return r;const n=Me(e,this.tracksInGroup,at);if(n>-1){const a=this.tracksInGroup[n];return this.setAudioTrack(n),a}else if(r){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=Kl(e,t.levels,i,a,at);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=Me(e,i);if(a>-1)return i[a]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,r=t[e],n=r.details&&!r.details.live;if(e===this.trackId&&r===i&&n||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(p.AUDIO_TRACK_SWITCHING,he({},r)),n))return;const a=this.switchParams(r.url,i==null?void 0:i.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const r=t[i];if(!(this.selectDefaultTrack&&!r.default)&&(!e||nt(e,r,at)))return i}if(e){const{name:i,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l}=e;for(let c=0;c<t.length;c++){const u=t[c];if(nt({name:i,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l},u,at))return c}for(let c=0;c<t.length;c++){const u=t[c];if(ut(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<t.length;c++){const u=t[c];if(ut(e.attrs,u.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(e){const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){super.loadPlaylist();const i=t.id,r=t.groupId;let n=t.url;if(e)try{n=e.addDirectives(n)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`loading audio-track playlist ${i} "${t.name}" lang:${t.lang} group:${r}`),this.clearTimer(),this.hls.trigger(p.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:e||null})}}}const Rn=500;class Wc extends Hi{constructor(e,t,i){super(e,t,i,"[subtitle-stream-controller]",j.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.ERROR,this.onError,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.ERROR,this.onError,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=M.IDLE,this.setInterval(Rn),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:r}=t;if(this.fragPrevious=i,this.state=M.IDLE,!r)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a;const o=i.start;for(let c=0;c<n.length;c++)if(o>=n[c].start&&o<=n[c].end){a=n[c];break}const l=i.start+i.duration;a?a.end=l:(a={start:o,end:l},n.push(a)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null)}onBufferFlushing(e,t){const{startOffset:i,endOffset:r}=t;if(i===0&&r!==Number.POSITIVE_INFINITY){const n=r-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(i,n,j.SUBTITLE)}}onFragBuffered(e,t){if(!this.loadedmetadata&&t.frag.type===j.MAIN){var i;(i=this.media)!=null&&i.buffered.length&&(this.loadedmetadata=!0)}}onError(e,t){const i=t.frag;(i==null?void 0:i.type)===j.SUBTITLE&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==M.STOPPED&&(this.state=M.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&An(this.levels,t)){this.levels=t.map(i=>new st(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const r=new st(i);return this.tracksBuffered[r.id]=[],r}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,j.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}const r=this.levels[this.currentTrackId];r!=null&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.setInterval(Rn)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:r,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=n[r];if(o>=n.length||o!==r||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(a.live||(i=l.details)!=null&&i.live){const h=this.mainDetails;if(a.deltaUpdateFailed||!h)return;const d=h.fragments[0];if(!l.details)a.hasProgramDateTime&&h.hasProgramDateTime?(Wt(a,h),c=a.fragments[0].start):d&&(c=d.start,Mi(a,c));else{var u;c=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details),c===0&&d&&(c=d.start,Mi(a,c))}}l.details=a,this.levelLastLoaded=l,!this.startFragRequested&&(this.mainDetails||!a.live)&&this.setStartPosition(this.mainDetails||a,c),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===M.IDLE&&(Gt(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,r=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&r!=null&&r.key&&r.iv&&r.method==="AES-128"){const a=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer).catch(o=>{throw n.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const l=performance.now();n.trigger(p.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=M.IDLE})}}doTick(){if(!this.media){this.state=M.IDLE;return}if(this.state===M.IDLE){const{currentTrackId:e,levels:t}=this,i=t==null?void 0:t[e];if(!i||!t.length||!i.details)return;const{config:r}=this,n=this.getLoadPosition(),a=se.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,r.maxBufferHole),{end:o,len:l}=a,c=this.getFwdBufferInfo(this.media,j.MAIN),u=i.details,h=this.getMaxBufferLength(c==null?void 0:c.len)+u.levelTargetDuration;if(l>h)return;const d=u.fragments,f=d.length,m=u.edge;let g=null;const y=this.fragPrevious;if(o<m){const v=r.maxFragLookUpTolerance,T=o>m-v?0:v;g=Gt(y,d,Math.max(d[0].start,o),T),!g&&y&&y.start<d[0].start&&(g=d[0])}else g=d[f-1];if(!g)return;if(g=this.mapToInitFragWhenRequired(g),g.sn!=="initSegment"){const v=g.sn-u.startSN,T=d[v-1];T&&T.cc===g.cc&&this.fragmentTracker.getState(T)===de.NOT_LOADED&&(g=T)}this.fragmentTracker.getState(g)===de.NOT_LOADED&&this.loadFragment(g,i,o)}}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,i){this.fragCurrent=e,e.sn==="initSegment"?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,i))}get mediaBufferTimeRanges(){return new zc(this.tracksBuffered[this.currentTrackId]||[])}}class zc{constructor(e){this.buffered=void 0;const t=(i,r,n)=>{if(r=r>>>0,r>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}class Yc extends $i{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.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=Mt(this.media.textTracks);for(let n=0;n<i.length;n++)if(i[n].mode==="hidden")t=i[n];else if(i[n].mode==="showing"){t=i[n];break}const r=this.findTrackForTextTrack(t);this.subtitleTrack!==r&&this.setSubtitleTrack(r)},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(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.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(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),Mt(this.media.textTracks).forEach(t=>{it(t)}),this.subtitleTrack=-1,this.media=null}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:i,groupId:r,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,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 i=t.subtitleGroups||null,r=this.groupIds;let n=this.currentTrack;if(!i||(r==null?void 0:r.length)!==(i==null?void 0:i.length)||i!=null&&i.some(a=>(r==null?void 0:r.indexOf(a))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(u=>!i||i.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=Me(o,a);if(u>-1)n=a[u];else{const h=Me(o,this.tracks);n=this.tracks[h]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));const c={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i==null?void 0:i.join(",")}" group-id`),this.hls.trigger(p.SUBTITLE_TRACKS_UPDATED,c),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}else this.shouldReloadPlaylist(n)&&this.setSubtitleTrack(this.trackId)}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r<t.length;r++){const n=t[r];if(!(i&&!n.default||!i&&!e)&&(!e||nt(n,e)))return r}if(e){for(let r=0;r<t.length;r++){const n=t[r];if(ut(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){const n=t[r];if(ut(e.attrs,n.attrs,["LANGUAGE"]))return r}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const r=t[i];if(Qi(r,e))return i}}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){const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&nt(e,i))return i;const r=Me(e,this.tracksInGroup);if(r>-1){const n=this.tracksInGroup[r];return this.setSubtitleTrack(r),n}else{if(i)return null;{const n=Me(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){const i=t.id,r=t.groupId;let n=t.url;if(e)try{n=e.addDirectives(n)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(p.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:e||null})}}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Mt(e.textTracks),i=this.currentTrack;let r;if(i&&(r=t.filter(n=>Qi(i,n))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==r&&(n.mode="disabled")}),r){const n=this.subtitleDisplay?"showing":"hidden";r.mode!==n&&(r.mode=n)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!W(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r){this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:e});return}const n=!!r.details&&!r.details.live;if(e===this.trackId&&r===i&&n)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:a,groupId:o="",name:l,type:c,url:u}=r;this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:c,url:u});const h=this.switchParams(r.url,i==null?void 0:i.details);this.loadPlaylist(h)}}class jc{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t,i){const r=this.queues[t];r.push(e),r.length===1&&!i&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const i=new Promise(n=>{t=n}),r={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(r,e),i}executeNext(e){const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(r){S.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${r}`),i.onError(r);const n=this.buffers[e];n!=null&&n.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const Cn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;class qc{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=i=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:i,mediaSource:r}=this;this.log("Media source opened"),i&&(i.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(p.MEDIA_ATTACHED,{media:i,mediaSource:r})),r&&r.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:r}=this;i!==r&&S.error(`Media element src was set while attaching MediaSource (${r} > ${i})`)},this.hls=e;const t="[buffer-controller]";this.appendSource=e.config.preferManagedMediaSource,this.log=S.log.bind(S,t),this.warn=S.warn.bind(S,t),this.error=S.error.bind(S,t),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_APPENDING,this.onBufferAppending,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.BUFFER_EOS,this.onBufferEos,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.FRAG_PARSED,this.onFragParsed,this),e.on(p.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_APPENDING,this.onBufferAppending,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_EOS,this.onBufferEos,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.FRAG_PARSED,this.onFragParsed,this),e.off(p.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new jc(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const i=this.media=t.media,r=tt(this.appendSource);if(i&&r){var n;const a=this.mediaSource=new r;this.log(`created media source: ${(n=a.constructor)==null?void 0:n.name}`),a.addEventListener("sourceopen",this._onMediaSourceOpen),a.addEventListener("sourceended",this._onMediaSourceEnded),a.addEventListener("sourceclose",this._onMediaSourceClose),a.addEventListener("startstreaming",this._onStartStreaming),a.addEventListener("endstreaming",this._onEndStreaming);const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");const l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&a instanceof l,Dn(i),Xc(i,o),i.load()}catch{i.src=o}else i.src=o;i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:i}=this;if(t){if(this.log("media source detaching"),t.readyState==="open")try{t.endOfStream()}catch(r){this.warn(`onMediaDetaching: ${r.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),t.removeEventListener("startstreaming",this._onStartStreaming),t.removeEventListener("endstreaming",this._onEndStreaming),e&&(e.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(e.removeAttribute("src"),this.appendSource&&Dn(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(p.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{this.resetBuffer(e)}),this._initSourceBuffer()}resetBuffer(e){const t=this.sourceBuffer[e];try{if(t){var i;this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}}catch(r){this.warn(`onBufferReset ${e}`,r)}}onBufferCodecs(e,t){const i=this.getSourceBufferTypes().length,r=Object.keys(t);if(r.forEach(a=>{if(i){const l=this.tracks[a];if(l&&typeof l.buffer.changeType=="function"){var o;const{id:c,codec:u,levelCodec:h,container:d,metadata:f}=t[a],m=Sr(l.codec,l.levelCodec),g=m==null?void 0:m.replace(Cn,"$1");let y=Sr(u,h);const v=(o=y)==null?void 0:o.replace(Cn,"$1");if(y&&g!==v){a.slice(0,5)==="audio"&&(y=Ft(y,this.hls.config.preferManagedMediaSource));const T=`${d};codecs=${y}`;this.appendChangeType(a,T),this.log(`switching codec ${m} to ${y}`),this.tracks[a]={buffer:l.buffer,codec:u,container:d,levelCodec:h,metadata:f,id:c}}}}else this.pendingTracks[a]=t[a]}),i)return;const n=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==n&&(this.log(`${n} bufferCodec event(s) expected ${r.join(",")}`),this.bufferCodecEventsExpected=n),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks()}appendChangeType(e,t){const{operationQueue:i}=this,r={execute:()=>{const n=this.sourceBuffer[e];n&&(this.log(`changing ${e} sourceBuffer type to ${t}`),n.changeType(t)),i.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${e} SourceBuffer type`,n)}};i.append(r,e,!!this.pendingTracks[e])}onBufferAppending(e,t){const{hls:i,operationQueue:r,tracks:n}=this,{data:a,type:o,frag:l,part:c,chunkMeta:u}=t,h=u.buffering[o],d=self.performance.now();h.start=d;const f=l.stats.buffering,m=c?c.stats.buffering:null;f.start===0&&(f.start=d),m&&m.start===0&&(m.start=d);const g=n.audio;let y=!1;o==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(y=!this.lastMpegAudioChunk||u.id===1||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);const v=l.start,T={execute:()=>{if(h.executeStart=self.performance.now(),y){const x=this.sourceBuffer[o];if(x){const L=v-x.timestampOffset;Math.abs(L)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${v} (delta: ${L}) sn: ${l.sn})`),x.timestampOffset=v)}}this.appendExecutor(a,o)},onStart:()=>{},onComplete:()=>{const x=self.performance.now();h.executeEnd=h.end=x,f.first===0&&(f.first=x),m&&m.first===0&&(m.first=x);const{sourceBuffer:L}=this,E={};for(const k in L)E[k]=se.getBuffered(L[k]);this.appendErrors[o]=0,o==="audio"||o==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(p.BUFFER_APPENDED,{type:o,frag:l,part:c,chunkMeta:u,parent:l.type,timeRanges:E})},onError:x=>{const L={type:q.MEDIA_ERROR,parent:l.type,details:_.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:l,part:c,chunkMeta:u,error:x,err:x,fatal:!1};if(x.code===DOMException.QUOTA_EXCEEDED_ERR)L.details=_.BUFFER_FULL_ERROR;else{const E=++this.appendErrors[o];L.details=_.BUFFER_APPEND_ERROR,this.warn(`Failed ${E}/${i.config.appendErrorMaxRetry} times to append segment in "${o}" sourceBuffer`),E>=i.config.appendErrorMaxRetry&&(L.fatal=!0)}i.trigger(p.ERROR,L)}};r.append(T,o,!!this.pendingTracks[o])}onBufferFlushing(e,t){const{operationQueue:i}=this,r=n=>({execute:this.removeExecutor.bind(this,n,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(p.BUFFER_FLUSHED,{type:n})},onError:a=>{this.warn(`Failed to remove from ${n} SourceBuffer`,a)}});t.type?i.append(r(t.type),t.type):this.getSourceBufferTypes().forEach(n=>{i.append(r(n),n)})}onFragParsed(e,t){const{frag:i,part:r}=t,n=[],a=r?r.elementaryStreams:i.elementaryStreams;a[te.AUDIOVIDEO]?n.push("audiovideo"):(a[te.AUDIO]&&n.push("audio"),a[te.VIDEO]&&n.push("video"));const o=()=>{const l=self.performance.now();i.stats.buffering.end=l,r&&(r.stats.buffering.end=l);const c=r?r.stats:i.stats;this.hls.trigger(p.FRAG_BUFFERED,{frag:i,part:r,stats:c,id:i.type})};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,n)}onFragChanged(e,t){this.trimBuffers()}onBufferEos(e,t){this.getSourceBufferTypes().reduce((r,n)=>{const a=this.sourceBuffer[n];return a&&(!t.type||t.type===n)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${n} sourceBuffer now EOS`))),r&&!!(!a||a.ended)},!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(n=>{const a=this.sourceBuffer[n];a&&(a.ending=!1)});const{mediaSource:r}=this;if(!r||r.readyState!=="open"){r&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${r.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),r.endOfStream()}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.getSourceBufferTypes().length)return;const n=e.config,a=i.currentTime,o=t.levelTargetDuration,l=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(W(l)&&l>0){const c=Math.max(l,o),u=Math.floor(a/o)*o-c;this.flushBackBuffer(a,o,u)}if(W(n.frontBufferFlushThreshold)&&n.frontBufferFlushThreshold>0){const c=Math.max(n.maxBufferLength,n.frontBufferFlushThreshold),u=Math.max(c,o),h=Math.floor(a/o)*o+u;this.flushFrontBuffer(a,o,h)}}flushBackBuffer(e,t,i){const{details:r,sourceBuffer:n}=this;this.getSourceBufferTypes().forEach(o=>{const l=n[o];if(l){const c=se.getBuffered(l);if(c.length>0&&i>c.start(0)){if(this.hls.trigger(p.BACK_BUFFER_REACHED,{bufferEnd:i}),r!=null&&r.live)this.hls.trigger(p.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l.ended&&c.end(c.length-1)-e<t*2){this.log(`Cannot flush ${o} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:o})}}})}flushFrontBuffer(e,t,i){const{sourceBuffer:r}=this;this.getSourceBufferTypes().forEach(a=>{const o=r[a];if(o){const l=se.getBuffered(o),c=l.length;if(c<2)return;const u=l.start(c-1),h=l.end(c-1);if(i>u||e>=u&&e<=h)return;if(o.ended&&e-h<2*t){this.log(`Cannot flush ${a} front buffer while SourceBuffer is in ended state`);return}this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:a})}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:e,hls:t,media:i,mediaSource:r}=this,n=e.fragments[0].start+e.totalduration,a=i.duration,o=W(r.duration)?r.duration:0;e.live&&t.config.liveDurationInfinity?(r.duration=1/0,this.updateSeekableRange(e)):(n>o&&n>a||!W(a))&&(this.log(`Updating Media Source duration to ${n.toFixed(3)}`),r.duration=n)}updateSeekableRange(e){const t=this.mediaSource,i=e.fragments;if(i.length&&e.live&&t!=null&&t.setLiveSeekableRange){const n=Math.max(0,i[0].start),a=Math.max(n,n+e.totalduration);this.log(`Media Source duration is set to ${t.duration}. Setting seekable range to ${n}-${a}.`),t.setLiveSeekableRange(n,a)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:i}=this,r=Object.keys(i).length;if(r&&(!e||r===2||"audiovideo"in i)){this.createSourceBuffers(i),this.pendingTracks={};const n=this.getSourceBufferTypes();if(n.length)this.hls.trigger(p.BUFFER_CREATED,{tracks:this.tracks}),n.forEach(a=>{t.executeNext(a)});else{const a=new Error("could not create source buffer for media codec(s)");this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:a,reason:a.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const r in e)if(!t[r]){const n=e[r];if(!n)throw Error(`source buffer exists for track ${r}, however track does not`);let a=n.levelCodec||n.codec;a&&r.slice(0,5)==="audio"&&(a=Ft(a,this.hls.config.preferManagedMediaSource));const o=`${n.container};codecs=${a}`;this.log(`creating sourceBuffer(${o})`);try{const l=t[r]=i.addSourceBuffer(o),c=r;this.addBufferListener(c,"updatestart",this._onSBUpdateStart),this.addBufferListener(c,"updateend",this._onSBUpdateEnd),this.addBufferListener(c,"error",this._onSBUpdateError),this.addBufferListener(c,"bufferedchange",(u,h)=>{const d=h.removedRanges;d!=null&&d.length&&this.hls.trigger(p.BUFFER_FLUSHED,{type:r})}),this.tracks[r]={buffer:l,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(l){this.error(`error while trying to add sourceBuffer: ${l.message}`),this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:l,sourceBufferName:r,mimeType:o})}}}get mediaSrc(){var e;const t=((e=this.media)==null?void 0:e.firstChild)||this.media;return t==null?void 0:t.src}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const{operationQueue:i}=this;i.current(e).onComplete(),i.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){var i;const r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${r}`,t),this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});const n=this.operationQueue.current(e);n&&n.onError(r)}removeExecutor(e,t,i){const{media:r,mediaSource:n,operationQueue:a,sourceBuffer:o}=this,l=o[e];if(!r||!n||!l){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),a.shiftAndExecuteNext(e);return}const c=W(r.duration)?r.duration:1/0,u=W(n.duration)?n.duration:1/0,h=Math.max(0,t),d=Math.min(i,c,u);d>h&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${h},${d}] from the ${e} SourceBuffer`),l.remove(h,d)):a.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.sourceBuffer[t];if(!i){if(!this.pendingTracks[t])throw new Error(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);return}i.ended=!1,i.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length){this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}const{operationQueue:i}=this,r=t.map(n=>i.appendBlocker(n));Promise.all(r).then(()=>{e(),t.forEach(n=>{const a=this.sourceBuffer[n];a!=null&&a.updating||i.shiftAndExecuteNext(n)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,i){const r=this.sourceBuffer[e];if(!r)return;const n=i.bind(this,e);this.listeners[e].push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach(i=>{t.removeEventListener(i.event,i.listener)})}}function Dn(s){const e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function Xc(s,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}const _n={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},In=function(e){let t=e;return _n.hasOwnProperty(e)&&(t=_n[e]),String.fromCharCode(t)},_e=15,Ve=100,Zc={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Qc={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Jc={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},eu={25:2,26:4,29:6,30:8,31:10,27:13,28:15},tu=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class iu{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;S.log(`${this.time} [${e}] ${i}`)}}}const Qe=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class wn{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 i=0;i<t.length;i++){const r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class su{constructor(){this.uchar=" ",this.penState=new wn}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 ru{constructor(e){this.chars=[],this.pos=0,this.currPenState=new wn,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ve;t++)this.chars.push(new su);this.logger=e}equals(e){for(let t=0;t<Ve;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Ve;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Ve;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>Ve&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ve)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i<t+1;i++)this.chars[i].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=In(e);if(this.pos>=Ve){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<Ve;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 i=0;i<Ve;i++){const r=this.chars[i].uchar;r!==" "&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class Ji{constructor(e){this.rows=[],this.currRow=_e-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<_e;t++)this.rows.push(new ru(e));this.logger=e}reset(){for(let e=0;e<_e;e++)this.rows[e].clear();this.currRow=_e-1}equals(e){let t=!0;for(let i=0;i<_e;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<_e;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<_e;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 = "+JSON.stringify(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<_e;o++)this.rows[o].clear();const n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[n].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(a.rows[n+c])}}this.currRow=t;const i=this.rows[this.currRow];if(e.indent!==null){const n=e.indent,a=Math.max(n-1,0);i.setCursor(e.indent),e.color=i.chars[a].penState.foreground}const r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+JSON.stringify(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 i="",r=-1;for(let n=0;n<_e;n++){const a=this.rows[n].getTextString();a&&(r=n+1,e?t.push("Row "+r+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
15
15
  `)),i}getTextAndFormat(){return this.rows}}class kn{constructor(e,t,i){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 Ji(i),this.nonDisplayedMemory=new Ji(i),this.lastOutputScreen=new Ji(i),this.currRollUpRow=this.displayedMemory.rows[_e-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[_e-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 i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);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 i=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(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 Pn{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Fn(),this.logger=void 0;const r=this.logger=new iu;this.channels=[null,new kn(e,t,r),new kn(e+1,i,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){let i,r,n,a=!1;this.logger.time=e;for(let o=0;o<t.length;o+=2)if(r=t[o]&127,n=t[o+1]&127,!(r===0&&n===0)){if(this.logger.log(3,"["+Qe([t[o],t[o+1]])+"] -> ("+Qe([r,n])+")"),i=this.parseCmd(r,n),i||(i=this.parseMidrow(r,n)),i||(i=this.parsePAC(r,n)),i||(i=this.parseBackgroundAttributes(r,n)),!i&&(a=this.parseChars(r,n),a)){const l=this.currentChannel;l&&l>0?this.channels[l].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!i&&!a&&this.logger.log(2,"Couldn't parse cleaned data "+Qe([r,n])+" orig: "+Qe([t[o],t[o+1]]))}}parseCmd(e,t){const{cmdHistory:i}=this,r=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(r||n))return!1;if(On(e,t,i))return ht(null,null,i),this.logger.log(3,"Repeated command ("+Qe([e,t])+") is dropped"),!0;const a=e===20||e===21||e===23?1:2,o=this.channels[a];return e===20||e===21||e===28||e===29?t===32?o.ccRCL():t===33?o.ccBS():t===34?o.ccAOF():t===35?o.ccAON():t===36?o.ccDER():t===37?o.ccRU(2):t===38?o.ccRU(3):t===39?o.ccRU(4):t===40?o.ccFON():t===41?o.ccRDC():t===42?o.ccTR():t===43?o.ccRTD():t===44?o.ccEDM():t===45?o.ccCR():t===46?o.ccENM():t===47&&o.ccEOC():o.ccTO(t-32),ht(e,t,i),this.currentChannel=a,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[i];return r?(r.ccMIDROW(t),this.logger.log(3,"MIDROW ("+Qe([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const r=this.cmdHistory,n=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,a=(e===16||e===24)&&t>=64&&t<=95;if(!(n||a))return!1;if(On(e,t,r))return ht(null,null,r),!0;const o=e<=23?1:2;t>=64&&t<=95?i=o===1?Zc[e]:Jc[e]:i=o===1?Qc[e]:eu[e];const l=this.channels[o];return l?(l.setPAC(this.interpretPAC(i,t)),ht(e,t,r),this.currentChannel=o,!0):!1}interpretPAC(e,t){let i;const r={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,r.underline=(i&1)===1,i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=Math.floor((i-16)/2)*4,r}parseChars(e,t){let i,r=null,n=null;if(e>=25?(i=2,n=e-8):(i=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 '"+In(a)+"' in channel "+i),r=[a]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);if(r){const a=Qe(r);this.logger.log(3,"Char codes = "+a.join(",")),ht(e,t,this.cmdHistory)}return r}parseBackgroundAttributes(e,t){const i=(e===16||e===24)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=45&&t<=47;if(!(i||r))return!1;let n;const a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=tu[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),ht(e,t,this.cmdHistory),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}this.cmdHistory=Fn()}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const i=this.channels[t];i&&i.cueSplitAtTime(e)}}}function ht(s,e,t){t.a=s,t.b=e}function On(s,e,t){return t.a===s&&t.b===e}function Fn(){return{a:null,b:null}}class Zt{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,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var es=function(){if(et!=null&&et.VTTCue)return self.VTTCue;const s=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const c=l.toLowerCase();return~o.indexOf(c)?c:!1}function i(o){return t(s,o)}function r(o){return t(e,o)}function n(o,...l){let c=1;for(;c<arguments.length;c++){const u=arguments[c];for(const h in u)o[h]=u[h]}return o}function a(o,l,c){const u=this,h={enumerable:!0};u.hasBeenReset=!1;let d="",f=!1,m=o,g=l,y=c,v=null,T="",x=!0,L="auto",E="start",k=50,R="middle",B=50,C="middle";Object.defineProperty(u,"id",n({},h,{get:function(){return d},set:function(b){d=""+b}})),Object.defineProperty(u,"pauseOnExit",n({},h,{get:function(){return f},set:function(b){f=!!b}})),Object.defineProperty(u,"startTime",n({},h,{get:function(){return m},set:function(b){if(typeof b!="number")throw new TypeError("Start time must be set to a number.");m=b,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",n({},h,{get:function(){return g},set:function(b){if(typeof b!="number")throw new TypeError("End time must be set to a number.");g=b,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",n({},h,{get:function(){return y},set:function(b){y=""+b,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",n({},h,{get:function(){return v},set:function(b){v=b,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",n({},h,{get:function(){return T},set:function(b){const D=i(b);if(D===!1)throw new SyntaxError("An invalid or illegal string was specified.");T=D,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",n({},h,{get:function(){return x},set:function(b){x=!!b,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",n({},h,{get:function(){return L},set:function(b){if(typeof b!="number"&&b!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");L=b,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",n({},h,{get:function(){return E},set:function(b){const D=r(b);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");E=D,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",n({},h,{get:function(){return k},set:function(b){if(b<0||b>100)throw new Error("Position must be between 0 and 100.");k=b,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",n({},h,{get:function(){return R},set:function(b){const D=r(b);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");R=D,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",n({},h,{get:function(){return B},set:function(b){if(b<0||b>100)throw new Error("Size must be between 0 and 100.");B=b,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",n({},h,{get:function(){return C},set:function(b){const D=r(b);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");C=D,this.hasBeenReset=!0}})),u.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class nu{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Mn(s){function e(i,r,n,a){return(i|0)*3600+(r|0)*60+(n|0)+parseFloat(a||0)}const t=s.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 au{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let r=0;r<i.length;++r)if(t===i[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}function Nn(s,e,t,i){const r=i?s.split(i):[s];for(const n in r){if(typeof r[n]!="string")continue;const a=r[n].split(t);if(a.length!==2)continue;const o=a[0],l=a[1];e(o,l)}}const ts=new es(0,0,""),Qt=ts.align==="middle"?"middle":"center";function ou(s,e,t){const i=s;function r(){const o=Mn(s);if(o===null)throw new Error("Malformed timestamp: "+i);return s=s.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){const c=new au;Nn(o,function(d,f){let m;switch(d){case"region":for(let g=t.length-1;g>=0;g--)if(t[g].id===f){c.set(d,t[g].region);break}break;case"vertical":c.alt(d,f,["rl","lr"]);break;case"line":m=f.split(","),c.integer(d,m[0]),c.percent(d,m[0])&&c.set("snapToLines",!1),c.alt(d,m[0],["auto"]),m.length===2&&c.alt("lineAlign",m[1],["start",Qt,"end"]);break;case"position":m=f.split(","),c.percent(d,m[0]),m.length===2&&c.alt("positionAlign",m[1],["start",Qt,"end","line-left","line-right","auto"]);break;case"size":c.percent(d,f);break;case"align":c.alt(d,f,["start",Qt,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let u=c.get("line","auto");u==="auto"&&ts.line===-1&&(u=-1),l.line=u,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",Qt);let h=c.get("position","auto");h==="auto"&&ts.position===50&&(h=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=h}function a(){s=s.replace(/^\s+/,"")}if(a(),e.startTime=r(),a(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);s=s.slice(3),a(),e.endTime=r(),a(),n(s,e)}function Bn(s){return s.replace(/<br(?: \/)?>/gi,`
16
16
  `)}class lu{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new nu,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 i(){let n=t.buffer,a=0;for(n=Bn(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
17
17
  `;)++a;const o=n.slice(0,a);return n[a]==="\r"&&++a,n[a]===`
@@ -23,7 +23,7 @@
23
23
  `),c=[],u=e?kc(e.baseTime,e.timescale):0;let h="00:00.000",d=0,f=0,m,g=!0;o.oncue=function(y){const v=t[i];let T=t.ccOffset;const x=(d-u)/9e4;if(v!=null&&v.new&&(f!==void 0?T=t.ccOffset=v.start:hu(t,i,x)),x){if(!e){m=new Error("Missing initPTS for VTT MPEGTS");return}T=x-t.presentationOffset}const L=y.endTime-y.startTime,E=Ae((y.startTime+T-f)*9e4,r*9e4)/9e4;y.startTime=Math.max(E,0),y.endTime=Math.max(E+L,0);const k=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(k)),y.id||(y.id=rs(y.startTime,y.endTime,k)),y.endTime>0&&c.push(y)},o.onparsingerror=function(y){m=y},o.onflush=function(){if(m){a(m);return}n(c)},l.forEach(y=>{if(g)if(is(y,"X-TIMESTAMP-MAP=")){g=!1,y.slice(16).split(",").forEach(v=>{is(v,"LOCAL:")?h=v.slice(6):is(v,"MPEGTS:")&&(d=parseInt(v.slice(7)))});try{f=uu(h)/1e3}catch(v){m=v}return}else y===""&&(g=!1);o.parse(y+`
24
24
  `)}),o.flush()}const ns="stpp.ttml.im1t",$n=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Un=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,fu={left:"start",center:"center",right:"end",start:"start",end:"end"};function Gn(s,e,t,i){const r=X(new Uint8Array(s),["mdat"]);if(r.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const n=r.map(o=>ke(o)),a=wc(e.baseTime,1,e.timescale);try{n.forEach(o=>t(mu(o,a)))}catch(o){i(o)}}function mu(s,e){const r=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((h,d)=>(h[d]=r.getAttribute(`ttp:${d}`)||n[d],h),{}),o=r.getAttribute("xml:space")!=="preserve",l=Hn(as(r,"styling","style")),c=Hn(as(r,"layout","region")),u=as(r,"body","[begin]");return[].map.call(u,h=>{const d=Vn(h,o);if(!d||!h.hasAttribute("begin"))return null;const f=ls(h.getAttribute("begin"),a),m=ls(h.getAttribute("dur"),a);let g=ls(h.getAttribute("end"),a);if(f===null)throw Kn(h);if(g===null){if(m===null)throw Kn(h);g=f+m}const y=new es(f-e,g-e,d);y.id=rs(y.startTime,y.endTime,y.text);const v=c[h.getAttribute("region")],T=l[h.getAttribute("style")],x=gu(v,T,l),{textAlign:L}=x;if(L){const E=fu[L];E&&(y.lineAlign=E),y.align=L}return oe(y,x),y}).filter(h=>h!==null)}function as(s,e,t){const i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function Hn(s){return s.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Vn(s,e){return[].slice.call(s.childNodes).reduce((t,i,r)=>{var n;return i.nodeName==="br"&&r?t+`
25
25
  `:(n=i.childNodes)!=null&&n.length?Vn(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function gu(s,e,t){const i="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(r=t[a]),n.reduce((o,l)=>{const c=os(e,i,l)||os(s,i,l)||os(r,i,l);return c&&(o[l]=c),o},{})}function os(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function Kn(s){return new Error(`Could not parse ttml timestamp ${s}`)}function ls(s,e){if(!s)return null;let t=Mn(s);return t===null&&($n.test(s)?t=pu(s,e):Un.test(s)&&(t=yu(s,e))),t}function pu(s,e){const t=$n.exec(s),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function yu(s,e){const t=Un.exec(s),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}class vu{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=Yn(),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(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const e=new Zt(this,"textTrack1"),t=new Zt(this,"textTrack2"),i=new Zt(this,"textTrack3"),r=new Zt(this,"textTrack4");this.cea608Parser1=new Pn(1,e,t),this.cea608Parser2=new Pn(3,i,r)}}addCues(e,t,i,r,n){let a=!1;for(let o=n.length;o--;){const l=n[o],c=xu(l[0],l[1],t,i);if(c>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),a=!0,c/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,i,r)}else{const o=this.Cues.newCue(null,t,i,r);this.hls.trigger(p.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:n}){const{unparsedVttFrags:a}=this;i==="main"&&(this.initPTS[t.cc]={baseTime:r,timescale:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(p.FRAG_LOADED,o)}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let r=0;r<i.textTracks.length;r++){const n=i.textTracks[r];if(zn(n,{name:e,lang:t,attrs:{}}))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:i,media:r}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)i[e]=o,it(i[e]),Pr(i[e],r);else{const l=this.createTextTrack("captions",n,a);l&&(l[e]=!0,i[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i=t.label,r={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}createTextTrack(e,t,i){const r=this.media;if(r)return r.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach(t=>{it(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Yn(),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 i=0;i<t.length;i++)it(t[i])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],r=i.some(n=>n.textCodec===ns);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(An(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const a=this.media,o=a?Mt(a.textTracks):null;if(this.tracks.forEach((l,c)=>{let u;if(o){let h=null;for(let d=0;d<o.length;d++)if(o[d]&&zn(o[d],l)){h=o[d],o[d]=null;break}h&&(u=h)}if(u)it(u);else{const h=Wn(l);u=this.createTextTrack(h,l.name,l.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),o!=null&&o.length){const l=o.filter(c=>c!==null).map(c=>c.label);l.length&&S.warn(`Media element contains unused subtitle tracks: ${l.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(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const r=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!r)return;const n=`textTrack${r[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){this.initCea608Parsers();const{cea608Parser1:i,cea608Parser2:r,lastCc:n,lastSn:a,lastPartIndex:o}=this;if(!(!this.enabled||!i||!r)&&t.frag.type===j.MAIN){var l,c;const{cc:u,sn:h}=t.frag,d=(l=t==null||(c=t.part)==null?void 0:c.index)!=null?l:-1;h===a+1||h===a&&d===o+1||u===n||(i.reset(),r.reset()),this.lastCc=u,this.lastSn=h,this.lastPartIndex=d}}onFragLoaded(e,t){const{frag:i,payload:r}=t;if(i.type===j.SUBTITLE)if(r.byteLength){const n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){const o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===ns?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;Gn(t,this.initPTS[e.cc],r=>{this._appendCues(r,e.level),i.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},r=>{S.log(`Failed to parse IMSC1: ${r}`),i.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:r})})}_parseVTTs(e){var t;const{frag:i,payload:r}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[i.cc]&&o===-1){a.push(e);return}const l=this.hls,c=(t=i.initSegment)!=null&&t.data?be(i.initSegment.data,new Uint8Array(r)):r;du(c,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,u=>{this._appendCues(u,i.level),l.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},u=>{const h=u.message==="Missing initPTS for VTT MPEGTS";h?a.push(e):this._fallbackToIMSC1(i,r),S.log(`Failed to parse VTT cue: ${u}`),!(h&&o>i.cc)&&l.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:u})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||Gn(t,this.initPTS[e.cc],()=>{i.textCodec=ns,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const r=this.textTracks[t];if(!r||r.mode==="disabled")return;e.forEach(n=>Or(r,n))}else{const r=this.tracks[t];if(!r)return;const n=r.default?"default":"subtitles"+t;i.trigger(p.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===j.SUBTITLE&&this.onFragLoaded(p.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){this.initCea608Parsers();const{cea608Parser1:i,cea608Parser2:r}=this;if(!this.enabled||!i||!r)return;const{frag:n,samples:a}=t;if(!(n.type===j.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let o=0;o<a.length;o++){const l=a[o].bytes;if(l){const c=this.extractCea608Data(l);i.addData(a[o].pts,c[0]),r.addData(a[o].pts,c[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:r,type:n}){const{media:a}=this;if(!(!a||a.currentTime<i)){if(!n||n==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>wi(o[l],t,i))}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>wi(o[l],t,r))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let r=2;for(let n=0;n<i;n++){const a=e[r++],o=127&e[r++],l=127&e[r++];if(o===0&&l===0)continue;if((4&a)!==0){const u=3&a;(u===0||u===1)&&(t[u].push(o),t[u].push(l))}}return t}}function Wn(s){return s.characteristics&&/transcribes-spoken-dialog/gi.test(s.characteristics)&&/describes-music-and-sound/gi.test(s.characteristics)?"captions":"subtitles"}function zn(s,e){return!!s&&s.kind===Wn(e)&&Qi(e,s)}function xu(s,e,t,i){return Math.min(e,i)-Math.max(s,t)}function Yn(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class cs{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(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.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 i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&W(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}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,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&S.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,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 i=t.filter((r,n)=>this.isLevelAllowed(r)&&n<=e);return this.clientRect=null,cs.getMaxLevelByMediaSize(i,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 i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.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 e}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const r=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let n=e.length-1;const a=Math.max(t,i);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=a||l.height>=a)&&r(l,e[o+1])){n=o;break}}return n}}class Tu{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(p.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&typeof r.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){const r=performance.now();if(t){if(this.lastTime){const n=r-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,c=this.hls;if(c.trigger(p.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>c.config.fpsDroppedMonitoringThreshold*o){let u=c.currentLevel;S.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=u)&&(u=u-1,c.trigger(p.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:c.currentLevel}),c.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,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)}}const Jt="[eme]";class dt{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=dt.CDMCleanupPromise?[dt.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=S.debug.bind(S,Jt),this.log=S.log.bind(S,Jt),this.warn=S.warn.bind(S,Jt),this.error=S.error.bind(S,Jt),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t[e];if(r)return r.licenseUrl;if(e===ne.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,r=t.map(a=>a.audioCodec).filter(i),n=t.map(a=>a.videoCodec).filter(i);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{const l=c=>{const u=c.shift();this.getMediaKeysPromise(u,r,n).then(h=>a({keySystem:u,mediaKeys:h})).catch(h=>{c.length?l(c):h instanceof Le?o(h):o(new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${i}`;return rr===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return i(e,t)}getMediaKeysPromise(e,t,i){const r=wo(e,t,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[e];let a=n==null?void 0:n.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(r)}`),a=this.requestMediaKeySystemAccess(e,r);const o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const c=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=l.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),c.then(h=>h?this.setMediaKeysServerCertificate(u,e,h):u))),o.mediaKeys.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),o.mediaKeys})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${Pe.hexDump(e.keyId||[])}`);const r=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,n,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return Pe.hexDump(e.keyId)}updateKeySession(e,t){var i;const r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${Pe.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])}
26
- } (data length: ${t&&t.byteLength})`),r.update(t)}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){return new Promise((t,i)=>{const r=Ei(this.config),n=e.map(tr).filter(a=>!!a&&r.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:a})=>{const o=sr(a);o?t(o):i(new Error(`Unable to find format for key-system "${a}"`))}).catch(i)})}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let n=this.keyIdToKeySessionPromise[i];return n||(n=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:t}),c="cenc";return this.generateRequestWithPreferredKeySession(l,c,t.pssh,"playlist-key")}))),n.catch(a=>this.handleError(a))),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Le?this.hls.trigger(p.ERROR,e.data):this.hls.trigger(p.ERROR,{type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const r=tr(e.keyFormat),n=r?[r]:Ei(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Ei(this.config)),e.length===0)throw new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:i}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),i===null)return;let r,n;if(t==="sinf"&&this.config.drmSystems[ne.FAIRPLAY]){const u=ce(new Uint8Array(i));try{const h=xi(JSON.parse(u).sinf),d=fr(new Uint8Array(h));if(!d)return;r=d.subarray(8,24),n=ne.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{const u=il(i);if(u===null)return;u.version===0&&u.systemId===ir.WIDEVINE&&u.data&&(r=u.data.subarray(8,24)),n=Io(u.systemId)}if(!n||!r)return;const a=Pe.hexDump(r),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this;let c=o[a];for(let u=0;u<l.length;u++){const h=l[u],d=h.decryptdata;if(d.pssh||!d.keyId)continue;const f=Pe.hexDump(d.keyId);if(a===f||d.uri.replace(/-/g,"").indexOf(a)!==-1){c=o[f],delete o[f],d.pssh=new Uint8Array(i),d.keyId=r,c=o[a]=c.then(()=>this.generateRequestWithPreferredKeySession(h,t,i,"encrypted-event-key-match"));break}}c||(c=o[a]=this.getKeySystemSelectionPromise([n]).then(({keySystem:u,mediaKeys:h})=>{var d;this.throwIfDestroyed();const f=new vt("ISO-23001-7",a,(d=sr(u))!=null?d:"");return f.pssh=new Uint8Array(i),f.keyId=r,this.attemptSetMediaKeys(u,h).then(()=>{this.throwIfDestroyed();const m=this.createMediaKeySessionContext({decryptdata:f,keySystem:u,mediaKeys:h});return this.generateRequestWithPreferredKeySession(m,t,i,"encrypted-event-no-match")})})),c.catch(u=>this.handleError(u))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const r=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,i,r){var n,a;const o=(n=this.config.drmSystems)==null||(a=n[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const m=o.call(this.hls,t,i,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,i=e.decryptdata.pssh=m.initData?new Uint8Array(m.initData):null}catch(m){var l;if(this.warn(m.message),(l=this.hls)!=null&&l.config.debug)throw m}if(i===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);const c=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${c} (init data type: ${t} length: ${i?i.byteLength:null})`);const u=new Zi,h=e._onmessage=m=>{const g=e.mediaKeysSession;if(!g){u.emit("error",new Error("invalid state"));return}const{messageType:y,message:v}=m;this.log(`"${y}" message event for session "${g.sessionId}" message size: ${v.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,v).catch(T=>{this.handleError(T),u.emit("error",T)}):y==="license-release"?e.keySystem===ne.FAIRPLAY&&(this.updateKeySession(e,Ti("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${y}"`)},d=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){u.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const y=e.keyStatus;u.emit("keyStatus",y),y==="expired"&&(this.warn(`${e.keySystem} expired for key ${c}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",h),e.mediaKeysSession.addEventListener("keystatuseschange",d);const f=new Promise((m,g)=>{u.on("error",g),u.on("keyStatus",y=>{y.startsWith("usable")?m():y==="output-restricted"?g(new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):y==="internal-error"?g(new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${y}"`)):y==="expired"?g(new Error("key expired while generating request")):this.warn(`unhandled key status change "${y}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var m;this.log(`Request generated for key-session "${(m=e.mediaKeysSession)==null?void 0:m.sessionId}" keyId: ${c}`)}).catch(m=>{throw new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_SESSION,error:m,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>{throw u.removeAllListeners(),this.removeSession(e),m}).then(()=>(u.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${Pe.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${Pe.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,i=t.loader,r=new i(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:n},c=t.certLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,f,m,g)=>{a(d.data)},onError:(d,f,m,g)=>{o(new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:he({url:l.url,data:void 0},d)},`"${e}" certificate request failed (${n}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,m)=>{o(new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(d,f,m)=>{o(new Error("aborted"))}};r.load(l,u,h)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((r,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),r(e)}).catch(a=>{n(new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(r=>{throw new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:r,fatal:!0},r.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const r=new DOMParser().parseFromString(i,"application/xml"),n=r.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,m=(o=u.querySelector("value"))==null?void 0:o.textContent;f&&m&&e.setRequestHeader(f,m)}}const l=r.querySelector("Challenge"),c=l==null?void 0:l.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return Ti(atob(c))}setupLicenseXHR(e,t,i,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,r)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,i,r)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{const a=this.getLicenseServerUrl(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 l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,a,e)}catch(u){this.error(u)}r(l)}else{const l=i.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)n(new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_LICENSE_REQUEST_FAILED,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=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(r,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:c})=>{e.keySystem==ne.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(l,c)),l.send(c)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},vt.clearKeyUriToKeyIdMap();const i=t.length;dt.CDMCleanupPromise=Promise.all(t.map(r=>this.removeSession(r)).concat(e==null?void 0:e.setMediaKeys(null).catch(r=>{this.log(`Could not clear media keys: ${r}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(r=>{this.log(`Could not close sessions and clear media keys: ${r}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch(n=>{this.log(`Could not remove session: ${n}`)}).then(()=>t.close()).catch(n=>{this.log(`Could not close session: ${n}`)})}}}dt.CDMCleanupPromise=void 0;class Le 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}}var ve;(function(s){s.MANIFEST="m",s.AUDIO="a",s.VIDEO="v",s.MUXED="av",s.INIT="i",s.CAPTION="c",s.TIMED_TEXT="tt",s.KEY="k",s.OTHER="o"})(ve||(ve={}));var us;(function(s){s.DASH="d",s.HLS="h",s.SMOOTH="s",s.OTHER="o"})(us||(us={}));var Je;(function(s){s.OBJECT="CMCD-Object",s.REQUEST="CMCD-Request",s.SESSION="CMCD-Session",s.STATUS="CMCD-Status"})(Je||(Je={}));const Eu={[Je.OBJECT]:["br","d","ot","tb"],[Je.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Je.SESSION]:["cid","pr","sf","sid","st","v"],[Je.STATUS]:["bs","rtp"]};class ft{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(i=>i instanceof ft?i:new ft(i))),this.value=e,this.params=t}}class jn{constructor(e){this.description=void 0,this.description=e}}const Su="Dict";function bu(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function Au(s,e,t,i){return new Error(`failed to ${s} "${bu(e)}" as ${t}`,{cause:i})}const qn="Bare Item",Lu="Boolean",Ru="Byte Sequence",Cu="Decimal",Du="Integer";function _u(s){return s<-999999999999999||999999999999999<s}const Iu=/[\x00-\x1f\x7f]+/,wu="Token",ku="Key";function Be(s,e,t){return Au("serialize",s,e,t)}function Pu(s){if(typeof s!="boolean")throw Be(s,Lu);return s?"?1":"?0"}function Ou(s){return btoa(String.fromCharCode(...s))}function Fu(s){if(ArrayBuffer.isView(s)===!1)throw Be(s,Ru);return`:${Ou(s)}:`}function Xn(s){if(_u(s))throw Be(s,Du);return s.toString()}function Mu(s){return`@${Xn(s.getTime()/1e3)}`}function Zn(s,e){if(s<0)return-Zn(-s,e);const t=Math.pow(10,e);if(Math.abs(s*t%1-.5)<Number.EPSILON){const r=Math.floor(s*t);return(r%2===0?r:r+1)/t}else return Math.round(s*t)/t}function Nu(s){const e=Zn(s,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Be(s,Cu);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Bu="String";function $u(s){if(Iu.test(s))throw Be(s,Bu);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Uu(s){return s.description||s.toString().slice(7,-1)}function Qn(s){const e=Uu(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Be(e,wu);return e}function hs(s){switch(typeof s){case"number":if(!W(s))throw Be(s,qn);return Number.isInteger(s)?Xn(s):Nu(s);case"string":return $u(s);case"symbol":return Qn(s);case"boolean":return Pu(s);case"object":if(s instanceof Date)return Mu(s);if(s instanceof Uint8Array)return Fu(s);if(s instanceof jn)return Qn(s);default:throw Be(s,qn)}}function ds(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Be(s,ku);return s}function fs(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${ds(e)}`:`;${ds(e)}=${hs(t)}`).join("")}function Jn(s){return s instanceof ft?`${hs(s.value)}${fs(s.params)}`:hs(s)}function Gu(s){return`(${s.value.map(Jn).join(" ")})${fs(s.params)}`}function Hu(s,e={whitespace:!0}){if(typeof s!="object")throw Be(s,Su);const t=s instanceof Map?s.entries():Object.entries(s),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof ft||(n=new ft(n));let a=ds(r);return n.value===!0?a+=fs(n.params):(a+="=",Array.isArray(n.value)?a+=Gu(n):a+=Jn(n)),a}).join(`,${i}`)}function Vu(s,e){return Hu(s,e)}const Ku=s=>s==="ot"||s==="sf"||s==="st",Wu=s=>typeof s=="number"?W(s):s!=null&&s!==""&&s!==!1;function zu(s,e){const t=new URL(s),i=new URL(e);if(t.origin!==i.origin)return s;const r=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")}function Yu(){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,r=>{const n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(r=="x"?n:n&3|8).toString(16)})}}}const ei=s=>Math.round(s),ju=(s,e)=>(e!=null&&e.baseUrl&&(s=zu(s,e.baseUrl)),encodeURIComponent(s)),ti=s=>ei(s/100)*100,qu={br:ei,d:ei,bl:ti,dl:ti,mtp:ti,nor:ju,rtp:ti,tb:ei};function Xu(s,e){const t={};if(s==null||typeof s!="object")return t;const i=Object.keys(s).sort(),r=oe({},qu,e==null?void 0:e.formatters),n=e==null?void 0:e.filter;return i.forEach(a=>{if(n!=null&&n(a))return;let o=s[a];const l=r[a];l&&(o=l(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||Wu(o)&&(Ku(a)&&typeof o=="string"&&(o=new jn(o)),t[a]=o))}),t}function ea(s,e={}){return s?Vu(Xu(s,e),oe({whitespace:!1},e)):""}function Zu(s,e={}){if(!s)return{};const t=Object.entries(s),i=Object.entries(Eu).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),r=t.reduce((n,a)=>{var o,l;const[c,u]=a,h=((o=i.find(d=>d[1].includes(c)))==null?void 0:o[0])||Je.REQUEST;return(l=n[h])!=null||(n[h]={}),n[h][c]=u,n},{});return Object.entries(r).reduce((n,[a,o])=>(n[a]=ea(o,e),n),{})}function Qu(s,e,t){return oe(s,Zu(e,t))}const Ju="CMCD";function eh(s,e={}){if(!s)return"";const t=ea(s,e);return`${Ju}=${encodeURIComponent(t)}`}const ta=/CMCD=[^&#]+/;function th(s,e,t){const i=eh(e,t);if(!i)return s;if(ta.test(s))return s.replace(ta,i);const r=s.includes("?")?"&":"?";return`${s}${r}${i}`}class ih{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=r=>{try{this.apply(r,{ot:ve.MANIFEST,su:!this.initialized})}catch(n){S.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=r=>{try{const n=r.frag,a=this.hls.levels[n.level],o=this.getObjectType(n),l={d:n.duration*1e3,ot:o};(o===ve.VIDEO||o===ve.AUDIO||o==ve.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(r,l)}catch(n){S.warn("Could not generate segment CMCD data.",n)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||Yu(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=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 i,r;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(r=t.tracks.video)==null?void 0:r.buffer}createData(){var e;return{v:1,sf:us.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 i=t.ot===ve.INIT||t.ot===ve.VIDEO||t.ot===ve.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((n,a)=>(r.includes(a)&&(n[a]=t[a]),n),{})),this.useHeaders?(e.headers||(e.headers={}),Qu(e.headers,t)):e.url=th(e.url,t)}getObjectType(e){const{type:t}=e;if(t==="subtitle")return ve.TIMED_TEXT;if(e.sn==="initSegment")return ve.INIT;if(t==="audio")return ve.AUDIO;if(t==="main")return this.hls.audioTracks.length?ve.VIDEO:ve.MUXED}getTopBandwidth(e){let t=0,i;const r=this.hls;if(e===ve.AUDIO)i=r.audioTracks;else{const n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;i=r.levels.slice(0,a)}for(const n of i)n.bitrate>t&&(t=n.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.hls.media,i=e===ve.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:se.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(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,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(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 sh=3e5;class rh{constructor(e){this.hls=void 0,this.log=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.log=S.log.bind(S,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this))}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(i=>i!==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:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((i==null?void 0:i.action)===ge.SendAlternateToPenaltyBox&&i.flags===De.MoveAllAlternatesMatchingHost){const r=this.levels;let n=this.pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:c}=t.context;o&&r?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&r&&(n=r.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),i.resolved||S.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${r&&r.length} priorities: ${JSON.stringify(n)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t;const i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(n=>{r-i[n]>sh&&delete i[n]});for(let n=0;n<e.length;n++){const a=e[n];if(a in i)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,Hr(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){const r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===ee.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===ee.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},r={};e.forEach(n=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(u=>u.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(u=>{const h=new ae(u.attrs);h["PATHWAY-ID"]=a;const d=h.AUDIO&&`${h.AUDIO}_clone_${a}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;d&&(i[h.AUDIO]=d,h.AUDIO=d),f&&(r[h.SUBTITLES]=f,h.SUBTITLES=f);const m=sa(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new st({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:m,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let y=1;y<u.audioGroups.length;y++)g.addGroupId("audio",`${u.audioGroups[y]}_clone_${a}`);if(u.subtitleGroups)for(let y=1;y<u.subtitleGroups.length;y++)g.addGroupId("text",`${u.subtitleGroups[y]}_clone_${a}`);return g});t.push(...c),ia(this.audioTracks,i,l,a),ia(this.subtitleTracks,r,l,a)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+u)}const n={responseType:"json",url:r.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(u,h,d,f)=>{this.log(`Loaded steering manifest: "${r}"`);const m=u.data;if(m.VERSION!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;const{"RELOAD-URI":g,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":v}=m;if(g)try{this.uri=new self.URL(g,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||d.url),y&&this.clonePathways(y);const T={steeringManifest:m,url:r.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,T),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 m=this.timeToLoad*1e3;if(u.code===429){const g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){const y=g.getResponseHeader("Retry-After");y&&(m=parseFloat(y)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,m)},onTimeout:(u,h,d)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const r=(i=this.hls)==null?void 0:i.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function ia(s,e,t,i){s&&Object.keys(e).forEach(r=>{const n=s.filter(a=>a.groupId===r).map(a=>{const o=oe({},a);return o.details=void 0,o.attrs=new ae(o.attrs),o.url=o.attrs.URI=sa(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=i,o});s.push(...n)})}function sa(s,e,t,i){const{HOST:r,PARAMS:n,[t]:a}=i;let o;e&&(o=a==null?void 0:a[e],o&&(s=o));const l=new self.URL(s);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(c=>{c&&l.searchParams.set(c,n[c])}),l.href}const nh=/^age:\s*[\d.]+\s*$/im;class ra{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 Dt,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null,this.stats=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,i){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=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!this.stats.aborted)return n(i,t.url)}).catch(a=>(i.open("GET",t.url,!0),n(i,t.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{this.callbacks.onError({code:i.status,text:a.message},t,i,r)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(r)for(const o in r)e.setRequestHeader(o,r[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),i.timeout=n&&W(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const r=t.readyState,n=this.config;if(!i.aborted&&r>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.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-(i.loading.first-i.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const a=t.status,o=t.responseType!=="text";if(a>=200&&a<300&&(o&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=o?t.response:t.responseText,c=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=c,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;const u=this.callbacks.onProgress;if(u&&u(i,e,l,t),!this.callbacks)return;const h={url:t.responseURL,data:l,code:a};this.callbacks.onSuccess(h,i,e,t)}else{const l=n.loadPolicy.errorRetry,c=i.retry,u={url:e.url,data:void 0,code:a};Ut(l,c,!1,u)?this.retry(l):(S.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:t.statusText},e,t,i))}}}loadtimeout(){var e;const t=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,i=this.stats.retry;if(Ut(t,i,!0))this.retry(t);else{var r;S.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Ni(e,i.retry),i.retry++,S.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${i.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&&nh.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}}function ah(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const oh=/(\d+)-(\d+)\/(\d+)/;class na{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||hh,this.controller=new self.AbortController,this.stats=new Dt}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,i){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const n=lh(e,this.controller.signal),a=i.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:u}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=c&&W(c)?c:u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response)},t.timeout),self.fetch(this.request).then(h=>{this.response=this.loader=h;const d=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response)},u-(d-r.loading.start)),!h.ok){const{status:f,statusText:m}=h;throw new dh(m||"fetch, bad network response",f,h)}return r.loading.first=d,r.total=uh(h.headers)||r.total,a&&W(t.highWaterMark)?this.loadProgressively(h,r,e,t.highWaterMark,a):o?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{const d=this.response;if(!d)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const f=h[l];f&&(r.loaded=r.total=f);const m={url:d.url,data:h,code:d.status};a&&!W(t.highWaterMark)&&a(r,e,h,d),i.onSuccess(m,r,e,d)}).catch(h=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const d=h&&h.code||0,f=h?h.message:null;i.onError({code:d,text:f},e,h?h.details:null,r)})}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,i,r=0,n){const a=new en,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&n(t,i,a.flush(),e),Promise.resolve(new ArrayBuffer(0));const u=c.value,h=u.length;return t.loaded+=h,h<r||a.dataLength?(a.push(u),a.dataLength>=r&&n(t,i,a.flush(),e)):n(t,i,u,e),l()}).catch(()=>Promise.reject());return l()}}function lh(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(oe({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function ch(s){const e=oh.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function uh(s){const e=s.get("Content-Range");if(e){const i=ch(e);if(W(i))return i}const t=s.get("Content-Length");if(t)return parseInt(t)}function hh(s,e){return new self.Request(s.url,e)}class dh extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const fh=/\s/,mh={newCue(s,e,t,i){const r=[];let n,a,o,l,c;const u=self.VTTCue||self.TextTrackCue;for(let d=0;d<i.rows.length;d++)if(n=i.rows[d],o=!0,l=0,c="",!n.isEmpty()){var h;for(let g=0;g<n.chars.length;g++)fh.test(n.chars[g].uchar)&&o?l++:(c+=n.chars[g].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=Bn(c.trim()),m=rs(e,t,f);s!=null&&(h=s.cues)!=null&&h.getCueById(m)||(a=new u(e,t,f),a.id=m,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a))}return s&&r.length&&(r.sort((d,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),r.forEach(d=>Or(s,d))),r}},gh={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},aa=he(he({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,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,loader:ra,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Wl,bufferController:qc,capLevelController:cs,errorController:Pl,fpsController:Tu,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:rr,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:gh},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}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},ph()),{},{subtitleStreamController:Wc,subtitleTrackController:Yc,timelineController:vu,audioStreamController:Vc,audioTrackController:Kc,emeController:dt,cmcdController:ih,contentSteeringController:rh});function ph(){return{cueHandler:mh,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 yh(s,e){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 t=ms(s),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{const a=`${n==="level"?"playlist":n}LoadPolicy`,o=e[a]===void 0,l=[];r.forEach(c=>{const u=`${n}Loading${c}`,h=e[u];if(h!==void 0&&o){l.push(u);const d=t[a].default;switch(e[a]={default:d},c){case"TimeOut":d.maxLoadTimeMs=h,d.maxTimeToFirstByteMs=h;break;case"MaxRetry":d.errorRetry.maxNumRetry=h,d.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":d.errorRetry.retryDelayMs=h,d.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":d.errorRetry.maxRetryDelayMs=h,d.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&S.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`)}),he(he({},t),e)}function ms(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(ms):Object.keys(s).reduce((e,t)=>(e[t]=ms(s[t]),e),{}):s}function vh(s){const e=s.loader;e!==na&&e!==ra?(S.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):ah()&&(s.loader=na,s.progressive=!0,s.enableSoftwareAES=!0,S.log("[config]: Progressive streaming enabled, using FetchLoader"))}let gs;class xh extends $i{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(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.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 i=this.hls.config.preferManagedMediaSource,r=[],n={},a={};let o=!1,l=!1,c=!1;t.levels.forEach(u=>{var h,d;const f=u.attrs;let{audioCodec:m,videoCodec:g}=u;((h=m)==null?void 0:h.indexOf("mp4a.40.34"))!==-1&&(gs||(gs=/chrome|firefox/i.test(navigator.userAgent)),gs&&(u.audioCodec=m=void 0)),m&&(u.audioCodec=m=Ft(m,i)),((d=g)==null?void 0:d.indexOf("avc1"))===0&&(g=u.videoCodec=ll(g));const{width:y,height:v,unknownCodecs:T}=u;if(o||(o=!!(y&&v)),l||(l=!!g),c||(c=!!m),T!=null&&T.length||m&&!Di(m,"audio",i)||g&&!Di(g,"video",i))return;const{CODECS:x,"FRAME-RATE":L,"HDCP-LEVEL":E,"PATHWAY-ID":k,RESOLUTION:R,"VIDEO-RANGE":B}=f,b=`${`${k||"."}-`}${u.bitrate}-${R}-${L}-${x}-${B}-${E}`;if(n[b])if(n[b].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const D=a[b]+=1;u.attrs["PATHWAY-ID"]=new Array(D+1).join(".");const P=new st(u);n[b]=P,r.push(P)}else n[b].addGroupId("audio",f.AUDIO),n[b].addGroupId("text",f.SUBTITLES);else{const D=new st(u);n[b]=D,a[b]=1,r.push(D)}}),this.filterAndSortMediaOptions(r,t,o,l,c)}filterAndSortMediaOptions(e,t,i,r,n){let a=[],o=[],l=e;if((i||r)&&n&&(l=l.filter(({videoCodec:m,videoRange:g,width:y,height:v})=>(!!m||!!(y&&v))&&El(g))),l.length===0){Promise.resolve().then(()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);const m=new Error("no level with compatible codecs found in manifest");this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:m,reason:m.message})}});return}if(t.audioTracks){const{preferManagedMediaSource:m}=this.hls.config;a=t.audioTracks.filter(g=>!g.audioCodec||Di(g.audioCodec,"audio",m)),oa(a)}t.subtitles&&(o=t.subtitles,oa(o));const c=l.slice(0);l.sort((m,g)=>{if(m.attrs["HDCP-LEVEL"]!==g.attrs["HDCP-LEVEL"])return(m.attrs["HDCP-LEVEL"]||"")>(g.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&m.height!==g.height)return m.height-g.height;if(m.frameRate!==g.frameRate)return m.frameRate-g.frameRate;if(m.videoRange!==g.videoRange)return Bt.indexOf(m.videoRange)-Bt.indexOf(g.videoRange);if(m.videoCodec!==g.videoCodec){const y=Er(m.videoCodec),v=Er(g.videoCodec);if(y!==v)return v-y}if(m.uri===g.uri&&m.codecSet!==g.codecSet){const y=Ot(m.codecSet),v=Ot(g.codecSet);if(y!==v)return v-y}return m.averageBitrate!==g.averageBitrate?m.averageBitrate-g.averageBitrate:0});let u=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let m=0;m<c.length;m++)if(c[m].pathwayId===l[0].pathwayId){u=c[m];break}}this._levels=l;for(let m=0;m<l.length;m++)if(l[m]===u){var h;this._firstLevel=m;const g=u.bitrate,y=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${g}`),((h=this.hls.userConfig)==null?void 0:h.abrEwmaDefaultEstimate)===void 0){const v=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);v>y&&y===aa.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=v)}break}const d=n&&!r,f={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:!d&&a.some(m=>!!m.url)};this.hls.trigger(p.MANIFEST_PARSED,f),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}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(p.ERROR,{type:q.OTHER_ERROR,details:_.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:u,reason:u.message}),h)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,r=this.currentLevel,n=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&a.details&&r&&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 ${i}${n?" with Pathway "+n:""}`);const l={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(p.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const u=this.switchParams(a.uri,r==null?void 0:r.details);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}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===j.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;const r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(e,t){var i;const{level:r,details:n}=t,a=this._levels[r];if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}r===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(r,t,a.details)):(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let r=i.uri;if(e)try{r=e.addDirectives(r)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}const n=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${n?" Pathway "+n:""} ${r}`),this.clearTimer(),this.hls.trigger(p.LEVEL_LOADING,{url:r,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||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;const i=this._levels.filter((r,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(a=>a.level=-1)),!1));Hr(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(p.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function oa(s){const e={};s.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}class Th{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[i].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=_.KEY_LOAD_ERROR,i,r,n){return new He({type:q.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:r}=e;for(let n=0;n<t.length;n++){const a=t[n];if(r<=a.cc&&(i==="initSegment"||a.sn==="initSegment"||i<a.sn)){this.emeController.selectKeySystemFormat(a).then(o=>{a.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,c))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return n.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((r=o)!=null&&r.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(c=>(n.key=c.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const r=this.emeController.loadKey(i);if(r)return(e.keyLoadPromise=r.then(n=>(e.mediaKeySessionContext=n,i))).catch(n=>{throw e.keyLoadPromise=null,n})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,r=i.loader,n=new r(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=i.keyLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,f,m,g)=>{const{frag:y,keyInfo:v,url:T}=m;if(!y.decryptdata||v!==this.keyUriToKeyInfo[T])return o(this.createKeyLoadError(y,_.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));v.decryptdata.key=y.decryptdata.key=new Uint8Array(d.data),y.keyLoader=null,v.loader=null,a({frag:y,keyInfo:v})},onError:(d,f,m,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,_.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),m,he({url:l.url,data:void 0},d)))},onTimeout:(d,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,_.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(d,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,_.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};n.load(l,u,h)})}resetLoader(e){const{frag:t,keyInfo:i,url:r}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],n&&n.destroy()}}function la(){return self.SourceBuffer||self.WebKitSourceBuffer}function ca(){if(!tt())return!1;const e=la();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Eh(){if(!ca())return!1;const s=tt();return typeof(s==null?void 0:s.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(xt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(xt(e,"audio"))))}function Sh(){var s;const e=la();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}const bh=250,ii=2,Ah=.1,Lh=.05;class Rh{constructor(e,t,i,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:i,media:r,stalled:n}=this;if(r===null)return;const{currentTime:a,seeking:o}=r,l=this.seeking&&!o,c=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,o||(this.nudgeRetry=0),n!==null){if(this.stallReported){const y=self.performance.now()-n;S.warn(`playback not stuck anymore @${a}, after ${Math.round(y)}ms`),this.stallReported=!1}this.stalled=null}return}if(c||l){this.stalled=null;return}if(r.paused&&!o||r.ended||r.playbackRate===0||!se.getBuffered(r).length){this.nudgeRetry=0;return}const u=se.bufferInfo(r,a,0),h=u.nextStart||0;if(o){const y=u.len>ii,v=!h||t&&t.start<=a||h-a>ii&&!this.fragmentTracker.getPartialFragment(a);if(y||v)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var d;if(!(u.len>0)&&!h)return;const v=Math.max(h,u.start||0)-a,T=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,L=(T==null||(d=T.details)==null?void 0:d.live)?T.details.targetduration*2:ii,E=this.fragmentTracker.getPartialFragment(a);if(v>0&&(v<=L||E)){r.paused||this._trySkipBufferHole(E);return}}const f=self.performance.now();if(n===null){this.stalled=f;return}const m=f-n;if(!o&&m>=bh&&(this._reportStall(u),!this.media))return;const g=se.bufferInfo(r,a,i.maxBufferHole);this._tryFixBufferStall(g,m)}_tryFixBufferStall(e,t){const{config:i,fragmentTracker:r,media:n}=this;if(n===null)return;const a=n.currentTime,o=r.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-a<i.maxBufferHole)&&t>i.highBufferWatchdogPeriod*1e3&&(S.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:i,stallReported:r}=this;if(!r&&i){this.stallReported=!0;const n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);S.warn(n.message),t.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:i,media:r}=this;if(r===null)return 0;const n=r.currentTime,a=se.bufferInfo(r,n,0),o=n<a.start?a.start:a.nextStart;if(o){const l=a.len<=t.maxBufferHole,c=a.len>0&&a.len<1&&r.readyState<3,u=o-n;if(u>0&&(l||c)){if(u>t.maxBufferHole){const{fragmentTracker:d}=this;let f=!1;if(n===0){const m=d.getAppendedFrag(0,j.MAIN);m&&o<m.end&&(f=!0)}if(!f){const m=e||d.getAppendedFrag(n,j.MAIN);if(m){let g=!1,y=m.end;for(;y<o;){const v=d.getPartialFragment(y);if(v)y+=v.duration;else{g=!0;break}}if(g)return 0}}}const h=Math.max(o+Lh,n+Ah);if(S.warn(`skipping hole, adjusting currentTime from ${n} to ${h}`),this.moved=!0,this.stalled=null,r.currentTime=h,e&&!e.gap){const d=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${h}`);i.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:e})}return h}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:i,nudgeRetry:r}=this;if(i===null)return;const n=i.currentTime;if(this.nudgeRetry++,r<e.nudgeMaxRetry){const a=n+(r+1)*e.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);S.warn(o.message),i.currentTime=a,t.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const a=new Error(`Playhead still not moving while enough data buffered @${n} after ${e.nudgeMaxRetry} nudges`);S.error(a.message),t.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,error:a,fatal:!0})}}}const Ch=100;class Dh extends Hi{constructor(e,t,i){super(e,t,i,"[stream-controller]",j.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(p.ERROR,this.onError,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(p.ERROR,this.onError,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:i}=this;if(this.stopLoad(),this.setInterval(Ch),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=M.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=M.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case M.WAITING_LEVEL:{const{levels:t,level:i}=this,r=t==null?void 0:t[i],n=r==null?void 0:r.details;if(n&&(!n.live||this.levelLastLoaded===r)){if(this.waitForCdnTuneIn(n))break;this.state=M.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=M.IDLE;break}break}case M.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){const{levels:r,level:n}=this,a=r==null?void 0:r[n];this.resetStartWhenNotLoaded(a||null),this.state=M.IDLE}}break}this.state===M.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(t===null||!r&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const n=e.nextLoadLevel;if(!(i!=null&&i[n]))return;const a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const g={};this.altAudio&&(g.type="video"),this.hls.trigger(p.BUFFER_EOS,g),this.state=M.ENDED;return}e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;const c=a.details;if(!c||this.state===M.WAITING_LEVEL||c.live&&this.levelLastLoaded!==a){this.level=n,this.state=M.WAITING_LEVEL;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,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&f.sn!=="initSegment"&&this.fragmentTracker.getState(f)!==de.OK){var m;const y=((m=this.backtrackFragment)!=null?m:f).sn-c.startSN,v=c.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?te.AUDIO:te.VIDEO,v=(y===te.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,y,j.MAIN)}f=this.getNextFragmentLoopLoading(f,c,o,j.MAIN,h)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,d))}loadFragment(e,t,i){const r=this.fragmentTracker.getState(e);this.fragCurrent=e,r===de.NOT_LOADED||r===de.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):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)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,j.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 i;const r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.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,l=e[o],c=this.fragLastKbps;c&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:i=0}else i=0;const a=this.getBufferedFrag(t.currentTime+i);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,c=o.duration,u=Math.max(a.end,l+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*(this.couldBacktrack?.5:.125)),c*(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 M.KEY_LOADING:case M.FRAG_LOADING:case M.FRAG_LOADING_WAITING_RETRY:case M.PARSING:case M.PARSED:this.state=M.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Rh(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;W(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(p.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let i=!1,r=!1;t.levels.forEach(n=>{const a=n.audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=i&&r&&!Sh(),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:i}=this;if(!i||this.state!==M.IDLE)return;const r=i[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(r.details))&&(this.state=M.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!r){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=r[n],c=this.fragCurrent;c&&(this.state===M.FRAG_LOADING||this.state===M.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let u=0;if(a.live||(i=l.details)!=null&&i.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(p.LEVEL_UPDATED,{details:a,level:n}),this.state===M.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=M.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,u),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:r,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=a[i.level],l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const c=o.videoCodec,u=l.PTSKnown||!l.live,h=(t=i.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new bn(this.hls,j.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=r?r.index:-1,g=m!==-1,y=new Ui(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,g),v=this.initPTS[i.cc];f.push(n,h,d,c,i,r,l.totalduration,u,y,v)}onAudioTrackSwitching(e,t){const i=this.altAudio;if(!!!t.url){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();const n=this.hls;i&&(n.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),n.trigger(p.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=t.id,r=!!this.hls.audioTracks[i].url;if(r){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=r,this.tick()}onBufferCreated(e,t){const i=t.tracks;let r,n,a=!1;for(const o in i){const l=i[o];if(l.id==="main"){if(n=o,r=l,o==="video"){const c=i[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:r}=t;if(i&&i.type!==j.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===M.PARSED&&(this.state=M.IDLE);return}const n=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}onError(e,t){var i;if(t.fatal){this.state=M.ERROR;return}switch(t.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(j.MAIN,t);break;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===M.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===ee.LEVEL&&(this.state=M.IDLE);break;case _.BUFFER_APPEND_ERROR:case _.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===_.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case _.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){const{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!se.getBuffered(e).length){const i=this.state!==M.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=M.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==te.AUDIO||this.audioOnly&&!this.altAudio){const i=(t===te.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,j.MAIN),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const r=se.getBuffered(e),a=(r.length?r.start(0):0)-i;a>0&&(a<this.config.maxBufferHole||a<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${a} to match buffer start`),i+=a,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${t}`),e.currentTime=i}}_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(i=>{const{hls:r}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=M.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=e.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),r.trigger(p.FRAG_LOADED,i),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const i="main",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:u}=o,{video:h,text:d,id3:f,initSegment:m}=n,{details:g}=u,y=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=M.PARSING,m){if(m!=null&&m.tracks){const x=l.initSegment||l;this._bufferInitSegment(u,m.tracks,x,a),r.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:x,id:i,tracks:m.tracks})}const v=m.initPTS,T=m.timescale;W(v)&&(this.initPTS[l.cc]={baseTime:v,timescale:T},r.trigger(p.INIT_PTS_FOUND,{frag:l,id:i,initPTS:v,timescale:T}))}if(h&&g&&l.sn!=="initSegment"){const v=g.fragments[l.sn-1-g.startSN],T=l.sn===g.startSN,x=!v||l.cc>v.cc;if(n.independent!==!1){const{startPTS:L,endPTS:E,startDTS:k,endDTS:R}=h;if(c)c.elementaryStreams[h.type]={startPTS:L,endPTS:E,startDTS:k,endDTS:R};else if(h.firstKeyFrame&&h.independent&&a.id===1&&!x&&(this.couldBacktrack=!0),h.dropped&&h.independent){const B=this.getMainFwdBufferInfo(),C=(B?B.end:this.getLoadPosition())+this.config.maxBufferHole,b=h.firstKeyFramePTS?h.firstKeyFramePTS:L;if(!T&&C<b-this.config.maxBufferHole&&!x){this.backtrack(l);return}else x&&(l.gap=!0);l.setElementaryStreamInfo(h.type,l.start,E,l.start,R,!0)}else T&&L>ii&&(l.gap=!0);l.setElementaryStreamInfo(h.type,L,E,k,R),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(h,l,c,a,T||x)}else if(T||x)l.gap=!0;else{this.backtrack(l);return}}if(y){const{startPTS:v,endPTS:T,startDTS:x,endDTS:L}=y;c&&(c.elementaryStreams[te.AUDIO]={startPTS:v,endPTS:T,startDTS:x,endDTS:L}),l.setElementaryStreamInfo(te.AUDIO,v,T,x,L),this.bufferFragmentData(y,l,c,a)}if(g&&f!=null&&(t=f.samples)!=null&&t.length){const v={id:i,frag:l,details:g,samples:f.samples};r.trigger(p.FRAG_PARSING_METADATA,v)}if(g&&d){const v={id:i,frag:l,details:g,samples:d.samples};r.trigger(p.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(e,t,i,r){if(this.state!==M.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:n,video:a,audiovideo:o}=t;if(n){let l=e.audioCodec;const c=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5"),n.metadata.channelCount!==1&&c.indexOf("firefox")===-1&&(l="mp4a.40.5")),l&&l.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),n.levelCodec=l,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${n.codec}]`)}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(p.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{const u=t[l].initSegment;u!=null&&u.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:l,data:u,frag:i,part:null,chunkMeta:r,parent:i.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,j.MAIN)}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=M.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(se.isBuffered(e,i)?t=this.getAppendedFrag(i):se.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const r=this.fragPlaying,n=t.level;(!r||t.sn!==r.sn||r.level!==n)&&(this.fragPlaying=t,this.hls.trigger(p.FRAG_CHANGED,{frag:t}),(!r||r.level!==n)&&this.hls.trigger(p.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,i=this.currentFrag;if(i&&W(t)&&W(i.programDateTime)){const r=i.programDateTime+(t-i.start)*1e3;return new Date(r)}}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 $e{static get version(){return"1.5.6"}static isMSESupported(){return ca()}static isSupported(){return Eh()}static getMediaSource(){return tt()}static get Events(){return p}static get ErrorTypes(){return q}static get ErrorDetails(){return _}static get DefaultConfig(){return $e.defaultConfig?$e.defaultConfig:aa}static set DefaultConfig(e){$e.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new Zi,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.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,To(e.debug||!1,"Hls instance");const t=this.config=yh($e.DefaultConfig,e);this.userConfig=e,t.progressive&&vh(t);const{abrController:i,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=t,l=new a(this),c=this.abrController=new i(this),u=this.bufferController=new r(this),h=this.capLevelController=new n(this),d=new o(this),f=new fl(this),m=new vl(this),g=t.contentSteeringController,y=g?new g(this):null,v=this.levelController=new xh(this,y),T=new Yl(this),x=new Th(this.config),L=this.streamController=new Dh(this,T,x);h.setStreamController(L),d.setStreamController(L);const E=[f,v,L];y&&E.splice(1,0,y),this.networkControllers=E;const k=[c,u,h,d,m,T];this.audioTrackController=this.createController(t.audioTrackController,E);const R=t.audioStreamController;R&&E.push(new R(this,T,x)),this.subtitleTrackController=this.createController(t.subtitleTrackController,E);const B=t.subtitleStreamController;B&&E.push(new B(this,T,x)),this.createController(t.timelineController,k),x.emeController=this.emeController=this.createController(t.emeController,k),this.cmcdController=this.createController(t.cmcdController,k),this.latencyController=this.createController(xl,k),this.coreComponents=k,E.push(l);const C=l.onErrorOut;typeof C=="function"&&this.on(p.ERROR,C,l)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,r){this._emitter.off(e,t,i,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(S.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const r=e===p.ERROR;this.trigger(p.ERROR,{type:q.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:r,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){S.log("destroy"),this.trigger(p.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){S.log("attachMedia"),this._media=e,this.trigger(p.MEDIA_ATTACHING,{media:e})}detachMedia(){S.log("detachMedia"),this.trigger(p.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,i=this.url,r=this.url=pi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,S.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(p.MANIFEST_LOADING,{url:e})}startLoad(e=-1){S.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){S.log("stopLoad"),this.started=!1,this.networkControllers.forEach(e=>{e.stopLoad()})}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1)})}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.stopLoad()})}swapAudioCodec(){S.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){S.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){S.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){S.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){S.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){S.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){S.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 ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(S.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Tl(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 i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,i)for(let n=r;n--;){const a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var t;return(t=this.audioTrackController)==null?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return(t=this.subtitleTrackController)==null||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}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}$e.defaultConfig=void 0;function ps(){const s=document;return!!(s.fullscreenElement||s.mozFullScreenElement||s.webkitFullscreenElement||s.msFullscreenElement)}function ua(s){if(ps())return new Promise(t=>t(null));const e=s;if(e.requestFullscreen)return e==null?void 0:e.requestFullscreen();if(e.mozRequestFullScreen)return e==null?void 0:e.mozRequestFullScreen();if(e.webkitRequestFullScreen)return e==null?void 0:e.webkitRequestFullScreen();if(e.msRequestFullscreen)return e==null?void 0:e.msRequestFullscreen()}function ha(){if(!ps())return new Promise(e=>e(null));const s=document;if(s.exitFullscreen)return s.exitFullscreen();if(s.mozCancelFullScreen)return s.mozCancelFullScreen();if(s.webkitCancelFullScreen)return s.webkitCancelFullScreen();if(s.msExitFullscreen)return s.msExitFullscreen()}function da(s,e){let t=null;return function(...i){const r=this;t!==null&&clearTimeout(t),t=setTimeout(()=>{t=null,s.apply(r,i)},e||1e3)}}const ys=new Intl.NumberFormat(void 0,{minimumIntegerDigits:2}),fa=["play","pause","ended","loadeddata","waiting","playing","timeupdate","canplay","canplaythrough","statechanged","error"],vs=s=>{const e=Math.floor(s%60),t=Math.floor(s/60)%60,i=Math.floor(s/3600);return i===0?`${t}:${ys.format(e)}`:`${i}:${ys.format(t)}:${ys.format(e)}`},_h=Ee.extend({name:"VideoPlayer",components:{ESpinner:gi},props:{sources:{type:[Array,String],required:!0},videoListeners:{type:Object,default:()=>({})},videoOptions:{type:Object,default:()=>({})},isHls:{type:Boolean,default:!1},streamingToken:{type:String,default:""},isLiveView:{type:Boolean,default:!1}},data(){return{playing:!1,percentagePlayed:0,videoLength:"0:00",duration:0,videoDuration:0,currentTime:"0:00",realtime:0,isScrubbing:!1,wasPaused:!1,isFullscreen:!1,isFinished:!1,isLoading:!0,isError:!1,player:new $e}},computed:{sourceItems(){return Array.isArray(this.sources)?this.sources:[{src:this.sources}]},hasStartedOrFinished(){return(this.isFinished||this.realtime<=.1)&&!this.isLoading&&!this.isLooped()},withControls(){const s=this.videoOptions;return(s==null?void 0:s.controls)===!1?"hide":""}},mounted(){this.isHls&&this.initHls(),this.bindEvents(),this.initializePlayer(),this.initializeFullscreenListeners()},beforeDestroy(){this.unbindEvents(),this.destroyPlayer(),this.removeFullscreenListeners()},methods:{initHls(){var e,t,i,r;const s=this.$refs.player;(e=this.player)!=null&&e.stopLoad&&this.player.stopLoad(),$e.isSupported()&&(this.isLoading=!0,this.player=new $e({startPosition:0,xhrSetup:n=>{this.streamingToken&&n.setRequestHeader("Authorization",`Bearer ${this.streamingToken}`)}}),(t=this.player)==null||t.loadSource(this.sources[0].src),(i=this.player)==null||i.attachMedia(s),(r=this.player)==null||r.on($e.Events.MANIFEST_PARSED,()=>{this.playing&&s.play()}))},handle404Error(){this.isError=!0,this.isLoading=!1,this.playing=!1},bindEvents(){const s=this.$refs.player;fa.forEach(e=>{s.addEventListener(e,()=>this.bindVideoEvent(e),!0)})},unbindEvents(){const s=this.$refs.player;fa.forEach(e=>{s.removeEventListener(e,()=>this.bindVideoEvent(e),!0)})},bindVideoEvent(s){const e=this.$refs.player;if(!e)return;const t=this.$refs.timelineContainer;s==="loadeddata"&&(this.videoLength=vs(e.duration)),s==="timeupdate"&&(this.percentagePlayed=(e==null?void 0:e.currentTime)/e.duration*100,t.style.setProperty("--progress-position",this.percentagePlayed.toString())),this.$emit(s,{event,player:e})},initializePlayer(){const s=this.$refs.player;s&&(s.autoplay&&this.setPlaying(!0),document.addEventListener("mouseup",this.handleScrubbingOnMouseEnd),document.addEventListener("keydown",this.handleKeyDown))},destroyPlayer(){window.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("mouseup",this.handleScrubbingOnMouseEnd)},removeFullscreenListeners(){document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled?(document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("webkitfullscreenchange",this.handleFullscreenChange),document.removeEventListener("mozfullscreenchange",this.handleFullscreenChange),document.removeEventListener("MSFullscreenChange",this.handleFullscreenChange)):console.log("Fullscreen API is not supported in this browser.")},initializeFullscreenListeners(){document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled?(document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("webkitfullscreenchange",this.handleFullscreenChange),document.addEventListener("mozfullscreenchange",this.handleFullscreenChange),document.addEventListener("MSFullscreenChange",this.handleFullscreenChange)):console.log("Fullscreen API is not supported in this browser.")},handleFullscreenChange(){this.isFullscreen=document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement||window.innerWidth==screen.width&&window.innerHeight==screen.height},isLooped(){return this.$refs.player.loop},handleScrubbingOnMouseEnd(s){this.isScrubbing&&this.toggleScrubbing(s)},handleEnded(){this.isFinished=!0,this.playing=!1},handleLoading(){this.isLoading=!1},play(){const s=this.$refs.player;if(!s)return;s.play()!==void 0&&s.play().then(()=>this.setPlaying(!0)).catch(console.error)},pause(){const s=this.$refs.player;s&&(s.pause(),this.setPlaying(!1))},togglePlay(){this.playing?this.pause():this.play()},setPlaying(s){this.playing=s},seekToPercentage(s){const e=this.$refs.player;if(!e)return;const t=s/100*e.duration;e.currentTime=t},convertTimeToDuration(s){return[parseInt(s/60%60,10),parseInt(s%60,10)].join(":").replace(/\b(\d)\b/g,"0$1")},closeFullscreenMode(){document.fullscreenElement&&(ha().then(()=>{this.isFullscreen=!1,console.log("Exited fullscreen")}),this.isFullscreen=!1)},openFullscreenMode(){const s=this.$refs.videoContainer;s&&(ua(s).then(()=>{this.isFullscreen=!0}),this.isFullscreen=!0)},toggleFullscreenMode(){this.isFullscreen?this.closeFullscreenMode():this.openFullscreenMode()},getDuration(){const s=this.$refs.player;this.videoLength=vs(s.duration),this.videoDuration=s.duration},handleTimeUpdate(){const s=this.$refs.player,e=this.$refs.timelineContainer;if(!s||!e)return;this.currentTime=vs(s.currentTime),this.realtime=s.currentTime;const t=Number(this.realtime)/Number(this.videoDuration);e.style.setProperty("--progress-position",t.toString())},handleTimelineUpdate(s){const e=this.$refs.player;if(!document.body.contains(e))return;const t=this.$refs.timelineContainer,i=t.getBoundingClientRect(),r=Math.min(Math.max(0,s.x-i.x),i.width)/i.width;t.style.setProperty("--preview-position",r.toString()),this.isScrubbing&&(s.preventDefault(),t.style.setProperty("--progress-position",r.toString()))},skip(s=5){const e=this.$refs.player;e.currentTime+=s},async toggleScrubbing(s){const e=this.$refs.timelineContainer,t=this.$refs.videoContainer,i=this.$refs.player;if(!i)return;const r=e.getBoundingClientRect(),n=Math.min(Math.max(0,s.x-r.x),r.width)/r.width;if(this.isScrubbing=(s.buttons&1)===1,t.classList.toggle("scrubbing",this.isScrubbing),this.isScrubbing){this.wasPaused=i.paused,await i.pause(),this.handleTimelineUpdate(s);return}if(this.realtime=n*this.videoDuration,i.currentTime=n*this.videoDuration,this.wasPaused)return;const a=i.play();a!==void 0&&a.then(()=>this.handleTimelineUpdate(s)).catch(console.error)},handleKeyDown(s){var t;const e=(t=document.activeElement)==null?void 0:t.tagName.toLowerCase();if(e!=="input")switch(s.key.toLowerCase()){case" ":if(e==="button")return;this.togglePlay();break;case"k":this.togglePlay();break;case"escape":s.preventDefault(),this.closeFullscreenMode(),this.isFullscreen=!1;break;case"f":this.openFullscreenMode(),this.isFullscreen=!0;break}}}}),Qh="";var Ih=function(){var e=this,t=e._self._c;return t("div",{ref:"videoContainer",staticClass:"video-container paused",attrs:{"data-volume-level":"high"}},[t("video",e._g(e._b({ref:"player",attrs:{controls:!1,preload:"auto"},on:{ended:e.handleEnded,click:e.togglePlay,loadedmetadata:e.getDuration,timeupdate:e.handleTimeUpdate,loadeddata:e.handleLoading}},"video",e.videoOptions,!1),e.videoListeners),e._l(e.sourceItems,function(i){return t("source",e._g({key:i.src,attrs:{src:i.src,type:i.type},on:{error:e.handle404Error}},e.videoListeners))}),0),e.isLoading?t("div",{staticClass:"spinner-container"},[t("ESpinner",{attrs:{color:!e.isHls,size:e.isHls?"7xl":"9xl",opacity:"0.6",dark:!0}})],1):e._e(),e.isError?t("div",{staticClass:"spinner-container e-gap-3"},[t("i",{staticClass:"fa-solid fa-video-slash fa-2xl e-align-middle"}),t("span",[e._v("This video file cannot be played.")])]):e._e(),t("div",{class:["video-controls-container",e.withControls]},[t("div",{staticClass:"controls"},[t("button",{ref:"playPauseBtn",staticClass:"play-pause-btn fa-lg fa-solid",class:{"fa-play":!e.playing,"fa-pause":e.playing},attrs:{title:e.playing?"pause":"play"},on:{click:e.togglePlay}}),t("div",{staticClass:"duration-container"},[t("div",{ref:"currentTimeElem",staticClass:"current-time"},[e._v(" "+e._s(e.currentTime)+" ")]),e._v(" / "),t("div",{ref:"totalTimeElem",staticClass:"total-time"},[e._v(e._s(e.videoLength))])]),t("div",{ref:"timelineContainer",staticClass:"timeline-container",on:{mousemove:e.handleTimelineUpdate,mousedown:e.toggleScrubbing}},[e._m(0)]),t("button",{ref:"fullScreenBtn",staticClass:"full-screen-btn fa-solid",class:{"fa-expand":!e.isFullscreen,"fa-compress":e.isFullscreen},on:{click:e.toggleFullscreenMode}})])])])},wh=[function(){var s=this,e=s._self._c;return e("div",{staticClass:"timeline"},[e("div",{staticClass:"thumb-indicator"})])}],kh=Ie(_h,Ih,wh,!1,null,"9071f674",null,null);const ma=kh.exports,si=s=>{const e=I.utcFormat("%_d")(s),i={1:"st",2:"nd",3:"rd"}[e.charAt(1)]||"th";return`${e}${i}`},ga=s=>new Date(Date.UTC(s.getUTCFullYear(),s.getUTCMonth(),s.getUTCDate()+1)).getUTCDate()===1?"":I.utcFormat("%-d")(s),St=s=>["0"," 0","00"].includes(I.utcFormat("%H")(s))?"":`${I.utcFormat("%H")(s)}h`,je=s=>{const e=I.utcFormat("%H:%M")(s);return e==="00:00"?"":e},xs=s=>I.utcFormat("%M:%S")(s),pa=s=>`${I.utcFormat("%Hh%Mm")(s)}`,Ts=s=>{const e=je(s),t=si(s),i=I.utcFormat("%B")(s);return e||`${i} ${t}`},Es=s=>{const e=je(s),t=Number.parseInt(I.utcFormat("%H")(s)),i=si(s),r=I.utcFormat("%B")(s);return e&&t%6===0?`${r} ${i} ${e}`:Ts(s)},bt=s=>e=>{const t=I.utcFormat("%H")(e);return!(I.utcFormat("%M")(e)==="00"&&Number.parseInt(t)%s===0)},Ss=s=>e=>{const t=I.utcFormat("%M")(e);return Number.parseInt(t)%s!==0},ya=s=>e=>{const t=I.utcFormat("%M")(e),i=I.utcFormat("%S")(e);return Number.parseInt(t)%s!==0&&Number.parseInt(i)===0},K={_10_seconds:25e-6,_20_seconds:1e-4,_30_seconds:15e-5,_1_minute:3e-4,_2_minutes:75e-5,_5_minutes:.002,_15_minutes:.005,_30_minutes:.01,_1_hour:.025,_2_hours:.05,_3_hours:.1,_4_hours:.15,_6_hours:.25,_1_day:1,_2_days:2,_1_month:8,_1_month_abbr:13,_1_month_letter:22,_3_months:33,_2_year:48,_5_years:120,_20_years:480,_75_years:1800,_300_years:7200,infinity:1/0},Ph={[mt.overview]:[{precision:K._30_seconds,interval:I.utcMinute.every(2),format:pa},{precision:K._1_minute,interval:I.utcMinute.every(5),format:pa},{precision:K._2_minutes,interval:I.utcMinute.every(10),format:Ts},{precision:K._5_minutes,interval:I.utcMinute.every(20),format:Es},{precision:K._15_minutes,interval:I.utcHour,format:Es},{precision:K._30_minutes,interval:I.utcHour.every(2),format:Es},{precision:K._2_hours,interval:I.utcHour.every(6),format:s=>{const e=je(s),t=si(s),i=I.utcFormat("%B")(s);return e||`${i} ${t}`}},{precision:K._3_hours,interval:I.utcHour.every(12),format:Ts},{precision:K._6_hours,interval:I.utcHour.every(24),format:s=>{const e=si(s);return`${I.utcFormat("%b")(s)} ${e}`}},{precision:K._2_days,interval:I.utcMonth,format:s=>{const t=s.getUTCMonth()===0&&s.getUTCDate()===1?"%Y – %B":"%B";return I.utcFormat(t)(s)}},{precision:K._2_year,interval:I.utcYear.every(2),format:"%Y"},{precision:K._5_years,interval:I.utcYear.every(5),format:"%Y"},{precision:K._20_years,interval:I.utcYear.every(20),format:"%Y"},{precision:K._75_years,interval:I.utcYear.every(75),format:"%Y"},{precision:K._300_years,interval:I.utcYear.every(300),format:"%Y"},{precision:K.infinity,interval:I.utcMonth.every(12),format:"%Y"}],[mt.detailed]:[{precision:K._10_seconds,interval:I.utcSecond.every(10),format:xs},{precision:K._20_seconds,interval:(Ea=I.utcSecond.every(20))==null?void 0:Ea.filter(ya(2)),format:xs},{precision:K._30_seconds,interval:(Sa=I.utcSecond.every(30))==null?void 0:Sa.filter(ya(2)),format:xs},{precision:K._1_minute,interval:I.utcMinute.filter(Ss(5)),format:je},{precision:K._2_minutes,interval:(ba=I.utcMinute.every(2))==null?void 0:ba.filter(Ss(10)),format:je},{precision:K._5_minutes,interval:(Aa=I.utcMinute.every(5))==null?void 0:Aa.filter(Ss(20)),format:je},{precision:K._15_minutes,interval:(La=I.utcMinute.every(15))==null?void 0:La.filter(bt(1)),format:je},{precision:K._30_minutes,interval:(Ra=I.utcMinute.every(30))==null?void 0:Ra.filter(bt(2)),format:je},{precision:K._1_hour,interval:I.utcHour.filter(bt(6)),format:St},{precision:K._2_hours,interval:(Ca=I.utcHour.every(2))==null?void 0:Ca.filter(bt(6)),format:St},{precision:K._3_hours,interval:(Da=I.utcHour.every(3))==null?void 0:Da.filter(bt(12)),format:St},{precision:K._4_hours,interval:I.utcHour.every(4),format:St},{precision:K._6_hours,interval:I.utcHour.every(6),format:St},{precision:K._1_day,interval:I.utcDay,format:ga},{precision:K._2_days,interval:I.utcDay.every(2),format:ga},{precision:K._1_month,interval:I.utcMonth,format:"%B"},{precision:K._1_month_abbr,interval:I.utcMonth,format:"%b"},{precision:K._1_month_letter,interval:I.utcMonth,format:s=>I.utcFormat("%B")(s).charAt(0)},{precision:K._3_months,interval:I.utcMonth.every(3),format:"Q%q"},{precision:K._2_year,interval:I.utcMonth.every(6),format:"%Y"},{precision:K._5_years,interval:I.utcYear.every(2),format:"%Y"},{precision:K._20_years,interval:I.utcYear.every(4),format:"%Y"},{precision:K._75_years,interval:I.utcYear.every(25),format:"%Y"},{precision:K._300_years,interval:I.utcYear.every(100),format:"%Y"},{precision:K.infinity,interval:I.utcYear.every(500),format:""}],[mt.detailedBackground]:[{precision:K._10_seconds,interval:I.utcSecond,format:""},{precision:K._20_seconds,interval:I.utcSecond.every(5),format:""},{precision:K._30_seconds,interval:I.utcSecond.every(10),format:""},{precision:K._1_minute,interval:I.utcSecond.every(20),format:""},{precision:K._2_minutes,interval:I.utcSecond.every(30),format:""},{precision:K._5_minutes,interval:I.utcMinute,format:""},{precision:K._15_minutes,interval:I.utcMinute.every(3),format:""},{precision:K._30_minutes,interval:I.utcMinute.every(6),format:""},{precision:K._1_hour,interval:I.utcMinute.every(15),format:""},{precision:K._2_hours,interval:I.utcMinute.every(30),format:""},{precision:K._3_hours,interval:I.utcHour,format:""},{precision:K._4_hours,interval:I.utcHour,format:""},{precision:K._6_hours,interval:I.utcMinute.every(120),format:""},{precision:K._1_day,interval:I.utcHour.every(8),format:""},{precision:K._2_days,interval:I.utcHour.every(12),format:""},{precision:K._1_month,interval:I.utcDay.filter(s=>{const e=s.getUTCDate(),t=new Date(s.getUTCFullYear(),s.getUTCMonth()+1,0).getUTCDate(),i=Math.ceil(t/5);return e===i||e===2*i||e===3*i||e===4*i}),format:""},{precision:K._1_month_abbr,interval:I.utcDay.filter(s=>{const e=s.getUTCDate(),t=new Date(s.getUTCFullYear(),s.getUTCMonth()+1,0).getUTCDate(),i=Math.ceil(t/4);return e===i||e===2*i||e===3*i}),format:""},{precision:K._1_month_letter,interval:I.utcDay.filter(s=>{const e=s.getUTCDate(),t=new Date(s.getUTCFullYear(),s.getUTCMonth()+1,0).getUTCDate(),i=Math.ceil(t/2);return e===i}),format:""},{precision:K._3_months,interval:I.utcMonth,format:""},{precision:K._3_months,interval:I.utcMonth,format:""},{precision:K._2_year,interval:I.utcYear,format:""},{precision:K._5_years,interval:I.utcYear.every(2),format:""},{precision:K._20_years,interval:I.utcYear.every(5),format:""},{precision:K._75_years,interval:I.utcYear.every(20),format:""},{precision:K._300_years,interval:I.utcYear.every(100),format:""},{precision:K.infinity,interval:I.utcYear.every(500),format:""}]},ri={bind(s,e){const{value:t}=e;if(typeof t!="function"){console.error("Invalid callback function provided to v-resize-observer");return}const i=new ResizeObserver(r=>{r[0]&&t(r[0])});i.observe(s),s.__resizeObserver__=i},unbind(s){s.__resizeObserver__&&(s.__resizeObserver__.disconnect(),delete s.__resizeObserver__)}},va=[{name:"resize-observer",definition:ri}],qe={milestone:"e-tl-milestone",milestoneBullet:"e-tl-milestone--bullet",milestoneDot:"e-tl-milestone--dot",milestoneContent:"e-tl-milestone-content",milestoneLine:"e-tl-milestone-line",milestonesContainer:"e-tl-milestones",milestoneHovered:"e-tl-milestone--hovered",milestoneSelected:"e-tl-milestone--selected",milestoneLabel:"e-tl-milestone-label",milestoneDotContainer:"e-tl-milestone-dot-container",milestoneDotLine:"e-tl-milestone-dot-line",milestoneDotDot:"e-tl-milestone-dot-dot",milestoneDotHovered:"e-tl-milestone-dot--hovered"},Oh=Ee.extend({name:"ETimeline",directives:{resizeObserver:ri},props:{milestone:{type:Object,required:!0},size:{type:Number,default:18},borderColor:{type:String,default:"#eee"},backgroundColor:{type:String,default:"#aaa"},borderWidth:{type:Number,default:2},transitionDuration:{type:Number,default:500},dot:{type:Boolean,default:!1},dotSize:{type:Number,default:8},lineWidth:{type:Number,default:2},lineHeight:{type:Number,default:28}},data(){return{milestoneClasses:qe,timeouts:[],isInitialRender:!0,isMouseOver:!1}},computed:{transitionStyles(){return this.isInitialRender?{}:{transition:`transform ${this.transitionDuration}ms, width ${this.transitionDuration}ms, height ${this.transitionDuration}ms, padding ${this.transitionDuration}ms, border-radius ${this.transitionDuration}ms`}},sizeStyles(){return this.dot?{}:{width:`${this.size}px`,height:`${this.size}px`}},positionStyles(){return this.dot&&this.isMouseOver?{transform:`translateY(calc(-100% - ${this.lineHeight}px))`}:{}},styles(){return{...this.sizeStyles,...this.positionStyles,backgroundColor:this.backgroundColor,borderColor:this.borderColor,borderWidth:`${this.borderWidth}px`,borderStyle:"solid",...this.transitionStyles}},contentStyles(){return this.transitionStyles},computedTransitionDuration(){return this.isInitialRender?0:this.transitionDuration},labelStyles(){return{transition:`opacity ${this.computedTransitionDuration}ms`}},dotContainerStyles(){return{top:this.isMouseOver?`calc(100% - ${this.borderWidth}px)`:`calc(50% + ${this.dotSize/2}px)`,height:`calc(${this.lineHeight}px + ${this.dotSize}px)`,left:`calc(50% - ${this.lineWidth}px / 2)`,transition:`${this.computedTransitionDuration}ms`}},lineStyles(){return{bottom:`${this.dotSize/2}px`,left:`calc(50% - ${this.lineWidth}px / 2)`,width:`${this.lineWidth}px`,height:this.isMouseOver?`${this.lineHeight}px`:"0",backgroundColor:this.borderColor,transition:`${this.computedTransitionDuration}ms`}},dotStyles(){return{top:`${this.lineHeight}px`,left:`calc(50% - ${this.dotSize}px / 2)`,width:`${this.dotSize}px`,height:`${this.dotSize}px`,backgroundColor:this.borderColor,transition:`${this.computedTransitionDuration}ms`}}},mounted(){this.$nextTick(()=>{this.dot||(this.onMilestoneMouseOver(),this.onMilestoneMouseLeave()),this.isInitialRender=!1})},methods:{onMilestoneMouseOver(s){if(this.isMouseOver=!0,this.dot)return;const e=(s==null?void 0:s.target)||this.$refs.container;if(!e)return;const t=e.children[0];if(!t)return;const i=t.children[0];if(!i)return;const r=i.getBoundingClientRect(),n=e.dataset.timeoutId;n&&(clearTimeout(Number(n)),e.dataset.timeoutId=""),e.dataset.initialWidth||(e.dataset.initialWidth=e.style.width),e.dataset.initialHeight||(e.dataset.initialHeight=e.style.height),e.dataset.initialContentWidth||(e.dataset.initialContentWidth=String(r.width)),e.dataset.initialContentHeight||(e.dataset.initialContentHeight=String(r.height)),e.dataset.transitionStart=String(Date.now()),e.style.width=e.dataset.initialContentWidth+"px",e.style.height=e.dataset.initialContentHeight+"px",e.style.borderRadius="0.5em",e.classList.add(qe.milestoneHovered),t.style.opacity="1",t.style.width=e.dataset.initialContentWidth+"px",t.style.height=e.dataset.initialContentHeight+"px"},onMilestoneMouseMove(){this.timeouts.forEach(s=>clearTimeout(s)),this.isMouseOver=!0},onMilestoneMouseLeave(s){if(this.dot){this.timeouts.push(setTimeout(()=>{this.isMouseOver=!1},this.transitionDuration+100));return}const e=(s==null?void 0:s.target)||this.$refs.container;if(!e)return;e.style.width=e.dataset.initialWidth||"",e.style.height=e.dataset.initialHeight||"",e.style.borderRadius="10em";const t=e.children[0];if(!t)return;t.style.width="0",t.style.height="0",t.style.opacity="0";const i=Date.now()-Number(e.dataset.transitionStart),r=i>this.transitionDuration?this.transitionDuration:i,n=setTimeout(()=>{e.classList.remove(qe.milestoneHovered),e.dataset.timeoutId=""},r);e.dataset.timeoutId=String(n),this.timeouts.push(n)},onMilestoneClick(s,e){this.$emit("milestone-click",e)}}}),Jh="";var Fh=function(){var e=this,t=e._self._c;return t("div",{ref:"container",class:{[e.milestoneClasses.milestone]:!0,[e.milestoneClasses.milestoneBullet]:!e.dot,[e.milestoneClasses.milestoneHovered]:e.isMouseOver&&!e.dot,[e.milestoneClasses.milestoneDot]:e.dot,[e.milestoneClasses.milestoneDotHovered]:e.isMouseOver&&e.dot},style:e.styles,attrs:{tabindex:"0"},on:{mouseover:i=>e.onMilestoneMouseOver(i,e.milestone),mousemove:e.onMilestoneMouseMove,mouseleave:i=>e.onMilestoneMouseLeave(i,e.milestone),click:i=>e.onMilestoneClick(i,e.milestone)}},[t("div",{class:e.milestoneClasses.milestoneContent,style:e.contentStyles},[e._t("content",function(){return[t("span",[e._v(" "+e._s(e.milestone.text)+" ")])]})],2),e.dot?t("div",{class:e.milestoneClasses.milestoneDotContainer,style:e.dotContainerStyles},[t("div",{class:e.milestoneClasses.milestoneDotLine,style:e.lineStyles}),t("div",{class:e.milestoneClasses.milestoneDotDot,style:e.dotStyles})]):t("div",{class:e.milestoneClasses.milestoneLabel,style:e.labelStyles},[e._t("label")],2)])},Mh=[],Nh=Ie(Oh,Fh,Mh,!1,null,null,null,null);const Bh=Nh.exports,$={eventGroup:"event-group",eventGroupBg:"event-group-bg",eventRect:"event-rect",eventBarContainer:"event-bar-container",eventBarContainerHovered:"event-bar-container--hovered",eventBarContainerSelected:"event-bar-container--selected",eventBar:"event-bar",eventBarHoverZone:"event-bar-hover-zone",eventBarCap:"event-bar-cap",eventRectText:"event-rect-text",eventRectHovered:"event-rect--hovered",eventRectSelected:"event-rect--selected",labelGroup:"label-g",labelBg:"label-bg",labelBgFill:"label-bg-fill",labelText:"label-text",loadingIndicator:"loading-indicator",xAxis:"x-axis",selectedTimestampCursor:"selected-timestamp-cursor",marker:"marker",markerLabel:"marker-label",markerLine:"marker-line",markerDragged:"marker--dragged",milestone:"milestone",milestoneLine:"milestone-line",milestonesContainer:"milestones",milestoneHovered:"milestone--hovered",barChartGroup:"bar-chart-group",lineGraphGroup:"line-graph-group",lineGraphGroupLabel:"line-graph-group-label",lineGraphPath:"line-graph-path",lineGraphHoverZone:"line-graph-hover-zone",lineGraphDot:"line-graph-dot",curtain:"curtain",forbiddenInterval:"forbidden-interval"},Ue={transparencyGradient:"transparency-gradient",transparencyGradientLight:"transparency-gradient-light",loadingGradient:"loading-gradient",stripedPattern:"stripedPattern"},$h=Ee.extend({name:"ETimeline",directives:{resizeObserver:ri},components:{ETimelineMilestone:Bh},props:{eventsGroups:{type:Object,default:()=>({})},xAxesConfig:{type:Object,default:()=>Ph},dark:{type:Boolean,default:!1},startDate:{type:String,default:void 0},endDate:{type:String,default:void 0},selectedTimestamp:{type:String,default:void 0},showEventTooltip:{type:Boolean,default:!0},disableZoom:{type:Boolean,default:!1},insertZerosAtInterval:{type:String,default:void 0},flattenLineGraphEnds:{type:Boolean,default:!0},curtains:{type:Boolean,default:!1},showLabels:{type:Boolean,default:!0},rectMinWidth:{type:Number,default:1},barHeight:{type:Number,default:18},barYPadding:{type:Number,default:0},barXPadding:{type:Number,default:0},chartMinHeight:{type:Number,default:60},chartMinLabelHeight:{type:Number,default:18},minZoom:{type:Number,default:1e-4},maxZoom:{type:Number,default:85e4},minDate:{type:String,default:void 0},maxDate:{type:String,default:void 0},minVisibleDate:{type:String,default:void 0},maxVisibleDate:{type:String,default:void 0},cursorTimestamp:{type:[String,void 0],default:void 0},selectedClass:{type:[String,void 0],default:void 0},panOnDateClick:{type:Boolean,default:!1},panTransitionDuration:{type:Number,default:800},selectedDate:{type:String,default:""},autoResize:{type:Boolean,default:!0},markers:{type:Array,default:()=>[]},stickyMarkers:{type:Boolean,default:!0},fitMarkersOnChange:{type:Boolean,default:!1},fitMarkersTransitionDuration:{type:Number,default:800},zoomToBoundariesTransitionDuration:{type:Number,default:0},milestoneBulletSize:{type:Number,default:18},milestonesFirst:{type:Boolean,default:!0}},data(){return{tooltip:null,cursor:null,timeline:null,wrapperDiv:null,selectedTimestampCursor:null,svg:null,axesContainer:null,xAxes:{},timeScale:null,initialTimeScale:null,currentTimeScaleDensity:null,zoomBehavior:null,isMouseDown:!1,axisHeight:22,isHoveringEvent:!1,hoveredEvent:null,isHoveringTimeline:!1,hoveredTimestamp:null,eventTooltipStyle:{},hoveredEventType:null,utcOffset:0,lastTransform:{x:0,k:1},transformDiff:{translation:0,scale:1},yScale:null,hoveredCounts:[],countsByTimestamp:{},dotsByTimestamp:{},visibleFrom:null,visibleTo:null,curtainHandleWidth:5,leftCurtainWidth:50,rightCurtainWidth:50,isHoveringCurtain:!1,isDraggingCurtain:!1,characterWidth:7.5,textPadding:5,debouncedOnResize:()=>{},isFirstPaint:!0,timeouts:[],groupsVisibility:{},markersPositions:{},markersDragBehavior:null,initialMarkerDragMouseOffset:0,selectedMilestoneId:null,isInitialized:!1,lastValidTransform:I.zoomIdentity}},computed:{combinedBarsHeight(){return Object.values(this.barGroups).reduce((s,e)=>s+(this.getBarGroupHeight(e)||this.barChartHeight),0)},combinedBottomBarsHeight(){return Object.values(this.barGroups).reduce((s,e)=>s+(e.bottom?this.getBarGroupHeight(e):0),0)},combinedMilestonesHeight(){return Object.values(this.milestonesGroups).reduce((s,e)=>s+(e.height||this.barChartHeight),0)},milestonesYOffset(){return this.milestonesFirst?0:this.combinedBarsHeight-this.combinedBottomBarsHeight+(this.hasChart?this.chartHeight:0)},chartsYOffset(){return this.hasMilestones&&this.milestonesFirst?this.combinedMilestonesHeight:0},barsYOffset(){return(this.hasChart?this.chartHeight:0)+(this.hasMilestones&&this.milestonesFirst?this.combinedMilestonesHeight:0)},hasMilestones(){return Object.keys(this.milestonesGroups).length>0},barChartHeight(){return this.barHeight+this.barYPadding},classes(){return{wrapper:{"e-border-gray-700 e-timeline--dark":this.dark,"e-border-gray-300":!this.dark,"e-timeline--dragging":this.isInteractingWithCurtain},background:this.dark?"e-bg-gray-900":"e-bg-gray-50",tooltipSlot:this.dark?"e-bg-gray-900 e-text-white e-border-gray-700":"e-bg-gray-100 e-text-gray-700 e-border-gray-300",eventTooltipSlot:this.dark?"e-bg-gray-900 e-text-white e-border-gray-700":"e-bg-gray-100 e-text-gray-700 e-border-gray-300"}},lineGraphGroups(){return Object.entries(this.filteredEventsGroups).reduce((s,[e,t])=>t.chartType===Se.lineGraph?{...s,[e]:t}:s,{})},chartHeight(){if(!this.showLabels)return this.chartMinHeight;const e=(Object.keys(this.lineGraphGroups).length+Object.keys(this.barChartGroups).length)*this.barChartHeight;return Math.max(this.chartMinHeight,e)},barGroups(){return Object.entries(this.filteredEventsGroups).reduce((s,[e,t])=>!t.chartType||[Se.bars,Se.dots].includes(t.chartType)?{...s,[e]:t}:s,{})},barChartGroups(){return Object.entries(this.filteredEventsGroups).reduce((s,[e,t])=>t.chartType===Se.barChart?{...s,[e]:t}:s,{})},milestonesGroups(){return Object.entries(this.filteredEventsGroups).reduce((s,[e,t])=>t.chartType===Se.milestones?{...s,[e]:t}:s,{})},hasChart(){return Object.keys(this.lineGraphGroups).length+Object.keys(this.barChartGroups).length>0},labelRectWidth(){return Object.values(this.eventsGroups).reduce((t,i)=>{var r;return Math.max(t,(r=i.label)==null?void 0:r.length)},0)*this.characterWidth+2*this.textPadding},combinedXAxesHeight(){const s=Object.keys(this.xAxesConfig).length-1;return this.axisHeight*s},timelineHeight(){return(this.hasChart?this.chartHeight:0)+this.combinedXAxesHeight+this.combinedBarsHeight+this.combinedMilestonesHeight},filteredEventsGroups(){const s=Object.entries(this.eventsGroups).filter(([e,t])=>this.getCurrentGroupVisibility(e));return Object.fromEntries(s)},allEventsSorted(){const s=Object.values(this.filteredEventsGroups).map(e=>e.events).flat();return this.getSortedEvents(s)},oldestEvent(){let s;return this.allEventsSorted.length>1?s=this.allEventsSorted[0]:s={timestamp:new Date(new Date().getTime()-864e5)},s},latestEvent(){let s;return this.allEventsSorted.length>1?s=this.allEventsSorted[this.allEventsSorted.length-1]:s={timestamp:new Date},s},allLineChartTimestamps(){const s=new Set;return Object.values(this.lineGraphGroups).forEach(e=>{e.events.forEach(t=>{s.add(t.timestamp)})}),Array.from(s).sort()},placeholderLineChartGroup(){return this.fillTimeGaps(this.allLineChartTimestamps.map(s=>({timestamp:s,count:0})))},filledGapsLineGraphGroups(){return Object.entries(this.lineGraphGroups).reduce((s,[e,t])=>({...s,[e]:{...t,events:this.fillEvents(t.events)}}),{})},isInteractingWithCurtain(){return this.isHoveringCurtain||this.isDraggingCurtain},flattenedCounts(){return[...Object.values(this.lineGraphGroups),...Object.values(this.barChartGroups)].map(s=>s.events).flat()},hiddenGroupsLabels(){return Object.entries(this.groupsVisibility).reduce((s,[e,t])=>t?s:[...s,e],[])},minHoverZone(){return this.showLabels?this.labelRectWidth:0},sortedMarkers(){return this.isInitialized?[...this.markers].sort((s,e)=>new Date(s.timestamp).getTime()>new Date(e.timestamp).getTime()?1:-1):[]}},watch:{dark(){this.handleDarkModeChange()},selectedTimestamp(){this.repositionSelectedTimestampCursor()},markers(){this.updateMarkers(),this.fitMarkersOnChange&&this.zoomToFitMarkers()},startDate(){this.zoomToStartAndEndDates()},minDate(){this.updateForbiddenIntervals()},maxDate(){this.updateForbiddenIntervals()},endDate(){this.zoomToStartAndEndDates()},eventsGroups(){this.updateAndRedrawTimeline()},cursorTimestamp(){if(this.cursorTimestamp){this.hoveredTimestamp=this.cursorTimestamp;const s=this.tzStringToDate(this.hoveredTimestamp),e=this.timeScale(s);this.cursor.style.left=e+"px",this.isHoveringTimeline=!0}else this.isHoveringTimeline=!1},selectedDate(s){s&&this.panToTimestamp(s)},groupsVisibility(){this.updateAndRedrawTimeline()}},created(){this.debouncedOnResize=da(this.handleResize,100)},mounted(){this.initTimeline()},beforeDestroy(){this.clearTimeline(),document.removeEventListener("mouseup",this.handleDocumentMouseUp)},methods:{updateTimeline(){this.initOrUpdateSvg(),this.updateXAxes(),this.updateYScaleDomain(),this.updateForbiddenIntervals(),this.drawEventsGroups(),this.updateCurtains(),this.repositionSelectedTimestampCursor(),this.updateMarkers(),this.registerEventsListeners(),this.isInitialized=!0},initTimeline(s,e){if(this.initRefs(),!this.timeline||this.timeline.offsetWidth===0){this.timeouts.push(setTimeout(this.initTimeline,500));return}this.initOrUpdateSvg(),this.initDefs(),this.initUtcOffset(),this.initTimeScale(s,e),this.initXAxes(),this.initYScale(),this.initZoomBehavior(),this.initForbiddenIntervals(),this.drawEventsGroups(),this.curtains&&(this.initCurtains(),this.emitCurtainChange()),this.initSelectedTimestampCursor(),this.updateMarkers(),this.registerEventsListeners(),this.emitVisibleInterval(gt.initial),this.selectedDate&&this.panOnDateClick&&this.panToTimestamp(this.selectedDate),this.isInitialized=!0},initRefs(){this.tooltip=this.$refs.tooltip,this.cursor=this.$refs.cursor,this.timeline=this.$refs.timelineContainer,this.selectedTimestampCursor=this.$refs.selectedTimestamp,this.wrapperDiv=this.$refs.wrapperDiv},initOrUpdateSvg(){this.svg||(this.svg=I.select(this.timeline).append("svg")),this.svg.attr("width",this.timeline.offsetWidth).attr("height",this.timelineHeight)},initDefs(){const s=this.svg.append("defs");Object.entries(this.filteredEventsGroups).forEach(([t,i])=>{const{color:r,chartType:n}=i,a=s.append("linearGradient").attr("id",`${Ue.loadingGradient}-${t}`).attr("x1","0%").attr("y1","0%").attr("x2","100%").attr("y2","0%");a.append("stop").attr("offset","0%").attr("stop-color",r).attr("stop-opacity","0"),a.append("stop").attr("offset","50%").attr("stop-color",r).attr("stop-opacity","0.6"),a.append("stop").attr("offset","100%").attr("stop-color",r).attr("stop-opacity","0"),[Se.lineGraph,Se.barChart].includes(n)&&[{id:Ue.transparencyGradientLight,stop:38,opacity:.3},{id:Ue.transparencyGradient,stop:130,opacity:.4}].forEach(({id:l,stop:c,opacity:u})=>{const h=s.append("linearGradient").attr("id",`${l}-${t}`).attr("x1","0%").attr("x2","0%").attr("y1","0%").attr("y2","100%");h.append("stop").attr("offset","0%").style("stop-color",r).style("stop-opacity",u),h.append("stop").attr("offset",`${c}%`).style("stop-color",r).style("stop-opacity",0)})}),s.append("pattern").attr("id",Ue.stripedPattern).attr("width",6).attr("height",4).attr("patternUnits","userSpaceOnUse").attr("patternTransform","rotate(45)").append("rect").attr("width",2).attr("height",6).attr("transform","translate(0,0)").attr("fill","#ddd")},initUtcOffset(){const s=this.startDate||this.oldestEvent.timestamp||this.oldestEvent.startDate;this.utcOffset=We.parseZone(s).utcOffset()},initTimeScale(s,e){const t=s||this.startDate||this.oldestEvent.timestamp||this.oldestEvent.startDate,i=e||this.endDate||this.latestEvent.timestamp||this.latestEvent.endDate;this.timeScale=I.scaleTime().domain([this.tzStringToDate(t),this.tzStringToDate(i)]).range([0,this.timeline.offsetWidth]),this.initialTimeScale=this.timeScale.copy(),this.updateCurrentTimeScaleDensity()},initXAxes(){let s=0;const e=5;for(const t in this.xAxesConfig){const i=this.createAxis(t);this.xAxes[t]=i,this.svg.append("g").classed($.xAxis,!0).classed(`${$.xAxis}-${t}`,!0).attr("transform",`translate(0, ${s||e})`).call(i),this.translateTicksText(t),s+=this.axisHeight}this.updateXAxes()},updateXAxes(){let s=0;const e=5;for(const t in this.xAxesConfig){const i=this.xAxes[t];i.tickSizeOuter(0),i.tickSizeInner(this.timelineHeight),this.svg.select(`.${$.xAxis}-${t}`).attr("transform",`translate(0, ${s||e})`).call(i),this.translateTicksText(t),s+=this.axisHeight}},initYScale(){this.yScale=I.scaleLinear().range([this.chartHeight,0]),this.updateYScaleDomain()},updateYScaleDomain(){const[s,e]=this.timeScale.domain(),t=this.flattenedCounts.filter(r=>{const n=new Date(r.startDate||r.timestamp),a=new Date(r.endDate||r.timestamp);return a>=s&&a<=e||n>=s&&n<=e}),i=I.max(t,r=>r.count);this.yScale.domain([0,i])},initZoomBehavior(){this.disableZoom||(this.zoomBehavior=I.zoom().on("zoom",this.handleZoom).scaleExtent([this.minZoom,this.maxZoom]),this.svg.call(this.zoomBehavior),this.svg.call(this.zoomBehavior.transform,I.zoomIdentity))},zoomToFitMarkers(){const s=this.markers.map(u=>new Date(u.timestamp).getTime());if(s.length<2)return;const e=Math.min(...s),t=Math.max(...s),i=this.initialTimeScale.domain().map(u=>u.getTime()),r=i[1]-i[0],n=t-e,a=.1*n,o=n+2*a;let l=r/o;const c=this.zoomBehavior.scaleExtent();l=Math.min(Math.max(l,c[0]),c[1]),this.svg.transition().duration(this.fitMarkersTransitionDuration/2).call(this.zoomBehavior.scaleTo,l).on("end",()=>this.translateMarkersIntoView(e,t,l))},translateMarkersIntoView(s,e,t){const i=this.timeScale(new Date(s)),r=this.timeScale(new Date(e)),n=(i+r)/2,o=this.svg.node().getBoundingClientRect().width/2-n,l=I.zoomTransform(this.svg.node());this.svg.transition().duration(this.fitMarkersTransitionDuration/2).call(this.zoomBehavior.transform,I.zoomIdentity.translate(l.x+o,l.y).scale(t))},initSelectedTimestampCursor(){this.svg.append("line").attr("class",$.selectedTimestampCursor).style("stroke","red").style("stroke-width","1px").style("opacity",0).attr("x1",0).attr("x2",0).attr("y1",0),this.repositionSelectedTimestampCursor()},updateMarkers(){if(!this.markers.length)return;const s=12,e=200;this.sortedMarkers.forEach((t,i,r)=>{const n=typeof t.timestamp=="string"?this.tzStringToDate(t.timestamp):t.timestamp,a=this.timeScale(n);let o=!1;const l=this.stickyMarkers?Math.max(a,i*s):a;if(i<r.length-1){const c=r[i+1],u=typeof c.timestamp=="string"?this.tzStringToDate(c.timestamp):c.timestamp,h=this.timeScale(u);o=(this.stickyMarkers?Math.max(h,(i+1)*s):a)-l<e+s}this.markersPositions={...this.markersPositions,[t.id]:{isHidden:o,position:l}}}),this.initMarkersDragBehavior()},updateAndRedrawTimeline(){this.updateTimeline()},clearTimeline(){this.svg&&this.svg.remove(),this.countsByTimestamp={}},repositionSelectedTimestampCursor(){const s=this.svg.select(`.${$.selectedTimestampCursor}`);if(!this.selectedTimestamp){s.style("opacity",0);return}const e=this.tzStringToDate(this.selectedTimestamp),t=this.timeScale(e);isNaN(t)?s.style("opacity",0):s.attr("x1",t).attr("x2",t).style("opacity",.5),s.attr("y2",this.timelineHeight)},updateCurrentTimeScaleDensity(){const s=this.timeScale.invert(0).getTime(),e=this.timeScale.invert(1).getTime(),t=36e5,i=(e-s)/t;isNaN(i)||(this.currentTimeScaleDensity=i)},registerEventsListeners(){document.addEventListener("mouseup",this.handleDocumentMouseUp),this.svg.on("mousedown",this.handleMouseDown),this.svg.on("mousemove",this.handleMouseMove),this.svg.on("click",this.handleClick),this.svg.on("mouseleave",this.handleMouseLeave)},emitVisibleInterval(s){const e=this.timeScale.invert(0),t=this.timeScale.invert(this.timeline.offsetWidth);if(this.visibleFrom&&this.visibleFrom.getTime()===e.getTime()&&this.visibleTo&&this.visibleTo.getTime()===t.getTime())return;this.visibleFrom=e,this.visibleTo=t;const i=this.dateToTzString(this.visibleFrom),r=this.dateToTzString(this.visibleTo);this.$emit("visible-interval-change",{fromDate:i,toDate:r,trigger:s,transform:this.transformDiff})},createAxis(s){const e=this.xAxesConfig[s],t=this.getAxisTicksConfig(e);return I.axisBottom(this.timeScale).ticks(t.interval).tickFormat(t.formatFn).tickSizeOuter(0).tickSizeInner(this.timelineHeight)},getAxisTicksConfig(s){const{interval:e,format:t}=s.find(r=>r.precision>=this.currentTimeScaleDensity&&r.interval);return{formatFn:r=>typeof t=="function"?t(r):I.timeFormat(t)(r),interval:e}},onResize(s){this.isFirstPaint?(this.handleResize(s),this.isFirstPaint=!1):this.debouncedOnResize(s)},handleResize({contentRect:s}){this.svg&&(this.svg.attr("width",s.width),this.updateAndRedrawTimeline())},handleDarkModeChange(){if(!this.showLabels)return;const s=this;this.svg.selectAll(`.${$.labelBg}`).each(function(){I.select(this).style("fill",s.dark?"black":"white")}),this.svg.selectAll(`.${$.labelBgFill}`).each(function(){const e=I.select(this),t=e.node().dataset.color;e.style("fill",s.getLabelBackgroundColor(t)).style("stroke",s.getTextFillColor(t)).style("stroke-width",.25)}),this.svg.selectAll(`.${$.labelText}`).each(function(){const e=I.select(this),t=e.node().dataset.color;e.style("fill",s.getTextFillColor(t))})},handleMouseDown(){this.isMouseDown=!0},handleDocumentMouseUp(s){this.isMouseDown=!1},handleMouseLeave(){this.isHoveringTimeline=!1,this.$emit("hovered-timestamp",void 0)},handleMouseMove(s){if(this.isMouseDown)return;const e=s.offsetX;if(e<=this.minHoverZone){this.isHoveringTimeline=!1;return}const t=this.timeScale.invert(e);this.hoveredTimestamp=this.dateToTzString(t),this.isHoveringTimeline=!0,this.$emit("hovered-timestamp",this.hoveredTimestamp),this.cursor.style.left=e+"px",this.tooltip&&(this.eventTooltipStyle={left:`${e}px`,bottom:`${this.timeline.getBoundingClientRect().height}px`,zIndex:100})},handleClick(s){const e=s.offsetX;if(e<=this.minHoverZone)return;const t=this.timeScale.invert(e),i=this.dateToTzString(t);this.$emit("date-clicked",i),this.isHoveringEvent&&this.$emit("event-clicked",{event:this.hoveredEvent,type:this.hoveredEventType}),this.panOnDateClick&&this.panToTimestamp(i)},handleMarkerClick(s){this.$emit("marker-clicked",s),this.panOnDateClick&&this.panToTimestamp(s.timestamp)},handleLineMouseOver(s,e,t){this.hoveredCounts=Object.entries(this.countsByTimestamp[`${e.timestamp}`]).reduce((i,r)=>{const[n,a]=r;return[...i,{type:n,count:a}]},[]),this.hoveredEvent=e,this.isHoveringEvent=!0,this.$emit("event-mouseover",{eventData:e,eventType:t,hoveredCounts:this.hoveredCounts})},handleLineMouseOut(){this.isHoveringEvent=!1,this.hoveredCounts=[],this.$emit("event-mouseout")},handleBarMouseOver(s,e,t){s.offsetX<=this.minHoverZone||(this.hoveredEvent=e,this.hoveredEventType=t,this.isHoveringEvent=!0,this.$emit("event-mouseover",{eventData:e,eventType:t}))},handleBarMouseOut(){this.isHoveringEvent=!1,this.hoveredEvent=null,this.$emit("event-mouseout")},handleLabelMouseOver(s){I.selectAll(`.${$.lineGraphGroup}-${s}`).classed(`${$.lineGraphGroup}--highlighted`,!0),I.selectAll(`.${$.lineGraphGroupLabel}`).classed(`${$.lineGraphGroupLabel}--highlighted`,!0)},handleLabelMouseLeave(s){I.selectAll(`.${$.lineGraphGroup}-${s}`).classed(`${$.lineGraphGroup}--highlighted`,!1),I.selectAll(`.${$.lineGraphGroupLabel}`).classed(`${$.lineGraphGroupLabel}--highlighted`,!1)},isZoomAllowed(s){const e=this.initialTimeScale.copy(),t=s.transform.rescaleX(e).domain(),i=this.minVisibleDate?this.tzStringToDate(this.minVisibleDate):void 0,r=this.maxVisibleDate?this.tzStringToDate(this.maxVisibleDate):void 0;return(!i||t[0]>=i)&&(!r||t[1]<=r)},handleZoom(s){if(!this.isZoomAllowed(s)){s.sourceEvent.preventDefault(),this.svg.call(this.zoomBehavior.transform,this.lastValidTransform);return}this.lastValidTransform=s.transform;const e=s.transform.rescaleX(this.initialTimeScale);this.timeScale.domain(e.domain()),this.updateCurrentTimeScaleDensity(),this.updateYScaleDomain();const t=s.transform.k/this.lastTransform.k;this.transformDiff={scale:t,translation:s.transform.x-this.lastTransform.x},this.lastTransform={...s.transform};for(const i in this.xAxes)this.rescaleAxis(i,e),this.translateTicksText(i);this.updateEventsBars(),this.updateLineGraphs(),this.updateBarChart(),this.updateLineGraphHoverZones(),this.updateMilestonesPositions(),this.repositionSelectedTimestampCursor(),this.updateForbiddenIntervals(),this.updateMarkers(),this.emitVisibleInterval(gt.zoom),this.curtains&&this.emitCurtainChange()},panToTimestamp(s){const e=this.tzStringToDate(s),t=this.timeScale(e),i=I.zoomTransform(this.svg.node()),r=i.x-t+this.timeline.offsetWidth/2;this.svg.transition().duration(this.panTransitionDuration).call(this.zoomBehavior.transform,I.zoomIdentity.translate(r,0).scale(i.k)),this.emitVisibleInterval(gt.autoPan)},emitCurtainChange(){const{startDate:s,endDate:e}=this.calculateDateRangeFromCurtains();this.$emit("curtain-range-change",{startDate:new Date(s).toISOString(),endDate:new Date(e).toISOString()})},calculateDateRangeFromCurtains(){const s=this.timeline.offsetWidth,e=this.timeScale.domain(),t=e[1].getTime()-e[0].getTime(),i=(this.leftCurtainWidth-this.curtainHandleWidth*2)/s*t,r=(this.rightCurtainWidth+this.curtainHandleWidth*2)/s*t,n=new Date(e[0].getTime()+i),a=new Date(e[1].getTime()-r);return{startDate:n,endDate:a}},handleDragStart(){this.isDraggingCurtain=!0},handleDragEnd(){this.isDraggingCurtain=!1},handleLeftDrag(s){s.sourceEvent.stopPropagation();const e=Math.min(s.x,this.timeline.offsetWidth-this.rightCurtainWidth);this.leftCurtainWidth=Math.max(0,e),this.svg.select(`.${$.curtain}--left`).attr("width",this.leftCurtainWidth),this.emitCurtainChange()},handleRightDrag(s){s.sourceEvent.stopPropagation();const e=this.timeline.offsetWidth,t=Math.min(this.timeline.offsetWidth-s.x,this.timeline.offsetWidth-this.leftCurtainWidth),i=e-t;this.rightCurtainWidth=Math.max(0,t),this.svg.select(`.${$.curtain}--right`).attr("width",this.rightCurtainWidth).attr("x",i),this.emitCurtainChange()},zoomToStartAndEndDates(){const s=this.startDate||this.oldestEvent.timestamp||this.oldestEvent.startDate,e=this.endDate||this.latestEvent.timestamp||this.latestEvent.endDate,t=this.tzStringToDate(s),i=this.tzStringToDate(e);this.initialTimeScale.domain([t,i]);const r=I.zoomTransform(this.svg.node()),n=i.getTime()-t.getTime(),o=this.initialTimeScale.range().map(f=>this.initialTimeScale.invert(f)).reduce((f,m)=>m.getTime()-f,0)/n*r.k,c=-(this.initialTimeScale(t)*o),[u,h]=this.zoomBehavior.scaleExtent(),d=Math.max(u,Math.min(h,o));this.svg.transition().duration(this.zoomToBoundariesTransitionDuration).call(this.zoomBehavior.transform,I.zoomIdentity.translate(c,0).scale(d))},rescaleAxis(s,e){const t=this.xAxes[s],i=this.getAxisTicksConfig(this.xAxesConfig[s]);t.scale(e).ticks(i.interval).tickFormat(i.formatFn).tickSizeOuter(0),this.svg.select(`.${$.xAxis}-${s}`).call(t)},translateTicksText(s){this.svg.select(`.${$.xAxis}-${s}`).selectAll(".tick text").each(function(){let e=I.select(this),t=e.node().getBBox();e.attr("x",t.height/2).attr("y",0).style("text-anchor","start")})},updateEventsBars(){const s=`.${$.eventGroup} > rect.${$.eventRect}`,e=`${s}:not(.${$.eventRect}--dot)`;this.svg.selectAll(s).attr("x",this.getEventRectX),this.svg.selectAll(e).attr("width",this.getEventRectWidth);const t=`.${$.eventGroup} > text.${$.eventRectText}`;this.svg.selectAll(t).attr("x",i=>this.getEventRectX(i)+this.textPadding).text(this.getEventText)},updateBarChart(){const s=Object.keys(this.barChartGroups).length;Object.keys(this.barChartGroups).forEach((e,t)=>{const i=d=>(this.getEventRectWidth(d)-this.barXPadding*2)/s,r=d=>this.yScale.range()[0]-this.yScale(d.count),n=d=>this.getEventRectX(d)+this.barXPadding+t*i(d),a=d=>this.yScale(d.count),o=`.${$.eventBarContainer}-${e}`,l=this.svg.selectAll(o),c=`.${$.barChartGroup} rect.${$.eventBarHoverZone}`;l.selectAll(c).attr("x",n).attr("width",i);const u=`.${$.barChartGroup} rect.${$.eventBar}`;l.selectAll(u).attr("x",n).attr("width",i).attr("y",a).attr("height",r);const h=`.${$.barChartGroup} rect.${$.eventBarCap}`;l.selectAll(h).attr("x",n).attr("width",i).attr("y",a)})},updateLineGraphs(){Object.entries(this.lineGraphGroups).forEach(([s])=>{const e=I.area().x(t=>this.timeScale(this.tzStringToDate(t.timestamp))).y0(this.timelineHeight).y1(t=>this.yScale(t.count)).curve(I.curveMonotoneX);this.svg.selectAll(`.${$.lineGraphPath}-${s}`).attr("d",t=>e(t))})},updateLineGraphHoverZones(){Object.keys(this.lineGraphGroups).forEach(s=>{const e=this;this.svg.selectAll(`.${$.lineGraphDot}-${s}`).each(function(t){I.select(this).attr("cx",e.timeScale(e.tzStringToDate(t.timestamp))).attr("cy",e.yScale(t.count))}),this.svg.selectAll(`.${$.lineGraphHoverZone}-${s}`).each(function(t){const i=e.timeScale(e.tzStringToDate(t.timestamp).getTime())-15;I.select(this).attr("x",i).attr("y",0).attr("width",30).attr("height",e.chartHeight)})})},getEventRectX(s){return isNaN(this.timeScale(this.tzStringToDate(s.startDate||s.timestamp)))?0:this.timeScale(this.tzStringToDate(s.startDate||s.timestamp))},getEventRectWidth(s){if(!s)return 0;if(s.startDate&&s.endDate){const e=new Date(s.startDate),t=new Date(s.endDate),i=this.timeScale(t)-this.timeScale(e);return Math.max(i,this.rectMinWidth)}else{const e=1/(this.currentTimeScaleDensity*3600);return Math.max(e,this.rectMinWidth)}},getEventText(s){var i;const t=(this.getEventRectWidth(s)-this.textPadding)/this.characterWidth;return t<4?"":((i=s.text)==null?void 0:i.length)<=t?s.text:`${s.text.slice(0,t-3)}...`},getElementLeftPosition(s){if(!s)return 0;const e=window.getComputedStyle(s);return parseInt(e.left)},isTimestampAllowedForMarker(s,e){return(this.minDate?s>=this.tzStringToDate(this.minDate):!0)&&(this.maxDate?s<=this.tzStringToDate(this.maxDate):!0)&&(e.minDate?s>=this.tzStringToDate(e.minDate):!0)&&(e.maxDate?s<=this.tzStringToDate(e.maxDate):!0)},handleMarkerDrag({marker:s,markerElement:e,dragEvent:t}){if(!s.isDraggable)return;t.type==="start"&&(this.initialMarkerDragMouseOffset=t.x-e.node().querySelector(`.${$.markerLine}`).getBoundingClientRect().left,e.classed($.markerDragged,!0));const i=t.x-this.initialMarkerDragMouseOffset,r=this.timeScale.invert(i-this.svg.node().getBoundingClientRect().left),n=this.timeScale(r),a=this.isTimestampAllowedForMarker(r,s);if(t.type==="drag"&&a&&e.attr("style",`left: ${n}px`),t.type==="end"&&a){const o=s.id||s.timestamp;this.markersPositions={...this.markersPositions,[o]:{...this.markersPositions[o],position:n}},e.classed($.markerDragged,!1)}t.type!=="start"&&this.$emit(`marker-drag-${t.type}`,{marker:s,newTimestamp:r.toISOString()})},removeMarkersDragBehavior(){this.markersDragBehavior&&(this.markersDragBehavior.on("start",null).on("drag",null).on("end",null),I.selectAll(`.${$.marker}`).call(this.markersDragBehavior))},initMarkersDragBehavior(){this.removeMarkersDragBehavior();const s=this;this.markersDragBehavior=I.drag().on("start",function(e,t){var i;(i=e.sourceEvent)==null||i.preventDefault(),s.handleMarkerDrag({marker:t,markerElement:I.select(this),dragEvent:e})}).on("drag",function(e,t){s.handleMarkerDrag({marker:t,markerElement:I.select(this),dragEvent:e})}).on("end",function(e,t){s.handleMarkerDrag({marker:t,markerElement:I.select(this),dragEvent:e})}),I.selectAll(`.${$.marker}`).data(this.sortedMarkers).call(this.markersDragBehavior)},initCurtains(){this.createCurtains(),this.updateCurtains()},createCurtains(){this.curtains&&(this.svg.append("rect").classed(`${$.curtain} ${$.curtain}--left`,!0).attr("fill","rgba(0, 0, 0, 0.5)").on("mouseenter",()=>this.isHoveringCurtain=!0).on("mouseleave",()=>this.isHoveringCurtain=!1).call(I.drag().on("start",this.handleDragStart).on("drag",this.handleLeftDrag).on("end",this.handleDragEnd)),this.svg.append("rect").classed(`${$.curtain} ${$.curtain}--right`,!0).attr("fill","rgba(0, 0, 0, 0.5)").on("mouseenter",()=>this.isHoveringCurtain=!0).on("mouseleave",()=>this.isHoveringCurtain=!1).call(I.drag().on("start",this.handleDragStart).on("drag",this.handleRightDrag).on("end",this.handleDragEnd)),this.updateCurtains())},updateCurtains(){const s=this.timeline.offsetWidth,e=this.timelineHeight;this.svg.select(`.${$.curtain}--left`).attr("width",this.leftCurtainWidth).attr("height",e+this.curtainHandleWidth*2).attr("y",-this.curtainHandleWidth).attr("x",-this.curtainHandleWidth),this.svg.select(`.${$.curtain}--right`).attr("x",s-this.rightCurtainWidth+this.curtainHandleWidth).attr("y",-this.curtainHandleWidth).attr("width",this.rightCurtainWidth+this.curtainHandleWidth*2).attr("height",e+this.curtainHandleWidth*2)},initForbiddenIntervals(){this.minDate&&this.svg.append("rect").attr("class",`${$.forbiddenInterval} ${$.forbiddenInterval}--min`),this.maxDate&&this.svg.append("rect").attr("class",`${$.forbiddenInterval} ${$.forbiddenInterval}--max`),this.updateForbiddenIntervals()},updateForbiddenIntervals(){const s=this.minDate?this.tzStringToDate(this.minDate).getTime():null,e=this.maxDate?this.tzStringToDate(this.maxDate).getTime():null;if(s){const t=this.timeScale(s);this.svg.select(`.${$.forbiddenInterval}--min`).attr("x",0).attr("y",0).attr("width",t>0?t:0).attr("height",this.timelineHeight).attr("fill",`url(#${Ue.stripedPattern})`)}if(e){const t=this.timeline.offsetWidth-this.timeScale(e),i=this.timeScale(e);this.svg.select(`.${$.forbiddenInterval}--max`).attr("x",i>0?i:0).attr("y",0).attr("width",t>0?t:0).attr("height",this.timelineHeight).attr("fill",`url(#${Ue.stripedPattern})`)}},drawEventsGroups(){this.svg.selectAll(`g.${$.eventGroup}`).remove(),this.svg.selectAll(`.${$.barChartGroup}`).remove(),this.svg.selectAll(`.${$.lineGraphGroup}`).remove(),this.svg.selectAll(`.${$.lineGraphGroupLabel}`).remove(),this.svg.selectAll(`.${$.loadingIndicator}`).remove(),this.drawLineGraphEventsGroups(),this.drawBarEventsGroups(),this.drawBarChartEventsGroups(),this.drawMilestonesPlaceholder()},drawLineGraphEventsGroups(){const s=this.combinedXAxesHeight+this.chartsYOffset,e=this.insertZerosAtInterval?this.filledGapsLineGraphGroups:this.lineGraphGroups;Object.entries(e).forEach(([t,i])=>{const r=this.svg.append("g").classed(`${$.lineGraphGroup} ${$.lineGraphGroup}-${t}`,!0).attr("transform",`translate(0,${s})`),{color:n,events:a}=i;this.drawLineGraph({events:a,gElement:r,color:n,type:t}),this.drawLineGraphHoverZones({events:a,gElement:r,color:n,type:t})}),Object.entries(this.lineGraphGroups).forEach(([t,i],r)=>{const{color:n,isLoading:a,label:o}=i,l=Math.max(this.chartMinLabelHeight,this.barChartHeight),c=this.chartHeight-l*(r+1),u=s+this.chartHeight-l,h=this.svg.append("g").classed($.lineGraphGroupLabel,!0).attr("transform",`translate(0,${s})`).on("mouseover",()=>this.handleLabelMouseOver(t)).on("mouseleave",()=>this.handleLabelMouseLeave(t));this.drawProgressIndicator({type:t,color:n,isLoading:a,yPosition:u}),this.drawTextLabel({color:n,label:o,type:t,height:l,yPosition:c,gElement:h})})},drawLineGraph({events:s,gElement:e,color:t,type:i}){const r=I.area().x(a=>this.timeScale(this.tzStringToDate(a.timestamp))).y0(this.timelineHeight).y1(a=>this.yScale(a.count)).curve(I.curveMonotoneX),n=`clip-${i}`;e.append("defs").append("clipPath").attr("id",n).append("rect").attr("width",this.timeline.offsetWidth).attr("height",this.chartHeight),e.append("path").datum(s).classed(`${$.lineGraphPath}-${i}`,!0).attr("fill",`url(#${Ue.transparencyGradientLight}-${i})`).attr("stroke",t).attr("stroke-linejoin","round").attr("stroke-linecap","round").attr("stroke-width",1).attr("d",a=>r(a)).attr("clip-path",`url(#${n})`)},drawLineGraphHoverZones({events:s,gElement:e,color:t,type:i}){s.forEach(r=>{const n=`${r.timestamp}`;this.countsByTimestamp[n]={...this.countsByTimestamp[n]||{},[i]:r.count};const a=e.append("circle").classed(`${$.lineGraphDot} ${$.lineGraphDot}-${i}`,!0).attr("cx",this.timeScale(this.tzStringToDate(r.timestamp))).attr("cy",this.yScale(r.count)).attr("r",1.5).attr("fill",t).attr("stroke-width",0).datum(r);this.dotsByTimestamp[n]=[...this.dotsByTimestamp[n]||[],a],e.append("rect").classed(`${$.lineGraphHoverZone}-${i}`,!0).attr("x",this.timeScale(this.tzStringToDate(r.timestamp))-15).attr("y",0).attr("width",30).attr("height",this.chartHeight).attr("fill","transparent").datum(r).on("mouseover",o=>{this.handleLineMouseOver(o,r,i),this.dotsByTimestamp[n].forEach(l=>l.classed(`${$.lineGraphDot}--active`,!0))}).on("mouseout",()=>{this.handleLineMouseOut(),this.dotsByTimestamp[n].forEach(o=>o.classed(`${$.lineGraphDot}--active`,!1))})})},drawSingleBarEventsGroup({type:s,eventsGroup:e,milestone:t,dots:i,dotsSize:r,bottom:n}){const{color:a,bgColor:o,label:l,events:c,barBorderRadius:u,isLoading:h,height:d,chartType:f}=e;let m=this.getBarGroupYPosition(s,n);const y=[Se.bars,Se.dots,void 0].includes(f)?this.getBarGroupHeight(e):d;t&&(m=this.getMilestoneGroupYPosition(s)),this.drawProgressIndicator({yPosition:m,type:s,color:a,isLoading:h});const v=this.svg.append("g").attr("data-color",a).classed($.eventGroup,!0).classed(`${$.eventGroup}-${s}`,!0);if(this.drawBackground({color:o||a,gElement:v,yPosition:m,height:y}),t||i){const T=i?.5:2,x=m+y/2;v.append("line").classed(qe.milestoneLine,!0).attr("x1",0).attr("x2",this.timeline.offsetWidth).attr("y1",x).attr("y2",x).style("stroke",a).style("stroke-width",T)}this.drawBars({events:c,color:a,gElement:v,yPosition:m,type:s,dots:i,dotsSize:r,height:d,barBorderRadius:u}),l&&this.drawTextLabel({color:a,label:l,type:s,gElement:v,yPosition:m,height:d})},drawBarEventsGroups(){Object.entries(this.barGroups).forEach(([s,e])=>this.drawSingleBarEventsGroup({type:s,eventsGroup:e,bottom:e.bottom,dots:e.chartType===Se.dots,dotsSize:e.dotsSize||3}))},drawMilestonesPlaceholder(){Object.entries(this.milestonesGroups).forEach(([s,e])=>this.drawSingleBarEventsGroup({type:s,eventsGroup:{...e,events:[],isLoading:!1},milestone:!0})),this.updateMilestonesPositions()},getMilestoneClass(s){return{[qe.milestoneSelected]:[s.id,s.timestamp].includes(this.selectedMilestoneId)}},getMilestoneColors(s,e){return{background:s||e,border:this.getTextFillColor(s||e,.25)}},getMilestoneGroupYPosition(s){let e=0;for(const[t,i]of Object.entries(this.milestonesGroups)){if(t===s)break;e+=i.height||this.barChartHeight}return this.combinedXAxesHeight+this.milestonesYOffset+e},getBarGroupYPosition(s,e){let t=this.combinedXAxesHeight;e?t+=(this.hasChart?this.chartHeight:0)+(this.hasMilestones?this.combinedMilestonesHeight:0):t+=this.barsYOffset;for(const[i,r]of Object.entries(this.barGroups)){if(i===s)break;!e&&r.bottom||(t+=this.getBarGroupHeight(r))}return t},getBarGroupHeight(s){return s.height?Math.max(s.height+this.barYPadding,1):this.barChartHeight},updateMilestonesPositions(){Object.entries(this.milestonesGroups).forEach(([s,e])=>{const t=this.getMilestoneGroupYPosition(s),i=this.svg.select(`g.${$.eventGroup}-${s}`),r=2,a=(e.height||this.barChartHeight)/2,o=t+a-r/2;i.attr("x1",0).attr("x2",this.timeline.offsetWidth).select(`.${qe.milestoneLine}`).attr("y1",o).attr("y2",o);const l=I.select(`.${qe.milestonesContainer}-${s}`);l.style("top",`${t}px`).style("height",`${e.height||this.barChartHeight}px`);const c=l.selectAll(`.${qe.milestone}`).data(this.getSortedEvents(e.events));c.exit().remove(),c.enter().append("div").merge(c).style("left",u=>`${this.timeScale(this.tzStringToDate(u.timestamp))}px`).style("top",`${o}px`)})},drawBarChartEventsGroups(){const s=this.combinedXAxesHeight,e=this.barChartGroups;Object.entries(e).forEach(([t,i],r)=>{const n=this.svg.append("g").classed(`${$.barChartGroup} ${$.barChartGroup}-${t}`,!0).attr("transform",`translate(0,${s})`),{color:a,events:o}=i;this.drawBarsChart({events:o,color:a,gElement:n,yOffset:s,type:t,index:r})})},drawProgressIndicator({yPosition:s,type:e,isLoading:t}){this.svg.append("rect").classed(`${$.loadingIndicator} ${$.loadingIndicator}-${e}`,!0).attr("x",0).attr("y",s).attr("width",this.timeline.offsetWidth/3).attr("height",this.barChartHeight).attr("fill",`url(#${Ue.loadingGradient}-${e})`).style("visibility",t?"visible":"hidden")},drawBackground({color:s,yPosition:e,gElement:t,height:i}){t.append("rect").attr("class",$.eventGroupBg).attr("x",0).attr("y",e).attr("width",this.timeline.offsetWidth).attr("height",i||this.barChartHeight).attr("fill",I.color(s).toString()).style("opacity",.1)},drawBars({events:s,gElement:e,yPosition:t,color:i,type:r,dots:n,dotsSize:a,height:o,barBorderRadius:l=1.5}){const c=this,u=t+this.barYPadding/2,h=n?((o||this.barChartHeight)-a)/2:0;let d=Math.max((o!=null?o:this.barChartHeight)-this.barYPadding,1);n&&(d=a),e.selectAll($.eventRect).data(s).enter().append("rect").attr("class",f=>$.eventRect+(n?` ${$.eventRect}--dot`:"")+(f.className?` ${f.className}`:"")).attr("x",this.getEventRectX).attr("y",u+h).attr("ry",n?a:l).attr("rx",n?a:l).attr("width",n?a:this.getEventRectWidth).attr("height",d).attr("stroke-width",5).attr("cursor","pointer").attr("stroke","#0000").style("fill",f=>f.color||i).on("mouseover",function(f,m){I.select(this).classed($.eventRectHovered,!0),c.handleBarMouseOver(f,m,r)}).on("mouseout",function(){I.select(this).classed($.eventRectHovered,!1),c.handleBarMouseOut()}),e.selectAll($.eventRectText).data(s.filter(f=>!!f.text)).enter().append("text").attr("class",$.eventRectText).attr("x",f=>this.getEventRectX(f)+this.textPadding).attr("y",t+this.barChartHeight/2).attr("dy","0.35em").style("text-anchor","start").style("font-size","12px").style("font-weight",600).style("stroke-linejoin","round").style("paint-order","stroke").style("pointer-events","none").style("fill",f=>this.getTextFillColor(f.color||i,.75)).text(this.getEventText)},drawBarsChart({events:s,gElement:e,color:t,yOffset:i,type:r,index:n}){const a=this,o=Object.keys(this.barChartGroups).length,l=f=>(this.getEventRectWidth(f)-this.barXPadding*2)/o,c=f=>this.yScale.range()[0]-this.yScale(f.count),u=f=>this.getEventRectX(f)+this.barXPadding+n*l(f),h=f=>this.yScale(f.count),d=e.selectAll($.eventBarContainer).data(s).enter().append("g").attr("class",`${$.eventBarContainer} ${$.eventBarContainer}-${r}`);d.append("rect").attr("class",f=>$.eventBarHoverZone+(f.className?` ${f.className}`:"")).attr("x",u).attr("y",-i).attr("width",l).attr("height",this.yScale.range()[0]+i).attr("fill",f=>f.color||t).attr("fill-opacity",0),d.append("rect").attr("class",f=>$.eventBar+(f.className?` ${f.className}`:"")).attr("x",u).attr("y",h).attr("width",l).attr("height",c).attr("stroke-width",5).attr("cursor","pointer").attr("stroke","#0000").attr("fill",`url(#${Ue.transparencyGradient}-${r})`),d.append("rect").attr("class",f=>$.eventBarCap+(f.className?` ${f.className}`:"")).attr("x",u).attr("y",h).attr("width",l).attr("height",2).attr("stroke-width",0).style("fill",f=>f.color||t),d.on("mouseover",function(f,m){const g=I.select(this);a.onBarChartBarMouseOver(g,t),a.handleBarMouseOver(f,m,r)}).on("mouseout",function(){const f=I.select(this);a.onBarChartBarMouseOut(f,r),a.handleBarMouseOut()}).on("click",function(){e.selectAll(`.${$.eventBarContainerSelected}`).classed($.eventBarContainerSelected,!1),I.select(this).classed($.eventBarContainerSelected,!0)})},onBarChartBarMouseOver(s,e){s.classed($.eventBarContainerHovered,!0),s.selectAll(`.${$.eventBarHoverZone}`).attr("fill-opacity",.2);const i=s.selectAll(`.${$.eventBar}`);i.attr("fill",e),i.attr("fill-opacity",.5)},onBarChartBarMouseOut(s,e){s.classed($.eventBarContainerHovered,!1),s.selectAll(`.${$.eventBarHoverZone}`).attr("fill-opacity",0);const i=s.selectAll(`.${$.eventBar}`);i.attr("fill",`url(#${Ue.transparencyGradient}-${e})`),i.attr("fill-opacity",1)},drawTextLabel({gElement:s,yPosition:e,color:t,label:i,type:r,height:n}){if(!this.showLabels)return;const a={x:-5,y:e,w:this.labelRectWidth,h:n||this.barChartHeight,radius:3},o=s.append("g").attr("class",`${$.labelGroup} ${$.labelGroup}-${r}`).style("cursor","pointer").on("click",()=>this.toggleGroupVisibility(r));o.append("rect").attr("class",$.labelBg).attr("data-color",t).attr("x",a.x).attr("y",a.y).attr("width",a.w).attr("height",a.h).attr("rx",a.radius).attr("ry",a.radius).style("fill",this.dark?"#131a29":"white"),o.append("rect").attr("class",$.labelBgFill).attr("data-color",t).attr("x",a.x).attr("y",a.y).attr("width",a.w).attr("height",a.h).attr("rx",a.radius).attr("ry",a.radius).style("fill",this.getLabelBackgroundColor(t)).style("stroke",this.getTextFillColor(t)).style("stroke-width",.25),o.append("text").attr("class",$.labelText).attr("data-color",t).attr("x",5).attr("y",e+(n||this.barChartHeight)/2).attr("dy","0.35em").style("text-anchor","start").style("font-size","12px").style("font-weight",500).style("stroke-linejoin","round").style("paint-order","stroke").style("fill",this.getTextFillColor(t)).text(i)},getTextFillColor(s,e=0){var t,i;return(this.dark?(t=I.color(s))==null?void 0:t.brighter(1.5+e):(i=I.color(s))==null?void 0:i.darker(2+e)).toString()},getLabelBackgroundColor(s){let e=I.color(s);return e.opacity=this.dark?.2:.5,e.toString()},getCurrentGroupVisibility(s){var i;const e=this.groupsVisibility[s];if(e!==void 0)return e;const t=(i=this.eventsGroups[s])==null?void 0:i.isHidden;return t!==void 0?!t:!0},toggleGroupVisibility(s){this.groupsVisibility={...this.groupsVisibility,[s]:!this.getCurrentGroupVisibility(s)}},getExternalLabelStyles(s){const e=this.eventsGroups[s].color;return{background:this.getLabelBackgroundColor(e),color:this.getTextFillColor(e)}},getExternalLabelWrapperStyles(s){const e=this.eventsGroups[s].color;return{borderColor:this.getTextFillColor(e)}},getMarkerClass(s){var e;return{"marker--hidden":(e=this.markersPositions[s==null?void 0:s.id])==null?void 0:e.isHidden,"marker--draggable":s==null?void 0:s.isDraggable,...s.className?{[s==null?void 0:s.className]:!0}:{}}},getMarkerContainerStyle(s){var e;return{left:`${(e=this.markersPositions[s.id])==null?void 0:e.position}px`}},getMarkerLabelStyle(s){return{background:s.color,color:s.textColor||""}},getMarkerLineStyle(s){return{background:s.color,height:`${this.timelineHeight+24}px`}},tzStringToDate(s){return We(s).add(this.utcOffset,"minutes").toDate()},dateToTzString(s){const e=new Date(s).getTimezoneOffset();return We(s).add(e,"minutes").utcOffset(this.utcOffset,!0).format()},getCurrentTimeBounds(){const s=this.timeScale.domain();return{startDate:s[0],endDate:s[1]}},getFormattedTimestamp(s){return We.parseZone(s).format("YYYY-MM-DDTHH:mm:ss")},fillTimeGaps(s){if(s.length<=1)return s;const e=this.insertZerosAtInterval,t=n=>n.clone().add(1,e),i=n=>n.clone().subtract(1,e);let r=[];for(let n=0;n<s.length;n++){const a=s[n];if(r.push(a),n===s.length-1)break;const o=s[n+1],l=We(a.timestamp),c=We(o.timestamp);if(c.diff(l,e)>1){const u=t(l).toISOString(),h=i(c).toISOString();r.push({timestamp:u,count:0}),u!==h&&r.push({timestamp:h,count:0})}}if(this.flattenLineGraphEnds){const n=We(s[0].timestamp),a=We(s[s.length-1].timestamp),o=i(n).toISOString(),l=t(a).toISOString();r=[{timestamp:o,count:0},...r,{timestamp:l,count:0}]}return r},fillEvents(s){return this.placeholderLineChartGroup.map(e=>s.find(i=>i.timestamp===e.timestamp)||e)},onMilestoneClick(s,e){this.panOnDateClick&&this.panToTimestamp(s.timestamp),this.selectedMilestoneId=s.id||s.timestamp,this.$emit("milestone-click",{milestone:s,milestoneType:e})},getSortedEvents(s){return[...s].sort((e,t)=>new Date(e.timestamp||e.startDate)>new Date(t.timestamp||t.startDate)?1:-1)}}}),ed="";var Uh=function(){var e=this,t=e._self._c;return t("div",{ref:"wrapperDiv",staticClass:"e-relative e-timeline e-border e-rounded",class:e.classes.wrapper},[t("div",{staticClass:"e-timeline__background e-w-full e-h-full e-absolute e-top-0 e-rounded",class:e.classes.background}),e._l(e.sortedMarkers,function(i){return t("div",{key:i.id,staticClass:"marker e-absolute e-h-full e-top-0",class:e.getMarkerClass(i),style:e.getMarkerContainerStyle(i),attrs:{"data-id":i.id},on:{click:function(r){return e.handleMarkerClick(i)}}},[t("div",{staticClass:"marker-label e-absolute"},[t("div",{staticClass:"marker-label-text",style:e.getMarkerLabelStyle(i)},[e._t(`marker.${i.id}`,function(){return[e._v(" "+e._s(i.label)+" ")]},{marker:i})],2)]),t("div",{staticClass:"marker-line e-absolute e-pointer-events-none",style:e.getMarkerLineStyle(i)})])}),e.autoResize?t("div",{directives:[{name:"resize-observer",rawName:"v-resize-observer",value:e.onResize,expression:"onResize"}],ref:"timelineContainer",staticClass:"e-timeline__svg-container e-relative e-h-13 e-rounded e-select-none e-overflow-x-hidden"}):t("div",{ref:"timelineContainer",staticClass:"e-timeline__svg-container e-relative e-h-13 e-rounded e-select-none e-overflow-x-hidden"}),e._l(e.milestonesGroups,function(i,r){return t("div",{key:`${r}`,staticClass:"e-timeline-milestones"},[t("div",{class:`e-tl-milestones e-tl-milestones-${r}`},e._l(e.getSortedEvents(i.events),function(n,a){return t("ETimelineMilestone",{key:`${n.milestoneType}-${a}`,class:e.getMilestoneClass(n),attrs:{"data-timestamp":n.timestamp,milestone:n,dot:i.dots,size:n.size||e.milestoneBulletSize,"transition-duration":i.milestonesTransitionDuration,"line-height":i.milestonesLineHeight,"dot-size":i.milestonesDotSize,"background-color":e.getMilestoneColors(n.color,i.color).background,"border-color":e.getMilestoneColors(n.color,i.color).border},on:{"milestone-click":function(o){return e.onMilestoneClick(n,r)}},scopedSlots:e._u([{key:"content",fn:function(){return[e._t(`milestoneContent.${n.milestoneType}`,function(){return[t("span",{staticClass:"e-px-2"},[e._v(" "+e._s(n.text)+" ")])]},{milestone:n,index:a})]},proxy:!0},{key:"label",fn:function(){return[e._t(`milestoneLabel.${n.milestoneType}`,null,{milestone:n})]},proxy:!0}],null,!0)})}),1)])}),t("div",{directives:[{name:"show",rawName:"v-show",value:e.isHoveringTimeline&&!e.isInteractingWithCurtain,expression:"isHoveringTimeline && !isInteractingWithCurtain"}],ref:"cursor",staticClass:"e-timeline__cursor e-absolute e-bg-green-600 e-w-px e-h-full e-top-0 e-pointer-events-none"}),t("div",{staticClass:"external-labels-container e-flex"},e._l(e.hiddenGroupsLabels,function(i){return t("div",{key:i,staticClass:"external-label",class:e.classes.background,style:e.getExternalLabelWrapperStyles(i),on:{click:function(r){return e.toggleGroupVisibility(i)}}},[t("div",{staticClass:"external-label__content",style:e.getExternalLabelStyles(i)},[e._v(" "+e._s(i)+" ")])])}),0),t("div",{key:"tooltip",ref:"tooltip",staticClass:"e-absolute",style:e.eventTooltipStyle},[e._t("tooltip",function(){return[t("div",{directives:[{name:"show",rawName:"v-show",value:e.isHoveringTimeline&&!e.isHoveringEvent&&!e.isInteractingWithCurtain&&!e.cursorTimestamp,expression:`
26
+ } (data length: ${t&&t.byteLength})`),r.update(t)}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){return new Promise((t,i)=>{const r=Ei(this.config),n=e.map(tr).filter(a=>!!a&&r.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:a})=>{const o=sr(a);o?t(o):i(new Error(`Unable to find format for key-system "${a}"`))}).catch(i)})}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let n=this.keyIdToKeySessionPromise[i];return n||(n=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:t}),c="cenc";return this.generateRequestWithPreferredKeySession(l,c,t.pssh,"playlist-key")}))),n.catch(a=>this.handleError(a))),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Le?this.hls.trigger(p.ERROR,e.data):this.hls.trigger(p.ERROR,{type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const r=tr(e.keyFormat),n=r?[r]:Ei(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Ei(this.config)),e.length===0)throw new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:i}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),i===null)return;let r,n;if(t==="sinf"&&this.config.drmSystems[ne.FAIRPLAY]){const u=ce(new Uint8Array(i));try{const h=xi(JSON.parse(u).sinf),d=fr(new Uint8Array(h));if(!d)return;r=d.subarray(8,24),n=ne.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{const u=il(i);if(u===null)return;u.version===0&&u.systemId===ir.WIDEVINE&&u.data&&(r=u.data.subarray(8,24)),n=Io(u.systemId)}if(!n||!r)return;const a=Pe.hexDump(r),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this;let c=o[a];for(let u=0;u<l.length;u++){const h=l[u],d=h.decryptdata;if(d.pssh||!d.keyId)continue;const f=Pe.hexDump(d.keyId);if(a===f||d.uri.replace(/-/g,"").indexOf(a)!==-1){c=o[f],delete o[f],d.pssh=new Uint8Array(i),d.keyId=r,c=o[a]=c.then(()=>this.generateRequestWithPreferredKeySession(h,t,i,"encrypted-event-key-match"));break}}c||(c=o[a]=this.getKeySystemSelectionPromise([n]).then(({keySystem:u,mediaKeys:h})=>{var d;this.throwIfDestroyed();const f=new vt("ISO-23001-7",a,(d=sr(u))!=null?d:"");return f.pssh=new Uint8Array(i),f.keyId=r,this.attemptSetMediaKeys(u,h).then(()=>{this.throwIfDestroyed();const m=this.createMediaKeySessionContext({decryptdata:f,keySystem:u,mediaKeys:h});return this.generateRequestWithPreferredKeySession(m,t,i,"encrypted-event-no-match")})})),c.catch(u=>this.handleError(u))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const r=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,i,r){var n,a;const o=(n=this.config.drmSystems)==null||(a=n[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const m=o.call(this.hls,t,i,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,i=e.decryptdata.pssh=m.initData?new Uint8Array(m.initData):null}catch(m){var l;if(this.warn(m.message),(l=this.hls)!=null&&l.config.debug)throw m}if(i===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);const c=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${c} (init data type: ${t} length: ${i?i.byteLength:null})`);const u=new Zi,h=e._onmessage=m=>{const g=e.mediaKeysSession;if(!g){u.emit("error",new Error("invalid state"));return}const{messageType:y,message:v}=m;this.log(`"${y}" message event for session "${g.sessionId}" message size: ${v.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,v).catch(T=>{this.handleError(T),u.emit("error",T)}):y==="license-release"?e.keySystem===ne.FAIRPLAY&&(this.updateKeySession(e,Ti("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${y}"`)},d=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){u.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const y=e.keyStatus;u.emit("keyStatus",y),y==="expired"&&(this.warn(`${e.keySystem} expired for key ${c}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",h),e.mediaKeysSession.addEventListener("keystatuseschange",d);const f=new Promise((m,g)=>{u.on("error",g),u.on("keyStatus",y=>{y.startsWith("usable")?m():y==="output-restricted"?g(new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):y==="internal-error"?g(new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${y}"`)):y==="expired"?g(new Error("key expired while generating request")):this.warn(`unhandled key status change "${y}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var m;this.log(`Request generated for key-session "${(m=e.mediaKeysSession)==null?void 0:m.sessionId}" keyId: ${c}`)}).catch(m=>{throw new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_SESSION,error:m,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>{throw u.removeAllListeners(),this.removeSession(e),m}).then(()=>(u.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${Pe.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${Pe.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,i=t.loader,r=new i(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:n},c=t.certLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,f,m,g)=>{a(d.data)},onError:(d,f,m,g)=>{o(new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:he({url:l.url,data:void 0},d)},`"${e}" certificate request failed (${n}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,m)=>{o(new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(d,f,m)=>{o(new Error("aborted"))}};r.load(l,u,h)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((r,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),r(e)}).catch(a=>{n(new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(r=>{throw new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:r,fatal:!0},r.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const r=new DOMParser().parseFromString(i,"application/xml"),n=r.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,m=(o=u.querySelector("value"))==null?void 0:o.textContent;f&&m&&e.setRequestHeader(f,m)}}const l=r.querySelector("Challenge"),c=l==null?void 0:l.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return Ti(atob(c))}setupLicenseXHR(e,t,i,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,r)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,i,r)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{const a=this.getLicenseServerUrl(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 l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,a,e)}catch(u){this.error(u)}r(l)}else{const l=i.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)n(new Le({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_LICENSE_REQUEST_FAILED,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=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(r,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:c})=>{e.keySystem==ne.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(l,c)),l.send(c)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},vt.clearKeyUriToKeyIdMap();const i=t.length;dt.CDMCleanupPromise=Promise.all(t.map(r=>this.removeSession(r)).concat(e==null?void 0:e.setMediaKeys(null).catch(r=>{this.log(`Could not clear media keys: ${r}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(r=>{this.log(`Could not close sessions and clear media keys: ${r}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch(n=>{this.log(`Could not remove session: ${n}`)}).then(()=>t.close()).catch(n=>{this.log(`Could not close session: ${n}`)})}}}dt.CDMCleanupPromise=void 0;class Le 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}}var ve;(function(s){s.MANIFEST="m",s.AUDIO="a",s.VIDEO="v",s.MUXED="av",s.INIT="i",s.CAPTION="c",s.TIMED_TEXT="tt",s.KEY="k",s.OTHER="o"})(ve||(ve={}));var us;(function(s){s.DASH="d",s.HLS="h",s.SMOOTH="s",s.OTHER="o"})(us||(us={}));var Je;(function(s){s.OBJECT="CMCD-Object",s.REQUEST="CMCD-Request",s.SESSION="CMCD-Session",s.STATUS="CMCD-Status"})(Je||(Je={}));const Eu={[Je.OBJECT]:["br","d","ot","tb"],[Je.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Je.SESSION]:["cid","pr","sf","sid","st","v"],[Je.STATUS]:["bs","rtp"]};class ft{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(i=>i instanceof ft?i:new ft(i))),this.value=e,this.params=t}}class jn{constructor(e){this.description=void 0,this.description=e}}const Su="Dict";function bu(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function Au(s,e,t,i){return new Error(`failed to ${s} "${bu(e)}" as ${t}`,{cause:i})}const qn="Bare Item",Lu="Boolean",Ru="Byte Sequence",Cu="Decimal",Du="Integer";function _u(s){return s<-999999999999999||999999999999999<s}const Iu=/[\x00-\x1f\x7f]+/,wu="Token",ku="Key";function Be(s,e,t){return Au("serialize",s,e,t)}function Pu(s){if(typeof s!="boolean")throw Be(s,Lu);return s?"?1":"?0"}function Ou(s){return btoa(String.fromCharCode(...s))}function Fu(s){if(ArrayBuffer.isView(s)===!1)throw Be(s,Ru);return`:${Ou(s)}:`}function Xn(s){if(_u(s))throw Be(s,Du);return s.toString()}function Mu(s){return`@${Xn(s.getTime()/1e3)}`}function Zn(s,e){if(s<0)return-Zn(-s,e);const t=Math.pow(10,e);if(Math.abs(s*t%1-.5)<Number.EPSILON){const r=Math.floor(s*t);return(r%2===0?r:r+1)/t}else return Math.round(s*t)/t}function Nu(s){const e=Zn(s,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Be(s,Cu);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Bu="String";function $u(s){if(Iu.test(s))throw Be(s,Bu);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Uu(s){return s.description||s.toString().slice(7,-1)}function Qn(s){const e=Uu(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Be(e,wu);return e}function hs(s){switch(typeof s){case"number":if(!W(s))throw Be(s,qn);return Number.isInteger(s)?Xn(s):Nu(s);case"string":return $u(s);case"symbol":return Qn(s);case"boolean":return Pu(s);case"object":if(s instanceof Date)return Mu(s);if(s instanceof Uint8Array)return Fu(s);if(s instanceof jn)return Qn(s);default:throw Be(s,qn)}}function ds(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Be(s,ku);return s}function fs(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${ds(e)}`:`;${ds(e)}=${hs(t)}`).join("")}function Jn(s){return s instanceof ft?`${hs(s.value)}${fs(s.params)}`:hs(s)}function Gu(s){return`(${s.value.map(Jn).join(" ")})${fs(s.params)}`}function Hu(s,e={whitespace:!0}){if(typeof s!="object")throw Be(s,Su);const t=s instanceof Map?s.entries():Object.entries(s),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof ft||(n=new ft(n));let a=ds(r);return n.value===!0?a+=fs(n.params):(a+="=",Array.isArray(n.value)?a+=Gu(n):a+=Jn(n)),a}).join(`,${i}`)}function Vu(s,e){return Hu(s,e)}const Ku=s=>s==="ot"||s==="sf"||s==="st",Wu=s=>typeof s=="number"?W(s):s!=null&&s!==""&&s!==!1;function zu(s,e){const t=new URL(s),i=new URL(e);if(t.origin!==i.origin)return s;const r=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")}function Yu(){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,r=>{const n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(r=="x"?n:n&3|8).toString(16)})}}}const ei=s=>Math.round(s),ju=(s,e)=>(e!=null&&e.baseUrl&&(s=zu(s,e.baseUrl)),encodeURIComponent(s)),ti=s=>ei(s/100)*100,qu={br:ei,d:ei,bl:ti,dl:ti,mtp:ti,nor:ju,rtp:ti,tb:ei};function Xu(s,e){const t={};if(s==null||typeof s!="object")return t;const i=Object.keys(s).sort(),r=oe({},qu,e==null?void 0:e.formatters),n=e==null?void 0:e.filter;return i.forEach(a=>{if(n!=null&&n(a))return;let o=s[a];const l=r[a];l&&(o=l(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||Wu(o)&&(Ku(a)&&typeof o=="string"&&(o=new jn(o)),t[a]=o))}),t}function ea(s,e={}){return s?Vu(Xu(s,e),oe({whitespace:!1},e)):""}function Zu(s,e={}){if(!s)return{};const t=Object.entries(s),i=Object.entries(Eu).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),r=t.reduce((n,a)=>{var o,l;const[c,u]=a,h=((o=i.find(d=>d[1].includes(c)))==null?void 0:o[0])||Je.REQUEST;return(l=n[h])!=null||(n[h]={}),n[h][c]=u,n},{});return Object.entries(r).reduce((n,[a,o])=>(n[a]=ea(o,e),n),{})}function Qu(s,e,t){return oe(s,Zu(e,t))}const Ju="CMCD";function eh(s,e={}){if(!s)return"";const t=ea(s,e);return`${Ju}=${encodeURIComponent(t)}`}const ta=/CMCD=[^&#]+/;function th(s,e,t){const i=eh(e,t);if(!i)return s;if(ta.test(s))return s.replace(ta,i);const r=s.includes("?")?"&":"?";return`${s}${r}${i}`}class ih{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=r=>{try{this.apply(r,{ot:ve.MANIFEST,su:!this.initialized})}catch(n){S.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=r=>{try{const n=r.frag,a=this.hls.levels[n.level],o=this.getObjectType(n),l={d:n.duration*1e3,ot:o};(o===ve.VIDEO||o===ve.AUDIO||o==ve.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(r,l)}catch(n){S.warn("Could not generate segment CMCD data.",n)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||Yu(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=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 i,r;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(r=t.tracks.video)==null?void 0:r.buffer}createData(){var e;return{v:1,sf:us.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 i=t.ot===ve.INIT||t.ot===ve.VIDEO||t.ot===ve.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((n,a)=>(r.includes(a)&&(n[a]=t[a]),n),{})),this.useHeaders?(e.headers||(e.headers={}),Qu(e.headers,t)):e.url=th(e.url,t)}getObjectType(e){const{type:t}=e;if(t==="subtitle")return ve.TIMED_TEXT;if(e.sn==="initSegment")return ve.INIT;if(t==="audio")return ve.AUDIO;if(t==="main")return this.hls.audioTracks.length?ve.VIDEO:ve.MUXED}getTopBandwidth(e){let t=0,i;const r=this.hls;if(e===ve.AUDIO)i=r.audioTracks;else{const n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;i=r.levels.slice(0,a)}for(const n of i)n.bitrate>t&&(t=n.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.hls.media,i=e===ve.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:se.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(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,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(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 sh=3e5;class rh{constructor(e){this.hls=void 0,this.log=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.log=S.log.bind(S,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this))}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(i=>i!==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:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((i==null?void 0:i.action)===ge.SendAlternateToPenaltyBox&&i.flags===De.MoveAllAlternatesMatchingHost){const r=this.levels;let n=this.pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:c}=t.context;o&&r?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&r&&(n=r.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),i.resolved||S.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${r&&r.length} priorities: ${JSON.stringify(n)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t;const i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(n=>{r-i[n]>sh&&delete i[n]});for(let n=0;n<e.length;n++){const a=e[n];if(a in i)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,Hr(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){const r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===ee.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===ee.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},r={};e.forEach(n=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(u=>u.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(u=>{const h=new ae(u.attrs);h["PATHWAY-ID"]=a;const d=h.AUDIO&&`${h.AUDIO}_clone_${a}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;d&&(i[h.AUDIO]=d,h.AUDIO=d),f&&(r[h.SUBTITLES]=f,h.SUBTITLES=f);const m=sa(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new st({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:m,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let y=1;y<u.audioGroups.length;y++)g.addGroupId("audio",`${u.audioGroups[y]}_clone_${a}`);if(u.subtitleGroups)for(let y=1;y<u.subtitleGroups.length;y++)g.addGroupId("text",`${u.subtitleGroups[y]}_clone_${a}`);return g});t.push(...c),ia(this.audioTracks,i,l,a),ia(this.subtitleTracks,r,l,a)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+u)}const n={responseType:"json",url:r.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(u,h,d,f)=>{this.log(`Loaded steering manifest: "${r}"`);const m=u.data;if(m.VERSION!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;const{"RELOAD-URI":g,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":v}=m;if(g)try{this.uri=new self.URL(g,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||d.url),y&&this.clonePathways(y);const T={steeringManifest:m,url:r.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,T),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 m=this.timeToLoad*1e3;if(u.code===429){const g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){const y=g.getResponseHeader("Retry-After");y&&(m=parseFloat(y)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,m)},onTimeout:(u,h,d)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const r=(i=this.hls)==null?void 0:i.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function ia(s,e,t,i){s&&Object.keys(e).forEach(r=>{const n=s.filter(a=>a.groupId===r).map(a=>{const o=oe({},a);return o.details=void 0,o.attrs=new ae(o.attrs),o.url=o.attrs.URI=sa(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=i,o});s.push(...n)})}function sa(s,e,t,i){const{HOST:r,PARAMS:n,[t]:a}=i;let o;e&&(o=a==null?void 0:a[e],o&&(s=o));const l=new self.URL(s);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(c=>{c&&l.searchParams.set(c,n[c])}),l.href}const nh=/^age:\s*[\d.]+\s*$/im;class ra{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 Dt,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null,this.stats=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,i){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=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!this.stats.aborted)return n(i,t.url)}).catch(a=>(i.open("GET",t.url,!0),n(i,t.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{this.callbacks.onError({code:i.status,text:a.message},t,i,r)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(r)for(const o in r)e.setRequestHeader(o,r[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),i.timeout=n&&W(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const r=t.readyState,n=this.config;if(!i.aborted&&r>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.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-(i.loading.first-i.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const a=t.status,o=t.responseType!=="text";if(a>=200&&a<300&&(o&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=o?t.response:t.responseText,c=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=c,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;const u=this.callbacks.onProgress;if(u&&u(i,e,l,t),!this.callbacks)return;const h={url:t.responseURL,data:l,code:a};this.callbacks.onSuccess(h,i,e,t)}else{const l=n.loadPolicy.errorRetry,c=i.retry,u={url:e.url,data:void 0,code:a};Ut(l,c,!1,u)?this.retry(l):(S.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:t.statusText},e,t,i))}}}loadtimeout(){var e;const t=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,i=this.stats.retry;if(Ut(t,i,!0))this.retry(t);else{var r;S.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Ni(e,i.retry),i.retry++,S.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${i.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&&nh.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}}function ah(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const oh=/(\d+)-(\d+)\/(\d+)/;class na{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||hh,this.controller=new self.AbortController,this.stats=new Dt}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,i){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const n=lh(e,this.controller.signal),a=i.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:u}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=c&&W(c)?c:u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response)},t.timeout),self.fetch(this.request).then(h=>{this.response=this.loader=h;const d=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response)},u-(d-r.loading.start)),!h.ok){const{status:f,statusText:m}=h;throw new dh(m||"fetch, bad network response",f,h)}return r.loading.first=d,r.total=uh(h.headers)||r.total,a&&W(t.highWaterMark)?this.loadProgressively(h,r,e,t.highWaterMark,a):o?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{const d=this.response;if(!d)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const f=h[l];f&&(r.loaded=r.total=f);const m={url:d.url,data:h,code:d.status};a&&!W(t.highWaterMark)&&a(r,e,h,d),i.onSuccess(m,r,e,d)}).catch(h=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const d=h&&h.code||0,f=h?h.message:null;i.onError({code:d,text:f},e,h?h.details:null,r)})}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,i,r=0,n){const a=new en,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&n(t,i,a.flush(),e),Promise.resolve(new ArrayBuffer(0));const u=c.value,h=u.length;return t.loaded+=h,h<r||a.dataLength?(a.push(u),a.dataLength>=r&&n(t,i,a.flush(),e)):n(t,i,u,e),l()}).catch(()=>Promise.reject());return l()}}function lh(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(oe({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function ch(s){const e=oh.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function uh(s){const e=s.get("Content-Range");if(e){const i=ch(e);if(W(i))return i}const t=s.get("Content-Length");if(t)return parseInt(t)}function hh(s,e){return new self.Request(s.url,e)}class dh extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const fh=/\s/,mh={newCue(s,e,t,i){const r=[];let n,a,o,l,c;const u=self.VTTCue||self.TextTrackCue;for(let d=0;d<i.rows.length;d++)if(n=i.rows[d],o=!0,l=0,c="",!n.isEmpty()){var h;for(let g=0;g<n.chars.length;g++)fh.test(n.chars[g].uchar)&&o?l++:(c+=n.chars[g].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=Bn(c.trim()),m=rs(e,t,f);s!=null&&(h=s.cues)!=null&&h.getCueById(m)||(a=new u(e,t,f),a.id=m,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a))}return s&&r.length&&(r.sort((d,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),r.forEach(d=>Or(s,d))),r}},gh={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},aa=he(he({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,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,loader:ra,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Wl,bufferController:qc,capLevelController:cs,errorController:Pl,fpsController:Tu,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:rr,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:gh},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}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},ph()),{},{subtitleStreamController:Wc,subtitleTrackController:Yc,timelineController:vu,audioStreamController:Vc,audioTrackController:Kc,emeController:dt,cmcdController:ih,contentSteeringController:rh});function ph(){return{cueHandler:mh,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 yh(s,e){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 t=ms(s),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{const a=`${n==="level"?"playlist":n}LoadPolicy`,o=e[a]===void 0,l=[];r.forEach(c=>{const u=`${n}Loading${c}`,h=e[u];if(h!==void 0&&o){l.push(u);const d=t[a].default;switch(e[a]={default:d},c){case"TimeOut":d.maxLoadTimeMs=h,d.maxTimeToFirstByteMs=h;break;case"MaxRetry":d.errorRetry.maxNumRetry=h,d.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":d.errorRetry.retryDelayMs=h,d.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":d.errorRetry.maxRetryDelayMs=h,d.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&S.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`)}),he(he({},t),e)}function ms(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(ms):Object.keys(s).reduce((e,t)=>(e[t]=ms(s[t]),e),{}):s}function vh(s){const e=s.loader;e!==na&&e!==ra?(S.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):ah()&&(s.loader=na,s.progressive=!0,s.enableSoftwareAES=!0,S.log("[config]: Progressive streaming enabled, using FetchLoader"))}let gs;class xh extends $i{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(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.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 i=this.hls.config.preferManagedMediaSource,r=[],n={},a={};let o=!1,l=!1,c=!1;t.levels.forEach(u=>{var h,d;const f=u.attrs;let{audioCodec:m,videoCodec:g}=u;((h=m)==null?void 0:h.indexOf("mp4a.40.34"))!==-1&&(gs||(gs=/chrome|firefox/i.test(navigator.userAgent)),gs&&(u.audioCodec=m=void 0)),m&&(u.audioCodec=m=Ft(m,i)),((d=g)==null?void 0:d.indexOf("avc1"))===0&&(g=u.videoCodec=ll(g));const{width:y,height:v,unknownCodecs:T}=u;if(o||(o=!!(y&&v)),l||(l=!!g),c||(c=!!m),T!=null&&T.length||m&&!Di(m,"audio",i)||g&&!Di(g,"video",i))return;const{CODECS:x,"FRAME-RATE":L,"HDCP-LEVEL":E,"PATHWAY-ID":k,RESOLUTION:R,"VIDEO-RANGE":B}=f,b=`${`${k||"."}-`}${u.bitrate}-${R}-${L}-${x}-${B}-${E}`;if(n[b])if(n[b].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const D=a[b]+=1;u.attrs["PATHWAY-ID"]=new Array(D+1).join(".");const P=new st(u);n[b]=P,r.push(P)}else n[b].addGroupId("audio",f.AUDIO),n[b].addGroupId("text",f.SUBTITLES);else{const D=new st(u);n[b]=D,a[b]=1,r.push(D)}}),this.filterAndSortMediaOptions(r,t,o,l,c)}filterAndSortMediaOptions(e,t,i,r,n){let a=[],o=[],l=e;if((i||r)&&n&&(l=l.filter(({videoCodec:m,videoRange:g,width:y,height:v})=>(!!m||!!(y&&v))&&El(g))),l.length===0){Promise.resolve().then(()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);const m=new Error("no level with compatible codecs found in manifest");this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:m,reason:m.message})}});return}if(t.audioTracks){const{preferManagedMediaSource:m}=this.hls.config;a=t.audioTracks.filter(g=>!g.audioCodec||Di(g.audioCodec,"audio",m)),oa(a)}t.subtitles&&(o=t.subtitles,oa(o));const c=l.slice(0);l.sort((m,g)=>{if(m.attrs["HDCP-LEVEL"]!==g.attrs["HDCP-LEVEL"])return(m.attrs["HDCP-LEVEL"]||"")>(g.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&m.height!==g.height)return m.height-g.height;if(m.frameRate!==g.frameRate)return m.frameRate-g.frameRate;if(m.videoRange!==g.videoRange)return Bt.indexOf(m.videoRange)-Bt.indexOf(g.videoRange);if(m.videoCodec!==g.videoCodec){const y=Er(m.videoCodec),v=Er(g.videoCodec);if(y!==v)return v-y}if(m.uri===g.uri&&m.codecSet!==g.codecSet){const y=Ot(m.codecSet),v=Ot(g.codecSet);if(y!==v)return v-y}return m.averageBitrate!==g.averageBitrate?m.averageBitrate-g.averageBitrate:0});let u=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let m=0;m<c.length;m++)if(c[m].pathwayId===l[0].pathwayId){u=c[m];break}}this._levels=l;for(let m=0;m<l.length;m++)if(l[m]===u){var h;this._firstLevel=m;const g=u.bitrate,y=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${g}`),((h=this.hls.userConfig)==null?void 0:h.abrEwmaDefaultEstimate)===void 0){const v=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);v>y&&y===aa.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=v)}break}const d=n&&!r,f={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:!d&&a.some(m=>!!m.url)};this.hls.trigger(p.MANIFEST_PARSED,f),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}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(p.ERROR,{type:q.OTHER_ERROR,details:_.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:u,reason:u.message}),h)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,r=this.currentLevel,n=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&a.details&&r&&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 ${i}${n?" with Pathway "+n:""}`);const l={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(p.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const u=this.switchParams(a.uri,r==null?void 0:r.details);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}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===j.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;const r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(e,t){var i;const{level:r,details:n}=t,a=this._levels[r];if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}r===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(r,t,a.details)):(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let r=i.uri;if(e)try{r=e.addDirectives(r)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}const n=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${n?" Pathway "+n:""} ${r}`),this.clearTimer(),this.hls.trigger(p.LEVEL_LOADING,{url:r,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||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;const i=this._levels.filter((r,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(a=>a.level=-1)),!1));Hr(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(p.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function oa(s){const e={};s.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}class Th{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[i].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=_.KEY_LOAD_ERROR,i,r,n){return new Ge({type:q.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:r}=e;for(let n=0;n<t.length;n++){const a=t[n];if(r<=a.cc&&(i==="initSegment"||a.sn==="initSegment"||i<a.sn)){this.emeController.selectKeySystemFormat(a).then(o=>{a.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,c))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return n.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((r=o)!=null&&r.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(c=>(n.key=c.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const r=this.emeController.loadKey(i);if(r)return(e.keyLoadPromise=r.then(n=>(e.mediaKeySessionContext=n,i))).catch(n=>{throw e.keyLoadPromise=null,n})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,r=i.loader,n=new r(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=i.keyLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,f,m,g)=>{const{frag:y,keyInfo:v,url:T}=m;if(!y.decryptdata||v!==this.keyUriToKeyInfo[T])return o(this.createKeyLoadError(y,_.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));v.decryptdata.key=y.decryptdata.key=new Uint8Array(d.data),y.keyLoader=null,v.loader=null,a({frag:y,keyInfo:v})},onError:(d,f,m,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,_.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),m,he({url:l.url,data:void 0},d)))},onTimeout:(d,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,_.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(d,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,_.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};n.load(l,u,h)})}resetLoader(e){const{frag:t,keyInfo:i,url:r}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],n&&n.destroy()}}function la(){return self.SourceBuffer||self.WebKitSourceBuffer}function ca(){if(!tt())return!1;const e=la();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Eh(){if(!ca())return!1;const s=tt();return typeof(s==null?void 0:s.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(xt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(xt(e,"audio"))))}function Sh(){var s;const e=la();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}const bh=250,ii=2,Ah=.1,Lh=.05;class Rh{constructor(e,t,i,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:i,media:r,stalled:n}=this;if(r===null)return;const{currentTime:a,seeking:o}=r,l=this.seeking&&!o,c=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,o||(this.nudgeRetry=0),n!==null){if(this.stallReported){const y=self.performance.now()-n;S.warn(`playback not stuck anymore @${a}, after ${Math.round(y)}ms`),this.stallReported=!1}this.stalled=null}return}if(c||l){this.stalled=null;return}if(r.paused&&!o||r.ended||r.playbackRate===0||!se.getBuffered(r).length){this.nudgeRetry=0;return}const u=se.bufferInfo(r,a,0),h=u.nextStart||0;if(o){const y=u.len>ii,v=!h||t&&t.start<=a||h-a>ii&&!this.fragmentTracker.getPartialFragment(a);if(y||v)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var d;if(!(u.len>0)&&!h)return;const v=Math.max(h,u.start||0)-a,T=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,L=(T==null||(d=T.details)==null?void 0:d.live)?T.details.targetduration*2:ii,E=this.fragmentTracker.getPartialFragment(a);if(v>0&&(v<=L||E)){r.paused||this._trySkipBufferHole(E);return}}const f=self.performance.now();if(n===null){this.stalled=f;return}const m=f-n;if(!o&&m>=bh&&(this._reportStall(u),!this.media))return;const g=se.bufferInfo(r,a,i.maxBufferHole);this._tryFixBufferStall(g,m)}_tryFixBufferStall(e,t){const{config:i,fragmentTracker:r,media:n}=this;if(n===null)return;const a=n.currentTime,o=r.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-a<i.maxBufferHole)&&t>i.highBufferWatchdogPeriod*1e3&&(S.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:i,stallReported:r}=this;if(!r&&i){this.stallReported=!0;const n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);S.warn(n.message),t.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:i,media:r}=this;if(r===null)return 0;const n=r.currentTime,a=se.bufferInfo(r,n,0),o=n<a.start?a.start:a.nextStart;if(o){const l=a.len<=t.maxBufferHole,c=a.len>0&&a.len<1&&r.readyState<3,u=o-n;if(u>0&&(l||c)){if(u>t.maxBufferHole){const{fragmentTracker:d}=this;let f=!1;if(n===0){const m=d.getAppendedFrag(0,j.MAIN);m&&o<m.end&&(f=!0)}if(!f){const m=e||d.getAppendedFrag(n,j.MAIN);if(m){let g=!1,y=m.end;for(;y<o;){const v=d.getPartialFragment(y);if(v)y+=v.duration;else{g=!0;break}}if(g)return 0}}}const h=Math.max(o+Lh,n+Ah);if(S.warn(`skipping hole, adjusting currentTime from ${n} to ${h}`),this.moved=!0,this.stalled=null,r.currentTime=h,e&&!e.gap){const d=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${h}`);i.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:e})}return h}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:i,nudgeRetry:r}=this;if(i===null)return;const n=i.currentTime;if(this.nudgeRetry++,r<e.nudgeMaxRetry){const a=n+(r+1)*e.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);S.warn(o.message),i.currentTime=a,t.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const a=new Error(`Playhead still not moving while enough data buffered @${n} after ${e.nudgeMaxRetry} nudges`);S.error(a.message),t.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,error:a,fatal:!0})}}}const Ch=100;class Dh extends Hi{constructor(e,t,i){super(e,t,i,"[stream-controller]",j.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(p.ERROR,this.onError,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(p.ERROR,this.onError,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:i}=this;if(this.stopLoad(),this.setInterval(Ch),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=M.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=M.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case M.WAITING_LEVEL:{const{levels:t,level:i}=this,r=t==null?void 0:t[i],n=r==null?void 0:r.details;if(n&&(!n.live||this.levelLastLoaded===r)){if(this.waitForCdnTuneIn(n))break;this.state=M.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=M.IDLE;break}break}case M.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){const{levels:r,level:n}=this,a=r==null?void 0:r[n];this.resetStartWhenNotLoaded(a||null),this.state=M.IDLE}}break}this.state===M.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(t===null||!r&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const n=e.nextLoadLevel;if(!(i!=null&&i[n]))return;const a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const g={};this.altAudio&&(g.type="video"),this.hls.trigger(p.BUFFER_EOS,g),this.state=M.ENDED;return}e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;const c=a.details;if(!c||this.state===M.WAITING_LEVEL||c.live&&this.levelLastLoaded!==a){this.level=n,this.state=M.WAITING_LEVEL;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,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&f.sn!=="initSegment"&&this.fragmentTracker.getState(f)!==de.OK){var m;const y=((m=this.backtrackFragment)!=null?m:f).sn-c.startSN,v=c.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?te.AUDIO:te.VIDEO,v=(y===te.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,y,j.MAIN)}f=this.getNextFragmentLoopLoading(f,c,o,j.MAIN,h)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,d))}loadFragment(e,t,i){const r=this.fragmentTracker.getState(e);this.fragCurrent=e,r===de.NOT_LOADED||r===de.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):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)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,j.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 i;const r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.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,l=e[o],c=this.fragLastKbps;c&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:i=0}else i=0;const a=this.getBufferedFrag(t.currentTime+i);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,c=o.duration,u=Math.max(a.end,l+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*(this.couldBacktrack?.5:.125)),c*(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 M.KEY_LOADING:case M.FRAG_LOADING:case M.FRAG_LOADING_WAITING_RETRY:case M.PARSING:case M.PARSED:this.state=M.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Rh(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;W(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(p.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let i=!1,r=!1;t.levels.forEach(n=>{const a=n.audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=i&&r&&!Sh(),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:i}=this;if(!i||this.state!==M.IDLE)return;const r=i[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(r.details))&&(this.state=M.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!r){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=r[n],c=this.fragCurrent;c&&(this.state===M.FRAG_LOADING||this.state===M.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let u=0;if(a.live||(i=l.details)!=null&&i.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(p.LEVEL_UPDATED,{details:a,level:n}),this.state===M.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=M.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,u),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:r,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=a[i.level],l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const c=o.videoCodec,u=l.PTSKnown||!l.live,h=(t=i.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new bn(this.hls,j.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=r?r.index:-1,g=m!==-1,y=new Ui(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,g),v=this.initPTS[i.cc];f.push(n,h,d,c,i,r,l.totalduration,u,y,v)}onAudioTrackSwitching(e,t){const i=this.altAudio;if(!!!t.url){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();const n=this.hls;i&&(n.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),n.trigger(p.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=t.id,r=!!this.hls.audioTracks[i].url;if(r){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=r,this.tick()}onBufferCreated(e,t){const i=t.tracks;let r,n,a=!1;for(const o in i){const l=i[o];if(l.id==="main"){if(n=o,r=l,o==="video"){const c=i[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:r}=t;if(i&&i.type!==j.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===M.PARSED&&(this.state=M.IDLE);return}const n=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}onError(e,t){var i;if(t.fatal){this.state=M.ERROR;return}switch(t.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(j.MAIN,t);break;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===M.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===ee.LEVEL&&(this.state=M.IDLE);break;case _.BUFFER_APPEND_ERROR:case _.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===_.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case _.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){const{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!se.getBuffered(e).length){const i=this.state!==M.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=M.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==te.AUDIO||this.audioOnly&&!this.altAudio){const i=(t===te.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,j.MAIN),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const r=se.getBuffered(e),a=(r.length?r.start(0):0)-i;a>0&&(a<this.config.maxBufferHole||a<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${a} to match buffer start`),i+=a,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${t}`),e.currentTime=i}}_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(i=>{const{hls:r}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=M.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=e.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),r.trigger(p.FRAG_LOADED,i),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const i="main",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:u}=o,{video:h,text:d,id3:f,initSegment:m}=n,{details:g}=u,y=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=M.PARSING,m){if(m!=null&&m.tracks){const x=l.initSegment||l;this._bufferInitSegment(u,m.tracks,x,a),r.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:x,id:i,tracks:m.tracks})}const v=m.initPTS,T=m.timescale;W(v)&&(this.initPTS[l.cc]={baseTime:v,timescale:T},r.trigger(p.INIT_PTS_FOUND,{frag:l,id:i,initPTS:v,timescale:T}))}if(h&&g&&l.sn!=="initSegment"){const v=g.fragments[l.sn-1-g.startSN],T=l.sn===g.startSN,x=!v||l.cc>v.cc;if(n.independent!==!1){const{startPTS:L,endPTS:E,startDTS:k,endDTS:R}=h;if(c)c.elementaryStreams[h.type]={startPTS:L,endPTS:E,startDTS:k,endDTS:R};else if(h.firstKeyFrame&&h.independent&&a.id===1&&!x&&(this.couldBacktrack=!0),h.dropped&&h.independent){const B=this.getMainFwdBufferInfo(),C=(B?B.end:this.getLoadPosition())+this.config.maxBufferHole,b=h.firstKeyFramePTS?h.firstKeyFramePTS:L;if(!T&&C<b-this.config.maxBufferHole&&!x){this.backtrack(l);return}else x&&(l.gap=!0);l.setElementaryStreamInfo(h.type,l.start,E,l.start,R,!0)}else T&&L>ii&&(l.gap=!0);l.setElementaryStreamInfo(h.type,L,E,k,R),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(h,l,c,a,T||x)}else if(T||x)l.gap=!0;else{this.backtrack(l);return}}if(y){const{startPTS:v,endPTS:T,startDTS:x,endDTS:L}=y;c&&(c.elementaryStreams[te.AUDIO]={startPTS:v,endPTS:T,startDTS:x,endDTS:L}),l.setElementaryStreamInfo(te.AUDIO,v,T,x,L),this.bufferFragmentData(y,l,c,a)}if(g&&f!=null&&(t=f.samples)!=null&&t.length){const v={id:i,frag:l,details:g,samples:f.samples};r.trigger(p.FRAG_PARSING_METADATA,v)}if(g&&d){const v={id:i,frag:l,details:g,samples:d.samples};r.trigger(p.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(e,t,i,r){if(this.state!==M.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:n,video:a,audiovideo:o}=t;if(n){let l=e.audioCodec;const c=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5"),n.metadata.channelCount!==1&&c.indexOf("firefox")===-1&&(l="mp4a.40.5")),l&&l.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),n.levelCodec=l,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${n.codec}]`)}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(p.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{const u=t[l].initSegment;u!=null&&u.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:l,data:u,frag:i,part:null,chunkMeta:r,parent:i.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,j.MAIN)}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=M.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(se.isBuffered(e,i)?t=this.getAppendedFrag(i):se.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const r=this.fragPlaying,n=t.level;(!r||t.sn!==r.sn||r.level!==n)&&(this.fragPlaying=t,this.hls.trigger(p.FRAG_CHANGED,{frag:t}),(!r||r.level!==n)&&this.hls.trigger(p.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,i=this.currentFrag;if(i&&W(t)&&W(i.programDateTime)){const r=i.programDateTime+(t-i.start)*1e3;return new Date(r)}}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 $e{static get version(){return"1.5.6"}static isMSESupported(){return ca()}static isSupported(){return Eh()}static getMediaSource(){return tt()}static get Events(){return p}static get ErrorTypes(){return q}static get ErrorDetails(){return _}static get DefaultConfig(){return $e.defaultConfig?$e.defaultConfig:aa}static set DefaultConfig(e){$e.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new Zi,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.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,To(e.debug||!1,"Hls instance");const t=this.config=yh($e.DefaultConfig,e);this.userConfig=e,t.progressive&&vh(t);const{abrController:i,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=t,l=new a(this),c=this.abrController=new i(this),u=this.bufferController=new r(this),h=this.capLevelController=new n(this),d=new o(this),f=new fl(this),m=new vl(this),g=t.contentSteeringController,y=g?new g(this):null,v=this.levelController=new xh(this,y),T=new Yl(this),x=new Th(this.config),L=this.streamController=new Dh(this,T,x);h.setStreamController(L),d.setStreamController(L);const E=[f,v,L];y&&E.splice(1,0,y),this.networkControllers=E;const k=[c,u,h,d,m,T];this.audioTrackController=this.createController(t.audioTrackController,E);const R=t.audioStreamController;R&&E.push(new R(this,T,x)),this.subtitleTrackController=this.createController(t.subtitleTrackController,E);const B=t.subtitleStreamController;B&&E.push(new B(this,T,x)),this.createController(t.timelineController,k),x.emeController=this.emeController=this.createController(t.emeController,k),this.cmcdController=this.createController(t.cmcdController,k),this.latencyController=this.createController(xl,k),this.coreComponents=k,E.push(l);const C=l.onErrorOut;typeof C=="function"&&this.on(p.ERROR,C,l)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,r){this._emitter.off(e,t,i,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(S.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const r=e===p.ERROR;this.trigger(p.ERROR,{type:q.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:r,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){S.log("destroy"),this.trigger(p.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){S.log("attachMedia"),this._media=e,this.trigger(p.MEDIA_ATTACHING,{media:e})}detachMedia(){S.log("detachMedia"),this.trigger(p.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,i=this.url,r=this.url=pi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,S.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(p.MANIFEST_LOADING,{url:e})}startLoad(e=-1){S.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){S.log("stopLoad"),this.started=!1,this.networkControllers.forEach(e=>{e.stopLoad()})}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1)})}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.stopLoad()})}swapAudioCodec(){S.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){S.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){S.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){S.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){S.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){S.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){S.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 ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(S.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Tl(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 i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,i)for(let n=r;n--;){const a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var t;return(t=this.audioTrackController)==null?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return(t=this.subtitleTrackController)==null||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}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}$e.defaultConfig=void 0;function ps(){const s=document;return!!(s.fullscreenElement||s.mozFullScreenElement||s.webkitFullscreenElement||s.msFullscreenElement)}function ua(s){if(ps())return new Promise(t=>t(null));const e=s;if(e.requestFullscreen)return e==null?void 0:e.requestFullscreen();if(e.mozRequestFullScreen)return e==null?void 0:e.mozRequestFullScreen();if(e.webkitRequestFullScreen)return e==null?void 0:e.webkitRequestFullScreen();if(e.msRequestFullscreen)return e==null?void 0:e.msRequestFullscreen()}function ha(){if(!ps())return new Promise(e=>e(null));const s=document;if(s.exitFullscreen)return s.exitFullscreen();if(s.mozCancelFullScreen)return s.mozCancelFullScreen();if(s.webkitCancelFullScreen)return s.webkitCancelFullScreen();if(s.msExitFullscreen)return s.msExitFullscreen()}function da(s,e){let t=null;return function(...i){const r=this;t!==null&&clearTimeout(t),t=setTimeout(()=>{t=null,s.apply(r,i)},e||1e3)}}const ys=new Intl.NumberFormat(void 0,{minimumIntegerDigits:2}),fa=["play","pause","ended","loadeddata","waiting","playing","timeupdate","canplay","canplaythrough","statechanged","error"],vs=s=>{const e=Math.floor(s%60),t=Math.floor(s/60)%60,i=Math.floor(s/3600);return i===0?`${t}:${ys.format(e)}`:`${i}:${ys.format(t)}:${ys.format(e)}`},_h=Ee.extend({name:"VideoPlayer",components:{ESpinner:gi},props:{sources:{type:[Array,String],required:!0},videoListeners:{type:Object,default:()=>({})},videoOptions:{type:Object,default:()=>({})},isHls:{type:Boolean,default:!1},streamingToken:{type:String,default:""},isLiveView:{type:Boolean,default:!1}},data(){return{playing:!1,percentagePlayed:0,videoLength:"0:00",duration:0,videoDuration:0,currentTime:"0:00",realtime:0,isScrubbing:!1,wasPaused:!1,isFullscreen:!1,isFinished:!1,isLoading:!0,isError:!1,player:new $e}},computed:{sourceItems(){return Array.isArray(this.sources)?this.sources:[{src:this.sources}]},hasStartedOrFinished(){return(this.isFinished||this.realtime<=.1)&&!this.isLoading&&!this.isLooped()},withControls(){const s=this.videoOptions;return(s==null?void 0:s.controls)===!1?"hide":""}},mounted(){this.isHls&&this.initHls(),this.bindEvents(),this.initializePlayer(),this.initializeFullscreenListeners()},beforeDestroy(){this.unbindEvents(),this.destroyPlayer(),this.removeFullscreenListeners()},methods:{initHls(){var e,t,i,r;const s=this.$refs.player;(e=this.player)!=null&&e.stopLoad&&this.player.stopLoad(),$e.isSupported()&&(this.isLoading=!0,this.player=new $e({startPosition:0,xhrSetup:n=>{this.streamingToken&&n.setRequestHeader("Authorization",`Bearer ${this.streamingToken}`)}}),(t=this.player)==null||t.loadSource(this.sources[0].src),(i=this.player)==null||i.attachMedia(s),(r=this.player)==null||r.on($e.Events.MANIFEST_PARSED,()=>{this.playing&&s.play()}))},handle404Error(){this.isError=!0,this.isLoading=!1,this.playing=!1},bindEvents(){const s=this.$refs.player;fa.forEach(e=>{s.addEventListener(e,()=>this.bindVideoEvent(e),!0)})},unbindEvents(){const s=this.$refs.player;fa.forEach(e=>{s.removeEventListener(e,()=>this.bindVideoEvent(e),!0)})},bindVideoEvent(s){const e=this.$refs.player;if(!e)return;const t=this.$refs.timelineContainer;s==="loadeddata"&&(this.videoLength=vs(e.duration)),s==="timeupdate"&&(this.percentagePlayed=(e==null?void 0:e.currentTime)/e.duration*100,t.style.setProperty("--progress-position",this.percentagePlayed.toString())),this.$emit(s,{event,player:e})},initializePlayer(){const s=this.$refs.player;s&&(s.autoplay&&this.setPlaying(!0),document.addEventListener("mouseup",this.handleScrubbingOnMouseEnd),document.addEventListener("keydown",this.handleKeyDown))},destroyPlayer(){window.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("mouseup",this.handleScrubbingOnMouseEnd)},removeFullscreenListeners(){document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled?(document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("webkitfullscreenchange",this.handleFullscreenChange),document.removeEventListener("mozfullscreenchange",this.handleFullscreenChange),document.removeEventListener("MSFullscreenChange",this.handleFullscreenChange)):console.log("Fullscreen API is not supported in this browser.")},initializeFullscreenListeners(){document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled?(document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("webkitfullscreenchange",this.handleFullscreenChange),document.addEventListener("mozfullscreenchange",this.handleFullscreenChange),document.addEventListener("MSFullscreenChange",this.handleFullscreenChange)):console.log("Fullscreen API is not supported in this browser.")},handleFullscreenChange(){this.isFullscreen=document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement||window.innerWidth==screen.width&&window.innerHeight==screen.height},isLooped(){return this.$refs.player.loop},handleScrubbingOnMouseEnd(s){this.isScrubbing&&this.toggleScrubbing(s)},handleEnded(){this.isFinished=!0,this.playing=!1},handleLoading(){this.isLoading=!1},play(){const s=this.$refs.player;if(!s)return;s.play()!==void 0&&s.play().then(()=>this.setPlaying(!0)).catch(console.error)},pause(){const s=this.$refs.player;s&&(s.pause(),this.setPlaying(!1))},togglePlay(){this.playing?this.pause():this.play()},setPlaying(s){this.playing=s},seekToPercentage(s){const e=this.$refs.player;if(!e)return;const t=s/100*e.duration;e.currentTime=t},convertTimeToDuration(s){return[parseInt(s/60%60,10),parseInt(s%60,10)].join(":").replace(/\b(\d)\b/g,"0$1")},closeFullscreenMode(){document.fullscreenElement&&(ha().then(()=>{this.isFullscreen=!1,console.log("Exited fullscreen")}),this.isFullscreen=!1)},openFullscreenMode(){const s=this.$refs.videoContainer;s&&(ua(s).then(()=>{this.isFullscreen=!0}),this.isFullscreen=!0)},toggleFullscreenMode(){this.isFullscreen?this.closeFullscreenMode():this.openFullscreenMode()},getDuration(){const s=this.$refs.player;this.videoLength=vs(s.duration),this.videoDuration=s.duration},handleTimeUpdate(){const s=this.$refs.player,e=this.$refs.timelineContainer;if(!s||!e)return;this.currentTime=vs(s.currentTime),this.realtime=s.currentTime;const t=Number(this.realtime)/Number(this.videoDuration);e.style.setProperty("--progress-position",t.toString())},handleTimelineUpdate(s){const e=this.$refs.player;if(!document.body.contains(e))return;const t=this.$refs.timelineContainer,i=t.getBoundingClientRect(),r=Math.min(Math.max(0,s.x-i.x),i.width)/i.width;t.style.setProperty("--preview-position",r.toString()),this.isScrubbing&&(s.preventDefault(),t.style.setProperty("--progress-position",r.toString()))},skip(s=5){const e=this.$refs.player;e.currentTime+=s},async toggleScrubbing(s){const e=this.$refs.timelineContainer,t=this.$refs.videoContainer,i=this.$refs.player;if(!i)return;const r=e.getBoundingClientRect(),n=Math.min(Math.max(0,s.x-r.x),r.width)/r.width;if(this.isScrubbing=(s.buttons&1)===1,t.classList.toggle("scrubbing",this.isScrubbing),this.isScrubbing){this.wasPaused=i.paused,await i.pause(),this.handleTimelineUpdate(s);return}if(this.realtime=n*this.videoDuration,i.currentTime=n*this.videoDuration,this.wasPaused)return;const a=i.play();a!==void 0&&a.then(()=>this.handleTimelineUpdate(s)).catch(console.error)},handleKeyDown(s){var t;const e=(t=document.activeElement)==null?void 0:t.tagName.toLowerCase();if(e!=="input")switch(s.key.toLowerCase()){case" ":if(e==="button")return;this.togglePlay();break;case"k":this.togglePlay();break;case"escape":s.preventDefault(),this.closeFullscreenMode(),this.isFullscreen=!1;break;case"f":this.openFullscreenMode(),this.isFullscreen=!0;break}}}}),Qh="";var Ih=function(){var e=this,t=e._self._c;return t("div",{ref:"videoContainer",staticClass:"video-container paused",attrs:{"data-volume-level":"high"}},[t("video",e._g(e._b({ref:"player",attrs:{controls:!1,preload:"auto"},on:{ended:e.handleEnded,click:e.togglePlay,loadedmetadata:e.getDuration,timeupdate:e.handleTimeUpdate,loadeddata:e.handleLoading}},"video",e.videoOptions,!1),e.videoListeners),e._l(e.sourceItems,function(i){return t("source",e._g({key:i.src,attrs:{src:i.src,type:i.type},on:{error:e.handle404Error}},e.videoListeners))}),0),e.isLoading?t("div",{staticClass:"spinner-container"},[t("ESpinner",{attrs:{color:!e.isHls,size:e.isHls?"7xl":"9xl",opacity:"0.6",dark:!0}})],1):e._e(),e.isError?t("div",{staticClass:"spinner-container e-gap-3"},[t("i",{staticClass:"fa-solid fa-video-slash fa-2xl e-align-middle"}),t("span",[e._v("This video file cannot be played.")])]):e._e(),t("div",{class:["video-controls-container",e.withControls]},[t("div",{staticClass:"controls"},[t("button",{ref:"playPauseBtn",staticClass:"play-pause-btn fa-lg fa-solid",class:{"fa-play":!e.playing,"fa-pause":e.playing},attrs:{title:e.playing?"pause":"play"},on:{click:e.togglePlay}}),t("div",{staticClass:"duration-container"},[t("div",{ref:"currentTimeElem",staticClass:"current-time"},[e._v(" "+e._s(e.currentTime)+" ")]),e._v(" / "),t("div",{ref:"totalTimeElem",staticClass:"total-time"},[e._v(e._s(e.videoLength))])]),t("div",{ref:"timelineContainer",staticClass:"timeline-container",on:{mousemove:e.handleTimelineUpdate,mousedown:e.toggleScrubbing}},[e._m(0)]),t("button",{ref:"fullScreenBtn",staticClass:"full-screen-btn fa-solid",class:{"fa-expand":!e.isFullscreen,"fa-compress":e.isFullscreen},on:{click:e.toggleFullscreenMode}})])])])},wh=[function(){var s=this,e=s._self._c;return e("div",{staticClass:"timeline"},[e("div",{staticClass:"thumb-indicator"})])}],kh=Ie(_h,Ih,wh,!1,null,"9071f674",null,null);const ma=kh.exports,si=s=>{const e=I.utcFormat("%_d")(s),i={1:"st",2:"nd",3:"rd"}[e.charAt(1)]||"th";return`${e}${i}`},ga=s=>new Date(Date.UTC(s.getUTCFullYear(),s.getUTCMonth(),s.getUTCDate()+1)).getUTCDate()===1?"":I.utcFormat("%-d")(s),St=s=>["0"," 0","00"].includes(I.utcFormat("%H")(s))?"":`${I.utcFormat("%H")(s)}h`,je=s=>{const e=I.utcFormat("%H:%M")(s);return e==="00:00"?"":e},xs=s=>I.utcFormat("%M:%S")(s),pa=s=>`${I.utcFormat("%Hh%Mm")(s)}`,Ts=s=>{const e=je(s),t=si(s),i=I.utcFormat("%B")(s);return e||`${i} ${t}`},Es=s=>{const e=je(s),t=Number.parseInt(I.utcFormat("%H")(s)),i=si(s),r=I.utcFormat("%B")(s);return e&&t%6===0?`${r} ${i} ${e}`:Ts(s)},bt=s=>e=>{const t=I.utcFormat("%H")(e);return!(I.utcFormat("%M")(e)==="00"&&Number.parseInt(t)%s===0)},Ss=s=>e=>{const t=I.utcFormat("%M")(e);return Number.parseInt(t)%s!==0},ya=s=>e=>{const t=I.utcFormat("%M")(e),i=I.utcFormat("%S")(e);return Number.parseInt(t)%s!==0&&Number.parseInt(i)===0},K={_10_seconds:25e-6,_20_seconds:1e-4,_30_seconds:15e-5,_1_minute:3e-4,_2_minutes:75e-5,_5_minutes:.002,_15_minutes:.005,_30_minutes:.01,_1_hour:.025,_2_hours:.05,_3_hours:.1,_4_hours:.15,_6_hours:.25,_1_day:1,_2_days:2,_1_month:8,_1_month_abbr:13,_1_month_letter:22,_3_months:33,_2_year:48,_5_years:120,_20_years:480,_75_years:1800,_300_years:7200,infinity:1/0},Ph={[mt.overview]:[{precision:K._30_seconds,interval:I.utcMinute.every(2),format:pa},{precision:K._1_minute,interval:I.utcMinute.every(5),format:pa},{precision:K._2_minutes,interval:I.utcMinute.every(10),format:Ts},{precision:K._5_minutes,interval:I.utcMinute.every(20),format:Es},{precision:K._15_minutes,interval:I.utcHour,format:Es},{precision:K._30_minutes,interval:I.utcHour.every(2),format:Es},{precision:K._2_hours,interval:I.utcHour.every(6),format:s=>{const e=je(s),t=si(s),i=I.utcFormat("%B")(s);return e||`${i} ${t}`}},{precision:K._3_hours,interval:I.utcHour.every(12),format:Ts},{precision:K._6_hours,interval:I.utcHour.every(24),format:s=>{const e=si(s);return`${I.utcFormat("%b")(s)} ${e}`}},{precision:K._2_days,interval:I.utcMonth,format:s=>{const t=s.getUTCMonth()===0&&s.getUTCDate()===1?"%Y – %B":"%B";return I.utcFormat(t)(s)}},{precision:K._2_year,interval:I.utcYear.every(2),format:"%Y"},{precision:K._5_years,interval:I.utcYear.every(5),format:"%Y"},{precision:K._20_years,interval:I.utcYear.every(20),format:"%Y"},{precision:K._75_years,interval:I.utcYear.every(75),format:"%Y"},{precision:K._300_years,interval:I.utcYear.every(300),format:"%Y"},{precision:K.infinity,interval:I.utcMonth.every(12),format:"%Y"}],[mt.detailed]:[{precision:K._10_seconds,interval:I.utcSecond.every(10),format:xs},{precision:K._20_seconds,interval:(Ea=I.utcSecond.every(20))==null?void 0:Ea.filter(ya(2)),format:xs},{precision:K._30_seconds,interval:(Sa=I.utcSecond.every(30))==null?void 0:Sa.filter(ya(2)),format:xs},{precision:K._1_minute,interval:I.utcMinute.filter(Ss(5)),format:je},{precision:K._2_minutes,interval:(ba=I.utcMinute.every(2))==null?void 0:ba.filter(Ss(10)),format:je},{precision:K._5_minutes,interval:(Aa=I.utcMinute.every(5))==null?void 0:Aa.filter(Ss(20)),format:je},{precision:K._15_minutes,interval:(La=I.utcMinute.every(15))==null?void 0:La.filter(bt(1)),format:je},{precision:K._30_minutes,interval:(Ra=I.utcMinute.every(30))==null?void 0:Ra.filter(bt(2)),format:je},{precision:K._1_hour,interval:I.utcHour.filter(bt(6)),format:St},{precision:K._2_hours,interval:(Ca=I.utcHour.every(2))==null?void 0:Ca.filter(bt(6)),format:St},{precision:K._3_hours,interval:(Da=I.utcHour.every(3))==null?void 0:Da.filter(bt(12)),format:St},{precision:K._4_hours,interval:I.utcHour.every(4),format:St},{precision:K._6_hours,interval:I.utcHour.every(6),format:St},{precision:K._1_day,interval:I.utcDay,format:ga},{precision:K._2_days,interval:I.utcDay.every(2),format:ga},{precision:K._1_month,interval:I.utcMonth,format:"%B"},{precision:K._1_month_abbr,interval:I.utcMonth,format:"%b"},{precision:K._1_month_letter,interval:I.utcMonth,format:s=>I.utcFormat("%B")(s).charAt(0)},{precision:K._3_months,interval:I.utcMonth.every(3),format:"Q%q"},{precision:K._2_year,interval:I.utcMonth.every(6),format:"%Y"},{precision:K._5_years,interval:I.utcYear.every(2),format:"%Y"},{precision:K._20_years,interval:I.utcYear.every(4),format:"%Y"},{precision:K._75_years,interval:I.utcYear.every(25),format:"%Y"},{precision:K._300_years,interval:I.utcYear.every(100),format:"%Y"},{precision:K.infinity,interval:I.utcYear.every(500),format:""}],[mt.detailedBackground]:[{precision:K._10_seconds,interval:I.utcSecond,format:""},{precision:K._20_seconds,interval:I.utcSecond.every(5),format:""},{precision:K._30_seconds,interval:I.utcSecond.every(10),format:""},{precision:K._1_minute,interval:I.utcSecond.every(20),format:""},{precision:K._2_minutes,interval:I.utcSecond.every(30),format:""},{precision:K._5_minutes,interval:I.utcMinute,format:""},{precision:K._15_minutes,interval:I.utcMinute.every(3),format:""},{precision:K._30_minutes,interval:I.utcMinute.every(6),format:""},{precision:K._1_hour,interval:I.utcMinute.every(15),format:""},{precision:K._2_hours,interval:I.utcMinute.every(30),format:""},{precision:K._3_hours,interval:I.utcHour,format:""},{precision:K._4_hours,interval:I.utcHour,format:""},{precision:K._6_hours,interval:I.utcMinute.every(120),format:""},{precision:K._1_day,interval:I.utcHour.every(8),format:""},{precision:K._2_days,interval:I.utcHour.every(12),format:""},{precision:K._1_month,interval:I.utcDay.filter(s=>{const e=s.getUTCDate(),t=new Date(s.getUTCFullYear(),s.getUTCMonth()+1,0).getUTCDate(),i=Math.ceil(t/5);return e===i||e===2*i||e===3*i||e===4*i}),format:""},{precision:K._1_month_abbr,interval:I.utcDay.filter(s=>{const e=s.getUTCDate(),t=new Date(s.getUTCFullYear(),s.getUTCMonth()+1,0).getUTCDate(),i=Math.ceil(t/4);return e===i||e===2*i||e===3*i}),format:""},{precision:K._1_month_letter,interval:I.utcDay.filter(s=>{const e=s.getUTCDate(),t=new Date(s.getUTCFullYear(),s.getUTCMonth()+1,0).getUTCDate(),i=Math.ceil(t/2);return e===i}),format:""},{precision:K._3_months,interval:I.utcMonth,format:""},{precision:K._3_months,interval:I.utcMonth,format:""},{precision:K._2_year,interval:I.utcYear,format:""},{precision:K._5_years,interval:I.utcYear.every(2),format:""},{precision:K._20_years,interval:I.utcYear.every(5),format:""},{precision:K._75_years,interval:I.utcYear.every(20),format:""},{precision:K._300_years,interval:I.utcYear.every(100),format:""},{precision:K.infinity,interval:I.utcYear.every(500),format:""}]},ri={bind(s,e){const{value:t}=e;if(typeof t!="function"){console.error("Invalid callback function provided to v-resize-observer");return}const i=new ResizeObserver(r=>{r[0]&&t(r[0])});i.observe(s),s.__resizeObserver__=i},unbind(s){s.__resizeObserver__&&(s.__resizeObserver__.disconnect(),delete s.__resizeObserver__)}},va=[{name:"resize-observer",definition:ri}],qe={milestone:"e-tl-milestone",milestoneBullet:"e-tl-milestone--bullet",milestoneDot:"e-tl-milestone--dot",milestoneContent:"e-tl-milestone-content",milestoneLine:"e-tl-milestone-line",milestonesContainer:"e-tl-milestones",milestoneHovered:"e-tl-milestone--hovered",milestoneSelected:"e-tl-milestone--selected",milestoneLabel:"e-tl-milestone-label",milestoneDotContainer:"e-tl-milestone-dot-container",milestoneDotLine:"e-tl-milestone-dot-line",milestoneDotDot:"e-tl-milestone-dot-dot",milestoneDotHovered:"e-tl-milestone-dot--hovered"},Oh=Ee.extend({name:"ETimeline",directives:{resizeObserver:ri},props:{milestone:{type:Object,required:!0},size:{type:Number,default:18},borderColor:{type:String,default:"#eee"},backgroundColor:{type:String,default:"#aaa"},borderWidth:{type:Number,default:2},transitionDuration:{type:Number,default:500},dot:{type:Boolean,default:!1},dotSize:{type:Number,default:8},lineWidth:{type:Number,default:2},lineHeight:{type:Number,default:28}},data(){return{milestoneClasses:qe,timeouts:[],isInitialRender:!0,isMouseOver:!1}},computed:{transitionStyles(){return this.isInitialRender?{}:{transition:`transform ${this.transitionDuration}ms, width ${this.transitionDuration}ms, height ${this.transitionDuration}ms, padding ${this.transitionDuration}ms, border-radius ${this.transitionDuration}ms`}},sizeStyles(){return this.dot?{}:{width:`${this.size}px`,height:`${this.size}px`}},positionStyles(){return this.dot&&this.isMouseOver?{transform:`translateY(calc(-100% - ${this.lineHeight}px))`}:{}},styles(){return{...this.sizeStyles,...this.positionStyles,backgroundColor:this.backgroundColor,borderColor:this.borderColor,borderWidth:`${this.borderWidth}px`,borderStyle:"solid",...this.transitionStyles}},contentStyles(){return this.transitionStyles},computedTransitionDuration(){return this.isInitialRender?0:this.transitionDuration},labelStyles(){return{transition:`opacity ${this.computedTransitionDuration}ms`}},dotContainerStyles(){return{top:this.isMouseOver?`calc(100% - ${this.borderWidth}px)`:`calc(50% + ${this.dotSize/2}px)`,height:`calc(${this.lineHeight}px + ${this.dotSize}px)`,left:`calc(50% - ${this.lineWidth}px / 2)`,transition:`${this.computedTransitionDuration}ms`}},lineStyles(){return{bottom:`${this.dotSize/2}px`,left:`calc(50% - ${this.lineWidth}px / 2)`,width:`${this.lineWidth}px`,height:this.isMouseOver?`${this.lineHeight}px`:"0",backgroundColor:this.borderColor,transition:`${this.computedTransitionDuration}ms`}},dotStyles(){return{top:`${this.lineHeight}px`,left:`calc(50% - ${this.dotSize}px / 2)`,width:`${this.dotSize}px`,height:`${this.dotSize}px`,backgroundColor:this.borderColor,transition:`${this.computedTransitionDuration}ms`}}},mounted(){this.$nextTick(()=>{this.dot||(this.onMilestoneMouseOver(),this.onMilestoneMouseLeave()),this.isInitialRender=!1})},methods:{onMilestoneMouseOver(s){if(this.isMouseOver=!0,this.dot)return;const e=(s==null?void 0:s.target)||this.$refs.container;if(!e)return;const t=e.children[0];if(!t)return;const i=t.children[0];if(!i)return;const r=i.getBoundingClientRect(),n=e.dataset.timeoutId;n&&(clearTimeout(Number(n)),e.dataset.timeoutId=""),e.dataset.initialWidth||(e.dataset.initialWidth=e.style.width),e.dataset.initialHeight||(e.dataset.initialHeight=e.style.height),e.dataset.initialContentWidth||(e.dataset.initialContentWidth=String(r.width)),e.dataset.initialContentHeight||(e.dataset.initialContentHeight=String(r.height)),e.dataset.transitionStart=String(Date.now()),e.style.width=e.dataset.initialContentWidth+"px",e.style.height=e.dataset.initialContentHeight+"px",e.style.borderRadius="0.5em",e.classList.add(qe.milestoneHovered),t.style.opacity="1",t.style.width=e.dataset.initialContentWidth+"px",t.style.height=e.dataset.initialContentHeight+"px"},onMilestoneMouseMove(){this.timeouts.forEach(s=>clearTimeout(s)),this.isMouseOver=!0},onMilestoneMouseLeave(s){if(this.dot){this.timeouts.push(setTimeout(()=>{this.isMouseOver=!1},this.transitionDuration+100));return}const e=(s==null?void 0:s.target)||this.$refs.container;if(!e)return;e.style.width=e.dataset.initialWidth||"",e.style.height=e.dataset.initialHeight||"",e.style.borderRadius="10em";const t=e.children[0];if(!t)return;t.style.width="0",t.style.height="0",t.style.opacity="0";const i=Date.now()-Number(e.dataset.transitionStart),r=i>this.transitionDuration?this.transitionDuration:i,n=setTimeout(()=>{e.classList.remove(qe.milestoneHovered),e.dataset.timeoutId=""},r);e.dataset.timeoutId=String(n),this.timeouts.push(n)},onMilestoneClick(s,e){this.$emit("milestone-click",e)}}}),Jh="";var Fh=function(){var e=this,t=e._self._c;return t("div",{ref:"container",class:{[e.milestoneClasses.milestone]:!0,[e.milestoneClasses.milestoneBullet]:!e.dot,[e.milestoneClasses.milestoneHovered]:e.isMouseOver&&!e.dot,[e.milestoneClasses.milestoneDot]:e.dot,[e.milestoneClasses.milestoneDotHovered]:e.isMouseOver&&e.dot},style:e.styles,attrs:{tabindex:"0"},on:{mouseover:i=>e.onMilestoneMouseOver(i,e.milestone),mousemove:e.onMilestoneMouseMove,mouseleave:i=>e.onMilestoneMouseLeave(i,e.milestone),click:i=>e.onMilestoneClick(i,e.milestone)}},[t("div",{class:e.milestoneClasses.milestoneContent,style:e.contentStyles},[e._t("content",function(){return[t("span",[e._v(" "+e._s(e.milestone.text)+" ")])]})],2),e.dot?t("div",{class:e.milestoneClasses.milestoneDotContainer,style:e.dotContainerStyles},[t("div",{class:e.milestoneClasses.milestoneDotLine,style:e.lineStyles}),t("div",{class:e.milestoneClasses.milestoneDotDot,style:e.dotStyles})]):t("div",{class:e.milestoneClasses.milestoneLabel,style:e.labelStyles},[e._t("label")],2)])},Mh=[],Nh=Ie(Oh,Fh,Mh,!1,null,null,null,null);const Bh=Nh.exports,G={eventGroup:"event-group",eventGroupBg:"event-group-bg",eventRect:"event-rect",eventBarContainer:"event-bar-container",eventBarContainerHovered:"event-bar-container--hovered",eventBarContainerSelected:"event-bar-container--selected",eventBar:"event-bar",eventBarHoverZone:"event-bar-hover-zone",eventBarCap:"event-bar-cap",eventRectText:"event-rect-text",eventRectHovered:"event-rect--hovered",eventRectSelected:"event-rect--selected",labelGroup:"label-g",labelBg:"label-bg",labelBgFill:"label-bg-fill",labelText:"label-text",loadingIndicator:"loading-indicator",xAxis:"x-axis",selectedTimestampCursor:"selected-timestamp-cursor",marker:"marker",markerLabel:"marker-label",markerLine:"marker-line",markerDragged:"marker--dragged",milestone:"milestone",milestoneLine:"milestone-line",milestonesContainer:"milestones",milestoneHovered:"milestone--hovered",barChartGroup:"bar-chart-group",lineGraphGroup:"line-graph-group",lineGraphGroupLabel:"line-graph-group-label",lineGraphPath:"line-graph-path",lineGraphHoverZone:"line-graph-hover-zone",lineGraphDot:"line-graph-dot",curtain:"curtain",forbiddenInterval:"forbidden-interval"},Ke={transparencyGradient:"transparency-gradient",transparencyGradientLight:"transparency-gradient-light",loadingGradient:"loading-gradient",stripedPattern:"stripedPattern"},$h=Ee.extend({name:"ETimeline",directives:{resizeObserver:ri},components:{ETimelineMilestone:Bh},props:{eventsGroups:{type:Object,default:()=>({})},xAxesConfig:{type:Object,default:()=>Ph},dark:{type:Boolean,default:!1},startDate:{type:String,default:void 0},endDate:{type:String,default:void 0},selectedTimestamp:{type:String,default:void 0},showEventTooltip:{type:Boolean,default:!0},disableZoom:{type:Boolean,default:!1},insertZerosAtInterval:{type:String,default:void 0},flattenLineGraphEnds:{type:Boolean,default:!0},curtains:{type:Boolean,default:!1},showLabels:{type:Boolean,default:!0},rectMinWidth:{type:Number,default:1},barHeight:{type:Number,default:18},barYPadding:{type:Number,default:0},barXPadding:{type:Number,default:0},chartMinHeight:{type:Number,default:60},chartMinLabelHeight:{type:Number,default:18},minZoom:{type:Number,default:1e-4},maxZoom:{type:Number,default:85e4},minDate:{type:String,default:void 0},maxDate:{type:String,default:void 0},cursorTimestamp:{type:[String,void 0],default:void 0},selectedClass:{type:[String,void 0],default:void 0},panOnDateClick:{type:Boolean,default:!1},panTransitionDuration:{type:Number,default:800},selectedDate:{type:String,default:""},autoResize:{type:Boolean,default:!0},markers:{type:Array,default:()=>[]},stickyMarkers:{type:Boolean,default:!0},fitMarkersOnChange:{type:Boolean,default:!1},fitMarkersTransitionDuration:{type:Number,default:800},zoomToBoundariesTransitionDuration:{type:Number,default:0},milestoneBulletSize:{type:Number,default:18},milestonesFirst:{type:Boolean,default:!0},forbiddenIntervals:{type:Array,default:()=>[]},forbiddenIntervalColor:{type:String,default:"#ddd"}},data(){return{tooltip:null,cursor:null,timeline:null,wrapperDiv:null,selectedTimestampCursor:null,svg:null,axesContainer:null,xAxes:{},timeScale:null,initialTimeScale:null,currentTimeScaleDensity:null,zoomBehavior:null,isMouseDown:!1,axisHeight:22,isHoveringEvent:!1,hoveredEvent:null,isHoveringTimeline:!1,hoveredTimestamp:null,eventTooltipStyle:{},hoveredEventType:null,utcOffset:0,lastTransform:{x:0,k:1},transformDiff:{translation:0,scale:1},yScale:null,hoveredCounts:[],countsByTimestamp:{},dotsByTimestamp:{},visibleFrom:null,visibleTo:null,curtainHandleWidth:5,leftCurtainWidth:50,rightCurtainWidth:50,isHoveringCurtain:!1,isDraggingCurtain:!1,characterWidth:7.5,textPadding:5,debouncedOnResize:()=>{},isFirstPaint:!0,timeouts:[],groupsVisibility:{},markersPositions:{},markersDragBehavior:null,initialMarkerDragMouseOffset:0,selectedMilestoneId:null,isInitialized:!1,lastValidTransform:I.zoomIdentity}},computed:{combinedBarsHeight(){return Object.values(this.barGroups).reduce((s,e)=>s+(this.getBarGroupHeight(e)||this.barChartHeight),0)},combinedBottomBarsHeight(){return Object.values(this.barGroups).reduce((s,e)=>s+(e.bottom?this.getBarGroupHeight(e):0),0)},combinedMilestonesHeight(){return Object.values(this.milestonesGroups).reduce((s,e)=>s+(e.height||this.barChartHeight),0)},milestonesYOffset(){return this.milestonesFirst?0:this.combinedBarsHeight-this.combinedBottomBarsHeight+(this.hasChart?this.chartHeight:0)},chartsYOffset(){return this.hasMilestones&&this.milestonesFirst?this.combinedMilestonesHeight:0},barsYOffset(){return(this.hasChart?this.chartHeight:0)+(this.hasMilestones&&this.milestonesFirst?this.combinedMilestonesHeight:0)},hasMilestones(){return Object.keys(this.milestonesGroups).length>0},barChartHeight(){return this.barHeight+this.barYPadding},classes(){return{wrapper:{"e-border-gray-700 e-timeline--dark":this.dark,"e-border-gray-300":!this.dark,"e-timeline--dragging":this.isInteractingWithCurtain},background:this.dark?"e-bg-gray-900":"e-bg-gray-50",tooltipSlot:this.dark?"e-bg-gray-900 e-text-white e-border-gray-700":"e-bg-gray-100 e-text-gray-700 e-border-gray-300",eventTooltipSlot:this.dark?"e-bg-gray-900 e-text-white e-border-gray-700":"e-bg-gray-100 e-text-gray-700 e-border-gray-300"}},lineGraphGroups(){return Object.entries(this.filteredEventsGroups).reduce((s,[e,t])=>t.chartType===Se.lineGraph?{...s,[e]:t}:s,{})},chartHeight(){if(!this.showLabels)return this.chartMinHeight;const e=(Object.keys(this.lineGraphGroups).length+Object.keys(this.barChartGroups).length)*this.barChartHeight;return Math.max(this.chartMinHeight,e)},barGroups(){return Object.entries(this.filteredEventsGroups).reduce((s,[e,t])=>!t.chartType||[Se.bars,Se.dots].includes(t.chartType)?{...s,[e]:t}:s,{})},barChartGroups(){return Object.entries(this.filteredEventsGroups).reduce((s,[e,t])=>t.chartType===Se.barChart?{...s,[e]:t}:s,{})},milestonesGroups(){return Object.entries(this.filteredEventsGroups).reduce((s,[e,t])=>t.chartType===Se.milestones?{...s,[e]:t}:s,{})},hasChart(){return Object.keys(this.lineGraphGroups).length+Object.keys(this.barChartGroups).length>0},labelRectWidth(){return Object.values(this.eventsGroups).reduce((t,i)=>{var r;return Math.max(t,(r=i.label)==null?void 0:r.length)},0)*this.characterWidth+2*this.textPadding},combinedXAxesHeight(){const s=Object.keys(this.xAxesConfig).length-1;return this.axisHeight*s},timelineHeight(){return(this.hasChart?this.chartHeight:0)+this.combinedXAxesHeight+this.combinedBarsHeight+this.combinedMilestonesHeight},filteredEventsGroups(){const s=Object.entries(this.eventsGroups).filter(([e,t])=>this.getCurrentGroupVisibility(e));return Object.fromEntries(s)},allEventsSorted(){const s=Object.values(this.filteredEventsGroups).map(e=>e.events).flat();return this.getSortedEvents(s)},oldestEvent(){let s;return this.allEventsSorted.length>1?s=this.allEventsSorted[0]:s={timestamp:new Date(new Date().getTime()-864e5)},s},latestEvent(){let s;return this.allEventsSorted.length>1?s=this.allEventsSorted[this.allEventsSorted.length-1]:s={timestamp:new Date},s},allLineChartTimestamps(){const s=new Set;return Object.values(this.lineGraphGroups).forEach(e=>{e.events.forEach(t=>{s.add(t.timestamp)})}),Array.from(s).sort()},placeholderLineChartGroup(){return this.fillTimeGaps(this.allLineChartTimestamps.map(s=>({timestamp:s,count:0})))},filledGapsLineGraphGroups(){return Object.entries(this.lineGraphGroups).reduce((s,[e,t])=>({...s,[e]:{...t,events:this.fillEvents(t.events)}}),{})},isInteractingWithCurtain(){return this.isHoveringCurtain||this.isDraggingCurtain},flattenedCounts(){return[...Object.values(this.lineGraphGroups),...Object.values(this.barChartGroups)].map(s=>s.events).flat()},hiddenGroupsLabels(){return Object.entries(this.groupsVisibility).reduce((s,[e,t])=>t?s:[...s,e],[])},minHoverZone(){return this.showLabels?this.labelRectWidth:0},sortedMarkers(){return this.isInitialized?[...this.markers].sort((s,e)=>new Date(s.timestamp).getTime()>new Date(e.timestamp).getTime()?1:-1):[]}},watch:{dark(){this.handleDarkModeChange()},selectedTimestamp(){this.repositionSelectedTimestampCursor()},markers(){this.updateMarkers(),this.fitMarkersOnChange&&this.zoomToFitMarkers()},startDate(){this.zoomToStartAndEndDates()},endDate(){this.zoomToStartAndEndDates()},eventsGroups(){this.updateAndRedrawTimeline()},cursorTimestamp(){if(this.cursorTimestamp){this.hoveredTimestamp=this.cursorTimestamp;const s=this.tzStringToDate(this.hoveredTimestamp),e=this.timeScale(s);this.cursor.style.left=e+"px",this.isHoveringTimeline=!0}else this.isHoveringTimeline=!1},selectedDate(s){s&&this.panToTimestamp(s)},groupsVisibility(){this.updateAndRedrawTimeline()},forbiddenIntervals(){this.updateForbiddenIntervals(!0)}},created(){this.debouncedOnResize=da(this.handleResize,100)},mounted(){this.initTimeline()},beforeDestroy(){this.clearTimeline(),document.removeEventListener("mouseup",this.handleDocumentMouseUp)},methods:{updateTimeline(){this.initOrUpdateSvg(),this.updateXAxes(),this.updateYScaleDomain(),this.updateForbiddenIntervals(),this.drawEventsGroups(),this.updateCurtains(),this.repositionSelectedTimestampCursor(),this.updateMarkers(),this.registerEventsListeners(),this.isInitialized=!0},initTimeline(s,e){if(this.initRefs(),!this.timeline||this.timeline.offsetWidth===0){this.timeouts.push(setTimeout(this.initTimeline,500));return}this.initOrUpdateSvg(),this.initDefs(),this.initUtcOffset(),this.initTimeScale(s,e),this.initXAxes(),this.initYScale(),this.initZoomBehavior(),this.drawEventsGroups(),this.curtains&&(this.initCurtains(),this.emitCurtainChange()),this.initSelectedTimestampCursor(),this.updateMarkers(),this.registerEventsListeners(),this.emitVisibleInterval(gt.initial),this.selectedDate&&this.panOnDateClick&&this.panToTimestamp(this.selectedDate),this.isInitialized=!0},initRefs(){this.tooltip=this.$refs.tooltip,this.cursor=this.$refs.cursor,this.timeline=this.$refs.timelineContainer,this.selectedTimestampCursor=this.$refs.selectedTimestamp,this.wrapperDiv=this.$refs.wrapperDiv},initOrUpdateSvg(){this.svg||(this.svg=I.select(this.timeline).append("svg")),this.svg.attr("width",this.timeline.offsetWidth).attr("height",this.timelineHeight)},initDefs(){const s=this.svg.append("defs");Object.entries(this.filteredEventsGroups).forEach(([t,i])=>{const{color:r,chartType:n}=i,a=s.append("linearGradient").attr("id",`${Ke.loadingGradient}-${t}`).attr("x1","0%").attr("y1","0%").attr("x2","100%").attr("y2","0%");a.append("stop").attr("offset","0%").attr("stop-color",r).attr("stop-opacity","0"),a.append("stop").attr("offset","50%").attr("stop-color",r).attr("stop-opacity","0.6"),a.append("stop").attr("offset","100%").attr("stop-color",r).attr("stop-opacity","0"),[Se.lineGraph,Se.barChart].includes(n)&&[{id:Ke.transparencyGradientLight,stop:38,opacity:.3},{id:Ke.transparencyGradient,stop:130,opacity:.4}].forEach(({id:l,stop:c,opacity:u})=>{const h=s.append("linearGradient").attr("id",`${l}-${t}`).attr("x1","0%").attr("x2","0%").attr("y1","0%").attr("y2","100%");h.append("stop").attr("offset","0%").style("stop-color",r).style("stop-opacity",u),h.append("stop").attr("offset",`${c}%`).style("stop-color",r).style("stop-opacity",0)})}),s.append("pattern").attr("id",Ke.stripedPattern).attr("width",5).attr("height",3).attr("patternUnits","userSpaceOnUse").attr("patternTransform","rotate(45)").append("rect").attr("width",1).attr("height",4).attr("transform","translate(0,0)").attr("fill",this.forbiddenIntervalColor)},initUtcOffset(){const s=this.startDate||this.oldestEvent.timestamp||this.oldestEvent.startDate;this.utcOffset=We.parseZone(s).utcOffset()},initTimeScale(s,e){const t=s||this.startDate||this.oldestEvent.timestamp||this.oldestEvent.startDate,i=e||this.endDate||this.latestEvent.timestamp||this.latestEvent.endDate;this.timeScale=I.scaleTime().domain([this.tzStringToDate(t),this.tzStringToDate(i)]).range([0,this.timeline.offsetWidth]),this.initialTimeScale=this.timeScale.copy(),this.updateCurrentTimeScaleDensity()},initXAxes(){let s=0;const e=5;for(const t in this.xAxesConfig){const i=this.createAxis(t);this.xAxes[t]=i,this.svg.append("g").classed(G.xAxis,!0).classed(`${G.xAxis}-${t}`,!0).attr("transform",`translate(0, ${s||e})`).call(i),this.translateTicksText(t),s+=this.axisHeight}this.updateXAxes()},updateXAxes(){let s=0;const e=5;for(const t in this.xAxesConfig){const i=this.xAxes[t];i.tickSizeOuter(0),i.tickSizeInner(this.timelineHeight),this.svg.select(`.${G.xAxis}-${t}`).attr("transform",`translate(0, ${s||e})`).call(i),this.translateTicksText(t),s+=this.axisHeight}},initYScale(){this.yScale=I.scaleLinear().range([this.chartHeight,0]),this.updateYScaleDomain()},updateYScaleDomain(){const[s,e]=this.timeScale.domain(),t=this.flattenedCounts.filter(r=>{const n=new Date(r.startDate||r.timestamp),a=new Date(r.endDate||r.timestamp);return a>=s&&a<=e||n>=s&&n<=e}),i=I.max(t,r=>r.count);this.yScale.domain([0,i])},initZoomBehavior(){this.disableZoom||(this.zoomBehavior=I.zoom().on("zoom",this.handleZoom).scaleExtent([this.minZoom,this.maxZoom]),this.svg.call(this.zoomBehavior),this.svg.call(this.zoomBehavior.transform,I.zoomIdentity))},zoomToFitMarkers(){const s=this.markers.map(u=>new Date(u.timestamp).getTime());if(s.length<2)return;const e=Math.min(...s),t=Math.max(...s),i=this.initialTimeScale.domain().map(u=>u.getTime()),r=i[1]-i[0],n=t-e,a=.1*n,o=n+2*a;let l=r/o;const c=this.zoomBehavior.scaleExtent();l=Math.min(Math.max(l,c[0]),c[1]),this.svg.transition().duration(this.fitMarkersTransitionDuration/2).call(this.zoomBehavior.scaleTo,l).on("end",()=>this.translateMarkersIntoView(e,t,l))},translateMarkersIntoView(s,e,t){const i=this.timeScale(new Date(s)),r=this.timeScale(new Date(e)),n=(i+r)/2,o=this.svg.node().getBoundingClientRect().width/2-n,l=I.zoomTransform(this.svg.node());this.svg.transition().duration(this.fitMarkersTransitionDuration/2).call(this.zoomBehavior.transform,I.zoomIdentity.translate(l.x+o,l.y).scale(t))},initSelectedTimestampCursor(){this.svg.append("line").attr("class",G.selectedTimestampCursor).style("stroke","red").style("stroke-width","1px").style("opacity",0).attr("x1",0).attr("x2",0).attr("y1",0),this.repositionSelectedTimestampCursor()},updateMarkers(){if(!this.markers.length)return;const s=12,e=200;this.sortedMarkers.forEach((t,i,r)=>{const n=typeof t.timestamp=="string"?this.tzStringToDate(t.timestamp):t.timestamp,a=this.timeScale(n);let o=!1;const l=this.stickyMarkers?Math.max(a,i*s):a;if(i<r.length-1){const c=r[i+1],u=typeof c.timestamp=="string"?this.tzStringToDate(c.timestamp):c.timestamp,h=this.timeScale(u);o=(this.stickyMarkers?Math.max(h,(i+1)*s):a)-l<e+s}this.markersPositions={...this.markersPositions,[t.id]:{isHidden:o,position:l}}}),this.initMarkersDragBehavior()},updateAndRedrawTimeline(){this.updateTimeline()},clearTimeline(){this.svg&&this.svg.remove(),this.countsByTimestamp={}},repositionSelectedTimestampCursor(){const s=this.svg.select(`.${G.selectedTimestampCursor}`);if(!this.selectedTimestamp){s.style("opacity",0);return}const e=this.tzStringToDate(this.selectedTimestamp),t=this.timeScale(e);isNaN(t)?s.style("opacity",0):s.attr("x1",t).attr("x2",t).style("opacity",.5),s.attr("y2",this.timelineHeight)},updateCurrentTimeScaleDensity(){const s=this.timeScale.invert(0).getTime(),e=this.timeScale.invert(1).getTime(),t=36e5,i=(e-s)/t;isNaN(i)||(this.currentTimeScaleDensity=i)},registerEventsListeners(){document.addEventListener("mouseup",this.handleDocumentMouseUp),this.svg.on("mousedown",this.handleMouseDown),this.svg.on("mousemove",this.handleMouseMove),this.svg.on("click",this.handleClick),this.svg.on("mouseleave",this.handleMouseLeave)},emitVisibleInterval(s){const e=this.timeScale.invert(0),t=this.timeScale.invert(this.timeline.offsetWidth);if(this.visibleFrom&&this.visibleFrom.getTime()===e.getTime()&&this.visibleTo&&this.visibleTo.getTime()===t.getTime())return;this.visibleFrom=e,this.visibleTo=t;const i=this.dateToTzString(this.visibleFrom),r=this.dateToTzString(this.visibleTo);this.$emit("visible-interval-change",{fromDate:i,toDate:r,trigger:s,transform:this.transformDiff})},createAxis(s){const e=this.xAxesConfig[s],t=this.getAxisTicksConfig(e);return I.axisBottom(this.timeScale).ticks(t.interval).tickFormat(t.formatFn).tickSizeOuter(0).tickSizeInner(this.timelineHeight)},getAxisTicksConfig(s){const{interval:e,format:t}=s.find(r=>r.precision>=this.currentTimeScaleDensity&&r.interval);return{formatFn:r=>typeof t=="function"?t(r):I.timeFormat(t)(r),interval:e}},onResize(s){this.isFirstPaint?(this.handleResize(s),this.isFirstPaint=!1):this.debouncedOnResize(s)},handleResize({contentRect:s}){this.svg&&(this.svg.attr("width",s.width),this.updateAndRedrawTimeline())},handleDarkModeChange(){if(!this.showLabels)return;const s=this;this.svg.selectAll(`.${G.labelBg}`).each(function(){I.select(this).style("fill",s.dark?"black":"white")}),this.svg.selectAll(`.${G.labelBgFill}`).each(function(){const e=I.select(this),t=e.node().dataset.color;e.style("fill",s.getLabelBackgroundColor(t)).style("stroke",s.getTextFillColor(t)).style("stroke-width",.25)}),this.svg.selectAll(`.${G.labelText}`).each(function(){const e=I.select(this),t=e.node().dataset.color;e.style("fill",s.getTextFillColor(t))})},handleMouseDown(){this.isMouseDown=!0},handleDocumentMouseUp(s){this.isMouseDown=!1},handleMouseLeave(){this.isHoveringTimeline=!1,this.$emit("hovered-timestamp",void 0)},handleMouseMove(s){if(this.isMouseDown)return;const e=s.offsetX;if(e<=this.minHoverZone){this.isHoveringTimeline=!1;return}const t=this.timeScale.invert(e);this.hoveredTimestamp=this.dateToTzString(t),this.isHoveringTimeline=!0,this.$emit("hovered-timestamp",this.hoveredTimestamp),this.cursor.style.left=e+"px",this.tooltip&&(this.eventTooltipStyle={left:`${e}px`,bottom:`${this.timeline.getBoundingClientRect().height}px`,zIndex:100})},handleClick(s){const e=s.offsetX;if(e<=this.minHoverZone)return;const t=this.timeScale.invert(e),i=this.dateToTzString(t);this.$emit("date-clicked",i),this.isHoveringEvent&&this.$emit("event-clicked",{event:this.hoveredEvent,type:this.hoveredEventType}),this.panOnDateClick&&this.panToTimestamp(i)},handleMarkerClick(s){this.$emit("marker-clicked",s),this.panOnDateClick&&this.panToTimestamp(s.timestamp)},handleLineMouseOver(s,e,t){this.hoveredCounts=Object.entries(this.countsByTimestamp[`${e.timestamp}`]).reduce((i,r)=>{const[n,a]=r;return[...i,{type:n,count:a}]},[]),this.hoveredEvent=e,this.isHoveringEvent=!0,this.$emit("event-mouseover",{eventData:e,eventType:t,hoveredCounts:this.hoveredCounts})},handleLineMouseOut(){this.isHoveringEvent=!1,this.hoveredCounts=[],this.$emit("event-mouseout")},handleBarMouseOver(s,e,t){s.offsetX<=this.minHoverZone||(this.hoveredEvent=e,this.hoveredEventType=t,this.isHoveringEvent=!0,this.$emit("event-mouseover",{eventData:e,eventType:t}))},handleBarMouseOut(){this.isHoveringEvent=!1,this.hoveredEvent=null,this.$emit("event-mouseout")},handleLabelMouseOver(s){I.selectAll(`.${G.lineGraphGroup}-${s}`).classed(`${G.lineGraphGroup}--highlighted`,!0),I.selectAll(`.${G.lineGraphGroupLabel}`).classed(`${G.lineGraphGroupLabel}--highlighted`,!0)},handleLabelMouseLeave(s){I.selectAll(`.${G.lineGraphGroup}-${s}`).classed(`${G.lineGraphGroup}--highlighted`,!1),I.selectAll(`.${G.lineGraphGroupLabel}`).classed(`${G.lineGraphGroupLabel}--highlighted`,!1)},isZoomAllowed(s){const e=this.initialTimeScale.copy(),t=s.transform.rescaleX(e).domain(),i=this.minDate?this.tzStringToDate(this.minDate):void 0,r=this.maxDate?this.tzStringToDate(this.maxDate):void 0;return(!i||t[0]>=i)&&(!r||t[1]<=r)},handleZoom(s){if(!this.isZoomAllowed(s)){s.sourceEvent.preventDefault(),this.svg.call(this.zoomBehavior.transform,this.lastValidTransform);return}this.lastValidTransform=s.transform;const e=s.transform.rescaleX(this.initialTimeScale);this.timeScale.domain(e.domain()),this.updateCurrentTimeScaleDensity(),this.updateYScaleDomain();const t=s.transform.k/this.lastTransform.k;this.transformDiff={scale:t,translation:s.transform.x-this.lastTransform.x},this.lastTransform={...s.transform};for(const i in this.xAxes)this.rescaleAxis(i,e),this.translateTicksText(i);this.updateEventsBars(),this.updateLineGraphs(),this.updateBarChart(),this.updateLineGraphHoverZones(),this.updateMilestonesPositions(),this.repositionSelectedTimestampCursor(),this.updateForbiddenIntervals(),this.updateMarkers(),this.emitVisibleInterval(gt.zoom),this.curtains&&this.emitCurtainChange()},panToTimestamp(s){const e=this.tzStringToDate(s),t=this.timeScale(e),i=I.zoomTransform(this.svg.node()),r=i.x-t+this.timeline.offsetWidth/2;this.svg.transition().duration(this.panTransitionDuration).call(this.zoomBehavior.transform,I.zoomIdentity.translate(r,0).scale(i.k)),this.emitVisibleInterval(gt.autoPan)},emitCurtainChange(){const{startDate:s,endDate:e}=this.calculateDateRangeFromCurtains();this.$emit("curtain-range-change",{startDate:new Date(s).toISOString(),endDate:new Date(e).toISOString()})},calculateDateRangeFromCurtains(){const s=this.timeline.offsetWidth,e=this.timeScale.domain(),t=e[1].getTime()-e[0].getTime(),i=(this.leftCurtainWidth-this.curtainHandleWidth*2)/s*t,r=(this.rightCurtainWidth+this.curtainHandleWidth*2)/s*t,n=new Date(e[0].getTime()+i),a=new Date(e[1].getTime()-r);return{startDate:n,endDate:a}},handleDragStart(){this.isDraggingCurtain=!0},handleDragEnd(){this.isDraggingCurtain=!1},handleLeftDrag(s){s.sourceEvent.stopPropagation();const e=Math.min(s.x,this.timeline.offsetWidth-this.rightCurtainWidth);this.leftCurtainWidth=Math.max(0,e),this.svg.select(`.${G.curtain}--left`).attr("width",this.leftCurtainWidth),this.emitCurtainChange()},handleRightDrag(s){s.sourceEvent.stopPropagation();const e=this.timeline.offsetWidth,t=Math.min(this.timeline.offsetWidth-s.x,this.timeline.offsetWidth-this.leftCurtainWidth),i=e-t;this.rightCurtainWidth=Math.max(0,t),this.svg.select(`.${G.curtain}--right`).attr("width",this.rightCurtainWidth).attr("x",i),this.emitCurtainChange()},zoomToStartAndEndDates(){const s=this.startDate||this.oldestEvent.timestamp||this.oldestEvent.startDate,e=this.endDate||this.latestEvent.timestamp||this.latestEvent.endDate,t=this.tzStringToDate(s),i=this.tzStringToDate(e);this.initialTimeScale.domain([t,i]);const r=I.zoomTransform(this.svg.node()),n=i.getTime()-t.getTime(),o=this.initialTimeScale.range().map(f=>this.initialTimeScale.invert(f)).reduce((f,m)=>m.getTime()-f,0)/n*r.k,c=-(this.initialTimeScale(t)*o),[u,h]=this.zoomBehavior.scaleExtent(),d=Math.max(u,Math.min(h,o));this.svg.transition().duration(this.zoomToBoundariesTransitionDuration).call(this.zoomBehavior.transform,I.zoomIdentity.translate(c,0).scale(d))},rescaleAxis(s,e){const t=this.xAxes[s],i=this.getAxisTicksConfig(this.xAxesConfig[s]);t.scale(e).ticks(i.interval).tickFormat(i.formatFn).tickSizeOuter(0),this.svg.select(`.${G.xAxis}-${s}`).call(t)},translateTicksText(s){this.svg.select(`.${G.xAxis}-${s}`).selectAll(".tick text").each(function(){let e=I.select(this),t=e.node().getBBox();e.attr("x",t.height/2).attr("y",0).style("text-anchor","start")})},updateEventsBars(){const s=`.${G.eventGroup} > rect.${G.eventRect}`,e=`${s}:not(.${G.eventRect}--dot)`;this.svg.selectAll(s).attr("x",this.getEventRectX),this.svg.selectAll(e).attr("width",this.getEventRectWidth);const t=`.${G.eventGroup} > text.${G.eventRectText}`;this.svg.selectAll(t).attr("x",i=>this.getEventRectX(i)+this.textPadding).text(this.getEventText)},updateBarChart(){const s=Object.keys(this.barChartGroups).length;Object.keys(this.barChartGroups).forEach((e,t)=>{const i=d=>(this.getEventRectWidth(d)-this.barXPadding*2)/s,r=d=>this.yScale.range()[0]-this.yScale(d.count),n=d=>this.getEventRectX(d)+this.barXPadding+t*i(d),a=d=>this.yScale(d.count),o=`.${G.eventBarContainer}-${e}`,l=this.svg.selectAll(o),c=`.${G.barChartGroup} rect.${G.eventBarHoverZone}`;l.selectAll(c).attr("x",n).attr("width",i);const u=`.${G.barChartGroup} rect.${G.eventBar}`;l.selectAll(u).attr("x",n).attr("width",i).attr("y",a).attr("height",r);const h=`.${G.barChartGroup} rect.${G.eventBarCap}`;l.selectAll(h).attr("x",n).attr("width",i).attr("y",a)})},updateLineGraphs(){Object.entries(this.lineGraphGroups).forEach(([s])=>{const e=I.area().x(t=>this.timeScale(this.tzStringToDate(t.timestamp))).y0(this.timelineHeight).y1(t=>this.yScale(t.count)).curve(I.curveMonotoneX);this.svg.selectAll(`.${G.lineGraphPath}-${s}`).attr("d",t=>e(t))})},updateLineGraphHoverZones(){Object.keys(this.lineGraphGroups).forEach(s=>{const e=this;this.svg.selectAll(`.${G.lineGraphDot}-${s}`).each(function(t){I.select(this).attr("cx",e.timeScale(e.tzStringToDate(t.timestamp))).attr("cy",e.yScale(t.count))}),this.svg.selectAll(`.${G.lineGraphHoverZone}-${s}`).each(function(t){const i=e.timeScale(e.tzStringToDate(t.timestamp).getTime())-15;I.select(this).attr("x",i).attr("y",0).attr("width",30).attr("height",e.chartHeight)})})},getEventRectX(s){return isNaN(this.timeScale(this.tzStringToDate(s.startDate||s.timestamp)))?0:this.timeScale(this.tzStringToDate(s.startDate||s.timestamp))},getEventRectWidth(s){if(!s)return 0;if(s.startDate&&s.endDate){const e=new Date(s.startDate),t=new Date(s.endDate),i=this.timeScale(t)-this.timeScale(e);return Math.max(i,this.rectMinWidth)}else{const e=1/(this.currentTimeScaleDensity*3600);return Math.max(e,this.rectMinWidth)}},getEventText(s){var i;const t=(this.getEventRectWidth(s)-this.textPadding)/this.characterWidth;return t<4?"":((i=s.text)==null?void 0:i.length)<=t?s.text:`${s.text.slice(0,t-3)}...`},getElementLeftPosition(s){if(!s)return 0;const e=window.getComputedStyle(s);return parseInt(e.left)},isTimestampAllowedForMarker(s,e){return(e.minDate?s>=this.tzStringToDate(e.minDate):!0)&&(e.maxDate?s<=this.tzStringToDate(e.maxDate):!0)},handleMarkerDrag({marker:s,markerElement:e,dragEvent:t}){if(!s.isDraggable)return;t.type==="start"&&(this.initialMarkerDragMouseOffset=t.x-e.node().querySelector(`.${G.markerLine}`).getBoundingClientRect().left,e.classed(G.markerDragged,!0));const i=t.x-this.initialMarkerDragMouseOffset,r=this.timeScale.invert(i-this.svg.node().getBoundingClientRect().left),n=this.timeScale(r),a=this.isTimestampAllowedForMarker(r,s);if(t.type==="drag"&&a&&e.attr("style",`left: ${n}px`),t.type==="end"&&a){const o=s.id||s.timestamp;this.markersPositions={...this.markersPositions,[o]:{...this.markersPositions[o],position:n}},e.classed(G.markerDragged,!1)}t.type!=="start"&&this.$emit(`marker-drag-${t.type}`,{marker:s,newTimestamp:r.toISOString()})},removeMarkersDragBehavior(){this.markersDragBehavior&&(this.markersDragBehavior.on("start",null).on("drag",null).on("end",null),I.selectAll(`.${G.marker}`).call(this.markersDragBehavior))},initMarkersDragBehavior(){this.removeMarkersDragBehavior();const s=this;this.markersDragBehavior=I.drag().on("start",function(e,t){var i;(i=e.sourceEvent)==null||i.preventDefault(),s.handleMarkerDrag({marker:t,markerElement:I.select(this),dragEvent:e})}).on("drag",function(e,t){s.handleMarkerDrag({marker:t,markerElement:I.select(this),dragEvent:e})}).on("end",function(e,t){s.handleMarkerDrag({marker:t,markerElement:I.select(this),dragEvent:e})}),I.selectAll(`.${G.marker}`).data(this.sortedMarkers).call(this.markersDragBehavior)},initCurtains(){this.createCurtains(),this.updateCurtains()},createCurtains(){this.curtains&&(this.svg.append("rect").classed(`${G.curtain} ${G.curtain}--left`,!0).attr("fill","rgba(0, 0, 0, 0.5)").on("mouseenter",()=>this.isHoveringCurtain=!0).on("mouseleave",()=>this.isHoveringCurtain=!1).call(I.drag().on("start",this.handleDragStart).on("drag",this.handleLeftDrag).on("end",this.handleDragEnd)),this.svg.append("rect").classed(`${G.curtain} ${G.curtain}--right`,!0).attr("fill","rgba(0, 0, 0, 0.5)").on("mouseenter",()=>this.isHoveringCurtain=!0).on("mouseleave",()=>this.isHoveringCurtain=!1).call(I.drag().on("start",this.handleDragStart).on("drag",this.handleRightDrag).on("end",this.handleDragEnd)),this.updateCurtains())},updateCurtains(){const s=this.timeline.offsetWidth,e=this.timelineHeight;this.svg.select(`.${G.curtain}--left`).attr("width",this.leftCurtainWidth).attr("height",e+this.curtainHandleWidth*2).attr("y",-this.curtainHandleWidth).attr("x",-this.curtainHandleWidth),this.svg.select(`.${G.curtain}--right`).attr("x",s-this.rightCurtainWidth+this.curtainHandleWidth).attr("y",-this.curtainHandleWidth).attr("width",this.rightCurtainWidth+this.curtainHandleWidth*2).attr("height",e+this.curtainHandleWidth*2)},updateForbiddenIntervals(s=!1){s&&this.svg.selectAll(`.${G.forbiddenInterval}`).remove();const e=this.timeScale.domain();this.forbiddenIntervals.forEach((t,i)=>{const r=t.startDate===-1/0?e[0]:this.tzStringToDate(t.startDate),n=t.endDate===1/0?e[1]:this.tzStringToDate(t.endDate),a=this.timeScale(r),o=this.timeScale(n),l=Math.max(o-a,0);let c=this.svg.select(`.${G.forbiddenInterval}-${i}`);c.empty()&&(c=this.svg.append("rect").attr("class",`${G.forbiddenInterval} ${G.forbiddenInterval}-${i}`).attr("fill",`url(#${Ke.stripedPattern})`)),c.attr("x",a).attr("y",0).attr("width",l).attr("height",this.timelineHeight)})},drawEventsGroups(){this.svg.selectAll(`g.${G.eventGroup}`).remove(),this.svg.selectAll(`.${G.barChartGroup}`).remove(),this.svg.selectAll(`.${G.lineGraphGroup}`).remove(),this.svg.selectAll(`.${G.lineGraphGroupLabel}`).remove(),this.svg.selectAll(`.${G.loadingIndicator}`).remove(),this.drawLineGraphEventsGroups(),this.drawBarEventsGroups(),this.drawBarChartEventsGroups(),this.drawMilestonesPlaceholder()},drawLineGraphEventsGroups(){const s=this.combinedXAxesHeight+this.chartsYOffset,e=this.insertZerosAtInterval?this.filledGapsLineGraphGroups:this.lineGraphGroups;Object.entries(e).forEach(([t,i])=>{const r=this.svg.append("g").classed(`${G.lineGraphGroup} ${G.lineGraphGroup}-${t}`,!0).attr("transform",`translate(0,${s})`),{color:n,events:a}=i;this.drawLineGraph({events:a,gElement:r,color:n,type:t}),this.drawLineGraphHoverZones({events:a,gElement:r,color:n,type:t})}),Object.entries(this.lineGraphGroups).forEach(([t,i],r)=>{const{color:n,isLoading:a,label:o}=i,l=Math.max(this.chartMinLabelHeight,this.barChartHeight),c=this.chartHeight-l*(r+1),u=s+this.chartHeight-l,h=this.svg.append("g").classed(G.lineGraphGroupLabel,!0).attr("transform",`translate(0,${s})`).on("mouseover",()=>this.handleLabelMouseOver(t)).on("mouseleave",()=>this.handleLabelMouseLeave(t));this.drawProgressIndicator({type:t,color:n,isLoading:a,yPosition:u}),this.drawTextLabel({color:n,label:o,type:t,height:l,yPosition:c,gElement:h})})},drawLineGraph({events:s,gElement:e,color:t,type:i}){const r=I.area().x(a=>this.timeScale(this.tzStringToDate(a.timestamp))).y0(this.timelineHeight).y1(a=>this.yScale(a.count)).curve(I.curveMonotoneX),n=`clip-${i}`;e.append("defs").append("clipPath").attr("id",n).append("rect").attr("width",this.timeline.offsetWidth).attr("height",this.chartHeight),e.append("path").datum(s).classed(`${G.lineGraphPath}-${i}`,!0).attr("fill",`url(#${Ke.transparencyGradientLight}-${i})`).attr("stroke",t).attr("stroke-linejoin","round").attr("stroke-linecap","round").attr("stroke-width",1).attr("d",a=>r(a)).attr("clip-path",`url(#${n})`)},drawLineGraphHoverZones({events:s,gElement:e,color:t,type:i}){s.forEach(r=>{const n=`${r.timestamp}`;this.countsByTimestamp[n]={...this.countsByTimestamp[n]||{},[i]:r.count};const a=e.append("circle").classed(`${G.lineGraphDot} ${G.lineGraphDot}-${i}`,!0).attr("cx",this.timeScale(this.tzStringToDate(r.timestamp))).attr("cy",this.yScale(r.count)).attr("r",1.5).attr("fill",t).attr("stroke-width",0).datum(r);this.dotsByTimestamp[n]=[...this.dotsByTimestamp[n]||[],a],e.append("rect").classed(`${G.lineGraphHoverZone}-${i}`,!0).attr("x",this.timeScale(this.tzStringToDate(r.timestamp))-15).attr("y",0).attr("width",30).attr("height",this.chartHeight).attr("fill","transparent").datum(r).on("mouseover",o=>{this.handleLineMouseOver(o,r,i),this.dotsByTimestamp[n].forEach(l=>l.classed(`${G.lineGraphDot}--active`,!0))}).on("mouseout",()=>{this.handleLineMouseOut(),this.dotsByTimestamp[n].forEach(o=>o.classed(`${G.lineGraphDot}--active`,!1))})})},drawSingleBarEventsGroup({type:s,eventsGroup:e,milestone:t,dots:i,dotsSize:r,bottom:n}){const{color:a,bgColor:o,label:l,events:c,barBorderRadius:u,isLoading:h,height:d,chartType:f}=e;let m=this.getBarGroupYPosition(s,n);const y=[Se.bars,Se.dots,void 0].includes(f)?this.getBarGroupHeight(e):d;t&&(m=this.getMilestoneGroupYPosition(s)),this.drawProgressIndicator({yPosition:m,type:s,color:a,isLoading:h});const v=this.svg.append("g").attr("data-color",a).classed(G.eventGroup,!0).classed(`${G.eventGroup}-${s}`,!0);if(this.drawBackground({color:o||a,gElement:v,yPosition:m,height:y}),t||i){const T=i?.5:2,x=m+y/2;v.append("line").classed(qe.milestoneLine,!0).attr("x1",0).attr("x2",this.timeline.offsetWidth).attr("y1",x).attr("y2",x).style("stroke",a).style("stroke-width",T)}this.drawBars({events:c,color:a,gElement:v,yPosition:m,type:s,dots:i,dotsSize:r,height:d,barBorderRadius:u}),l&&this.drawTextLabel({color:a,label:l,type:s,gElement:v,yPosition:m,height:d})},drawBarEventsGroups(){Object.entries(this.barGroups).forEach(([s,e])=>this.drawSingleBarEventsGroup({type:s,eventsGroup:e,bottom:e.bottom,dots:e.chartType===Se.dots,dotsSize:e.dotsSize||3}))},drawMilestonesPlaceholder(){Object.entries(this.milestonesGroups).forEach(([s,e])=>this.drawSingleBarEventsGroup({type:s,eventsGroup:{...e,events:[],isLoading:!1},milestone:!0})),this.updateMilestonesPositions()},getMilestoneClass(s){return{[qe.milestoneSelected]:[s.id,s.timestamp].includes(this.selectedMilestoneId)}},getMilestoneColors(s,e){return{background:s||e,border:this.getTextFillColor(s||e,.25)}},getMilestoneGroupYPosition(s){let e=0;for(const[t,i]of Object.entries(this.milestonesGroups)){if(t===s)break;e+=i.height||this.barChartHeight}return this.combinedXAxesHeight+this.milestonesYOffset+e},getBarGroupYPosition(s,e){let t=this.combinedXAxesHeight;e?t+=(this.hasChart?this.chartHeight:0)+(this.hasMilestones?this.combinedMilestonesHeight:0):t+=this.barsYOffset;for(const[i,r]of Object.entries(this.barGroups)){if(i===s)break;!e&&r.bottom||(t+=this.getBarGroupHeight(r))}return t},getBarGroupHeight(s){return s.height?Math.max(s.height+this.barYPadding,1):this.barChartHeight},updateMilestonesPositions(){Object.entries(this.milestonesGroups).forEach(([s,e])=>{const t=this.getMilestoneGroupYPosition(s),i=this.svg.select(`g.${G.eventGroup}-${s}`),r=2,a=(e.height||this.barChartHeight)/2,o=t+a-r/2;i.attr("x1",0).attr("x2",this.timeline.offsetWidth).select(`.${qe.milestoneLine}`).attr("y1",o).attr("y2",o);const l=I.select(`.${qe.milestonesContainer}-${s}`);l.style("top",`${t}px`).style("height",`${e.height||this.barChartHeight}px`);const c=l.selectAll(`.${qe.milestone}`).data(this.getSortedEvents(e.events));c.exit().remove(),c.enter().append("div").merge(c).style("left",u=>`${this.timeScale(this.tzStringToDate(u.timestamp))}px`).style("top",`${o}px`)})},drawBarChartEventsGroups(){const s=this.combinedXAxesHeight,e=this.barChartGroups;Object.entries(e).forEach(([t,i],r)=>{const n=this.svg.append("g").classed(`${G.barChartGroup} ${G.barChartGroup}-${t}`,!0).attr("transform",`translate(0,${s})`),{color:a,events:o}=i;this.drawBarsChart({events:o,color:a,gElement:n,yOffset:s,type:t,index:r})})},drawProgressIndicator({yPosition:s,type:e,isLoading:t}){this.svg.append("rect").classed(`${G.loadingIndicator} ${G.loadingIndicator}-${e}`,!0).attr("x",0).attr("y",s).attr("width",this.timeline.offsetWidth/3).attr("height",this.barChartHeight).attr("fill",`url(#${Ke.loadingGradient}-${e})`).style("visibility",t?"visible":"hidden")},drawBackground({color:s,yPosition:e,gElement:t,height:i}){t.append("rect").attr("class",G.eventGroupBg).attr("x",0).attr("y",e).attr("width",this.timeline.offsetWidth).attr("height",i||this.barChartHeight).attr("fill",I.color(s).toString()).style("opacity",.1)},drawBars({events:s,gElement:e,yPosition:t,color:i,type:r,dots:n,dotsSize:a,height:o,barBorderRadius:l=1.5}){const c=this,u=t+this.barYPadding/2,h=n?((o||this.barChartHeight)-a)/2:0;let d=Math.max((o!=null?o:this.barChartHeight)-this.barYPadding,1);n&&(d=a),e.selectAll(G.eventRect).data(s).enter().append("rect").attr("class",f=>G.eventRect+(n?` ${G.eventRect}--dot`:"")+(f.className?` ${f.className}`:"")).attr("x",this.getEventRectX).attr("y",u+h).attr("ry",n?a:l).attr("rx",n?a:l).attr("width",n?a:this.getEventRectWidth).attr("height",d).attr("stroke-width",5).attr("cursor","pointer").attr("stroke","#0000").style("fill",f=>f.color||i).on("mouseover",function(f,m){I.select(this).classed(G.eventRectHovered,!0),c.handleBarMouseOver(f,m,r)}).on("mouseout",function(){I.select(this).classed(G.eventRectHovered,!1),c.handleBarMouseOut()}),e.selectAll(G.eventRectText).data(s.filter(f=>!!f.text)).enter().append("text").attr("class",G.eventRectText).attr("x",f=>this.getEventRectX(f)+this.textPadding).attr("y",t+this.barChartHeight/2).attr("dy","0.35em").style("text-anchor","start").style("font-size","12px").style("font-weight",600).style("stroke-linejoin","round").style("paint-order","stroke").style("pointer-events","none").style("fill",f=>this.getTextFillColor(f.color||i,.75)).text(this.getEventText)},drawBarsChart({events:s,gElement:e,color:t,yOffset:i,type:r,index:n}){const a=this,o=Object.keys(this.barChartGroups).length,l=f=>(this.getEventRectWidth(f)-this.barXPadding*2)/o,c=f=>this.yScale.range()[0]-this.yScale(f.count),u=f=>this.getEventRectX(f)+this.barXPadding+n*l(f),h=f=>this.yScale(f.count),d=e.selectAll(G.eventBarContainer).data(s).enter().append("g").attr("class",`${G.eventBarContainer} ${G.eventBarContainer}-${r}`);d.append("rect").attr("class",f=>G.eventBarHoverZone+(f.className?` ${f.className}`:"")).attr("x",u).attr("y",-i).attr("width",l).attr("height",this.yScale.range()[0]+i).attr("fill",f=>f.color||t).attr("fill-opacity",0),d.append("rect").attr("class",f=>G.eventBar+(f.className?` ${f.className}`:"")).attr("x",u).attr("y",h).attr("width",l).attr("height",c).attr("stroke-width",5).attr("cursor","pointer").attr("stroke","#0000").attr("fill",`url(#${Ke.transparencyGradient}-${r})`),d.append("rect").attr("class",f=>G.eventBarCap+(f.className?` ${f.className}`:"")).attr("x",u).attr("y",h).attr("width",l).attr("height",2).attr("stroke-width",0).style("fill",f=>f.color||t),d.on("mouseover",function(f,m){const g=I.select(this);a.onBarChartBarMouseOver(g,t),a.handleBarMouseOver(f,m,r)}).on("mouseout",function(){const f=I.select(this);a.onBarChartBarMouseOut(f,r),a.handleBarMouseOut()}).on("click",function(){e.selectAll(`.${G.eventBarContainerSelected}`).classed(G.eventBarContainerSelected,!1),I.select(this).classed(G.eventBarContainerSelected,!0)})},onBarChartBarMouseOver(s,e){s.classed(G.eventBarContainerHovered,!0),s.selectAll(`.${G.eventBarHoverZone}`).attr("fill-opacity",.2);const i=s.selectAll(`.${G.eventBar}`);i.attr("fill",e),i.attr("fill-opacity",.5)},onBarChartBarMouseOut(s,e){s.classed(G.eventBarContainerHovered,!1),s.selectAll(`.${G.eventBarHoverZone}`).attr("fill-opacity",0);const i=s.selectAll(`.${G.eventBar}`);i.attr("fill",`url(#${Ke.transparencyGradient}-${e})`),i.attr("fill-opacity",1)},drawTextLabel({gElement:s,yPosition:e,color:t,label:i,type:r,height:n}){if(!this.showLabels)return;const a={x:-5,y:e,w:this.labelRectWidth,h:n||this.barChartHeight,radius:3},o=s.append("g").attr("class",`${G.labelGroup} ${G.labelGroup}-${r}`).style("cursor","pointer").on("click",()=>this.toggleGroupVisibility(r));o.append("rect").attr("class",G.labelBg).attr("data-color",t).attr("x",a.x).attr("y",a.y).attr("width",a.w).attr("height",a.h).attr("rx",a.radius).attr("ry",a.radius).style("fill",this.dark?"#131a29":"white"),o.append("rect").attr("class",G.labelBgFill).attr("data-color",t).attr("x",a.x).attr("y",a.y).attr("width",a.w).attr("height",a.h).attr("rx",a.radius).attr("ry",a.radius).style("fill",this.getLabelBackgroundColor(t)).style("stroke",this.getTextFillColor(t)).style("stroke-width",.25),o.append("text").attr("class",G.labelText).attr("data-color",t).attr("x",5).attr("y",e+(n||this.barChartHeight)/2).attr("dy","0.35em").style("text-anchor","start").style("font-size","12px").style("font-weight",500).style("stroke-linejoin","round").style("paint-order","stroke").style("fill",this.getTextFillColor(t)).text(i)},getTextFillColor(s,e=0){var t,i;return(this.dark?(t=I.color(s))==null?void 0:t.brighter(1.5+e):(i=I.color(s))==null?void 0:i.darker(2+e)).toString()},getLabelBackgroundColor(s){let e=I.color(s);return e.opacity=this.dark?.2:.5,e.toString()},getCurrentGroupVisibility(s){var i;const e=this.groupsVisibility[s];if(e!==void 0)return e;const t=(i=this.eventsGroups[s])==null?void 0:i.isHidden;return t!==void 0?!t:!0},toggleGroupVisibility(s){this.groupsVisibility={...this.groupsVisibility,[s]:!this.getCurrentGroupVisibility(s)}},getExternalLabelStyles(s){const e=this.eventsGroups[s].color;return{background:this.getLabelBackgroundColor(e),color:this.getTextFillColor(e)}},getExternalLabelWrapperStyles(s){const e=this.eventsGroups[s].color;return{borderColor:this.getTextFillColor(e)}},getMarkerClass(s){var e;return{"marker--hidden":(e=this.markersPositions[s==null?void 0:s.id])==null?void 0:e.isHidden,"marker--draggable":s==null?void 0:s.isDraggable,...s.className?{[s==null?void 0:s.className]:!0}:{}}},getMarkerContainerStyle(s){var e;return{left:`${(e=this.markersPositions[s.id])==null?void 0:e.position}px`}},getMarkerLabelStyle(s){return{background:s.color,color:s.textColor||""}},getMarkerLineStyle(s){return{background:s.color,height:`${this.timelineHeight+24}px`}},tzStringToDate(s){return We(s).add(this.utcOffset,"minutes").toDate()},dateToTzString(s){const e=new Date(s).getTimezoneOffset();return We(s).add(e,"minutes").utcOffset(this.utcOffset,!0).format()},getCurrentTimeBounds(){const s=this.timeScale.domain();return{startDate:s[0],endDate:s[1]}},getFormattedTimestamp(s){return We.parseZone(s).format("YYYY-MM-DDTHH:mm:ss")},fillTimeGaps(s){if(s.length<=1)return s;const e=this.insertZerosAtInterval,t=n=>n.clone().add(1,e),i=n=>n.clone().subtract(1,e);let r=[];for(let n=0;n<s.length;n++){const a=s[n];if(r.push(a),n===s.length-1)break;const o=s[n+1],l=We(a.timestamp),c=We(o.timestamp);if(c.diff(l,e)>1){const u=t(l).toISOString(),h=i(c).toISOString();r.push({timestamp:u,count:0}),u!==h&&r.push({timestamp:h,count:0})}}if(this.flattenLineGraphEnds){const n=We(s[0].timestamp),a=We(s[s.length-1].timestamp),o=i(n).toISOString(),l=t(a).toISOString();r=[{timestamp:o,count:0},...r,{timestamp:l,count:0}]}return r},fillEvents(s){return this.placeholderLineChartGroup.map(e=>s.find(i=>i.timestamp===e.timestamp)||e)},onMilestoneClick(s,e){this.panOnDateClick&&this.panToTimestamp(s.timestamp),this.selectedMilestoneId=s.id||s.timestamp,this.$emit("milestone-click",{milestone:s,milestoneType:e})},getSortedEvents(s){return[...s].sort((e,t)=>new Date(e.timestamp||e.startDate)>new Date(t.timestamp||t.startDate)?1:-1)}}}),ed="";var Uh=function(){var e=this,t=e._self._c;return t("div",{ref:"wrapperDiv",staticClass:"e-relative e-timeline e-border e-rounded",class:e.classes.wrapper},[t("div",{staticClass:"e-timeline__background e-w-full e-h-full e-absolute e-top-0 e-rounded",class:e.classes.background}),e._l(e.sortedMarkers,function(i){return t("div",{key:i.id,staticClass:"marker e-absolute e-h-full e-top-0",class:e.getMarkerClass(i),style:e.getMarkerContainerStyle(i),attrs:{"data-id":i.id},on:{click:function(r){return e.handleMarkerClick(i)}}},[t("div",{staticClass:"marker-label e-absolute"},[t("div",{staticClass:"marker-label-text",style:e.getMarkerLabelStyle(i)},[e._t(`marker.${i.id}`,function(){return[e._v(" "+e._s(i.label)+" ")]},{marker:i})],2)]),t("div",{staticClass:"marker-line e-absolute e-pointer-events-none",style:e.getMarkerLineStyle(i)})])}),e.autoResize?t("div",{directives:[{name:"resize-observer",rawName:"v-resize-observer",value:e.onResize,expression:"onResize"}],ref:"timelineContainer",staticClass:"e-timeline__svg-container e-relative e-h-13 e-rounded e-select-none e-overflow-x-hidden"}):t("div",{ref:"timelineContainer",staticClass:"e-timeline__svg-container e-relative e-h-13 e-rounded e-select-none e-overflow-x-hidden"}),e._l(e.milestonesGroups,function(i,r){return t("div",{key:`${r}`,staticClass:"e-timeline-milestones"},[t("div",{class:`e-tl-milestones e-tl-milestones-${r}`},e._l(e.getSortedEvents(i.events),function(n,a){return t("ETimelineMilestone",{key:`${n.milestoneType}-${a}`,class:e.getMilestoneClass(n),attrs:{"data-timestamp":n.timestamp,milestone:n,dot:i.dots,size:n.size||e.milestoneBulletSize,"transition-duration":i.milestonesTransitionDuration,"line-height":i.milestonesLineHeight,"dot-size":i.milestonesDotSize,"background-color":e.getMilestoneColors(n.color,i.color).background,"border-color":e.getMilestoneColors(n.color,i.color).border},on:{"milestone-click":function(o){return e.onMilestoneClick(n,r)}},scopedSlots:e._u([{key:"content",fn:function(){return[e._t(`milestoneContent.${n.milestoneType}`,function(){return[t("span",{staticClass:"e-px-2"},[e._v(" "+e._s(n.text)+" ")])]},{milestone:n,index:a})]},proxy:!0},{key:"label",fn:function(){return[e._t(`milestoneLabel.${n.milestoneType}`,null,{milestone:n})]},proxy:!0}],null,!0)})}),1)])}),t("div",{directives:[{name:"show",rawName:"v-show",value:e.isHoveringTimeline&&!e.isInteractingWithCurtain,expression:"isHoveringTimeline && !isInteractingWithCurtain"}],ref:"cursor",staticClass:"e-timeline__cursor e-absolute e-bg-green-600 e-w-px e-h-full e-top-0 e-pointer-events-none"}),t("div",{staticClass:"external-labels-container e-flex"},e._l(e.hiddenGroupsLabels,function(i){return t("div",{key:i,staticClass:"external-label",class:e.classes.background,style:e.getExternalLabelWrapperStyles(i),on:{click:function(r){return e.toggleGroupVisibility(i)}}},[t("div",{staticClass:"external-label__content",style:e.getExternalLabelStyles(i)},[e._v(" "+e._s(i)+" ")])])}),0),t("div",{key:"tooltip",ref:"tooltip",staticClass:"e-absolute",style:e.eventTooltipStyle},[e._t("tooltip",function(){return[t("div",{directives:[{name:"show",rawName:"v-show",value:e.isHoveringTimeline&&!e.isHoveringEvent&&!e.isInteractingWithCurtain&&!e.cursorTimestamp,expression:`
27
27
  isHoveringTimeline &&
28
28
  !isHoveringEvent &&
29
29
  !isInteractingWithCurtain &&