···11-MIT License
22-33-Copyright (c) 2026 Tao Bojlén
44-55-Permission is hereby granted, free of charge, to any person obtaining a copy
66-of this software and associated documentation files (the "Software"), to deal
77-in the Software without restriction, including without limitation the rights
88-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
99-copies of the Software, and to permit persons to whom the Software is
1010-furnished to do so, subject to the following conditions:
1111-1212-The above copyright notice and this permission notice shall be included in all
1313-copies or substantial portions of the Software.
1414-1515-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1616-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1717-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1818-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1919-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2020-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2121-SOFTWARE.
+23-17
README.md
···11-# AtmosphereConf 2026 TV
11+# AtmosphereConf 2026 Talks
2233-Watch [AtmosphereConf 2026](https://atmosphereconf.org/) talks.
33+A straightforward interface to view [AtmosphereConf 2026](https://atmosphereconf.org/) talks. Supports linking to individual talks.
4455A submission for the [@stream.place VOD jam](https://blog.stream.place/3micfu6ifyk2a).
6677-## Development
77+This repo is a single-page app using Preact, Tailwind, and Vite for building an interface to view ATmosphereConf 2026 talks.
88+99+## Generate Type Definitions
81099-Run the development server:
1111+Before running the app, generate ATProto type definitions:
10121113```bash
1212-npm run dev
1414+ts-lex install com.atproto.repo.listRecords
1515+ts-lex build
1316```
14171515-This will start a development server at `http://localhost:8080` with:
1616-- Hot module replacement
1717-- Fast builds
1818-- Error overlay
1818+This will handle all the hard parts of generating type definitions for ATProto.
19192020-## Building for Production
2020+## Development
21212222-Build the site for production:
2222+Run the development server:
23232424```bash
2525-npm run build
2525+npx wispctl serve --path ./build --spa
2626+```
2727+2828+## Deploying to Wisp
2929+3030+```bash
3131+npx wispctl deploy --path ./build --spa
2632```
27332834This will:
···3036- Optimize and minify assets
3137- Generate files in the `build/` directory
32383333-## Preview Production Build
3939+## Credits
34403535-Preview the production build locally:
4141+Forked from https://tangled.org/btao.org/atmosphereconf-tv, thank you!
36423737-```bash
3838-npm run preview
3939-```
4343+AI agents used: Claude, Devstral, GLM-5.
4444+4545+License: MIT
+55-41
build/index.html
···3030 />
31313232 <style>/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */
3333-@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-white:#fff;--spacing:.25rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--font-weight-semibold:600;--tracking-wide:.025em;--tracking-widest:.1em;--leading-tight:1.25;--radius-lg:.5rem;--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.pointer-events-none{pointer-events:none}.absolute{position:absolute}.relative{position:relative}.inset-0{inset:calc(var(--spacing) * 0)}.top-4{top:calc(var(--spacing) * 4)}.right-5{right:calc(var(--spacing) * 5)}.bottom-2\.5{bottom:calc(var(--spacing) * 2.5)}.bottom-4{bottom:calc(var(--spacing) * 4)}.left-1\/2{left:50%}.left-4{left:calc(var(--spacing) * 4)}.z-7{z-index:7}.z-10{z-index:10}.m-0{margin:calc(var(--spacing) * 0)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.ml-2{margin-left:calc(var(--spacing) * 2)}.flex{display:flex}.hidden{display:none}.h-screen{height:100vh}.min-h-\[100px\]{min-height:100px}.w-0{width:calc(var(--spacing) * 0)}.w-\[400px\]{width:400px}.w-full{width:100%}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-\[400px\]{min-width:400px}.flex-1{flex:1}.shrink-0{flex-shrink:0}.-translate-x-1\/2{--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.cursor-pointer{cursor:pointer}.flex-col{flex-direction:column}.flex-row{flex-direction:row}.items-center{align-items:center}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-3{gap:calc(var(--spacing) * 3)}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-lg{border-radius:var(--radius-lg)}.border{border-style:var(--tw-border-style);border-width:1px}.border-r-0{border-right-style:var(--tw-border-style);border-right-width:0}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-l-\[3px\]{border-left-style:var(--tw-border-style);border-left-width:3px}.border-\[\#7dd3fc\]{border-color:#7dd3fc}.border-\[rgba\(125\,211\,252\,0\.2\)\]{border-color:#7dd3fc33}.border-\[rgba\(125\,211\,252\,0\.3\)\]{border-color:#7dd3fc4d}.border-\[rgba\(125\,211\,252\,0\.4\)\]{border-color:#7dd3fc66}.border-l-\[\#7dd3fc\]{border-left-color:#7dd3fc}.border-l-\[rgba\(125\,211\,252\,0\.6\)\]{border-left-color:#7dd3fc99}.bg-\[\#0a0806\]{background-color:#0a0806}.bg-\[\#1a1a1a\]{background-color:#1a1a1a}.bg-\[rgba\(125\,211\,252\,0\.15\)\]{background-color:#7dd3fc26}.bg-transparent{background-color:#0000}.object-contain{object-fit:contain}.p-1{padding:calc(var(--spacing) * 1)}.p-2\.5{padding:calc(var(--spacing) * 2.5)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-5{padding-inline:calc(var(--spacing) * 5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-4{padding-block:calc(var(--spacing) * 4)}.pb-2{padding-bottom:calc(var(--spacing) * 2)}.text-center{text-align:center}.font-sans{font-family:var(--font-sans)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[11px\]{font-size:11px}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.tracking-widest{--tw-tracking:var(--tracking-widest);letter-spacing:var(--tracking-widest)}.text-\[\#7dd3fc\]{color:#7dd3fc}.text-\[rgba\(125\,211\,252\,0\.5\)\]{color:#7dd3fc80}.text-\[rgba\(125\,211\,252\,0\.6\)\]{color:#7dd3fc99}.text-\[rgba\(125\,211\,252\,0\.7\)\]{color:#7dd3fcb3}.text-white\/25{color:#ffffff40}@supports (color:color-mix(in lab, red, red)){.text-white\/25{color:color-mix(in oklab, var(--color-white) 25%, transparent)}}.no-underline{text-decoration-line:none}.opacity-0{opacity:0}.opacity-100{opacity:1}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-150{--tw-duration:.15s;transition-duration:.15s}.duration-300{--tw-duration:.3s;transition-duration:.3s}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.\[background\:linear-gradient\(45deg\,\#0a0806_0\%\,\#1a1410_50\%\,\#0a0806_100\%\)\]{background:linear-gradient(45deg,#0a0806 0%,#1a1410 50%,#0a0806 100%)}.last\:border-r:last-child{border-right-style:var(--tw-border-style);border-right-width:1px}.last\:border-\[rgba\(125\,211\,252\,0\.3\)\]:last-child{border-color:#7dd3fc4d}@media (hover:hover){.hover\:border-\[rgba\(125\,211\,252\,0\.6\)\]:hover{border-color:#7dd3fc99}.hover\:border-l-\[\#7dd3fc\]:hover{border-left-color:#7dd3fc}.hover\:bg-\[rgba\(125\,211\,252\,0\.1\)\]:hover{background-color:#7dd3fc1a}.hover\:bg-\[rgba\(125\,211\,252\,0\.2\)\]:hover{background-color:#7dd3fc33}.hover\:bg-\[rgba\(125\,211\,252\,0\.08\)\]:hover{background-color:#7dd3fc14}.hover\:text-white\/50:hover{color:#ffffff80}@supports (color:color-mix(in lab, red, red)){.hover\:text-white\/50:hover{color:color-mix(in oklab, var(--color-white) 50%, transparent)}}.hover\:underline:hover{text-decoration-line:underline}}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}</style>
3434- <script type="module" crossorigin>(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const r of i)if(r.type==="childList")for(const a of r.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&s(a)}).observe(document,{childList:!0,subtree:!0});function t(i){const r={};return i.integrity&&(r.integrity=i.integrity),i.referrerPolicy&&(r.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?r.credentials="include":i.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(i){if(i.ep)return;i.ep=!0;const r=t(i);fetch(i.href,r)}})();var Us,ae,ta,tt,vr,sa,ia,ra,Ki,yi,Ei,na,As={},_s=[],sl=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,qt=Array.isArray;function Ze(n,e){for(var t in e)n[t]=e[t];return n}function Vi(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function Is(n,e,t){var s,i,r,a={};for(r in e)r=="key"?s=e[r]:r=="ref"?i=e[r]:a[r]=e[r];if(arguments.length>2&&(a.children=arguments.length>3?Us.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(r in n.defaultProps)a[r]===void 0&&(a[r]=n.defaultProps[r]);return ds(n,a,s,i,null)}function ds(n,e,t,s,i){var r={type:n,props:e,key:t,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++ta,__i:-1,__u:0};return i==null&&ae.vnode!=null&&ae.vnode(r),r}function jt(n){return n.children}function fs(n,e){this.props=n,this.context=e}function bt(n,e){if(e==null)return n.__?bt(n.__,n.__i+1):null;for(var t;e<n.__k.length;e++)if((t=n.__k[e])!=null&&t.__e!=null)return t.__e;return typeof n.type=="function"?bt(n):null}function il(n){if(n.__P&&n.__d){var e=n.__v,t=e.__e,s=[],i=[],r=Ze({},e);r.__v=e.__v+1,ae.vnode&&ae.vnode(r),Hi(n.__P,r,e,n.__n,n.__P.namespaceURI,32&e.__u?[t]:null,s,t??bt(e),!!(32&e.__u),i),r.__v=e.__v,r.__.__k[r.__i]=r,ha(s,r,i),e.__e=e.__=null,r.__e!=t&&aa(r)}}function aa(n){if((n=n.__)!=null&&n.__c!=null)return n.__e=n.__c.base=null,n.__k.some(function(e){if(e!=null&&e.__e!=null)return n.__e=n.__c.base=e.__e}),aa(n)}function Ti(n){(!n.__d&&(n.__d=!0)&&tt.push(n)&&!Ls.__r++||vr!=ae.debounceRendering)&&((vr=ae.debounceRendering)||sa)(Ls)}function Ls(){try{for(var n,e=1;tt.length;)tt.length>e&&tt.sort(ia),n=tt.shift(),e=tt.length,il(n)}finally{tt.length=Ls.__r=0}}function oa(n,e,t,s,i,r,a,o,c,l,h){var u,d,f,g,p,y,E,T=s&&s.__k||_s,S=e.length;for(c=rl(t,e,T,c,S),u=0;u<S;u++)(f=t.__k[u])!=null&&(d=f.__i!=-1&&T[f.__i]||As,f.__i=u,y=Hi(n,f,d,i,r,a,o,c,l,h),g=f.__e,f.ref&&d.ref!=f.ref&&(d.ref&&Wi(d.ref,null,f),h.push(f.ref,f.__c||g,f)),p==null&&g!=null&&(p=g),(E=!!(4&f.__u))||d.__k===f.__k?c=la(f,c,n,E):typeof f.type=="function"&&y!==void 0?c=y:g&&(c=g.nextSibling),f.__u&=-7);return t.__e=p,c}function rl(n,e,t,s,i){var r,a,o,c,l,h=t.length,u=h,d=0;for(n.__k=new Array(i),r=0;r<i;r++)(a=e[r])!=null&&typeof a!="boolean"&&typeof a!="function"?(typeof a=="string"||typeof a=="number"||typeof a=="bigint"||a.constructor==String?a=n.__k[r]=ds(null,a,null,null,null):qt(a)?a=n.__k[r]=ds(jt,{children:a},null,null,null):a.constructor===void 0&&a.__b>0?a=n.__k[r]=ds(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):n.__k[r]=a,c=r+d,a.__=n,a.__b=n.__b+1,o=null,(l=a.__i=nl(a,t,c,u))!=-1&&(u--,(o=t[l])&&(o.__u|=2)),o==null||o.__v==null?(l==-1&&(i>h?d--:i<h&&d++),typeof a.type!="function"&&(a.__u|=4)):l!=c&&(l==c-1?d--:l==c+1?d++:(l>c?d--:d++,a.__u|=4))):n.__k[r]=null;if(u)for(r=0;r<h;r++)(o=t[r])!=null&&!(2&o.__u)&&(o.__e==s&&(s=bt(o)),da(o,o));return s}function la(n,e,t,s){var i,r;if(typeof n.type=="function"){for(i=n.__k,r=0;i&&r<i.length;r++)i[r]&&(i[r].__=n,e=la(i[r],e,t,s));return e}n.__e!=e&&(s&&(e&&n.type&&!e.parentNode&&(e=bt(n)),t.insertBefore(n.__e,e||null)),e=n.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ca(n,e){return e=e||[],n==null||typeof n=="boolean"||(qt(n)?n.some(function(t){ca(t,e)}):e.push(n)),e}function nl(n,e,t,s){var i,r,a,o=n.key,c=n.type,l=e[t],h=l!=null&&(2&l.__u)==0;if(l===null&&o==null||h&&o==l.key&&c==l.type)return t;if(s>(h?1:0)){for(i=t-1,r=t+1;i>=0||r<e.length;)if((l=e[a=i>=0?i--:r++])!=null&&!(2&l.__u)&&o==l.key&&c==l.type)return a}return-1}function xr(n,e,t){e[0]=="-"?n.setProperty(e,t??""):n[e]=t==null?"":typeof t!="number"||sl.test(e)?t:t+"px"}function zt(n,e,t,s,i){var r,a;e:if(e=="style")if(typeof t=="string")n.style.cssText=t;else{if(typeof s=="string"&&(n.style.cssText=s=""),s)for(e in s)t&&e in t||xr(n.style,e,"");if(t)for(e in t)s&&t[e]==s[e]||xr(n.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")r=e!=(e=e.replace(ra,"$1")),a=e.toLowerCase(),e=a in n||e=="onFocusOut"||e=="onFocusIn"?a.slice(2):e.slice(2),n.l||(n.l={}),n.l[e+r]=t,t?s?t.u=s.u:(t.u=Ki,n.addEventListener(e,r?Ei:yi,r)):n.removeEventListener(e,r?Ei:yi,r);else{if(i=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in n)try{n[e]=t??"";break e}catch{}typeof t=="function"||(t==null||t===!1&&e[4]!="-"?n.removeAttribute(e):n.setAttribute(e,e=="popover"&&t==1?"":t))}}function Ar(n){return function(e){if(this.l){var t=this.l[e.type+n];if(e.t==null)e.t=Ki++;else if(e.t<t.u)return;return t(ae.event?ae.event(e):e)}}}function Hi(n,e,t,s,i,r,a,o,c,l){var h,u,d,f,g,p,y,E,T,S,v,x,D,A,b,I=e.type;if(e.constructor!==void 0)return null;128&t.__u&&(c=!!(32&t.__u),r=[o=e.__e=t.__e]),(h=ae.__b)&&h(e);e:if(typeof I=="function")try{if(E=e.props,T=I.prototype&&I.prototype.render,S=(h=I.contextType)&&s[h.__c],v=h?S?S.props.value:h.__:s,t.__c?y=(u=e.__c=t.__c).__=u.__E:(T?e.__c=u=new I(E,v):(e.__c=u=new fs(E,v),u.constructor=I,u.render=ol),S&&S.sub(u),u.state||(u.state={}),u.__n=s,d=u.__d=!0,u.__h=[],u._sb=[]),T&&u.__s==null&&(u.__s=u.state),T&&I.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=Ze({},u.__s)),Ze(u.__s,I.getDerivedStateFromProps(E,u.__s))),f=u.props,g=u.state,u.__v=e,d)T&&I.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),T&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(T&&I.getDerivedStateFromProps==null&&E!==f&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(E,v),e.__v==t.__v||!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(E,u.__s,v)===!1){e.__v!=t.__v&&(u.props=E,u.state=u.__s,u.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(_){_&&(_.__=e)}),_s.push.apply(u.__h,u._sb),u._sb=[],u.__h.length&&a.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(E,u.__s,v),T&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(f,g,p)})}if(u.context=v,u.props=E,u.__P=n,u.__e=!1,x=ae.__r,D=0,T)u.state=u.__s,u.__d=!1,x&&x(e),h=u.render(u.props,u.state,u.context),_s.push.apply(u.__h,u._sb),u._sb=[];else do u.__d=!1,x&&x(e),h=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++D<25);u.state=u.__s,u.getChildContext!=null&&(s=Ze(Ze({},s),u.getChildContext())),T&&!d&&u.getSnapshotBeforeUpdate!=null&&(p=u.getSnapshotBeforeUpdate(f,g)),A=h!=null&&h.type===jt&&h.key==null?ua(h.props.children):h,o=oa(n,qt(A)?A:[A],e,t,s,i,r,a,o,c,l),u.base=e.__e,e.__u&=-161,u.__h.length&&a.push(u),y&&(u.__E=u.__=null)}catch(_){if(e.__v=null,c||r!=null)if(_.then){for(e.__u|=c?160:128;o&&o.nodeType==8&&o.nextSibling;)o=o.nextSibling;r[r.indexOf(o)]=null,e.__e=o}else{for(b=r.length;b--;)Vi(r[b]);Si(e)}else e.__e=t.__e,e.__k=t.__k,_.then||Si(e);ae.__e(_,e,t)}else r==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=al(t.__e,e,t,s,i,r,a,c,l);return(h=ae.diffed)&&h(e),128&e.__u?void 0:o}function Si(n){n&&(n.__c&&(n.__c.__e=!0),n.__k&&n.__k.some(Si))}function ha(n,e,t){for(var s=0;s<t.length;s++)Wi(t[s],t[++s],t[++s]);ae.__c&&ae.__c(e,n),n.some(function(i){try{n=i.__h,i.__h=[],n.some(function(r){r.call(i)})}catch(r){ae.__e(r,i.__v)}})}function ua(n){return typeof n!="object"||n==null||n.__b>0?n:qt(n)?n.map(ua):Ze({},n)}function al(n,e,t,s,i,r,a,o,c){var l,h,u,d,f,g,p,y=t.props||As,E=e.props,T=e.type;if(T=="svg"?i="http://www.w3.org/2000/svg":T=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),r!=null){for(l=0;l<r.length;l++)if((f=r[l])&&"setAttribute"in f==!!T&&(T?f.localName==T:f.nodeType==3)){n=f,r[l]=null;break}}if(n==null){if(T==null)return document.createTextNode(E);n=document.createElementNS(i,T,E.is&&E),o&&(ae.__m&&ae.__m(e,r),o=!1),r=null}if(T==null)y===E||o&&n.data==E||(n.data=E);else{if(r=r&&Us.call(n.childNodes),!o&&r!=null)for(y={},l=0;l<n.attributes.length;l++)y[(f=n.attributes[l]).name]=f.value;for(l in y)f=y[l],l=="dangerouslySetInnerHTML"?u=f:l=="children"||l in E||l=="value"&&"defaultValue"in E||l=="checked"&&"defaultChecked"in E||zt(n,l,null,f,i);for(l in E)f=E[l],l=="children"?d=f:l=="dangerouslySetInnerHTML"?h=f:l=="value"?g=f:l=="checked"?p=f:o&&typeof f!="function"||y[l]===f||zt(n,l,f,y[l],i);if(h)o||u&&(h.__html==u.__html||h.__html==n.innerHTML)||(n.innerHTML=h.__html),e.__k=[];else if(u&&(n.innerHTML=""),oa(e.type=="template"?n.content:n,qt(d)?d:[d],e,t,s,T=="foreignObject"?"http://www.w3.org/1999/xhtml":i,r,a,r?r[0]:t.__k&&bt(t,0),o,c),r!=null)for(l=r.length;l--;)Vi(r[l]);o||(l="value",T=="progress"&&g==null?n.removeAttribute("value"):g!=null&&(g!==n[l]||T=="progress"&&!g||T=="option"&&g!=y[l])&&zt(n,l,g,y[l],i),l="checked",p!=null&&p!=n[l]&&zt(n,l,p,y[l],i))}return n}function Wi(n,e,t){try{if(typeof n=="function"){var s=typeof n.__u=="function";s&&n.__u(),s&&e==null||(n.__u=n(e))}else n.current=e}catch(i){ae.__e(i,t)}}function da(n,e,t){var s,i;if(ae.unmount&&ae.unmount(n),(s=n.ref)&&(s.current&&s.current!=n.__e||Wi(s,null,e)),(s=n.__c)!=null){if(s.componentWillUnmount)try{s.componentWillUnmount()}catch(r){ae.__e(r,e)}s.base=s.__P=null}if(s=n.__k)for(i=0;i<s.length;i++)s[i]&&da(s[i],e,t||typeof n.type!="function");t||Vi(n.__e),n.__c=n.__=n.__e=void 0}function ol(n,e,t){return this.constructor(n,t)}function ll(n,e,t){var s,i,r,a;e==document&&(e=document.documentElement),ae.__&&ae.__(n,e),i=(s=!1)?null:e.__k,r=[],a=[],Hi(e,n=e.__k=Is(jt,null,[n]),i||As,As,e.namespaceURI,i?null:e.firstChild?Us.call(e.childNodes):null,r,i?i.__e:e.firstChild,s,a),ha(r,n,a)}function cl(n){function e(t){var s,i;return this.getChildContext||(s=new Set,(i={})[e.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){s=null},this.shouldComponentUpdate=function(r){this.props.value!=r.value&&s.forEach(function(a){a.__e=!0,Ti(a)})},this.sub=function(r){s.add(r);var a=r.componentWillUnmount;r.componentWillUnmount=function(){s&&s.delete(r),a&&a.call(r)}}),t.children}return e.__c="__cC"+na++,e.__=n,e.Provider=e.__l=(e.Consumer=function(t,s){return t.children(s)}).contextType=e,e}Us=_s.slice,ae={__e:function(n,e,t,s){for(var i,r,a;e=e.__;)if((i=e.__c)&&!i.__)try{if((r=i.constructor)&&r.getDerivedStateFromError!=null&&(i.setState(r.getDerivedStateFromError(n)),a=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(n,s||{}),a=i.__d),a)return i.__E=i}catch(o){n=o}throw n}},ta=0,fs.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Ze({},this.state),typeof n=="function"&&(n=n(Ze({},t),this.props)),n&&Ze(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),Ti(this))},fs.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),Ti(this))},fs.prototype.render=jt,tt=[],sa=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ia=function(n,e){return n.__v.__b-e.__v.__b},Ls.__r=0,ra=/(PointerCapture)$|Capture$/i,Ki=0,yi=Ar(!1),Ei=Ar(!0),na=0;var hl=0;function Z(n,e,t,s,i,r){e||(e={});var a,o,c=e;if("ref"in c)for(o in c={},e)o=="ref"?a=e[o]:c[o]=e[o];var l={type:n,props:c,key:t,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--hl,__i:-1,__u:0,__source:i,__self:r};if(typeof n=="function"&&(a=n.defaultProps))for(o in a)c[o]===void 0&&(c[o]=a[o]);return ae.vnode&&ae.vnode(l),l}var Dt,ce,Ys,_r,Rs=0,fa=[],fe=ae,Ir=fe.__b,Lr=fe.__r,Rr=fe.diffed,br=fe.__c,Dr=fe.unmount,Cr=fe.__;function $s(n,e){fe.__h&&fe.__h(ce,n,Rs||e),Rs=0;var t=ce.__H||(ce.__H={__:[],__h:[]});return n>=t.__.length&&t.__.push({}),t.__[n]}function rt(n){return Rs=1,ul(ma,n)}function ul(n,e,t){var s=$s(Dt++,2);if(s.t=n,!s.__c&&(s.__=[ma(void 0,e),function(o){var c=s.__N?s.__N[0]:s.__[0],l=s.t(c,o);c!==l&&(s.__N=[l,s.__[1]],s.__c.setState({}))}],s.__c=ce,!ce.__f)){var i=function(o,c,l){if(!s.__c.__H)return!0;var h=s.__c.__H.__.filter(function(d){return d.__c});if(h.every(function(d){return!d.__N}))return!r||r.call(this,o,c,l);var u=s.__c.props!==o;return h.some(function(d){if(d.__N){var f=d.__[0];d.__=d.__N,d.__N=void 0,f!==d.__[0]&&(u=!0)}}),r&&r.call(this,o,c,l)||u};ce.__f=!0;var r=ce.shouldComponentUpdate,a=ce.componentWillUpdate;ce.componentWillUpdate=function(o,c,l){if(this.__e){var h=r;r=void 0,i(o,c,l),r=h}a&&a.call(this,o,c,l)},ce.shouldComponentUpdate=i}return s.__N||s.__}function vi(n,e){var t=$s(Dt++,3);!fe.__s&&ga(t.__H,e)&&(t.__=n,t.u=e,ce.__H.__h.push(t))}function Mt(n){return Rs=5,dl(function(){return{current:n}},[])}function dl(n,e){var t=$s(Dt++,7);return ga(t.__H,e)&&(t.__=n(),t.__H=e,t.__h=n),t.__}function fl(n){var e=ce.context[n.__c],t=$s(Dt++,9);return t.c=n,e?(t.__==null&&(t.__=!0,e.sub(ce)),e.props.value):n.__}function gl(){for(var n;n=fa.shift();){var e=n.__H;if(n.__P&&e)try{e.__h.some(gs),e.__h.some(xi),e.__h=[]}catch(t){e.__h=[],fe.__e(t,n.__v)}}}fe.__b=function(n){ce=null,Ir&&Ir(n)},fe.__=function(n,e){n&&e.__k&&e.__k.__m&&(n.__m=e.__k.__m),Cr&&Cr(n,e)},fe.__r=function(n){Lr&&Lr(n),Dt=0;var e=(ce=n.__c).__H;e&&(Ys===ce?(e.__h=[],ce.__h=[],e.__.some(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.some(gs),e.__h.some(xi),e.__h=[],Dt=0)),Ys=ce},fe.diffed=function(n){Rr&&Rr(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&(fa.push(e)!==1&&_r===fe.requestAnimationFrame||((_r=fe.requestAnimationFrame)||ml)(gl)),e.__H.__.some(function(t){t.u&&(t.__H=t.u),t.u=void 0})),Ys=ce=null},fe.__c=function(n,e){e.some(function(t){try{t.__h.some(gs),t.__h=t.__h.filter(function(s){return!s.__||xi(s)})}catch(s){e.some(function(i){i.__h&&(i.__h=[])}),e=[],fe.__e(s,t.__v)}}),br&&br(n,e)},fe.unmount=function(n){Dr&&Dr(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.some(function(s){try{gs(s)}catch(i){e=i}}),t.__H=void 0,e&&fe.__e(e,t.__v))};var Pr=typeof requestAnimationFrame=="function";function ml(n){var e,t=function(){clearTimeout(s),Pr&&cancelAnimationFrame(e),setTimeout(n)},s=setTimeout(t,35);Pr&&(e=requestAnimationFrame(t))}function gs(n){var e=ce,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),ce=e}function xi(n){var e=ce;n.__c=n.__(),ce=e}function ga(n,e){return!n||n.length!==e.length||e.some(function(t,s){return t!==n[s]})}function ma(n,e){return typeof e=="function"?e(n):e}const pl="https://iameli.com",yl="did:plc:rbvrr34edl5ddpuwcubjiost",El="place.stream.video";async function Tl(){let n=[],e;do{const t=new URLSearchParams({repo:yl,collection:El,limit:"100"});e&&t.set("cursor",e);const s=await(await fetch(`${pl}/xrpc/com.atproto.repo.listRecords?${t}`)).json();n=n.concat(s.records||[]),e=s.cursor}while(e);return console.info(n),n.reverse()}function Sl(n){const e=Math.floor(n/3600),t=Math.floor(n%3600/60),s=n%60;return e>0?`${e}:${String(t).padStart(2,"0")}:${String(s).padStart(2,"0")}`:`${t}:${String(s).padStart(2,"0")}`}function vl(n){return new Date(n).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/Los_Angeles"})}function pa(n){return new Date(n.value.createdAt).toLocaleDateString("en-CA",{timeZone:"America/Los_Angeles"})}function xl(n){const[e,t,s]=n.split("-").map(Number);return new Date(e,t-1,s).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"})}function Al({days:n,selectedDay:e,onSelectDay:t}){return Z("div",{class:"flex w-full",children:n.map(s=>Z("button",{class:`flex-1 py-2 px-1 bg-transparent border border-[rgba(125,211,252,0.3)] border-r-0 last:border-r last:border-[rgba(125,211,252,0.3)] text-[rgba(125,211,252,0.7)] text-xs cursor-pointer transition-all duration-150 text-center hover:bg-[rgba(125,211,252,0.1)] ${s===e?"bg-[rgba(125,211,252,0.15)] border-[#7dd3fc] text-[#7dd3fc]":""}`,onClick:()=>t(s),children:xl(s)}))})}function _l({record:n,index:e,isSelected:t,onClick:s}){const i=n.value.title||"Unknown Programme",r=Math.round((n.value.duration||0)/1e9),a=r>0?` (${Sl(r)})`:"",o=vl(n.value.createdAt);return Z("div",{class:`bg-transparent border border-[rgba(125,211,252,0.4)] border-l-[3px] border-l-[rgba(125,211,252,0.6)] rounded p-2.5 flex flex-col gap-1 cursor-pointer transition-all duration-150 min-h-[100px] hover:bg-[rgba(125,211,252,0.08)] hover:border-[rgba(125,211,252,0.6)] hover:border-l-[#7dd3fc] ${t?"bg-[rgba(125,211,252,0.15)] border-[#7dd3fc] border-l-[#7dd3fc] hover:bg-[rgba(125,211,252,0.2)]":""}`,onClick:s,children:[Z("div",{class:"text-[11px] text-[rgba(125,211,252,0.5)] tracking-wide",children:o}),Z("div",{class:"text-sm text-[#7dd3fc] leading-tight",children:[i,a]})]})}function Il({vods:n,selectedDay:e,currentChannel:t,onSelectVideo:s}){const i=e?n.filter(o=>pa(o)===e):n,r=i.findIndex(o=>o.uri===t);let a="0/0";return i.length>0&&(a=r>=0?`${r+1}/${i.length}`:`${i.length} videos`),Z(jt,{children:[Z("div",{class:"text-lg text-[#7dd3fc] mb-3 pb-2 border-b border-[rgba(125,211,252,0.2)] flex justify-between items-center",children:Z("h3",{class:"m-0",children:["Available Videos",Z("span",{class:"text-sm text-[rgba(125,211,252,0.6)] ml-2",children:a})]})}),Z("div",{class:"flex flex-col gap-1.5 p-1",id:"videoListContainer",children:i.map((o,c)=>Z(_l,{record:o,index:c,isSelected:o.uri===t,onClick:()=>s(o.uri)},o.uri))})]})}function Ll(n){const e=new Map;for(const t of n){const s=pa(t);e.has(s)||e.set(s,[]),e.get(s).push(t)}return e}function Rl({vods:n,currentChannel:e,selectedDay:t,onSelectDay:s,onSelectVideo:i,collapsed:r}){const a=Ll(n),o=Array.from(a.keys()).sort();return Z("div",{class:`transition-all duration-300 ease-in-out overflow-hidden ${r?"w-0 min-w-0":"w-[400px] min-w-[400px]"} h-screen overflow-y-auto bg-[#1a1a1a]`,children:Z("div",{class:r?"opacity-0 pointer-events-none":"opacity-100",children:[Z(Al,{days:o,selectedDay:t,onSelectDay:s}),Z(Il,{vods:n,selectedDay:t,currentChannel:e,onSelectVideo:i})]})})}function bl({currentTitle:n,currentUri:e,isLoading:t,showStandby:s,videoRef:i,audioRef:r}){return Z("div",{class:"relative flex flex-1 flex-col",children:[Z("div",{class:"relative flex flex-col justify-center items-center overflow-hidden rounded-lg [background:linear-gradient(45deg,#0a0806_0%,#1a1410_50%,#0a0806_100%)]",children:[Z("video",{id:"video",ref:i,controls:!0,class:"w-full object-contain bg-[#0a0806]"}),Z("audio",{id:"audio",ref:r,preload:"none"}),Z("div",{class:`absolute top-4 left-4 z-10 transition-opacity duration-300 ${n?"opacity-100":"opacity-0"}`,id:"channelOverlay",children:n&&e&&Z("a",{class:"font-sans text-sm text-[#7dd3fc] no-underline hover:underline",href:`https://pds.ls/${e}`,target:"_blank",rel:"noopener",children:n})}),Z("div",{class:`absolute bottom-4 left-1/2 -translate-x-1/2 z-7 font-sans text-lg text-[#7dd3fc] transition-opacity duration-300 pointer-events-none ${t?"opacity-100":"opacity-0"}`,id:"loadingIndicator",children:"Loading..."}),Z("div",{class:`absolute inset-0 flex flex-col justify-center items-center [background:linear-gradient(45deg,#0a0806_0%,#1a1410_50%,#0a0806_100%)] ${s?"":"hidden"}`,id:"standby",children:Z("div",{class:"font-sans text-3xl font-semibold text-[#7dd3fc] tracking-widest",children:"ATmosphereConf 2026"})})]}),Z("a",{class:"font-sans text-xs text-white/25 no-underline mt-2 absolute bottom-2.5 right-5 hover:text-white/50",href:"https://tangled.org/timryan.org/atmosphereconf2026",target:"_blank",rel:"noopener",children:"View Source"})]})}/**
3333+@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-md:28rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--font-weight-medium:500;--font-weight-semibold:600;--tracking-wide:.025em;--tracking-widest:.1em;--leading-tight:1.25;--radius-lg:.5rem;--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.pointer-events-none{pointer-events:none}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.inset-0{inset:calc(var(--spacing) * 0)}.inset-y-0{inset-block:calc(var(--spacing) * 0)}.bottom-4{bottom:calc(var(--spacing) * 4)}.left-0{left:calc(var(--spacing) * 0)}.left-1\/2{left:50%}.z-10{z-index:10}.z-40{z-index:40}.z-50{z-index:50}.m-0{margin:calc(var(--spacing) * 0)}.mx-4{margin-inline:calc(var(--spacing) * 4)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.ml-2{margin-left:calc(var(--spacing) * 2)}.flex{display:flex}.hidden{display:none}.h-4{height:calc(var(--spacing) * 4)}.h-screen{height:100vh}.min-h-\[100px\]{min-height:100px}.w-0{width:calc(var(--spacing) * 0)}.w-4{width:calc(var(--spacing) * 4)}.w-fit{width:fit-content}.w-full{width:100%}.max-w-md{max-width:var(--container-md)}.min-w-0{min-width:calc(var(--spacing) * 0)}.flex-1{flex:1}.shrink-0{flex-shrink:0}.-translate-x-1\/2{--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.cursor-pointer{cursor:pointer}.flex-col{flex-direction:column}.flex-row{flex-direction:row}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-lg{border-radius:var(--radius-lg)}.border{border-style:var(--tw-border-style);border-width:1px}.border-r-0{border-right-style:var(--tw-border-style);border-right-width:0}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-l-\[3px\]{border-left-style:var(--tw-border-style);border-left-width:3px}.border-none{--tw-border-style:none;border-style:none}.border-\[rgba\(255\,255\,255\,0\.2\)\]{border-color:#fff3}.border-\[rgba\(255\,255\,255\,0\.3\)\]{border-color:#ffffff4d}.border-\[rgba\(255\,255\,255\,0\.4\)\]{border-color:#fff6}.border-\[rgba\(255\,255\,255\,0\.9\)\]{border-color:#ffffffe6}.border-white\/10{border-color:#ffffff1a}@supports (color:color-mix(in lab, red, red)){.border-white\/10{border-color:color-mix(in oklab, var(--color-white) 10%, transparent)}}.border-white\/20{border-color:#fff3}@supports (color:color-mix(in lab, red, red)){.border-white\/20{border-color:color-mix(in oklab, var(--color-white) 20%, transparent)}}.border-white\/30{border-color:#ffffff4d}@supports (color:color-mix(in lab, red, red)){.border-white\/30{border-color:color-mix(in oklab, var(--color-white) 30%, transparent)}}.border-l-\[rgba\(255\,255\,255\,0\.6\)\]{border-left-color:#fff9}.border-l-\[rgba\(255\,255\,255\,0\.9\)\]{border-left-color:#ffffffe6}.bg-\[\#0a0806\]{background-color:#0a0806}.bg-\[\#1a1a1a\]{background-color:#1a1a1a}.bg-\[\#7dd3fc\]{background-color:#7dd3fc}.bg-\[\#141414\]{background-color:#141414}.bg-\[rgba\(255\,255\,255\,0\.15\)\]{background-color:#ffffff26}.bg-black\/30{background-color:#0000004d}@supports (color:color-mix(in lab, red, red)){.bg-black\/30{background-color:color-mix(in oklab, var(--color-black) 30%, transparent)}}.bg-black\/50{background-color:#00000080}@supports (color:color-mix(in lab, red, red)){.bg-black\/50{background-color:color-mix(in oklab, var(--color-black) 50%, transparent)}}.bg-black\/70{background-color:#000000b3}@supports (color:color-mix(in lab, red, red)){.bg-black\/70{background-color:color-mix(in oklab, var(--color-black) 70%, transparent)}}.bg-transparent{background-color:#0000}.bg-white\/10{background-color:#ffffff1a}@supports (color:color-mix(in lab, red, red)){.bg-white\/10{background-color:color-mix(in oklab, var(--color-white) 10%, transparent)}}.object-contain{object-fit:contain}.p-1{padding:calc(var(--spacing) * 1)}.p-2\.5{padding:calc(var(--spacing) * 2.5)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-5{padding-inline:calc(var(--spacing) * 5)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-4{padding-block:calc(var(--spacing) * 4)}.pb-2{padding-bottom:calc(var(--spacing) * 2)}.text-center{text-align:center}.font-sans{font-family:var(--font-sans)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[11px\]{font-size:11px}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.tracking-widest{--tw-tracking:var(--tracking-widest);letter-spacing:var(--tracking-widest)}.whitespace-pre-wrap{white-space:pre-wrap}.text-\[\#7dd3fc\]{color:#7dd3fc}.text-\[rgba\(255\,255\,255\,0\.5\)\]{color:#ffffff80}.text-\[rgba\(255\,255\,255\,0\.6\)\]{color:#fff9}.text-\[rgba\(255\,255\,255\,0\.7\)\]{color:#ffffffb3}.text-\[rgba\(255\,255\,255\,0\.9\)\]{color:#ffffffe6}.text-black{color:var(--color-black)}.text-white{color:var(--color-white)}.text-white\/50{color:#ffffff80}@supports (color:color-mix(in lab, red, red)){.text-white\/50{color:color-mix(in oklab, var(--color-white) 50%, transparent)}}.text-white\/60{color:#fff9}@supports (color:color-mix(in lab, red, red)){.text-white\/60{color:color-mix(in oklab, var(--color-white) 60%, transparent)}}.text-white\/70{color:#ffffffb3}@supports (color:color-mix(in lab, red, red)){.text-white\/70{color:color-mix(in oklab, var(--color-white) 70%, transparent)}}.text-white\/80{color:#fffc}@supports (color:color-mix(in lab, red, red)){.text-white\/80{color:color-mix(in oklab, var(--color-white) 80%, transparent)}}.text-white\/90{color:#ffffffe6}@supports (color:color-mix(in lab, red, red)){.text-white\/90{color:color-mix(in oklab, var(--color-white) 90%, transparent)}}.no-underline{text-decoration-line:none}.accent-\[\#7dd3fc\]{accent-color:#7dd3fc}.opacity-0{opacity:0}.opacity-100{opacity:1}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-150{--tw-duration:.15s;transition-duration:.15s}.duration-300{--tw-duration:.3s;transition-duration:.3s}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.outline-none{--tw-outline-style:none;outline-style:none}.\[background\:linear-gradient\(45deg\,\#0a0806_0\%\,\#1a1410_50\%\,\#0a0806_100\%\)\]{background:linear-gradient(45deg,#0a0806 0%,#1a1410 50%,#0a0806 100%)}.last\:border-r:last-child{border-right-style:var(--tw-border-style);border-right-width:1px}.last\:border-\[rgba\(255\,255\,255\,0\.3\)\]:last-child{border-color:#ffffff4d}@media (hover:hover){.hover\:border-\[rgba\(255\,255\,255\,0\.6\)\]:hover{border-color:#fff9}.hover\:border-l-\[rgba\(255\,255\,255\,0\.9\)\]:hover{border-left-color:#ffffffe6}.hover\:bg-\[\#5cb8e0\]:hover{background-color:#5cb8e0}.hover\:bg-\[rgba\(125\,211\,252\,0\.1\)\]:hover{background-color:#7dd3fc1a}.hover\:bg-\[rgba\(255\,255\,255\,0\.1\)\]:hover{background-color:#ffffff1a}.hover\:bg-\[rgba\(255\,255\,255\,0\.2\)\]:hover{background-color:#fff3}.hover\:bg-\[rgba\(255\,255\,255\,0\.08\)\]:hover{background-color:#ffffff14}.hover\:bg-white\/20:hover{background-color:#fff3}@supports (color:color-mix(in lab, red, red)){.hover\:bg-white\/20:hover{background-color:color-mix(in oklab, var(--color-white) 20%, transparent)}}.hover\:text-\[rgba\(255\,255\,255\,0\.7\)\]:hover{color:#ffffffb3}.hover\:text-white:hover{color:var(--color-white)}.hover\:text-white\/70:hover{color:#ffffffb3}@supports (color:color-mix(in lab, red, red)){.hover\:text-white\/70:hover{color:color-mix(in oklab, var(--color-white) 70%, transparent)}}.hover\:text-white\/80:hover{color:#fffc}@supports (color:color-mix(in lab, red, red)){.hover\:text-white\/80:hover{color:color-mix(in oklab, var(--color-white) 80%, transparent)}}.hover\:underline:hover{text-decoration-line:underline}}@media (min-width:64rem){.lg\:relative{position:relative}.lg\:z-auto{z-index:auto}.lg\:hidden{display:none}.lg\:w-\[400px\]{width:400px}.lg\:min-w-\[400px\]{min-width:400px}}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}</style>
3434+ <script type="module" crossorigin>var gm=Object.defineProperty;var Wo=i=>{throw TypeError(i)};var mm=(i,e,t)=>e in i?gm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var w=(i,e,t)=>mm(i,typeof e!="symbol"?e+"":e,t),zo=(i,e,t)=>e.has(i)||Wo("Cannot "+t);var Yi=(i,e,t)=>(zo(i,e,"read from private field"),t?t.call(i):e.get(i)),Xi=(i,e,t)=>e.has(i)?Wo("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),Qi=(i,e,t,r)=>(zo(i,e,"write to private field"),r?r.call(i,t):e.set(i,t),t);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const n of s)if(n.type==="childList")for(const a of n.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function t(s){const n={};return s.integrity&&(n.integrity=s.integrity),s.referrerPolicy&&(n.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?n.credentials="include":s.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function r(s){if(s.ep)return;s.ep=!0;const n=t(s);fetch(s.href,n)}})();var on,le,oh,Ct,Yo,lh,uh,ch,Xa,Ta,ba,dh,Bs={},Us=[],pm=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ki=Array.isArray;function Tt(i,e){for(var t in e)i[t]=e[t];return i}function Qa(i){i&&i.parentNode&&i.parentNode.removeChild(i)}function $s(i,e,t){var r,s,n,a={};for(n in e)n=="key"?r=e[n]:n=="ref"?s=e[n]:a[n]=e[n];if(arguments.length>2&&(a.children=arguments.length>3?on.call(arguments,2):t),typeof i=="function"&&i.defaultProps!=null)for(n in i.defaultProps)a[n]===void 0&&(a[n]=i.defaultProps[n]);return Ds(i,a,r,s,null)}function Ds(i,e,t,r,s){var n={type:i,props:e,key:t,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:s??++oh,__i:-1,__u:0};return s==null&&le.vnode!=null&&le.vnode(n),n}function qi(i){return i.children}function Ls(i,e){this.props=i,this.context=e}function Qr(i,e){if(e==null)return i.__?Qr(i.__,i.__i+1):null;for(var t;e<i.__k.length;e++)if((t=i.__k[e])!=null&&t.__e!=null)return t.__e;return typeof i.type=="function"?Qr(i):null}function ym(i){if(i.__P&&i.__d){var e=i.__v,t=e.__e,r=[],s=[],n=Tt({},e);n.__v=e.__v+1,le.vnode&&le.vnode(n),Za(i.__P,n,e,i.__n,i.__P.namespaceURI,32&e.__u?[t]:null,r,t??Qr(e),!!(32&e.__u),s),n.__v=e.__v,n.__.__k[n.__i]=n,ph(r,n,s),e.__e=e.__=null,n.__e!=t&&hh(n)}}function hh(i){if((i=i.__)!=null&&i.__c!=null)return i.__e=i.__c.base=null,i.__k.some(function(e){if(e!=null&&e.__e!=null)return i.__e=i.__c.base=e.__e}),hh(i)}function xa(i){(!i.__d&&(i.__d=!0)&&Ct.push(i)&&!js.__r++||Yo!=le.debounceRendering)&&((Yo=le.debounceRendering)||lh)(js)}function js(){try{for(var i,e=1;Ct.length;)Ct.length>e&&Ct.sort(uh),i=Ct.shift(),e=Ct.length,ym(i)}finally{Ct.length=js.__r=0}}function fh(i,e,t,r,s,n,a,o,u,l,c){var d,h,f,g,p,m,v,y=r&&r.__k||Us,S=e.length;for(u=vm(t,e,y,u,S),d=0;d<S;d++)(f=t.__k[d])!=null&&(h=f.__i!=-1&&y[f.__i]||Bs,f.__i=d,m=Za(i,f,h,s,n,a,o,u,l,c),g=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&Ja(h.ref,null,f),c.push(f.ref,f.__c||g,f)),p==null&&g!=null&&(p=g),(v=!!(4&f.__u))||h.__k===f.__k?u=gh(f,u,i,v):typeof f.type=="function"&&m!==void 0?u=m:g&&(u=g.nextSibling),f.__u&=-7);return t.__e=p,u}function vm(i,e,t,r,s){var n,a,o,u,l,c=t.length,d=c,h=0;for(i.__k=new Array(s),n=0;n<s;n++)(a=e[n])!=null&&typeof a!="boolean"&&typeof a!="function"?(typeof a=="string"||typeof a=="number"||typeof a=="bigint"||a.constructor==String?a=i.__k[n]=Ds(null,a,null,null,null):Ki(a)?a=i.__k[n]=Ds(qi,{children:a},null,null,null):a.constructor===void 0&&a.__b>0?a=i.__k[n]=Ds(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):i.__k[n]=a,u=n+h,a.__=i,a.__b=i.__b+1,o=null,(l=a.__i=Em(a,t,u,d))!=-1&&(d--,(o=t[l])&&(o.__u|=2)),o==null||o.__v==null?(l==-1&&(s>c?h--:s<c&&h++),typeof a.type!="function"&&(a.__u|=4)):l!=u&&(l==u-1?h--:l==u+1?h++:(l>u?h--:h++,a.__u|=4))):i.__k[n]=null;if(d)for(n=0;n<c;n++)(o=t[n])!=null&&!(2&o.__u)&&(o.__e==r&&(r=Qr(o)),vh(o,o));return r}function gh(i,e,t,r){var s,n;if(typeof i.type=="function"){for(s=i.__k,n=0;s&&n<s.length;n++)s[n]&&(s[n].__=i,e=gh(s[n],e,t,r));return e}i.__e!=e&&(r&&(e&&i.type&&!e.parentNode&&(e=Qr(i)),t.insertBefore(i.__e,e||null)),e=i.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function mh(i,e){return e=e||[],i==null||typeof i=="boolean"||(Ki(i)?i.some(function(t){mh(t,e)}):e.push(i)),e}function Em(i,e,t,r){var s,n,a,o=i.key,u=i.type,l=e[t],c=l!=null&&(2&l.__u)==0;if(l===null&&o==null||c&&o==l.key&&u==l.type)return t;if(r>(c?1:0)){for(s=t-1,n=t+1;s>=0||n<e.length;)if((l=e[a=s>=0?s--:n++])!=null&&!(2&l.__u)&&o==l.key&&u==l.type)return a}return-1}function Xo(i,e,t){e[0]=="-"?i.setProperty(e,t??""):i[e]=t==null?"":typeof t!="number"||pm.test(e)?t:t+"px"}function Zi(i,e,t,r,s){var n,a;e:if(e=="style")if(typeof t=="string")i.style.cssText=t;else{if(typeof r=="string"&&(i.style.cssText=r=""),r)for(e in r)t&&e in t||Xo(i.style,e,"");if(t)for(e in t)r&&t[e]==r[e]||Xo(i.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")n=e!=(e=e.replace(ch,"$1")),a=e.toLowerCase(),e=a in i||e=="onFocusOut"||e=="onFocusIn"?a.slice(2):e.slice(2),i.l||(i.l={}),i.l[e+n]=t,t?r?t.u=r.u:(t.u=Xa,i.addEventListener(e,n?ba:Ta,n)):i.removeEventListener(e,n?ba:Ta,n);else{if(s=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in i)try{i[e]=t??"";break e}catch{}typeof t=="function"||(t==null||t===!1&&e[4]!="-"?i.removeAttribute(e):i.setAttribute(e,e=="popover"&&t==1?"":t))}}function Qo(i){return function(e){if(this.l){var t=this.l[e.type+i];if(e.t==null)e.t=Xa++;else if(e.t<t.u)return;return t(le.event?le.event(e):e)}}}function Za(i,e,t,r,s,n,a,o,u,l){var c,d,h,f,g,p,m,v,y,S,_,T,x,b,I,A=e.type;if(e.constructor!==void 0)return null;128&t.__u&&(u=!!(32&t.__u),n=[o=e.__e=t.__e]),(c=le.__b)&&c(e);e:if(typeof A=="function")try{if(v=e.props,y=A.prototype&&A.prototype.render,S=(c=A.contextType)&&r[c.__c],_=c?S?S.props.value:c.__:r,t.__c?m=(d=e.__c=t.__c).__=d.__E:(y?e.__c=d=new A(v,_):(e.__c=d=new Ls(v,_),d.constructor=A,d.render=_m),S&&S.sub(d),d.state||(d.state={}),d.__n=r,h=d.__d=!0,d.__h=[],d._sb=[]),y&&d.__s==null&&(d.__s=d.state),y&&A.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=Tt({},d.__s)),Tt(d.__s,A.getDerivedStateFromProps(v,d.__s))),f=d.props,g=d.state,d.__v=e,h)y&&A.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),y&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(y&&A.getDerivedStateFromProps==null&&v!==f&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(v,_),e.__v==t.__v||!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(v,d.__s,_)===!1){e.__v!=t.__v&&(d.props=v,d.state=d.__s,d.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(D){D&&(D.__=e)}),Us.push.apply(d.__h,d._sb),d._sb=[],d.__h.length&&a.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(v,d.__s,_),y&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(f,g,p)})}if(d.context=_,d.props=v,d.__P=i,d.__e=!1,T=le.__r,x=0,y)d.state=d.__s,d.__d=!1,T&&T(e),c=d.render(d.props,d.state,d.context),Us.push.apply(d.__h,d._sb),d._sb=[];else do d.__d=!1,T&&T(e),c=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++x<25);d.state=d.__s,d.getChildContext!=null&&(r=Tt(Tt({},r),d.getChildContext())),y&&!h&&d.getSnapshotBeforeUpdate!=null&&(p=d.getSnapshotBeforeUpdate(f,g)),b=c!=null&&c.type===qi&&c.key==null?yh(c.props.children):c,o=fh(i,Ki(b)?b:[b],e,t,r,s,n,a,o,u,l),d.base=e.__e,e.__u&=-161,d.__h.length&&a.push(d),m&&(d.__E=d.__=null)}catch(D){if(e.__v=null,u||n!=null)if(D.then){for(e.__u|=u?160:128;o&&o.nodeType==8&&o.nextSibling;)o=o.nextSibling;n[n.indexOf(o)]=null,e.__e=o}else{for(I=n.length;I--;)Qa(n[I]);Aa(e)}else e.__e=t.__e,e.__k=t.__k,D.then||Aa(e);le.__e(D,e,t)}else n==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=Sm(t.__e,e,t,r,s,n,a,u,l);return(c=le.diffed)&&c(e),128&e.__u?void 0:o}function Aa(i){i&&(i.__c&&(i.__c.__e=!0),i.__k&&i.__k.some(Aa))}function ph(i,e,t){for(var r=0;r<t.length;r++)Ja(t[r],t[++r],t[++r]);le.__c&&le.__c(e,i),i.some(function(s){try{i=s.__h,s.__h=[],i.some(function(n){n.call(s)})}catch(n){le.__e(n,s.__v)}})}function yh(i){return typeof i!="object"||i==null||i.__b>0?i:Ki(i)?i.map(yh):Tt({},i)}function Sm(i,e,t,r,s,n,a,o,u){var l,c,d,h,f,g,p,m=t.props||Bs,v=e.props,y=e.type;if(y=="svg"?s="http://www.w3.org/2000/svg":y=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),n!=null){for(l=0;l<n.length;l++)if((f=n[l])&&"setAttribute"in f==!!y&&(y?f.localName==y:f.nodeType==3)){i=f,n[l]=null;break}}if(i==null){if(y==null)return document.createTextNode(v);i=document.createElementNS(s,y,v.is&&v),o&&(le.__m&&le.__m(e,n),o=!1),n=null}if(y==null)m===v||o&&i.data==v||(i.data=v);else{if(n=n&&on.call(i.childNodes),!o&&n!=null)for(m={},l=0;l<i.attributes.length;l++)m[(f=i.attributes[l]).name]=f.value;for(l in m)f=m[l],l=="dangerouslySetInnerHTML"?d=f:l=="children"||l in v||l=="value"&&"defaultValue"in v||l=="checked"&&"defaultChecked"in v||Zi(i,l,null,f,s);for(l in v)f=v[l],l=="children"?h=f:l=="dangerouslySetInnerHTML"?c=f:l=="value"?g=f:l=="checked"?p=f:o&&typeof f!="function"||m[l]===f||Zi(i,l,f,m[l],s);if(c)o||d&&(c.__html==d.__html||c.__html==i.innerHTML)||(i.innerHTML=c.__html),e.__k=[];else if(d&&(i.innerHTML=""),fh(e.type=="template"?i.content:i,Ki(h)?h:[h],e,t,r,y=="foreignObject"?"http://www.w3.org/1999/xhtml":s,n,a,n?n[0]:t.__k&&Qr(t,0),o,u),n!=null)for(l=n.length;l--;)Qa(n[l]);o||(l="value",y=="progress"&&g==null?i.removeAttribute("value"):g!=null&&(g!==i[l]||y=="progress"&&!g||y=="option"&&g!=m[l])&&Zi(i,l,g,m[l],s),l="checked",p!=null&&p!=i[l]&&Zi(i,l,p,m[l],s))}return i}function Ja(i,e,t){try{if(typeof i=="function"){var r=typeof i.__u=="function";r&&i.__u(),r&&e==null||(i.__u=i(e))}else i.current=e}catch(s){le.__e(s,t)}}function vh(i,e,t){var r,s;if(le.unmount&&le.unmount(i),(r=i.ref)&&(r.current&&r.current!=i.__e||Ja(r,null,e)),(r=i.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(n){le.__e(n,e)}r.base=r.__P=null}if(r=i.__k)for(s=0;s<r.length;s++)r[s]&&vh(r[s],e,t||typeof i.type!="function");t||Qa(i.__e),i.__c=i.__=i.__e=void 0}function _m(i,e,t){return this.constructor(i,t)}function Tm(i,e,t){var r,s,n,a;e==document&&(e=document.documentElement),le.__&&le.__(i,e),s=(r=!1)?null:e.__k,n=[],a=[],Za(e,i=e.__k=$s(qi,null,[i]),s||Bs,Bs,e.namespaceURI,s?null:e.firstChild?on.call(e.childNodes):null,n,s?s.__e:e.firstChild,r,a),ph(n,i,a)}function bm(i){function e(t){var r,s;return this.getChildContext||(r=new Set,(s={})[e.__c]=this,this.getChildContext=function(){return s},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(n){this.props.value!=n.value&&r.forEach(function(a){a.__e=!0,xa(a)})},this.sub=function(n){r.add(n);var a=n.componentWillUnmount;n.componentWillUnmount=function(){r&&r.delete(n),a&&a.call(n)}}),t.children}return e.__c="__cC"+dh++,e.__=i,e.Provider=e.__l=(e.Consumer=function(t,r){return t.children(r)}).contextType=e,e}on=Us.slice,le={__e:function(i,e,t,r){for(var s,n,a;e=e.__;)if((s=e.__c)&&!s.__)try{if((n=s.constructor)&&n.getDerivedStateFromError!=null&&(s.setState(n.getDerivedStateFromError(i)),a=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(i,r||{}),a=s.__d),a)return s.__E=s}catch(o){i=o}throw i}},oh=0,Ls.prototype.setState=function(i,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Tt({},this.state),typeof i=="function"&&(i=i(Tt({},t),this.props)),i&&Tt(t,i),i!=null&&this.__v&&(e&&this._sb.push(e),xa(this))},Ls.prototype.forceUpdate=function(i){this.__v&&(this.__e=!0,i&&this.__h.push(i),xa(this))},Ls.prototype.render=qi,Ct=[],lh=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,uh=function(i,e){return i.__v.__b-e.__v.__b},js.__r=0,ch=/(PointerCapture)$|Capture$/i,Xa=0,Ta=Qo(!1),ba=Qo(!0),dh=0;var xm=0;function H(i,e,t,r,s,n){e||(e={});var a,o,u=e;if("ref"in u)for(o in u={},e)o=="ref"?a=e[o]:u[o]=e[o];var l={type:i,props:u,key:t,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--xm,__i:-1,__u:0,__source:s,__self:n};if(typeof i=="function"&&(a=i.defaultProps))for(o in a)u[o]===void 0&&(u[o]=a[o]);return le.vnode&&le.vnode(l),l}var Zr,he,Sn,Zo,Mi=0,Eh=[],ye=le,Jo=ye.__b,el=ye.__r,tl=ye.diffed,rl=ye.__c,il=ye.unmount,sl=ye.__;function ln(i,e){ye.__h&&ye.__h(he,i,Mi||e),Mi=0;var t=he.__H||(he.__H={__:[],__h:[]});return i>=t.__.length&&t.__.push({}),t.__[i]}function ze(i){return Mi=1,Am(Th,i)}function Am(i,e,t){var r=ln(Zr++,2);if(r.t=i,!r.__c&&(r.__=[Th(void 0,e),function(o){var u=r.__N?r.__N[0]:r.__[0],l=r.t(u,o);u!==l&&(r.__N=[l,r.__[1]],r.__c.setState({}))}],r.__c=he,!he.__f)){var s=function(o,u,l){if(!r.__c.__H)return!0;var c=r.__c.__H.__.filter(function(h){return h.__c});if(c.every(function(h){return!h.__N}))return!n||n.call(this,o,u,l);var d=r.__c.props!==o;return c.some(function(h){if(h.__N){var f=h.__[0];h.__=h.__N,h.__N=void 0,f!==h.__[0]&&(d=!0)}}),n&&n.call(this,o,u,l)||d};he.__f=!0;var n=he.shouldComponentUpdate,a=he.componentWillUpdate;he.componentWillUpdate=function(o,u,l){if(this.__e){var c=n;n=void 0,s(o,u,l),n=c}a&&a.call(this,o,u,l)},he.shouldComponentUpdate=s}return r.__N||r.__}function Gs(i,e){var t=ln(Zr++,3);!ye.__s&&_h(t.__H,e)&&(t.__=i,t.u=e,he.__H.__h.push(t))}function Ci(i){return Mi=5,Sh(function(){return{current:i}},[])}function Sh(i,e){var t=ln(Zr++,7);return _h(t.__H,e)&&(t.__=i(),t.__H=e,t.__h=i),t.__}function _n(i,e){return Mi=8,Sh(function(){return i},e)}function Im(i){var e=he.context[i.__c],t=ln(Zr++,9);return t.c=i,e?(t.__==null&&(t.__=!0,e.sub(he)),e.props.value):i.__}function Dm(){for(var i;i=Eh.shift();){var e=i.__H;if(i.__P&&e)try{e.__h.some(Rs),e.__h.some(Ia),e.__h=[]}catch(t){e.__h=[],ye.__e(t,i.__v)}}}ye.__b=function(i){he=null,Jo&&Jo(i)},ye.__=function(i,e){i&&e.__k&&e.__k.__m&&(i.__m=e.__k.__m),sl&&sl(i,e)},ye.__r=function(i){el&&el(i),Zr=0;var e=(he=i.__c).__H;e&&(Sn===he?(e.__h=[],he.__h=[],e.__.some(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.some(Rs),e.__h.some(Ia),e.__h=[],Zr=0)),Sn=he},ye.diffed=function(i){tl&&tl(i);var e=i.__c;e&&e.__H&&(e.__H.__h.length&&(Eh.push(e)!==1&&Zo===ye.requestAnimationFrame||((Zo=ye.requestAnimationFrame)||Lm)(Dm)),e.__H.__.some(function(t){t.u&&(t.__H=t.u),t.u=void 0})),Sn=he=null},ye.__c=function(i,e){e.some(function(t){try{t.__h.some(Rs),t.__h=t.__h.filter(function(r){return!r.__||Ia(r)})}catch(r){e.some(function(s){s.__h&&(s.__h=[])}),e=[],ye.__e(r,t.__v)}}),rl&&rl(i,e)},ye.unmount=function(i){il&&il(i);var e,t=i.__c;t&&t.__H&&(t.__H.__.some(function(r){try{Rs(r)}catch(s){e=s}}),t.__H=void 0,e&&ye.__e(e,t.__v))};var nl=typeof requestAnimationFrame=="function";function Lm(i){var e,t=function(){clearTimeout(r),nl&&cancelAnimationFrame(e),setTimeout(i)},r=setTimeout(t,35);nl&&(e=requestAnimationFrame(t))}function Rs(i){var e=he,t=i.__c;typeof t=="function"&&(i.__c=void 0,t()),he=e}function Ia(i){var e=he;i.__c=i.__(),he=e}function _h(i,e){return!i||i.length!==e.length||e.some(function(t,r){return t!==i[r]})}function Th(i,e){return typeof e=="function"?e(i):e}/**
3535 * @license lucide-preact v1.7.0 - ISC
3636 *
3737 * This source code is licensed under the ISC license.
3838 * See the LICENSE file in the root directory of this source tree.
3939- */const ya=(...n)=>n.filter((e,t,s)=>!!e&&e.trim()!==""&&s.indexOf(e)===t).join(" ").trim();/**
3939+ */const bh=(...i)=>i.filter((e,t,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===t).join(" ").trim();/**
4040 * @license lucide-preact v1.7.0 - ISC
4141 *
4242 * This source code is licensed under the ISC license.
4343 * See the LICENSE file in the root directory of this source tree.
4444- */const kr=n=>n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
4444+ */const al=i=>i.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
4545 * @license lucide-preact v1.7.0 - ISC
4646 *
4747 * This source code is licensed under the ISC license.
4848 * See the LICENSE file in the root directory of this source tree.
4949- */const Dl=n=>n.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,s)=>s?s.toUpperCase():t.toLowerCase());/**
4949+ */const Rm=i=>i.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,r)=>r?r.toUpperCase():t.toLowerCase());/**
5050 * @license lucide-preact v1.7.0 - ISC
5151 *
5252 * This source code is licensed under the ISC license.
5353 * See the LICENSE file in the root directory of this source tree.
5454- */const wr=n=>{const e=Dl(n);return e.charAt(0).toUpperCase()+e.slice(1)};/**
5454+ */const ol=i=>{const e=Rm(i);return e.charAt(0).toUpperCase()+e.slice(1)};/**
5555 * @license lucide-preact v1.7.0 - ISC
5656 *
5757 * This source code is licensed under the ISC license.
5858 * See the LICENSE file in the root directory of this source tree.
5959- */var Cl={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"};/**
5959+ */var Cm={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"};/**
6060 * @license lucide-preact v1.7.0 - ISC
6161 *
6262 * This source code is licensed under the ISC license.
6363 * See the LICENSE file in the root directory of this source tree.
6464- */const Pl=cl({size:24,color:"currentColor",strokeWidth:2,absoluteStrokeWidth:!1,class:""}),kl=()=>fl(Pl);/**
6464+ */const wm=bm({size:24,color:"currentColor",strokeWidth:2,absoluteStrokeWidth:!1,class:""}),Pm=()=>Im(wm);/**
6565 * @license lucide-preact v1.7.0 - ISC
6666 *
6767 * This source code is licensed under the ISC license.
6868 * See the LICENSE file in the root directory of this source tree.
6969- */const wl=n=>{for(const e in n)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};/**
6969+ */const km=i=>{for(const e in i)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};/**
7070 * @license lucide-preact v1.7.0 - ISC
7171 *
7272 * This source code is licensed under the ISC license.
7373 * See the LICENSE file in the root directory of this source tree.
7474- */const Ol=({color:n,size:e,strokeWidth:t,absoluteStrokeWidth:s,children:i,iconNode:r,class:a="",...o})=>{const{size:c=24,strokeWidth:l=2,absoluteStrokeWidth:h=!1,color:u="currentColor",class:d=""}=kl()??{},f=s??h?Number(t??l)*24/Number(e??c):t??l;return Is("svg",{...Cl,width:e??c??24,height:e??c??24,stroke:n??u,"stroke-width":f,class:ya("lucide",d,a),...!i&&!wl(o)&&{"aria-hidden":"true"},...o},[...r.map(([g,p])=>Is(g,p)),...ca(i)])};/**
7474+ */const Om=({color:i,size:e,strokeWidth:t,absoluteStrokeWidth:r,children:s,iconNode:n,class:a="",...o})=>{const{size:u=24,strokeWidth:l=2,absoluteStrokeWidth:c=!1,color:d="currentColor",class:h=""}=Pm()??{},f=r??c?Number(t??l)*24/Number(e??u):t??l;return $s("svg",{...Cm,width:e??u??24,height:e??u??24,stroke:i??d,"stroke-width":f,class:bh("lucide",h,a),...!s&&!km(o)&&{"aria-hidden":"true"},...o},[...n.map(([g,p])=>$s(g,p)),...mh(s)])};/**
7575 * @license lucide-preact v1.7.0 - ISC
7676 *
7777 * This source code is licensed under the ISC license.
7878 * See the LICENSE file in the root directory of this source tree.
7979- */const Ea=(n,e)=>{const t=({class:s="",className:i="",children:r,...a})=>Is(Ol,{...a,iconNode:e,class:ya(`lucide-${kr(wr(n))}`,`lucide-${kr(n)}`,s,i)},r);return t.displayName=wr(n),t};/**
7979+ */const xh=(i,e)=>{const t=({class:r="",className:s="",children:n,...a})=>$s(Om,{...a,iconNode:e,class:bh(`lucide-${al(ol(i))}`,`lucide-${al(i)}`,r,s)},n);return t.displayName=ol(i),t};/**
8080 * @license lucide-preact v1.7.0 - ISC
8181 *
8282 * This source code is licensed under the ISC license.
8383 * See the LICENSE file in the root directory of this source tree.
8484- */const Fl=Ea("panel-left-close",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]);/**
8484+ */const Mm=xh("panel-left-close",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]);/**
8585 * @license lucide-preact v1.7.0 - ISC
8686 *
8787 * This source code is licensed under the ISC license.
8888 * See the LICENSE file in the root directory of this source tree.
8989- */const Ml=Ea("panel-left",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);function Nl({sidebarCollapsed:n,onToggleSidebar:e}){return Z("h1",{class:"font-sans text-2xl font-semibold text-[#7dd3fc] m-0 py-4 px-5 tracking-wide shrink-0 flex items-center gap-3",children:[Z("button",{onClick:e,class:"p-1 hover:bg-[rgba(125,211,252,0.1)] rounded transition-colors text-[#7dd3fc] cursor-pointer","aria-label":n?"Expand sidebar":"Collapse sidebar",children:n?Z(Ml,{size:24}):Z(Fl,{size:24})}),Z("span",{children:"AtmosphereConf 2026"})]})}const M=Number.isFinite||function(n){return typeof n=="number"&&isFinite(n)},Bl=Number.isSafeInteger||function(n){return typeof n=="number"&&Math.abs(n)<=Ul},Ul=Number.MAX_SAFE_INTEGER||9007199254740991;let H=function(n){return n.NETWORK_ERROR="networkError",n.MEDIA_ERROR="mediaError",n.KEY_SYSTEM_ERROR="keySystemError",n.MUX_ERROR="muxError",n.OTHER_ERROR="otherError",n}({}),R=function(n){return n.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",n.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",n.KEY_SYSTEM_NO_SESSION="keySystemNoSession",n.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",n.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",n.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",n.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",n.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",n.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",n.MANIFEST_LOAD_ERROR="manifestLoadError",n.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",n.MANIFEST_PARSING_ERROR="manifestParsingError",n.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",n.LEVEL_EMPTY_ERROR="levelEmptyError",n.LEVEL_LOAD_ERROR="levelLoadError",n.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",n.LEVEL_PARSING_ERROR="levelParsingError",n.LEVEL_SWITCH_ERROR="levelSwitchError",n.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",n.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",n.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",n.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",n.FRAG_LOAD_ERROR="fragLoadError",n.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",n.FRAG_DECRYPT_ERROR="fragDecryptError",n.FRAG_PARSING_ERROR="fragParsingError",n.FRAG_GAP="fragGap",n.REMUX_ALLOC_ERROR="remuxAllocError",n.KEY_LOAD_ERROR="keyLoadError",n.KEY_LOAD_TIMEOUT="keyLoadTimeOut",n.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",n.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",n.BUFFER_APPEND_ERROR="bufferAppendError",n.BUFFER_APPENDING_ERROR="bufferAppendingError",n.BUFFER_STALLED_ERROR="bufferStalledError",n.BUFFER_FULL_ERROR="bufferFullError",n.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",n.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",n.ASSET_LIST_LOAD_ERROR="assetListLoadError",n.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",n.ASSET_LIST_PARSING_ERROR="assetListParsingError",n.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",n.INTERNAL_EXCEPTION="internalException",n.INTERNAL_ABORTED="aborted",n.ATTACH_MEDIA_ERROR="attachMediaError",n.UNKNOWN="unknown",n}({}),m=function(n){return n.MEDIA_ATTACHING="hlsMediaAttaching",n.MEDIA_ATTACHED="hlsMediaAttached",n.MEDIA_DETACHING="hlsMediaDetaching",n.MEDIA_DETACHED="hlsMediaDetached",n.MEDIA_ENDED="hlsMediaEnded",n.STALL_RESOLVED="hlsStallResolved",n.BUFFER_RESET="hlsBufferReset",n.BUFFER_CODECS="hlsBufferCodecs",n.BUFFER_CREATED="hlsBufferCreated",n.BUFFER_APPENDING="hlsBufferAppending",n.BUFFER_APPENDED="hlsBufferAppended",n.BUFFER_EOS="hlsBufferEos",n.BUFFERED_TO_END="hlsBufferedToEnd",n.BUFFER_FLUSHING="hlsBufferFlushing",n.BUFFER_FLUSHED="hlsBufferFlushed",n.MANIFEST_LOADING="hlsManifestLoading",n.MANIFEST_LOADED="hlsManifestLoaded",n.MANIFEST_PARSED="hlsManifestParsed",n.LEVEL_SWITCHING="hlsLevelSwitching",n.LEVEL_SWITCHED="hlsLevelSwitched",n.LEVEL_LOADING="hlsLevelLoading",n.LEVEL_LOADED="hlsLevelLoaded",n.LEVEL_UPDATED="hlsLevelUpdated",n.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",n.LEVELS_UPDATED="hlsLevelsUpdated",n.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",n.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",n.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",n.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",n.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",n.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",n.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",n.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",n.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",n.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",n.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",n.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",n.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",n.CUES_PARSED="hlsCuesParsed",n.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",n.INIT_PTS_FOUND="hlsInitPtsFound",n.FRAG_LOADING="hlsFragLoading",n.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",n.FRAG_LOADED="hlsFragLoaded",n.FRAG_DECRYPTED="hlsFragDecrypted",n.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",n.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",n.FRAG_PARSING_METADATA="hlsFragParsingMetadata",n.FRAG_PARSED="hlsFragParsed",n.FRAG_BUFFERED="hlsFragBuffered",n.FRAG_CHANGED="hlsFragChanged",n.FPS_DROP="hlsFpsDrop",n.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",n.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",n.ERROR="hlsError",n.DESTROYING="hlsDestroying",n.KEY_LOADING="hlsKeyLoading",n.KEY_LOADED="hlsKeyLoaded",n.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",n.BACK_BUFFER_REACHED="hlsBackBufferReached",n.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",n.ASSET_LIST_LOADING="hlsAssetListLoading",n.ASSET_LIST_LOADED="hlsAssetListLoaded",n.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",n.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",n.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",n.INTERSTITIAL_STARTED="hlsInterstitialStarted",n.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",n.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",n.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",n.INTERSTITIAL_ENDED="hlsInterstitialEnded",n.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",n.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",n.EVENT_CUE_ENTER="hlsEventCueEnter",n}({});var Q={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},U={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class yt{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class $l{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new yt(e),this.fast_=new yt(t),this.defaultTTFB_=i,this.ttfb_=new yt(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new yt(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new yt(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new yt(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,i=e/1e3,r=s/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function Gl(n,e,t){return(e=Vl(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function re(){return re=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(n[s]=t[s])}return n},re.apply(null,arguments)}function Or(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(n);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,s)}return t}function se(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Or(Object(t),!0).forEach(function(s){Gl(n,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):Or(Object(t)).forEach(function(s){Object.defineProperty(n,s,Object.getOwnPropertyDescriptor(t,s))})}return n}function Kl(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var s=t.call(n,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function Vl(n){var e=Kl(n,"string");return typeof e=="symbol"?e:e+""}class Fe{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=st,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const st=function(){},Hl={trace:st,debug:st,log:st,warn:st,info:st,error:st};function Ai(){return re({},Hl)}function Wl(n,e){const t=self.console[n];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${n}] >`):st}function Fr(n,e,t){return e[n]?e[n].bind(e):Wl(n,t)}const _i=Ai();function Yl(n,e,t){const s=Ai();if(typeof console=="object"&&n===!0||typeof n=="object"){const i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=Fr(r,n,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return Ai()}i.forEach(r=>{_i[r]=Fr(r,n)})}else re(_i,s);return s}const ie=_i;function at(n=!0){return typeof self>"u"?void 0:(n||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ql(n){return typeof self<"u"&&n===self.ManagedMediaSource}function Ta(n,e){const t=Object.keys(n),s=Object.keys(e),i=t.length,r=s.length;return!i||!r||i===r&&!t.some(a=>s.indexOf(a)===-1)}function Ce(n,e=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(n);if(e){const h=l.indexOf("\0");return h!==-1?l.substring(0,h):l}return l.replace(/\0/g,"")}const t=n.length;let s,i,r,a="",o=0;for(;o<t;){if(s=n[o++],s===0&&e)return a;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:i=n[o++],a+=String.fromCharCode((s&31)<<6|i&63);break;case 14:i=n[o++],r=n[o++],a+=String.fromCharCode((s&15)<<12|(i&63)<<6|(r&63)<<0);break}}return a}function Te(n){let e="";for(let t=0;t<n.length;t++){let s=n[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function Sa(n){return Uint8Array.from(n.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function jl(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var qs={exports:{}},Mr;function Xl(){return Mr||(Mr=1,function(n,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(c,l,h){if(h=h||{},c=c.trim(),l=l.trim(),!l){if(!h.alwaysNormalize)return c;var u=o.parseURL(c);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):l;var f=o.parseURL(c);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=i.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(p.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)p.path=f.path,d.params||(p.params=f.params,d.query||(p.query=f.query));else{var y=f.path,E=y.substring(0,y.lastIndexOf("/")+1)+d.path;p.path=o.normalizePath(E)}return p.path===null&&(p.path=h.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(p)},parseURL:function(c){var l=s.exec(c);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(c){for(c=c.split("").reverse().join("").replace(r,"");c.length!==(c=c.replace(a,"")).length;);return c.split("").reverse().join("")},buildURLFromParts:function(c){return c.scheme+c.netLoc+c.path+c.params+c.query+c.fragment}};n.exports=o})()}(qs)),qs.exports}var Yi=Xl();class qi{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 ne={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class va{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,Ql(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=(t==null?void 0:t.byteRangeEndOffset)||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[ne.AUDIO]:null,[ne.VIDEO]:null,[ne.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new qi),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Yi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ne.AUDIO]=null,e[ne.VIDEO]=null,e[ne.AUDIOVIDEO]=null}}function de(n){return n.sn!=="initSegment"}class js extends va{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(M(e)&&M(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const s=Object.keys(t);if(s.length===1){const i=this._decryptdata=t[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=M(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(t=this.levelkeys[s[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!M(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return de(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const i=t[e];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,a=!1){const{elementaryStreams:o}=this,c=o[e];if(!c){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:a};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,s),c.startDTS=Math.min(c.startDTS,i),c.endDTS=Math.max(c.endDTS,r)}}class zl extends va{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function xa(n,e){const t=Object.getPrototypeOf(n);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||xa(t,e)}}function Ql(n,e){const t=xa(n,e);t&&(t.enumerable=!0,Object.defineProperty(n,e,t))}const Nr=Math.pow(2,32)-1,Zl=[].push,Aa={video:1,audio:2,id3:3,text:4};function ge(n){return String.fromCharCode.apply(null,n)}function _a(n,e){const t=n[e]<<8|n[e+1];return t<0?65536+t:t}function Y(n,e){const t=Ia(n,e);return t<0?4294967296+t:t}function Br(n,e){let t=Y(n,e);return t*=Math.pow(2,32),t+=Y(n,e+4),t}function Ia(n,e){return n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3]}function Jl(n){const e=n.byteLength;for(let t=0;t<e;){const s=Y(n,t);if(s>8&&n[t+4]===109&&n[t+5]===111&&n[t+6]===111&&n[t+7]===102)return!0;t=s>1?t+s:e}return!1}function z(n,e){const t=[];if(!e.length)return t;const s=n.byteLength;for(let i=0;i<s;){const r=Y(n,i),a=ge(n.subarray(i+4,i+8)),o=r>1?i+r:s;if(a===e[0])if(e.length===1)t.push(n.subarray(i+8,o));else{const c=z(n.subarray(i+8,o),e.slice(1));c.length&&Zl.apply(t,c)}i=o}return t}function ec(n){const e=[],t=n[0];let s=8;const i=Y(n,s);s+=4;let r=0,a=0;t===0?(r=Y(n,s),a=Y(n,s+4),s+=8):(r=Br(n,s),a=Br(n,s+8),s+=16),s+=2;let o=n.length+a;const c=_a(n,s);s+=2;for(let l=0;l<c;l++){let h=s;const u=Y(n,h);h+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return ie.warn("SIDX has hierarchical references (not supported)"),null;const g=Y(n,h);h+=4,e.push({referenceSize:d,subsegmentDuration:g,info:{duration:g/i,start:o,end:o+d-1}}),o+=d,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:c,references:e}}function La(n){const e=[],t=z(n,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],a=z(r,["tkhd"])[0];if(a){let o=a[0];const c=Y(a,o===0?12:20),l=z(r,["mdia","mdhd"])[0];if(l){o=l[0];const h=Y(l,o===0?12:20),u=z(r,["mdia","hdlr"])[0];if(u){const d=ge(u.subarray(8,12)),f={soun:ne.AUDIO,vide:ne.VIDEO}[d],g=z(r,["mdia","minf","stbl","stsd"])[0],p=tc(g);f?(e[c]={timescale:h,type:f,stsd:p},e[f]=se({timescale:h,id:c},p)):e[c]={timescale:h,type:d,stsd:p}}}}}return z(n,["moov","mvex","trex"]).forEach(i=>{const r=Y(i,4),a=e[r];a&&(a.default={duration:Y(i,12),flags:Y(i,20)})}),e}function tc(n){const e=n.subarray(8),t=e.subarray(86),s=ge(e.subarray(4,8));let i=s,r;const a=s==="enca"||s==="encv";if(a){const l=z(e,[s])[0].subarray(s==="enca"?28:78);z(l,["sinf"]).forEach(u=>{const d=z(u,["schm"])[0];if(d){const f=ge(d.subarray(4,8));if(f==="cbcs"||f==="cenc"){const g=z(u,["frma"])[0];g&&(i=ge(g))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const c=z(t,["avcC"])[0];c&&c.length>3&&(i+="."+Zt(c[1])+Zt(c[2])+Zt(c[3]),r=Qt(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=z(e,[s])[0],l=z(c.subarray(28),["esds"])[0];if(l&&l.length>7){let h=4;if(l[h++]!==3)break;h=Xs(l,h),h+=2;const u=l[h++];if(u&128&&(h+=2),u&64&&(h+=l[h++]),l[h++]!==4)break;h=Xs(l,h);const d=l[h++];if(d===64)i+="."+Zt(d);else break;if(h+=12,l[h++]!==5)break;h=Xs(l,h);const f=l[h++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((l[h]&224)>>5)),i+="."+g}break}case"hvc1":case"hev1":{const c=z(t,["hvcC"])[0];if(c&&c.length>12){const l=c[1],h=["","A","B","C"][l>>6],u=l&31,d=Y(c,2),f=(l&32)>>5?"H":"L",g=c[12],p=c.subarray(6,12);i+="."+h+u,i+="."+sc(d).toString(16).toUpperCase(),i+="."+f+g;let y="";for(let E=p.length;E--;){const T=p[E];(T||y)&&(y="."+T.toString(16).toUpperCase()+y)}i+=y}r=Qt(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=Qt(i,t)||i;break}case"vp09":{const c=z(t,["vpcC"])[0];if(c&&c.length>6){const l=c[4],h=c[5],u=c[6]>>4&15;i+="."+Ke(l)+"."+Ke(h)+"."+Ke(u)}break}case"av01":{const c=z(t,["av1C"])[0];if(c&&c.length>2){const l=c[1]>>>5,h=c[1]&31,u=c[2]>>>7?"H":"M",d=(c[2]&64)>>6,f=(c[2]&32)>>5,g=l===2&&d?f?12:10:d?10:8,p=(c[2]&16)>>4,y=(c[2]&8)>>3,E=(c[2]&4)>>2,T=c[2]&3;i+="."+l+"."+Ke(h)+u+"."+Ke(g)+"."+p+"."+y+E+T+"."+Ke(1)+"."+Ke(1)+"."+Ke(1)+"."+0,r=Qt("dav1",t)}break}}return{codec:i,encrypted:a,supplemental:r}}function Qt(n,e){const t=z(e,["dvvC"]),s=t.length?t[0]:z(e,["dvcC"])[0];if(s){const i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return n+"."+Ke(i)+"."+Ke(r)}}function sc(n){let e=0;for(let t=0;t<32;t++)e|=(n>>t&1)<<31-t;return e>>>0}function Xs(n,e){const t=e+5;for(;n[e++]&128&&e<t;);return e}function Zt(n){return("0"+n.toString(16).toUpperCase()).slice(-2)}function Ke(n){return(n<10?"0":"")+n}function ic(n,e){if(!n||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&Ra(n,(s,i)=>{const r=s.subarray(8,24);r.some(a=>a!==0)||(ie.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Te(r)} -> ${Te(t)}`),s.set(t,8))})}function rc(n){const e=[];return Ra(n,t=>e.push(t.subarray(8,24))),e}function Ra(n,e){z(n,["moov","trak"]).forEach(s=>{const i=z(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;const r=i.subarray(8);let a=z(r,["enca"]);const o=a.length>0;o||(a=z(r,["encv"])),a.forEach(c=>{const l=o?c.subarray(28):c.subarray(78);z(l,["sinf"]).forEach(u=>{const d=ba(u);d&&e(d,o)})})})}function ba(n){const e=z(n,["schm"])[0];if(e){const t=ge(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=z(n,["schi","tenc"])[0];if(s)return s}}}function nc(n,e,t){const s={},i=z(n,["moof","traf"]);for(let r=0;r<i.length;r++){const a=i[r],o=z(a,["tfhd"])[0],c=Y(o,4),l=e[c];if(!l)continue;s[c]||(s[c]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const h=s[c],u=z(a,["tfdt"])[0];if(u){const S=u[0];let v=Y(u,4);S===1&&(v===Nr?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(v*=Nr+1,v+=Y(u,8))),M(v)&&(!M(h.start)||v<h.start)&&(h.start=v)}const d=l.default,f=Y(o,0)|(d==null?void 0:d.flags);let g=(d==null?void 0:d.duration)||0;f&8&&(f&2?g=Y(o,12):g=Y(o,8));const p=z(a,["trun"]);let y=h.start||0,E=0,T=g;for(let S=0;S<p.length;S++){const v=p[S],x=Y(v,4),D=h.sampleCount;h.sampleCount+=x;const A=v[3]&1,b=v[3]&4,I=v[2]&1,_=v[2]&2,C=v[2]&4,k=v[2]&8;let B=8,K=x;for(A&&(B+=4),b&&x&&(!(v[B+1]&1)&&h.keyFrameIndex===void 0&&(h.keyFrameIndex=D),B+=4,I?(T=Y(v,B),B+=4):T=g,_&&(B+=4),k&&(B+=4),y+=T,E+=T,K--);K--;)I?(T=Y(v,B),B+=4):T=g,_&&(B+=4),C&&(v[B+1]&1||h.keyFrameIndex===void 0&&(h.keyFrameIndex=h.sampleCount-(K+1),h.keyFrameStart=y),B+=4),k&&(B+=4),y+=T,E+=T;!E&&g&&(E+=g*x)}h.duration+=E}if(!Object.keys(s).some(r=>s[r].duration)){let r=1/0,a=0;const o=z(n,["sidx"]);for(let c=0;c<o.length;c++){const l=ec(o[c]);if(l!=null&&l.references){r=Math.min(r,l.earliestPresentationTime/l.timescale);const h=l.references.reduce((u,d)=>u+d.info.duration||0,0);a=Math.max(a,h+l.earliestPresentationTime/l.timescale)}}a&&M(a)&&Object.keys(s).forEach(c=>{s[c].duration||(s[c].duration=a*s[c].timescale-s[c].start)})}return s}function ac(n){const e={valid:null,remainder:null},t=z(n,["moof"]);if(t.length<2)return e.remainder=n,e;const s=t[t.length-1];return e.valid=n.slice(0,s.byteOffset-8),e.remainder=n.slice(s.byteOffset-8),e}function Oe(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function Ur(n,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let a=!1;return z(s,["moof"]).map(c=>{const l=c.byteOffset-8;z(c,["traf"]).map(u=>{const d=z(u,["tfdt"]).map(f=>{const g=f[0];let p=Y(f,4);return g===1&&(p*=Math.pow(2,32),p+=Y(f,8)),p/i})[0];return d!==void 0&&(n=d),z(u,["tfhd"]).map(f=>{const g=Y(f,4),p=Y(f,0)&16777215,y=(p&1)!==0,E=(p&2)!==0,T=(p&8)!==0;let S=0;const v=(p&16)!==0;let x=0;const D=(p&32)!==0;let A=8;g===r&&(y&&(A+=8),E&&(A+=4),T&&(S=Y(f,A),A+=4),v&&(x=Y(f,A),A+=4),D&&(A+=4),e.type==="video"&&(a=Gs(e.codec)),z(u,["trun"]).map(b=>{const I=b[0],_=Y(b,0)&16777215,C=(_&1)!==0;let k=0;const B=(_&4)!==0,K=(_&256)!==0;let $=0;const w=(_&512)!==0;let G=0;const N=(_&1024)!==0,V=(_&2048)!==0;let W=0;const O=Y(b,4);let F=8;C&&(k=Y(b,F),F+=4),B&&(F+=4);let j=k+l;for(let te=0;te<O;te++){if(K?($=Y(b,F),F+=4):$=S,w?(G=Y(b,F),F+=4):G=x,N&&(F+=4),V&&(I===0?W=Y(b,F):W=Ia(b,F),F+=4),e.type===ne.VIDEO){let X=0;for(;X<G;){const J=Y(s,j);if(j+=4,oc(a,s[j])){const ve=s.subarray(j,j+J);ji(ve,a?2:1,n+W/i,t)}j+=J,X+=J+4}}n+=$/i}}))})})}),t}function Gs(n){if(!n)return!1;const e=n.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function oc(n,e){if(n){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function ji(n,e,t,s){const i=Da(n);let r=0;r+=e;let a=0,o=0,c=0;for(;r<i.length;){a=0;do{if(r>=i.length)break;c=i[r++],a+=c}while(c===255);o=0;do{if(r>=i.length)break;c=i[r++],o+=c}while(c===255);const l=i.length-r;let h=r;if(o<l)r+=o;else if(o>l){ie.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(a===4){if(i[h++]===181){const d=_a(i,h);if(h+=2,d===49){const f=Y(i,h);if(h+=4,f===1195456820){const g=i[h++];if(g===3){const p=i[h++],y=31&p,E=64&p,T=E?2+y*3:0,S=new Uint8Array(T);if(E){S[0]=p;for(let v=1;v<T;v++)S[v]=i[h++]}s.push({type:g,payloadType:a,pts:t,bytes:S})}}}}}else if(a===5&&o>16){const u=[];for(let g=0;g<16;g++){const p=i[h++].toString(16);u.push(p.length==1?"0"+p:p),(g===3||g===5||g===7||g===9)&&u.push("-")}const d=o-16,f=new Uint8Array(d);for(let g=0;g<d;g++)f[g]=i[h++];s.push({payloadType:a,pts:t,uuid:u.join(""),userData:Ce(f),userDataBytes:f})}}}function Da(n){const e=n.byteLength,t=[];let s=1;for(;s<e-2;)n[s]===0&&n[s+1]===0&&n[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return n;const i=e-t.length,r=new Uint8Array(i);let a=0;for(s=0;s<i;a++,s++)a===t[0]&&(a++,t.shift()),r[s]=n[a];return r}function lc(n){const e=n[0];let t="",s="",i=0,r=0,a=0,o=0,c=0,l=0;if(e===0){for(;ge(n.subarray(l,l+1))!=="\0";)t+=ge(n.subarray(l,l+1)),l+=1;for(t+=ge(n.subarray(l,l+1)),l+=1;ge(n.subarray(l,l+1))!=="\0";)s+=ge(n.subarray(l,l+1)),l+=1;s+=ge(n.subarray(l,l+1)),l+=1,i=Y(n,12),r=Y(n,16),o=Y(n,20),c=Y(n,24),l=28}else if(e===1){l+=4,i=Y(n,l),l+=4;const u=Y(n,l);l+=4;const d=Y(n,l);for(l+=4,a=2**32*u+d,Bl(a)||(a=Number.MAX_SAFE_INTEGER,ie.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Y(n,l),l+=4,c=Y(n,l),l+=4;ge(n.subarray(l,l+1))!=="\0";)t+=ge(n.subarray(l,l+1)),l+=1;for(t+=ge(n.subarray(l,l+1)),l+=1;ge(n.subarray(l,l+1))!=="\0";)s+=ge(n.subarray(l,l+1)),l+=1;s+=ge(n.subarray(l,l+1)),l+=1}const h=n.subarray(l,n.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:a,presentationTimeDelta:r,eventDuration:o,id:c,payload:h}}function cc(n,...e){const t=e.length;let s=8,i=t;for(;i--;)s+=e[i].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(n,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function hc(n,e,t){if(n.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),cc([112,115,115,104],new Uint8Array([s,0,0,0]),n,r,i,a,t)}function uc(n){const e=[];if(n instanceof ArrayBuffer){const t=n.byteLength;let s=0;for(;s+32<t;){const i=new DataView(n,s),r=dc(i);e.push(r),s+=r.size}}return e}function dc(n){const e=n.getUint32(0),t=n.byteOffset,s=n.byteLength;if(s<e)return{offset:t,size:s};if(n.getUint32(4)!==1886614376)return{offset:t,size:e};const r=n.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const a=n.buffer,o=Te(new Uint8Array(a,t+12,16));let c=null,l=null,h=0;if(r===0)h=28;else{const d=n.getUint32(28);if(!d||s<32+d*16)return{offset:t,size:e};c=[];for(let f=0;f<d;f++)c.push(new Uint8Array(a,t+32+f*16,16));h=32+d*16}if(!h)return{offset:t,size:e};const u=n.getUint32(h);return e-32<u?{offset:t,size:e}:(l=new Uint8Array(a,t+h+4,u),{version:r,systemId:o,kids:c,data:l,offset:t,size:e})}const Ca=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Ct={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Xi(n,e){const t=Ct[e];return!!t&&!!t[n.slice(0,4)]}function $t(n,e,t=!0){return!n.split(",").some(s=>!zi(s,e,t))}function zi(n,e,t=!0){var s;const i=at(t);return(s=i==null?void 0:i.isTypeSupported(Gt(n,e)))!=null?s:!1}function Gt(n,e){return`${e}/mp4;codecs=${n}`}function $r(n){if(n){const e=n.substring(0,4);return Ct.video[e]}return 2}function bs(n){const e=Ca();return n.split(",").reduce((t,s)=>{const r=e&&Gs(s)?9:Ct.video[s];return r?(r*2+t)/(t?3:2):(Ct.audio[s]+t)/(t?2:1)},0)}const zs={};function fc(n,e=!0){if(zs[n])return zs[n];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[n];for(let i=0;i<t.length;i++){var s;if(zi(t[i],"audio",e))return zs[n]=t[i],t[i];if(t[i]==="mp3"&&(s=at(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return n}const gc=/flac|opus|mp4a\.40\.34/i;function Ds(n,e=!0){return n.replace(gc,t=>fc(t.toLowerCase(),e))}function mc(n,e){const t=[];if(n){const s=n.split(",");for(let i=0;i<s.length;i++)Xi(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function ms(n,e){if(n&&(n.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(n)!==-1)&&(Gr(n,"audio")||Gr(n,"video")))return n;if(e){const t=e.split(",");if(t.length>1){if(n){for(let s=t.length;s--;)if(t[s].substring(0,4)===n.substring(0,4))return t[s]}return t[0]}}return e||n}function Gr(n,e){return Xi(n,e)&&zi(n,e)}function pc(n){const e=n.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function yc(n){if(n.startsWith("av01.")){const e=n.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return n}function Kr(n){const e=at(n)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ii(n){return n.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Ec={supported:!0,powerEfficient:!0,smooth:!0},Tc={supported:!1,smooth:!1,powerEfficient:!1},Pa={supported:!0,configurations:[],decodingInfoResults:[Ec]};function ka(n,e){return{supported:!1,configurations:e,decodingInfoResults:[Tc],error:n}}function Sc(n,e,t,s,i,r){const a=n.videoCodec,o=n.audioCodec?n.audioGroups:null,c=r==null?void 0:r.audioCodec,l=r==null?void 0:r.channels,h=l?parseInt(l):c?1/0:2;let u=null;if(o!=null&&o.length)try{o.length===1&&o[0]?u=e.groups[o[0]].channels:u=o.reduce((d,f)=>{if(f){const g=e.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(p=>{d[p]=(d[p]||0)+g.channels[p]})}return d},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(d=>Gs(d))||n.width>1920&&n.height>1088||n.height>1920&&n.width>1088||n.frameRate>Math.max(s,30)||n.videoRange!=="SDR"&&n.videoRange!==t||n.bitrate>Math.max(i,8e6))||!!u&&M(h)&&Object.keys(u).some(d=>parseInt(d)>h)}function wa(n,e,t,s={}){const i=n.videoCodec;if(!i&&!n.audioCodec||!t)return Promise.resolve(Pa);const r=[],a=vc(n),o=a.length,c=xc(n,e,o>0),l=c.length;for(let h=o||1*l||1;h--;){const u={type:"media-source"};if(o&&(u.video=a[h%o]),l){u.audio=c[h%l];const d=u.audio.bitrate;u.video&&d&&(u.video.bitrate-=d)}r.push(u)}if(i){const h=navigator.userAgent;if(i.split(",").some(u=>Gs(u))&&Ca())return Promise.resolve(ka(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),r))}return Promise.all(r.map(h=>{const u=_c(h);return s[u]||(s[u]=t.decodingInfo(h))})).then(h=>({supported:!h.some(u=>!u.supported),configurations:r,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:r,decodingInfoResults:[],error:h}))}function vc(n){var e;const t=(e=n.videoCodec)==null?void 0:e.split(","),s=Oa(n),i=n.width||640,r=n.height||480,a=n.frameRate||30,o=n.videoRange.toLowerCase();return t?t.map(c=>{const l={contentType:Gt(yc(c),"video"),width:i,height:r,bitrate:s,framerate:a};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function xc(n,e,t){var s;const i=(s=n.audioCodec)==null?void 0:s.split(","),r=Oa(n);return i&&n.audioGroups?n.audioGroups.reduce((a,o)=>{var c;const l=o?(c=e.groups[o])==null?void 0:c.tracks:null;return l?l.reduce((h,u)=>{if(u.groupId===o){const d=parseFloat(u.channels||"");i.forEach(f=>{const g={contentType:Gt(f,"audio"),bitrate:t?Ac(f,r):r};d&&(g.channels=""+d),h.push(g)})}return h},a):a},[]):[]}function Ac(n,e){if(e<=1)return 1;let t=128e3;return n==="ec-3"?t=768e3:n==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Oa(n){return Math.ceil(Math.max(n.bitrate*.9,n.averageBitrate)/1e3)*1e3||1}function _c(n){let e="";const{audio:t,video:s}=n;if(s){const i=Ii(s.contentType);e+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){const i=Ii(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}const Li=["NONE","TYPE-0","TYPE-1",null];function Ic(n){return Li.indexOf(n)>-1}const Cs=["SDR","PQ","HLG"];function Lc(n){return!!n&&Cs.indexOf(n)>-1}var ps={No:"",Yes:"YES",v2:"v2"};function Vr(n){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=n,i=s<e/2;return e&&i?t?ps.v2:ps.Yes:ps.No}class Hr{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Kt{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Wr(this._audioGroups,e)}hasSubtitleGroup(e){return Wr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Wr(n,e){return!e||!n?!1:n.indexOf(e)!==-1}function Rc(){if(typeof matchMedia=="function"){const n=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(n.media!==e.media)return n.matches===!0}return!1}function bc(n,e){let t=!1,s=[];if(n&&(t=n!=="SDR",s=[n]),e){s=e.allowedVideoRanges||Cs.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&Rc(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const Dc=n=>{const e=new WeakSet;return(t,s)=>{if(n&&(s=n(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},oe=(n,e)=>JSON.stringify(n,Dc(e));function Cc(n,e,t,s,i){const r=Object.keys(n),a=s==null?void 0:s.channels,o=s==null?void 0:s.audioCodec,c=i==null?void 0:i.videoCodec,l=a&&parseInt(a)===2;let h=!1,u=!1,d=1/0,f=1/0,g=1/0,p=1/0,y=0,E=[];const{preferHDR:T,allowedVideoRanges:S}=bc(e,i);for(let b=r.length;b--;){const I=n[r[b]];h||(h=I.channels[2]>0),d=Math.min(d,I.minHeight),f=Math.min(f,I.minFramerate),g=Math.min(g,I.minBitrate),S.filter(C=>I.videoRanges[C]>0).length>0&&(u=!0)}d=M(d)?d:0,f=M(f)?f:0;const v=Math.max(1080,d),x=Math.max(30,f);g=M(g)?g:t,t=Math.max(g,t),u||(e=void 0);const D=r.length>1;return{codecSet:r.reduce((b,I)=>{const _=n[I];if(I===b)return b;if(E=u?S.filter(C=>_.videoRanges[C]>0):[],D){if(_.minBitrate>t)return $e(I,`min bitrate of ${_.minBitrate} > current estimate of ${t}`),b;if(!_.hasDefaultAudio)return $e(I,"no renditions with default or auto-select sound found"),b;if(o&&I.indexOf(o.substring(0,4))%5!==0)return $e(I,`audio codec preference "${o}" not found`),b;if(a&&!l){if(!_.channels[a])return $e(I,`no renditions with ${a} channel sound found (channels options: ${Object.keys(_.channels)})`),b}else if((!o||l)&&h&&_.channels[2]===0)return $e(I,"no renditions with stereo sound found"),b;if(_.minHeight>v)return $e(I,`min resolution of ${_.minHeight} > maximum of ${v}`),b;if(_.minFramerate>x)return $e(I,`min framerate of ${_.minFramerate} > maximum of ${x}`),b;if(!E.some(C=>_.videoRanges[C]>0))return $e(I,`no variants with VIDEO-RANGE of ${oe(E)} found`),b;if(c&&I.indexOf(c.substring(0,4))%5!==0)return $e(I,`video codec preference "${c}" not found`),b;if(_.maxScore<y)return $e(I,`max score of ${_.maxScore} < selected max of ${y}`),b}return b&&(bs(I)>=bs(b)||_.fragmentError>n[b].fragmentError)?b:(p=_.minIndex,y=_.maxScore,I)},void 0),videoRanges:E,preferHDR:T,minFramerate:f,minBitrate:g,minIndex:p}}function $e(n,e){ie.log(`[abr] start candidates with "${n}" ignored because ${e}`)}function Fa(n){return n.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Pc(n,e,t,s){return n.slice(t,s+1).reduce((i,r,a)=>{if(!r.codecSet)return i;const o=r.audioGroups;let c=i[r.codecSet];c||(i[r.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return c.minHeight=Math.min(c.minHeight,l),c.minFramerate=Math.min(c.minFramerate,r.frameRate),c.minIndex=Math.min(c.minIndex,a),c.maxScore=Math.max(c.maxScore,r.score),c.fragmentError+=r.fragmentError,c.videoRanges[r.videoRange]=(c.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const u=e.groups[h];u&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(d=>{c.channels[d]=(c.channels[d]||0)+u.channels[d]}))}),i},{})}function Yr(n){if(!n)return n;const{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}=n;return{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}}function He(n,e,t){if("attrs"in n){const s=e.indexOf(n);if(s!==-1)return s}for(let s=0;s<e.length;s++){const i=e[s];if(gt(n,i,t))return s}return-1}function gt(n,e,t){const{groupId:s,name:i,lang:r,assocLang:a,default:o}=n,c=n.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(r===void 0||kc(r,e.lang))&&(r===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in n)||wc(n.characteristics||"",e.characteristics))&&(t===void 0||t(n,e))}function kc(n,e="--"){return n.length===e.length?n===e:n.startsWith(e)||e.startsWith(n)}function wc(n,e=""){const t=n.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function ft(n,e){const{audioCodec:t,channels:s}=n;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function Oc(n,e,t,s,i){const r=e[s],o=e.reduce((d,f,g)=>{const p=f.uri;return(d[p]||(d[p]=[])).push(g),d},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const c=r.videoRange,l=r.frameRate,h=r.codecSet.substring(0,4),u=qr(e,s,d=>{if(d.videoRange!==c||d.frameRate!==l||d.codecSet.substring(0,4)!==h)return!1;const f=d.audioGroups,g=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return He(n,g,i)>-1});return u>-1?u:qr(e,s,d=>{const f=d.audioGroups,g=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return He(n,g,i)>-1})}function qr(n,e,t){for(let s=e;s>-1;s--)if(t(n[s]))return s;for(let s=e+1;s<n.length;s++)if(t(n[s]))return s;return-1}function Ps(n,e){var t;return!!n&&n!==((t=e.loadLevelObj)==null?void 0:t.uri)}class Fc extends Fe{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:i,partCurrent:r,hls:a}=this,{autoLevelEnabled:o,media:c}=a;if(!i||!c)return;const l=performance.now(),h=r?r.stats:i.stats,u=r?r.duration:i.duration,d=l-h.loading.start,f=a.minAutoLevel,g=i.level,p=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const y=p>-1&&p!==g,E=!!t||y;if(!E&&(c.paused||!c.playbackRate||!c.readyState))return;const T=a.mainForwardBufferInfo;if(!E&&T===null)return;const S=this.bwEstimator.getEstimateTTFB(),v=Math.abs(c.playbackRate);if(d<=Math.max(S,1e3*(u/(v*2))))return;const x=T?T.len/v:0,D=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&D>-1,b=this.getBwEstimate(),I=a.levels,_=I[g],C=Math.max(h.loaded,Math.round(u*(i.bitrate||_.averageBitrate)/8));let k=A?d-D:d;k<1&&A&&(k=Math.min(d,h.loaded*8/b));const B=A?h.loaded*1e3/k:0,K=S/1e3,$=B?(C-h.loaded)/B:C*8/b+K;if($<=x)return;const w=B?B*8:b,G=((s=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,N=this.hls.config.abrBandWidthUpFactor;let V=Number.POSITIVE_INFINITY,W;for(W=g-1;W>f;W--){const te=I[W].maxBitrate,X=!I[W].details||G;if(V=this.getTimeToLoadFrag(K,w,u*te,X),V<Math.min(x,u+K))break}if(V>=$||V>u*10)return;A?this.bwEstimator.sample(d-Math.min(S,D),h.loaded):this.bwEstimator.sampleTTFB(d);const O=I[W].maxBitrate;this.getBwEstimate()*N>O&&this.resetEstimator(O);const F=this.findBestLevel(O,f,W,0,x,1,1);F>-1&&(W=F),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;
9090- Fragment duration: ${i.duration.toFixed(3)}
9191- Time to underbuffer: ${x.toFixed(3)} s
9292- Estimated load time for current fragment: ${$.toFixed(3)} s
9393- Estimated load time for down switch fragment: ${V.toFixed(3)} s
9494- TTFB estimate: ${D|0} ms
9595- Current BW estimate: ${M(b)?b|0:"Unknown"} bps
8989+ */const Fm=xh("panel-left",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);function ri(i){if(i.__esModule)return i;var e=i.default;if(typeof e=="function"){var t=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(i).forEach(function(r){var s=Object.getOwnPropertyDescriptor(i,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return i[r]}})}),t}var Ah={},Da=function(i,e){return Da=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t[s]=r[s])},Da(i,e)};function Ih(i,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Da(i,e);function t(){this.constructor=i}i.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var Vs=function(){return Vs=Object.assign||function(e){for(var t,r=1,s=arguments.length;r<s;r++){t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},Vs.apply(this,arguments)};function Dh(i,e){var t={};for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&e.indexOf(r)<0&&(t[r]=i[r]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(i);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(i,r[s])&&(t[r[s]]=i[r[s]]);return t}function Lh(i,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(i,e,t,r);else for(var o=i.length-1;o>=0;o--)(a=i[o])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}function Rh(i,e){return function(t,r){e(t,r,i)}}function Ch(i,e,t,r,s,n){function a(v){if(v!==void 0&&typeof v!="function")throw new TypeError("Function expected");return v}for(var o=r.kind,u=o==="getter"?"get":o==="setter"?"set":"value",l=!e&&i?r.static?i:i.prototype:null,c=e||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,h=!1,f=t.length-1;f>=0;f--){var g={};for(var p in r)g[p]=p==="access"?{}:r[p];for(var p in r.access)g.access[p]=r.access[p];g.addInitializer=function(v){if(h)throw new TypeError("Cannot add initializers after decoration has completed");n.push(a(v||null))};var m=(0,t[f])(o==="accessor"?{get:c.get,set:c.set}:c[u],g);if(o==="accessor"){if(m===void 0)continue;if(m===null||typeof m!="object")throw new TypeError("Object expected");(d=a(m.get))&&(c.get=d),(d=a(m.set))&&(c.set=d),(d=a(m.init))&&s.unshift(d)}else(d=a(m))&&(o==="field"?s.unshift(d):c[u]=d)}l&&Object.defineProperty(l,r.name,c),h=!0}function wh(i,e,t){for(var r=arguments.length>2,s=0;s<e.length;s++)t=r?e[s].call(i,t):e[s].call(i);return r?t:void 0}function Ph(i){return typeof i=="symbol"?i:"".concat(i)}function kh(i,e,t){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(i,"name",{configurable:!0,value:t?"".concat(t," ",e):e})}function Oh(i,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(i,e)}function Mh(i,e,t,r){function s(n){return n instanceof t?n:new t(function(a){a(n)})}return new(t||(t=Promise))(function(n,a){function o(c){try{l(r.next(c))}catch(d){a(d)}}function u(c){try{l(r.throw(c))}catch(d){a(d)}}function l(c){c.done?n(c.value):s(c.value).then(o,u)}l((r=r.apply(i,e||[])).next())})}function Fh(i,e){var t={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},r,s,n,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function o(l){return function(c){return u([l,c])}}function u(l){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(t=0)),t;)try{if(r=1,s&&(n=l[0]&2?s.return:l[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,l[1])).done)return n;switch(s=0,n&&(l=[l[0]&2,n.value]),l[0]){case 0:case 1:n=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,s=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(n=t.trys,!(n=n.length>0&&n[n.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!n||l[1]>n[0]&&l[1]<n[3])){t.label=l[1];break}if(l[0]===6&&t.label<n[1]){t.label=n[1],n=l;break}if(n&&t.label<n[2]){t.label=n[2],t.ops.push(l);break}n[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(i,t)}catch(c){l=[6,c],s=0}finally{r=n=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}var un=Object.create?function(i,e,t,r){r===void 0&&(r=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(i,r,s)}:function(i,e,t,r){r===void 0&&(r=t),i[r]=e[t]};function Nh(i,e){for(var t in i)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&un(e,i,t)}function Ks(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],r=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&r>=i.length&&(i=void 0),{value:i&&i[r++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function eo(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var r=t.call(i),s,n=[],a;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)n.push(s.value)}catch(o){a={error:o}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return n}function Bh(){for(var i=[],e=0;e<arguments.length;e++)i=i.concat(eo(arguments[e]));return i}function Uh(){for(var i=0,e=0,t=arguments.length;e<t;e++)i+=arguments[e].length;for(var r=Array(i),s=0,e=0;e<t;e++)for(var n=arguments[e],a=0,o=n.length;a<o;a++,s++)r[s]=n[a];return r}function $h(i,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,n;r<s;r++)(n||!(r in e))&&(n||(n=Array.prototype.slice.call(e,0,r)),n[r]=e[r]);return i.concat(n||Array.prototype.slice.call(e))}function Jr(i){return this instanceof Jr?(this.v=i,this):new Jr(i)}function jh(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(i,e||[]),s,n=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",a),s[Symbol.asyncIterator]=function(){return this},s;function a(f){return function(g){return Promise.resolve(g).then(f,d)}}function o(f,g){r[f]&&(s[f]=function(p){return new Promise(function(m,v){n.push([f,p,m,v])>1||u(f,p)})},g&&(s[f]=g(s[f])))}function u(f,g){try{l(r[f](g))}catch(p){h(n[0][3],p)}}function l(f){f.value instanceof Jr?Promise.resolve(f.value.v).then(c,d):h(n[0][2],f)}function c(f){u("next",f)}function d(f){u("throw",f)}function h(f,g){f(g),n.shift(),n.length&&u(n[0][0],n[0][1])}}function Gh(i){var e,t;return e={},r("next"),r("throw",function(s){throw s}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(s,n){e[s]=i[s]?function(a){return(t=!t)?{value:Jr(i[s](a)),done:!1}:n?n(a):a}:n}}function Vh(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof Ks=="function"?Ks(i):i[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=i[n]&&function(a){return new Promise(function(o,u){a=i[n](a),s(o,u,a.done,a.value)})}}function s(n,a,o,u){Promise.resolve(u).then(function(l){n({value:l,done:o})},a)}}function Kh(i,e){return Object.defineProperty?Object.defineProperty(i,"raw",{value:e}):i.raw=e,i}var Nm=Object.create?function(i,e){Object.defineProperty(i,"default",{enumerable:!0,value:e})}:function(i,e){i.default=e},La=function(i){return La=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},La(i)};function qh(i){if(i&&i.__esModule)return i;var e={};if(i!=null)for(var t=La(i),r=0;r<t.length;r++)t[r]!=="default"&&un(e,i,t[r]);return Nm(e,i),e}function Hh(i){return i&&i.__esModule?i:{default:i}}function Wh(i,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?i!==e||!r:!e.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(i):r?r.value:e.get(i)}function zh(i,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?i!==e||!s:!e.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(i,t):s?s.value=t:e.set(i,t),t}function Yh(i,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof i=="function"?e===i:i.has(e)}function Xh(i,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,s;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],t&&(s=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");s&&(r=function(){try{s.call(this)}catch(n){return Promise.reject(n)}}),i.stack.push({value:e,dispose:r,async:t})}else t&&i.stack.push({async:!0});return e}var Bm=typeof SuppressedError=="function"?SuppressedError:function(i,e,t){var r=new Error(t);return r.name="SuppressedError",r.error=i,r.suppressed=e,r};function Qh(i){function e(n){i.error=i.hasError?new Bm(n,i.error,"An error was suppressed during disposal."):n,i.hasError=!0}var t,r=0;function s(){for(;t=i.stack.pop();)try{if(!t.async&&r===1)return r=0,i.stack.push(t),Promise.resolve().then(s);if(t.dispose){var n=t.dispose.call(t.value);if(t.async)return r|=2,Promise.resolve(n).then(s,function(a){return e(a),s()})}else r|=1}catch(a){e(a)}if(r===1)return i.hasError?Promise.reject(i.error):Promise.resolve();if(i.hasError)throw i.error}return s()}function Zh(i,e){return typeof i=="string"&&/^\.\.?\//.test(i)?i.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(t,r,s,n,a){return r?e?".jsx":".js":s&&(!n||!a)?t:s+n+"."+a.toLowerCase()+"js"}):i}const Um={__extends:Ih,__assign:Vs,__rest:Dh,__decorate:Lh,__param:Rh,__esDecorate:Ch,__runInitializers:wh,__propKey:Ph,__setFunctionName:kh,__metadata:Oh,__awaiter:Mh,__generator:Fh,__createBinding:un,__exportStar:Nh,__values:Ks,__read:eo,__spread:Bh,__spreadArrays:Uh,__spreadArray:$h,__await:Jr,__asyncGenerator:jh,__asyncDelegator:Gh,__asyncValues:Vh,__makeTemplateObject:Kh,__importStar:qh,__importDefault:Hh,__classPrivateFieldGet:Wh,__classPrivateFieldSet:zh,__classPrivateFieldIn:Yh,__addDisposableResource:Xh,__disposeResources:Qh,__rewriteRelativeImportExtension:Zh},$m=Object.freeze(Object.defineProperty({__proto__:null,__addDisposableResource:Xh,get __assign(){return Vs},__asyncDelegator:Gh,__asyncGenerator:jh,__asyncValues:Vh,__await:Jr,__awaiter:Mh,__classPrivateFieldGet:Wh,__classPrivateFieldIn:Yh,__classPrivateFieldSet:zh,__createBinding:un,__decorate:Lh,__disposeResources:Qh,__esDecorate:Ch,__exportStar:Nh,__extends:Ih,__generator:Fh,__importDefault:Hh,__importStar:qh,__makeTemplateObject:Kh,__metadata:Oh,__param:Rh,__propKey:Ph,__read:eo,__rest:Dh,__rewriteRelativeImportExtension:Zh,__runInitializers:wh,__setFunctionName:kh,__spread:Bh,__spreadArray:$h,__spreadArrays:Uh,__values:Ks,default:Um},Symbol.toStringTag,{value:"Module"})),ce=ri($m);var oi={},ll;function to(){if(ll)return oi;ll=1,Object.defineProperty(oi,"__esModule",{value:!0}),oi.isAgent=i,oi.buildAgent=e;function i(r){return typeof r=="object"&&r!==null&&"fetchHandler"in r&&typeof r.fetchHandler=="function"&&(!("did"in r)||r.did===void 0||typeof r.did=="string")}function e(r){const s=typeof r=="function"?{did:void 0,fetchHandler:r}:typeof r=="string"||r instanceof URL?{did:void 0,service:r}:r;if(i(s))return s;const{service:n,fetch:a=globalThis.fetch}=s;if(typeof a!="function")throw new TypeError("fetch() is not available in this environment");return{get did(){return s.did},async fetchHandler(o,u){const l=s.headers!=null&&u.headers!=null?t(s.headers,u.headers):s.headers||u.headers;return a(new URL(o,n),l!==u.headers?{...u,headers:l}:u)}}}function t(r,s){const n=new Headers(r),a=s instanceof Headers?s:new Headers(s);for(const[o,u]of a.entries())n.set(o,u);return n}return oi}var li={},Tn={},bn={},xn={},ui={},ul;function jm(){if(ul)return ui;ul=1,Object.defineProperty(ui,"__esModule",{value:!0}),ui.$type=i,ui.$typed=e;function i(t,r){return r==="main"?t:`${t}#${r}`}function e(t,r){return t.$type===r?t:{...t,$type:r}}return ui}var ci={},An={},rt={},bt={},cl;function cn(){if(cl)return bt;cl=1,Object.defineProperty(bt,"__esModule",{value:!0}),bt.InvalidDidError=void 0,bt.ensureValidDid=i,bt.ensureValidDidRegex=t,bt.isValidDid=r;function i(n){if(!n.startsWith("did:"))throw new s('DID requires "did:" prefix');if(n.length>2048)throw new s("DID is too long (2048 chars max)");if(n.endsWith(":")||n.endsWith("%"))throw new s('DID can not end with ":" or "%"');if(!/^[a-zA-Z0-9._:%-]*$/.test(n))throw new s("Disallowed characters in DID (ASCII letters, digits, and a couple other characters only)");const{length:a,1:o}=n.split(":");if(a<3)throw new s("DID requires prefix, method, and method-specific content");if(!/^[a-z]+$/.test(o))throw new s("DID method must be lower-case letters")}const e=/^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$/;function t(n){if(!e.test(n))throw new s("DID didn't validate via regex");if(n.length>2048)throw new s("DID is too long (2048 chars max)")}function r(n){return n.length<=2048&&e.test(n)}class s extends Error{}return bt.InvalidDidError=s,bt}var In={},dl;function ro(){return dl||(dl=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.DisallowedDomainError=i.UnsupportedDomainError=i.ReservedHandleError=i.InvalidHandleError=i.DISALLOWED_TLDS=i.INVALID_HANDLE=void 0,i.ensureValidHandle=e,i.ensureValidHandleRegex=r,i.normalizeHandle=s,i.normalizeAndEnsureValidHandle=n,i.isValidHandle=a,i.isValidTld=o,i.INVALID_HANDLE="handle.invalid",i.DISALLOWED_TLDS=[".local",".arpa",".invalid",".localhost",".internal",".example",".alt",".onion"];function e(h){if(!/^[a-zA-Z0-9.-]*$/.test(h))throw new u("Disallowed characters in handle (ASCII letters, digits, dashes, periods only)");if(h.length>253)throw new u("Handle is too long (253 chars max)");const f=h.split(".");if(f.length<2)throw new u("Handle domain needs at least two parts");for(let g=0;g<f.length;g++){const p=f[g];if(p.length<1)throw new u("Handle parts can not be empty");if(p.length>63)throw new u("Handle part too long (max 63 chars)");if(p.endsWith("-")||p.startsWith("-"))throw new u("Handle parts can not start or end with hyphens");if(g+1===f.length&&!/^[a-zA-Z]/.test(p))throw new u("Handle final component (TLD) must start with ASCII letter")}}const t=/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function r(h){if(h.length>253)throw new u("Handle is too long (253 chars max)");if(!t.test(h))throw new u("Handle didn't validate via regex")}function s(h){return h.toLowerCase()}function n(h){const f=s(h);return e(f),f}function a(h){return h.length<=253&&t.test(h)}function o(h){for(const f of i.DISALLOWED_TLDS)if(h.endsWith(f))return!1;return!0}class u extends Error{}i.InvalidHandleError=u;class l extends Error{}i.ReservedHandleError=l;class c extends Error{}i.UnsupportedDomainError=c;class d extends Error{}i.DisallowedDomainError=d}(In)),In}var hl;function io(){if(hl)return rt;hl=1,Object.defineProperty(rt,"__esModule",{value:!0}),rt.isHandleIdentifier=t,rt.isDidIdentifier=r,rt.assertAtIdentifierString=s,rt.ensureValidAtIdentifier=s,rt.asAtIdentifierString=n,rt.isAtIdentifierString=a,rt.isValidAtIdentifier=a,rt.ifAtIdentifierString=o;const i=cn(),e=ro();function t(u){return!r(u)}function r(u){return u.startsWith("did:")}function s(u){try{if(!u||typeof u!="string")throw new TypeError("Identifier must be a non-empty string");u.startsWith("did:")?(0,i.ensureValidDidRegex)(u):(0,e.ensureValidHandleRegex)(u)}catch(l){throw new e.InvalidHandleError("Invalid DID or handle",{cause:l})}}function n(u){return s(u),u}function a(u){return!u||typeof u!="string"?!1:u.startsWith("did:")?(0,i.isValidDid)(u):(0,e.isValidHandle)(u)}function o(u){return a(u)?u:void 0}return rt}var Dn={},je={},fl;function so(){if(fl)return je;fl=1,Object.defineProperty(je,"__esModule",{value:!0}),je.InvalidNsidError=je.NSID=void 0,je.ensureValidNsid=e,je.parseNsid=t,je.isValidNsid=r,je.validateNsid=s,je.ensureValidNsidRegex=c,je.validateNsidRegex=d;class i{constructor(g){w(this,"segments");this.segments=t(g)}static parse(g){return new i(g)}static create(g,p){const m=[...g.split(".").reverse(),p].join(".");return new i(m)}static isValid(g){return r(g)}static from(g){return g instanceof i?g:Array.isArray(g)?new i(g.join(".")):new i(String(g))}get authority(){return this.segments.slice(0,this.segments.length-1).reverse().join(".")}get name(){return this.segments.at(this.segments.length-1)}toString(){return this.segments.join(".")}}je.NSID=i;function e(f){const g=s(f);if(!g.success)throw new h(g.message)}function t(f){const g=s(f);if(!g.success)throw new h(g.message);return g.value}function r(f){return d(f).success}function s(f){if(f.length>317)return{success:!1,message:"NSID is too long (317 chars max)"};if(n(f))return{success:!1,message:"Disallowed characters in NSID (ASCII letters, digits, dashes, periods only)"};const g=f.split(".");if(g.length<3)return{success:!1,message:"NSID needs at least three parts"};for(const p of g){if(p.length<1)return{success:!1,message:"NSID parts can not be empty"};if(p.length>63)return{success:!1,message:"NSID part too long (max 63 chars)"};if(o(p)||u(p))return{success:!1,message:"NSID parts can not start or end with hyphen"}}return a(g[0])?{success:!1,message:"NSID first part may not start with a digit"}:l(g[g.length-1])?{success:!0,value:g}:{success:!1,message:"NSID name part must be only letters and digits (and no leading digit)"}}function n(f){return!/^[a-zA-Z0-9.-]*$/.test(f)}function a(f){const g=f.charCodeAt(0);return g>=48&&g<=57}function o(f){return f.charCodeAt(0)===45}function u(f){return f.charCodeAt(f.length-1)===45}function l(f){return!a(f)&&!f.includes("-")}function c(f){const g=d(f);if(!g.success)throw new h(g.message)}function d(f){return f.length>317?{success:!1,message:"NSID is too long (317 chars max)"}:f.length<5||!/^[a-zA-Z](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?:\.[a-zA-Z](?:[a-zA-Z0-9]{0,62})?)$/.test(f)?{success:!1,message:"NSID didn't validate via regex"}:{success:!0,value:f}}class h extends Error{}return je.InvalidNsidError=h,je}var Ut={},gl;function Jh(){if(gl)return Ut;gl=1,Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.InvalidRecordKeyError=void 0,Ut.ensureValidRecordKey=s,Ut.isValidRecordKey=n;const i=512,e=1,t=new Set([".",".."]),r=/^[a-zA-Z0-9_~.:-]{1,512}$/;function s(o){if(o.length>i||o.length<e)throw new a(`record key must be ${e} to ${i} characters`);if(t.has(o))throw new a('record key can not be "." or ".."');if(!r.test(o))throw new a("record key syntax not valid (regex)")}function n(o){return o.length>=e&&o.length<=i&&r.test(o)&&!t.has(o)}class a extends Error{}return Ut.InvalidRecordKeyError=a,Ut}var ur={},ml;function Gm(){if(ml)return ur;ml=1,Object.defineProperty(ur,"__esModule",{value:!0}),ur.ensureValidAtUri=s,ur.ensureValidAtUriRegex=n,ur.isValidAtUri=a;const i=io(),e=cn(),t=ro(),r=so();function s(o){const u=o.indexOf("#");if(u!==-1){if(o.charCodeAt(u+1)!==47)throw new Error("ATURI fragment must be non-empty and start with slash");if(o.includes("#",u+1))throw new Error('ATURI can have at most one "#", separating fragment out');const m=o.slice(u+1);if(!/^\/[a-zA-Z0-9._~:@!$&')(*+,;=%[\]/-]*$/.test(m))throw new Error("Disallowed characters in ATURI fragment (ASCII)")}const l=u===-1?o:o.slice(0,u);if(l.length>8*1024)throw new Error("ATURI is far too long");if(!l.startsWith("at://"))throw new Error('ATURI must start with "at://"');if(!/^[a-zA-Z0-9._~:@!$&')(*+,;=%/-]*$/.test(l))throw new Error("Disallowed characters in ATURI (ASCII)");const c=l.indexOf("/",5),d=c===-1?l.slice(5):l.slice(5,c);try{(0,i.ensureValidAtIdentifier)(d)}catch(m){throw new Error("ATURI authority must be a valid handle or DID",{cause:m})}const h=c===-1?-1:c+1,f=h===-1?-1:l.indexOf("/",h);if(h!==-1){const m=f===-1?l.slice(h):l.slice(h,f);if(m.length===0)throw new Error("ATURI can not have a slash after authority without a path segment");if(!(0,r.isValidNsid)(m))throw new Error("ATURI requires first path segment (if supplied) to be valid NSID")}const g=f===-1?-1:f+1,p=g===-1?-1:l.indexOf("/",g);if(g!==-1&&g===l.length)throw new Error("ATURI can not have a slash after collection, unless record key is provided");if(p!==-1)throw new Error("ATURI path can have at most two parts, and no trailing slash")}function n(o){const u=/^at:\/\/(?<authority>[a-zA-Z0-9._:%-]+)(\/(?<collection>[a-zA-Z0-9-.]+)(\/(?<rkey>[a-zA-Z0-9._~:@!$&%')(*+,;=-]+))?)?(#(?<fragment>\/[a-zA-Z0-9._~:@!$&%')(*+,;=\-[\]/\\]*))?$/,l=o.match(u);if(!l||!l.groups)throw new Error("ATURI didn't validate via regex");const c=l.groups;try{(0,t.ensureValidHandleRegex)(c.authority)}catch{try{(0,e.ensureValidDidRegex)(c.authority)}catch{throw new Error("ATURI authority must be a valid handle or DID")}}if(c.collection&&!(0,r.isValidNsid)(c.collection))throw new Error("ATURI collection path segment must be a valid NSID");if(o.length>8*1024)throw new Error("ATURI is far too long")}function a(o){try{s(o)}catch{return!1}return!0}return ur}var pl;function Vm(){return pl||(pl=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.AtUri=i.ATP_URI_REGEX=void 0;const e=ce,t=io(),r=cn(),s=so(),n=Jh();e.__exportStar(Gm(),i),i.ATP_URI_REGEX=/^(at:\/\/)?((?:did:[a-z0-9:%-]+)|(?:[a-z0-9][a-z0-9.:-]*))(\/[^?#\s]*)?(\?[^#\s]+)?(#[^\s]+)?$/i;const a=/^(\/[^?#\s]*)?(\?[^#\s]+)?(#[^\s]+)?$/i;class o{constructor(d,h){w(this,"hash");w(this,"host");w(this,"pathname");w(this,"searchParams");const f=h!==void 0?Object.assign(typeof h=="string"?u(h):{host:h.host},l(d)):u(d);(0,t.ensureValidAtIdentifier)(f.host),this.hash=f.hash??"",this.host=f.host,this.pathname=f.pathname??"",this.searchParams=f.searchParams}static make(d,h,f){let g=d;return h&&(g+="/"+h),f&&(g+="/"+f),new o(g)}get protocol(){return"at:"}get origin(){return`at://${this.host}`}get did(){const{host:d}=this;if((0,t.isDidIdentifier)(d))return d;throw new r.InvalidDidError(`AtUri "${this}" does not have a DID hostname`)}get hostname(){return this.host}set hostname(d){(0,t.ensureValidAtIdentifier)(d),this.host=d}get search(){return this.searchParams.toString()}set search(d){this.searchParams=new URLSearchParams(d)}get collection(){return this.pathname.split("/").filter(Boolean)[0]||""}get collectionSafe(){const{collection:d}=this;return(0,s.ensureValidNsid)(d),d}set collection(d){(0,s.ensureValidNsid)(d),this.unsafelySetCollection(d)}unsafelySetCollection(d){const h=this.pathname.split("/").filter(Boolean);h[0]=d,this.pathname=h.join("/")}get rkey(){return this.pathname.split("/").filter(Boolean)[1]||""}get rkeySafe(){const{rkey:d}=this;return(0,n.ensureValidRecordKey)(d),d}set rkey(d){(0,n.ensureValidRecordKey)(d),this.unsafelySetRkey(d)}unsafelySetRkey(d){const h=this.pathname.split("/").filter(Boolean);h[0]||(h[0]="undefined"),h[1]=d,this.pathname=h.join("/")}get href(){return this.toString()}toString(){let d=this.pathname||"/";d.startsWith("/")||(d=`/${d}`);let h="";this.searchParams.size&&(h=`?${this.searchParams.toString()}`);let f=this.hash;return f&&!f.startsWith("#")&&(f=`#${f}`),`at://${this.host}${d}${h}${f}`}}i.AtUri=o;function u(c){const d=c.match(i.ATP_URI_REGEX);if(!d)throw new Error(`Invalid AT uri: ${c}`);return{host:d[2],hash:d[5],pathname:d[3],searchParams:new URLSearchParams(d[4])}}function l(c){const d=c.match(a);if(!d)throw new Error(`Invalid path: ${c}`);return{hash:d[3],pathname:d[1],searchParams:new URLSearchParams(d[2])}}}(Dn)),Dn}var ve={},yl;function Km(){if(yl)return ve;yl=1,Object.defineProperty(ve,"__esModule",{value:!0}),ve.InvalidDatetimeError=void 0,ve.assertAtprotoDate=e,ve.asAtprotoDate=t,ve.isAtprotoDate=r,ve.ifAtprotoDate=s,ve.assertDatetimeString=n,ve.ensureValidDatetime=n,ve.asDatetimeString=a,ve.isDatetimeString=o,ve.isValidDatetime=o,ve.ifDatetimeString=u,ve.currentDatetimeString=l,ve.toDatetimeString=c,ve.normalizeDatetime=d,ve.normalizeDatetimeAlways=h;class i extends Error{}ve.InvalidDatetimeError=i;function e(y){const S=v(y);if(!S.success)throw new i(S.message)}function t(y){return e(y),y}function r(y){return v(y).success}function s(y){return r(y)?y:void 0}function n(y){const S=m(y);if(!S.success)throw new i(S.message)}function a(y){return n(y),y}function o(y){return m(y).success}function u(y){return o(y)?y:void 0}function l(){return c(new Date)}function c(y){return t(y).toISOString()}function d(y){const S=new Date(y);if(r(S))return S.toISOString();if(isNaN(S.getTime())&&!/.*(([+-]\d\d:?\d\d)|[a-zA-Z])$/.test(y)){const _=new Date(`${y}Z`);if(r(_))return _.toISOString()}throw new i("datetime did not parse as any timestamp format")}function h(y){try{return d(y)}catch{return"1970-01-01T00:00:00.000Z"}}const f=y=>({success:!1,message:y}),g=y=>({success:!0,value:y}),p=/^(?<full_year>[0-9]{4})-(?<date_month>0[1-9]|1[012])-(?<date_mday>[0-2][0-9]|3[01])T(?<time_hour>[0-1][0-9]|2[0-3]):(?<time_minute>[0-5][0-9]):(?<time_second>[0-5][0-9]|60)(?<time_secfrac>\.[0-9]+)?(?<time_offset>Z|(?<time_numoffset>[+-](?:[0-1][0-9]|2[0-3]):[0-5][0-9]))$/;function m(y){if(typeof y!="string")return f("datetime must be a string");if(y.length>64)return f("datetime is too long (64 chars max)");if(y.endsWith("-00:00"))return f('datetime can not use "-00:00" for UTC timezone');if(!p.test(y))return f("datetime is not in a valid format (must match RFC 3339 & ISO 8601 with 'Z' or ±hh:mm timezone)");const S=new Date(y);return v(S)}function v(y){const S=y.getUTCFullYear();return Number.isNaN(S)?f("datetime did not parse as ISO 8601"):S<0?f("datetime normalized to a negative time"):S>9999?f("datetime year is too far in the future"):g(y)}return ve}var di={},vl;function qm(){if(vl)return di;vl=1,Object.defineProperty(di,"__esModule",{value:!0}),di.parseLanguageString=e,di.isValidLanguage=t;const i=/^((?<grandfathered>(en-GB-oed|i-ami|i-bnn|i-default|i-enochian|i-hak|i-klingon|i-lux|i-mingo|i-navajo|i-pwn|i-tao|i-tay|i-tsu|sgn-BE-FR|sgn-BE-NL|sgn-CH-DE)|(art-lojban|cel-gaulish|no-bok|no-nyn|zh-guoyu|zh-hakka|zh-min|zh-min-nan|zh-xiang))|((?<language>([A-Za-z]{2,3}(-(?<extlang>[A-Za-z]{3}(-[A-Za-z]{3}){0,2}))?)|[A-Za-z]{4}|[A-Za-z]{5,8})(-(?<script>[A-Za-z]{4}))?(-(?<region>[A-Za-z]{2}|[0-9]{3}))?(-(?<variant>[A-Za-z0-9]{5,8}|[0-9][A-Za-z0-9]{3}))*(-(?<extension>[0-9A-WY-Za-wy-z](-[A-Za-z0-9]{2,8})+))*(-(?<privateUseA>x(-[A-Za-z0-9]{1,8})+))?)|(?<privateUseB>x(-[A-Za-z0-9]{1,8})+))$/;function e(r){const s=r.match(i);if(!(s!=null&&s.groups))return null;const{groups:n}=s;return{grandfathered:n.grandfathered,language:n.language,extlang:n.extlang,script:n.script,region:n.region,variant:n.variant,extension:n.extension,privateUse:n.privateUseA||n.privateUseB}}function t(r){return i.test(r)}return di}var $t={},El;function Hm(){if(El)return $t;El=1,Object.defineProperty($t,"__esModule",{value:!0}),$t.InvalidTidError=void 0,$t.ensureValidTid=t,$t.isValidTid=r;const i=13,e=/^[234567abcdefghij][234567abcdefghijklmnopqrstuvwxyz]{12}$/;function t(n){if(n.length!==i)throw new s(`TID must be ${i} characters`);if(!e.test(n))throw new s("TID syntax not valid (regex)")}function r(n){return n.length===i&&e.test(n)}class s extends Error{}return $t.InvalidTidError=s,$t}var Ji={},Sl;function Wm(){if(Sl)return Ji;Sl=1,Object.defineProperty(Ji,"__esModule",{value:!0}),Ji.isValidUri=i;function i(e){return/^\w+:(?:\/\/)?[^\s/][^\s]*$/.test(e)}return Ji}var _l;function Kr(){return _l||(_l=1,function(i){Object.defineProperty(i,"__esModule",{value:!0});const e=ce;e.__exportStar(io(),i),e.__exportStar(Vm(),i),e.__exportStar(Km(),i),e.__exportStar(cn(),i),e.__exportStar(ro(),i),e.__exportStar(so(),i),e.__exportStar(qm(),i),e.__exportStar(Jh(),i),e.__exportStar(Hm(),i),e.__exportStar(Wm(),i)}(An)),An}var Tl;function zm(){if(Tl)return ci;Tl=1,Object.defineProperty(ci,"__esModule",{value:!0}),ci.isLexiconRecordKey=e,ci.asLexiconRecordKey=t;const i=Kr();function e(r){return r==="any"||r==="nsid"||r==="tid"||typeof r=="string"&&r.startsWith("literal:")&&r.length>8&&(0,i.isValidRecordKey)(r.slice(8))}function t(r){if(e(r))return r;throw new Error(`Invalid record key: ${String(r)}`)}return ci}var mt={},bl;function no(){if(bl)return mt;bl=1,Object.defineProperty(mt,"__esModule",{value:!0}),mt.success=i,mt.failure=e,mt.failureReason=t,mt.successValue=r,mt.catchall=s,mt.createCatcher=n;function i(a){return{success:!0,value:a}}function e(a){return{success:!1,reason:a}}function t(a){return a.reason}function r(a){return a.value}function s(a){return a instanceof Error?e(a):e(new Error("Unknown error",{cause:a}))}function n(a){return o=>{if(o instanceof a)return e(o);throw o}}return mt}var hi={},es={},xl;function ii(){if(xl)return es;xl=1,Object.defineProperty(es,"__esModule",{value:!0}),es.lazyProperty=i;function i(e,t,r){return Object.defineProperty(e,t,{value:r,writable:!1,enumerable:!1,configurable:!0}),r}return es}var fi={},gi={},mi={},Ln={},cr={},Rn={},Ym=ef,Al=128,Xm=-128,Qm=Math.pow(2,31);function ef(i,e,t){e=e||[],t=t||0;for(var r=t;i>=Qm;)e[t++]=i&255|Al,i/=128;for(;i&Xm;)e[t++]=i&255|Al,i>>>=7;return e[t]=i|0,ef.bytes=t-r+1,e}var Zm=Ra,Jm=128,Il=127;function Ra(i,r){var t=0,r=r||0,s=0,n=r,a,o=i.length;do{if(n>=o)throw Ra.bytes=0,new RangeError("Could not decode varint");a=i[n++],t+=s<28?(a&Il)<<s:(a&Il)*Math.pow(2,s),s+=7}while(a>=Jm);return Ra.bytes=n-r,t}var ep=Math.pow(2,7),tp=Math.pow(2,14),rp=Math.pow(2,21),ip=Math.pow(2,28),sp=Math.pow(2,35),np=Math.pow(2,42),ap=Math.pow(2,49),op=Math.pow(2,56),lp=Math.pow(2,63),up=function(i){return i<ep?1:i<tp?2:i<rp?3:i<ip?4:i<sp?5:i<np?6:i<ap?7:i<op?8:i<lp?9:10},cp={encode:Ym,decode:Zm,encodingLength:up},qs=cp;const Ca=(i,e=0)=>[qs.decode(i,e),qs.decode.bytes],Hs=(i,e,t=0)=>(qs.encode(i,e,t),e),Ws=i=>qs.encodingLength(i),dp=(i,e)=>{if(i===e)return!0;if(i.byteLength!==e.byteLength)return!1;for(let t=0;t<i.byteLength;t++)if(i[t]!==e[t])return!1;return!0},ao=i=>{if(i instanceof Uint8Array&&i.constructor.name==="Uint8Array")return i;if(i instanceof ArrayBuffer)return new Uint8Array(i);if(ArrayBuffer.isView(i))return new Uint8Array(i.buffer,i.byteOffset,i.byteLength);throw new Error("Unknown type, must be binary type")},hp=i=>new TextEncoder().encode(i),fp=i=>new TextDecoder().decode(i),zs=(i,e)=>{const t=e.byteLength,r=Ws(i),s=r+Ws(t),n=new Uint8Array(s+t);return Hs(i,n,0),Hs(t,n,r),n.set(e,s),new dn(i,t,e,n)},tf=i=>{const e=ao(i),[t,r]=Ca(e),[s,n]=Ca(e.subarray(r)),a=e.subarray(r+n);if(a.byteLength!==s)throw new Error("Incorrect length");return new dn(t,s,a,e)},rf=(i,e)=>i===e?!0:i.code===e.code&&i.size===e.size&&dp(i.bytes,e.bytes);class dn{constructor(e,t,r,s){this.code=e,this.size=t,this.digest=r,this.bytes=s}}const gp=Object.freeze(Object.defineProperty({__proto__:null,Digest:dn,create:zs,decode:tf,equals:rf},Symbol.toStringTag,{value:"Module"}));function mp(i,e){if(i.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var s=0;s<i.length;s++){var n=i.charAt(s),a=n.charCodeAt(0);if(t[a]!==255)throw new TypeError(n+" is ambiguous");t[a]=s}var o=i.length,u=i.charAt(0),l=Math.log(o)/Math.log(256),c=Math.log(256)/Math.log(o);function d(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var p=0,m=0,v=0,y=g.length;v!==y&&g[v]===0;)v++,p++;for(var S=(y-v)*c+1>>>0,_=new Uint8Array(S);v!==y;){for(var T=g[v],x=0,b=S-1;(T!==0||x<m)&&b!==-1;b--,x++)T+=256*_[b]>>>0,_[b]=T%o>>>0,T=T/o>>>0;if(T!==0)throw new Error("Non-zero carry");m=x,v++}for(var I=S-m;I!==S&&_[I]===0;)I++;for(var A=u.repeat(p);I<S;++I)A+=i.charAt(_[I]);return A}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var p=0;if(g[p]!==" "){for(var m=0,v=0;g[p]===u;)m++,p++;for(var y=(g.length-p)*l+1>>>0,S=new Uint8Array(y);g[p];){var _=t[g.charCodeAt(p)];if(_===255)return;for(var T=0,x=y-1;(_!==0||T<v)&&x!==-1;x--,T++)_+=o*S[x]>>>0,S[x]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");v=T,p++}if(g[p]!==" "){for(var b=y-v;b!==y&&S[b]===0;)b++;for(var I=new Uint8Array(m+(y-b)),A=m;b!==y;)I[A++]=S[b++];return I}}}function f(g){var p=h(g);if(p)return p;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:f}}var pp=mp,yp=pp;class vp{constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Ep{constructor(e,t,r){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return sf(this,e)}}class Sp{constructor(e){this.decoders=e}or(e){return sf(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const sf=(i,e)=>new Sp({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}});class _p{constructor(e,t,r,s){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=s,this.encoder=new vp(e,t,r),this.decoder=new Ep(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const hn=({name:i,prefix:e,encode:t,decode:r})=>new _p(i,e,t,r),Hi=({prefix:i,name:e,alphabet:t})=>{const{encode:r,decode:s}=yp(t,e);return hn({prefix:i,name:e,encode:r,decode:n=>ao(s(n))})},Tp=(i,e,t,r)=>{const s={};for(let c=0;c<e.length;++c)s[e[c]]=c;let n=i.length;for(;i[n-1]==="=";)--n;const a=new Uint8Array(n*t/8|0);let o=0,u=0,l=0;for(let c=0;c<n;++c){const d=s[i[c]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);u=u<<t|d,o+=t,o>=8&&(o-=8,a[l++]=255&u>>o)}if(o>=t||255&u<<8-o)throw new SyntaxError("Unexpected end of data");return a},bp=(i,e,t)=>{const r=e[e.length-1]==="=",s=(1<<t)-1;let n="",a=0,o=0;for(let u=0;u<i.length;++u)for(o=o<<8|i[u],a+=8;a>t;)a-=t,n+=e[s&o>>a];if(a&&(n+=e[s&o<<t-a]),r)for(;n.length*t&7;)n+="=";return n},Le=({name:i,prefix:e,bitsPerChar:t,alphabet:r})=>hn({prefix:e,name:i,encode(s){return bp(s,r,t)},decode(s){return Tp(s,r,t,i)}}),_t=Hi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xp=Hi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Ap=Object.freeze(Object.defineProperty({__proto__:null,base58btc:_t,base58flickr:xp},Symbol.toStringTag,{value:"Module"})),wi=Le({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ip=Le({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Dp=Le({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Lp=Le({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Rp=Le({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Cp=Le({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),wp=Le({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Pp=Le({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),kp=Le({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Op=Object.freeze(Object.defineProperty({__proto__:null,base32:wi,base32hex:Rp,base32hexpad:wp,base32hexpadupper:Pp,base32hexupper:Cp,base32pad:Dp,base32padupper:Lp,base32upper:Ip,base32z:kp},Symbol.toStringTag,{value:"Module"}));class we{constructor(e,t,r,s){this.code=t,this.version=e,this.multihash=r,this.bytes=s,this.byteOffset=s.byteOffset,this.byteLength=s.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:rs,byteLength:rs,code:ts,version:ts,multihash:ts,bytes:ts,_baseCache:rs,asCID:rs})}toV0(){switch(this.version){case 0:return this;default:{const{code:e,multihash:t}=this;if(e!==pi)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Bp)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return we.createV0(t)}}}toV1(){switch(this.version){case 0:{const{code:e,digest:t}=this.multihash,r=zs(e,t);return we.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&rf(this.multihash,e.multihash)}toString(e){const{bytes:t,version:r,_baseCache:s}=this;switch(r){case 0:return Fp(t,s,e||_t.encoder);default:return Np(t,s,e||wi.encoder)}}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(e){return $p(/^0\.0/,jp),!!(e&&(e[Ll]||e.asCID===e))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(e){if(e instanceof we)return e;if(e!=null&&e.asCID===e){const{version:t,code:r,multihash:s,bytes:n}=e;return new we(t,r,s,n||Dl(t,r,s.bytes))}else if(e!=null&&e[Ll]===!0){const{version:t,multihash:r,code:s}=e,n=tf(r);return we.create(t,s,n)}else return null}static create(e,t,r){if(typeof t!="number")throw new Error("String codecs are no longer supported");switch(e){case 0:{if(t!==pi)throw new Error(`Version 0 CID must use dag-pb (code: ${pi}) block encoding`);return new we(e,t,r,r.bytes)}case 1:{const s=Dl(e,t,r.bytes);return new we(e,t,r,s)}default:throw new Error("Invalid version")}}static createV0(e){return we.create(0,pi,e)}static createV1(e,t){return we.create(1,e,t)}static decode(e){const[t,r]=we.decodeFirst(e);if(r.length)throw new Error("Incorrect length");return t}static decodeFirst(e){const t=we.inspectBytes(e),r=t.size-t.multihashSize,s=ao(e.subarray(r,r+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");const n=s.subarray(t.multihashSize-t.digestSize),a=new dn(t.multihashCode,t.digestSize,n,s);return[t.version===0?we.createV0(a):we.createV1(t.codec,a),e.subarray(t.size)]}static inspectBytes(e){let t=0;const r=()=>{const[d,h]=Ca(e.subarray(t));return t+=h,d};let s=r(),n=pi;if(s===18?(s=0,t=0):s===1&&(n=r()),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);const a=t,o=r(),u=r(),l=t+u,c=l-a;return{version:s,codec:n,multihashCode:o,digestSize:u,multihashSize:c,size:l}}static parse(e,t){const[r,s]=Mp(e,t),n=we.decode(s);return n._baseCache.set(r,e),n}}const Mp=(i,e)=>{switch(i[0]){case"Q":{const t=e||_t;return[_t.prefix,t.decode(`${_t.prefix}${i}`)]}case _t.prefix:{const t=e||_t;return[_t.prefix,t.decode(i)]}case wi.prefix:{const t=e||wi;return[wi.prefix,t.decode(i)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[i[0],e.decode(i)]}}},Fp=(i,e,t)=>{const{prefix:r}=t;if(r!==_t.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);const s=e.get(r);if(s==null){const n=t.encode(i).slice(1);return e.set(r,n),n}else return s},Np=(i,e,t)=>{const{prefix:r}=t,s=e.get(r);if(s==null){const n=t.encode(i);return e.set(r,n),n}else return s},pi=112,Bp=18,Dl=(i,e,t)=>{const r=Ws(i),s=r+Ws(e),n=new Uint8Array(s+t.byteLength);return Hs(i,n,0),Hs(e,n,r),n.set(t,s),n},Ll=Symbol.for("@ipld/js-cid/CID"),ts={writable:!1,configurable:!1,enumerable:!0},rs={writable:!1,enumerable:!1,configurable:!1},Up="0.0.0-dev",$p=(i,e)=>{if(i.test(Up))console.warn(e);else throw new Error(e)},jp=`CID.isCID(v) is deprecated and will be removed in the next major release.
9090+Following code pattern:
9191+9292+if (CID.isCID(value)) {
9393+ doSomethingWithCID(value)
9494+}
9595+9696+Is replaced with:
9797+9898+const cid = CID.asCID(value)
9999+if (cid) {
100100+ // Make sure to use cid instead of value
101101+ doSomethingWithCID(cid)
102102+}
103103+`,Gp=Object.freeze(Object.defineProperty({__proto__:null,CID:we},Symbol.toStringTag,{value:"Module"})),Vp=ri(Gp),Kp=ri(gp),nf=({name:i,code:e,encode:t})=>new qp(i,e,t);class qp{constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?zs(this.code,t):t.then(r=>zs(this.code,r))}else throw Error("Unknown type, must be binary type")}}const af=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),Hp=nf({name:"sha2-256",code:18,encode:af("SHA-256")}),Wp=nf({name:"sha2-512",code:19,encode:af("SHA-512")}),zp=Object.freeze(Object.defineProperty({__proto__:null,sha256:Hp,sha512:Wp},Symbol.toStringTag,{value:"Module"})),Yp=ri(zp);var yi={},Rl;function Xp(){if(Rl)return yi;Rl=1,Object.defineProperty(yi,"__esModule",{value:!0}),yi.toHexString=i,yi.isUint8=e;function i(t){return`0x${t.toString(16).padStart(2,"0")}`}function e(t){return Number.isInteger(t)&&t>=0&&t<256}return yi}var dr={},Cl;function Wi(){if(Cl)return dr;Cl=1,Object.defineProperty(dr,"__esModule",{value:!0}),dr.isObject=i,dr.isPlainObject=r,dr.isPlainProto=s;function i(n){return n!=null&&typeof n=="object"}const e=Object.prototype,t=Object.prototype.toString;function r(n){return i(n)&&s(n)}function s(n){const a=Object.getPrototypeOf(n);return a===null?!0:(a===e||Object.getPrototypeOf(a)===null)&&t.call(n)==="[object Object]"}return dr}var Cn={},hr={},vi={},wl;function si(){var e;if(wl)return vi;wl=1,Object.defineProperty(vi,"__esModule",{value:!0}),vi.NodeJSBuffer=void 0;const i="Bu"+"f".repeat(2)+"er";return vi.NodeJSBuffer=((e=globalThis==null?void 0:globalThis[i])==null?void 0:e.prototype)instanceof Uint8Array&&"byteLength"in globalThis[i]?globalThis[i]:null,vi}var Pl;function Qp(){if(Pl)return hr;Pl=1,Object.defineProperty(hr,"__esModule",{value:!0}),hr.ui8ConcatNode=void 0,hr.ui8ConcatPonyfill=t;const e=si().NodeJSBuffer;hr.ui8ConcatNode=e?function(s){return e.concat(s)}:null;function t(r){let s=0;for(const o of r)s+=o.length;const n=new Uint8Array(s);let a=0;for(const o of r)n.set(o,a),a+=o.length;return n}return hr}var xt={};const Zp=hn({prefix:"\0",name:"identity",encode:i=>fp(i),decode:i=>hp(i)}),Jp=Object.freeze(Object.defineProperty({__proto__:null,identity:Zp},Symbol.toStringTag,{value:"Module"})),e0=Le({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),t0=Object.freeze(Object.defineProperty({__proto__:null,base2:e0},Symbol.toStringTag,{value:"Module"})),r0=Le({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),i0=Object.freeze(Object.defineProperty({__proto__:null,base8:r0},Symbol.toStringTag,{value:"Module"})),s0=Hi({prefix:"9",name:"base10",alphabet:"0123456789"}),n0=Object.freeze(Object.defineProperty({__proto__:null,base10:s0},Symbol.toStringTag,{value:"Module"})),a0=Le({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),o0=Le({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),l0=Object.freeze(Object.defineProperty({__proto__:null,base16:a0,base16upper:o0},Symbol.toStringTag,{value:"Module"})),u0=Hi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),c0=Hi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),d0=Object.freeze(Object.defineProperty({__proto__:null,base36:u0,base36upper:c0},Symbol.toStringTag,{value:"Module"})),h0=Le({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),f0=Le({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),g0=Le({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),m0=Le({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),p0=Object.freeze(Object.defineProperty({__proto__:null,base64:h0,base64pad:f0,base64url:g0,base64urlpad:m0},Symbol.toStringTag,{value:"Module"})),of=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),y0=of.reduce((i,e,t)=>(i[t]=e,i),[]),v0=of.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function E0(i){return i.reduce((e,t)=>(e+=y0[t],e),"")}function S0(i){const e=[];for(const t of i){const r=v0[t.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(r)}return new Uint8Array(e)}const _0=hn({prefix:"🚀",name:"base256emoji",encode:E0,decode:S0}),T0=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:_0},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const kl={...Jp,...t0,...i0,...n0,...l0,...Op,...d0,...Ap,...p0,...T0};function lf(i,e,t,r){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:r}}}const Ol=lf("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),wn=lf("ascii","a",i=>{let e="a";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return e},i=>{i=i.substring(1);const e=new Uint8Array(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),uf={utf8:Ol,"utf-8":Ol,hex:kl.base16,latin1:wn,ascii:wn,binary:wn,...kl};function b0(i,e="utf8"){const t=uf[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${i}`)}const x0=Object.freeze(Object.defineProperty({__proto__:null,fromString:b0},Symbol.toStringTag,{value:"Module"})),cf=ri(x0);var Ml;function A0(){if(Ml)return xt;Ml=1,Object.defineProperty(xt,"__esModule",{value:!0}),xt.fromBase64Node=xt.fromBase64Native=void 0,xt.fromBase64Ponyfill=r;const i=cf,t=si().NodeJSBuffer;xt.fromBase64Native=typeof Uint8Array.fromBase64=="function"?function(a,o="base64"){return Uint8Array.fromBase64(a,{alphabet:o,lastChunkHandling:"loose"})}:null,xt.fromBase64Node=t?function(a,o="base64"){const u=t.from(a,o);return s(a,u),new Uint8Array(u.buffer,u.byteOffset,u.byteLength)}:null;function r(n,a="base64"){const o=(0,i.fromString)(n,n.endsWith("=")?`${a}pad`:a);return s(n,o),o}function s(n,a){const o=n.endsWith("==")?2:n.endsWith("=")?1:0,u=n.length-o,l=Math.floor(u*3/4);if(a.length!==l)throw new Error("Invalid base64 string");const c=a.length/3*4,d=c%4===0?0:4-c%4,h=c+d;if(n.length>h)throw new Error("Invalid base64 string");for(let f=Math.ceil(c);f<n.length-o;f++){const g=n.charCodeAt(f);if(!(g>=65&&g<=90)&&!(g>=97&&g<=122)&&!(g>=48&&g<=57)&&g!==43&&g!==47)throw new Error("Invalid base64 string")}}return xt}var At={};function I0(i,e="utf8"){const t=uf[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(i).substring(1)}const D0=Object.freeze(Object.defineProperty({__proto__:null,toString:I0},Symbol.toStringTag,{value:"Module"})),df=ri(D0);var Fl;function hf(){if(Fl)return At;Fl=1,Object.defineProperty(At,"__esModule",{value:!0}),At.toBase64Node=At.toBase64Native=void 0,At.toBase64Ponyfill=r;const i=df,t=si().NodeJSBuffer;At.toBase64Native=typeof Uint8Array.prototype.toBase64=="function"?function(n,a="base64"){return n.toBase64({alphabet:a,omitPadding:!0})}:null,At.toBase64Node=t?function(n,a="base64"){const u=(n instanceof t?n:t.from(n)).toString(a);return u.charCodeAt(u.length-1)===61?u.charCodeAt(u.length-2)===61?u.slice(0,-2):u.slice(0,-1):u}:null;function r(s,n="base64"){return(0,i.toString)(s,n)}return At}var Nl;function oo(){return Nl||(Nl=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.ui8Concat=i.fromBase64=i.toBase64=void 0,i.ifUint8Array=s,i.asUint8Array=n,i.ui8Equals=a;const e=Qp(),t=A0(),r=hf();i.toBase64=r.toBase64Native??r.toBase64Node??r.toBase64Ponyfill,i.fromBase64=t.fromBase64Native??t.fromBase64Node??t.fromBase64Ponyfill;/* v8 ignore next -- @preserve */i.toBase64===r.toBase64Ponyfill||(i.fromBase64,t.fromBase64Ponyfill);function s(o){if(o instanceof Uint8Array)return o}function n(o){if(o instanceof Uint8Array)return o;if(ArrayBuffer.isView(o))return new Uint8Array(o.buffer,o.byteOffset,o.byteLength/Uint8Array.BYTES_PER_ELEMENT);if(o instanceof ArrayBuffer)return new Uint8Array(o)}function a(o,u){if(o.byteLength!==u.byteLength)return!1;for(let l=0;l<o.byteLength;l++)if(o[l]!==u[l])return!1;return!0}i.ui8Concat=e.ui8ConcatNode??e.ui8ConcatPonyfill}(Cn)),Cn}var Bl;function fn(){return Bl||(Bl=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.CID=i.SHA512_HASH_CODE=i.SHA256_HASH_CODE=i.RAW_DATA_CODEC=i.CBOR_DATA_CODEC=void 0,i.multihashEquals=o,i.asMultiformatsCID=u,i.isRawCid=l,i.isDaslCid=c,i.isCborCid=d,i.checkCid=h,i.isCid=f,i.ifCid=g,i.asCid=p,i.decodeCid=m,i.parseCid=v,i.validateCidString=y,i.parseCidSafe=S,i.ensureValidCidString=_,i.isCidForBytes=T,i.createCid=x,i.cidForCbor=b,i.cidForRawBytes=I,i.cidForRawHash=A;const e=Vp;Object.defineProperty(i,"CID",{enumerable:!0,get:function(){return e.CID}});const t=Kp,r=Yp,s=Xp(),n=Wi(),a=oo();i.CBOR_DATA_CODEC=113,i.RAW_DATA_CODEC=85,i.SHA256_HASH_CODE=r.sha256.code,i.SHA512_HASH_CODE=r.sha512.code;function o(L,P){return L===P?!0:L.code===P.code&&(0,a.ui8Equals)(L.digest,P.digest)}function u(L){return e.CID.asCID(L)??e.CID.create(L.version,L.code,(0,t.create)(L.multihash.code,L.multihash.digest))}function l(L){return L.version===1&&L.code===i.RAW_DATA_CODEC}function c(L){return L.version===1&&(L.code===i.RAW_DATA_CODEC||L.code===i.CBOR_DATA_CODEC)&&L.multihash.code===i.SHA256_HASH_CODE&&L.multihash.digest.byteLength===32}function d(L){return L.code===i.CBOR_DATA_CODEC&&c(L)}function h(L,P){switch(P==null?void 0:P.flavor){case void 0:return!0;case"cbor":return d(L);case"dasl":return c(L);case"raw":return l(L);default:throw new TypeError(`Unknown CID flavor: ${P==null?void 0:P.flavor}`)}}function f(L,P){return D(L)&&h(L,P)}function g(L,P){return f(L,P)?L:null}function p(L,P){if(f(L,P))return L;throw new Error(`Invalid ${P!=null&&P.flavor?`${P.flavor} CID`:"CID"} "${L}"`)}function m(L,P){const O=e.CID.decode(L);return p(O,P)}function v(L,P){const O=e.CID.parse(L);return p(O,P)}function y(L,P){var O;return((O=S(L,P))==null?void 0:O.toString())===L}function S(L,P){try{return v(L,P)}catch{return null}}function _(L,P){if(!y(L,P))throw new Error(`Invalid CID string "${L}"`)}async function T(L,P){if(L.multihash.code===r.sha256.code){const O=await r.sha256.digest(P);return o(O,L.multihash)}if(L.multihash.code===r.sha512.code){const O=await r.sha512.digest(P);return o(O,L.multihash)}throw new Error(`Unsupported CID multihash code: ${(0,s.toHexString)(L.multihash.code)}`)}function x(L,P,O){return e.CID.createV1(L,(0,t.create)(P,O))}async function b(L){const P=await r.sha256.digest(L);return e.CID.createV1(i.CBOR_DATA_CODEC,P)}async function I(L){const P=await r.sha256.digest(L);return e.CID.createV1(i.RAW_DATA_CODEC,P)}function A(L){if(L.length!==32)throw new Error(`Invalid SHA-256 hash length: ${(0,s.toHexString)(L.length)}`);return x(i.RAW_DATA_CODEC,r.sha256.code,L)}function D(L){if(e.CID.asCID(L))return L.bytes!=null;try{if(!(0,n.isObject)(L))return!1;const P=L;if(P.version!==0&&P.version!==1||!(0,s.isUint8)(P.code)||!(0,n.isObject)(P.multihash))return!1;const O=P.multihash;return!(!(0,s.isUint8)(O.code)||!(O.digest instanceof Uint8Array)||!(P.bytes instanceof Uint8Array)||P.bytes[0]!==P.version||P.bytes[1]!==P.code||P.bytes[2]!==O.code||P.bytes[3]!==O.digest.length||P.bytes.length!==4+O.digest.length||!(0,a.ui8Equals)(P.bytes.subarray(4),O.digest)||typeof P.equals!="function"||P.equals(P)!==!0)}catch{return!1}}}(Rn)),Rn}var Ul;function L0(){if(Ul)return cr;Ul=1,Object.defineProperty(cr,"__esModule",{value:!0}),cr.isBlobRef=r,cr.isLegacyBlobRef=s,cr.enumBlobRefs=n;const i=fn(),e=Wi(),t=Number.isSafeInteger;function r(a,o){if(!(0,e.isPlainObject)(a)||(a==null?void 0:a.$type)!=="blob")return!1;const{mimeType:u,size:l,ref:c}=a;if(typeof u!="string"||!u.includes("/"))return!1;if(!(l===-1&&(o==null?void 0:o.strict)===!1)){if(!t(l)||l<0)return!1}if(typeof c!="object"||c===null)return!1;for(const h in a)if(h!=="$type"&&h!=="mimeType"&&h!=="ref"&&h!=="size")return!1;return!!(0,i.ifCid)(c,(o==null?void 0:o.strict)===!1?void 0:{flavor:"raw"})}function s(a){if(!(0,e.isPlainObject)(a))return!1;const{cid:o,mimeType:u}=a;if(typeof o!="string"||typeof u!="string"||u.length===0)return!1;for(const l in a)if(l!=="cid"&&l!=="mimeType")return!1;return!!(0,i.validateCidString)(o)}function*n(a,o){const u=(o==null?void 0:o.allowLegacy)===!0,l=[a],c=new Set;do{const d=l.pop();if(d!=null&&typeof d=="object"){if(Array.isArray(d)){if(c.has(d))continue;c.add(d),l.push(...d)}else if((0,e.isPlainProto)(d)){if(c.has(d))continue;if(c.add(d),r(d,o))yield d;else if(u&&s(d))yield d;else for(const h of Object.values(d))h!=null&&l.push(h)}}}while(l.length>0);c.clear()}return cr}var is={},$l;function R0(){if($l)return is;$l=1,Object.defineProperty(is,"__esModule",{value:!0}),is.lexEquals=r;const i=fn(),e=Wi(),t=oo();function r(s,n){var u;if(Object.is(s,n))return!0;if(s==null||n==null||typeof s!="object"||typeof n!="object")return!1;if(Array.isArray(s)){if(!Array.isArray(n)||s.length!==n.length)return!1;for(let l=0;l<s.length;l++)if(!r(s[l],n[l]))return!1;return!0}else if(Array.isArray(n))return!1;if(ArrayBuffer.isView(s))return ArrayBuffer.isView(n)?(0,t.ui8Equals)(s,n):!1;if(ArrayBuffer.isView(n))return!1;if((0,i.isCid)(s))return((u=(0,i.ifCid)(n))==null?void 0:u.equals(s))===!0;if((0,i.isCid)(n))return!1;if(!(0,e.isPlainObject)(s)||!(0,e.isPlainObject)(n))throw new TypeError("Invalid LexValue (expected CID, Uint8Array, or LexMap)");const a=Object.keys(s),o=Object.keys(n);if(a.length!==o.length)return!1;for(const l of a){const c=s[l],d=n[l];if(c===void 0){if(d===void 0&&o.includes(l))continue;return!1}else if(d===void 0)return!1;if(!r(c,d))return!1}return!0}return is}var Ei={},jl;function C0(){if(jl)return Ei;jl=1,Object.defineProperty(Ei,"__esModule",{value:!0}),Ei.LexError=void 0;class i extends Error{constructor(r,s,n){super(s,n);w(this,"error");w(this,"name","LexError");this.error=r}toString(){return`${this.name}: [${this.error}] ${this.message}`}toJSON(){const{error:r,message:s}=this;return{error:r,message:s||void 0}}}return Ei.LexError=i,Ei}var It={},Gl;function w0(){if(Gl)return It;Gl=1,Object.defineProperty(It,"__esModule",{value:!0}),It.isLexMap=t,It.isLexArray=r,It.isLexScalar=s,It.isLexValue=n,It.isTypedLexMap=a;const i=fn(),e=Wi();function t(o){return(0,e.isPlainObject)(o)&&Object.values(o).every(n)}function r(o){return Array.isArray(o)&&o.every(n)}function s(o){switch(typeof o){case"object":return o===null||o instanceof Uint8Array||(0,i.isCid)(o);case"string":case"boolean":return!0;case"number":if(Number.isInteger(o))return!0;default:return!1}}function n(o){const u=[o],l=new Set;do{const c=u.pop();if((0,e.isPlainObject)(c)){if(l.has(c))return!1;l.add(c),u.push(...Object.values(c))}else if(Array.isArray(c)){if(l.has(c))return!1;l.add(c),u.push(...c)}else if(!s(c))return!1}while(u.length>0);return l.clear(),!0}function a(o){return t(o)&&typeof o.$type=="string"&&o.$type.length>0}return It}var Pn={},fr={},Vl;function P0(){if(Vl)return fr;Vl=1,Object.defineProperty(fr,"__esModule",{value:!0}),fr.utf8FromBase64Node=void 0,fr.utf8FromBase64Ponyfill=s;const i=cf,t=si().NodeJSBuffer;fr.utf8FromBase64Node=t?function(a,o="base64"){return t.from(a,o).toString("utf8")}:null;const r=new TextDecoder;function s(n,a){const o=(0,i.fromString)(n,a);return r.decode(o)}return fr}var gr={},jt={},ss={},Kl;function lo(){if(Kl)return ss;Kl=1,ss.decodeUnicodeData=i,ss.findUnicodeRangeIndex=e;function i(t,r=""){let s=[],n=t.split(",").map(o=>o?parseInt(o,36):0),a=0;for(let o=0;o<n.length;o++)o%2?s.push([a,a+n[o],r?parseInt(r[o>>1],36):0]):a=n[o];return s}function e(t,r,s=0,n=r.length-1){for(;s<=n;){let a=s+n>>>1,o=r[a];if(t<o[0])n=a-1;else if(t>o[1])s=a+1;else return a}return-1}return ss}var mr={},ql;function k0(){if(ql)return mr;ql=1,mr.grapheme_ranges=mr.GraphemeCategory=void 0;var i=lo();return mr.GraphemeCategory={Any:0,CR:1,Control:2,Extend:3,Extended_Pictographic:4,L:5,LF:6,LV:7,LVT:8,Prepend:9,Regional_Indicator:10,SpacingMark:11,T:12,V:13,ZWJ:14},mr.grapheme_ranges=(0,i.decodeUnicodeData)(",9,a,,b,1,d,,e,h,3j,w,4p,,4t,,4u,,lc,33,w3,6,13l,18,14v,,14x,1,150,1,153,,16o,5,174,a,17g,,18r,k,19s,,1cm,6,1ct,,1cv,5,1d3,1,1d6,3,1e7,,1e9,,1f4,q,1ie,a,1kb,8,1kt,,1li,3,1ln,8,1lx,2,1m1,4,1nd,2,1ow,1,1p3,8,1qi,n,1r6,,1r7,v,1s3,,1tm,,1tn,,1to,,1tq,2,1tt,7,1u1,3,1u5,,1u6,1,1u9,6,1uq,1,1vl,,1vm,1,1x8,,1xa,,1xb,1,1xd,3,1xj,1,1xn,1,1xp,,1xz,,1ya,1,1z2,,1z5,1,1z7,,20s,,20u,2,20x,1,213,1,217,2,21d,,228,1,22d,,22p,1,22r,,24c,,24e,2,24h,4,24n,1,24p,,24r,1,24t,,25e,1,262,5,269,,26a,1,27w,,27y,1,280,,281,3,287,1,28b,1,28d,,28l,2,28y,1,29u,,2bi,,2bj,,2bk,,2bl,1,2bq,2,2bu,2,2bx,,2c7,,2dc,,2dd,2,2dg,,2f0,,2f2,2,2f5,3,2fa,2,2fe,3,2fp,1,2g2,1,2gx,,2gy,1,2ik,,2im,,2in,1,2ip,,2iq,,2ir,1,2iu,2,2iy,3,2j9,1,2jm,1,2k3,,2kg,1,2ki,1,2m3,1,2m6,,2m7,1,2m9,3,2me,2,2mi,2,2ml,,2mm,,2mv,,2n6,1,2o1,,2o2,1,2q2,,2q7,,2q8,1,2qa,2,2qe,,2qg,6,2qn,,2r6,1,2sx,,2sz,,2t0,6,2tj,7,2wh,,2wj,,2wk,8,2x4,6,2zc,1,305,,307,,309,,30e,1,31t,d,327,,328,4,32e,1,32l,a,32x,z,346,,371,3,375,,376,5,37d,1,37f,1,37h,1,386,1,388,1,38e,2,38x,3,39e,,39g,,39h,1,39p,,3a5,,3cw,2n,3fk,1z,3hk,2f,3tp,2,4k2,3,4ky,2,4lu,1,4mq,1,4ok,1,4om,,4on,6,4ou,7,4p2,,4p3,1,4p5,a,4pp,,4qz,2,4r2,,4r3,,4ud,1,4vd,,4yo,2,4yr,3,4yv,1,4yx,2,4z4,1,4z6,,4z7,5,4zd,2,55j,1,55l,1,55n,,579,,57a,,57b,,57c,6,57k,,57m,,57p,7,57x,5,583,9,58f,,59s,u,5c0,3,5c4,,5dg,9,5dq,3,5du,2,5ez,8,5fk,1,5fm,,5gh,,5gi,3,5gm,1,5go,5,5ie,,5if,,5ig,1,5ii,2,5il,,5im,,5in,4,5k4,7,5kc,7,5kk,1,5km,1,5ow,2,5p0,c,5pd,,5pe,6,5pp,,5pw,,5pz,,5q0,1,5vk,1r,6bv,,6bw,,6bx,,6by,1,6co,6,6d8,,6dl,,6e8,f,6hc,w,6jm,,6k9,,6ms,5,6nd,1,6xm,1,6y0,,70o,,72n,,73d,a,73s,2,79e,,7fu,1,7g6,,7gg,,7i3,3,7i8,5,7if,b,7is,35,7m8,39,7pk,a,7pw,,7py,,7q5,,7q9,,7qg,,7qr,1,7r8,,7rb,,7rg,,7ri,,7rn,2,7rr,,7s3,4,7th,2,7tt,,7u8,,7un,,850,1,8hx,2,8ij,1,8k0,,8k5,,8vj,2,8zj,,928,v,wvj,3,wvo,9,wwu,1,wz4,1,x6q,,x6u,,x6z,,x7n,1,x7p,1,x7r,,x7w,,xa8,1,xbo,f,xc4,1,xcw,h,xdr,,xeu,7,xfr,a,xg2,,xg3,,xgg,s,xhc,2,xhf,,xir,,xis,1,xiu,3,xiy,1,xj0,1,xj2,1,xj4,,xk5,,xm1,5,xm7,1,xm9,1,xmb,1,xmd,1,xmr,,xn0,,xn1,,xoc,,xps,,xpu,2,xpz,1,xq6,1,xq9,,xrf,,xrg,1,xri,1,xrp,,xrq,,xyb,1,xyd,,xye,1,xyg,,xyh,1,xyk,,xyl,,1e68,f,1e74,f,1edb,,1ehq,1,1ek0,b,1eyl,,1f4w,,1f92,4,1gjl,2,1gjp,1,1gjw,3,1gl4,2,1glb,,1gpx,1,1h5w,3,1h7t,4,1hgr,1,1hj0,3,1hl2,a,1hmq,3,1hq8,,1hq9,,1hqa,,1hrs,e,1htc,,1htf,1,1htr,2,1htu,,1hv4,2,1hv7,3,1hvb,1,1hvd,1,1hvh,,1hvm,,1hvx,,1hxc,2,1hyf,4,1hyk,,1hyl,7,1hz9,1,1i0j,,1i0w,1,1i0y,,1i2b,2,1i2e,8,1i2n,,1i2o,,1i2q,1,1i2x,3,1i32,,1i33,,1i5o,2,1i5r,2,1i5u,1,1i5w,3,1i66,,1i69,,1ian,,1iao,2,1iar,7,1ibk,1,1ibm,1,1id7,1,1ida,,1idb,,1idc,,1idd,3,1idj,1,1idn,1,1idp,,1idz,,1iea,1,1iee,6,1ieo,4,1igo,,1igp,1,1igr,5,1igy,,1ih1,,1ih3,2,1ih6,,1ih8,1,1iha,2,1ihd,,1ihe,,1iht,1,1ik5,2,1ik8,7,1ikg,1,1iki,2,1ikl,,1ikm,,1ila,,1ink,,1inl,1,1inn,5,1int,,1inu,,1inv,1,1inx,,1iny,,1inz,1,1io1,,1io2,1,1iun,,1iuo,1,1iuq,3,1iuw,3,1iv0,1,1iv2,,1iv3,1,1ivw,1,1iy8,2,1iyb,7,1iyj,1,1iyl,,1iym,,1iyn,1,1j1n,,1j1o,,1j1p,,1j1q,1,1j1s,7,1j4t,,1j4u,,1j4v,,1j4y,3,1j52,,1j53,4,1jcc,2,1jcf,8,1jco,,1jcp,1,1jjk,,1jjl,4,1jjr,1,1jjv,3,1jjz,,1jk0,,1jk1,,1jk2,,1jk3,,1jo1,2,1jo4,3,1joa,1,1joc,3,1jog,,1jok,,1jpd,9,1jqr,5,1jqx,,1jqy,,1jqz,3,1jrb,,1jrl,5,1jrr,1,1jrt,2,1jt0,5,1jt6,c,1jtj,,1jtk,1,1k4v,,1k4w,6,1k54,5,1k5a,,1k5b,,1k7m,l,1k89,,1k8a,6,1k8h,,1k8i,1,1k8k,,1k8l,1,1kc1,5,1kca,,1kcc,1,1kcf,6,1kcm,,1kcn,,1kei,4,1keo,1,1ker,1,1ket,,1keu,,1kev,,1koj,1,1kol,1,1kow,1,1koy,,1koz,,1kqc,1,1kqe,4,1kqm,1,1kqo,2,1kre,,1ovk,f,1ow0,,1ow7,e,1xr2,b,1xre,2,1xrh,2,1zow,4,1zqo,6,206b,,206f,3,20jz,,20k1,1i,20lr,3,20o4,,20og,1,2ftp,1,2fts,3,2jgg,19,2jhs,m,2jxh,4,2jxp,5,2jxv,7,2jy3,7,2jyd,6,2jze,3,2k3m,2,2lmo,1i,2lob,1d,2lpx,,2lqc,,2lqz,4,2lr5,e,2mtc,6,2mtk,g,2mu3,6,2mub,1,2mue,4,2mxb,,2n1s,6,2nce,,2ne4,3,2nsc,3,2nzi,1,2ok0,6,2on8,6,2pz4,73,2q6l,2,2q7j,,2q98,5,2q9q,1,2qa6,,2qa9,9,2qb1,1k,2qcm,p,2qdd,e,2qe2,,2qen,,2qeq,8,2qf0,3,2qfd,c1,2qrf,4,2qrk,8t,2r0m,7d,2r9c,3j,2rg4,b,2rit,16,2rkc,3,2rm0,7,2rmi,5,2rns,7,2rou,29,2rrg,1a,2rss,9,2rt3,c8,2scg,sd,jny8,v,jnz4,2n,jo1s,3j,jo5c,6n,joc0,2rz","262122424333333393233393339333333333393393b3b3b3b3b333b33b3bb33333b3b3333333b3b33bb3333b33b3bb33333b3bbb333b333b33333b3b3b3b3333b3b33b3bb39333b33b33b3b3b333b333333b3b333333b33b3b3333b3335dc333333b3b3b33323333b3bb3b33b3b3b3333b3333b3b333bb3b33b3b3b3b3b333b333b3323e2244234444444444444444444444444444444444444444443333333333b3b3bb33333b353b3b3b3b333b3b333b333333b3bb3b3b3bb333232333333333333333b3b3333bb3b393933b3b33bb3b393b3b3b3333b33b33b3bbb33b333b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b33bb39b9b3b33b3b33b9333b393b3b33b33b3b3b3333393b3b3b33b39bb3b332333b333dd3b33332333323333333333333333333333344444444a44444434444444444444423232"),mr}var ns={},Hl;function O0(){if(Hl)return ns;Hl=1,ns.consonant_ranges=void 0;var i=lo();return ns.consonant_ranges=(0,i.decodeUnicodeData)("1sl,10,1ug,7,1vc,7,1w5,j,1wq,6,1wy,,1x2,3,1y4,1,1y7,,1yo,1,239,j,23u,6,242,1,245,4,261,,26t,j,27e,6,27m,1,27p,4,28s,1,28v,,29d,,2dx,j,2ei,f,2fs,2,2l1,11"),ns}var Wl;function M0(){if(Wl)return jt;Wl=1,jt.countGrapheme=jt.countGraphemes=n,jt.graphemeSegments=s,jt.splitGraphemes=a;var i=lo(),e=k0();jt.GraphemeCategory=e.GraphemeCategory;var t=O0();const r=65535;function*s(m){let v=m.codePointAt(0);if(v==null)return;let y=v<=r?1:2,S=m.length,_=g(v),T=0,x=0,b=!1,I=!1,A=!1,D=0,L=_,P=v;for(;y<S;){v=m.codePointAt(y),T=g(v);let O=!0;_===1?O=T!==6:_===2||_===6||T===1||T===2||T===6?O=!0:T===3||T===14||T===11||_===9?O=!1:_===14&&T===4?O=!b:_===10&&T===10?O=x++%2===1:_===5?O=!(T===5||T===13||T===7||T===8):((_===7||_===13)&&(T===13||T===12)||(_===8||_===12)&&T===12||T===0&&I&&A&&p(v))&&(O=!1),O?(yield{segment:m.slice(D,y),index:D,input:m,_hd:P,_catBegin:L,_catEnd:_},b=!1,x=0,D=y,L=T,P=v):T===14&&(_===3||_===4)?b=!0:v>=2325&&(!I&&_===0&&(I=p(P)),I&&T===3?A=A||v===2381||v===2509||v===2637||v===2765||v===2893||v===3149||v===3405:A=!1),y+=v<=r?1:2,_=T}D<S&&(yield{segment:m.slice(D),index:D,input:m,_hd:P,_catBegin:L,_catEnd:_})}function n(m){let v=0;for(let y of s(m))v+=1;return v}function*a(m){for(let v of s(m))yield v.segment}const o=new Uint8Array(6080),u=128,l=12287,c=new Uint8Array(1536),d=40960,h=44031,f=(()=>{let m=0;for(;;){let[v,y,S]=e.grapheme_ranges[m];if(v>h)break;if(m++,!(y<u||v>l&&y<d))for(let _=v;_<=y;_++){let T,x=0;_<=l?(T=o,x=_-u>>1):(T=c,x=_-d>>1),T[x]=_&1?T[x]&15|S<<4:T[x]&240|S}}return m})();function g(m){if(m<u)return m>=32?0:m===10?6:m===13?1:2;if(m<=l){let y=o[m-u>>1];return m&1?y>>4:y&15}if(m<d)return m<12336?m>=12330?3:0:m<12443?m===12336||m===12349?4:m>=12441?3:0:m===12951||m===12953?4:0;if(m<=h){let y=c[m-d>>1];return m&1?y>>4:y&15}if(m<=55203)return(m-44032)%28===0?7:8;if(m<=55295)return m<=55238?m>=55216?13:0:m>=55243?12:0;if(m<65024)return m===64286?3:0;let v=(0,i.findUnicodeRangeIndex)(m,e.grapheme_ranges,f);return v<0?0:e.grapheme_ranges[v][2]}function p(m){return(0,i.findUnicodeRangeIndex)(m,t.consonant_ranges)>=0}return jt}var zl;function F0(){if(zl)return gr;zl=1,Object.defineProperty(gr,"__esModule",{value:!0}),gr.graphemeLenNative=void 0,gr.graphemeLenPonyfill=t;const i=M0(),e="Segmenter"in Intl&&typeof Intl.Segmenter=="function"?new Intl.Segmenter:null;gr.graphemeLenNative=e?function(s){let n=0;for(const a of e.segment(s))n++;return n}:null;function t(r){return(0,i.countGraphemes)(r)}return gr}var pr={},Yl;function N0(){if(Yl)return pr;Yl=1,Object.defineProperty(pr,"__esModule",{value:!0}),pr.utf8LenNode=void 0,pr.utf8LenCompute=e;const i=si();pr.utf8LenNode=i.NodeJSBuffer?function(r){return i.NodeJSBuffer.byteLength(r,"utf8")}:null;function e(t){let r=t.length,s;for(let n=0;n<t.length;n+=1)s=t.charCodeAt(n),s<=127||(s<=2047?r+=1:(r+=2,s>=55296&&s<=56319&&(s=t.charCodeAt(n+1),s>=56320&&s<=57343&&n++)));return r}return pr}var yr={},Xl;function B0(){if(Xl)return yr;Xl=1,Object.defineProperty(yr,"__esModule",{value:!0}),yr.utf8ToBase64Node=void 0,yr.utf8ToBase64Ponyfill=n;const i=df,e=si(),t=hf(),r=e.NodeJSBuffer;yr.utf8ToBase64Node=r?function(o,u){const l=r.from(o,"utf8");return t.toBase64Node(l,u)}:null;const s=new TextEncoder;function n(a,o){const u=s.encode(a);return(0,i.toString)(u,o)}return yr}var Ql;function U0(){return Ql||(Ql=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.utf8FromBase64=i.utf8ToBase64=i.utf8Len=i.graphemeLen=void 0;const e=P0(),t=F0(),r=N0(),s=B0();i.graphemeLen=t.graphemeLenNative??t.graphemeLenPonyfill;/* v8 ignore next -- @preserve */i.graphemeLen,t.graphemeLenPonyfill,i.utf8Len=r.utf8LenNode??r.utf8LenCompute,i.utf8ToBase64=s.utf8ToBase64Node??s.utf8ToBase64Ponyfill,i.utf8FromBase64=e.utf8FromBase64Node??e.utf8FromBase64Ponyfill}(Pn)),Pn}var Zl;function pe(){return Zl||(Zl=1,function(i){Object.defineProperty(i,"__esModule",{value:!0});const e=ce;e.__exportStar(L0(),i),e.__exportStar(fn(),i),e.__exportStar(R0(),i),e.__exportStar(C0(),i),e.__exportStar(w0(),i),e.__exportStar(Wi(),i),e.__exportStar(oo(),i),e.__exportStar(U0(),i)}(Ln)),Ln}var as={},Jl;function $0(){if(Jl)return as;Jl=1,Object.defineProperty(as,"__esModule",{value:!0}),as.arrayAgg=i;function i(e,t,r){if(e.length===0)return[];const s=[[e[0]]],n=Array(e.length);e:for(let a=1;a<e.length;a++){if(n[a])continue;const o=e[a];for(let u=0;u<s.length;u++)if(t(o,s[u][0])){s[u].push(o),n[a]=!0;continue e}s.push([o])}return s.map(r)}return as}var Ee={},eu;function uo(){if(eu)return Ee;eu=1,Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.IssueTooSmall=Ee.IssueTooBig=Ee.IssueRequiredKey=Ee.IssueInvalidValue=Ee.IssueInvalidType=Ee.IssueInvalidFormat=Ee.IssueCustom=Ee.Issue=void 0;const i=pe(),e=48,t="…";class r{constructor(_,T,x){w(this,"code");w(this,"path");w(this,"input");this.code=_,this.path=T,this.input=x}toString(){return`${this.message}${h(this.path)}`}toJSON(){return{code:this.code,path:this.path,message:this.message}}}Ee.Issue=r;class s extends r{constructor(T,x,b){super("custom",T,x);w(this,"path");w(this,"input");w(this,"message");this.path=T,this.input=x,this.message=b}}Ee.IssueCustom=s;class n extends r{constructor(T,x,b,I){super("invalid_format",T,x);w(this,"format");w(this,"detail");this.format=b,this.detail=I}get message(){return`Invalid ${this.formatDescription}${this.detail?` (${this.detail}, `:" ("}got ${m(this.input)})`}get formatDescription(){switch(this.format){case"at-identifier":return"AT identifier";case"did":return"DID";case"nsid":return"NSID";case"cid":return"CID string";case"tid":return"TID string";case"record-key":return"record key";default:return this.format}}toJSON(){return{...super.toJSON(),format:this.format}}}Ee.IssueInvalidFormat=n;class a extends r{constructor(T,x,b){super("invalid_type",T,x);w(this,"expected");this.expected=b}get message(){return`Expected ${p(this.expected.map(d))} value type (got ${m(this.input)})`}toJSON(){return{...super.toJSON(),expected:this.expected}}}Ee.IssueInvalidType=a;class o extends r{constructor(T,x,b){super("invalid_value",T,x);w(this,"values");this.values=b}get message(){return`Expected ${p(this.values.map(m))} (got ${m(this.input)})`}toJSON(){return{...super.toJSON(),values:this.values}}}Ee.IssueInvalidValue=o;class u extends r{constructor(T,x,b){super("required_key",T,x);w(this,"key");this.key=b}get message(){return`Missing required key "${String(this.key)}"`}toJSON(){return{...super.toJSON(),key:this.key}}}Ee.IssueRequiredKey=u;class l extends r{constructor(T,x,b,I,A){super("too_big",T,x);w(this,"maximum");w(this,"type");w(this,"actual");this.maximum=b,this.type=I,this.actual=A}get message(){return`${this.type} too big (maximum ${this.maximum}, got ${this.actual})`}toJSON(){return{...super.toJSON(),type:this.type,maximum:this.maximum}}}Ee.IssueTooBig=l;class c extends r{constructor(T,x,b,I,A){super("too_small",T,x);w(this,"minimum");w(this,"type");w(this,"actual");this.minimum=b,this.type=I,this.actual=A}get message(){return`${this.type} too small (minimum ${this.minimum}, got ${this.actual})`}toJSON(){return{...super.toJSON(),type:this.type,minimum:this.minimum}}}Ee.IssueTooSmall=c;function d(S){return S==="$typed"?'an object which includes the "$type" property':S}function h(S){return` at ${f(S)}`}function f(S){return`$${S.map(g).join("")}`}function g(S){return typeof S=="number"||typeof S=="symbol"?`[${String(S)}]`:/^[a-zA-Z_$][a-zA-Z0-9_]*$/.test(S)?`.${S}`:`[${JSON.stringify(S)}]`}function p(S){return S.length===0?"":S.length===1?S[0]:`one of ${S.slice(0,-1).join(", ")} or ${S.at(-1)}`}function m(S){switch(typeof S){case"bigint":return`${S}n`;case"number":case"boolean":return String(S);case"string":return JSON.stringify(S.length<e?S:`${S.slice(0,e-t.length)}${t}`);case"object":return S===null?"null":Array.isArray(S)?`[${y(S,m)}]`:(0,i.isPlainObject)(S)?`{${y(Object.entries(S),v)}}`:(0,i.ifCid)(S)?"cid":(0,i.isLegacyBlobRef)(S)?"legacy-blob":S instanceof Date?"date":S instanceof RegExp?"regexp":S instanceof Map?"map":S instanceof Set?"set":"object";default:return typeof S}}function v([S,_]){return`${JSON.stringify(S)}: ...`}function y(S,_,T=2){return S.slice(0,T).map(_).join(", ")+(S.length>T?", ...":"")}return Ee}var tu;function ff(){if(tu)return mi;tu=1,Object.defineProperty(mi,"__esModule",{value:!0}),mi.LexValidationError=void 0;const i=pe(),e=$0(),t=no(),r=uo();class s extends i.LexError{constructor(c,d){const h=a(c);super("InvalidRequest",h.join(", "),d);w(this,"name","LexValidationError");w(this,"issues");w(this,"success",!1);this.issues=h}get reason(){return this}toJSON(){return{...super.toJSON(),issues:this.issues.map(c=>c.toJSON())}}static fromFailures(c){if(c.length===1)return(0,t.failureReason)(c[0]);const d=c.flatMap(n);return new s(d,{cause:c.map(t.failureReason)})}}mi.LexValidationError=s;function n(u){return u.reason.issues}function a(u){return u.length<=1||u.length===2&&u[0].code!==u[1].code?u:[...(0,e.arrayAgg)(u.filter(l=>l instanceof r.IssueInvalidType),(l,c)=>o(l.path,c.path),l=>new r.IssueInvalidType(l[0].path,l[0].input,Array.from(new Set(l.flatMap(c=>c.expected))))),...(0,e.arrayAgg)(u.filter(l=>l instanceof r.IssueInvalidValue),(l,c)=>o(l.path,c.path),l=>new r.IssueInvalidValue(l[0].path,l[0].input,Array.from(new Set(l.flatMap(c=>c.values))))),...u.filter(l=>!(l instanceof r.IssueInvalidType)&&!(l instanceof r.IssueInvalidValue))]}function o(u,l){if(u.length!==l.length)return!1;for(let c=0;c<u.length;c++)if(u[c]!==l[c])return!1;return!0}return mi}var ru;function co(){if(ru)return gi;ru=1,Object.defineProperty(gi,"__esModule",{value:!0}),gi.ValidationContext=void 0;const i=no(),e=ff(),t=uo();class r{constructor(n){w(this,"options");w(this,"currentPath");w(this,"issues",[]);this.options=n,this.currentPath=Array.from(n.path)}static validate(n,a,o){return new r({path:(o==null?void 0:o.path)??[],mode:(o==null?void 0:o.mode)??"validate",strict:(o==null?void 0:o.strict)??!0}).validate(n,a)}get path(){return Array.from(this.currentPath)}concatPath(n){return n==null?this.path:this.currentPath.concat(n)}validate(n,a){const o=a.validateInContext(n,this);if(o.success){if(this.issues.length>0)return new e.LexValidationError(Array.from(this.issues));if(this.options.mode!=="parse"&&!Object.is(o.value,n))return this.issueInvalidValue(n,[o.value])}return o}validateChild(n,a,o){this.currentPath.push(a);try{return this.validate(n[a],o)}finally{this.currentPath.length--}}addIssue(n){this.issues.push(n)}success(n){return(0,i.success)(n)}failure(n){return n}issue(n){return this.failure(new e.LexValidationError([...this.issues,n]))}issueInvalidValue(n,a){return this.issue(new t.IssueInvalidValue(this.path,n,a))}issueInvalidType(n,a){return this.issue(new t.IssueInvalidType(this.path,n,a))}issueUnexpectedType(n,a){return this.issueInvalidType(n,[a])}issueRequiredKey(n,a){return this.issue(new t.IssueRequiredKey(this.path,n,a))}issueInvalidFormat(n,a,o){return this.issue(new t.IssueInvalidFormat(this.path,n,a,o))}issueTooBig(n,a,o,u){return this.issue(new t.IssueTooBig(this.path,n,o,a,u))}issueTooSmall(n,a,o,u){return this.issue(new t.IssueTooSmall(this.path,n,o,a,u))}issueInvalidPropertyValue(n,a,o){const u=n[a],l=this.concatPath(a);return this.issue(new t.IssueInvalidValue(l,u,o))}issueInvalidPropertyType(n,a,o){const u=n[a],l=this.concatPath(a);return this.issue(new t.IssueInvalidType(l,u,[o]))}}return gi.ValidationContext=r,gi}var iu;function j0(){if(iu)return fi;iu=1,Object.defineProperty(fi,"__esModule",{value:!0}),fi.StandardSchemaAdapter=void 0;const i=co();class e{constructor(r){w(this,"validator");w(this,"version",1);w(this,"vendor","@atproto/lex-schema");this.validator=r}validate(r,s){return i.ValidationContext.validate(r,this.validator,{...s==null?void 0:s.libraryOptions,mode:"parse"})}}return fi.StandardSchemaAdapter=e,fi}var su;function G0(){if(su)return hi;su=1,Object.defineProperty(hi,"__esModule",{value:!0}),hi.Schema=void 0;const i=ii(),e=j0(),t=co();class r{get"~standard"(){return(0,i.lazyProperty)(this,"~standard",new e.StandardSchemaAdapter(this))}assert(n,a){const o=this.safeValidate(n,a);if(!o.success)throw o.reason}check(n,a){this.assert(n,a)}cast(n,a){const o=this.safeValidate(n,a);if(o.success)return o.value;throw o.reason}matches(n,a){return this.safeValidate(n,a).success}ifMatches(n,a){return this.matches(n,a)?n:void 0}parse(n,a){const o=this.safeParse(n,a);if(o.success)return o.value;throw o.reason}safeParse(n,a){return t.ValidationContext.validate(n,this,{...a,mode:"parse"})}validate(n,a){const o=this.safeValidate(n,a);if(o.success)return o.value;throw o.reason}safeValidate(n,a){return t.ValidationContext.validate(n,this,{...a,mode:"validate"})}get $assert(){return(0,i.lazyProperty)(this,"$assert",this.assert.bind(this))}get $check(){return(0,i.lazyProperty)(this,"$check",this.check.bind(this))}get $cast(){return(0,i.lazyProperty)(this,"$cast",this.cast.bind(this))}get $matches(){return(0,i.lazyProperty)(this,"$matches",this.matches.bind(this))}get $ifMatches(){return(0,i.lazyProperty)(this,"$ifMatches",this.ifMatches.bind(this))}get $parse(){return(0,i.lazyProperty)(this,"$parse",this.parse.bind(this))}get $safeParse(){return(0,i.lazyProperty)(this,"$safeParse",this.safeParse.bind(this))}get $validate(){return(0,i.lazyProperty)(this,"$validate",this.validate.bind(this))}get $safeValidate(){return(0,i.lazyProperty)(this,"$safeValidate",this.safeValidate.bind(this))}}return hi.Schema=r,hi}var kn={},On={},nu;function V0(){return nu||(nu=1,function(i){(()=>{var e={d:(c,d)=>{for(var h in d)e.o(d,h)&&!e.o(c,h)&&Object.defineProperty(c,h,{enumerable:!0,get:d[h]})},o:(c,d)=>Object.prototype.hasOwnProperty.call(c,d),r:c=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(c,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(c,"__esModule",{value:!0})}},t={};function r(c,d){return d===void 0&&(d="-"),new RegExp("^(?!0{4}"+d+"0{2}"+d+"0{2})((?=[0-9]{4}"+d+"(((0[^2])|1[0-2])|02(?="+d+"(([0-1][0-9])|2[0-8])))"+d+"[0-9]{2})|(?=((([13579][26])|([2468][048])|(0[48]))0{2})|([0-9]{2}((((0|[2468])[48])|[2468][048])|([13579][26])))"+d+"02"+d+"29))([0-9]{4})"+d+"(?!((0[469])|11)"+d+"31)((0[1,3-9]|1[0-2])|(02(?!"+d+"3)))"+d+"(0[1-9]|[1-2][0-9]|3[0-1])$").test(c)}function s(c){var d=/\D/.exec(c);return d?d[0]:""}function n(c,d,h){d===void 0&&(d=":"),h===void 0&&(h=!1);var f=new RegExp("^([0-1]|2(?=([0-3])|4"+d+"00))[0-9]"+d+"[0-5][0-9]("+d+"([0-5]|6(?=0))[0-9])?(.[0-9]{1,9})?$");if(!h||!/[Z+\-]/.test(c))return f.test(c);if(/Z$/.test(c))return f.test(c.replace("Z",""));var g=c.includes("+"),p=c.split(/[+-]/),m=p[0],v=p[1];return f.test(m)&&function(y,S,_){return _===void 0&&(_=":"),new RegExp(S?"^(0(?!(2"+_+"4)|0"+_+"3)|1(?=([0-1]|2(?="+_+"[04])|[34](?="+_+"0))))([03469](?="+_+"[03])|[17](?="+_+"0)|2(?="+_+"[04])|5(?="+_+"[034])|8(?="+_+"[04]))"+_+"([03](?=0)|4(?=5))[05]$":"^(0(?=[^0])|1(?=[0-2]))([39](?="+_+"[03])|[0-24-8](?="+_+"00))"+_+"[03]0$").test(y)}(v,g,s(v))}function a(c){var d=c.split("T"),h=d[0],f=d[1],g=r(h,s(h));if(!f)return!1;var p,m=(p=f.match(/([^Z+\-\d])(?=\d+\1)/),Array.isArray(p)?p[0]:"");return g&&n(f,m,!0)}function o(c,d){return d===void 0&&(d="-"),new RegExp("^[0-9]{4}"+d+"(0(?=[^0])|1(?=[0-2]))[0-9]$").test(c)}e.r(t),e.d(t,{isValidDate:()=>r,isValidISODateString:()=>a,isValidTime:()=>n,isValidYearMonth:()=>o});var u=i;for(var l in t)u[l]=t[l];t.__esModule&&Object.defineProperty(u,"__esModule",{value:!0})})()}(On)),On}var au;function K0(){return au||(au=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.STRING_FORMATS=i.isUriString=i.isTidString=i.isRecordKeyString=i.isNsidString=i.isLanguageString=i.isHandleString=i.isDidString=i.isCidString=i.isAtUriString=i.toDatetimeString=i.currentDatetimeString=i.isDatetimeString=i.ifDatetimeString=i.asDatetimeString=i.isHandleIdentifier=i.isDidIdentifier=i.isAtIdentifierString=i.ifAtIdentifierString=i.asAtIdentifierString=void 0,i.isDatetimeStringLoose=o,i.isStringFormat=c,i.assertStringFormat=d,i.asStringFormat=h,i.ifStringFormat=f;const e=V0(),t=pe(),r=Kr();var s=Kr();Object.defineProperty(i,"asAtIdentifierString",{enumerable:!0,get:function(){return s.asAtIdentifierString}}),Object.defineProperty(i,"ifAtIdentifierString",{enumerable:!0,get:function(){return s.ifAtIdentifierString}}),Object.defineProperty(i,"isAtIdentifierString",{enumerable:!0,get:function(){return s.isAtIdentifierString}});var n=Kr();Object.defineProperty(i,"isDidIdentifier",{enumerable:!0,get:function(){return n.isDidIdentifier}}),Object.defineProperty(i,"isHandleIdentifier",{enumerable:!0,get:function(){return n.isHandleIdentifier}});var a=Kr();Object.defineProperty(i,"asDatetimeString",{enumerable:!0,get:function(){return a.asDatetimeString}}),Object.defineProperty(i,"ifDatetimeString",{enumerable:!0,get:function(){return a.ifDatetimeString}}),Object.defineProperty(i,"isDatetimeString",{enumerable:!0,get:function(){return a.isDatetimeString}});function o(g){if(typeof g!="string")return!1;try{return(0,e.isValidISODateString)(g)}catch{return!1}}var u=Kr();Object.defineProperty(i,"currentDatetimeString",{enumerable:!0,get:function(){return u.currentDatetimeString}}),Object.defineProperty(i,"toDatetimeString",{enumerable:!0,get:function(){return u.toDatetimeString}}),i.isAtUriString=r.isValidAtUri,i.isCidString=g=>(0,t.validateCidString)(g),i.isDidString=r.isValidDid,i.isHandleString=r.isValidHandle,i.isLanguageString=r.isValidLanguage,i.isNsidString=r.isValidNsid,i.isRecordKeyString=r.isValidRecordKey,i.isTidString=r.isValidTid,i.isUriString=r.isValidUri;const l=Object.freeze({__proto__:null,"at-identifier":[r.isAtIdentifierString],"at-uri":[i.isAtUriString],cid:[i.isCidString],datetime:[r.isDatetimeString,o],did:[i.isDidString],handle:[i.isHandleString],language:[i.isLanguageString],nsid:[i.isNsidString],"record-key":[i.isRecordKeyString],tid:[i.isTidString],uri:[i.isUriString]});function c(g,p,m){const v=l[p];if(!v)throw new TypeError(`Unknown string format: ${p}`);return((m==null?void 0:m.strict)===!1?v[1]??v[0]:v[0])(g)}function d(g,p,m){if(!c(g,p,m))throw new TypeError(`Invalid string format (${p}): ${g}`)}function h(g,p,m){return g}function f(g,p,m){return c(g,p,m)?g:void 0}i.STRING_FORMATS=Object.freeze(Object.keys(l))}(kn)),kn}var Mn={},ou;function q0(){return ou||(ou=1,Object.defineProperty(Mn,"__esModule",{value:!0})),Mn}var lu;function te(){return lu||(lu=1,function(i){Object.defineProperty(i,"__esModule",{value:!0});const e=ce;e.__exportStar(jm(),i),e.__exportStar(zm(),i),e.__exportStar(no(),i),e.__exportStar(G0(),i),e.__exportStar(K0(),i),e.__exportStar(q0(),i),e.__exportStar(ff(),i),e.__exportStar(uo(),i),e.__exportStar(co(),i)}(xn)),xn}var vr={},Fn={},Gt={},Si={},uu;function Be(){if(uu)return Si;uu=1,Object.defineProperty(Si,"__esModule",{value:!0}),Si.memoizedOptions=i,Si.memoizedTransformer=e;function i(t){let r=null;return function(...n){if(n.length>0)return t(...n);if(r!=null)return r.value;const a=t(...n);return r={value:a},a}}function e(t){let r;return function(n,...a){if(a.length>0)return t(n,...a);r??(r=new WeakMap);const o=r.get(n);if(o)return o;const u=t(n,...a);return r.set(n,u),u}}return Si}var cu;function gf(){if(cu)return Gt;cu=1,Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.array=Gt.ArraySchema=void 0;const i=te(),e=Be();class t extends i.Schema{constructor(a,o={}){super();w(this,"validator");w(this,"options");w(this,"type","array");this.validator=a,this.options=o}validateInContext(a,o){if(!Array.isArray(a))return o.issueUnexpectedType(a,"array");const{minLength:u,maxLength:l}=this.options;if(u!=null&&a.length<u)return o.issueTooSmall(a,"array",u,a.length);if(l!=null&&a.length>l)return o.issueTooBig(a,"array",l,a.length);let c;for(let d=0;d<a.length;d++){const h=o.validateChild(a,d,this.validator);if(!h.success)return h;if(h.value!==a[d]){if(o.options.mode==="validate")return o.issueInvalidPropertyValue(a,d,[h.value]);c??(c=Array.from(a)),c[d]=h.value}}return o.success(c??a)}}Gt.ArraySchema=t;function r(s,n){return new t(s,n)}return Gt.array=(0,e.memoizedTransformer)(r),Gt}var Nn={},du;function H0(){return du||(du=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.blob=i.BlobSchema=i.isLegacyBlobRef=i.isBlobRef=void 0;const e=pe();Object.defineProperty(i,"isBlobRef",{enumerable:!0,get:function(){return e.isBlobRef}}),Object.defineProperty(i,"isLegacyBlobRef",{enumerable:!0,get:function(){return e.isLegacyBlobRef}});const t=te(),r=Be();class s extends t.Schema{constructor(l){super();w(this,"options");w(this,"type","blob");this.options=l}validateInContext(l,c){var h,f;const d=n.call(c,l,this.options);if(!d)return c.issueUnexpectedType(l,"blob");if(c.options.strict){const g=(h=this.options)==null?void 0:h.accept;if(g&&!a(d.mimeType,g))return c.issueInvalidPropertyValue(d,"mimeType",g);const p=(f=this.options)==null?void 0:f.maxSize;if(p!=null&&"size"in d&&d.size>p)return c.issueTooBig(d,"blob",p,d.size)}return c.success(d)}matchesMime(l){var d;const c=(d=this.options)==null?void 0:d.accept;return c?a(l,c):!0}}i.BlobSchema=s;function n(o,u){if((o==null?void 0:o.$type)!==void 0)return(0,e.isBlobRef)(o,this.options)?o:null;if(u!=null&&u.allowLegacy){if((0,e.isLegacyBlobRef)(o))return o}else if(!this.options.strict&&this.options.mode==="parse"&&(0,e.isLegacyBlobRef)(o)){const{cid:l,mimeType:c}=o,d=(0,e.parseCidSafe)(l);if(d)return{$type:"blob",ref:d,mimeType:c,size:-1}}return null}function a(o,u){if(u.includes("*/*")||u.includes(o))return!0;for(const l of u)if(l.endsWith("/*")&&o.startsWith(l.slice(0,-1)))return!0;return!1}i.blob=(0,r.memoizedOptions)(function(o){return new s(o)})}(Nn)),Nn}var Vt={},hu;function mf(){if(hu)return Vt;hu=1,Object.defineProperty(Vt,"__esModule",{value:!0}),Vt.boolean=Vt.BooleanSchema=void 0;const i=te(),e=Be();class t extends i.Schema{constructor(){super(...arguments);w(this,"type","boolean")}validateInContext(n,a){return typeof n=="boolean"?a.success(n):a.issueUnexpectedType(n,"boolean")}}return Vt.BooleanSchema=t,Vt.boolean=(0,e.memoizedOptions)(function(){return new t}),Vt}var Kt={},fu;function W0(){if(fu)return Kt;fu=1,Object.defineProperty(Kt,"__esModule",{value:!0}),Kt.bytes=Kt.BytesSchema=void 0;const i=pe(),e=te(),t=Be();class r extends e.Schema{constructor(a={}){super();w(this,"options");w(this,"type","bytes");this.options=a}validateInContext(a,o){const u=o.options.mode==="parse"?(0,i.asUint8Array)(a):(0,i.ifUint8Array)(a);if(!u)return o.issueUnexpectedType(a,"bytes");const{minLength:l}=this.options;if(l!=null&&u.length<l)return o.issueTooSmall(u,"bytes",l,u.length);const{maxLength:c}=this.options;return c!=null&&u.length>c?o.issueTooBig(u,"bytes",c,u.length):o.success(u)}}return Kt.BytesSchema=r,Kt.bytes=(0,t.memoizedOptions)(function(s){return new r(s)}),Kt}var qt={},gu;function z0(){if(gu)return qt;gu=1,Object.defineProperty(qt,"__esModule",{value:!0}),qt.cid=qt.CidSchema=void 0;const i=pe(),e=te(),t=Be();class r extends e.Schema{constructor(a){super();w(this,"options");w(this,"type","cid");this.options=a}validateInContext(a,o){return(0,i.isCid)(a,this.options)?o.success(a):o.issueUnexpectedType(a,"cid")}}return qt.CidSchema=r,qt.cid=(0,t.memoizedOptions)(function(s){return new r(s)}),qt}var Er={},mu;function pf(){if(mu)return Er;mu=1,Object.defineProperty(Er,"__esModule",{value:!0}),Er.DictSchema=void 0,Er.dict=r;const i=pe(),e=te();class t extends e.Schema{constructor(a,o){super();w(this,"keySchema");w(this,"valueSchema");w(this,"type","dict");this.keySchema=a,this.valueSchema=o}validateInContext(a,o,u){var c;if(!(0,i.isPlainObject)(a))return o.issueUnexpectedType(a,"dict");let l;for(const d in a){if((c=u==null?void 0:u.ignoredKeys)!=null&&c.has(d))continue;const h=o.validate(d,this.keySchema);if(!h.success)return h;if(h.value!==d)return o.issueRequiredKey(a,d);const f=o.validateChild(a,d,this.valueSchema);if(!f.success)return f;if(!Object.is(f.value,a[d])){if(o.options.mode==="validate")return o.issueInvalidPropertyValue(a,d,[f.value]);l??(l={...a}),l[d]=f.value}}return o.success(l??a)}}Er.DictSchema=t;function r(s,n){return new t(s,n)}return Er}var Ht={},pu;function ho(){if(pu)return Ht;pu=1,Object.defineProperty(Ht,"__esModule",{value:!0}),Ht.EnumSchema=void 0,Ht.enumSchema=t,Ht.enum=t;const i=te();class e extends i.Schema{constructor(n){super();w(this,"values");w(this,"type","enum");this.values=n}validateInContext(n,a){return this.values.includes(n)?a.success(n):a.issueInvalidValue(n,this.values)}}Ht.EnumSchema=e;function t(r){return new e(r)}return Ht}var Wt={},yu;function yf(){if(yu)return Wt;yu=1,Object.defineProperty(Wt,"__esModule",{value:!0}),Wt.integer=Wt.IntegerSchema=void 0;const i=te(),e=Be();class t extends i.Schema{constructor(a){super();w(this,"options");w(this,"type","integer");this.options=a}validateInContext(a,o){var u,l;return r(a)?((u=this.options)==null?void 0:u.minimum)!=null&&a<this.options.minimum?o.issueTooSmall(a,"integer",this.options.minimum,a):((l=this.options)==null?void 0:l.maximum)!=null&&a>this.options.maximum?o.issueTooBig(a,"integer",this.options.maximum,a):o.success(a):o.issueUnexpectedType(a,"integer")}}Wt.IntegerSchema=t;function r(s){return Number.isSafeInteger(s)}return Wt.integer=(0,e.memoizedOptions)(function(s){return new t(s)}),Wt}var Bn={},zt={},vu;function vf(){if(vu)return zt;vu=1,Object.defineProperty(zt,"__esModule",{value:!0}),zt.lexValue=zt.LexValueSchema=void 0;const i=pe(),e=te(),t=Be(),r=Object.freeze(["null","boolean","integer","string","cid","bytes","array","object"]);class s extends e.Schema{constructor(){super(...arguments);w(this,"type","lexValue")}validateInContext(o,u){if((0,i.isPlainObject)(o))for(const l of Object.keys(o)){const c=u.validateChild(o,l,this);if(!c.success)return c}else if(Array.isArray(o))for(let l=0;l<o.length;l++){const c=u.validateChild(o,l,this);if(!c.success)return c}else if(!(0,i.isLexScalar)(o))return u.issueInvalidType(o,r);return u.success(o)}}return zt.LexValueSchema=s,zt.lexValue=(0,t.memoizedOptions)(function(){return new s}),zt}var Eu;function Y0(){return Eu||(Eu=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.unknownObject=i.lexMap=i.LexMapSchema=void 0;const e=pe(),t=te(),r=Be(),n=(0,vf().lexValue)();class a extends t.Schema{constructor(){super(...arguments);w(this,"type","lexMap")}validateInContext(l,c){if(!(0,e.isPlainObject)(l))return c.issueUnexpectedType(l,"object");for(const d of Object.keys(l)){const h=c.validateChild(l,d,n);if(!h.success)return h}return c.success(l)}}i.LexMapSchema=a,i.lexMap=(0,r.memoizedOptions)(function(){return new a}),i.unknownObject=i.lexMap}(Bn)),Bn}var Sr={},Su;function gn(){if(Su)return Sr;Su=1,Object.defineProperty(Sr,"__esModule",{value:!0}),Sr.LiteralSchema=void 0,Sr.literal=t;const i=te();class e extends i.Schema{constructor(n){super();w(this,"value");w(this,"type","literal");this.value=n}validateInContext(n,a){return n!==this.value?a.issueInvalidValue(n,[this.value]):a.success(this.value)}}Sr.LiteralSchema=e;function t(r){return new e(r)}return Sr}var Yt={},_u;function X0(){if(_u)return Yt;_u=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.never=Yt.NeverSchema=void 0;const i=te(),e=Be();class t extends i.Schema{constructor(){super(...arguments);w(this,"type","never")}validateInContext(n,a){return a.issueUnexpectedType(n,"never")}}return Yt.NeverSchema=t,Yt.never=(0,e.memoizedOptions)(function(){return new t}),Yt}var Un={},Tu;function Q0(){return Tu||(Tu=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.null=i.nullSchema=i.NullSchema=void 0;const e=te(),t=Be();class r extends e.Schema{constructor(){super(...arguments);w(this,"type","null")}validateInContext(a,o){return a!==null?o.issueUnexpectedType(a,"null"):o.success(null)}}i.NullSchema=r,i.nullSchema=(0,t.memoizedOptions)(function(){return new r}),i.null=i.nullSchema}(Un)),Un}var _r={},bu;function Ef(){if(bu)return _r;bu=1,Object.defineProperty(_r,"__esModule",{value:!0}),_r.ObjectSchema=void 0,_r.object=s;const i=pe(),e=te(),t=ii();class r extends e.Schema{constructor(o){super();w(this,"shape");w(this,"type","object");this.shape=o}get validatorsMap(){const o=new Map(Object.entries(this.shape));return(0,t.lazyProperty)(this,"validatorsMap",o)}validateInContext(o,u){if(!(0,i.isPlainObject)(o))return u.issueUnexpectedType(o,"object");let l;for(const[c,d]of this.validatorsMap){const h=u.validateChild(o,c,d);if(!h.success)return c in o?h:u.issueRequiredKey(o,c);if(!(h.value===void 0&&!(c in o))&&!Object.is(h.value,o[c])){if(u.options.mode==="validate")return u.issueInvalidPropertyValue(o,c,[h.value]);l??(l={...o}),l[c]=h.value}}return u.success(l??o)}}_r.ObjectSchema=r;function s(n){return new r(n)}return _r}var Tr={},xu;function Z0(){if(xu)return Tr;xu=1,Object.defineProperty(Tr,"__esModule",{value:!0}),Tr.RegexpSchema=void 0,Tr.regexp=t;const i=te();class e extends i.Schema{constructor(n,a){super();w(this,"pattern");w(this,"message");w(this,"type","regexp");this.pattern=n,this.message=a}validateInContext(n,a){return typeof n!="string"?a.issueUnexpectedType(n,"string"):this.pattern.test(n)?a.success(n):a.issueInvalidFormat(n,this.pattern.toString(),this.message)}}Tr.RegexpSchema=e;function t(r,s){return new e(r,s)}return Tr}var Dt={},br={},Au;function Sf(){if(Au)return br;Au=1,Object.defineProperty(br,"__esModule",{value:!0}),br.TokenSchema=void 0,br.token=t;const i=te();class e extends i.Schema{constructor(n){super();w(this,"value");w(this,"type","token");this.value=n}validateInContext(n,a){return n===this.value?a.success(this.value):n instanceof e&&n.value===this.value?a.success(this.value):typeof n!="string"?a.issueUnexpectedType(n,"token"):a.issueInvalidValue(n,[this.value])}toJSON(){return this.value}toString(){return this.value}}br.TokenSchema=e;function t(r,s="main"){return new e((0,i.$type)(r,s))}return br}var Iu;function fo(){if(Iu)return Dt;Iu=1,Object.defineProperty(Dt,"__esModule",{value:!0}),Dt.string=Dt.StringSchema=void 0,Dt.coerceToString=n;const i=pe(),e=te(),t=Be(),r=Sf();class s extends e.Schema{constructor(l){super();w(this,"type","string");w(this,"options");this.options=l}validateInContext(l,c){const d=n(l);if(d==null)return c.issueUnexpectedType(l,"string");let h;const f=this.options.minLength;if(f!=null&&(h??(h=(0,i.utf8Len)(d)))<f)return c.issueTooSmall(d,"string",f,h);const g=this.options.maxLength;if(g!=null&&!(d.length*3<=g)){if((h??(h=(0,i.utf8Len)(d)))>g)return c.issueTooBig(d,"string",g,h)}let p;const m=this.options.minGraphemes;if(m!=null){if(d.length<m)return c.issueTooSmall(d,"grapheme",m,d.length);if((p??(p=(0,i.graphemeLen)(d)))<m)return c.issueTooSmall(d,"grapheme",m,p)}const v=this.options.maxGraphemes;if(v!=null&&!(d.length<=v)){if((p??(p=(0,i.graphemeLen)(d)))>v)return c.issueTooBig(d,"grapheme",v,p)}const y=this.options.format;return y!=null&&!(0,e.isStringFormat)(d,y,c.options)?c.issueInvalidFormat(d,y):c.success(d)}}Dt.StringSchema=s;function n(o){switch(typeof o){case"string":return o;case"object":{if(o==null)return null;if(o instanceof r.TokenSchema)return o.toString();if(o instanceof Date)return Number.isNaN(o.getTime())?null:o.toISOString();if(o instanceof URL)return o.toString();const u=(0,i.ifCid)(o);if(u)return u.toString();if(o instanceof String)return o.valueOf()}default:return null}}function a(o={}){return new s(o)}return Dt.string=(0,t.memoizedOptions)(a),Dt}var Xt={},Du;function J0(){if(Du)return Xt;Du=1,Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.unknown=Xt.UnknownSchema=void 0;const i=te(),e=Be();class t extends i.Schema{constructor(){super(...arguments);w(this,"type","unknown")}validateInContext(n,a){return a.success(n)}}return Xt.UnknownSchema=t,Xt.unknown=(0,e.memoizedOptions)(function(){return new t}),Xt}var xr={},Lu;function ey(){if(Lu)return xr;Lu=1,Object.defineProperty(xr,"__esModule",{value:!0}),xr.CustomSchema=void 0,xr.custom=t;const i=te();class e extends i.Schema{constructor(n,a,o){super();w(this,"assertion");w(this,"message");w(this,"path");w(this,"type","custom");this.assertion=n,this.message=a,this.path=o}validateInContext(n,a){if(!this.assertion.call(null,n,a)){const o=a.concatPath(this.path);return a.issue(new i.IssueCustom(o,n,this.message))}return a.success(n)}}xr.CustomSchema=e;function t(r,s,n){return new e(r,s,n)}return xr}var Ar={},Ru;function ty(){if(Ru)return Ar;Ru=1,Object.defineProperty(Ar,"__esModule",{value:!0}),Ar.DiscriminatedUnionSchema=void 0,Ar.discriminatedUnion=a;const i=pe(),e=te(),t=ho(),r=gn();class s extends e.Schema{constructor(l,c){super();w(this,"discriminator");w(this,"variants");w(this,"type","discriminatedUnion");w(this,"variantsMap");this.discriminator=l,this.variants=c,this.variantsMap=n(l,c)}validateInContext(l,c){if(!(0,i.isPlainObject)(l))return c.issueUnexpectedType(l,"object");const{discriminator:d}=this;if(!Object.hasOwn(l,d))return c.issueRequiredKey(l,d);const h=l[d],f=this.variantsMap.get(h);return f?c.validate(l,f):c.issueInvalidPropertyValue(l,d,[...this.variantsMap.keys()])}}Ar.DiscriminatedUnionSchema=s;function n(o,u){const l=new Map;for(const c of u){const d=c.shape[o];if(d instanceof r.LiteralSchema){if(l.has(d.value))throw new TypeError(`Overlapping discriminator value: ${d.value}`);l.set(d.value,c)}else if(d instanceof t.EnumSchema)for(const h of d.values){if(l.has(h))throw new TypeError(`Overlapping discriminator value: ${h}`);l.set(h,c)}else throw new TypeError("Discriminator schema must be a LiteralSchema or EnumSchema")}return l}function a(o,u){return new s(o,u)}return Ar}var Ir={},Cu;function ry(){if(Cu)return Ir;Cu=1,Object.defineProperty(Ir,"__esModule",{value:!0}),Ir.IntersectionSchema=void 0,Ir.intersection=t;const i=te();class e extends i.Schema{constructor(n,a){super();w(this,"left");w(this,"right");w(this,"type","intersection");this.left=n,this.right=a}validateInContext(n,a){const o=a.validate(n,this.left);return o.success?this.right.validateInContext(o.value,a,{ignoredKeys:this.left.validatorsMap}):o}}Ir.IntersectionSchema=e;function t(r,s){return new e(r,s)}return Ir}var Qt={},wu;function iy(){if(wu)return Qt;wu=1,Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.nullable=Qt.NullableSchema=void 0;const i=te(),e=Be();class t extends i.Schema{constructor(n){super();w(this,"validator");w(this,"type","nullable");this.validator=n}validateInContext(n,a){return n===null?a.success(null):a.validate(n,this.validator)}}return Qt.NullableSchema=t,Qt.nullable=(0,e.memoizedTransformer)(function(r){return new t(r)}),Qt}var Zt={},Pu;function _f(){if(Pu)return Zt;Pu=1,Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.optional=Zt.OptionalSchema=void 0;const i=te(),e=Be();class t extends i.Schema{constructor(n){super();w(this,"validator");w(this,"type","optional");this.validator=n}validateInContext(n,a){if(n===void 0&&a.options.mode==="validate")return a.success(n);const o=a.validate(n,this.validator);return o.success?o:n===void 0?a.success(n):o}}return Zt.OptionalSchema=t,Zt.optional=(0,e.memoizedTransformer)(function(r){return new t(r)}),Zt}var Dr={},ku;function sy(){var r;if(ku)return Dr;ku=1,Object.defineProperty(Dr,"__esModule",{value:!0}),Dr.RefSchema=void 0,Dr.ref=t;const i=te();class e extends i.Schema{constructor(a){super();w(this,"type","ref");Xi(this,r);Qi(this,r,a)}get validator(){return Yi(this,r).call(null)}unwrap(){return this.validator}validateInContext(a,o){return o.validate(a,this.validator)}}r=new WeakMap,Dr.RefSchema=e;function t(s){return new e(s)}return Dr}var os={},Ou;function ny(){if(Ou)return os;Ou=1,Object.defineProperty(os,"__esModule",{value:!0}),os.refine=e;const i=te();function e(r,s){return Object.create(r,{validateInContext:{value:t.bind({schema:r,refinement:s}),enumerable:!1,writable:!1,configurable:!0}})}function t(r,s){const n=s.validate(r,this.schema);if(!n.success)return n;if(!this.refinement.check.call(null,n.value,s)){const o=s.concatPath(this.refinement.path);return s.issue(new i.IssueCustom(o,r,this.refinement.message))}return n}return os}var Lr={},Mu;function Tf(){if(Mu)return Lr;Mu=1,Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.UnionSchema=void 0,Lr.union=t;const i=te();class e extends i.Schema{constructor(n){super();w(this,"validators");w(this,"type","union");this.validators=n}validateInContext(n,a){const o=[];for(const u of this.validators){const l=a.validate(n,u);if(l.success)return l;o.push(l)}return a.failure(i.LexValidationError.fromFailures(o))}}Lr.UnionSchema=e;function t(r){return new e(r)}return Lr}var Rr={},Fu;function bf(){if(Fu)return Rr;Fu=1,Object.defineProperty(Rr,"__esModule",{value:!0}),Rr.WithDefaultSchema=void 0,Rr.withDefault=t;const i=te();class e extends i.Schema{constructor(n,a){super();w(this,"validator");w(this,"defaultValue");w(this,"type","withDefault");this.validator=n,this.defaultValue=a}validateInContext(n,a){return n===void 0&&a.options.mode!=="validate"?a.validate(this.defaultValue,this.validator):a.validate(n,this.validator)}}Rr.WithDefaultSchema=e;function t(r,s){return new e(r,s)}return Rr}var $n={},Nu;function ay(){return Nu||(Nu=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.params=i.ParamsSchema=i.paramsSchema=i.paramSchema=void 0;const e=pe(),t=te(),r=ii(),s=Be(),n=gf(),a=mf(),o=pf(),u=ho(),l=yf(),c=gn(),d=_f(),h=fo(),f=Tf(),g=bf(),p=(0,f.union)([(0,a.boolean)(),(0,l.integer)(),(0,h.string)()]);i.paramSchema=(0,f.union)([p,(0,n.array)((0,a.boolean)()),(0,n.array)((0,l.integer)()),(0,n.array)((0,h.string)())]),i.paramsSchema=(0,o.dict)((0,h.string)(),(0,d.optional)(i.paramSchema));class m extends t.Schema{constructor(x){super();w(this,"shape");w(this,"type","params");this.shape=x}get shapeValidators(){const x=new Map(Object.entries(this.shape));return(0,r.lazyProperty)(this,"shapeValidators",x)}validateInContext(x,b){if(!(0,e.isPlainObject)(x))return b.issueUnexpectedType(x,"object");let I;for(const A in x){if(this.shapeValidators.has(A))continue;const D=b.validateChild(x,A,i.paramSchema);if(!D.success)return D;if(D.value!==x[A]){if(b.options.mode==="validate")return b.issueInvalidPropertyValue(x,A,[D.value]);I??(I={...x}),I[A]=D.value}}for(const[A,D]of this.shapeValidators){const L=b.validateChild(x,A,D);if(!L.success)return A in x?L:b.issueRequiredKey(x,A);if(!(L.value===void 0&&!(A in x))&&!Object.is(L.value,x[A])){if(b.options.mode==="validate")return b.issueInvalidPropertyValue(x,A,[L.value]);I??(I={...x}),I[A]=L.value}}return b.success(I??x)}fromURLSearchParams(x,b){const I={},A=typeof x=="string"?new URLSearchParams(x):x,D=A instanceof URLSearchParams?A.entries():A;for(const[L,P]of D){if(!P)continue;const O=this.shapeValidators.get(L),G=O?S(O):void 0,j=G instanceof n.ArraySchema,M=j?S(G.validator):G,U=v(L,P,M,b),F=I[L];F===void 0?I[L]=j?[U]:U:Array.isArray(F)?F.push(U):I[L]=[F,U]}return this.parse(I,b)}toURLSearchParams(x){const b=new URLSearchParams,I=this.parse(x);for(const[A,D]of Object.entries(I))if(Array.isArray(D))for(const L of D)b.append(A,String(L));else D!==void 0&&b.append(A,String(D));return b}}i.ParamsSchema=m;function v(_,T,x,b){let I;if(x){if(x instanceof h.StringSchema)return T;if(x instanceof l.IntegerSchema){if(/^-?\d+$/.test(T))return Number(T);I=new t.IssueInvalidType(y(_,b),T,["integer"])}else if(x instanceof a.BooleanSchema){if(T==="true")return!0;if(T==="false")return!1;I=new t.IssueInvalidType(y(_,b),T,["boolean"])}else if(x instanceof c.LiteralSchema){const{value:A}=x;if(String(A)===T)return A;I=new t.IssueInvalidValue(y(_,b),T,[A])}else if(x instanceof u.EnumSchema){const{values:A}=x;for(const D of A)if(String(D)===T)return D;I=new t.IssueInvalidValue(y(_,b),T,A)}else throw new Error(`Unsupported schema type for param coercion: ${x}`)}else return T;throw new t.LexValidationError([I])}function y(_,T){return T!=null&&T.path?[...T.path,_]:[_]}i.params=(0,s.memoizedOptions)(function(T={}){return new m(T)});function S(_){for(;_ instanceof d.OptionalSchema||_ instanceof g.WithDefaultSchema;)return S(_.validator);return _}}($n)),$n}var Jt={},Bu;function oy(){if(Bu)return Jt;Bu=1,Object.defineProperty(Jt,"__esModule",{value:!0}),Jt.Payload=void 0,Jt.payload=t,Jt.jsonPayload=r;const i=Ef();class e{constructor(n,a){w(this,"encoding");w(this,"schema");if(this.encoding=n,this.schema=a,n===void 0&&a!==void 0)throw new TypeError("schema cannot be defined when encoding is undefined")}matchesEncoding(n){const{encoding:a}=this;if(a===void 0)return!0;if(n==null)return!1;if(a==="*/*")return!0;const o=n==null?void 0:n.split(";",1)[0].trim();return a.endsWith("/*")?o.startsWith(a.slice(0,-1)):a.includes("*")?!1:a===o}}Jt.Payload=e;function t(s=void 0,n=void 0){return new e(s,n)}function r(s){return t("application/json",(0,i.object)(s))}return Jt}var Cr={},Uu;function ly(){if(Uu)return Cr;Uu=1,Object.defineProperty(Cr,"__esModule",{value:!0}),Cr.PermissionSet=void 0,Cr.permissionSet=e;class i{constructor(r,s,n={}){w(this,"nsid");w(this,"permissions");w(this,"options");this.nsid=r,this.permissions=s,this.options=n}}Cr.PermissionSet=i;function e(t,r,s){return new i(t,r,s)}return Cr}var wr={},$u;function uy(){if($u)return wr;$u=1,Object.defineProperty(wr,"__esModule",{value:!0}),wr.Permission=void 0,wr.permission=e;class i{constructor(r,s){w(this,"resource");w(this,"options");this.resource=r,this.options=s}}wr.Permission=i;function e(t,r={}){return new i(t,r)}return wr}var Pr={},ju;function cy(){if(ju)return Pr;ju=1,Object.defineProperty(Pr,"__esModule",{value:!0}),Pr.Procedure=void 0,Pr.procedure=e;class i{constructor(r,s,n,a,o){w(this,"nsid");w(this,"parameters");w(this,"input");w(this,"output");w(this,"errors");w(this,"type","procedure");this.nsid=r,this.parameters=s,this.input=n,this.output=a,this.errors=o}}Pr.Procedure=i;function e(t,r,s,n,a=void 0){return new i(t,r,s,n,a)}return Pr}var kr={},Gu;function dy(){if(Gu)return kr;Gu=1,Object.defineProperty(kr,"__esModule",{value:!0}),kr.Query=void 0,kr.query=e;class i{constructor(r,s,n,a){w(this,"nsid");w(this,"parameters");w(this,"output");w(this,"errors");w(this,"type","query");this.nsid=r,this.parameters=s,this.output=n,this.errors=a}}kr.Query=i;function e(t,r,s,n=void 0){return new i(t,r,s,n)}return kr}var Or={},Vu;function hy(){if(Vu)return Or;Vu=1,Object.defineProperty(Or,"__esModule",{value:!0}),Or.RecordSchema=void 0,Or.record=c;const i=te(),e=ii(),t=gn(),r=fo();class s extends i.Schema{constructor(f,g,p){super();w(this,"key");w(this,"$type");w(this,"schema");w(this,"type","record");w(this,"keySchema");this.key=f,this.$type=g,this.schema=p,this.keySchema=l(f)}validateInContext(f,g){const p=g.validate(f,this.schema);return p.success&&p.value.$type!==this.$type?g.issueInvalidPropertyValue(p.value,"$type",[this.$type]):p}build(f){return(0,i.$typed)(f,this.$type)}isTypeOf(f){return f.$type===this.$type}get $build(){return(0,e.lazyProperty)(this,"$build",this.build.bind(this))}get $isTypeOf(){return(0,e.lazyProperty)(this,"$isTypeOf",this.isTypeOf.bind(this))}}Or.RecordSchema=s;const n=(0,r.string)({minLength:1}),a=(0,r.string)({format:"tid"}),o=(0,r.string)({format:"nsid"}),u=(0,t.literal)("self");function l(d){if(d==="any")return n;if(d==="tid")return a;if(d==="nsid")return o;if(d.startsWith("literal:")){const h=d.slice(8);return h==="self"?u:(0,t.literal)(h)}throw new Error(`Unsupported record key type: ${d}`)}function c(d,h,f){return new s(d,h,f)}return Or}var Mr={},Ku;function fy(){if(Ku)return Mr;Ku=1,Object.defineProperty(Mr,"__esModule",{value:!0}),Mr.Subscription=void 0,Mr.subscription=e;class i{constructor(r,s,n,a){w(this,"nsid");w(this,"parameters");w(this,"message");w(this,"errors");w(this,"type","subscription");this.nsid=r,this.parameters=s,this.message=n,this.errors=a}}Mr.Subscription=i;function e(t,r,s,n=void 0){return new i(t,r,s,n)}return Mr}var Fr={},qu;function gy(){if(qu)return Fr;qu=1,Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.TypedObjectSchema=void 0,Fr.typedObject=s;const i=pe(),e=te(),t=ii();class r extends e.Schema{constructor(o,u){super();w(this,"$type");w(this,"schema");w(this,"type","typedObject");this.$type=o,this.schema=u}validateInContext(o,u){return(0,i.isPlainObject)(o)?"$type"in o&&o.$type!==void 0&&o.$type!==this.$type?u.issueInvalidPropertyValue(o,"$type",[this.$type]):u.validate(o,this.schema):u.issueUnexpectedType(o,"object")}build(o){return(0,e.$typed)(o,this.$type)}isTypeOf(o){return o.$type===void 0||o.$type===this.$type}get $build(){return(0,t.lazyProperty)(this,"$build",this.build.bind(this))}get $isTypeOf(){return(0,t.lazyProperty)(this,"$isTypeOf",this.isTypeOf.bind(this))}}Fr.TypedObjectSchema=r;function s(n,a,o){return new r((0,e.$type)(n,a),o)}return Fr}var Nr={},Hu;function my(){var r;if(Hu)return Nr;Hu=1,Object.defineProperty(Nr,"__esModule",{value:!0}),Nr.TypedRefSchema=void 0,Nr.typedRef=t;const i=te();class e extends i.Schema{constructor(a){super();w(this,"type","typedRef");Xi(this,r);Qi(this,r,a)}get validator(){return Yi(this,r).call(null)}get $type(){return this.validator.$type}validateInContext(a,o){const u=o.validate(a,this.validator);return u.success&&u.value.$type!==this.$type?o.issueInvalidPropertyValue(u.value,"$type",[this.$type]):u}}r=new WeakMap,Nr.TypedRefSchema=e;function t(s){return new e(s)}return Nr}var Br={},Wu;function py(){if(Wu)return Br;Wu=1,Object.defineProperty(Br,"__esModule",{value:!0}),Br.TypedUnionSchema=void 0,Br.typedUnion=s;const i=pe(),e=te(),t=ii();class r extends e.Schema{constructor(o,u){super();w(this,"validators");w(this,"closed");w(this,"type","typedUnion");this.validators=o,this.closed=u}get validatorsMap(){const o=new Map;for(const u of this.validators)o.set(u.$type,u);return(0,t.lazyProperty)(this,"validatorsMap",o)}get $types(){return Array.from(this.validatorsMap.keys())}validateInContext(o,u){if(!(0,i.isPlainObject)(o)||!("$type"in o))return u.issueUnexpectedType(o,"$typed");const{$type:l}=o,c=this.validatorsMap.get(l);return c?u.validate(o,c):this.closed?u.issueInvalidPropertyValue(o,"$type",this.$types):typeof l!="string"?u.issueInvalidPropertyType(o,"$type","string"):u.success(o)}}Br.TypedUnionSchema=r;function s(n,a){return new r(n,a)}return Br}var zu;function xf(){return zu||(zu=1,function(i){Object.defineProperty(i,"__esModule",{value:!0});const e=ce;e.__exportStar(gf(),i),e.__exportStar(H0(),i),e.__exportStar(mf(),i),e.__exportStar(W0(),i),e.__exportStar(z0(),i),e.__exportStar(pf(),i),e.__exportStar(ho(),i),e.__exportStar(yf(),i),e.__exportStar(Y0(),i),e.__exportStar(vf(),i),e.__exportStar(gn(),i),e.__exportStar(X0(),i),e.__exportStar(Q0(),i),e.__exportStar(Ef(),i),e.__exportStar(Z0(),i),e.__exportStar(fo(),i),e.__exportStar(J0(),i),e.__exportStar(ey(),i),e.__exportStar(ty(),i),e.__exportStar(ry(),i),e.__exportStar(iy(),i),e.__exportStar(_f(),i),e.__exportStar(sy(),i),e.__exportStar(ny(),i),e.__exportStar(Tf(),i),e.__exportStar(bf(),i),e.__exportStar(ay(),i),e.__exportStar(oy(),i),e.__exportStar(ly(),i),e.__exportStar(uy(),i),e.__exportStar(cy(),i),e.__exportStar(dy(),i),e.__exportStar(hy(),i),e.__exportStar(fy(),i),e.__exportStar(Sf(),i),e.__exportStar(gy(),i),e.__exportStar(my(),i),e.__exportStar(py(),i)}(Fn)),Fn}var Yu;function yy(){if(Yu)return vr;Yu=1,Object.defineProperty(vr,"__esModule",{value:!0}),vr.lexErrorDataSchema=void 0,vr.getMain=e;const i=xf();function e(t){return"main"in t?t.main:t}return vr.lexErrorDataSchema=(0,i.object)({error:(0,i.regexp)(/^[\w_-]+$/,"Expected ASCII constant with no whitespace"),message:(0,i.optional)((0,i.string)())}),vr}var Xu;function Qu(){return Xu||(Xu=1,function(i){Object.defineProperty(i,"__esModule",{value:!0});const e=ce;e.__exportStar(te(),i),e.__exportStar(yy(),i),e.__exportStar(xf(),i)}(bn)),bn}var Zu;function nt(){return Zu||(Zu=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.l=void 0;const e=ce,t=e.__importStar(Qu());i.l=t,e.__exportStar(Qu(),i)}(Tn)),Tn}var _i={},Ti={},er={},xe={},jn={},Pe={},tr={},Ju;function Fi(){if(Ju)return tr;Ju=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.commitMeta=tr.$nsid=void 0;const i=nt(),e="com.atproto.repo.defs";tr.$nsid=e;const t=i.l.typedObject(e,"commitMeta",i.l.object({cid:i.l.string({format:"cid"}),rev:i.l.string({format:"tid"})}));return tr.commitMeta=t,tr}var ec;function tc(){if(ec)return Pe;ec=1,Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.$output=Pe.$input=Pe.$params=Pe.$lxm=Pe.main=Pe.$nsid=void 0;const i=ce,e=nt(),t=i.__importStar(Fi()),r="com.atproto.repo.createRecord";Pe.$nsid=r;const s=e.l.procedure(r,e.l.params(),e.l.jsonPayload({repo:e.l.string({format:"at-identifier"}),collection:e.l.string({format:"nsid"}),rkey:e.l.optional(e.l.string({format:"record-key",maxLength:512})),validate:e.l.optional(e.l.boolean()),record:e.l.lexMap(),swapCommit:e.l.optional(e.l.string({format:"cid"}))}),e.l.jsonPayload({uri:e.l.string({format:"at-uri"}),cid:e.l.string({format:"cid"}),commit:e.l.optional(e.l.ref(()=>t.commitMeta)),validationStatus:e.l.optional(e.l.string())}),["InvalidSwap"]);return Pe.main=s,Pe.$lxm=s.nsid,Pe.$params=s.parameters,Pe.$input=s.input,Pe.$output=s.output,Pe}var rc;function vy(){return rc||(rc=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.$defs=void 0;const e=ce;e.__exportStar(tc(),i),i.$defs=e.__importStar(tc())}(jn)),jn}var Gn={},ke={},ic;function sc(){if(ic)return ke;ic=1,Object.defineProperty(ke,"__esModule",{value:!0}),ke.$output=ke.$input=ke.$params=ke.$lxm=ke.main=ke.$nsid=void 0;const i=ce,e=nt(),t=i.__importStar(Fi()),r="com.atproto.repo.deleteRecord";ke.$nsid=r;const s=e.l.procedure(r,e.l.params(),e.l.jsonPayload({repo:e.l.string({format:"at-identifier"}),collection:e.l.string({format:"nsid"}),rkey:e.l.string({format:"record-key"}),swapRecord:e.l.optional(e.l.string({format:"cid"})),swapCommit:e.l.optional(e.l.string({format:"cid"}))}),e.l.jsonPayload({commit:e.l.optional(e.l.ref(()=>t.commitMeta))}),["InvalidSwap"]);return ke.main=s,ke.$lxm=s.nsid,ke.$params=s.parameters,ke.$input=s.input,ke.$output=s.output,ke}var nc;function Ey(){return nc||(nc=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.$defs=void 0;const e=ce;e.__exportStar(sc(),i),i.$defs=e.__importStar(sc())}(Gn)),Gn}var Vn={},Ge={},ac;function oc(){if(ac)return Ge;ac=1,Object.defineProperty(Ge,"__esModule",{value:!0}),Ge.$output=Ge.$params=Ge.$lxm=Ge.main=Ge.$nsid=void 0;const i=nt(),e="com.atproto.repo.getRecord";Ge.$nsid=e;const t=i.l.query(e,i.l.params({repo:i.l.string({format:"at-identifier"}),collection:i.l.string({format:"nsid"}),rkey:i.l.string({format:"record-key"}),cid:i.l.optional(i.l.string({format:"cid"}))}),i.l.jsonPayload({uri:i.l.string({format:"at-uri"}),cid:i.l.optional(i.l.string({format:"cid"})),value:i.l.lexMap()}),["RecordNotFound"]);return Ge.main=t,Ge.$lxm=t.nsid,Ge.$params=t.parameters,Ge.$output=t.output,Ge}var lc;function Sy(){return lc||(lc=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.$defs=void 0;const e=ce;e.__exportStar(oc(),i),i.$defs=e.__importStar(oc())}(Vn)),Vn}var Kn={},Oe={},uc;function cc(){if(uc)return Oe;uc=1,Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.record=Oe.$output=Oe.$params=Oe.$lxm=Oe.main=Oe.$nsid=void 0;const i=nt(),e="com.atproto.repo.listRecords";Oe.$nsid=e;const t=i.l.query(e,i.l.params({repo:i.l.string({format:"at-identifier"}),collection:i.l.string({format:"nsid"}),limit:i.l.optional(i.l.withDefault(i.l.integer({minimum:1,maximum:100}),50)),cursor:i.l.optional(i.l.string()),reverse:i.l.optional(i.l.boolean())}),i.l.jsonPayload({cursor:i.l.optional(i.l.string()),records:i.l.array(i.l.ref(()=>r))}));Oe.main=t,Oe.$lxm=t.nsid,Oe.$params=t.parameters,Oe.$output=t.output;const r=i.l.typedObject(e,"record",i.l.object({uri:i.l.string({format:"at-uri"}),cid:i.l.string({format:"cid"}),value:i.l.lexMap()}));return Oe.record=r,Oe}var dc;function _y(){return dc||(dc=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.$defs=void 0;const e=ce;e.__exportStar(cc(),i),i.$defs=e.__importStar(cc())}(Kn)),Kn}var qn={},Me={},hc;function fc(){if(hc)return Me;hc=1,Object.defineProperty(Me,"__esModule",{value:!0}),Me.$output=Me.$input=Me.$params=Me.$lxm=Me.main=Me.$nsid=void 0;const i=ce,e=nt(),t=i.__importStar(Fi()),r="com.atproto.repo.putRecord";Me.$nsid=r;const s=e.l.procedure(r,e.l.params(),e.l.jsonPayload({repo:e.l.string({format:"at-identifier"}),collection:e.l.string({format:"nsid"}),rkey:e.l.string({format:"record-key",maxLength:512}),validate:e.l.optional(e.l.boolean()),record:e.l.lexMap(),swapRecord:e.l.optional(e.l.nullable(e.l.string({format:"cid"}))),swapCommit:e.l.optional(e.l.string({format:"cid"}))}),e.l.jsonPayload({uri:e.l.string({format:"at-uri"}),cid:e.l.string({format:"cid"}),commit:e.l.optional(e.l.ref(()=>t.commitMeta)),validationStatus:e.l.optional(e.l.string())}),["InvalidSwap"]);return Me.main=s,Me.$lxm=s.nsid,Me.$params=s.parameters,Me.$input=s.input,Me.$output=s.output,Me}var gc;function Ty(){return gc||(gc=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.$defs=void 0;const e=ce;e.__exportStar(fc(),i),i.$defs=e.__importStar(fc())}(qn)),qn}var Hn={},Fe={},mc;function pc(){if(mc)return Fe;mc=1,Object.defineProperty(Fe,"__esModule",{value:!0}),Fe.$output=Fe.$input=Fe.$params=Fe.$lxm=Fe.main=Fe.$nsid=void 0;const i=nt(),e="com.atproto.repo.uploadBlob";Fe.$nsid=e;const t=i.l.procedure(e,i.l.params(),i.l.payload("*/*"),i.l.jsonPayload({blob:i.l.blob({allowLegacy:!1})}));return Fe.main=t,Fe.$lxm=t.nsid,Fe.$params=t.parameters,Fe.$input=t.input,Fe.$output=t.output,Fe}var yc;function by(){return yc||(yc=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.$defs=void 0;const e=ce;e.__exportStar(pc(),i),i.$defs=e.__importStar(pc())}(Hn)),Hn}var Wn={},vc;function xy(){return vc||(vc=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.$defs=void 0;const e=ce;e.__exportStar(Fi(),i),i.$defs=e.__importStar(Fi())}(Wn)),Wn}var Ec;function Ay(){if(Ec)return xe;Ec=1,Object.defineProperty(xe,"__esModule",{value:!0}),xe.defs=xe.uploadBlob=xe.putRecord=xe.listRecords=xe.getRecord=xe.deleteRecord=xe.createRecord=void 0;const i=ce;return xe.createRecord=i.__importStar(vy()),xe.deleteRecord=i.__importStar(Ey()),xe.getRecord=i.__importStar(Sy()),xe.listRecords=i.__importStar(_y()),xe.putRecord=i.__importStar(Ty()),xe.uploadBlob=i.__importStar(by()),xe.defs=i.__importStar(xy()),xe}var bi={},zn={},Ve={},Sc;function _c(){if(Sc)return Ve;Sc=1,Object.defineProperty(Ve,"__esModule",{value:!0}),Ve.$output=Ve.$params=Ve.$lxm=Ve.main=Ve.$nsid=void 0;const i=nt(),e="com.atproto.sync.getBlob";Ve.$nsid=e;const t=i.l.query(e,i.l.params({did:i.l.string({format:"did"}),cid:i.l.string({format:"cid"})}),i.l.payload("*/*"),["BlobNotFound","RepoNotFound","RepoTakendown","RepoSuspended","RepoDeactivated"]);return Ve.main=t,Ve.$lxm=t.nsid,Ve.$params=t.parameters,Ve.$output=t.output,Ve}var Tc;function Iy(){return Tc||(Tc=1,function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.$defs=void 0;const e=ce;e.__exportStar(_c(),i),i.$defs=e.__importStar(_c())}(zn)),zn}var bc;function Dy(){if(bc)return bi;bc=1,Object.defineProperty(bi,"__esModule",{value:!0}),bi.getBlob=void 0;const i=ce;return bi.getBlob=i.__importStar(Iy()),bi}var xc;function Ly(){if(xc)return er;xc=1,Object.defineProperty(er,"__esModule",{value:!0}),er.sync=er.repo=void 0;const i=ce;return er.repo=i.__importStar(Ay()),er.sync=i.__importStar(Dy()),er}var Ac;function Ry(){if(Ac)return Ti;Ac=1,Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.atproto=void 0;const i=ce;return Ti.atproto=i.__importStar(Ly()),Ti}var Ic;function Cy(){if(Ic)return _i;Ic=1,Object.defineProperty(_i,"__esModule",{value:!0}),_i.com=void 0;const i=ce;return _i.com=i.__importStar(Ry()),_i}var pt={},Dc;function Af(){if(Dc)return pt;Dc=1,Object.defineProperty(pt,"__esModule",{value:!0}),pt.applyDefaults=i,pt.isBlobLike=e,pt.isAsyncIterable=t,pt.buildXrpcRequestHeaders=r,pt.toReadableStream=s,pt.toReadableStreamPonyfill=n;function i(a,o){const u={...a};for(const l of Object.keys(o))a[l]===void 0&&(u[l]=o[l]);return u}function e(a){if(a==null||typeof a!="object")return!1;if(typeof Blob=="function"&&a instanceof Blob)return!0;const o=a[Symbol.toStringTag];return o==="Blob"||o==="File"?"stream"in a&&typeof a.stream=="function":!1}function t(a){return a!=null&&typeof a[Symbol.asyncIterator]=="function"}function r(a){var u;const o=new Headers(a==null?void 0:a.headers);return a.service&&!o.has("atproto-proxy")&&o.set("atproto-proxy",a.service),a.labelers&&o.set("atproto-accept-labelers",[...a.labelers,(u=o.get("atproto-accept-labelers"))==null?void 0:u.trim()].filter(Boolean).join(", ")),o}function s(a){/* v8 ignore next -- @preserve */if("from"in ReadableStream&&typeof ReadableStream.from=="function")return ReadableStream.from(a);/* v8 ignore next -- @preserve */return n(a)}function n(a){let o;return new ReadableStream({async pull(u){try{o??(o=a[Symbol.asyncIterator]());const l=await o.next();l.done?u.close():u.enqueue(l.value)}catch(l){u.error(l),o=void 0}},async cancel(){var u;await((u=o==null?void 0:o.return)==null?void 0:u.call(o)),o=void 0}})}return pt}var xi={},Yn={},Ai={},Lc;function If(){if(Lc)return Ai;Lc=1,Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.parseLexBytes=e,Ai.encodeLexBytes=t;const i=pe();function e(r){if(!(!r||!("$bytes"in r))){for(const s in r)if(s!=="$bytes")return;if(typeof r.$bytes=="string")try{return(0,i.fromBase64)(r.$bytes)}catch{return}}}function t(r){return{$bytes:(0,i.toBase64)(r)}}return Ai}var Xn={},Rc;function wy(){return Rc||(Rc=1,Object.defineProperty(Xn,"__esModule",{value:!0})),Xn}var rr={},ls={},Ii={},Cc;function go(){if(Cc)return Ii;Cc=1,Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.parseLexLink=e,Ii.encodeLexLink=t;const i=pe();function e(r,s){if(!r||!("$link"in r))return;for(const a in r)if(a!=="$link")return;const{$link:n}=r;if(typeof n=="string"&&n.length!==0&&!(n.length>2048))try{return(0,i.parseCid)(n,s)}catch{return}}function t(r){return{$link:r.toString()}}return Ii}var wc;function Py(){if(wc)return ls;wc=1,Object.defineProperty(ls,"__esModule",{value:!0}),ls.parseBlobRef=t;const i=pe(),e=go();function t(r,s){if(r.$type!=="blob")return;const n=r==null?void 0:r.ref;if(!(!n||typeof n!="object")){if("$link"in n){const a=(0,e.parseLexLink)(n);if(!a)return;const o={...r,ref:a};if((0,i.isBlobRef)(o,s))return o}if((0,i.isBlobRef)(r))return r}}return ls}var Pc;function ky(){if(Pc)return rr;Pc=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.lexStringify=s,rr.lexParse=n,rr.jsonToLex=a,rr.lexToJson=l;const i=pe(),e=Py(),t=If(),r=go();function s(f){return JSON.stringify(l(f))}function n(f,g={strict:!1}){return JSON.parse(f,function(p,m){switch(typeof m){case"object":return m===null?null:Array.isArray(m)?m:h(m,g)??m;case"number":if(Number.isSafeInteger(m))return m;if(g.strict)throw new TypeError(`Invalid non-integer number: ${m}`);default:return m}})}function a(f,g={strict:!1}){switch(typeof f){case"object":return f===null?null:Array.isArray(f)?o(f,g):h(f,g)??u(f,g);case"number":if(Number.isSafeInteger(f))return f;if(g.strict)throw new TypeError(`Invalid non-integer number: ${f}`);case"boolean":case"string":return f;default:throw new TypeError(`Invalid JSON value: ${typeof f}`)}}function o(f,g){let p;for(let m=0;m<f.length;m++){const v=f[m],y=a(v,g);y!==v&&(p??(p=Array.from(f)),p[m]=y)}return p??f}function u(f,g){let p;for(const[m,v]of Object.entries(f)){if(m==="__proto__")throw new TypeError("Invalid key: __proto__");if(v===void 0){p??(p={...f}),delete p[m];continue}const y=a(v,g);y!==v&&(p??(p={...f}),p[m]=y)}return p??f}function l(f){switch(typeof f){case"object":return f===null?f:Array.isArray(f)?c(f):(0,i.isCid)(f)?(0,r.encodeLexLink)(f):ArrayBuffer.isView(f)?(0,t.encodeLexBytes)(f):d(f);case"boolean":case"string":case"number":return f;default:throw new TypeError(`Invalid Lex value: ${typeof f}`)}}function c(f){let g;for(let p=0;p<f.length;p++){const m=f[p],v=l(m);v!==m&&(g??(g=Array.from(f)),g[p]=v)}return g??f}function d(f){let g;for(const[p,m]of Object.entries(f)){if(p==="__proto__")throw new TypeError("Invalid key: __proto__");if(m===void 0){g??(g={...f}),delete g[p];continue}const v=l(m);v!==m&&(g??(g={...f}),g[p]=v)}return g??f}function h(f,g){if(f.$link!==void 0){const p=(0,r.parseLexLink)(f);if(p)return p;if(g.strict)throw new TypeError("Invalid $link object")}else if(f.$bytes!==void 0){const p=(0,t.parseLexBytes)(f);if(p)return p;if(g.strict)throw new TypeError("Invalid $bytes object")}else if(f.$type!==void 0&&g.strict)if(f.$type==="blob"){const p=(0,e.parseBlobRef)(f,g);if(p)return p;throw new TypeError("Invalid blob object")}else{if(typeof f.$type!="string")throw new TypeError(`Invalid $type property (${typeof f.$type})`);if(f.$type.length===0)throw new TypeError("Empty $type property")}}return rr}var kc;function Df(){return kc||(kc=1,function(i){Object.defineProperty(i,"__esModule",{value:!0});const e=ce;e.__exportStar(If(),i),e.__exportStar(wy(),i),e.__exportStar(ky(),i),e.__exportStar(go(),i)}(Yn)),Yn}var Qn={},us={},Oc;function Oy(){if(Oc)return us;Oc=1,Object.defineProperty(us,"__esModule",{value:!0}),us.parseWWWAuthenticateHeader=i;function i(e){var a;if(typeof e!="string")return;const t={},r=e.trim();if(!r)return t;const s=r.split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/);let n=null;for(let o of s){const u=o.trim().match(/^([^"=\s]+)(\s+.*)?$/);if(u){const h=u[1];if(Object.hasOwn(t,h))return;const f=(a=u[2])==null?void 0:a.trim();if(!f){n=null,t[h]=Object.create(null);continue}if(!f.includes("=")){n=null,t[h]=f;continue}n=Object.create(null),t[h]=n,o=f}if(!n)return;const l=o.match(/^\s*([^"\s=]+)=(?:("[^"\\]*(?:\\.[^"\\]*)*")|([^\s,"]*))\s*$/);if(!l)return;const c=l[1],d=l[3]??l[2].slice(1,-1).replaceAll(/\\(.)/g,"$1");n[c]=d}return t}return us}var Mc;function mo(){return Mc||(Mc=1,function(i){var v;Object.defineProperty(i,"__esModule",{value:!0}),i.XrpcFetchError=i.XrpcInternalError=i.XrpcResponseValidationError=i.XrpcInvalidResponseError=i.XrpcAuthenticationError=i.XrpcResponseError=i.XrpcError=i.LexError=i.RETRYABLE_HTTP_STATUS_CODES=void 0,i.isXrpcErrorPayload=n,i.asXrpcFailure=f;const e=pe();Object.defineProperty(i,"LexError",{enumerable:!0,get:function(){return e.LexError}});const t=nt(),r=Oy(),s=new Map([[400,"InvalidRequest"],[401,"AuthenticationRequired"],[403,"Forbidden"],[404,"XRPCNotSupported"],[406,"NotAcceptable"],[413,"PayloadTooLarge"],[415,"UnsupportedMediaType"],[429,"RateLimitExceeded"],[500,"InternalServerError"],[501,"MethodNotImplemented"],[502,"UpstreamFailure"],[503,"NotEnoughResources"],[504,"UpstreamTimeout"]]);i.RETRYABLE_HTTP_STATUS_CODES=new Set([408,425,429,500,502,503,504,522,524]);function n(y){return y!=null&&y.encoding==="application/json"&&t.lexErrorDataSchema.matches(y.body)}class a extends e.LexError{constructor(_,T,x=`${T} Lexicon RPC error`,b){super(T,x,b);w(this,"method");w(this,"name","XrpcError");w(this,"success",!1);this.method=_}matchesSchemaErrors(){var _;return((_=this.method.errors)==null?void 0:_.includes(this.error))??!1}}i.XrpcError=a;class o extends a{constructor(_,T,x,b){const{error:I,message:A}=n(x)?x.body:{error:s.get(T.status)??(T.status>=500?"UpstreamFailure":"InvalidRequest"),message:m(T)};super(_,I,A,b);w(this,"response");w(this,"payload");w(this,"name","XrpcResponseError");this.response=T,this.payload=x}get reason(){return this}shouldRetry(){return i.RETRYABLE_HTTP_STATUS_CODES.has(this.response.status)}toJSON(){const{payload:_}=this;return n(_)?_.body:super.toJSON()}toDownstreamError(){const{status:_,headers:T}=this.response;return{status:_===500?502:_,headers:p(T),body:this.toJSON()}}get status(){return this.response.status}get headers(){return this.response.headers}get body(){var _;return(_=this.payload)==null?void 0:_.body}}i.XrpcResponseError=o;class u extends o{constructor(){super(...arguments);w(this,"name","XrpcAuthenticationError");Xi(this,v)}shouldRetry(){return!1}get wwwAuthenticate(){return Yi(this,v)??Qi(this,v,(0,r.parseWWWAuthenticateHeader)(this.response.headers.get("www-authenticate"))??{})}}v=new WeakMap,i.XrpcAuthenticationError=u;class l extends a{constructor(_,T,x,b=m(T),I){super(_,"InvalidResponse",b,I);w(this,"response");w(this,"payload");w(this,"name","XrpcInvalidResponseError");this.response=T,this.payload=x}get reason(){return this}shouldRetry(){return i.RETRYABLE_HTTP_STATUS_CODES.has(this.response.status)}toDownstreamError(){return{status:502,body:this.toJSON()}}}i.XrpcInvalidResponseError=l;class c extends l{constructor(_,T,x,b){super(_,T,x,`Invalid response payload: ${b.message}`,{cause:b});w(this,"cause");w(this,"name","XrpcResponseValidationError");this.cause=b}}i.XrpcResponseValidationError=c;class d extends a{constructor(_,T,x){super(_,"InternalServerError",T??"Unable to fulfill XRPC request",x);w(this,"name","XrpcInternalError")}get reason(){return this}shouldRetry(){return!1}toJSON(){return{error:this.error,message:"Internal Server Error"}}toDownstreamError(){return{status:500,body:this.toJSON()}}}i.XrpcInternalError=d;class h extends d{constructor(_,T){const x=T instanceof Error?T.message:String(T);super(_,`Unexpected fetchHandler() error: ${x}`,{cause:T});w(this,"name","XrpcFetchError")}shouldRetry(){return!0}toJSON(){return{error:this.error,message:"Failed to perform upstream request"}}toDownstreamError(){return{status:502,body:this.toJSON()}}}i.XrpcFetchError=h;function f(y,S){return(S instanceof o||S instanceof l||S instanceof d)&&S.method===y?S:new d(y,void 0,{cause:S})}const g=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]);function p(y){const S=new Headers(y);for(const T of g)S.delete(T);const _=y.get("connection");if(_)for(const T of _.split(","))S.delete(T.trim());return S.delete("content-length"),S.delete("content-encoding"),S}function m(y){return y.status<400?`Upstream server responded with an invalid status code (${y.status})`:`Upstream server responded with a ${y.status} error`}}(Qn)),Qn}var Di={},cs={},Fc;function Lf(){if(Fc)return cs;Fc=1,Object.defineProperty(cs,"__esModule",{value:!0}),cs.isEncodingString=i;function i(e){return e.includes("/")}return cs}var Nc;function Rf(){if(Nc)return Di;Nc=1,Object.defineProperty(Di,"__esModule",{value:!0}),Di.XrpcResponse=void 0;const i=Df(),e=mo(),t=Lf(),r="application/octet-stream",s="application/json";class n{constructor(l,c,d,h){w(this,"method");w(this,"status");w(this,"headers");w(this,"payload");w(this,"success",!0);this.method=l,this.status=c,this.headers=d,this.payload=h}get value(){return this}get isParsed(){return this.method.output.encoding===s}get encoding(){var l;return(l=this.payload)==null?void 0:l.encoding}get body(){var l;return(l=this.payload)==null?void 0:l.body}static async fromFetchResponse(l,c,d){var f;if(c.status>=400){const g=await a(l,c,{parse:{strict:!1}});throw c.status===401?new e.XrpcAuthenticationError(l,c,g):new e.XrpcResponseError(l,c,g)}if(c.status<200||c.status>=300)throw await((f=c.body)==null?void 0:f.cancel()),new e.XrpcInvalidResponseError(l,c,void 0,`Unexpected status code ${c.status}`);const h=await a(l,c,{parse:l.output.schema||l.output.encoding===s?{strict:(d==null?void 0:d.strictResponseProcessing)??!0}:l.output.encoding==null?{strict:!1}:!1});if(!l.output.matchesEncoding(h==null?void 0:h.encoding))throw new e.XrpcInvalidResponseError(l,c,h,`Expected ${o(l.output.encoding)} response (got ${o(h==null?void 0:h.encoding)})`);if(l.output.encoding!=null){if(!h)throw new Error("Expected payload");if(l.output.schema&&(d==null?void 0:d.validateResponse)!==!1){const g=l.output.schema.safeParse(h.body,{strict:(d==null?void 0:d.strictResponseProcessing)??!0});if(!g.success)throw new e.XrpcResponseValidationError(l,c,h,g.reason);const p={body:g.value,encoding:h.encoding};return new n(l,c.status,c.headers,p)}}return new n(l,c.status,c.headers,h)}}Di.XrpcResponse=n;async function a(u,l,c){var d;try{const h=(d=l.headers.get("content-type"))==null?void 0:d.split(";")[0].trim().toLowerCase();if(!h){const g=await l.arrayBuffer();return g.byteLength===0?void 0:{encoding:r,body:new Uint8Array(g)}}if(!(0,t.isEncodingString)(h))throw new TypeError(`Invalid content-type "${h}" in response`);if(c!=null&&c.parse&&h===s){const g=await l.text();return{encoding:h,body:(0,i.lexParse)(g,c.parse)}}const f=await l.arrayBuffer();return{encoding:h,body:new Uint8Array(f)}}catch(h){const f="Unable to parse response payload",g=h instanceof TypeError?h.message:void 0;throw new e.XrpcInvalidResponseError(u,l,void 0,g?`${f}: ${g}`:f,{cause:h})}}function o(u){return u?`"${u}"`:"no payload"}return Di}var Bc;function Cf(){if(Bc)return xi;Bc=1,Object.defineProperty(xi,"__esModule",{value:!0}),xi.xrpc=o,xi.xrpcSafe=u;const i=pe(),e=Df(),t=nt(),r=to(),s=mo(),n=Rf(),a=Af();async function o(g,p,m={}){const v=await u(g,p,m);if(v.success)return v;throw v}async function u(g,p,m={}){var y;(y=m.signal)==null||y.throwIfAborted();const v=(0,t.getMain)(p);try{const S=(0,r.buildAgent)(g),_=l(v,m),T=c(v,m),x=await S.fetchHandler(_,T).catch(b=>{throw new s.XrpcFetchError(v,b)});return await n.XrpcResponse.fromFetchResponse(v,x,m)}catch(S){return(0,s.asXrpcFailure)(v,S)}}function l(g,p){var y;const m=`/xrpc/${g.nsid}`,v=(y=g.parameters)==null?void 0:y.toURLSearchParams(p.params??{}).toString();return v?`${m}?${v}`:m}function c(g,p){const m=(0,a.buildXrpcRequestHeaders)(p);if(g.output.encoding&&m.set("accept",g.output.encoding),m.has("content-type")){const v=m.get("content-type");throw new TypeError(`Unexpected content-type header (${v})`)}if("input"in g){const v=p.encoding,y=d(g,p,v);if(y)m.set("content-type",y.encoding);else if(v!=null)throw new TypeError(`Unexpected encoding hint (${v})`);return{duplex:"half",redirect:"follow",referrerPolicy:"strict-origin-when-cross-origin",mode:"cors",signal:p.signal,method:"POST",headers:m,body:y==null?void 0:y.body}}return{duplex:"half",redirect:"follow",referrerPolicy:"strict-origin-when-cross-origin",mode:"cors",signal:p.signal,method:"GET",headers:m}}function d(g,p,m){var S;const{input:v}=g,{body:y}=p;if(p.validateRequest&&((S=v.schema)==null||S.check(y)),v.encoding==="application/json"){if(!(0,i.isLexScalar)(y)&&!(0,i.isPlainObject)(y)&&!Array.isArray(y))throw new TypeError(`Expected LexValue body, got ${typeof y}`);return h(v,(0,e.lexStringify)(y),m)}switch(typeof y){case"undefined":case"string":return h(v,y,m);case"object":{if(y===null)break;if(ArrayBuffer.isView(y)||y instanceof ArrayBuffer||y instanceof ReadableStream)return h(v,y,m);if((0,a.isAsyncIterable)(y))return h(v,(0,a.toReadableStream)(y),m);if((0,a.isBlobLike)(y))return h(v,y,m||y.type)}}throw new TypeError(`Invalid ${typeof y} body for ${v.encoding} encoding`)}function h(g,p,m){if(g.encoding===void 0){if(p!==void 0)throw new TypeError("Endpoint expects no payload");return null}if(p===void 0)throw new TypeError("A request body is expected but none was provided");return{encoding:f(g,m),body:p}}function f(g,p){if(!g.encoding)throw new TypeError("Unexpected payload");if(p!=null&&p.length){if(!g.matchesEncoding(p))throw new TypeError(`Cannot send a body with content-type "${p}" for "${g.encoding}" encoding`);return p}if(g.encoding==="*/*")return"application/octet-stream";if(g.encoding.startsWith("text/"))return g.encoding.includes("*")?"text/plain; charset=utf-8":`${g.encoding}; charset=utf-8`;if(!g.encoding.includes("*"))return g.encoding;throw new TypeError(`Unable to determine payload encoding. Please provide a 'content-type' header matching ${g.encoding}.`)}return xi}var Uc;function My(){if(Uc)return li;Uc=1,Object.defineProperty(li,"__esModule",{value:!0}),li.Client=void 0;const i=nt(),e=to(),t=Cy(),r=Af(),s=Cf();class n{constructor(l,c={}){w(this,"agent");w(this,"headers");w(this,"service");w(this,"labelers");w(this,"xrpcDefaults");this.agent=(0,e.buildAgent)(l),this.service=c.service,this.labelers=new Set(c.labelers),this.headers=new Headers(c.headers),this.xrpcDefaults=Object.freeze({validateRequest:c.validateRequest??!1,validateResponse:c.validateResponse??!0,strictResponseProcessing:c.strictResponseProcessing??!0})}static configure(l){l.appLabelers&&(this.appLabelers=[...l.appLabelers])}get did(){return this.agent.did}get assertDid(){return this.assertAuthenticated(),this.did}assertAuthenticated(){if(!this.did)throw new Error("Client is not authenticated")}setLabelers(l=[]){this.clearLabelers(),this.addLabelers(l)}addLabelers(l){for(const c of l)this.labelers.add(c)}clearLabelers(){this.labelers.clear()}fetchHandler(l,c){const d=(0,r.buildXrpcRequestHeaders)({headers:c.headers,service:this.service,labelers:[...this.constructor.appLabelers.map(h=>`${h};redact`),...this.labelers]});for(const[h,f]of this.headers)d.has(h)||d.set(h,f);return this.agent.fetchHandler(l,{...c,headers:d})}async xrpc(l,c={}){return(0,s.xrpc)(this,l,(0,r.applyDefaults)(c,this.xrpcDefaults))}async xrpcSafe(l,c={}){return(0,s.xrpcSafe)(this,l,(0,r.applyDefaults)(c,this.xrpcDefaults))}async createRecord(l,c,d){return this.xrpc(t.com.atproto.repo.createRecord.main,{...d,body:{repo:(d==null?void 0:d.repo)??this.assertDid,collection:l.$type,record:l,rkey:c,validate:d==null?void 0:d.validate,swapCommit:d==null?void 0:d.swapCommit}})}async deleteRecord(l,c,d){return this.xrpc(t.com.atproto.repo.deleteRecord.main,{...d,body:{repo:(d==null?void 0:d.repo)??this.assertDid,collection:l,rkey:c,swapCommit:d==null?void 0:d.swapCommit,swapRecord:d==null?void 0:d.swapRecord}})}async getRecord(l,c,d){return this.xrpc(t.com.atproto.repo.getRecord.main,{...d,params:{repo:(d==null?void 0:d.repo)??this.assertDid,collection:l,rkey:c}})}async putRecord(l,c,d){return this.xrpc(t.com.atproto.repo.putRecord.main,{...d,body:{repo:(d==null?void 0:d.repo)??this.assertDid,collection:l.$type,rkey:c,record:l,validate:d==null?void 0:d.validate,swapCommit:d==null?void 0:d.swapCommit,swapRecord:d==null?void 0:d.swapRecord}})}async listRecords(l,c){return this.xrpc(t.com.atproto.repo.listRecords.main,{...c,params:{repo:(c==null?void 0:c.repo)??this.assertDid,collection:l,cursor:c==null?void 0:c.cursor,limit:c==null?void 0:c.limit,reverse:c==null?void 0:c.reverse}})}async uploadBlob(l,c){return this.xrpc(t.com.atproto.repo.uploadBlob.main,{...c,body:l})}async getBlob(l,c,d){return this.xrpc(t.com.atproto.sync.getBlob.main,{...d,params:{did:l,cid:c}})}async call(l,c,d={}){const h=(0,i.getMain)(l);if(typeof h=="function")return h(this,c,d);if(h instanceof i.Procedure)return(await this.xrpc(h,{...d,body:c})).body;if(h instanceof i.Query)return(await this.xrpc(h,{...d,params:c})).body;throw new TypeError("Invalid lexicon")}async create(l,c,d={}){const h=(0,i.getMain)(l),f=h.build(c);d!=null&&d.validateRequest&&h.validate(f);const g=d.rkey??a(h);return g!==void 0&&h.keySchema.assert(g),(await this.createRecord(f,g,d)).body}async delete(l,c={}){const d=(0,i.getMain)(l),h=d.keySchema.parse(c.rkey??o(d));return(await this.deleteRecord(d.$type,h,c)).body}async get(l,c={}){const d=(0,i.getMain)(l),h=d.keySchema.parse(c.rkey??o(d)),f=await this.getRecord(d.$type,h,c),g=d.validate(f.body.value);return{...f.body,value:g}}async put(l,c,d={}){const h=(0,i.getMain)(l),f=h.build(c);d!=null&&d.validateRequest&&h.validate(f);const g=d.rkey??o(h);return(await this.putRecord(f,g,d)).body}async list(l,c){const d=(0,i.getMain)(l),{body:h}=await this.listRecords(d.$type,c),f=[],g=[];for(const p of h.records){const m=d.safeValidate(p.value);m.success?f.push({...p,value:m.value}):g.push(p.value)}return{...h,records:f,invalid:g}}}w(n,"appLabelers",[]),li.Client=n;function a(u){if(u.key!=="tid"&&u.key!=="any")return o(u)}function o(u){if(u.key.startsWith("literal:"))return u.key.slice(8);throw new TypeError(`An "rkey" must be provided for record key type "${u.key}" (${u.$type})`)}return li}(function(i){Object.defineProperty(i,"__esModule",{value:!0});const e=ce;e.__exportStar(to(),i),e.__exportStar(My(),i),e.__exportStar(mo(),i),e.__exportStar(Rf(),i),e.__exportStar(Lf(),i),e.__exportStar(Cf(),i)})(Ah);const Fy="https://iameli.com",Ny="did:plc:rbvrr34edl5ddpuwcubjiost",By="place.stream.video",ds=new Map;async function wf(i){var e,t,r,s;if(ds.has(i))return ds.get(i);try{if(i.startsWith("did:plc:")){const n=await fetch(`https://plc.directory/${i}`);if(!n.ok)return null;const o=((t=(e=(await n.json()).alsoKnownAs)==null?void 0:e.find(u=>u.startsWith("at://")))==null?void 0:t.replace("at://",""))??null;return o&&ds.set(i,o),o}else if(i.startsWith("did:web:")){const n=i.replace("did:web:",""),a=await fetch(`https://${n}/.well-known/did.json`);if(!a.ok)return null;const u=((s=(r=(await a.json()).alsoKnownAs)==null?void 0:r.find(l=>l.startsWith("at://")))==null?void 0:s.replace("at://",""))??null;return u&&ds.set(i,u),u}}catch{}return null}const Uy=new Ah.Client(Fy);async function $y(){const i=[];let e;do{const t=await Uy.listRecords(By,{repo:Ny,limit:100,cursor:e});for(const r of t.body.records)i.push({cid:r.cid,uri:r.uri,value:r.value});e=t.body.cursor}while(e);return i.reverse()}function Pf(){const i=window.location.pathname,e=i.lastIndexOf("/");return i.substring(0,e+1)}function jy(){const i=window.location.pathname,e=i.lastIndexOf("/");return i.substring(e+1)||null}function po(i){const e=i.split("/");return e[e.length-1]}function yo(i){return new Date(i.value.createdAt).toLocaleDateString("en-CA",{timeZone:"America/Los_Angeles"})}function kf(i){const e=new Map;for(const t of i){const r=yo(t);e.has(r)||e.set(r,[]),e.get(r).push(t)}return e}function $c(i){const e=Pf();if(i){const t=po(i);history.pushState({channel:i},"",`${e}${t}`)}else history.pushState(null,"",e)}function Gy(i){const e=i.match(/(?:(\d+)h)?(?:(\d+)m)?(\d+)s?/);if(!e)return 0;const t=parseInt(e[1]||"0",10),r=parseInt(e[2]||"0",10),s=parseInt(e[3]||"0",10);return t*3600+r*60+s}function Of(){const e=new URLSearchParams(window.location.search).get("t");return e?Gy(e):0}function Vy(i){const e=Math.floor(i/3600),t=Math.floor(i%3600/60),r=i%60;return e>0?`${e}:${String(t).padStart(2,"0")}:${String(r).padStart(2,"0")}`:`${t}:${String(r).padStart(2,"0")}`}function Ky(i){return new Date(i).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/Los_Angeles"})}function qy(i){const[e,t,r]=i.split("-").map(Number);return new Date(e,t-1,r).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"})}function Hy({days:i,selectedDay:e,onSelectDay:t}){return H("div",{class:"flex w-full",children:i.map(r=>H("button",{class:`flex-1 py-2 px-1 bg-transparent border border-[rgba(255,255,255,0.3)] border-r-0 last:border-r last:border-[rgba(255,255,255,0.3)] text-[rgba(255,255,255,0.7)] text-xs cursor-pointer transition-all duration-150 text-center hover:bg-[rgba(255,255,255,0.1)] ${r===e?"bg-[rgba(255,255,255,0.15)] border-[rgba(255,255,255,0.9)] text-[rgba(255,255,255,0.9)]":""}`,onClick:()=>t(r),children:qy(r)}))})}function Wy({record:i,index:e,isSelected:t,onClick:r,handle:s}){const n=i.value.title||"Unknown Programme",a=Math.round((i.value.duration||0)/1e9),o=a>0?` (${Vy(a)})`:"",u=Ky(i.value.createdAt);return H("div",{class:`bg-transparent border border-[rgba(255,255,255,0.4)] border-l-[3px] border-l-[rgba(255,255,255,0.6)] rounded p-2.5 flex flex-col gap-1 cursor-pointer transition-all duration-150 min-h-[100px] hover:bg-[rgba(255,255,255,0.08)] hover:border-[rgba(255,255,255,0.6)] hover:border-l-[rgba(255,255,255,0.9)] ${t?"bg-[rgba(255,255,255,0.15)] border-[rgba(255,255,255,0.9)] border-l-[rgba(255,255,255,0.9)] hover:bg-[rgba(255,255,255,0.2)]":""}`,onClick:r,children:[H("div",{class:"text-[11px] text-[rgba(255,255,255,0.5)] tracking-wide",children:u}),H("div",{class:"text-sm text-[rgba(255,255,255,0.9)] leading-tight",children:[n,o]}),s&&H("a",{class:"text-[11px] text-[rgba(255,255,255,0.5)] no-underline hover:text-[rgba(255,255,255,0.7)]",href:`https://bsky.app/profile/${s}`,target:"_blank",rel:"noopener",onClick:l=>l.stopPropagation(),children:["@",s]})]})}function zy({vods:i,selectedDay:e,currentChannel:t,handles:r,onSelectVideo:s}){const n=e?i.filter(u=>yo(u)===e):i,a=n.findIndex(u=>u.uri===t);let o="0/0";return n.length>0&&(o=a>=0?`${a+1}/${n.length}`:`${n.length} videos`),H(qi,{children:[H("div",{class:"text-lg text-[rgba(255,255,255,0.9)] mb-3 pb-2 border-b border-[rgba(255,255,255,0.2)] flex justify-between items-center",children:H("h3",{class:"m-0",children:["Available Videos",H("span",{class:"text-sm text-[rgba(255,255,255,0.6)] ml-2",children:o})]})}),H("div",{class:"flex flex-col gap-1.5 p-1",id:"videoListContainer",children:n.map((u,l)=>H(Wy,{record:u,index:l,isSelected:u.uri===t,onClick:()=>s(u.uri),handle:r.get(u.value.creator)??null},u.uri))})]})}function Yy({vods:i,handles:e,currentChannel:t,selectedDay:r,onSelectDay:s,onSelectVideo:n,collapsed:a}){const o=kf(i),u=Array.from(o.keys()).sort();return H("div",{class:`transition-all duration-300 ease-in-out overflow-hidden fixed lg:relative inset-y-0 left-0 z-50 lg:z-auto ${a?"w-0 min-w-0":"w-full lg:w-[400px] lg:min-w-[400px]"} h-screen overflow-y-auto bg-[#1a1a1a]`,children:H("div",{class:`p-4 ${a?"opacity-0 pointer-events-none":"opacity-100"}`,children:[H(Hy,{days:u,selectedDay:r,onSelectDay:s}),H(zy,{vods:i,selectedDay:r,currentChannel:t,handles:e,onSelectVideo:n})]})})}function Xy(i){const e=Math.floor(i/3600),t=Math.floor(i%3600/60),r=Math.floor(i%60);return e>0?`${e}:${t.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`:`${t}:${r.toString().padStart(2,"0")}`}function Qy(i){return new Date(i).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function Zy(i){const e=Math.floor(i/3600),t=Math.floor(i%3600/60),r=Math.floor(i%60);let s="";return e>0&&(s+=`${e}h`),t>0&&(s+=`${t}m`),(r>0||s==="")&&(s+=`${r}s`),s}function jc(i,e,t){if(!i)return"";const r=Pf(),s=po(i),n=new URL(`${r}${s}`,window.location.origin);return t&&e!==null&&e>0&&n.searchParams.set("t",Zy(e)),n.toString()}function Jy({currentTitle:i,currentUri:e,currentDescription:t,currentCreator:r,currentHandle:s,currentCreatedAt:n,currentDuration:a,isLoading:o,showStandby:u,videoRef:l,audioRef:c}){const[d,h]=ze(!1),[f,g]=ze(!1),[p,m]=ze(!1),v=_n(()=>{h(!0),m(!1)},[]),y=_n(()=>{const _=l.current,T=_?Math.floor(_.currentTime):null,x=jc(e,T,f);navigator.clipboard.writeText(x),m(!0),setTimeout(()=>m(!1),2e3)},[e,f,l]),S=_n(()=>{h(!1),g(!1),m(!1)},[]);return H("div",{class:"flex flex-1 flex-col overflow-auto p-4",children:[H("div",{class:"relative flex flex-col justify-center items-center overflow-hidden rounded-lg [background:linear-gradient(45deg,#0a0806_0%,#1a1410_50%,#0a0806_100%)]",children:[H("video",{id:"video",ref:l,controls:!0,class:"w-full object-contain bg-[#0a0806]"}),H("audio",{id:"audio",ref:c,preload:"none"}),H("div",{class:`absolute bottom-4 left-1/2 -translate-x-1/2 z-10 font-sans text-lg text-[#7dd3fc] transition-opacity duration-300 pointer-events-none ${o?"opacity-100":"opacity-0"}`,id:"loadingIndicator",children:"Loading..."}),H("div",{class:`absolute inset-0 flex flex-col justify-center items-center [background:linear-gradient(45deg,#0a0806_0%,#1a1410_50%,#0a0806_100%)] ${u?"":"hidden"}`,id:"standby",children:H("div",{class:"font-sans text-3xl font-semibold text-[#7dd3fc] tracking-widest",children:"ATmosphereConf 2026"})})]}),i&&!u&&H("div",{class:"flex flex-col gap-3 mt-4",children:[H("div",{class:"flex flex-col gap-1",children:[e?H("a",{class:"font-sans text-xl font-semibold text-[#7dd3fc] no-underline hover:underline",href:`https://pds.ls/${e}`,target:"_blank",rel:"noopener",children:i}):H("h2",{class:"font-sans text-xl font-semibold text-[#7dd3fc] m-0",children:i}),H("div",{class:"flex flex-wrap gap-3 font-sans text-sm text-white/60",children:[r&&H("span",{children:["By ",H("a",{class:"text-[#7dd3fc] no-underline hover:underline",href:s?`https://bsky.app/profile/${s}`:`https://bsky.app/profile/${r}`,target:"_blank",rel:"noopener",children:["@",s||r]})]}),n&&H("span",{children:Qy(n)}),a!==null&&H("span",{children:Xy(a)})]})]}),t&&H("p",{class:"font-sans text-sm text-white/80 m-0 whitespace-pre-wrap",children:t}),H("button",{onClick:v,class:"flex items-center gap-2 font-sans text-sm text-white/60 hover:text-white/80 bg-transparent border border-white/30 rounded px-3 py-1.5 cursor-pointer transition-colors w-fit",children:"Share"})]}),d&&H("div",{class:"fixed inset-0 bg-black/70 flex items-center justify-center z-50",onClick:S,children:H("div",{class:"bg-[#1a1a1a] rounded-lg p-6 max-w-md w-full mx-4 border border-white/20",onClick:_=>_.stopPropagation(),children:[H("h3",{class:"font-sans text-lg font-semibold text-white m-0 mb-4",children:"Share this video"}),H("label",{class:"flex items-center gap-2 font-sans text-sm text-white/80 mb-4 cursor-pointer",children:[H("input",{type:"checkbox",checked:f,onChange:_=>g(_.target.checked),class:"w-4 h-4 cursor-pointer accent-[#7dd3fc]"}),"Include current timestamp"]}),H("div",{class:"flex gap-2",children:[H("input",{type:"text",value:jc(e,l.current?Math.floor(l.current.currentTime):null,f),readOnly:!0,class:"flex-1 bg-black/30 border border-white/30 rounded px-3 py-2 font-sans text-sm text-white/90 outline-none"}),H("button",{onClick:y,class:"px-4 py-2 bg-[#7dd3fc] text-black font-sans text-sm font-medium rounded cursor-pointer hover:bg-[#5cb8e0] transition-colors",children:p?"Copied!":"Copy"})]}),H("button",{onClick:S,class:"mt-4 font-sans text-sm text-white/50 hover:text-white/70 cursor-pointer bg-transparent border-none",children:"Close"})]})})]})}const $=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},ev=Number.isSafeInteger||function(i){return typeof i=="number"&&Math.abs(i)<=tv},tv=Number.MAX_SAFE_INTEGER||9007199254740991;let q=function(i){return i.NETWORK_ERROR="networkError",i.MEDIA_ERROR="mediaError",i.KEY_SYSTEM_ERROR="keySystemError",i.MUX_ERROR="muxError",i.OTHER_ERROR="otherError",i}({}),C=function(i){return i.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",i.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",i.KEY_SYSTEM_NO_SESSION="keySystemNoSession",i.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",i.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",i.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",i.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",i.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",i.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",i.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",i.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",i.MANIFEST_LOAD_ERROR="manifestLoadError",i.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",i.MANIFEST_PARSING_ERROR="manifestParsingError",i.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",i.LEVEL_EMPTY_ERROR="levelEmptyError",i.LEVEL_LOAD_ERROR="levelLoadError",i.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",i.LEVEL_PARSING_ERROR="levelParsingError",i.LEVEL_SWITCH_ERROR="levelSwitchError",i.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",i.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",i.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",i.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",i.FRAG_LOAD_ERROR="fragLoadError",i.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",i.FRAG_DECRYPT_ERROR="fragDecryptError",i.FRAG_PARSING_ERROR="fragParsingError",i.FRAG_GAP="fragGap",i.REMUX_ALLOC_ERROR="remuxAllocError",i.KEY_LOAD_ERROR="keyLoadError",i.KEY_LOAD_TIMEOUT="keyLoadTimeOut",i.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",i.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",i.BUFFER_APPEND_ERROR="bufferAppendError",i.BUFFER_APPENDING_ERROR="bufferAppendingError",i.BUFFER_STALLED_ERROR="bufferStalledError",i.BUFFER_FULL_ERROR="bufferFullError",i.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",i.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",i.ASSET_LIST_LOAD_ERROR="assetListLoadError",i.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",i.ASSET_LIST_PARSING_ERROR="assetListParsingError",i.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",i.INTERNAL_EXCEPTION="internalException",i.INTERNAL_ABORTED="aborted",i.ATTACH_MEDIA_ERROR="attachMediaError",i.UNKNOWN="unknown",i}({}),E=function(i){return i.MEDIA_ATTACHING="hlsMediaAttaching",i.MEDIA_ATTACHED="hlsMediaAttached",i.MEDIA_DETACHING="hlsMediaDetaching",i.MEDIA_DETACHED="hlsMediaDetached",i.MEDIA_ENDED="hlsMediaEnded",i.STALL_RESOLVED="hlsStallResolved",i.BUFFER_RESET="hlsBufferReset",i.BUFFER_CODECS="hlsBufferCodecs",i.BUFFER_CREATED="hlsBufferCreated",i.BUFFER_APPENDING="hlsBufferAppending",i.BUFFER_APPENDED="hlsBufferAppended",i.BUFFER_EOS="hlsBufferEos",i.BUFFERED_TO_END="hlsBufferedToEnd",i.BUFFER_FLUSHING="hlsBufferFlushing",i.BUFFER_FLUSHED="hlsBufferFlushed",i.MANIFEST_LOADING="hlsManifestLoading",i.MANIFEST_LOADED="hlsManifestLoaded",i.MANIFEST_PARSED="hlsManifestParsed",i.LEVEL_SWITCHING="hlsLevelSwitching",i.LEVEL_SWITCHED="hlsLevelSwitched",i.LEVEL_LOADING="hlsLevelLoading",i.LEVEL_LOADED="hlsLevelLoaded",i.LEVEL_UPDATED="hlsLevelUpdated",i.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",i.LEVELS_UPDATED="hlsLevelsUpdated",i.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",i.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",i.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",i.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",i.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",i.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",i.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",i.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",i.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",i.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",i.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",i.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",i.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",i.CUES_PARSED="hlsCuesParsed",i.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",i.INIT_PTS_FOUND="hlsInitPtsFound",i.FRAG_LOADING="hlsFragLoading",i.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",i.FRAG_LOADED="hlsFragLoaded",i.FRAG_DECRYPTED="hlsFragDecrypted",i.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",i.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",i.FRAG_PARSING_METADATA="hlsFragParsingMetadata",i.FRAG_PARSED="hlsFragParsed",i.FRAG_BUFFERED="hlsFragBuffered",i.FRAG_CHANGED="hlsFragChanged",i.FPS_DROP="hlsFpsDrop",i.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",i.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",i.ERROR="hlsError",i.DESTROYING="hlsDestroying",i.KEY_LOADING="hlsKeyLoading",i.KEY_LOADED="hlsKeyLoaded",i.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",i.BACK_BUFFER_REACHED="hlsBackBufferReached",i.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",i.ASSET_LIST_LOADING="hlsAssetListLoading",i.ASSET_LIST_LOADED="hlsAssetListLoaded",i.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",i.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",i.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",i.INTERSTITIAL_STARTED="hlsInterstitialStarted",i.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",i.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",i.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",i.INTERSTITIAL_ENDED="hlsInterstitialEnded",i.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",i.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",i.EVENT_CUE_ENTER="hlsEventCueEnter",i}({});var J={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},V={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Ur{constructor(e,t=0,r=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_=r}sample(e,t){const r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*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 rv{constructor(e,t,r,s=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_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ur(e),this.fast_=new Ur(t),this.defaultTTFB_=s,this.ttfb_=new Ur(e)}update(e,t){const{slow_:r,fast_:s,ttfb_:n}=this;r.halfLife!==e&&(this.slow_=new Ur(e,r.getEstimate(),r.getTotalWeight())),s.halfLife!==t&&(this.fast_=new Ur(t,s.getEstimate(),s.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new Ur(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const r=8*t,s=e/1e3,n=r/s;this.fast_.sample(s,n),this.slow_.sample(s,n)}sampleTTFB(e){const t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function iv(i,e,t){return(e=nv(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function ae(){return ae=Object.assign?Object.assign.bind():function(i){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var r in t)({}).hasOwnProperty.call(t,r)&&(i[r]=t[r])}return i},ae.apply(null,arguments)}function Gc(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(i);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(i,s).enumerable})),t.push.apply(t,r)}return t}function se(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Gc(Object(t),!0).forEach(function(r){iv(i,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):Gc(Object(t)).forEach(function(r){Object.defineProperty(i,r,Object.getOwnPropertyDescriptor(t,r))})}return i}function sv(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var r=t.call(i,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function nv(i){var e=sv(i,"string");return typeof e=="symbol"?e:e+""}class et{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const r=`[${e}]:`;this.trace=wt,this.debug=t.debug.bind(null,r),this.log=t.log.bind(null,r),this.warn=t.warn.bind(null,r),this.info=t.info.bind(null,r),this.error=t.error.bind(null,r)}}const wt=function(){},av={trace:wt,debug:wt,log:wt,warn:wt,info:wt,error:wt};function wa(){return ae({},av)}function ov(i,e){const t=self.console[i];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${i}] >`):wt}function Vc(i,e,t){return e[i]?e[i].bind(e):ov(i,t)}const Pa=wa();function lv(i,e,t){const r=wa();if(typeof console=="object"&&i===!0||typeof i=="object"){const s=["debug","log","info","warn","error"];s.forEach(n=>{r[n]=Vc(n,i,t)});try{r.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return wa()}s.forEach(n=>{Pa[n]=Vc(n,i)})}else ae(Pa,r);return r}const ne=Pa;function Ot(i=!0){return typeof self>"u"?void 0:(i||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function uv(i){return typeof self<"u"&&i===self.ManagedMediaSource}function Mf(i,e){const t=Object.keys(i),r=Object.keys(e),s=t.length,n=r.length;return!s||!n||s===n&&!t.some(a=>r.indexOf(a)===-1)}function Ye(i,e=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(i);if(e){const c=l.indexOf("\0");return c!==-1?l.substring(0,c):l}return l.replace(/\0/g,"")}const t=i.length;let r,s,n,a="",o=0;for(;o<t;){if(r=i[o++],r===0&&e)return a;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:a+=String.fromCharCode(r);break;case 12:case 13:s=i[o++],a+=String.fromCharCode((r&31)<<6|s&63);break;case 14:s=i[o++],n=i[o++],a+=String.fromCharCode((r&15)<<12|(s&63)<<6|(n&63)<<0);break}}return a}function Ie(i){let e="";for(let t=0;t<i.length;t++){let r=i[t].toString(16);r.length<2&&(r="0"+r),e+=r}return e}function Ff(i){return Uint8Array.from(i.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function cv(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Zn={exports:{}},Kc;function dv(){return Kc||(Kc=1,function(i,e){(function(t){var r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(u,l,c){if(c=c||{},u=u.trim(),l=l.trim(),!l){if(!c.alwaysNormalize)return u;var d=o.parseURL(u);if(!d)throw new Error("Error trying to parse base URL.");return d.path=o.normalizePath(d.path),o.buildURLFromParts(d)}var h=o.parseURL(l);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return c.alwaysNormalize?(h.path=o.normalizePath(h.path),o.buildURLFromParts(h)):l;var f=o.parseURL(u);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=s.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(p.netLoc=f.netLoc,h.path[0]!=="/"))if(!h.path)p.path=f.path,h.params||(p.params=f.params,h.query||(p.query=f.query));else{var m=f.path,v=m.substring(0,m.lastIndexOf("/")+1)+h.path;p.path=o.normalizePath(v)}return p.path===null&&(p.path=c.alwaysNormalize?o.normalizePath(h.path):h.path),o.buildURLFromParts(p)},parseURL:function(u){var l=r.exec(u);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(u){for(u=u.split("").reverse().join("").replace(n,"");u.length!==(u=u.replace(a,"")).length;);return u.split("").reverse().join("")},buildURLFromParts:function(u){return u.scheme+u.netLoc+u.path+u.params+u.query+u.fragment}};i.exports=o})()}(Zn)),Zn.exports}var vo=dv();class Eo{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 oe={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Nf{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,fv(this,"stats")}setByteRange(e,t){const r=e.split("@",2);let s;r.length===1?s=(t==null?void 0:t.byteRangeEndOffset)||0:s=parseInt(r[1]),this._byteRange=[s,parseInt(r[0])+s]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[oe.AUDIO]:null,[oe.VIDEO]:null,[oe.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Eo),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=vo.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[oe.AUDIO]=null,e[oe.VIDEO]=null,e[oe.AUDIOVIDEO]=null}}function me(i){return i.sn!=="initSegment"}class Jn extends Nf{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if($(e)&&$(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const r=Object.keys(t);if(r.length===1){const s=this._decryptdata=t[r[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=$(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const r=Object.keys(this.levelkeys),s=r.length;if(s>1||s===1&&(t=this.levelkeys[r[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!$(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return me(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var r;const s=t[e];s&&!((r=this._decryptdata)!=null&&r.keyId)&&(this._decryptdata=s.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,r,s,n,a=!1){const{elementaryStreams:o}=this,u=o[e];if(!u){o[e]={startPTS:t,endPTS:r,startDTS:s,endDTS:n,partial:a};return}u.startPTS=Math.min(u.startPTS,t),u.endPTS=Math.max(u.endPTS,r),u.startDTS=Math.min(u.startDTS,s),u.endDTS=Math.max(u.endDTS,n)}}class hv extends Nf{constructor(e,t,r,s,n){super(r),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function Bf(i,e){const t=Object.getPrototypeOf(i);if(t){const r=Object.getOwnPropertyDescriptor(t,e);return r||Bf(t,e)}}function fv(i,e){const t=Bf(i,e);t&&(t.enumerable=!0,Object.defineProperty(i,e,t))}const qc=Math.pow(2,32)-1,gv=[].push,Uf={video:1,audio:2,id3:3,text:4};function Se(i){return String.fromCharCode.apply(null,i)}function $f(i,e){const t=i[e]<<8|i[e+1];return t<0?65536+t:t}function z(i,e){const t=jf(i,e);return t<0?4294967296+t:t}function Hc(i,e){let t=z(i,e);return t*=Math.pow(2,32),t+=z(i,e+4),t}function jf(i,e){return i[e]<<24|i[e+1]<<16|i[e+2]<<8|i[e+3]}function mv(i){const e=i.byteLength;for(let t=0;t<e;){const r=z(i,t);if(r>8&&i[t+4]===109&&i[t+5]===111&&i[t+6]===111&&i[t+7]===102)return!0;t=r>1?t+r:e}return!1}function Z(i,e){const t=[];if(!e.length)return t;const r=i.byteLength;for(let s=0;s<r;){const n=z(i,s),a=Se(i.subarray(s+4,s+8)),o=n>1?s+n:r;if(a===e[0])if(e.length===1)t.push(i.subarray(s+8,o));else{const u=Z(i.subarray(s+8,o),e.slice(1));u.length&&gv.apply(t,u)}s=o}return t}function pv(i){const e=[],t=i[0];let r=8;const s=z(i,r);r+=4;let n=0,a=0;t===0?(n=z(i,r),a=z(i,r+4),r+=8):(n=Hc(i,r),a=Hc(i,r+8),r+=16),r+=2;let o=i.length+a;const u=$f(i,r);r+=2;for(let l=0;l<u;l++){let c=r;const d=z(i,c);c+=4;const h=d&2147483647;if((d&2147483648)>>>31===1)return ne.warn("SIDX has hierarchical references (not supported)"),null;const g=z(i,c);c+=4,e.push({referenceSize:h,subsegmentDuration:g,info:{duration:g/s,start:o,end:o+h-1}}),o+=h,c+=4,r=c}return{earliestPresentationTime:n,timescale:s,version:t,referencesCount:u,references:e}}function Gf(i){const e=[],t=Z(i,["moov","trak"]);for(let s=0;s<t.length;s++){const n=t[s],a=Z(n,["tkhd"])[0];if(a){let o=a[0];const u=z(a,o===0?12:20),l=Z(n,["mdia","mdhd"])[0];if(l){o=l[0];const c=z(l,o===0?12:20),d=Z(n,["mdia","hdlr"])[0];if(d){const h=Se(d.subarray(8,12)),f={soun:oe.AUDIO,vide:oe.VIDEO}[h],g=Z(n,["mdia","minf","stbl","stsd"])[0],p=yv(g);f?(e[u]={timescale:c,type:f,stsd:p},e[f]=se({timescale:c,id:u},p)):e[u]={timescale:c,type:h,stsd:p}}}}}return Z(i,["moov","mvex","trex"]).forEach(s=>{const n=z(s,4),a=e[n];a&&(a.default={duration:z(s,12),flags:z(s,20)})}),e}function yv(i){const e=i.subarray(8),t=e.subarray(86),r=Se(e.subarray(4,8));let s=r,n;const a=r==="enca"||r==="encv";if(a){const l=Z(e,[r])[0].subarray(r==="enca"?28:78);Z(l,["sinf"]).forEach(d=>{const h=Z(d,["schm"])[0];if(h){const f=Se(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){const g=Z(d,["frma"])[0];g&&(s=Se(g))}}})}const o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const u=Z(t,["avcC"])[0];u&&u.length>3&&(s+="."+fs(u[1])+fs(u[2])+fs(u[3]),n=hs(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const u=Z(e,[r])[0],l=Z(u.subarray(28),["esds"])[0];if(l&&l.length>7){let c=4;if(l[c++]!==3)break;c=ea(l,c),c+=2;const d=l[c++];if(d&128&&(c+=2),d&64&&(c+=l[c++]),l[c++]!==4)break;c=ea(l,c);const h=l[c++];if(h===64)s+="."+fs(h);else break;if(c+=12,l[c++]!==5)break;c=ea(l,c);const f=l[c++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((l[c]&224)>>5)),s+="."+g}break}case"hvc1":case"hev1":{const u=Z(t,["hvcC"])[0];if(u&&u.length>12){const l=u[1],c=["","A","B","C"][l>>6],d=l&31,h=z(u,2),f=(l&32)>>5?"H":"L",g=u[12],p=u.subarray(6,12);s+="."+c+d,s+="."+vv(h).toString(16).toUpperCase(),s+="."+f+g;let m="";for(let v=p.length;v--;){const y=p[v];(y||m)&&(m="."+y.toString(16).toUpperCase()+m)}s+=m}n=hs(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{s=hs(s,t)||s;break}case"vp09":{const u=Z(t,["vpcC"])[0];if(u&&u.length>6){const l=u[4],c=u[5],d=u[6]>>4&15;s+="."+ut(l)+"."+ut(c)+"."+ut(d)}break}case"av01":{const u=Z(t,["av1C"])[0];if(u&&u.length>2){const l=u[1]>>>5,c=u[1]&31,d=u[2]>>>7?"H":"M",h=(u[2]&64)>>6,f=(u[2]&32)>>5,g=l===2&&h?f?12:10:h?10:8,p=(u[2]&16)>>4,m=(u[2]&8)>>3,v=(u[2]&4)>>2,y=u[2]&3;s+="."+l+"."+ut(c)+d+"."+ut(g)+"."+p+"."+m+v+y+"."+ut(1)+"."+ut(1)+"."+ut(1)+"."+0,n=hs("dav1",t)}break}}return{codec:s,encrypted:a,supplemental:n}}function hs(i,e){const t=Z(e,["dvvC"]),r=t.length?t[0]:Z(e,["dvcC"])[0];if(r){const s=r[2]>>1&127,n=r[2]<<5&32|r[3]>>3&31;return i+"."+ut(s)+"."+ut(n)}}function vv(i){let e=0;for(let t=0;t<32;t++)e|=(i>>t&1)<<31-t;return e>>>0}function ea(i,e){const t=e+5;for(;i[e++]&128&&e<t;);return e}function fs(i){return("0"+i.toString(16).toUpperCase()).slice(-2)}function ut(i){return(i<10?"0":"")+i}function Ev(i,e){if(!i||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&Vf(i,(r,s)=>{const n=r.subarray(8,24);n.some(a=>a!==0)||(ne.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${Ie(n)} -> ${Ie(t)}`),r.set(t,8))})}function Sv(i){const e=[];return Vf(i,t=>e.push(t.subarray(8,24))),e}function Vf(i,e){Z(i,["moov","trak"]).forEach(r=>{const s=Z(r,["mdia","minf","stbl","stsd"])[0];if(!s)return;const n=s.subarray(8);let a=Z(n,["enca"]);const o=a.length>0;o||(a=Z(n,["encv"])),a.forEach(u=>{const l=o?u.subarray(28):u.subarray(78);Z(l,["sinf"]).forEach(d=>{const h=Kf(d);h&&e(h,o)})})})}function Kf(i){const e=Z(i,["schm"])[0];if(e){const t=Se(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const r=Z(i,["schi","tenc"])[0];if(r)return r}}}function _v(i,e,t){const r={},s=Z(i,["moof","traf"]);for(let n=0;n<s.length;n++){const a=s[n],o=Z(a,["tfhd"])[0],u=z(o,4),l=e[u];if(!l)continue;r[u]||(r[u]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const c=r[u],d=Z(a,["tfdt"])[0];if(d){const S=d[0];let _=z(d,4);S===1&&(_===qc?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(_*=qc+1,_+=z(d,8))),$(_)&&(!$(c.start)||_<c.start)&&(c.start=_)}const h=l.default,f=z(o,0)|(h==null?void 0:h.flags);let g=(h==null?void 0:h.duration)||0;f&8&&(f&2?g=z(o,12):g=z(o,8));const p=Z(a,["trun"]);let m=c.start||0,v=0,y=g;for(let S=0;S<p.length;S++){const _=p[S],T=z(_,4),x=c.sampleCount;c.sampleCount+=T;const b=_[3]&1,I=_[3]&4,A=_[2]&1,D=_[2]&2,L=_[2]&4,P=_[2]&8;let O=8,G=T;for(b&&(O+=4),I&&T&&(!(_[O+1]&1)&&c.keyFrameIndex===void 0&&(c.keyFrameIndex=x),O+=4,A?(y=z(_,O),O+=4):y=g,D&&(O+=4),P&&(O+=4),m+=y,v+=y,G--);G--;)A?(y=z(_,O),O+=4):y=g,D&&(O+=4),L&&(_[O+1]&1||c.keyFrameIndex===void 0&&(c.keyFrameIndex=c.sampleCount-(G+1),c.keyFrameStart=m),O+=4),P&&(O+=4),m+=y,v+=y;!v&&g&&(v+=g*T)}c.duration+=v}if(!Object.keys(r).some(n=>r[n].duration)){let n=1/0,a=0;const o=Z(i,["sidx"]);for(let u=0;u<o.length;u++){const l=pv(o[u]);if(l!=null&&l.references){n=Math.min(n,l.earliestPresentationTime/l.timescale);const c=l.references.reduce((d,h)=>d+h.info.duration||0,0);a=Math.max(a,c+l.earliestPresentationTime/l.timescale)}}a&&$(a)&&Object.keys(r).forEach(u=>{r[u].duration||(r[u].duration=a*r[u].timescale-r[u].start)})}return r}function Tv(i){const e={valid:null,remainder:null},t=Z(i,["moof"]);if(t.length<2)return e.remainder=i,e;const r=t[t.length-1];return e.valid=i.slice(0,r.byteOffset-8),e.remainder=i.slice(r.byteOffset-8),e}function Je(i,e){const t=new Uint8Array(i.length+e.length);return t.set(i),t.set(e,i.length),t}function Wc(i,e){const t=[],r=e.samples,s=e.timescale,n=e.id;let a=!1;return Z(r,["moof"]).map(u=>{const l=u.byteOffset-8;Z(u,["traf"]).map(d=>{const h=Z(d,["tfdt"]).map(f=>{const g=f[0];let p=z(f,4);return g===1&&(p*=Math.pow(2,32),p+=z(f,8)),p/s})[0];return h!==void 0&&(i=h),Z(d,["tfhd"]).map(f=>{const g=z(f,4),p=z(f,0)&16777215,m=(p&1)!==0,v=(p&2)!==0,y=(p&8)!==0;let S=0;const _=(p&16)!==0;let T=0;const x=(p&32)!==0;let b=8;g===n&&(m&&(b+=8),v&&(b+=4),y&&(S=z(f,b),b+=4),_&&(T=z(f,b),b+=4),x&&(b+=4),e.type==="video"&&(a=mn(e.codec)),Z(d,["trun"]).map(I=>{const A=I[0],D=z(I,0)&16777215,L=(D&1)!==0;let P=0;const O=(D&4)!==0,G=(D&256)!==0;let j=0;const M=(D&512)!==0;let U=0;const F=(D&1024)!==0,K=(D&2048)!==0;let W=0;const N=z(I,4);let B=8;L&&(P=z(I,B),B+=4),O&&(B+=4);let X=P+l;for(let ie=0;ie<N;ie++){if(G?(j=z(I,B),B+=4):j=S,M?(U=z(I,B),B+=4):U=T,F&&(B+=4),K&&(A===0?W=z(I,B):W=jf(I,B),B+=4),e.type===oe.VIDEO){let Q=0;for(;Q<U;){const ee=z(r,X);if(X+=4,bv(a,r[X])){const Re=r.subarray(X,X+ee);So(Re,a?2:1,i+W/s,t)}X+=ee,Q+=ee+4}}i+=j/s}}))})})}),t}function mn(i){if(!i)return!1;const e=i.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function bv(i,e){if(i){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function So(i,e,t,r){const s=qf(i);let n=0;n+=e;let a=0,o=0,u=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;u=s[n++],a+=u}while(u===255);o=0;do{if(n>=s.length)break;u=s[n++],o+=u}while(u===255);const l=s.length-n;let c=n;if(o<l)n+=o;else if(o>l){ne.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(a===4){if(s[c++]===181){const h=$f(s,c);if(c+=2,h===49){const f=z(s,c);if(c+=4,f===1195456820){const g=s[c++];if(g===3){const p=s[c++],m=31&p,v=64&p,y=v?2+m*3:0,S=new Uint8Array(y);if(v){S[0]=p;for(let _=1;_<y;_++)S[_]=s[c++]}r.push({type:g,payloadType:a,pts:t,bytes:S})}}}}}else if(a===5&&o>16){const d=[];for(let g=0;g<16;g++){const p=s[c++].toString(16);d.push(p.length==1?"0"+p:p),(g===3||g===5||g===7||g===9)&&d.push("-")}const h=o-16,f=new Uint8Array(h);for(let g=0;g<h;g++)f[g]=s[c++];r.push({payloadType:a,pts:t,uuid:d.join(""),userData:Ye(f),userDataBytes:f})}}}function qf(i){const e=i.byteLength,t=[];let r=1;for(;r<e-2;)i[r]===0&&i[r+1]===0&&i[r+2]===3?(t.push(r+2),r+=2):r++;if(t.length===0)return i;const s=e-t.length,n=new Uint8Array(s);let a=0;for(r=0;r<s;a++,r++)a===t[0]&&(a++,t.shift()),n[r]=i[a];return n}function xv(i){const e=i[0];let t="",r="",s=0,n=0,a=0,o=0,u=0,l=0;if(e===0){for(;Se(i.subarray(l,l+1))!=="\0";)t+=Se(i.subarray(l,l+1)),l+=1;for(t+=Se(i.subarray(l,l+1)),l+=1;Se(i.subarray(l,l+1))!=="\0";)r+=Se(i.subarray(l,l+1)),l+=1;r+=Se(i.subarray(l,l+1)),l+=1,s=z(i,12),n=z(i,16),o=z(i,20),u=z(i,24),l=28}else if(e===1){l+=4,s=z(i,l),l+=4;const d=z(i,l);l+=4;const h=z(i,l);for(l+=4,a=2**32*d+h,ev(a)||(a=Number.MAX_SAFE_INTEGER,ne.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=z(i,l),l+=4,u=z(i,l),l+=4;Se(i.subarray(l,l+1))!=="\0";)t+=Se(i.subarray(l,l+1)),l+=1;for(t+=Se(i.subarray(l,l+1)),l+=1;Se(i.subarray(l,l+1))!=="\0";)r+=Se(i.subarray(l,l+1)),l+=1;r+=Se(i.subarray(l,l+1)),l+=1}const c=i.subarray(l,i.byteLength);return{schemeIdUri:t,value:r,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:u,payload:c}}function Av(i,...e){const t=e.length;let r=8,s=t;for(;s--;)r+=e[s].byteLength;const n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=r&255,n.set(i,4),s=0,r=8;s<t;s++)n.set(e[s],r),r+=e[s].byteLength;return n}function Iv(i,e,t){if(i.byteLength!==16)throw new RangeError("Invalid system id");let r,s;r=0,s=new Uint8Array;let n;r>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),Av([112,115,115,104],new Uint8Array([r,0,0,0]),i,n,s,a,t)}function Dv(i){const e=[];if(i instanceof ArrayBuffer){const t=i.byteLength;let r=0;for(;r+32<t;){const s=new DataView(i,r),n=Lv(s);e.push(n),r+=n.size}}return e}function Lv(i){const e=i.getUint32(0),t=i.byteOffset,r=i.byteLength;if(r<e)return{offset:t,size:r};if(i.getUint32(4)!==1886614376)return{offset:t,size:e};const n=i.getUint32(8)>>>24;if(n!==0&&n!==1)return{offset:t,size:e};const a=i.buffer,o=Ie(new Uint8Array(a,t+12,16));let u=null,l=null,c=0;if(n===0)c=28;else{const h=i.getUint32(28);if(!h||r<32+h*16)return{offset:t,size:e};u=[];for(let f=0;f<h;f++)u.push(new Uint8Array(a,t+32+f*16,16));c=32+h*16}if(!c)return{offset:t,size:e};const d=i.getUint32(c);return e-32<d?{offset:t,size:e}:(l=new Uint8Array(a,t+c+4,d),{version:n,systemId:o,kids:u,data:l,offset:t,size:e})}const Hf=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),ei={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function _o(i,e){const t=ei[e];return!!t&&!!t[i.slice(0,4)]}function Ni(i,e,t=!0){return!i.split(",").some(r=>!To(r,e,t))}function To(i,e,t=!0){var r;const s=Ot(t);return(r=s==null?void 0:s.isTypeSupported(Bi(i,e)))!=null?r:!1}function Bi(i,e){return`${e}/mp4;codecs=${i}`}function zc(i){if(i){const e=i.substring(0,4);return ei.video[e]}return 2}function Ys(i){const e=Hf();return i.split(",").reduce((t,r)=>{const n=e&&mn(r)?9:ei.video[r];return n?(n*2+t)/(t?3:2):(ei.audio[r]+t)/(t?2:1)},0)}const ta={};function Rv(i,e=!0){if(ta[i])return ta[i];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[i];for(let s=0;s<t.length;s++){var r;if(To(t[s],"audio",e))return ta[i]=t[s],t[s];if(t[s]==="mp3"&&(r=Ot(e))!=null&&r.isTypeSupported("audio/mpeg"))return""}return i}const Cv=/flac|opus|mp4a\.40\.34/i;function Xs(i,e=!0){return i.replace(Cv,t=>Rv(t.toLowerCase(),e))}function wv(i,e){const t=[];if(i){const r=i.split(",");for(let s=0;s<r.length;s++)_o(r[s],"video")||t.push(r[s])}return e&&t.push(e),t.join(",")}function Cs(i,e){if(i&&(i.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(i)!==-1)&&(Yc(i,"audio")||Yc(i,"video")))return i;if(e){const t=e.split(",");if(t.length>1){if(i){for(let r=t.length;r--;)if(t[r].substring(0,4)===i.substring(0,4))return t[r]}return t[0]}}return e||i}function Yc(i,e){return _o(i,e)&&To(i,e)}function Pv(i){const e=i.split(",");for(let t=0;t<e.length;t++){const r=e[t].split(".");r.length>2&&r[0]==="avc1"&&(e[t]=`avc1.${parseInt(r[1]).toString(16)}${("000"+parseInt(r[2]).toString(16)).slice(-4)}`)}return e.join(",")}function kv(i){if(i.startsWith("av01.")){const e=i.split("."),t=["0","111","01","01","01","0"];for(let r=e.length;r>4&&r<10;r++)e[r]=t[r-4];return e.join(".")}return i}function Xc(i){const e=Ot(i)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function ka(i){return i.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Ov={supported:!0,powerEfficient:!0,smooth:!0},Mv={supported:!1,smooth:!1,powerEfficient:!1},Wf={supported:!0,configurations:[],decodingInfoResults:[Ov]};function zf(i,e){return{supported:!1,configurations:e,decodingInfoResults:[Mv],error:i}}function Fv(i,e,t,r,s,n){const a=i.videoCodec,o=i.audioCodec?i.audioGroups:null,u=n==null?void 0:n.audioCodec,l=n==null?void 0:n.channels,c=l?parseInt(l):u?1/0:2;let d=null;if(o!=null&&o.length)try{o.length===1&&o[0]?d=e.groups[o[0]].channels:d=o.reduce((h,f)=>{if(f){const g=e.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(p=>{h[p]=(h[p]||0)+g.channels[p]})}return h},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(h=>mn(h))||i.width>1920&&i.height>1088||i.height>1920&&i.width>1088||i.frameRate>Math.max(r,30)||i.videoRange!=="SDR"&&i.videoRange!==t||i.bitrate>Math.max(s,8e6))||!!d&&$(c)&&Object.keys(d).some(h=>parseInt(h)>c)}function Yf(i,e,t,r={}){const s=i.videoCodec;if(!s&&!i.audioCodec||!t)return Promise.resolve(Wf);const n=[],a=Nv(i),o=a.length,u=Bv(i,e,o>0),l=u.length;for(let c=o||1*l||1;c--;){const d={type:"media-source"};if(o&&(d.video=a[c%o]),l){d.audio=u[c%l];const h=d.audio.bitrate;d.video&&h&&(d.video.bitrate-=h)}n.push(d)}if(s){const c=navigator.userAgent;if(s.split(",").some(d=>mn(d))&&Hf())return Promise.resolve(zf(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${c})`),n))}return Promise.all(n.map(c=>{const d=$v(c);return r[d]||(r[d]=t.decodingInfo(c))})).then(c=>({supported:!c.some(d=>!d.supported),configurations:n,decodingInfoResults:c})).catch(c=>({supported:!1,configurations:n,decodingInfoResults:[],error:c}))}function Nv(i){var e;const t=(e=i.videoCodec)==null?void 0:e.split(","),r=Xf(i),s=i.width||640,n=i.height||480,a=i.frameRate||30,o=i.videoRange.toLowerCase();return t?t.map(u=>{const l={contentType:Bi(kv(u),"video"),width:s,height:n,bitrate:r,framerate:a};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function Bv(i,e,t){var r;const s=(r=i.audioCodec)==null?void 0:r.split(","),n=Xf(i);return s&&i.audioGroups?i.audioGroups.reduce((a,o)=>{var u;const l=o?(u=e.groups[o])==null?void 0:u.tracks:null;return l?l.reduce((c,d)=>{if(d.groupId===o){const h=parseFloat(d.channels||"");s.forEach(f=>{const g={contentType:Bi(f,"audio"),bitrate:t?Uv(f,n):n};h&&(g.channels=""+h),c.push(g)})}return c},a):a},[]):[]}function Uv(i,e){if(e<=1)return 1;let t=128e3;return i==="ec-3"?t=768e3:i==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Xf(i){return Math.ceil(Math.max(i.bitrate*.9,i.averageBitrate)/1e3)*1e3||1}function $v(i){let e="";const{audio:t,video:r}=i;if(r){const s=ka(r.contentType);e+=`${s}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||"sd"}_${Math.ceil(r.bitrate/1e5)}`}if(t){const s=ka(t.contentType);e+=`${r?"_":""}${s}_c${t.channels}`}return e}const Oa=["NONE","TYPE-0","TYPE-1",null];function jv(i){return Oa.indexOf(i)>-1}const Qs=["SDR","PQ","HLG"];function Gv(i){return!!i&&Qs.indexOf(i)>-1}var ws={No:"",Yes:"YES",v2:"v2"};function Qc(i){const{canSkipUntil:e,canSkipDateRanges:t,age:r}=i,s=r<e/2;return e&&s?t?ws.v2:ws.Yes:ws.No}class Zc{constructor(e,t,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=r}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 Ui{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(r=>!!r).map(r=>r.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const r=(t=e.supplemental)==null?void 0:t.videoCodec;r&&r!==e.videoCodec&&(this.codecSet+=`,${r.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Jc(this._audioGroups,e)}hasSubtitleGroup(e){return Jc(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let r=this._audioGroups;r||(r=this._audioGroups=[]),r.indexOf(t)===-1&&r.push(t)}else if(e==="text"){let r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),r.indexOf(t)===-1&&r.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 Jc(i,e){return!e||!i?!1:i.indexOf(e)!==-1}function Vv(){if(typeof matchMedia=="function"){const i=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(i.media!==e.media)return i.matches===!0}return!1}function Kv(i,e){let t=!1,r=[];if(i&&(t=i!=="SDR",r=[i]),e){r=e.allowedVideoRanges||Qs.slice(0);const s=r.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:s&&Vv(),t||(r=["SDR"])}return{preferHDR:t,allowedVideoRanges:r}}const qv=i=>{const e=new WeakSet;return(t,r)=>{if(i&&(r=i(t,r)),typeof r=="object"&&r!==null){if(e.has(r))return;e.add(r)}return r}},ue=(i,e)=>JSON.stringify(i,qv(e));function Hv(i,e,t,r,s){const n=Object.keys(i),a=r==null?void 0:r.channels,o=r==null?void 0:r.audioCodec,u=s==null?void 0:s.videoCodec,l=a&&parseInt(a)===2;let c=!1,d=!1,h=1/0,f=1/0,g=1/0,p=1/0,m=0,v=[];const{preferHDR:y,allowedVideoRanges:S}=Kv(e,s);for(let I=n.length;I--;){const A=i[n[I]];c||(c=A.channels[2]>0),h=Math.min(h,A.minHeight),f=Math.min(f,A.minFramerate),g=Math.min(g,A.minBitrate),S.filter(L=>A.videoRanges[L]>0).length>0&&(d=!0)}h=$(h)?h:0,f=$(f)?f:0;const _=Math.max(1080,h),T=Math.max(30,f);g=$(g)?g:t,t=Math.max(g,t),d||(e=void 0);const x=n.length>1;return{codecSet:n.reduce((I,A)=>{const D=i[A];if(A===I)return I;if(v=d?S.filter(L=>D.videoRanges[L]>0):[],x){if(D.minBitrate>t)return ot(A,`min bitrate of ${D.minBitrate} > current estimate of ${t}`),I;if(!D.hasDefaultAudio)return ot(A,"no renditions with default or auto-select sound found"),I;if(o&&A.indexOf(o.substring(0,4))%5!==0)return ot(A,`audio codec preference "${o}" not found`),I;if(a&&!l){if(!D.channels[a])return ot(A,`no renditions with ${a} channel sound found (channels options: ${Object.keys(D.channels)})`),I}else if((!o||l)&&c&&D.channels[2]===0)return ot(A,"no renditions with stereo sound found"),I;if(D.minHeight>_)return ot(A,`min resolution of ${D.minHeight} > maximum of ${_}`),I;if(D.minFramerate>T)return ot(A,`min framerate of ${D.minFramerate} > maximum of ${T}`),I;if(!v.some(L=>D.videoRanges[L]>0))return ot(A,`no variants with VIDEO-RANGE of ${ue(v)} found`),I;if(u&&A.indexOf(u.substring(0,4))%5!==0)return ot(A,`video codec preference "${u}" not found`),I;if(D.maxScore<m)return ot(A,`max score of ${D.maxScore} < selected max of ${m}`),I}return I&&(Ys(A)>=Ys(I)||D.fragmentError>i[I].fragmentError)?I:(p=D.minIndex,m=D.maxScore,A)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:p}}function ot(i,e){ne.log(`[abr] start candidates with "${i}" ignored because ${e}`)}function Qf(i){return i.reduce((e,t)=>{let r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);const s=t.channels||"2";return r.channels[s]=(r.channels[s]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Wv(i,e,t,r){return i.slice(t,r+1).reduce((s,n,a)=>{if(!n.codecSet)return s;const o=n.audioGroups;let u=s[n.codecSet];u||(s[n.codecSet]=u={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),u.minBitrate=Math.min(u.minBitrate,n.bitrate);const l=Math.min(n.height,n.width);return u.minHeight=Math.min(u.minHeight,l),u.minFramerate=Math.min(u.minFramerate,n.frameRate),u.minIndex=Math.min(u.minIndex,a),u.maxScore=Math.max(u.maxScore,n.score),u.fragmentError+=n.fragmentError,u.videoRanges[n.videoRange]=(u.videoRanges[n.videoRange]||0)+1,o&&o.forEach(c=>{if(!c)return;const d=e.groups[c];d&&(u.hasDefaultAudio=u.hasDefaultAudio||e.hasDefaultAudio?d.hasDefault:d.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(d.channels).forEach(h=>{u.channels[h]=(u.channels[h]||0)+d.channels[h]}))}),s},{})}function ed(i){if(!i)return i;const{lang:e,assocLang:t,characteristics:r,channels:s,audioCodec:n}=i;return{lang:e,assocLang:t,characteristics:r,channels:s,audioCodec:n}}function dt(i,e,t){if("attrs"in i){const r=e.indexOf(i);if(r!==-1)return r}for(let r=0;r<e.length;r++){const s=e[r];if(ar(i,s,t))return r}return-1}function ar(i,e,t){const{groupId:r,name:s,lang:n,assocLang:a,default:o}=i,u=i.forced;return(r===void 0||e.groupId===r)&&(s===void 0||e.name===s)&&(n===void 0||zv(n,e.lang))&&(n===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(u===void 0||e.forced===u)&&(!("characteristics"in i)||Yv(i.characteristics||"",e.characteristics))&&(t===void 0||t(i,e))}function zv(i,e="--"){return i.length===e.length?i===e:i.startsWith(e)||e.startsWith(i)}function Yv(i,e=""){const t=i.split(","),r=e.split(",");return t.length===r.length&&!t.some(s=>r.indexOf(s)===-1)}function nr(i,e){const{audioCodec:t,channels:r}=i;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(r===void 0||r===(e.channels||"2"))}function Xv(i,e,t,r,s){const n=e[r],o=e.reduce((h,f,g)=>{const p=f.uri;return(h[p]||(h[p]=[])).push(g),h},{})[n.uri];o.length>1&&(r=Math.max.apply(Math,o));const u=n.videoRange,l=n.frameRate,c=n.codecSet.substring(0,4),d=td(e,r,h=>{if(h.videoRange!==u||h.frameRate!==l||h.codecSet.substring(0,4)!==c)return!1;const f=h.audioGroups,g=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return dt(i,g,s)>-1});return d>-1?d:td(e,r,h=>{const f=h.audioGroups,g=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return dt(i,g,s)>-1})}function td(i,e,t){for(let r=e;r>-1;r--)if(t(i[r]))return r;for(let r=e+1;r<i.length;r++)if(t(i[r]))return r;return-1}function Zs(i,e){var t;return!!i&&i!==((t=e.loadLevelObj)==null?void 0:t.uri)}class Qv extends et{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var r;const{fragCurrent:s,partCurrent:n,hls:a}=this,{autoLevelEnabled:o,media:u}=a;if(!s||!u)return;const l=performance.now(),c=n?n.stats:s.stats,d=n?n.duration:s.duration,h=l-c.loading.start,f=a.minAutoLevel,g=s.level,p=this._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const m=p>-1&&p!==g,v=!!t||m;if(!v&&(u.paused||!u.playbackRate||!u.readyState))return;const y=a.mainForwardBufferInfo;if(!v&&y===null)return;const S=this.bwEstimator.getEstimateTTFB(),_=Math.abs(u.playbackRate);if(h<=Math.max(S,1e3*(d/(_*2))))return;const T=y?y.len/_:0,x=c.loading.first?c.loading.first-c.loading.start:-1,b=c.loaded&&x>-1,I=this.getBwEstimate(),A=a.levels,D=A[g],L=Math.max(c.loaded,Math.round(d*(s.bitrate||D.averageBitrate)/8));let P=b?h-x:h;P<1&&b&&(P=Math.min(h,c.loaded*8/I));const O=b?c.loaded*1e3/P:0,G=S/1e3,j=O?(L-c.loaded)/O:L*8/I+G;if(j<=T)return;const M=O?O*8:I,U=((r=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:r.live)===!0,F=this.hls.config.abrBandWidthUpFactor;let K=Number.POSITIVE_INFINITY,W;for(W=g-1;W>f;W--){const ie=A[W].maxBitrate,Q=!A[W].details||U;if(K=this.getTimeToLoadFrag(G,M,d*ie,Q),K<Math.min(T,d+G))break}if(K>=j||K>d*10)return;b?this.bwEstimator.sample(h-Math.min(S,x),c.loaded):this.bwEstimator.sampleTTFB(h);const N=A[W].maxBitrate;this.getBwEstimate()*F>N&&this.resetEstimator(N);const B=this.findBestLevel(N,f,W,0,T,1,1);B>-1&&(W=B),this.warn(`Fragment ${s.sn}${n?" part "+n.index:""} of level ${g} is loading too slowly;
104104+ Fragment duration: ${s.duration.toFixed(3)}
105105+ Time to underbuffer: ${T.toFixed(3)} s
106106+ Estimated load time for current fragment: ${j.toFixed(3)} s
107107+ Estimated load time for down switch fragment: ${K.toFixed(3)} s
108108+ TTFB estimate: ${x|0} ms
109109+ Current BW estimate: ${$(I)?I|0:"Unknown"} bps
96110 New BW estimate: ${this.getBwEstimate()|0} bps
9797- Switching to level ${W} @ ${O|0} bps`),a.nextLoadLevel=a.nextAutoLevel=W,this.clearTimer();const j=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===W&&W>0){const te=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${W>0?"and switching down":""}
9898- Fragment duration: ${i.duration.toFixed(3)} s
9999- Time to underbuffer: ${te.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,W>f){let X=this.findBestLevel(this.hls.levels[f].bitrate,f,W,0,te,1,1);X===-1&&(X=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=X,this.resetEstimator(this.hls.levels[X].bitrate)}}};y||$>V*2?j():this.timer=self.setInterval(j,V*1e3),a.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:h})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new $l(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(m.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case R.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){const a=performance.now(),o=r?r.stats:s.stats,c=a-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(u,l),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,s,i){const r=e+s/t,a=i?e+this.lastLevelLoadSec:0;return r+a}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;M(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===U.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=s?s.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+i.loaded,c=(a.loaded?a.loaded.duration:0)+r;a.loaded={bytes:o,duration:c},a.realBitrate=Math.round(8*o/c)}if(t.bitrateTest){const r={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(m.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;const a=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==U.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;const a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,r)&&a[e].loadError<=a[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:a}=s,o=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,u=r.abrBandWidthUpFactor;if(l){const y=this.findBestLevel(c,a,i,l,0,h,u);if(y>=0)return this.rebufferNotice=-1,y}let d=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const y=this.bitrateTestDelay;y&&(d=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-y,this.info(`bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=u=1)}const f=this.findBestLevel(c,a,i,l,d,h,u);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const g=s.levels[a],p=s.loadLevelObj;return p&&(g==null?void 0:g.bitrate)<p.bitrate?a:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,a,o){var c;const l=i+r,h=this.lastLoadedFragLevel,u=h===-1?this.hls.firstLevel:h,{fragCurrent:d,partCurrent:f}=this,{levels:g,allAudioTracks:p,loadLevel:y,config:E}=this.hls;if(g.length===1)return 0;const T=g[u],S=!!((c=this.hls.latestLevelDetails)!=null&&c.live),v=y===-1||h===-1;let x,D="SDR",A=(T==null?void 0:T.frameRate)||0;const{audioPreference:b,videoPreference:I}=E,_=this.audioTracksByGroup||(this.audioTracksByGroup=Fa(p));let C=-1;if(v){if(this.firstSelection!==-1)return this.firstSelection;const w=this.codecTiers||(this.codecTiers=Pc(g,_,t,s)),G=Cc(w,D,e,b,I),{codecSet:N,videoRanges:V,minFramerate:W,minBitrate:O,minIndex:F,preferHDR:j}=G;C=F,x=N,D=j?V[V.length-1]:V[0],A=W,e=Math.max(e,O),this.log(`picked start tier ${oe(G)}`)}else x=T==null?void 0:T.codecSet,D=T==null?void 0:T.videoRange;const k=f?f.duration:d?d.duration:0,B=this.bwEstimator.getEstimateTTFB()/1e3,K=[];for(let w=s;w>=t;w--){var $;const G=g[w],N=w>u;if(!G)continue;if(E.useMediaCapabilities&&!G.supportedResult&&!G.supportedPromise){const X=navigator.mediaCapabilities;typeof(X==null?void 0:X.decodingInfo)=="function"&&Sc(G,_,D,A,e,b)?(G.supportedPromise=wa(G,_,X,this.supportedCache),G.supportedPromise.then(J=>{if(!this.hls)return;G.supportedResult=J;const ve=this.hls.levels,ye=ve.indexOf(G);J.error?this.warn(`MediaCapabilities decodingInfo error: "${J.error}" for level ${ye} ${oe(J)}`):J.supported?J.decodingInfoResults.some(Pe=>Pe.smooth===!1||Pe.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ye} not smooth or powerEfficient: ${oe(J)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ye} ${oe(J)}`),ye>-1&&ve.length>1&&(this.log(`Removing unsupported level ${ye}`),this.hls.removeLevel(ye),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(J=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${J}`)})):G.supportedResult=Pa}if((x&&G.codecSet!==x||D&&G.videoRange!==D||N&&A>G.frameRate||!N&&A>0&&A<G.frameRate||($=G.supportedResult)!=null&&($=$.decodingInfoResults)!=null&&$.some(X=>X.smooth===!1))&&(!v||w!==C)){K.push(w);continue}const V=G.details,W=(f?V==null?void 0:V.partTarget:V==null?void 0:V.averagetargetduration)||k;let O;N?O=o*e:O=a*e;const F=k&&i>=k*2&&r===0?G.averageBitrate:G.maxBitrate,j=this.getTimeToLoadFrag(B,O,F*W,V===void 0);if(O>=F&&(w===h||G.loadError===0&&G.fragmentError===0)&&(j<=B||!M(j)||S&&!this.bitrateTestDelay||j<l)){const X=this.forcedAutoLevel;return w!==y&&(X===-1||X!==y)&&(K.length&&this.trace(`Skipped level(s) ${K.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[K[0]].codecs}" ${g[K[0]].videoRange}; not compatible with "${x}" ${D}`),this.info(`switch candidate:${u}->${w} adjustedbw(${Math.round(O)})-bitrate=${Math.round(O-F)} ttfb:${B.toFixed(1)} avgDuration:${W.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${j.toFixed(1)} firstSelection:${v} codecSet:${G.codecSet} videoRange:${G.videoRange} hls.loadLevel:${y}`)),v&&(this.firstSelection=w),w}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const Ma={search:function(n,e){let t=0,s=n.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=n[i];const a=e(r);if(a>0)t=i+1;else if(a<0)s=i-1;else return r}return null}};function Mc(n,e,t){if(e===null||!Array.isArray(n)||!n.length||!M(e))return null;const s=n[0].programDateTime;if(e<(s||0))return null;const i=n[n.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let r=0;r<n.length;++r){const a=n[r];if(Bc(e,t,a))return a}return null}function mt(n,e,t=0,s=0,i=.005){let r=null;if(n){r=e[1+n.sn-e[0].sn]||null;const o=n.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),r&&n.level!==r.level&&r.end<=n.end&&(r=e[2+n.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!n||n.level===r.level)&&jr(t,s,r)===0||Nc(r,n,Math.min(i,s))))return r;const a=Ma.search(e,jr.bind(null,t,s));return a&&(a!==n||!r)?a:r}function Nc(n,e,t){if(e&&e.start===0&&e.level<n.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((i,r)=>(r[0]==="INF"&&(i+=parseFloat(r[1])),i),t);return n.start<=s}return!1}function jr(n=0,e=0,t){if(t.start<=n&&t.start+t.duration>n)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=n?1:t.start-s>n&&t.start?-1:0}function Bc(n,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>n}function Na(n,e,t){if(n&&n.startCC<=e&&n.endCC>=e){let s=n.fragments;const{fragmentHint:i}=n;i&&(s=s.concat(i));let r;return Ma.search(s,a=>a.cc<e?1:a.cc>e?-1:(r=a,a.end<=t?1:a.start>t?-1:0)),r||null}return null}function ks(n){switch(n.details){case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_TIMEOUT:case R.LEVEL_LOAD_TIMEOUT:case R.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Ba(n){return n.details.startsWith("key")}function Ua(n){return Ba(n)&&!!n.frag&&!n.frag.decryptdata}function Xr(n,e){const t=ks(e);return n.default[`${t?"timeout":"error"}Retry`]}function Qi(n,e){const t=n.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*n.retryDelayMs,n.maxRetryDelayMs)}function zr(n){return se(se({},n),{errorRetry:null,timeoutRetry:null})}function ws(n,e,t,s){if(!n)return!1;const i=s==null?void 0:s.code,r=e<n.maxNumRetry&&(Uc(i)||!!t);return n.shouldRetry?n.shouldRetry(n,e,t,s,r):r}function Uc(n){return Ri(n)||!!n&&(n<400||n>499)}function Ri(n){return n===0&&navigator.onLine===!1}var Ee={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Re={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class $c extends Fe{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(m.ERROR,this.onError,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(m.ERROR,this.onError,this),e.off(m.ERROR,this.onErrorOut,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===U.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(a=>i.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case R.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=_t();return}case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Ee.SendAlternateToPenaltyBox;return}case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:{var a;const c=t.parent===U.MAIN?t.level:i.loadLevel;t.details===R.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:typeof(r==null?void 0:r.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_LOAD_ERROR:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const c=i.loadLevelObj;if(c&&(r.type===Q.AUDIO_TRACK&&c.hasAudioGroup(r.groupId)||r.type===Q.SUBTITLE_TRACK&&c.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=Ee.SendAlternateToPenaltyBox,t.errorAction.flags=Re.MoveAllAlternatesMatchingHost;return}}return;case R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Ee.SendAlternateToPenaltyBox,flags:Re.MoveAllAlternatesMatchingHDCP};return;case R.KEY_SYSTEM_SESSION_UPDATE_FAILED:case R.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case R.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Ee.SendAlternateToPenaltyBox,flags:Re.MoveAllAlternatesMatchingKey};return;case R.BUFFER_ADD_CODEC_ERROR:case R.REMUX_ALLOC_ERROR:case R.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:i.loadLevel)}return;case R.INTERNAL_EXCEPTION:case R.BUFFER_APPENDING_ERROR:case R.BUFFER_FULL_ERROR:case R.LEVEL_SWITCH_ERROR:case R.BUFFER_STALLED_ERROR:case R.BUFFER_SEEK_OVER_HOLE:case R.BUFFER_NUDGE_ON_STALL:t.errorAction=_t();return}t.type===H.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=_t())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=Xr(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(ws(i,r,ks(e),e.response))return{action:Ee.RetryRequest,flags:Re.None,retryConfig:i,retryCount:r};const o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:a}=t.config,o=Xr(Ba(e)?a:r,e),c=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(i&&(e.details!==R.FRAG_GAP&&i.fragmentError++,!Ua(e)&&ws(o,c,ks(e),e.response)))return{action:Ee.RetryRequest,flags:Re.None,retryConfig:o,retryCount:c};const l=this.getLevelSwitchAction(e,s);return o&&(l.retryConfig=o,l.retryCount=c),l}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,a;const l=e.details;i.loadError++,l===R.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1;const{levels:u,loadLevel:d,minAutoLevel:f,maxAutoLevel:g}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const p=(r=e.frag)==null?void 0:r.type,E=(p===U.AUDIO&&l===R.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===R.BUFFER_ADD_CODEC_ERROR||l===R.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:D})=>i.audioCodec!==D),S=e.sourceBufferName==="video"&&(l===R.BUFFER_ADD_CODEC_ERROR||l===R.BUFFER_APPEND_ERROR)&&u.some(({codecSet:D,audioCodec:A})=>i.codecSet!==D&&i.audioCodec===A),{type:v,groupId:x}=(a=e.context)!=null?a:{};for(let D=u.length;D--;){const A=(D+d)%u.length;if(A!==d&&A>=f&&A<=g&&u[A].loadError===0){var o,c;const b=u[A];if(l===R.FRAG_GAP&&p===U.MAIN&&e.frag){const I=u[A].details;if(I){const _=mt(e.frag,I.fragments,e.frag.start);if(_!=null&&_.gap)continue}}else{if(v===Q.AUDIO_TRACK&&b.hasAudioGroup(x)||v===Q.SUBTITLE_TRACK&&b.hasSubtitleGroup(x))continue;if(p===U.AUDIO&&(o=i.audioGroups)!=null&&o.some(I=>b.hasAudioGroup(I))||p===U.SUBTITLE&&(c=i.subtitleGroups)!=null&&c.some(I=>b.hasSubtitleGroup(I))||E&&i.audioCodec===b.audioCodec||S&&i.codecSet===b.codecSet||!E&&i.codecSet!==b.codecSet)continue}h=A;break}}if(h>-1&&s.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:Ee.SendAlternateToPenaltyBox,flags:Re.None,nextAutoLevel:h}}return{action:Ee.SendAlternateToPenaltyBox,flags:Re.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case Ee.DoNothing:break;case Ee.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==R.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:i}=s,r=s.nextAutoLevel;switch(i){case Re.None:this.switchLevel(e,r);break;case Re.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(e.frag),l=t.levels[c],h=l==null?void 0:l.attrs["HDCP-LEVEL"];if(s.hdcpLevel=h,h==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(h){t.maxHdcpLevel=Li[Li.indexOf(h)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Re.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const l=this.hls.levels,h=l.length;for(let d=h;d--;)if(this.variantHasKey(l[d],c)){var a,o;this.log(`Banned key found in level ${d} (${l[d].bitrate}bps) or audio group "${(a=l[d].audioGroups)==null?void 0:a.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${Te(c.keyId||[])}`),l[d].fragmentError++,l[d].loadError++,this.log(`Removing level ${d} with key error (${e.error})`),this.hls.removeLevel(d)}const u=e.frag;if(this.hls.levels.length<h)s.resolved=!0;else if(u&&u.type!==U.MAIN){const d=u.decryptdata;d&&!c.matches(d)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===R.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=Ii(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${r} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(r))}}}function _t(n){const e={action:Ee.DoNothing,flags:Re.None};return n&&(e.resolved=!0),e}var me={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Gc{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const r=s[i];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let a=r.length;a--;){const o=i[r[a]];if((o==null?void 0:o.body.type)===t&&(!s||o.buffered)){const c=o.body;if(c.start<=e&&e<=c.end)return c}}return null}detectEvictedFragments(e,t,s,i,r){this.timeRanges&&(this.timeRanges[e]=t);const a=(i==null?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const c=this.fragments[o];if(!c||a>=c.body.sn)return;if(!c.buffered&&(!c.loaded||r)){c.body.type===s&&this.removeFragment(c.body);return}const l=c.range[e];if(l){if(l.time.length===0){this.removeFragment(c.body);return}l.time.some(h=>{const u=!this.isTimeBuffered(h.startPTS,h.endPTS,t);return u&&this.removeFragment(c.body),u})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,i=Et(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const a=!s.relurl;Object.keys(t).forEach(o=>{const c=s.elementaryStreams[o];if(!c)return;const l=t[o],h=a||c.partial===!0;r.range[o]=this.getBufferedTimes(s,e.part,h,l)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,s),Jt(r)||this.removeParts(s.sn-1,s.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Qr(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=Et(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},a=e.start,o=e.end,c=e.minEndPTS||o,l=e.maxStartPTS||a;for(let h=0;h<i.length;h++){const u=i.start(h)-this.bufferPadding,d=i.end(h)+this.bufferPadding;if(l>=u&&c<=d){r.time.push({startPTS:Math.max(a,i.start(h)),endPTS:Math.min(o,i.end(h))});break}else if(a<d&&o>u){const f=Math.max(a,i.start(h)),g=Math.min(o,i.end(h));g>f&&(r.partial=!0,r.time.push({startPTS:f,endPTS:g}))}else if(o<=u)break}return r}getPartialFragment(e){let t=null,s,i,r,a=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(l=>{const h=c[l];h&&Jt(h)&&(i=h.body.start-o,r=h.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),a<=s&&(t=h.body,a=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Jt(t))}getState(e){const t=Et(e),s=this.fragments[t];return s?s.buffered?Jt(s)?me.PARTIAL:me.OK:me.APPENDING:me.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let a=0;a<s.length;a++){if(i=s.start(a)-this.bufferPadding,r=s.end(a)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=Et(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r,type:a}=t;if(s.sn==="initSegment")return;const o=s.type;if(i){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(i)}this.timeRanges=r;const c=r[a];this.detectEvictedFragments(a,c,o,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Et(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if((r==null?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const c=o.body;c.type!==s||i&&!c.gap||c.start<t&&c.end>e&&(o.buffered||r)&&this.removeFragment(c)})}removeFragment(e){const t=Et(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=Qr(s,r=>r.fragment.sn!==i)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(s=>s.clearElementaryStreamInfo())}}function Jt(n){var e,t,s;return n.buffered&&!!(n.body.gap||(e=n.range.video)!=null&&e.partial||(t=n.range.audio)!=null&&t.partial||(s=n.range.audiovideo)!=null&&s.partial)}function Et(n){return`${n.type}_${n.level}_${n.sn}`}function Qr(n,e){return n.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var ot={cbc:0,ctr:1};class Kc{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case ot.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case ot.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function Vc(n){const e=n.byteLength,t=e&&new DataView(n.buffer).getUint8(e-1);return t?n.slice(0,e-t):n}class Hc{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],a=s[2],o=s[3],c=this.invSubMix,l=c[0],h=c[1],u=c[2],d=c[3],f=new Uint32Array(256);let g=0,p=0,y=0;for(y=0;y<256;y++)y<128?f[y]=y<<1:f[y]=y<<1^283;for(y=0;y<256;y++){let E=p^p<<1^p<<2^p<<3^p<<4;E=E>>>8^E&255^99,e[g]=E,t[E]=g;const T=f[g],S=f[T],v=f[S];let x=f[E]*257^E*16843008;i[g]=x<<24|x>>>8,r[g]=x<<16|x>>>16,a[g]=x<<8|x>>>24,o[g]=x,x=v*16843009^S*65537^T*257^g*16843008,l[E]=x<<24|x>>>8,h[E]=x<<16|x>>>16,u[E]=x<<8|x>>>24,d[E]=x,g?(g=T^f[f[f[v^T]]],p^=f[f[p]]):g=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const a=this.ksRows=(r+6+1)*4;let o,c;const l=this.keySchedule=new Uint32Array(a),h=this.invKeySchedule=new Uint32Array(a),u=this.sBox,d=this.rcon,f=this.invSubMix,g=f[0],p=f[1],y=f[2],E=f[3];let T,S;for(o=0;o<a;o++){if(o<r){T=l[o]=t[o];continue}S=T,o%r===0?(S=S<<8|S>>>24,S=u[S>>>24]<<24|u[S>>>16&255]<<16|u[S>>>8&255]<<8|u[S&255],S^=d[o/r|0]<<24):r>6&&o%r===4&&(S=u[S>>>24]<<24|u[S>>>16&255]<<16|u[S>>>8&255]<<8|u[S&255]),l[o]=T=(l[o-r]^S)>>>0}for(c=0;c<a;c++)o=a-c,c&3?S=l[o]:S=l[o-4],c<4||o<=4?h[c]=S:h[c]=g[u[S>>>24]]^p[u[S>>>16&255]]^y[u[S>>>8&255]]^E[u[S&255]],h[c]=h[c]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,c=o[0],l=o[1],h=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(s);let f=d[0],g=d[1],p=d[2],y=d[3];const E=new Int32Array(e),T=new Int32Array(E.length);let S,v,x,D,A,b,I,_,C,k,B,K,$,w;const G=this.networkToHostOrderSwap;for(;t<E.length;){for(C=G(E[t]),k=G(E[t+1]),B=G(E[t+2]),K=G(E[t+3]),A=C^r[0],b=K^r[1],I=B^r[2],_=k^r[3],$=4,w=1;w<i;w++)S=c[A>>>24]^l[b>>16&255]^h[I>>8&255]^u[_&255]^r[$],v=c[b>>>24]^l[I>>16&255]^h[_>>8&255]^u[A&255]^r[$+1],x=c[I>>>24]^l[_>>16&255]^h[A>>8&255]^u[b&255]^r[$+2],D=c[_>>>24]^l[A>>16&255]^h[b>>8&255]^u[I&255]^r[$+3],A=S,b=v,I=x,_=D,$=$+4;S=a[A>>>24]<<24^a[b>>16&255]<<16^a[I>>8&255]<<8^a[_&255]^r[$],v=a[b>>>24]<<24^a[I>>16&255]<<16^a[_>>8&255]<<8^a[A&255]^r[$+1],x=a[I>>>24]<<24^a[_>>16&255]<<16^a[A>>8&255]<<8^a[b&255]^r[$+2],D=a[_>>>24]<<24^a[A>>16&255]<<16^a[b>>8&255]<<8^a[I&255]^r[$+3],T[t]=G(S^f),T[t+1]=G(D^g),T[t+2]=G(x^p),T[t+3]=G(v^y),f=C,g=k,p=B,y=K,t=t+4}return T.buffer}}class Wc{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=Yc(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function Yc(n){switch(n){case ot.cbc:return"AES-CBC";case ot.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${n}`)}}const qc=16;class Zi{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Vc(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise((r,a)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,i);const c=this.flush();c?r(c.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:a,remainderData:o}=this;if(i!==ot.cbc||t.byteLength!==16)return ie.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Oe(o,e),this.remainderData=null);const c=this.getValidChunk(e);if(!c.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Hc),l.expandKey(t);const h=a;return this.currentResult=l.decrypt(c.buffer,0,s),this.currentIV=c.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Wc(this.subtle,t,i)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Kc(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(ie.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%qc;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(ie.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Zr=Math.pow(2,17);class jc{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new ze({type:H.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,a=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(g=>g[0]==="GAP")){c(en(e));return}else e.gap=!1;const l=this.loader=r?new r(i):new a(i),h=Jr(e);e.loader=l;const u=zr(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Zr};e.stats=l.stats;const f={onSuccess:(g,p,y,E)=>{this.resetLoader(e,l);let T=g.data;y.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),o({frag:e,part:null,payload:T,networkDetails:E})},onError:(g,p,y,E)=>{this.resetLoader(e,l),c(new ze({type:H.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:se({url:s,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:y,stats:E}))},onAbort:(g,p,y)=>{this.resetLoader(e,l),c(new ze({type:H.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:y,stats:g}))},onTimeout:(g,p,y)=>{this.resetLoader(e,l),c(new ze({type:H.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:y,stats:g}))}};t&&(f.onProgress=(g,p,y,E)=>t({frag:e,part:null,payload:y,networkDetails:E})),l.load(h,d,f)})}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,a=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(en(e,t));return}const l=this.loader=r?new r(i):new a(i),h=Jr(e,t);e.loader=l;const u=zr(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Zr};t.stats=l.stats,l.load(h,d,{onSuccess:(f,g,p,y)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const E={frag:e,part:t,payload:f.data,networkDetails:y};s(E),o(E)},onError:(f,g,p,y)=>{this.resetLoader(e,l),c(new ze({type:H.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:se({url:h.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:y}))},onAbort:(f,g,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new ze({type:H.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,l),c(new ze({type:H.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const c=Math.round(e.duration/t.duration),l=Math.min(Math.round(s.loaded/r),c),u=(c-l)*Math.round(s.loaded/l);s.total=s.loaded+u}else s.total=Math.max(s.loaded,s.total);const a=s.loading,o=i.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Jr(n,e=null){const t=e||n,s={frag:n,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},i=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(M(i)&&M(r)){var a;let o=i,c=r;if(n.sn==="initSegment"&&Xc((a=n.decryptdata)==null?void 0:a.method)){const l=r-i;l%16&&(c=r+(16-l%16)),i!==0&&(s.resetIV=!0,o=i-16)}s.rangeStart=o,s.rangeEnd=c}return s}function en(n,e){const t=new Error(`GAP ${n.gap?"tag":"attribute"} found`),s={type:H.MEDIA_ERROR,details:R.FRAG_GAP,fatal:!1,frag:n,error:t,networkDetails:null};return e&&(s.part=e),(e||n).stats.aborted=!0,new ze(s)}function Xc(n){return n==="AES-128"||n==="AES-256"}class ze extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class $a extends Fe{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Ji{constructor(e,t,s,i=0,r=-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=es(),this.buffering={audio:es(),video:es(),audiovideo:es()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=a}}function es(){return{start:0,executeStart:0,executeEnd:0,end:0}}const tn={length:0,start:()=>0,end:()=>0};class q{static isBuffered(e,t){if(e){const s=q.getBuffered(e);for(let i=s.length;i--;)if(t>=s.start(i)&&t<=s.end(i))return!0}return!1}static bufferedRanges(e){if(e){const t=q.getBuffered(e);return q.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const i=q.bufferedRanges(e);if(i.length)return q.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((h,u)=>h.start-u.start||u.end-h.end);let i=-1,r=[];if(s)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(i=h);const u=r.length;if(u){const d=r[u-1].end;e[h].start-d<s?e[h].end>d&&(r[u-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let a=0,o,c=t,l=t;for(let h=0;h<r.length;h++){const u=r[h].start,d=r[h].end;if(i===-1&&t>=u&&t<=d&&(i=h),t+s>=u&&t<d)c=u,l=d,a=l-t;else if(t+s<u){o=u;break}}return{len:a,start:c||0,end:l||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||tn}catch(t){return ie.log("failed to get media.buffered",t),tn}}}const Ga=/\{\$([a-zA-Z0-9-_]+)\}/g;function sn(n){return Ga.test(n)}function bi(n,e){if(n.variableList!==null||n.hasVariableRefs){const t=n.variableList;return e.replace(Ga,s=>{const i=s.substring(2,s.length-1),r=t==null?void 0:t[i];return r===void 0?(n.playlistParsingError||(n.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return e}function rn(n,e,t){let s=n.variableList;s||(n.variableList=s={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(i))r=a.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(a){n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=e.NAME,r=e.VALUE;i in s?n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function zc(n,e,t){const s=e.IMPORT;if(t&&s in t){let i=n.variableList;i||(n.variableList=i={}),i[s]=t[s]}else n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const Qc=/^(\d+)x(\d+)$/,nn=/(.+?)=(".*?"|.*?)(?:,|$)/g;class le{constructor(e,t){typeof e=="string"&&(e=le.parseAttrList(e,t)),re(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((i,r)=>(i[r.toLowerCase()]=!0,i),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=Qc.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={},r='"';for(nn.lastIndex=0;(s=nn.exec(e))!==null;){const a=s[1].trim();let o=s[2];const c=o.indexOf(r)===0&&o.lastIndexOf(r)===o.length-1;let l=!1;if(c)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(c||l))o=bi(t,o);else if(!l&&!c)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":ie.warn(`${e}: attribute ${a} is missing quotes`)}i[a]=o}return i}}const Zc="com.apple.hls.interstitial";function Jc(n){return n!=="ID"&&n!=="CLASS"&&n!=="CUE"&&n!=="START-DATE"&&n!=="DURATION"&&n!=="END-DATE"&&n!=="END-ON-NEXT"}function eh(n){return n==="SCTE35-OUT"||n==="SCTE35-IN"||n==="SCTE35-CMD"}class Ka{constructor(e,t,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(i=t==null?void 0:t.tagOrder)!=null?i:s,t){const r=t.attr;for(const a in r)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==r[a]){ie.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=re(new le({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const r=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);M(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(ie.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(M(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===Zc}get isValid(){return!!this.id&&!this._badValueForSameId&&M(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const th=10;class sh{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?M(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||th}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Os(n,e){return n.length===e.length?!n.some((t,s)=>t!==e[s]):!1}function an(n,e){return!n&&!e?!0:!n||!e?!1:Os(n,e)}function It(n){return n==="AES-128"||n==="AES-256"||n==="AES-256-CTR"}function er(n){switch(n){case"AES-128":case"AES-256":return ot.cbc;case"AES-256-CTR":return ot.ctr;default:throw new Error(`invalid full segment method ${n}`)}}function tr(n){return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}function Di(n){return Uint8Array.from(unescape(encodeURIComponent(n)),e=>e.charCodeAt(0))}function ih(n){const e=Di(n).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Va(n){const e=function(s,i,r){const a=s[i];s[i]=s[r],s[r]=a};e(n,0,3),e(n,1,2),e(n,4,5),e(n,6,7)}function Ha(n){const e=n.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){const r=i[0]==="base64",a=i[1];r?(s.splice(-1,1),t=tr(a)):t=ih(a)}}return t}const Fs=typeof self<"u"?self:void 0;var he={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Se={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function ys(n){switch(n){case Se.FAIRPLAY:return he.FAIRPLAY;case Se.PLAYREADY:return he.PLAYREADY;case Se.WIDEVINE:return he.WIDEVINE;case Se.CLEARKEY:return he.CLEARKEY}}function Qs(n){switch(n){case he.FAIRPLAY:return Se.FAIRPLAY;case he.PLAYREADY:return Se.PLAYREADY;case he.WIDEVINE:return Se.WIDEVINE;case he.CLEARKEY:return Se.CLEARKEY}}function Ft(n){const{drmSystems:e,widevineLicenseUrl:t}=n,s=e?[he.FAIRPLAY,he.WIDEVINE,he.PLAYREADY,he.CLEARKEY].filter(i=>!!e[i]):[];return!s[he.WIDEVINE]&&t&&s.push(he.WIDEVINE),s}const Wa=function(n){return Fs!=null&&(n=Fs.navigator)!=null&&n.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function rh(n,e,t,s){let i;switch(n){case he.FAIRPLAY:i=["cenc","sinf"];break;case he.WIDEVINE:case he.PLAYREADY:i=["cenc"];break;case he.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${n}`)}return nh(i,e,t,s)}function nh(n,e,t,s){return[{initDataTypes:n,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function ah(n){var e;return!!n&&(n.sessionType==="persistent-license"||!!((e=n.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Ya(n){const e=new Uint16Array(n.buffer,n.byteOffset,n.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(a){const o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){const c=tr(o).subarray(0,16);return Va(c),c}}return null}let Tt={};class nt{static clearKeyUriToKeyIdMap(){Tt={}}static setKeyIdForUri(e,t){Tt[e]=t}static addKeyIdForUri(e){const t=Object.keys(Tt).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),Tt[e]=s,s}constructor(e,t,s,i=[1],r=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!It(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Sa(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Os(e.keyFormatVersions,this.keyFormatVersions)&&an(e.iv,this.iv)&&an(e.keyId,this.keyId)}isSupported(){if(this.method){if(It(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Se.FAIRPLAY:case Se.WIDEVINE:case Se.PLAYREADY:case Se.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(It(this.method)){let r=this.iv;return r||(typeof e!="number"&&(ie.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=lh(e)),new nt(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=Tt[this.uri];if(r&&!Os(this.keyId,r)&&nt.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=Ha(this.uri);if(s)switch(this.keyFormat){case Se.WIDEVINE:if(this.pssh=s,!this.keyId){const r=uc(s.buffer);if(r.length){var i;const a=r[0];this.keyId=(i=a.kids)!=null&&i.length?a.kids[0]:null}}this.keyId||(this.keyId=on(t));break;case Se.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=hc(r,null,s),this.keyId=Ya(s);break}default:{let r=s.subarray(0,16);if(r.length!==16){const a=new Uint8Array(16);a.set(r,16-r.length),r=a}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=oh(t),r||(r=on(t),r||(r=Tt[this.uri])),r&&(this.keyId=r,nt.setKeyIdForUri(this.uri,r))}return this}}function oh(n){const e=n==null?void 0:n[Se.WIDEVINE];return e?e.keyId:null}function on(n){const e=n==null?void 0:n[Se.PLAYREADY];if(e){const t=Ha(e.uri);if(t)return Ya(t)}return null}function lh(n){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=n>>8*(15-t)&255;return e}const ln=/#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,cn=/#EXT-X-MEDIA:(.*)/g,ch=/^#EXT(?:INF|-X-TARGETDURATION):/m,Zs=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),hh=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class We{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return Yi.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return ch.test(e)}static parseMasterPlaylist(e,t){const s=sn(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];if(ln.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let a;for(;(a=ln.exec(e))!=null;)if(a[1]){var o;const l=new le(a[1],i),h=bi(i,a[2]),u={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:We.resolve(h,t)},d=l.decimalResolution("RESOLUTION");d&&(u.width=d.width,u.height=d.height),dn(l.CODECS,u);const f=l["SUPPLEMENTAL-CODECS"];f&&(u.supplemental={},dn(f,u.supplemental)),(o=u.unknownCodecs)!=null&&o.length||r.push(u),i.levels.push(u)}else if(a[3]){const l=a[3],h=a[4];switch(l){case"SESSION-DATA":{const u=new le(h,i),d=u["DATA-ID"];d&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[d]=u);break}case"SESSION-KEY":{const u=hn(h,t,i);u.encrypted&&u.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(u)):ie.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":{{const u=new le(h,i);rn(i,u,t)}break}case"CONTENT-STEERING":{const u=new le(h,i);i.contentSteering={uri:We.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=un(h);break}}}const c=r.length>0&&r.length<i.levels.length;return i.levels=c?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i;const r={},a=s.levels,o={AUDIO:a.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:a.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(cn.lastIndex=0;(i=cn.exec(e))!==null;){const l=new le(i[1],s),h=l.TYPE;if(h){const u=o[h],d=r[h]||[];r[h]=d;const f=l.LANGUAGE,g=l["ASSOC-LANGUAGE"],p=l.CHANNELS,y=l.CHARACTERISTICS,E=l["INSTREAM-ID"],T={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||f||"",type:h,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:f,url:l.URI?We.resolve(l.URI,t):""};if(g&&(T.assocLang=g),p&&(T.channels=p),y&&(T.characteristics=y),E&&(T.instreamId=E),u!=null&&u.length){const S=We.findGroup(u,T.groupId)||u[0];fn(T,S,"audioCodec"),fn(T,S,"textCodec")}d.push(T)}}return r}static parseLevelPlaylist(e,t,s,i,r,a){var o;const c={url:t},l=new sh(t),h=l.fragments,u=[];let d=null,f=0,g=0,p=0,y=0,E=0,T=null,S=new js(i,c),v,x,D,A=-1,b=!1,I=null,_;if(Zs.lastIndex=0,l.m3u8=e,l.hasVariableRefs=sn(e),((o=Zs.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(v=Zs.exec(e))!==null;){b&&(b=!1,S=new js(i,c),S.playlistOffset=p,S.setStart(p),S.sn=f,S.cc=y,E&&(S.bitrate=E),S.level=s,d&&(S.initSegment=d,d.rawProgramDateTime&&(S.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),I&&(S.setByteRange(I),I=null)));const K=v[1];if(K){S.duration=parseFloat(K);const $=(" "+v[2]).slice(1);S.title=$||null,S.tagList.push($?["INF",K,$]:["INF",K])}else if(v[3]){if(M(S.duration)){S.playlistOffset=p,S.setStart(p),D&&mn(S,D,l),S.sn=f,S.level=s,S.cc=y,h.push(S);const $=(" "+v[3]).slice(1);S.relurl=bi(l,$),Ci(S,T,u),T=S,p+=S.duration,f++,g=0,b=!0}}else{if(v=v[0].match(hh),!v){ie.warn("No matches on slow regex match for level playlist!");continue}for(x=1;x<v.length&&v[x]===void 0;x++);const $=(" "+v[x]).slice(1),w=(" "+v[x+1]).slice(1),G=v[x+2]?(" "+v[x+2]).slice(1):null;switch($){case"BYTERANGE":T?S.setByteRange(w,T):S.setByteRange(w);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=w,S.tagList.push(["PROGRAM-DATE-TIME",w]),A===-1&&(A=h.length);break;case"PLAYLIST-TYPE":l.type&&je(l,$,v),l.type=w.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?je(l,$,v):h.length>0&&pn(l,$,v),f=l.startSN=parseInt(w);break;case"SKIP":{l.skippedSegments&&je(l,$,v);const N=new le(w,l),V=N.decimalInteger("SKIPPED-SEGMENTS");if(M(V)){l.skippedSegments+=V;for(let O=V;O--;)h.push(null);f+=V}const W=N.enumeratedString("RECENTLY-REMOVED-DATERANGES");W&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(W.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&je(l,$,v),l.targetduration=Math.max(parseInt(w),1);break;case"VERSION":l.version!==null&&je(l,$,v),l.version=parseInt(w);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||je(l,$,v),l.live=!1;break;case"#":(w||G)&&S.tagList.push(G?[w,G]:[w]);break;case"DISCONTINUITY":y++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([$]);break;case"BITRATE":S.tagList.push([$,w]),E=parseInt(w)*1e3,M(E)?S.bitrate=E:E=0;break;case"DATERANGE":{const N=new le(w,l),V=new Ka(N,l.dateRanges[N.ID],l.dateRangeTagCount);l.dateRangeTagCount++,V.isValid||l.skippedSegments?l.dateRanges[V.id]=V:ie.warn(`Ignoring invalid DATERANGE tag: "${w}"`),S.tagList.push(["EXT-X-DATERANGE",w]);break}case"DEFINE":{{const N=new le(w,l);"IMPORT"in N?zc(l,N,a):rn(l,N,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?je(l,$,v):h.length>0&&pn(l,$,v),l.startCC=y=parseInt(w);break;case"KEY":{const N=hn(w,t,l);if(N.isSupported()){if(N.method==="NONE"){D=void 0;break}D||(D={});const V=D[N.keyFormat];V!=null&&V.matches(N)||(V&&(D=re({},D)),D[N.keyFormat]=N)}else ie.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${w}"`);break}case"START":l.startTimeOffset=un(w);break;case"MAP":{const N=new le(w,l);if(S.duration){const V=new js(i,c);gn(V,N,s,D),d=V,S.initSegment=d,d.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=d.rawProgramDateTime)}else{const V=S.byteRangeEndOffset;if(V){const W=S.byteRangeStartOffset;I=`${V-W}@${W}`}else I=null;gn(S,N,s,D),d=S,b=!0}d.cc=y;break}case"SERVER-CONTROL":{_&&je(l,$,v),_=new le(w),l.canBlockReload=_.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=_.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&_.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=_.optionalFloat("PART-HOLD-BACK",0),l.holdBack=_.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&je(l,$,v);const N=new le(w);l.partTarget=N.decimalFloatingPoint("PART-TARGET");break}case"PART":{let N=l.partList;N||(N=l.partList=[]);const V=g>0?N[N.length-1]:void 0,W=g++,O=new le(w,l),F=new zl(O,S,c,W,V);N.push(F),S.duration+=F.duration;break}case"PRELOAD-HINT":{const N=new le(w,l);l.preloadHint=N;break}case"RENDITION-REPORT":{const N=new le(w,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(N);break}default:ie.warn(`line parsed but not handled: ${v}`);break}}}T&&!T.relurl?(h.pop(),p-=T.duration,l.partList&&(l.fragmentHint=T)):l.partList&&(Ci(S,T,u),S.cc=y,l.fragmentHint=S,D&&mn(S,D,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const C=h.length,k=h[0],B=h[C-1];if(p+=l.skippedSegments*l.targetduration,p>0&&C&&B){l.averagetargetduration=p/C;const K=B.sn;l.endSN=K!=="initSegment"?K:0,l.live||(B.endList=!0),A>0&&(dh(h,A),k&&u.unshift(k))}return l.fragmentHint&&(p+=l.fragmentHint.duration),l.totalduration=p,u.length&&l.dateRangeTagCount&&k&&qa(u,l),l.endCC=y,l}}function qa(n,e){let t=n.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];n.push(o),t++}else return;const s=n[t-1],i=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){const c=e.dateRanges[r[o]],l=c.startDate.getTime();c.tagAnchor=s.ref;for(let h=t;h--;){var a;if(((a=n[h])==null?void 0:a.sn)<e.startSN)break;const u=uh(e,l,n,h,i);if(u!==-1){c.tagAnchor=e.fragments[u].ref;break}}}}function uh(n,e,t,s,i){const r=t[s];if(r){const o=r.programDateTime;if(e>=o||s===0){var a;const c=(((a=t[s+1])==null?void 0:a.start)||i)-r.start;if(e<=o+c*1e3){const l=t[s].sn-n.startSN;if(l<0)return-1;const h=n.fragments;if(h.length>t.length){const d=(t[s+1]||h[h.length-1]).sn-n.startSN;for(let f=d;f>l;f--){const g=h[f].programDateTime;if(e>=g&&e<g+h[f].duration*1e3)return f}}return l}}}return-1}function hn(n,e,t){var s,i;const r=new le(n,t),a=(s=r.METHOD)!=null?s:"",o=r.URI,c=r.hexadecimalInteger("IV"),l=r.KEYFORMATVERSIONS,h=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!c&&ie.error(`Invalid IV: ${r.IV}`);const u=o?We.resolve(o,e):"",d=(l||"1").split("/").map(Number).filter(Number.isFinite);return new nt(a,u,h,d,c,r.KEYID)}function un(n){const t=new le(n).decimalFloatingPoint("TIME-OFFSET");return M(t)?t:null}function dn(n,e){let t=(n||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const i=t.filter(r=>Xi(r,s));i.length&&(e[`${s}Codec`]=i.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>i.indexOf(r)===-1))}),e.unknownCodecs=t}function fn(n,e,t){const s=e[t];s&&(n[t]=s)}function dh(n,e){let t=n[e];for(let s=e;s--;){const i=n[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function Ci(n,e,t){n.rawProgramDateTime?t.push(n):e!=null&&e.programDateTime&&(n.programDateTime=e.endProgramDateTime)}function gn(n,e,t,s){n.relurl=e.URI,e.BYTERANGE&&n.setByteRange(e.BYTERANGE),n.level=t,n.sn="initSegment",s&&(n.levelkeys=s),n.initSegment=null}function mn(n,e,t){n.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(n)}function je(n,e,t){n.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function pn(n,e,t){n.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Js(n,e){const t=e.startPTS;if(M(t)){let s=0,i;e.sn>n.sn?(s=t-n.start,i=n):(s=n.start-t,i=e),i.duration!==s&&i.setDuration(s)}else e.sn>n.sn?n.cc===e.cc&&n.minEndPTS?e.setStart(n.start+(n.minEndPTS-n.start)):e.setStart(n.start+n.duration):e.setStart(Math.max(n.start-e.duration,0))}function ja(n,e,t,s,i,r,a){s-t<=0&&(a.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let c=t,l=s;const h=e.startPTS,u=e.endPTS;if(M(h)){const E=Math.abs(h-t);n&&E>n.totalduration?a.warn(`media timestamps and playlist times differ by ${E}s for level ${e.level} ${n.url}`):M(e.deltaPTS)?e.deltaPTS=Math.max(E,e.deltaPTS):e.deltaPTS=E,c=Math.max(t,h),t=Math.min(t,h),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,l=Math.min(s,u),s=Math.max(s,u),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const d=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=i,e.endPTS=s,e.minEndPTS=l,e.endDTS=r;const f=e.sn;if(!n||f<n.startSN||f>n.endSN)return 0;let g;const p=f-n.startSN,y=n.fragments;for(y[p]=e,g=p;g>0;g--)Js(y[g],y[g-1]);for(g=p;g<y.length-1;g++)Js(y[g],y[g+1]);return n.fragmentHint&&Js(y[y.length-1],n.fragmentHint),n.PTSKnown=n.alignedSliding=!0,d}function fh(n,e,t){if(n===e)return;let s=null;const i=n.fragments;for(let h=i.length-1;h>=0;h--){const u=i[h].initSegment;if(u){s=u;break}}n.fragmentHint&&delete n.fragmentHint.endPTS;let r;ph(n,e,(h,u,d,f)=>{if((!e.startCC||e.skippedSegments)&&u.cc!==h.cc){const g=h.cc-u.cc;for(let p=d;p<f.length;p++)f[p].cc+=g;e.endCC=f[f.length-1].cc}M(h.startPTS)&&M(h.endPTS)&&(u.setStart(u.startPTS=h.startPTS),u.startDTS=h.startDTS,u.maxStartPTS=h.maxStartPTS,u.endPTS=h.endPTS,u.endDTS=h.endDTS,u.minEndPTS=h.minEndPTS,u.setDuration(h.endPTS-h.startPTS),u.duration&&(r=u),e.PTSKnown=e.alignedSliding=!0),h.hasStreams&&(u.elementaryStreams=h.elementaryStreams),u.loader=h.loader,h.hasStats&&(u.stats=h.stats),h.initSegment&&(u.initSegment=h.initSegment,s=h.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(s&&o.forEach(h=>{var u;h&&(!h.initSegment||h.initSegment.relurl===((u=s)==null?void 0:u.relurl))&&(h.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(h=>!h),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=e.skippedSegments;h--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=gh(n.dateRanges,e,t));const h=n.fragments.filter(u=>u.rawProgramDateTime);if(n.hasProgramDateTime&&!e.hasProgramDateTime)for(let u=1;u<o.length;u++)o[u].programDateTime===null&&Ci(o[u],o[u-1],h);qa(h,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var c;const h=Qa(n,e.startSN-1);e.startCC=(c=h==null?void 0:h.cc)!=null?c:a[0].cc}mh(n.partList,e.partList,(h,u)=>{u.elementaryStreams=h.elementaryStreams,u.stats=h.stats}),r?ja(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):Xa(n,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=n.driftStartTime,e.driftStart=n.driftStart;const l=e.advancedDateTime;if(e.advanced&&l){const h=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=h),e.driftEndTime=l,e.driftEnd=h}else e.driftEndTime=n.driftEndTime,e.driftEnd=n.driftEnd,e.advancedDateTime=n.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=n.requestScheduled)}function gh(n,e,t){const{dateRanges:s,recentlyRemovedDateranges:i}=e,r=re({},n);i&&i.forEach(c=>{delete r[c]});const o=Object.keys(r).length;return o?(Object.keys(s).forEach(c=>{const l=r[c],h=new Ka(s[c].attr,l);h.isValid?(r[c]=h,l||(h.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${oe(s[c].attr)}"`)}),r):s}function mh(n,e,t){if(n&&e){let s=0;for(let i=0,r=n.length;i<=r;i++){const a=n[i],o=e[i+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):s--}}}function ph(n,e,t){const s=e.skippedSegments,i=Math.max(n.startSN,e.startSN)-e.startSN,r=(n.fragmentHint?1:0)+(s?e.endSN:Math.min(n.endSN,e.endSN))-e.startSN,a=e.startSN-n.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=n.fragmentHint?n.fragments.concat(n.fragmentHint):n.fragments;for(let l=i;l<=r;l++){const h=c[a+l];let u=o[l];if(s&&!u&&h&&(u=e.fragments[l]=h),h&&u){t(h,u,l,o);const d=h.relurl,f=u.relurl;if(d&&yh(d,f)){e.playlistParsingError=yn(`media sequence mismatch ${u.sn}:`,n,e,h,u);return}else if(h.cc!==u.cc){e.playlistParsingError=yn(`discontinuity sequence mismatch (${h.cc}!=${u.cc})`,n,e,h,u);return}}}}function yn(n,e,t,s,i){return new Error(`${n} ${i.url}
111111+ Switching to level ${W} @ ${N|0} bps`),a.nextLoadLevel=a.nextAutoLevel=W,this.clearTimer();const X=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===W&&W>0){const ie=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${W>0?"and switching down":""}
112112+ Fragment duration: ${s.duration.toFixed(3)} s
113113+ Time to underbuffer: ${ie.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,W>f){let Q=this.findBestLevel(this.hls.levels[f].bitrate,f,W,0,ie,1,1);Q===-1&&(Q=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=Q,this.resetEstimator(this.hls.levels[Q].bitrate)}}};m||j>K*2?X():this.timer=self.setInterval(X,K*1e3),a.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:n,stats:c})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new rv(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(E.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const r=t.frag;if(!this.ignoreFragment(r)){if(!r.bitrateTest){var s;this.fragCurrent=r,this.partCurrent=(s=t.part)!=null?s: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 C.BUFFER_ADD_CODEC_ERROR:case C.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case C.FRAG_LOAD_TIMEOUT:{const r=t.frag,{fragCurrent:s,partCurrent:n}=this;if(r&&s&&r.sn===s.sn&&r.level===s.level){const a=performance.now(),o=n?n.stats:r.stats,u=a-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){const d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(u-Math.min(d,l),o.loaded)}else this.bwEstimator.sampleTTFB(u)}break}}}getTimeToLoadFrag(e,t,r,s){const n=e+r/t,a=s?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){const r=this.hls.config,{loading:s}=t.stats,n=s.end-s.first;$(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:r}){const s=r?r.stats:t.stats;if(t.type===V.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const n=r?r.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+s.loaded,u=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:u},a.realBitrate=Math.round(8*o/u)}if(t.bitrateTest){const n={stats:s,frag:t,part:r,id:t.type};this.onFragBuffered(E.FRAG_BUFFERED,n),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:r,part:s}=t,n=s!=null&&s.stats.loaded?s.stats:r.stats;if(n.aborted||this.ignoreFragment(r))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(),r.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==V.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,r=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,n=this.findBestLevel(r,t,e,0,s,1,1);if(n>-1)return n;const a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,r=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(e!==-1&&(!r||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const n=r&&s?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:r}=this;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:s,config:n,minAutoLevel:a}=r,o=t?t.duration:e?e.duration:0,u=this.getBwEstimate(),l=this.getStarvationDelay();let c=n.abrBandWidthFactor,d=n.abrBandWidthUpFactor;if(l){const m=this.findBestLevel(u,a,s,l,0,c,d);if(m>=0)return this.rebufferNotice=-1,m}let h=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){const m=this.bitrateTestDelay;m&&(h=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-m,this.info(`bitrate test took ${Math.round(1e3*m)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),c=d=1)}const f=this.findBestLevel(u,a,s,l,h,c,d);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const g=r.levels[a],p=r.loadLevelObj;return p&&(g==null?void 0:g.bitrate)<p.bitrate?a:r.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const r=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/r}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,r,s,n,a,o){var u;const l=s+n,c=this.lastLoadedFragLevel,d=c===-1?this.hls.firstLevel:c,{fragCurrent:h,partCurrent:f}=this,{levels:g,allAudioTracks:p,loadLevel:m,config:v}=this.hls;if(g.length===1)return 0;const y=g[d],S=!!((u=this.hls.latestLevelDetails)!=null&&u.live),_=m===-1||c===-1;let T,x="SDR",b=(y==null?void 0:y.frameRate)||0;const{audioPreference:I,videoPreference:A}=v,D=this.audioTracksByGroup||(this.audioTracksByGroup=Qf(p));let L=-1;if(_){if(this.firstSelection!==-1)return this.firstSelection;const M=this.codecTiers||(this.codecTiers=Wv(g,D,t,r)),U=Hv(M,x,e,I,A),{codecSet:F,videoRanges:K,minFramerate:W,minBitrate:N,minIndex:B,preferHDR:X}=U;L=B,T=F,x=X?K[K.length-1]:K[0],b=W,e=Math.max(e,N),this.log(`picked start tier ${ue(U)}`)}else T=y==null?void 0:y.codecSet,x=y==null?void 0:y.videoRange;const P=f?f.duration:h?h.duration:0,O=this.bwEstimator.getEstimateTTFB()/1e3,G=[];for(let M=r;M>=t;M--){var j;const U=g[M],F=M>d;if(!U)continue;if(v.useMediaCapabilities&&!U.supportedResult&&!U.supportedPromise){const Q=navigator.mediaCapabilities;typeof(Q==null?void 0:Q.decodingInfo)=="function"&&Fv(U,D,x,b,e,I)?(U.supportedPromise=Yf(U,D,Q,this.supportedCache),U.supportedPromise.then(ee=>{if(!this.hls)return;U.supportedResult=ee;const Re=this.hls.levels,be=Re.indexOf(U);ee.error?this.warn(`MediaCapabilities decodingInfo error: "${ee.error}" for level ${be} ${ue(ee)}`):ee.supported?ee.decodingInfoResults.some(Xe=>Xe.smooth===!1||Xe.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${be} not smooth or powerEfficient: ${ue(ee)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${be} ${ue(ee)}`),be>-1&&Re.length>1&&(this.log(`Removing unsupported level ${be}`),this.hls.removeLevel(be),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(ee=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${ee}`)})):U.supportedResult=Wf}if((T&&U.codecSet!==T||x&&U.videoRange!==x||F&&b>U.frameRate||!F&&b>0&&b<U.frameRate||(j=U.supportedResult)!=null&&(j=j.decodingInfoResults)!=null&&j.some(Q=>Q.smooth===!1))&&(!_||M!==L)){G.push(M);continue}const K=U.details,W=(f?K==null?void 0:K.partTarget:K==null?void 0:K.averagetargetduration)||P;let N;F?N=o*e:N=a*e;const B=P&&s>=P*2&&n===0?U.averageBitrate:U.maxBitrate,X=this.getTimeToLoadFrag(O,N,B*W,K===void 0);if(N>=B&&(M===c||U.loadError===0&&U.fragmentError===0)&&(X<=O||!$(X)||S&&!this.bitrateTestDelay||X<l)){const Q=this.forcedAutoLevel;return M!==m&&(Q===-1||Q!==m)&&(G.length&&this.trace(`Skipped level(s) ${G.join(",")} of ${r} max with CODECS and VIDEO-RANGE:"${g[G[0]].codecs}" ${g[G[0]].videoRange}; not compatible with "${T}" ${x}`),this.info(`switch candidate:${d}->${M} adjustedbw(${Math.round(N)})-bitrate=${Math.round(N-B)} ttfb:${O.toFixed(1)} avgDuration:${W.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${X.toFixed(1)} firstSelection:${_} codecSet:${U.codecSet} videoRange:${U.videoRange} hls.loadLevel:${m}`)),_&&(this.firstSelection=M),M}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:r}=this.hls;return Math.min(Math.max(e,r),t)}}const Zf={search:function(i,e){let t=0,r=i.length-1,s=null,n=null;for(;t<=r;){s=(t+r)/2|0,n=i[s];const a=e(n);if(a>0)t=s+1;else if(a<0)r=s-1;else return n}return null}};function Zv(i,e,t){if(e===null||!Array.isArray(i)||!i.length||!$(e))return null;const r=i[0].programDateTime;if(e<(r||0))return null;const s=i[i.length-1].endProgramDateTime;if(e>=(s||0))return null;for(let n=0;n<i.length;++n){const a=i[n];if(eE(e,t,a))return a}return null}function or(i,e,t=0,r=0,s=.005){let n=null;if(i){n=e[1+i.sn-e[0].sn]||null;const o=i.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&i.level!==n.level&&n.end<=i.end&&(n=e[2+i.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!i||i.level===n.level)&&rd(t,r,n)===0||Jv(n,i,Math.min(s,r))))return n;const a=Zf.search(e,rd.bind(null,t,r));return a&&(a!==i||!n)?a:n}function Jv(i,e,t){if(e&&e.start===0&&e.level<i.level&&(e.endPTS||0)>0){const r=e.tagList.reduce((s,n)=>(n[0]==="INF"&&(s+=parseFloat(n[1])),s),t);return i.start<=r}return!1}function rd(i=0,e=0,t){if(t.start<=i&&t.start+t.duration>i)return 0;const r=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-r<=i?1:t.start-r>i&&t.start?-1:0}function eE(i,e,t){const r=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-r>i}function Jf(i,e,t){if(i&&i.startCC<=e&&i.endCC>=e){let r=i.fragments;const{fragmentHint:s}=i;s&&(r=r.concat(s));let n;return Zf.search(r,a=>a.cc<e?1:a.cc>e?-1:(n=a,a.end<=t?1:a.start>t?-1:0)),n||null}return null}function Js(i){switch(i.details){case C.FRAG_LOAD_TIMEOUT:case C.KEY_LOAD_TIMEOUT:case C.LEVEL_LOAD_TIMEOUT:case C.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function eg(i){return i.details.startsWith("key")}function tg(i){return eg(i)&&!!i.frag&&!i.frag.decryptdata}function id(i,e){const t=Js(e);return i.default[`${t?"timeout":"error"}Retry`]}function bo(i,e){const t=i.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*i.retryDelayMs,i.maxRetryDelayMs)}function sd(i){return se(se({},i),{errorRetry:null,timeoutRetry:null})}function en(i,e,t,r){if(!i)return!1;const s=r==null?void 0:r.code,n=e<i.maxNumRetry&&(tE(s)||!!t);return i.shouldRetry?i.shouldRetry(i,e,t,r,n):n}function tE(i){return Ma(i)||!!i&&(i<400||i>499)}function Ma(i){return i===0&&navigator.onLine===!1}var Ae={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},qe={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class rE extends et{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(E.ERROR,this.onError,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(E.ERROR,this.onError,this),e.off(E.ERROR,this.onErrorOut,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===V.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,r=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||r===-1?t.loadLevel:r}variantHasKey(e,t){if(e){var r;if((r=e.details)!=null&&r.hasKey(t))return!0;const s=e.audioGroups;if(s)return this.hls.allAudioTracks.filter(a=>s.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var r;if(t.fatal)return;const s=this.hls,n=t.context;switch(t.details){case C.FRAG_LOAD_ERROR:case C.FRAG_LOAD_TIMEOUT:case C.KEY_LOAD_ERROR:case C.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case C.FRAG_PARSING_ERROR:if((r=t.frag)!=null&&r.gap){t.errorAction=Wr();return}case C.FRAG_GAP:case C.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Ae.SendAlternateToPenaltyBox;return}case C.LEVEL_EMPTY_ERROR:case C.LEVEL_PARSING_ERROR:{var a;const u=t.parent===V.MAIN?t.level:s.loadLevel;t.details===C.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,u):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,u))}return;case C.LEVEL_LOAD_ERROR:case C.LEVEL_LOAD_TIMEOUT:typeof(n==null?void 0:n.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case C.AUDIO_TRACK_LOAD_ERROR:case C.AUDIO_TRACK_LOAD_TIMEOUT:case C.SUBTITLE_LOAD_ERROR:case C.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const u=s.loadLevelObj;if(u&&(n.type===J.AUDIO_TRACK&&u.hasAudioGroup(n.groupId)||n.type===J.SUBTITLE_TRACK&&u.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=Ae.SendAlternateToPenaltyBox,t.errorAction.flags=qe.MoveAllAlternatesMatchingHost;return}}return;case C.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Ae.SendAlternateToPenaltyBox,flags:qe.MoveAllAlternatesMatchingHDCP};return;case C.KEY_SYSTEM_SESSION_UPDATE_FAILED:case C.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case C.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Ae.SendAlternateToPenaltyBox,flags:qe.MoveAllAlternatesMatchingKey};return;case C.BUFFER_ADD_CODEC_ERROR:case C.REMUX_ALLOC_ERROR:case C.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:s.loadLevel)}return;case C.INTERNAL_EXCEPTION:case C.BUFFER_APPENDING_ERROR:case C.BUFFER_FULL_ERROR:case C.LEVEL_SWITCH_ERROR:case C.BUFFER_STALLED_ERROR:case C.BUFFER_SEEK_OVER_HOLE:case C.BUFFER_NUDGE_ON_STALL:t.errorAction=Wr();return}t.type===q.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Wr())}getPlaylistRetryOrSwitchAction(e,t){const r=this.hls,s=id(r.config.playlistLoadPolicy,e),n=this.playlistError++;if(en(s,n,Js(e),e.response))return{action:Ae.RetryRequest,flags:qe.None,retryConfig:s,retryCount:n};const o=this.getLevelSwitchAction(e,t);return s&&(o.retryConfig=s,o.retryCount=n),o}getFragRetryOrSwitchAction(e){const t=this.hls,r=this.getVariantLevelIndex(e.frag),s=t.levels[r],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=id(eg(e)?a:n,e),u=t.levels.reduce((c,d)=>c+d.fragmentError,0);if(s&&(e.details!==C.FRAG_GAP&&s.fragmentError++,!tg(e)&&en(o,u,Js(e),e.response)))return{action:Ae.RetryRequest,flags:qe.None,retryConfig:o,retryCount:u};const l=this.getLevelSwitchAction(e,r);return o&&(l.retryConfig=o,l.retryCount=u),l}getLevelSwitchAction(e,t){const r=this.hls;t==null&&(t=r.loadLevel);const s=this.hls.levels[t];if(s){var n,a;const l=e.details;s.loadError++,l===C.BUFFER_APPEND_ERROR&&s.fragmentError++;let c=-1;const{levels:d,loadLevel:h,minAutoLevel:f,maxAutoLevel:g}=r;!r.autoLevelEnabled&&!r.config.preserveManualLevelOnError&&(r.loadLevel=-1);const p=(n=e.frag)==null?void 0:n.type,v=(p===V.AUDIO&&l===C.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===C.BUFFER_ADD_CODEC_ERROR||l===C.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:x})=>s.audioCodec!==x),S=e.sourceBufferName==="video"&&(l===C.BUFFER_ADD_CODEC_ERROR||l===C.BUFFER_APPEND_ERROR)&&d.some(({codecSet:x,audioCodec:b})=>s.codecSet!==x&&s.audioCodec===b),{type:_,groupId:T}=(a=e.context)!=null?a:{};for(let x=d.length;x--;){const b=(x+h)%d.length;if(b!==h&&b>=f&&b<=g&&d[b].loadError===0){var o,u;const I=d[b];if(l===C.FRAG_GAP&&p===V.MAIN&&e.frag){const A=d[b].details;if(A){const D=or(e.frag,A.fragments,e.frag.start);if(D!=null&&D.gap)continue}}else{if(_===J.AUDIO_TRACK&&I.hasAudioGroup(T)||_===J.SUBTITLE_TRACK&&I.hasSubtitleGroup(T))continue;if(p===V.AUDIO&&(o=s.audioGroups)!=null&&o.some(A=>I.hasAudioGroup(A))||p===V.SUBTITLE&&(u=s.subtitleGroups)!=null&&u.some(A=>I.hasSubtitleGroup(A))||v&&s.audioCodec===I.audioCodec||S&&s.codecSet===I.codecSet||!v&&s.codecSet!==I.codecSet)continue}c=b;break}}if(c>-1&&r.loadLevel!==c)return e.levelRetry=!0,this.playlistError=0,{action:Ae.SendAlternateToPenaltyBox,flags:qe.None,nextAutoLevel:c}}return{action:Ae.SendAlternateToPenaltyBox,flags:qe.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var r;switch((r=t.errorAction)==null?void 0:r.action){case Ae.DoNothing:break;case Ae.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==C.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,r=e.errorAction;if(!r)return;const{flags:s}=r,n=r.nextAutoLevel;switch(s){case qe.None:this.switchLevel(e,n);break;case qe.MoveAllAlternatesMatchingHDCP:{const u=this.getVariantLevelIndex(e.frag),l=t.levels[u],c=l==null?void 0:l.attrs["HDCP-LEVEL"];if(r.hdcpLevel=c,c==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(c){t.maxHdcpLevel=Oa[Oa.indexOf(c)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case qe.MoveAllAlternatesMatchingKey:{const u=e.decryptdata;if(u){const l=this.hls.levels,c=l.length;for(let h=c;h--;)if(this.variantHasKey(l[h],u)){var a,o;this.log(`Banned key found in level ${h} (${l[h].bitrate}bps) or audio group "${(a=l[h].audioGroups)==null?void 0:a.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${Ie(u.keyId||[])}`),l[h].fragmentError++,l[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h)}const d=e.frag;if(this.hls.levels.length<c)r.resolved=!0;else if(d&&d.type!==V.MAIN){const h=d.decryptdata;h&&!u.matches(h)&&(r.resolved=!0)}}break}}r.resolved||this.switchLevel(e,n)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===C.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const r=ka(e.mimeType),s=this.hls.levels;for(let n=s.length;n--;)s[n][`${e.sourceBufferName}Codec`]===r&&(this.log(`Removing level ${n} for ${e.details} ("${r}" not supported)`),this.hls.removeLevel(n))}}}function Wr(i){const e={action:Ae.DoNothing,flags:qe.None};return i&&(e.resolved=!0),e}var _e={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class iE{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const r=this.activePartLists[t];if(r)for(let s=r.length;s--;){const n=r[s];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,r){const{fragments:s}=this,n=Object.keys(s);for(let a=n.length;a--;){const o=s[n[a]];if((o==null?void 0:o.body.type)===t&&(!r||o.buffered)){const u=o.body;if(u.start<=e&&e<=u.end)return u}}return null}detectEvictedFragments(e,t,r,s,n){this.timeRanges&&(this.timeRanges[e]=t);const a=(s==null?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const u=this.fragments[o];if(!u||a>=u.body.sn)return;if(!u.buffered&&(!u.loaded||n)){u.body.type===r&&this.removeFragment(u.body);return}const l=u.range[e];if(l){if(l.time.length===0){this.removeFragment(u.body);return}l.time.some(c=>{const d=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return d&&this.removeFragment(u.body),d})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const r=e.frag,s=$r(r),n=this.fragments[s];if(!n||n.buffered&&r.gap)return;const a=!r.relurl;Object.keys(t).forEach(o=>{const u=r.elementaryStreams[o];if(!u)return;const l=t[o],c=a||u.partial===!0;n.range[o]=this.getBufferedTimes(r,e.part,c,l)}),n.loaded=null,Object.keys(n.range).length?(this.bufferedEnd(n,r),gs(n)||this.removeParts(r.sn-1,r.type)):this.removeFragment(n.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const r=this.activePartLists[t];r&&(this.activePartLists[t]=nd(r,s=>s.fragment.sn>=e))}fragBuffered(e,t){const r=$r(e);let s=this.fragments[r];!s&&t&&(s=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,this.bufferedEnd(s,e))}getBufferedTimes(e,t,r,s){const n={time:[],partial:r},a=e.start,o=e.end,u=e.minEndPTS||o,l=e.maxStartPTS||a;for(let c=0;c<s.length;c++){const d=s.start(c)-this.bufferPadding,h=s.end(c)+this.bufferPadding;if(l>=d&&u<=h){n.time.push({startPTS:Math.max(a,s.start(c)),endPTS:Math.min(o,s.end(c))});break}else if(a<h&&o>d){const f=Math.max(a,s.start(c)),g=Math.min(o,s.end(c));g>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:g}))}else if(o<=d)break}return n}getPartialFragment(e){let t=null,r,s,n,a=0;const{bufferPadding:o,fragments:u}=this;return Object.keys(u).forEach(l=>{const c=u[l];c&&gs(c)&&(s=c.body.start-o,n=c.body.end+o,e>=s&&e<=n&&(r=Math.min(e-s,n-e),a<=r&&(t=c.body,a=r)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||gs(t))}getState(e){const t=$r(e),r=this.fragments[t];return r?r.buffered?gs(r)?_e.PARTIAL:_e.OK:_e.APPENDING:_e.NOT_LOADED}isTimeBuffered(e,t,r){let s,n;for(let a=0;a<r.length;a++){if(s=r.start(a)-this.bufferPadding,n=r.end(a)+this.bufferPadding,e>=s&&t<=n)return!0;if(t<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const r=t.frag,s=t.part?null:t,n=$r(r);this.fragments[n]={body:r,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:r,part:s,timeRanges:n,type:a}=t;if(r.sn==="initSegment")return;const o=r.type;if(s){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(s)}this.timeRanges=n;const u=n[a];this.detectEvictedFragments(a,u,o,s)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=$r(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,r=Object.keys(t);if(!e)return r.length>0;for(let s=r.length;s--;){const n=t[r[s]];if((n==null?void 0:n.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,r,s,n){s&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const u=o.body;u.type!==r||s&&!u.gap||u.start<t&&u.end>e&&(o.buffered||n)&&this.removeFragment(u)})}removeFragment(e){const t=$r(e);e.clearElementaryStreamInfo();const r=this.activePartLists[e.type];if(r){const s=e.sn;this.activePartLists[e.type]=nd(r,n=>n.fragment.sn!==s)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(r=>r.clearElementaryStreamInfo())}}function gs(i){var e,t,r;return i.buffered&&!!(i.body.gap||(e=i.range.video)!=null&&e.partial||(t=i.range.audio)!=null&&t.partial||(r=i.range.audiovideo)!=null&&r.partial)}function $r(i){return`${i.type}_${i.level}_${i.sn}`}function nd(i,e){return i.filter(t=>{const r=e(t);return r||t.clearElementaryStreamInfo(),r})}var Mt={cbc:0,ctr:1};class sE{constructor(e,t,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=r}decrypt(e,t){switch(this.aesMode){case Mt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Mt.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function nE(i){const e=i.byteLength,t=e&&new DataView(i.buffer).getUint8(e-1);return t?i.slice(0,e-t):i}class aE{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),r=new Uint32Array(4);for(let s=0;s<4;s++)r[s]=t.getUint32(s*4);return r}initTable(){const e=this.sBox,t=this.invSBox,r=this.subMix,s=r[0],n=r[1],a=r[2],o=r[3],u=this.invSubMix,l=u[0],c=u[1],d=u[2],h=u[3],f=new Uint32Array(256);let g=0,p=0,m=0;for(m=0;m<256;m++)m<128?f[m]=m<<1:f[m]=m<<1^283;for(m=0;m<256;m++){let v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^v&255^99,e[g]=v,t[v]=g;const y=f[g],S=f[y],_=f[S];let T=f[v]*257^v*16843008;s[g]=T<<24|T>>>8,n[g]=T<<16|T>>>16,a[g]=T<<8|T>>>24,o[g]=T,T=_*16843009^S*65537^y*257^g*16843008,l[v]=T<<24|T>>>8,c[v]=T<<16|T>>>16,d[v]=T<<8|T>>>24,h[v]=T,g?(g=y^f[f[f[_^y]]],p^=f[f[p]]):g=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let r=!0,s=0;for(;s<t.length&&r;)r=t[s]===this.key[s],s++;if(r)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,u;const l=this.keySchedule=new Uint32Array(a),c=this.invKeySchedule=new Uint32Array(a),d=this.sBox,h=this.rcon,f=this.invSubMix,g=f[0],p=f[1],m=f[2],v=f[3];let y,S;for(o=0;o<a;o++){if(o<n){y=l[o]=t[o];continue}S=y,o%n===0?(S=S<<8|S>>>24,S=d[S>>>24]<<24|d[S>>>16&255]<<16|d[S>>>8&255]<<8|d[S&255],S^=h[o/n|0]<<24):n>6&&o%n===4&&(S=d[S>>>24]<<24|d[S>>>16&255]<<16|d[S>>>8&255]<<8|d[S&255]),l[o]=y=(l[o-n]^S)>>>0}for(u=0;u<a;u++)o=a-u,u&3?S=l[o]:S=l[o-4],u<4||o<=4?c[u]=S:c[u]=g[d[S>>>24]]^p[d[S>>>16&255]]^m[d[S>>>8&255]]^v[d[S&255]],c[u]=c[u]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,r){const s=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,u=o[0],l=o[1],c=o[2],d=o[3],h=this.uint8ArrayToUint32Array_(r);let f=h[0],g=h[1],p=h[2],m=h[3];const v=new Int32Array(e),y=new Int32Array(v.length);let S,_,T,x,b,I,A,D,L,P,O,G,j,M;const U=this.networkToHostOrderSwap;for(;t<v.length;){for(L=U(v[t]),P=U(v[t+1]),O=U(v[t+2]),G=U(v[t+3]),b=L^n[0],I=G^n[1],A=O^n[2],D=P^n[3],j=4,M=1;M<s;M++)S=u[b>>>24]^l[I>>16&255]^c[A>>8&255]^d[D&255]^n[j],_=u[I>>>24]^l[A>>16&255]^c[D>>8&255]^d[b&255]^n[j+1],T=u[A>>>24]^l[D>>16&255]^c[b>>8&255]^d[I&255]^n[j+2],x=u[D>>>24]^l[b>>16&255]^c[I>>8&255]^d[A&255]^n[j+3],b=S,I=_,A=T,D=x,j=j+4;S=a[b>>>24]<<24^a[I>>16&255]<<16^a[A>>8&255]<<8^a[D&255]^n[j],_=a[I>>>24]<<24^a[A>>16&255]<<16^a[D>>8&255]<<8^a[b&255]^n[j+1],T=a[A>>>24]<<24^a[D>>16&255]<<16^a[b>>8&255]<<8^a[I&255]^n[j+2],x=a[D>>>24]<<24^a[b>>16&255]<<16^a[I>>8&255]<<8^a[A&255]^n[j+3],y[t]=U(S^f),y[t+1]=U(x^g),y[t+2]=U(T^p),y[t+3]=U(_^m),f=L,g=P,p=O,m=G,t=t+4}return y.buffer}}class oE{constructor(e,t,r){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=r}expandKey(){const e=lE(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function lE(i){switch(i){case Mt.cbc:return"AES-CBC";case Mt.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${i}`)}}const uE=16;class xo{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const r=self.crypto;r&&(this.subtle=r.subtle||r.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const r=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?nE(r):r}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,r,s){return this.useSoftware?new Promise((n,a)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,r,s);const u=this.flush();u?n(u.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r,s)}softwareDecrypt(e,t,r,s){const{currentIV:n,currentResult:a,remainderData:o}=this;if(s!==Mt.cbc||t.byteLength!==16)return ne.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Je(o,e),this.remainderData=null);const u=this.getValidChunk(e);if(!u.length)return null;n&&(r=n);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new aE),l.expandKey(t);const c=a;return this.currentResult=l.decrypt(u.buffer,0,r),this.currentIV=u.slice(-16).buffer,c||null}webCryptoDecrypt(e,t,r,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,s));this.key=t,this.fastAesKey=new oE(this.subtle,t,s)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new sE(this.subtle,new Uint8Array(r),s).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(ne.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,r,s)))}onWebCryptoError(e,t,r,s){const n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,s);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const r=e.length-e.length%uE;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t}logOnce(e){this.logEnabled&&(ne.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const ad=Math.pow(2,17);class cE{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 r=e.url;if(!r)return Promise.reject(new Et({type:q.NETWORK_ERROR,details:C.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const s=this.config,n=s.fLoader,a=s.loader;return new Promise((o,u)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(g=>g[0]==="GAP")){u(ld(e));return}else e.gap=!1;const l=this.loader=n?new n(s):new a(s),c=od(e);e.loader=l;const d=sd(s.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:ad};e.stats=l.stats;const f={onSuccess:(g,p,m,v)=>{this.resetLoader(e,l);let y=g.data;m.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(y.slice(0,16)),y=y.slice(16)),o({frag:e,part:null,payload:y,networkDetails:v})},onError:(g,p,m,v)=>{this.resetLoader(e,l),u(new Et({type:q.NETWORK_ERROR,details:C.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:se({url:r,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:m,stats:v}))},onAbort:(g,p,m)=>{this.resetLoader(e,l),u(new Et({type:q.NETWORK_ERROR,details:C.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:m,stats:g}))},onTimeout:(g,p,m)=>{this.resetLoader(e,l),u(new Et({type:q.NETWORK_ERROR,details:C.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:m,stats:g}))}};t&&(f.onProgress=(g,p,m,v)=>t({frag:e,part:null,payload:m,networkDetails:v})),l.load(c,h,f)})}loadPart(e,t,r){this.abort();const s=this.config,n=s.fLoader,a=s.loader;return new Promise((o,u)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){u(ld(e,t));return}const l=this.loader=n?new n(s):new a(s),c=od(e,t);e.loader=l;const d=sd(s.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:ad};t.stats=l.stats,l.load(c,h,{onSuccess:(f,g,p,m)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:f.data,networkDetails:m};r(v),o(v)},onError:(f,g,p,m)=>{this.resetLoader(e,l),u(new Et({type:q.NETWORK_ERROR,details:C.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:se({url:c.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:m}))},onAbort:(f,g,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),u(new Et({type:q.NETWORK_ERROR,details:C.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,l),u(new Et({type:q.NETWORK_ERROR,details:C.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(e,t){const r=e.stats,s=t.stats,n=s.total;if(r.loaded+=s.loaded,n){const u=Math.round(e.duration/t.duration),l=Math.min(Math.round(r.loaded/n),u),d=(u-l)*Math.round(r.loaded/l);r.total=r.loaded+d}else r.total=Math.max(r.loaded,r.total);const a=r.loading,o=s.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 od(i,e=null){const t=e||i,r={frag:i,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},s=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if($(s)&&$(n)){var a;let o=s,u=n;if(i.sn==="initSegment"&&dE((a=i.decryptdata)==null?void 0:a.method)){const l=n-s;l%16&&(u=n+(16-l%16)),s!==0&&(r.resetIV=!0,o=s-16)}r.rangeStart=o,r.rangeEnd=u}return r}function ld(i,e){const t=new Error(`GAP ${i.gap?"tag":"attribute"} found`),r={type:q.MEDIA_ERROR,details:C.FRAG_GAP,fatal:!1,frag:i,error:t,networkDetails:null};return e&&(r.part=e),(e||i).stats.aborted=!0,new Et(r)}function dE(i){return i==="AES-128"||i==="AES-256"}class Et extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class rg extends et{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Ao{constructor(e,t,r,s=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=ms(),this.buffering={audio:ms(),video:ms(),audiovideo:ms()},this.level=e,this.sn=t,this.id=r,this.size=s,this.part=n,this.partial=a}}function ms(){return{start:0,executeStart:0,executeEnd:0,end:0}}const ud={length:0,start:()=>0,end:()=>0};class Y{static isBuffered(e,t){if(e){const r=Y.getBuffered(e);for(let s=r.length;s--;)if(t>=r.start(s)&&t<=r.end(s))return!0}return!1}static bufferedRanges(e){if(e){const t=Y.getBuffered(e);return Y.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let r=0;r<e.length;r++)t.push({start:e.start(r),end:e.end(r)});return t}static bufferInfo(e,t,r){if(e){const s=Y.bufferedRanges(e);if(s.length)return Y.bufferedInfo(s,t,r)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,r){t=Math.max(0,t),e.length>1&&e.sort((c,d)=>c.start-d.start||d.end-c.end);let s=-1,n=[];if(r)for(let c=0;c<e.length;c++){t>=e[c].start&&t<=e[c].end&&(s=c);const d=n.length;if(d){const h=n[d-1].end;e[c].start-h<r?e[c].end>h&&(n[d-1].end=e[c].end):n.push(e[c])}else n.push(e[c])}else n=e;let a=0,o,u=t,l=t;for(let c=0;c<n.length;c++){const d=n[c].start,h=n[c].end;if(s===-1&&t>=d&&t<=h&&(s=c),t+r>=d&&t<h)u=d,l=h,a=l-t;else if(t+r<d){o=d;break}}return{len:a,start:u||0,end:l||0,nextStart:o,buffered:e,bufferedIndex:s}}static getBuffered(e){try{return e.buffered||ud}catch(t){return ne.log("failed to get media.buffered",t),ud}}}const ig=/\{\$([a-zA-Z0-9-_]+)\}/g;function cd(i){return ig.test(i)}function Fa(i,e){if(i.variableList!==null||i.hasVariableRefs){const t=i.variableList;return e.replace(ig,r=>{const s=r.substring(2,r.length-1),n=t==null?void 0:t[s];return n===void 0?(i.playlistParsingError||(i.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),r):n})}return e}function dd(i,e,t){let r=i.variableList;r||(i.variableList=r={});let s,n;if("QUERYPARAM"in e){s=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(s))n=a.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${t}"`)}catch(a){i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else s=e.NAME,n=e.VALUE;s in r?i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):r[s]=n||""}function hE(i,e,t){const r=e.IMPORT;if(t&&r in t){let s=i.variableList;s||(i.variableList=s={}),s[r]=t[r]}else i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}const fE=/^(\d+)x(\d+)$/,hd=/(.+?)=(".*?"|.*?)(?:,|$)/g;class de{constructor(e,t){typeof e=="string"&&(e=de.parseAttrList(e,t)),ae(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 r=new Uint8Array(t.length/2);for(let s=0;s<t.length/2;s++)r[s]=parseInt(t.slice(s*2,s*2+2),16);return r}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 r=this[e];return r?parseFloat(r):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const r=this[e];return(r?r.split(/[ ,]+/):[]).reduce((s,n)=>(s[n.toLowerCase()]=!0,s),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=fE.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let r;const s={},n='"';for(hd.lastIndex=0;(r=hd.exec(e))!==null;){const a=r[1].trim();let o=r[2];const u=o.indexOf(n)===0&&o.lastIndexOf(n)===o.length-1;let l=!1;if(u)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(u||l))o=Fa(t,o);else if(!l&&!u)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":ne.warn(`${e}: attribute ${a} is missing quotes`)}s[a]=o}return s}}const gE="com.apple.hls.interstitial";function mE(i){return i!=="ID"&&i!=="CLASS"&&i!=="CUE"&&i!=="START-DATE"&&i!=="DURATION"&&i!=="END-DATE"&&i!=="END-ON-NEXT"}function pE(i){return i==="SCTE35-OUT"||i==="SCTE35-IN"||i==="SCTE35-CMD"}class sg{constructor(e,t,r=0){var s;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(s=t==null?void 0:t.tagOrder)!=null?s:r,t){const n=t.attr;for(const a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){ne.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=ae(new de({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const n=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);$(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(ne.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if($(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===gE}get isValid(){return!!this.id&&!this._badValueForSameId&&$(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const yE=10;class vE{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&r>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)})}get hasProgramDateTime(){return this.fragments.length?$(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||yE}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let r=e.length;r--;)if(e[r].index>t)return e[r].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function tn(i,e){return i.length===e.length?!i.some((t,r)=>t!==e[r]):!1}function fd(i,e){return!i&&!e?!0:!i||!e?!1:tn(i,e)}function zr(i){return i==="AES-128"||i==="AES-256"||i==="AES-256-CTR"}function Io(i){switch(i){case"AES-128":case"AES-256":return Mt.cbc;case"AES-256-CTR":return Mt.ctr;default:throw new Error(`invalid full segment method ${i}`)}}function Do(i){return Uint8Array.from(atob(i),e=>e.charCodeAt(0))}function Na(i){return Uint8Array.from(unescape(encodeURIComponent(i)),e=>e.charCodeAt(0))}function EE(i){const e=Na(i).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function ng(i){const e=function(r,s,n){const a=r[s];r[s]=r[n],r[n]=a};e(i,0,3),e(i,1,2),e(i,4,5),e(i,6,7)}function ag(i){const e=i.split(":");let t=null;if(e[0]==="data"&&e.length===2){const r=e[1].split(";"),s=r[r.length-1].split(",");if(s.length===2){const n=s[0]==="base64",a=s[1];n?(r.splice(-1,1),t=Do(a)):t=EE(a)}}return t}const rn=typeof self<"u"?self:void 0;var fe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},De={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ps(i){switch(i){case De.FAIRPLAY:return fe.FAIRPLAY;case De.PLAYREADY:return fe.PLAYREADY;case De.WIDEVINE:return fe.WIDEVINE;case De.CLEARKEY:return fe.CLEARKEY}}function ra(i){switch(i){case fe.FAIRPLAY:return De.FAIRPLAY;case fe.PLAYREADY:return De.PLAYREADY;case fe.WIDEVINE:return De.WIDEVINE;case fe.CLEARKEY:return De.CLEARKEY}}function Ri(i){const{drmSystems:e,widevineLicenseUrl:t}=i,r=e?[fe.FAIRPLAY,fe.WIDEVINE,fe.PLAYREADY,fe.CLEARKEY].filter(s=>!!e[s]):[];return!r[fe.WIDEVINE]&&t&&r.push(fe.WIDEVINE),r}const og=function(i){return rn!=null&&(i=rn.navigator)!=null&&i.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function SE(i,e,t,r){let s;switch(i){case fe.FAIRPLAY:s=["cenc","sinf"];break;case fe.WIDEVINE:case fe.PLAYREADY:s=["cenc"];break;case fe.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${i}`)}return _E(s,e,t,r)}function _E(i,e,t,r){return[{initDataTypes:i,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}))}]}function TE(i){var e;return!!i&&(i.sessionType==="persistent-license"||!!((e=i.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function lg(i){const e=new Uint16Array(i.buffer,i.byteOffset,i.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),r=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(a){const o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){const u=Do(o).subarray(0,16);return ng(u),u}}return null}let jr={};class kt{static clearKeyUriToKeyIdMap(){jr={}}static setKeyIdForUri(e,t){jr[e]=t}static addKeyIdForUri(e){const t=Object.keys(jr).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,t),jr[e]=r,r}constructor(e,t,r,s=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=r,this.keyFormatVersions=s,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!zr(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Ff(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&tn(e.keyFormatVersions,this.keyFormatVersions)&&fd(e.iv,this.iv)&&fd(e.keyId,this.keyId)}isSupported(){if(this.method){if(zr(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case De.FAIRPLAY:case De.WIDEVINE:case De.PLAYREADY:case De.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(zr(this.method)){let n=this.iv;return n||(typeof e!="number"&&(ne.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),n=xE(e)),new kt(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){const n=jr[this.uri];if(n&&!tn(this.keyId,n)&&kt.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const r=ag(this.uri);if(r)switch(this.keyFormat){case De.WIDEVINE:if(this.pssh=r,!this.keyId){const n=Dv(r.buffer);if(n.length){var s;const a=n[0];this.keyId=(s=a.kids)!=null&&s.length?a.kids[0]:null}}this.keyId||(this.keyId=gd(t));break;case De.PLAYREADY:{const n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Iv(n,null,r),this.keyId=lg(r);break}default:{let n=r.subarray(0,16);if(n.length!==16){const a=new Uint8Array(16);a.set(n,16-n.length),n=a}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n;n=bE(t),n||(n=gd(t),n||(n=jr[this.uri])),n&&(this.keyId=n,kt.setKeyIdForUri(this.uri,n))}return this}}function bE(i){const e=i==null?void 0:i[De.WIDEVINE];return e?e.keyId:null}function gd(i){const e=i==null?void 0:i[De.PLAYREADY];if(e){const t=ag(e.uri);if(t)return lg(t)}return null}function xE(i){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=i>>8*(15-t)&255;return e}const md=/#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,pd=/#EXT-X-MEDIA:(.*)/g,AE=/^#EXT(?:INF|-X-TARGETDURATION):/m,ia=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),IE=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class ht{static findGroup(e,t){for(let r=0;r<e.length;r++){const s=e[r];if(s.id===t)return s}}static resolve(e,t){return vo.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return AE.test(e)}static parseMasterPlaylist(e,t){const r=cd(e),s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:r},n=[];if(md.lastIndex=0,!e.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let a;for(;(a=md.exec(e))!=null;)if(a[1]){var o;const l=new de(a[1],s),c=Fa(s,a[2]),d={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:ht.resolve(c,t)},h=l.decimalResolution("RESOLUTION");h&&(d.width=h.width,d.height=h.height),Ed(l.CODECS,d);const f=l["SUPPLEMENTAL-CODECS"];f&&(d.supplemental={},Ed(f,d.supplemental)),(o=d.unknownCodecs)!=null&&o.length||n.push(d),s.levels.push(d)}else if(a[3]){const l=a[3],c=a[4];switch(l){case"SESSION-DATA":{const d=new de(c,s),h=d["DATA-ID"];h&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[h]=d);break}case"SESSION-KEY":{const d=yd(c,t,s);d.encrypted&&d.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(d)):ne.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${c}"`);break}case"DEFINE":{{const d=new de(c,s);dd(s,d,t)}break}case"CONTENT-STEERING":{const d=new de(c,s);s.contentSteering={uri:ht.resolve(d["SERVER-URI"],t),pathwayId:d["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=vd(c);break}}}const u=n.length>0&&n.length<s.levels.length;return s.levels=u?n:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,r){let s;const n={},a=r.levels,o={AUDIO:a.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:a.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let u=0;for(pd.lastIndex=0;(s=pd.exec(e))!==null;){const l=new de(s[1],r),c=l.TYPE;if(c){const d=o[c],h=n[c]||[];n[c]=h;const f=l.LANGUAGE,g=l["ASSOC-LANGUAGE"],p=l.CHANNELS,m=l.CHARACTERISTICS,v=l["INSTREAM-ID"],y={attrs:l,bitrate:0,id:u++,groupId:l["GROUP-ID"]||"",name:l.NAME||f||"",type:c,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:f,url:l.URI?ht.resolve(l.URI,t):""};if(g&&(y.assocLang=g),p&&(y.channels=p),m&&(y.characteristics=m),v&&(y.instreamId=v),d!=null&&d.length){const S=ht.findGroup(d,y.groupId)||d[0];Sd(y,S,"audioCodec"),Sd(y,S,"textCodec")}h.push(y)}}return n}static parseLevelPlaylist(e,t,r,s,n,a){var o;const u={url:t},l=new vE(t),c=l.fragments,d=[];let h=null,f=0,g=0,p=0,m=0,v=0,y=null,S=new Jn(s,u),_,T,x,b=-1,I=!1,A=null,D;if(ia.lastIndex=0,l.m3u8=e,l.hasVariableRefs=cd(e),((o=ia.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(_=ia.exec(e))!==null;){I&&(I=!1,S=new Jn(s,u),S.playlistOffset=p,S.setStart(p),S.sn=f,S.cc=m,v&&(S.bitrate=v),S.level=r,h&&(S.initSegment=h,h.rawProgramDateTime&&(S.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),A&&(S.setByteRange(A),A=null)));const G=_[1];if(G){S.duration=parseFloat(G);const j=(" "+_[2]).slice(1);S.title=j||null,S.tagList.push(j?["INF",G,j]:["INF",G])}else if(_[3]){if($(S.duration)){S.playlistOffset=p,S.setStart(p),x&&Td(S,x,l),S.sn=f,S.level=r,S.cc=m,c.push(S);const j=(" "+_[3]).slice(1);S.relurl=Fa(l,j),Ba(S,y,d),y=S,p+=S.duration,f++,g=0,I=!0}}else{if(_=_[0].match(IE),!_){ne.warn("No matches on slow regex match for level playlist!");continue}for(T=1;T<_.length&&_[T]===void 0;T++);const j=(" "+_[T]).slice(1),M=(" "+_[T+1]).slice(1),U=_[T+2]?(" "+_[T+2]).slice(1):null;switch(j){case"BYTERANGE":y?S.setByteRange(M,y):S.setByteRange(M);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=M,S.tagList.push(["PROGRAM-DATE-TIME",M]),b===-1&&(b=c.length);break;case"PLAYLIST-TYPE":l.type&&yt(l,j,_),l.type=M.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?yt(l,j,_):c.length>0&&bd(l,j,_),f=l.startSN=parseInt(M);break;case"SKIP":{l.skippedSegments&&yt(l,j,_);const F=new de(M,l),K=F.decimalInteger("SKIPPED-SEGMENTS");if($(K)){l.skippedSegments+=K;for(let N=K;N--;)c.push(null);f+=K}const W=F.enumeratedString("RECENTLY-REMOVED-DATERANGES");W&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(W.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&yt(l,j,_),l.targetduration=Math.max(parseInt(M),1);break;case"VERSION":l.version!==null&&yt(l,j,_),l.version=parseInt(M);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||yt(l,j,_),l.live=!1;break;case"#":(M||U)&&S.tagList.push(U?[M,U]:[M]);break;case"DISCONTINUITY":m++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([j]);break;case"BITRATE":S.tagList.push([j,M]),v=parseInt(M)*1e3,$(v)?S.bitrate=v:v=0;break;case"DATERANGE":{const F=new de(M,l),K=new sg(F,l.dateRanges[F.ID],l.dateRangeTagCount);l.dateRangeTagCount++,K.isValid||l.skippedSegments?l.dateRanges[K.id]=K:ne.warn(`Ignoring invalid DATERANGE tag: "${M}"`),S.tagList.push(["EXT-X-DATERANGE",M]);break}case"DEFINE":{{const F=new de(M,l);"IMPORT"in F?hE(l,F,a):dd(l,F,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?yt(l,j,_):c.length>0&&bd(l,j,_),l.startCC=m=parseInt(M);break;case"KEY":{const F=yd(M,t,l);if(F.isSupported()){if(F.method==="NONE"){x=void 0;break}x||(x={});const K=x[F.keyFormat];K!=null&&K.matches(F)||(K&&(x=ae({},x)),x[F.keyFormat]=F)}else ne.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${M}"`);break}case"START":l.startTimeOffset=vd(M);break;case"MAP":{const F=new de(M,l);if(S.duration){const K=new Jn(s,u);_d(K,F,r,x),h=K,S.initSegment=h,h.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=h.rawProgramDateTime)}else{const K=S.byteRangeEndOffset;if(K){const W=S.byteRangeStartOffset;A=`${K-W}@${W}`}else A=null;_d(S,F,r,x),h=S,I=!0}h.cc=m;break}case"SERVER-CONTROL":{D&&yt(l,j,_),D=new de(M),l.canBlockReload=D.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=D.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&D.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=D.optionalFloat("PART-HOLD-BACK",0),l.holdBack=D.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&yt(l,j,_);const F=new de(M);l.partTarget=F.decimalFloatingPoint("PART-TARGET");break}case"PART":{let F=l.partList;F||(F=l.partList=[]);const K=g>0?F[F.length-1]:void 0,W=g++,N=new de(M,l),B=new hv(N,S,u,W,K);F.push(B),S.duration+=B.duration;break}case"PRELOAD-HINT":{const F=new de(M,l);l.preloadHint=F;break}case"RENDITION-REPORT":{const F=new de(M,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(F);break}default:ne.warn(`line parsed but not handled: ${_}`);break}}}y&&!y.relurl?(c.pop(),p-=y.duration,l.partList&&(l.fragmentHint=y)):l.partList&&(Ba(S,y,d),S.cc=m,l.fragmentHint=S,x&&Td(S,x,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const L=c.length,P=c[0],O=c[L-1];if(p+=l.skippedSegments*l.targetduration,p>0&&L&&O){l.averagetargetduration=p/L;const G=O.sn;l.endSN=G!=="initSegment"?G:0,l.live||(O.endList=!0),b>0&&(LE(c,b),P&&d.unshift(P))}return l.fragmentHint&&(p+=l.fragmentHint.duration),l.totalduration=p,d.length&&l.dateRangeTagCount&&P&&ug(d,l),l.endCC=m,l}}function ug(i,e){let t=i.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];i.push(o),t++}else return;const r=i[t-1],s=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const u=e.dateRanges[n[o]],l=u.startDate.getTime();u.tagAnchor=r.ref;for(let c=t;c--;){var a;if(((a=i[c])==null?void 0:a.sn)<e.startSN)break;const d=DE(e,l,i,c,s);if(d!==-1){u.tagAnchor=e.fragments[d].ref;break}}}}function DE(i,e,t,r,s){const n=t[r];if(n){const o=n.programDateTime;if(e>=o||r===0){var a;const u=(((a=t[r+1])==null?void 0:a.start)||s)-n.start;if(e<=o+u*1e3){const l=t[r].sn-i.startSN;if(l<0)return-1;const c=i.fragments;if(c.length>t.length){const h=(t[r+1]||c[c.length-1]).sn-i.startSN;for(let f=h;f>l;f--){const g=c[f].programDateTime;if(e>=g&&e<g+c[f].duration*1e3)return f}}return l}}}return-1}function yd(i,e,t){var r,s;const n=new de(i,t),a=(r=n.METHOD)!=null?r:"",o=n.URI,u=n.hexadecimalInteger("IV"),l=n.KEYFORMATVERSIONS,c=(s=n.KEYFORMAT)!=null?s:"identity";o&&n.IV&&!u&&ne.error(`Invalid IV: ${n.IV}`);const d=o?ht.resolve(o,e):"",h=(l||"1").split("/").map(Number).filter(Number.isFinite);return new kt(a,d,c,h,u,n.KEYID)}function vd(i){const t=new de(i).decimalFloatingPoint("TIME-OFFSET");return $(t)?t:null}function Ed(i,e){let t=(i||"").split(/[ ,]+/).filter(r=>r);["video","audio","text"].forEach(r=>{const s=t.filter(n=>_o(n,r));s.length&&(e[`${r}Codec`]=s.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>s.indexOf(n)===-1))}),e.unknownCodecs=t}function Sd(i,e,t){const r=e[t];r&&(i[t]=r)}function LE(i,e){let t=i[e];for(let r=e;r--;){const s=i[r];if(!s)return;s.programDateTime=t.programDateTime-s.duration*1e3,t=s}}function Ba(i,e,t){i.rawProgramDateTime?t.push(i):e!=null&&e.programDateTime&&(i.programDateTime=e.endProgramDateTime)}function _d(i,e,t,r){i.relurl=e.URI,e.BYTERANGE&&i.setByteRange(e.BYTERANGE),i.level=t,i.sn="initSegment",r&&(i.levelkeys=r),i.initSegment=null}function Td(i,e,t){i.levelkeys=e;const{encryptedFragments:r}=t;(!r.length||r[r.length-1].levelkeys!==e)&&Object.keys(e).some(s=>e[s].isCommonEncryption)&&r.push(i)}function yt(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function bd(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function sa(i,e){const t=e.startPTS;if($(t)){let r=0,s;e.sn>i.sn?(r=t-i.start,s=i):(r=i.start-t,s=e),s.duration!==r&&s.setDuration(r)}else e.sn>i.sn?i.cc===e.cc&&i.minEndPTS?e.setStart(i.start+(i.minEndPTS-i.start)):e.setStart(i.start+i.duration):e.setStart(Math.max(i.start-e.duration,0))}function cg(i,e,t,r,s,n,a){r-t<=0&&(a.warn("Fragment should have a positive duration",e),r=t+e.duration,n=s+e.duration);let u=t,l=r;const c=e.startPTS,d=e.endPTS;if($(c)){const v=Math.abs(c-t);i&&v>i.totalduration?a.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${i.url}`):$(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,u=Math.max(t,c),t=Math.min(t,c),s=e.startDTS!==void 0?Math.min(s,e.startDTS):s,l=Math.min(r,d),r=Math.max(r,d),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n}const h=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(r-e.start),e.startPTS=t,e.maxStartPTS=u,e.startDTS=s,e.endPTS=r,e.minEndPTS=l,e.endDTS=n;const f=e.sn;if(!i||f<i.startSN||f>i.endSN)return 0;let g;const p=f-i.startSN,m=i.fragments;for(m[p]=e,g=p;g>0;g--)sa(m[g],m[g-1]);for(g=p;g<m.length-1;g++)sa(m[g],m[g+1]);return i.fragmentHint&&sa(m[m.length-1],i.fragmentHint),i.PTSKnown=i.alignedSliding=!0,h}function RE(i,e,t){if(i===e)return;let r=null;const s=i.fragments;for(let c=s.length-1;c>=0;c--){const d=s[c].initSegment;if(d){r=d;break}}i.fragmentHint&&delete i.fragmentHint.endPTS;let n;PE(i,e,(c,d,h,f)=>{if((!e.startCC||e.skippedSegments)&&d.cc!==c.cc){const g=c.cc-d.cc;for(let p=h;p<f.length;p++)f[p].cc+=g;e.endCC=f[f.length-1].cc}$(c.startPTS)&&$(c.endPTS)&&(d.setStart(d.startPTS=c.startPTS),d.startDTS=c.startDTS,d.maxStartPTS=c.maxStartPTS,d.endPTS=c.endPTS,d.endDTS=c.endDTS,d.minEndPTS=c.minEndPTS,d.setDuration(c.endPTS-c.startPTS),d.duration&&(n=d),e.PTSKnown=e.alignedSliding=!0),c.hasStreams&&(d.elementaryStreams=c.elementaryStreams),d.loader=c.loader,c.hasStats&&(d.stats=c.stats),c.initSegment&&(d.initSegment=c.initSegment,r=c.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(r&&o.forEach(c=>{var d;c&&(!c.initSegment||c.initSegment.relurl===((d=r)==null?void 0:d.relurl))&&(c.initSegment=r)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(c=>!c),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let c=e.skippedSegments;c--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=CE(i.dateRanges,e,t));const c=i.fragments.filter(d=>d.rawProgramDateTime);if(i.hasProgramDateTime&&!e.hasProgramDateTime)for(let d=1;d<o.length;d++)o[d].programDateTime===null&&Ba(o[d],o[d-1],c);ug(c,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var u;const c=fg(i,e.startSN-1);e.startCC=(u=c==null?void 0:c.cc)!=null?u:a[0].cc}wE(i.partList,e.partList,(c,d)=>{d.elementaryStreams=c.elementaryStreams,d.stats=c.stats}),n?cg(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,t):dg(i,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=i.driftStartTime,e.driftStart=i.driftStart;const l=e.advancedDateTime;if(e.advanced&&l){const c=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=c),e.driftEndTime=l,e.driftEnd=c}else e.driftEndTime=i.driftEndTime,e.driftEnd=i.driftEnd,e.advancedDateTime=i.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=i.requestScheduled)}function CE(i,e,t){const{dateRanges:r,recentlyRemovedDateranges:s}=e,n=ae({},i);s&&s.forEach(u=>{delete n[u]});const o=Object.keys(n).length;return o?(Object.keys(r).forEach(u=>{const l=n[u],c=new sg(r[u].attr,l);c.isValid?(n[u]=c,l||(c.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ue(r[u].attr)}"`)}),n):r}function wE(i,e,t){if(i&&e){let r=0;for(let s=0,n=i.length;s<=n;s++){const a=i[s],o=e[s+r];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):r--}}}function PE(i,e,t){const r=e.skippedSegments,s=Math.max(i.startSN,e.startSN)-e.startSN,n=(i.fragmentHint?1:0)+(r?e.endSN:Math.min(i.endSN,e.endSN))-e.startSN,a=e.startSN-i.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,u=i.fragmentHint?i.fragments.concat(i.fragmentHint):i.fragments;for(let l=s;l<=n;l++){const c=u[a+l];let d=o[l];if(r&&!d&&c&&(d=e.fragments[l]=c),c&&d){t(c,d,l,o);const h=c.relurl,f=d.relurl;if(h&&kE(h,f)){e.playlistParsingError=xd(`media sequence mismatch ${d.sn}:`,i,e,c,d);return}else if(c.cc!==d.cc){e.playlistParsingError=xd(`discontinuity sequence mismatch (${c.cc}!=${d.cc})`,i,e,c,d);return}}}}function xd(i,e,t,r,s){return new Error(`${i} ${s.url}
100114Playlist starting @${e.startSN}
101115${e.m3u8}
102116103117Playlist starting @${t.startSN}
104104-${t.m3u8}`)}function Xa(n,e,t=!0){const s=e.startSN+e.skippedSegments-n.startSN,i=n.fragments,r=s>=0;let a=0;if(r&&s<i.length)a=i[s].start;else if(r&&e.startSN===n.endSN+1)a=n.fragmentEnd;else if(r&&t)a=n.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=n.fragmentStart;else return;Pi(e,a)}function Pi(n,e){if(e){const t=n.fragments;for(let s=n.skippedSegments;s<t.length;s++)t[s].addStart(e);n.fragmentHint&&n.fragmentHint.addStart(e)}}function za(n,e=1/0){let t=1e3*n.targetduration;if(n.updated){const s=n.fragments;if(s.length&&t*4>e){const r=s[s.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function Qa(n,e,t){if(!n)return null;let s=n.fragments[e-n.startSN];return s||(s=n.fragmentHint,s&&s.sn===e)?s:e<n.startSN&&t&&t.sn===e?t:null}function En(n,e,t){return n?Za(n.partList,e,t):null}function Za(n,e,t){if(n)for(let s=n.length;s--;){const i=n[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function Ja(n){n.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(i=>{i.level=t,i.initSegment&&(i.initSegment.level=t)})})}function yh(n,e){return n!==e&&e?Tn(n)!==Tn(e):!1}function Tn(n){return n.replace(/\?[^?]*$/,"")}function Nt(n,e){for(let s=0,i=n.length;s<i;s++){var t;if(((t=n[s])==null?void 0:t.cc)===e)return n[s]}return null}function Eh(n,e){return!!(n&&e.startCC<n.endCC&&e.endCC>n.startCC)}function Sn(n,e){const t=n.start+e;n.startPTS=t,n.setStart(t),n.endPTS=t+n.duration}function eo(n,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)Sn(t[s],n);e.fragmentHint&&Sn(e.fragmentHint,n),e.alignedSliding=!0}function Th(n,e){n&&(to(e,n),e.alignedSliding||Ms(e,n),!e.alignedSliding&&!e.skippedSegments&&Xa(n,e,!1))}function to(n,e){if(!Eh(e,n))return;const t=Math.min(e.endCC,n.endCC),s=Nt(e.fragments,t),i=Nt(n.fragments,t);if(!s||!i)return;ie.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const r=s.start-i.start;eo(r,n)}function Ms(n,e){if(!n.hasProgramDateTime||!e.hasProgramDateTime)return;const t=n.fragments,s=e.fragments;if(!t.length||!s.length)return;let i,r;const a=Math.min(e.endCC,n.endCC);e.startCC<a&&n.startCC<a&&(i=Nt(s,a),r=Nt(t,a)),(!i||!r)&&(i=s[Math.floor(s.length/2)],r=Nt(t,i.cc)||t[Math.floor(t.length/2)]);const o=i.programDateTime,c=r.programDateTime;if(!o||!c)return;const l=(c-o)/1e3-(r.start-i.start);eo(l,n)}function Ae(n,e,t){Ie(n,e,t),n.addEventListener(e,t)}function Ie(n,e,t){n.removeEventListener(e,t)}const Sh={toString:function(n){let e="";const t=n.length;for(let s=0;s<t;s++)e+=`[${n.start(s).toFixed(3)}-${n.end(s).toFixed(3)}]`;return e}},P={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class sr extends $a{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=P.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:a,fragCurrent:o,media:c,mediaBuffer:l,state:h}=this,u=c?c.currentTime:0,d=q.bufferInfo(l||c,u,a.maxBufferHole),f=!d.len;if(this.log(`Media seeking to ${M(u)?u.toFixed(3):u}, state: ${h}, ${f?"out of":"in"} buffer`),this.state===P.ENDED)this.resetLoadingState();else if(o){const g=a.maxFragLookUpTolerance,p=o.start-g,y=o.start+o.duration+g;if(f||y<d.start||p>d.end){const E=u>y;(u<p||E)&&(E&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0);const g=this.lastCurrentTime;if(u>g&&(this.lastCurrentTime=u),!this.loadingParts){const p=Math.max(d.end,u),y=this.shouldLoadParts(this.getLevelDetails(),p);y&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=y)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,f&&(this.startPosition=u)),f&&this.state===P.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new jc(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Zi(e.config)}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===P.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=P.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=q.bufferedInfo(r,e.start,0));const a=e.nextStart;if(a&&a>i&&a<t.edge||this.media.currentTime<e.start)return!1;const c=t.partList;if(c!=null&&c.length){const h=c[c.length-1];return q.isBuffered(this.media,h.start+h.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;Ae(s,"seeking",this.onMediaSeeking),Ae(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===P.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Ie(i,"seeking",this.onMediaSeeking),Ie(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=P.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=r=>{const a=r.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;const a=this.state,o=r.frag;if(this.fragContextChanged(o)){(a===P.FRAG_LOADING||!this.fragCurrent&&a===P.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=P.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(m.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(`Frag error: ${(r==null?void 0:r.message)||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===me.APPENDING){const r=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===me.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(m.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const i=s==null?void 0:s.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{frag:r,payload:a}=s,o=r.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&It(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,er(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{const h=self.performance.now();return i.trigger(m.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:c,tdecrypt:h}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==P.STOPPED&&(this.state=P.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&((s=r.audio)!=null&&s.encrypted||(i=r.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(m.ERROR,{type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?Sh.toString(q.getBuffered(s)):"(detached)"})`),de(e)){var i;if(e.type!==U.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=P.IDLE;return}}const r=(i=this.levels)==null?void 0:i[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=P.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,a=!r||r.length===0||r.some(c=>!c),o=new Ji(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;this.fragCurrent=e;const a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=P.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(m.KEY_LOADED,d),this.state===P.KEY_LOADING&&(this.state=P.IDLE),d}),this.hls.trigger(m.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(de(e)&&(!c||e.sn!==c.sn)){const d=this.shouldLoadParts(t.details,e.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${e.sn}`),this.loadingParts=d)}if(s=Math.max(e.start,s||0),this.loadingParts&&de(e)){const d=a.partList;if(d&&i){s>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const f=this.getNextPart(d,e,s);if(f>-1){const g=d[f];e=this.fragCurrent=g.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${g.index} (${f}/${d.length-1}) of ${this.fragInfo(e,!1,g)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=g.start+g.duration,this.state=P.FRAG_LOADING;let p;return o?p=o.then(y=>!y||this.fragContextChanged(y.frag)?null:this.doFragPartsLoad(e,g,t,i)).catch(y=>this.handleFragLoadError(y)):p=this.doFragPartsLoad(e,g,t,i).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:g,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(d,s))return Promise.resolve(null)}}if(de(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=a.partList)==null?void 0:l.filter(d=>d.loaded).map(d=>`[${d.start}-${d.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),M(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=P.FRAG_LOADING;const h=this.config.progressive&&e.type!==U.SUBTITLE;let u;return h&&o?u=o.then(d=>!d||this.fragContextChanged(d.frag)?null:this.fragmentLoader.load(e,i)).catch(d=>this.handleFragLoadError(d)):u=Promise.all([this.fragmentLoader.load(e,h?i:void 0),o]).then(([d])=>(!h&&i&&i(d),d)).catch(d=>this.handleFragLoadError(d)),this.hls.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,s,i){return new Promise((r,a)=>{var o;const c=[],l=(o=s.details)==null?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(e,u,i).then(d=>{c[u.index]=d;const f=d.part;this.hls.trigger(m.FRAG_LOADED,d);const g=En(s.details,e.sn,u.index+1)||Za(l,e.sn,u.index+1);if(g)h(g);else return r({frag:e,part:f,partsLoaded:c})}).catch(a)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===R.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===H.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(m.ERROR,t)}else this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==P.PARSING){!this.fragCurrent&&this.state!==P.STOPPED&&this.state!==P.ERROR&&(this.state=P.IDLE);return}const{frag:s,part:i,level:r}=t,a=self.performance.now();s.stats.parsing.end=a,i&&(i.stats.parsing.end=a);const o=this.getLevelDetails(),l=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(s,i,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const r=e.partList[0];if(r.fragment.type===U.SUBTITLE)return!1;const a=r.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=a){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:a}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const o=t[i],c=o.details,l=a>-1?En(c,r,a):null,h=l?l.fragment:Qa(c,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==P.PARSING)return;const{data1:a,data2:o}=e;let c=a;if(o&&(c=Oe(a,o)),!c.length)return;const l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,u={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:c};if(this.hls.trigger(m.BUFFER_APPENDING,u),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!q.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=q.bufferInfo(t,s,0),r=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-a,i.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;const i=this.getLoadPosition();if(!M(i))return null;const a=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,a)}getFwdBufferInfoAtPos(e,t,s,i){const r=q.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&(r.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(r.nextStart,a.end)-t,i);return q.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=U.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,a=s[0].start,o=r.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const u=r.initialLiveManifestSize;if(i<u)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${u})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),c=this.getInitialLiveFragment(t);const d=this.hls.startPosition,f=this.hls.liveSyncPosition,g=c?(d!==-1&&d>=a?d:f)||c.start:e;this.log(`Setting startPosition to ${g} to match start frag at live edge. mainStart: ${d} liveSyncPosition: ${f} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=g}}else e<=a&&(c=s[0]);if(!c){const u=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,u,t)}let h=this.filterReplacedPrimary(c,t);if(!h&&c){const u=c.sn-t.startSN;h=this.filterReplacedPrimary(s[u+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===me.OK||s===me.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=r){const c=a.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(vn(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(vn(this.config)&&e.type!==U.SUBTITLE){const s=this.hls.interstitialsManager,i=s==null?void 0:s.bufferingItem;if(i){const a=i.event;if(a){if(a.appendInPlace||Math.abs(e.start-i.start)>1||i.start===0)return null}else if(e.end<=i.start&&(t==null?void 0:t.live)===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}const r=s==null?void 0:s.playerQueue;if(r)for(let a=r.length;a--;){const o=r[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,r=!1,a=!0;for(let o=0,c=e.length;o<c;o++){const l=e[o];if(a=a&&!l.independent,i>-1&&s<l.start)break;const h=l.loaded;h?i=-1:(r||(l.independent||a)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${l.start}`),i=o),r=h}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=Mc(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const a=t[r-e.startSN];s.cc===a.cc&&(i=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=Na(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:a,endSN:o}=s;const{fragmentHint:c}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,u=!!(this.loadingParts&&h!=null&&h.length&&c);u&&!this.bitrateTest&&h[h.length-1].fragment.sn===c.sn&&(a=a.concat(c),o=c.sn);let d;if(e<t){var f;const p=e<this.lastCurrentTime||e>t-l||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:l;d=mt(r,a,e,p)}else d=a[a.length-1];if(d){const g=d.sn-s.startSN,p=this.fragmentTracker.getState(d);if((p===me.OK||p===me.PARTIAL&&d.gap)&&(r=d),r&&d.sn===r.sn&&(!u||h[0].fragment.sn>d.sn||!s.live)&&d.level===r.level){const E=a[g+1];d.sn<o&&this.fragmentTracker.getState(E)!==me.OK?d=E:d=null}}return d}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,a=!t,o=e.alignedSliding&&M(r);if(a||!o&&!r){Th(s,e);const c=e.fragmentStart;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),c}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(s===-1){const r=this.startTimeOffset!==null,a=r?this.startTimeOffset:e.startTimeOffset;a!==null&&M(a)?(s=t+a,a<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&de(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==P.FRAG_LOADING_WAITING_RETRY)&&(this.state=P.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const E=this.getCurrentContext(t.chunkMeta);E&&(t.frag=E.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 a=t.details===R.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction;if(!o){this.state=P.ERROR;return}const{action:c,flags:l,retryCount:h=0,retryConfig:u}=o,d=!!u,f=d&&c===Ee.RetryRequest,g=d&&!o.resolved&&l===Re.MoveAllAlternatesMatchingHost,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!f&&g&&de(i)&&!i.endList&&p&&!Ua(t))this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((f||g)&&h<u.maxNumRetry){var y;const E=Ri((y=t.response)==null?void 0:y.code),T=Qi(u,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=P.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,E){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${T}ms`)}else if(u)if(this.resetFragmentErrors(e),h<u.maxNumRetry)!a&&c!==Ee.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else c===Ee.SendAlternateToPenaltyBox?this.state=P.WAITING_LEVEL:this.state=P.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Ri(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=P.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===P.PARSING||this.state===P.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(t==null?void 0:t.duration)||10);const a=!r;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===U.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==P.STOPPED&&(this.state=P.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=q.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===P.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==P.STOPPED&&(this.state=P.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const r=s.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{const h=e.elementaryStreams[l];if(h){const u=h.endPTS-h.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${u})`),c||!1;const d=i?0:ja(r,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:r,level:s,drift:d,type:l,frag:e,start:h.startPTS,end:h.endPTS}),!0}return c},!1)){var o;const c=((o=this.transmuxer)==null?void 0:o.error)===null;if((s.fragmentError===0||c&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),c){const l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=P.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(m.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===U.MAIN?"level":"track"}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN).toFixed(3)}-${((r=t&&!s?e.endPTS:(s||e).end)!=null?r:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function vn(n){return!!n.interstitialsController&&n.enableInterstitialPlayback!==!1}class so{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=vh(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function vh(n,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<n.length;i++){const r=n[i];t.set(r,s),s+=r.length}return t}var ei={exports:{}},xn;function xh(){return xn||(xn=1,function(n){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(c,l,h){this.fn=c,this.context=l,this.once=h||!1}function r(c,l,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var f=new i(h,u||c,d),g=t?t+l:l;return c._events[g]?c._events[g].fn?c._events[g]=[c._events[g],f]:c._events[g].push(f):(c._events[g]=f,c._eventsCount++),c}function a(c,l){--c._eventsCount===0?c._events=new s:delete c._events[l]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],h,u;if(this._eventsCount===0)return l;for(u in h=this._events)e.call(h,u)&&l.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(h)):l},o.prototype.listeners=function(l){var h=t?t+l:l,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,g=new Array(f);d<f;d++)g[d]=u[d].fn;return g},o.prototype.listenerCount=function(l){var h=t?t+l:l,u=this._events[h];return u?u.fn?1:u.length:0},o.prototype.emit=function(l,h,u,d,f,g){var p=t?t+l:l;if(!this._events[p])return!1;var y=this._events[p],E=arguments.length,T,S;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),E){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,h),!0;case 3:return y.fn.call(y.context,h,u),!0;case 4:return y.fn.call(y.context,h,u,d),!0;case 5:return y.fn.call(y.context,h,u,d,f),!0;case 6:return y.fn.call(y.context,h,u,d,f,g),!0}for(S=1,T=new Array(E-1);S<E;S++)T[S-1]=arguments[S];y.fn.apply(y.context,T)}else{var v=y.length,x;for(S=0;S<v;S++)switch(y[S].once&&this.removeListener(l,y[S].fn,void 0,!0),E){case 1:y[S].fn.call(y[S].context);break;case 2:y[S].fn.call(y[S].context,h);break;case 3:y[S].fn.call(y[S].context,h,u);break;case 4:y[S].fn.call(y[S].context,h,u,d);break;default:if(!T)for(x=1,T=new Array(E-1);x<E;x++)T[x-1]=arguments[x];y[S].fn.apply(y[S].context,T)}}return!0},o.prototype.on=function(l,h,u){return r(this,l,h,u,!1)},o.prototype.once=function(l,h,u){return r(this,l,h,u,!0)},o.prototype.removeListener=function(l,h,u,d){var f=t?t+l:l;if(!this._events[f])return this;if(!h)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===h&&(!d||g.once)&&(!u||g.context===u)&&a(this,f);else{for(var p=0,y=[],E=g.length;p<E;p++)(g[p].fn!==h||d&&!g[p].once||u&&g[p].context!==u)&&y.push(g[p]);y.length?this._events[f]=y.length===1?y[0]:y:a(this,f)}return this},o.prototype.removeAllListeners=function(l){var h;return l?(h=t?t+l:l,this._events[h]&&a(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,n.exports=o}(ei)),ei.exports}var Ah=xh(),ir=jl(Ah);const Vt="1.6.15",Pt={};function _h(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Ih(){const n=Pt[Vt];if(n)return n.clientCount++,n;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),i={worker:new self.Worker(t),objectURL:t,clientCount:1};return Pt[Vt]=i,i}function Lh(n){const e=Pt[n];if(e)return e.clientCount++,e;const t=new self.URL(n,self.location.href).href,i={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Pt[n]=i,i}function Rh(n){const e=Pt[n||Vt];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete Pt[n||Vt],i&&self.URL.revokeObjectURL(i),s.terminate()}}function io(n,e){return e+10<=n.length&&n[e]===51&&n[e+1]===68&&n[e+2]===73&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128}function rr(n,e){return e+10<=n.length&&n[e]===73&&n[e+1]===68&&n[e+2]===51&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128}function Ks(n,e){let t=0;return t=(n[e]&127)<<21,t|=(n[e+1]&127)<<14,t|=(n[e+2]&127)<<7,t|=n[e+3]&127,t}function Ht(n,e){const t=e;let s=0;for(;rr(n,e);){s+=10;const i=Ks(n,e+6);s+=i,io(n,e+10)&&(s+=10),e+=s}if(s>0)return n.subarray(t,t+s)}function bh(n,e,t,s){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],a=r>>2&15;if(a>12){const f=new Error(`invalid ADTS sampling index:${a}`);n.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(r>>6&3)+1,c=e[t+3]>>6&3|(r&1)<<2,l="mp4a.40."+o,h=i[a];let u=a;(o===5||o===29)&&(u-=3);const d=[o<<3|(u&14)>>1,(u&1)<<7|c<<3];return ie.log(`manifest codec:${s}, parsed codec:${l}, channels:${c}, rate:${h} (ADTS object type:${o} sampling index:${a})`),{config:d,samplerate:h,channelCount:c,codec:l,parsedCodec:l,manifestCodec:s}}function ro(n,e){return n[e]===255&&(n[e+1]&246)===240}function no(n,e){return n[e+1]&1?7:9}function nr(n,e){return(n[e+3]&3)<<11|n[e+4]<<3|(n[e+5]&224)>>>5}function Dh(n,e){return e+5<n.length}function Ns(n,e){return e+1<n.length&&ro(n,e)}function Ch(n,e){return Dh(n,e)&&ro(n,e)&&nr(n,e)<=n.length-e}function Ph(n,e){if(Ns(n,e)){const t=no(n,e);if(e+t>=n.length)return!1;const s=nr(n,e);if(s<=t)return!1;const i=e+s;return i===n.length||Ns(n,i)}return!1}function ao(n,e,t,s,i){if(!n.samplerate){const r=bh(e,t,s,i);if(!r)return;re(n,r)}}function oo(n){return 1024*9e4/n}function kh(n,e){const t=no(n,e);if(e+t<=n.length){const s=nr(n,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function lo(n,e,t,s,i){const r=oo(n.samplerate),a=s+i*r,o=kh(e,t);let c;if(o){const{frameLength:u,headerLength:d}=o,f=d+u,g=Math.max(0,t+f-e.length);g?(c=new Uint8Array(f-d),c.set(e.subarray(t+d,e.length),0)):c=e.subarray(t+d,t+f);const p={unit:c,pts:a};return g||n.samples.push(p),{sample:p,length:f,missing:g}}const l=e.length-t;return c=new Uint8Array(l),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:a},length:l,missing:-1}}function wh(n,e){return rr(n,e)&&Ks(n,e+6)+10<=n.length-e}function Oh(n){return n instanceof ArrayBuffer?n:n.byteOffset==0&&n.byteLength==n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer}function ti(n,e=0,t=1/0){return Fh(n,e,t,Uint8Array)}function Fh(n,e,t,s){const i=Mh(n);let r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);const a=Nh(n)?n.byteOffset:0,o=(a+n.byteLength)/r,c=(a+e)/r,l=Math.floor(Math.max(0,Math.min(c,o))),h=Math.floor(Math.min(l+Math.max(t,0),o));return new s(i,l,h-l)}function Mh(n){return n instanceof ArrayBuffer?n:n.buffer}function Nh(n){return n&&n.buffer instanceof ArrayBuffer&&n.byteLength!==void 0&&n.byteOffset!==void 0}function Bh(n){const e={key:n.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(n.size<2)return;if(n.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const s=n.data.subarray(1).indexOf(0);if(s===-1)return;const i=Ce(ti(n.data,1,s)),r=n.data[2+s],a=n.data.subarray(3+s).indexOf(0);if(a===-1)return;const o=Ce(ti(n.data,3+s,a));let c;return i==="-->"?c=Ce(ti(n.data,4+s+a)):c=Oh(n.data.subarray(4+s+a)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=c,e}function Uh(n){if(n.size<2)return;const e=Ce(n.data,!0),t=new Uint8Array(n.data.subarray(e.length+1));return{key:n.type,info:e,data:t.buffer}}function $h(n){if(n.size<2)return;if(n.type==="TXXX"){let t=1;const s=Ce(n.data.subarray(t),!0);t+=s.length+1;const i=Ce(n.data.subarray(t));return{key:n.type,info:s,data:i}}const e=Ce(n.data.subarray(1));return{key:n.type,info:"",data:e}}function Gh(n){if(n.type==="WXXX"){if(n.size<2)return;let t=1;const s=Ce(n.data.subarray(t),!0);t+=s.length+1;const i=Ce(n.data.subarray(t));return{key:n.type,info:s,data:i}}const e=Ce(n.data);return{key:n.type,info:"",data:e}}function Kh(n){return n.type==="PRIV"?Uh(n):n.type[0]==="W"?Gh(n):n.type==="APIC"?Bh(n):$h(n)}function Vh(n){const e=String.fromCharCode(n[0],n[1],n[2],n[3]),t=Ks(n,4),s=10;return{type:e,size:t,data:n.subarray(s,s+t)}}const ts=10,Hh=10;function co(n){let e=0;const t=[];for(;rr(n,e);){const s=Ks(n,e+6);n[e+5]>>6&1&&(e+=ts),e+=ts;const i=e+s;for(;e+Hh<i;){const r=Vh(n.subarray(e)),a=Kh(r);a&&t.push(a),e+=r.size+ts}io(n,e)&&(e+=ts)}return t}function ho(n){return n&&n.key==="PRIV"&&n.info==="com.apple.streaming.transportStreamTimestamp"}function Wh(n){if(n.data.byteLength===8){const e=new Uint8Array(n.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function ar(n){const e=co(n);for(let t=0;t<e.length;t++){const s=e[t];if(ho(s))return Wh(s)}}let De=function(n){return n.audioId3="org.id3",n.dateRange="com.apple.quicktime.HLS",n.emsg="https://aomedia.org/emsg/ID3",n.misbklv="urn:misb:KLV:bin:1910.1",n}({});function Ve(n="",e=9e4){return{type:n,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class or{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=Oe(this.cachedData,e),this.cachedData=null);let s=Ht(e,0),i=s?s.length:0,r;const a=this._audioTrack,o=this._id3Track,c=s?ar(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&M(c))&&(this.basePTS=Yh(c,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:De.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const h=this.appendFrame(a,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=l}else wh(e,i)?(s=Ht(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:De.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===l&&r!==l){const h=e.slice(r);this.cachedData?this.cachedData=Oe(this.cachedData,h):this.cachedData=h}}return{audioTrack:a,videoTrack:Ve(),id3Track:o,textTrack:Ve()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Ve(),id3Track:this._id3Track,textTrack:Ve()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Yh=(n,e,t)=>{if(M(n))return n*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let ss=null;const qh=[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],jh=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Xh=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],zh=[0,1,1,4];function uo(n,e,t,s,i){if(t+24>e.length)return;const r=fo(e,t);if(r&&t+r.frameLength<=e.length){const a=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*a,c={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return n.config=[],n.channelCount=r.channelCount,n.samplerate=r.sampleRate,n.samples.push(c),{sample:c,length:r.frameLength,missing:0}}}function fo(n,e){const t=n[e+1]>>3&3,s=n[e+1]>>1&3,i=n[e+2]>>4&15,r=n[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){const a=n[e+2]>>1&1,o=n[e+3]>>6,c=t===3?3-s:s===3?3:4,l=qh[c*14+i-1]*1e3,u=jh[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,f=Xh[t][s],g=zh[s],p=f*8*g,y=Math.floor(f*l/u+a)*g;if(ss===null){const S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ss=S?parseInt(S[1]):0}return!!ss&&ss<=87&&s===2&&l>=224e3&&o===0&&(n[e+3]=n[e+3]|128),{sampleRate:u,channelCount:d,frameLength:y,samplesPerFrame:p}}}function lr(n,e){return n[e]===255&&(n[e+1]&224)===224&&(n[e+1]&6)!==0}function go(n,e){return e+1<n.length&&lr(n,e)}function Qh(n,e){return lr(n,e)&&4<=n.length-e}function mo(n,e){if(e+1<n.length&&lr(n,e)){const s=fo(n,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===n.length||go(n,r)}return!1}class Zh extends or{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=Ht(e,0);let i=(s==null?void 0:s.length)||0;if(mo(e,i))return!1;for(let r=e.length;i<r;i++)if(Ph(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Ch(e,t)}appendFrame(e,t,s){ao(e,this.observer,t,s,e.manifestCodec);const i=lo(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const po=(n,e)=>{let t=0,s=5;e+=s;const i=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=n[e];const o=Math.min(s,8),c=8-o;r[0]=4278190080>>>24+c<<c,i[0]=(a[0]&r[0])>>c,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t};class Jh extends or{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=yo(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=Ht(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&ar(t)!==void 0&&po(e,s)<16}}function yo(n,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],c=e[t+4]&63,h=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][c*3+r]*2;if(t+h>e.length)return-1;const u=e[t+6]>>5;let d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));const f=(e[t+6]<<8|e[t+7])>>12-d&1,p=[2,1,2,3,3,4,4,5][u]+f,y=e[t+5]>>3,E=e[t+5]&7,T=new Uint8Array([r<<6|y<<1|E>>2,(E&3)<<6|u<<3|f<<2|c>>4,c<<4&224]),S=1536/o*9e4,v=s+i*S,x=e.subarray(t,t+h);return n.config=T,n.channelCount=p,n.samplerate=o,n.samples.push({unit:x,pts:v}),h}class eu extends or{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Ht(e,0);let s=(t==null?void 0:t.length)||0;if(t&&e[s]===11&&e[s+1]===119&&ar(t)!==void 0&&po(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(mo(e,s))return ie.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Qh(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return uo(e,t,s,this.basePTS,this.frameIndex)}}const tu=/\/emsg[-/]ID3/i;class su{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=Ve("video",1),a=this.audioTrack=Ve("audio",1),o=this.txtTrack=Ve("text",1);if(this.id3Track=Ve("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=La(e);if(c.video){const{id:l,timescale:h,codec:u,supplemental:d}=c.video;r.id=l,r.timescale=o.timescale=h,r.codec=u,r.supplemental=d}if(c.audio){const{id:l,timescale:h,codec:u}=c.audio;a.id=l,a.timescale=h,a.codec=u}o.id=Aa.text,r.sampleDuration=0,r.duration=a.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return Jl(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Oe(this.remainderData,e));const o=ac(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const a=this.extractID3Track(i,t);return r.samples=Ur(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=Ur(e,t),{videoTrack:t,audioTrack:Ve(),id3Track:i,textTrack:Ve()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=z(e.samples,["emsg"]);i&&i.forEach(r=>{const a=lc(r);if(tu.test(a.schemeIdUri)){const o=An(a,t);let c=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const l=a.payload;s.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:De.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=An(a,t);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:De.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function An(n,e){return M(n.presentationTime)?n.presentationTime/n.timeScale:e+n.presentationTimeDelta/n.timeScale}class iu{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Zi(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,ot.cbc)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).then(o=>{const c=new Uint8Array(o);i.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const a=Da(r.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(c=>{r.data=this.getAvcDecryptedUnit(a,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}const r=e[t].units;for(;!(s>=r.length);s++){const a=r[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,s,i,a),!this.decrypter.isSync()))return}}}}class Eo{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,i=s.length;if(i){const r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;let r=e.naluState||0;const a=r,o=[];let c=0,l,h,u,d=-1,f=0;for(r===-1&&(d=0,f=this.getNALuType(t,0),r=0,c=1);c<i;){if(l=t[c++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(h=c-r-1,d>=0){const g={data:t.subarray(d,h),type:f};o.push(g)}else{const g=this.getLastNalUnit(e.samples);g&&(a&&c<=4-a&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-a)),h>0&&(g.data=Oe(g.data,t.subarray(0,h)),g.state=0))}c<i?(u=this.getNALuType(t,c),d=c,f=u,r=0):r=-1}else r=0}if(d>=0&&r>=0){const g={data:t.subarray(d,i),type:f,state:r};o.push(g)}if(o.length===0){const g=this.getLastNalUnit(e.samples);g&&(g.data=Oe(g.data,t))}return e.naluState=r,o}}class Bt{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&ie.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class ru extends Eo{parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let a=this.VideoSample,o,c=!1;s.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,u;switch(l.type){case 1:{let p=!1;o=!0;const y=l.data;if(c&&y.length>4){const E=this.readSliceType(y);(E===2||E===4||E===7||E===9)&&(p=!0)}if(p){var d;(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=p;break}case 5:o=!0,(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,ji(l.data,1,s.pts,t.samples);break}case 7:{var f,g;o=!0,c=!0;const p=l.data,y=this.readSPS(p);if(!e.sps||e.width!==y.width||e.height!==y.height||((f=e.pixelRatio)==null?void 0:f[0])!==y.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[p];const E=p.subarray(1,4);let T="avc1.";for(let S=0;S<3;S++){let v=E[S].toString(16);v.length<2&&(v="0"+v),T+=v}e.codec=T}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(u=a)!=null&&u.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(l)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Bt(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,r;for(let a=0;a<e;a++)i!==0&&(r=t.readEG(),i=(s+r+256)%256),s=i===0?s:i}readSPS(e){const t=new Bt(e);let s=0,i=0,r=0,a=0,o,c,l;const h=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),p=t.skipEG.bind(t),y=t.skipUEG.bind(t),E=this.skipScalingList.bind(this);h();const T=h();if(u(5),g(3),h(),y(),T===100||T===110||T===122||T===244||T===44||T===83||T===86||T===118||T===128){const b=d();if(b===3&&g(1),y(),y(),g(1),f())for(c=b!==3?8:12,l=0;l<c;l++)f()&&(l<6?E(16,t):E(64,t))}y();const S=d();if(S===0)d();else if(S===1)for(g(1),p(),p(),o=d(),l=0;l<o;l++)p();y(),g(1);const v=d(),x=d(),D=u(1);D===0&&g(1),g(1),f()&&(s=d(),i=d(),r=d(),a=d());let A=[1,1];if(f()&&f())switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:{A=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((v+1)*16-s*2-i*2),height:(2-D)*(x+1)*16-(D?2:4)*(r+a),pixelRatio:A}}}class nu extends Eo{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let a=this.VideoSample,o,c=!1;s.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,u;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var d;(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 39:o=!0,ji(l.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=re(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(o=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const f=this.readSPS(l.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const g in f.params)e.params[g]=f.params[g]}this.pushParameterSet(e.sps,l.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const f=this.readPPS(l.data);for(const g in f)e.params[g]=f[g]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(u=a)!=null&&u.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:o=!1;break}a&&o&&a.units.push(l)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Bt(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){const t=new Bt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),c=t.readUByte(),l=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),f=t.readUByte(),g=t.readUByte(),p=t.readUByte(),y=t.readUByte(),E=t.readUByte(),T=[],S=[];for(let ee=0;ee<s;ee++)T.push(t.readBoolean()),S.push(t.readBoolean());if(s>0)for(let ee=s;ee<8;ee++)t.readBits(2);for(let ee=0;ee<s;ee++)T[ee]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),S[ee]&&t.readUByte();t.readUEG();const v=t.readUEG();v==3&&t.skipBits(1);const x=t.readUEG(),D=t.readUEG(),A=t.readBoolean();let b=0,I=0,_=0,C=0;A&&(b+=t.readUEG(),I+=t.readUEG(),_+=t.readUEG(),C+=t.readUEG());const k=t.readUEG(),B=t.readUEG(),K=t.readUEG(),$=t.readBoolean();for(let ee=$?0:s;ee<=s;ee++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let xe=0;xe<4;xe++)for(let ke=0;ke<(xe===3?2:6);ke++)if(!t.readBoolean())t.readUEG();else{const Me=Math.min(64,1<<4+(xe<<1));xe>1&&t.readEG();for(let pt=0;pt<Me;pt++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const N=t.readUEG();let V=0;for(let ee=0;ee<N;ee++){let xe=!1;if(ee!==0&&(xe=t.readBoolean()),xe){ee===N&&t.readUEG(),t.readBoolean(),t.readUEG();let ke=0;for(let ct=0;ct<=V;ct++){const Me=t.readBoolean();let pt=!1;Me||(pt=t.readBoolean()),(Me||pt)&&ke++}V=ke}else{const ke=t.readUEG(),ct=t.readUEG();V=ke+ct;for(let Me=0;Me<ke;Me++)t.readUEG(),t.readBoolean();for(let Me=0;Me<ct;Me++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const ee=t.readUEG();for(let xe=0;xe<ee;xe++){for(let ke=0;ke<K+4;ke++)t.readBits(1);t.readBits(1)}}let O=0,F=1,j=1,te=!0,X=1,J=0;t.readBoolean(),t.readBoolean();let ve=!1;if(t.readBoolean()){if(t.readBoolean()){const ht=t.readUByte(),pr=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Xt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];ht>0&&ht<16?(F=pr[ht-1],j=Xt[ht-1]):ht===255&&(F=t.readBits(16),j=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),ve=t.readBoolean(),ve&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(X=t.readBits(32),J=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Xt=t.readBoolean(),yr=t.readBoolean();let kt=!1;(Xt||yr)&&(kt=t.readBoolean(),kt&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),kt&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Er=0;Er<=s;Er++){te=t.readBoolean();const tl=te||t.readBoolean();let Tr=!1;tl?t.readEG():Tr=t.readBoolean();const Sr=Tr?1:t.readUEG()+1;if(Xt)for(let wt=0;wt<Sr;wt++)t.readUEG(),t.readUEG(),kt&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(yr)for(let wt=0;wt<Sr;wt++)t.readUEG(),t.readUEG(),kt&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),O=t.readUEG())}let Pe=x,Ue=D;if(A){let ee=1,xe=1;v===1?ee=xe=2:v==2&&(ee=2),Pe=x-ee*I-ee*b,Ue=D-xe*C-xe*_}const lt=i?["A","B","C"][i]:"",el=o<<24|c<<16|l<<8|h;let Hs=0;for(let ee=0;ee<32;ee++)Hs=(Hs|(el>>ee&1)<<31-ee)>>>0;let Ws=Hs.toString(16);return a===1&&Ws==="2"&&(Ws="6"),{codecString:`hvc1.${lt}${a}.${Ws}.${r?"H":"L"}${E}.B0`,params:{general_tier_flag:r,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[o,c,l,h],general_constraint_indicator_flags:[u,d,f,g,p,y],general_level_idc:E,bit_depth:k+8,bit_depth_luma_minus8:k,bit_depth_chroma_minus8:B,min_spatial_segmentation_idc:O,chroma_format_idc:v,frame_rate:{fixed:te,fps:J/X}},width:Pe,height:Ue,pixelRatio:[F,j]}}readPPS(e){const t=new Bt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const i=t.readBoolean(),r=t.readBoolean();let a=1;return r&&i?a=0:r?a=3:i&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const pe=188;class it{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=it.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(pe*5,t-pe)+1,i=0;for(;i<s;){let r=!1,a=-1,o=0;for(let c=i;c<t;c+=pe)if(e[c]===71&&(t-c===pe||e[c+pe]===71)){if(o++,a===-1&&(a=c,a!==0&&(s=Math.min(a+pe*99,e.length-pe)+1)),r||(r=ki(e,c)===0),r&&o>1&&(a===0&&o>2||c+pe>s))return a}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Aa[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=it.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=it.createTrack("audio",i),this._id3Track=it.createTrack("id3"),this._txtTrack=it.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){s||(this.sampleAes=null);let r;const a=this._videoTrack,o=this._audioTrack,c=this._id3Track,l=this._txtTrack;let h=a.pid,u=a.pesData,d=o.pid,f=c.pid,g=o.pesData,p=c.pesData,y=null,E=this.pmtParsed,T=this._pmtId,S=e.length;if(this.remainderData&&(e=Oe(this.remainderData,e),S=e.length,this.remainderData=null),S<pe&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};const v=Math.max(0,it.syncOffset(e));S-=(S-v)%pe,S<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,S,e.buffer.byteLength-S));let x=0;for(let A=v;A<S;A+=pe)if(e[A]===71){const b=!!(e[A+1]&64),I=ki(e,A),_=(e[A+3]&48)>>4;let C;if(_>1){if(C=A+5+e[A+4],C===A+pe)continue}else C=A+4;switch(I){case h:b&&(u&&(r=St(u,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,l,r,!1)),u={data:[],size:0}),u&&(u.data.push(e.subarray(C,A+pe)),u.size+=A+pe-C);break;case d:if(b){if(g&&(r=St(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}g={data:[],size:0}}g&&(g.data.push(e.subarray(C,A+pe)),g.size+=A+pe-C);break;case f:b&&(p&&(r=St(p,this.logger))&&this.parseID3PES(c,r),p={data:[],size:0}),p&&(p.data.push(e.subarray(C,A+pe)),p.size+=A+pe-C);break;case 0:b&&(C+=e[C]+1),T=this._pmtId=au(e,C);break;case T:{b&&(C+=e[C]+1);const k=ou(e,C,this.typeSupported,s,this.observer,this.logger);h=k.videoPid,h>0&&(a.pid=h,a.segmentCodec=k.segmentVideoCodec),d=k.audioPid,d>0&&(o.pid=d,o.segmentCodec=k.segmentAudioCodec),f=k.id3Pid,f>0&&(c.pid=f),y!==null&&!E&&(this.logger.warn(`MPEG-TS PMT found at ${A} after unknown PID '${y}'. Backtracking to sync byte @${v} to parse all TS packets.`),y=null,A=v-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=I;break}}else x++;x>0&&wi(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=u,o.pesData=g,c.pesData=p;const D={audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(D),D}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:i,textTrack:r}=e,a=s.pesData,o=t.pesData,c=i.pesData;let l;if(a&&(l=St(a,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)):s.pesData=a,o&&(l=St(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;c&&(l=St(c,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=c}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new iu(this.observer,this.config,t);return this.decrypt(i,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new ru:e==="hevc"&&(this.videoParser=new nu))}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const i=this.aacOverFlow;let r=t.data;if(i){this.aacOverFlow=null;const u=i.missing,d=i.sample.unit.byteLength;if(u===-1)r=Oe(i.sample.unit,r);else{const f=d-u;i.sample.unit.set(r.subarray(0,u),f),e.samples.push(i.sample),s=i.missing}}let a,o;for(a=s,o=r.length;a<o-1&&!Ns(r,a);a++);if(a!==s){let u;const d=a<o-1;if(d?u=`AAC PES did not start with ADTS header,offset:${a}`:u="No ADTS header found in AAC PES",wi(this.observer,new Error(u),d,this.logger),!d)return}ao(e,this.observer,r,a,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){const u=oo(e.samplerate);c=i.sample.pts+u}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,h;for(;a<o;)if(h=lo(e,r,a,c,l),a+=h.length,h.missing){this.aacOverFlow=h;break}else for(l++;a<o-1&&!Ns(r,a);a++);}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,a=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<i;)if(go(s,a)){const c=uo(e,s,a,o,r);if(c)a+=c.length,r++;else break}else a++}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=s.length;let a=0,o=0,c;for(;o<r&&(c=yo(e,s,o,i,a++))>0;)o+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=re({},t,{type:this._videoTrack?De.emsg:De.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function ki(n,e){return((n[e+1]&31)<<8)+n[e+2]}function au(n,e){return(n[e+10]&31)<<8|n[e+11]}function ou(n,e,t,s,i,r){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(n[e+1]&15)<<8|n[e+2],c=e+3+o-4,l=(n[e+10]&15)<<8|n[e+11];for(e+=12+l;e<c;){const h=ki(n,e),u=(n[e+3]&15)<<8|n[e+4];switch(n[e]){case 207:if(!s){si("ADTS AAC",r);break}case 15:a.audioPid===-1&&(a.audioPid=h);break;case 21:a.id3Pid===-1&&(a.id3Pid=h);break;case 219:if(!s){si("H.264",r);break}case 27:a.videoPid===-1&&(a.videoPid=h);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=h,a.segmentAudioCodec="mp3");break;case 193:if(!s){si("AC-3",r);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=h,a.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&u>0){let d=e+5,f=u;for(;f>2;){switch(n[d]){case 106:t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=h,a.segmentAudioCodec="ac3");break}const p=n[d+1]+2;d+=p,f-=p}}break;case 194:case 135:return wi(i,new Error("Unsupported EC-3 in M2TS found"),void 0,r),a;case 36:a.videoPid===-1&&(a.videoPid=h,a.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=u+5}return a}function wi(n,e,t,s){s.warn(`parsing error: ${e.message}`),n.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function si(n,e){e.log(`${n} with AES-128-CBC encryption found in unencrypted stream`)}function St(n,e){let t=0,s,i,r,a,o;const c=n.data;if(!n||n.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=Oe(c[0],c[1]),c.splice(1,1);if(s=c[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>n.size-6)return null;const h=s[7];h&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,h&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),r=s[8];let u=r+9;if(n.size<=u)return null;n.size-=u;const d=new Uint8Array(n.size);for(let f=0,g=c.length;f<g;f++){s=c[f];let p=s.byteLength;if(u)if(u>p){u-=p;continue}else s=s.subarray(u),p-=u,u=0;d.set(s,t),t+=p}return i&&(i-=r+3),{data:d,pts:a,dts:o,len:i}}return null}class lu{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 Je=Math.pow(2,32)-1;class L{static init(){L.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in L.types)L.types.hasOwnProperty(e)&&(L.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);L.HDLR_TYPES={video:t,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);L.STTS=L.STSC=L.STCO=r,L.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),L.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),L.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),L.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);L.FTYP=L.box(L.types.ftyp,a,c,a,o),L.DINF=L.box(L.types.dinf,L.box(L.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const a=new Uint8Array(s);for(a[0]=s>>24&255,a[1]=s>>16&255,a[2]=s>>8&255,a[3]=s&255,a.set(e,4),i=0,s=8;i<r;i++)a.set(t[i],s),s+=t[i].byteLength;return a}static hdlr(e){return L.box(L.types.hdlr,L.HDLR_TYPES[e])}static mdat(e){return L.box(L.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(Je+1)),i=Math.floor(t%(Je+1));return L.box(L.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return L.box(L.types.mdia,L.mdhd(e.timescale||0,e.duration||0),L.hdlr(e.type),L.minf(e))}static mfhd(e){return L.box(L.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?L.box(L.types.minf,L.box(L.types.smhd,L.SMHD),L.DINF,L.stbl(e)):L.box(L.types.minf,L.box(L.types.vmhd,L.VMHD),L.DINF,L.stbl(e))}static moof(e,t,s){return L.box(L.types.moof,L.mfhd(e),L.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=L.trak(e[t]);return L.box.apply(null,[L.types.moov,L.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(L.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=L.trex(e[t]);return L.box.apply(null,[L.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(Je+1)),i=Math.floor(t%(Je+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return L.box(L.types.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return L.box(L.types.sdtp,s)}static stbl(e){return L.box(L.types.stbl,L.stsd(e),L.box(L.types.stts,L.STTS),L.box(L.types.stsc,L.STSC),L.box(L.types.stsz,L.STSZ),L.box(L.types.stco,L.STCO))}static avc1(e){let t=[],s=[],i,r,a;for(i=0;i<e.sps.length;i++)r=e.sps[i],a=r.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],a=r.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(r));const o=L.box(L.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),c=e.width,l=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return L.box(L.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,l>>8&255,l&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return L.box(L.types.mp4a,L.audioStsd(e),L.box(L.types.esds,L.esds(e)))}static mp3(e){return L.box(L.types[".mp3"],L.audioStsd(e))}static ac3(e){return L.box(L.types["ac-3"],L.audioStsd(e),L.box(L.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return L.box(L.types.stsd,L.STSD,L.mp4a(e));if(t==="ac3"&&e.config)return L.box(L.types.stsd,L.STSD,L.ac3(e));if(t==="mp3"&&e.codec==="mp3")return L.box(L.types.stsd,L.STSD,L.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return L.box(L.types.stsd,L.STSD,L.avc1(e));if(t==="hevc"&&e.vps)return L.box(L.types.stsd,L.STSD,L.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,a=Math.floor(s/(Je+1)),o=Math.floor(s%(Je+1));return L.box(L.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const s=L.sdtp(e),i=e.id,r=Math.floor(t/(Je+1)),a=Math.floor(t%(Je+1));return L.box(L.types.traf,L.box(L.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),L.box(L.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),L.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,L.box(L.types.trak,L.tkhd(e),L.mdia(e))}static trex(e){const t=e.id;return L.box(L.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],i=s.length,r=12+16*i,a=new Uint8Array(r);let o,c,l,h,u,d;for(t+=8+r,a.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)c=s[o],l=c.duration,h=c.size,u=c.flags,d=c.cts,a.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return L.box(L.types.trun,a)}static initSegment(e){L.types||L.init();const t=L.moov(e);return Oe(L.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],i=4,r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),i-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let a=r.length;for(let g=0;g<s.length;g+=1){a+=3;for(let p=0;p<s[g].length;p+=1)a+=2+s[g][p].length}const o=new Uint8Array(a);o.set(r,0),a=r.length;const c=s.length-1;for(let g=0;g<s.length;g+=1){o.set(new Uint8Array([32+g|(g===c?128:0),0,s[g].length]),a),a+=3;for(let p=0;p<s[g].length;p+=1)o.set(new Uint8Array([s[g][p].length>>8,s[g][p].length&255]),a),a+=2,o.set(s[g][p],a),a+=s[g][p].length}const l=L.box(L.types.hvcC,o),h=e.width,u=e.height,d=e.pixelRatio[0],f=e.pixelRatio[1];return L.box(L.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,h>>8&255,h&255,u>>8&255,u&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}}L.types=void 0;L.HDLR_TYPES=void 0;L.STTS=void 0;L.STSC=void 0;L.STCO=void 0;L.STSZ=void 0;L.VMHD=void 0;L.SMHD=void 0;L.STSD=void 0;L.FTYP=void 0;L.DINF=void 0;const To=9e4;function cr(n,e,t=1,s=!1){const i=n*e*t;return s?Math.round(i):i}function cu(n,e,t=1,s=!1){return cr(n,e,1/t,s)}function Ot(n,e=!1){return cr(n,1e3,1/To,e)}function hu(n,e=1){return cr(n,To,1/e)}function _n(n){const{baseTime:e,timescale:t,trackId:s}=n;return`${e/t} (${e}/${t}) trackId: ${s}`}const uu=10*1e3,du=1024,fu=1152,gu=1536;let vt=null,ii=null;function In(n,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:n?2:1,isNonSync:n?0:1}}}class Es extends Fe{constructor(e,t,s,i){if(super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,vt===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);vt=a?parseInt(a[1]):0}if(ii===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);ii=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&_n(t)} > ${e&&_n(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce((r,a)=>{let o=a.pts,c=o-r;return c<-4294967296&&(t=!0,o=be(o,s),c=o-r),c>0?r:o},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,a,o,c){let l,h,u,d,f,g,p=r,y=r;const E=e.pid>-1,T=t.pid>-1,S=t.samples.length,v=e.samples.length>0,x=o&&S>0||S>1;if((!E||v)&&(!T||x)||this.ISGenerated||o){if(this.ISGenerated){var A,b,I,_;const K=this.videoTrackConfig;(K&&(t.width!==K.width||t.height!==K.height||((A=t.pixelRatio)==null?void 0:A[0])!==((b=K.pixelRatio)==null?void 0:b[0])||((I=t.pixelRatio)==null?void 0:I[1])!==((_=K.pixelRatio)==null?void 0:_[1]))||!K&&x||this.nextAudioTs===null&&v)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,r,a));const C=this.isVideoContiguous;let k=-1,B;if(x&&(k=mu(t.samples),!C&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,k>0){this.warn(`Dropped ${k} out of ${S} video samples due to a missing keyframe`);const K=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(k),t.dropped+=k,y+=(t.samples[0].pts-K)/t.inputTimeScale,B=y}else k===-1&&(this.warn(`No keyframe found out of ${S} video samples`),g=!1);if(this.ISGenerated){if(v&&x){const K=this.getVideoStartPts(t.samples),w=(be(e.samples[0].pts,K)-K)/t.inputTimeScale;p+=Math.max(0,w),y+=Math.max(0,-w)}if(v){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,r,a)),h=this.remuxAudio(e,p,this.isAudioContiguous,a,T||x||c===U.AUDIO?y:void 0),x){const K=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,r,a)),l=this.remuxVideo(t,y,C,K)}}else x&&(l=this.remuxVideo(t,y,C,0));l&&(l.firstKeyFrame=k,l.independent=k!==-1,l.firstKeyFramePTS=B)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=So(s,r,this._initPTS,this._initDTS)),i.samples.length&&(d=vo(i,r,this._initPTS))),{audio:h,video:l,initSegment:u,independent:g,text:d,id3:f}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let a=be(e,r);if(a<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-a)/t} ${i}`);a<r+t;)a+=8589934592;return a-r}generateIS(e,t,s,i){const r=e.samples,a=t.samples,o=this.typeSupported,c={},l=this._initPTS;let h=!l||i,u="audio/mp4",d,f,g,p=-1;if(h&&(d=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):L.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(p=e.id,g=e.inputTimeScale,!l||g!==l.timescale?d=f=this.computeInitPts(r[0].pts,g,s,"audio"):h=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:L.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(p=t.id,g=t.inputTimeScale,!l||g!==l.timescale){const y=this.getVideoStartPts(a),E=be(a[0].dts,y),T=this.computeInitPts(E,g,s,"video"),S=this.computeInitPts(y,g,s,"video");f=Math.min(f,T),d=Math.min(d,S)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,h?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${d/g} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/g} (${d}/${g}) trackId: ${p}`),this._initPTS={baseTime:d,timescale:g,trackId:p},this._initDTS={baseTime:f,timescale:g,trackId:p}):d=g=void 0,{tracks:c,initPTS:d,timescale:g,trackId:p}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,a=e.samples,o=[],c=a.length,l=this._initPTS,h=l.baseTime*r/l.timescale;let u=this.nextVideoTs,d=8,f=this.videoSampleDuration,g,p,y=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,T=!1;if(!s||u===null){const O=h+t*r,F=a[0].pts-be(a[0].dts,a[0].pts);vt&&u!==null&&Math.abs(O-F-(u+h))<15e3?s=!0:u=O-F-h}const S=u+h;for(let O=0;O<c;O++){const F=a[O];F.pts=be(F.pts,S),F.dts=be(F.dts,S),F.dts<a[O>0?O-1:O].dts&&(T=!0)}T&&a.sort(function(O,F){const j=O.dts-F.dts,te=O.pts-F.pts;return j||te}),g=a[0].dts,p=a[a.length-1].dts;const v=p-g,x=v?Math.round(v/(c-1)):f||e.inputTimeScale/30;if(s){const O=g-S,F=O>x,j=O<-1;if((F||j)&&(F?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ot(O,!0)} ms (${O}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ot(-O,!0)} ms (${O}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!j||S>=a[0].pts||vt)){g=S;const te=a[0].pts-O;if(F)a[0].dts=g,a[0].pts=te;else{let X=!0;for(let J=0;J<a.length&&!(a[J].dts>te&&X);J++){const ve=a[J].pts;if(a[J].dts-=O,a[J].pts-=O,J<a.length-1){const ye=a[J+1].pts,Pe=a[J].pts,Ue=ye<=Pe,lt=ye<=ve;X=Ue==lt}}}this.log(`Video: Initial PTS/DTS adjusted: ${Ot(te,!0)}/${Ot(g,!0)}, delta: ${Ot(O,!0)} ms`)}}g=Math.max(0,g);let D=0,A=0,b=g;for(let O=0;O<c;O++){const F=a[O],j=F.units,te=j.length;let X=0;for(let J=0;J<te;J++)X+=j[J].data.length;A+=X,D+=te,F.length=X,F.dts<b?(F.dts=b,b+=x/4|0||1):b=F.dts,y=Math.min(F.pts,y),E=Math.max(F.pts,E)}p=a[c-1].dts;const I=A+4*D+8;let _;try{_=new Uint8Array(I)}catch(O){this.observer.emit(m.ERROR,m.ERROR,{type:H.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:O,bytes:I,reason:`fail allocating video mdat ${I}`});return}const C=new DataView(_.buffer);C.setUint32(0,I),_.set(L.types.mdat,4);let k=!1,B=Number.POSITIVE_INFINITY,K=Number.POSITIVE_INFINITY,$=Number.NEGATIVE_INFINITY,w=Number.NEGATIVE_INFINITY;for(let O=0;O<c;O++){const F=a[O],j=F.units;let te=0;for(let ve=0,ye=j.length;ve<ye;ve++){const Pe=j[ve],Ue=Pe.data,lt=Pe.data.byteLength;C.setUint32(d,lt),d+=4,_.set(Ue,d),d+=lt,te+=4+lt}let X;if(O<c-1)f=a[O+1].dts-F.dts,X=a[O+1].pts-F.pts;else{const ve=this.config,ye=O>0?F.dts-a[O-1].dts:x;if(X=O>0?F.pts-a[O-1].pts:x,ve.stretchShortVideoTrack&&this.nextAudioTs!==null){const Pe=Math.floor(ve.maxBufferHole*r),Ue=(i?y+i*r:this.nextAudioTs+h)-F.pts;Ue>Pe?(f=Ue-ye,f<0?f=ye:k=!0,this.log(`It is approximately ${Ue/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=ye}else f=ye}const J=Math.round(F.pts-F.dts);B=Math.min(B,f),$=Math.max($,f),K=Math.min(K,X),w=Math.max(w,X),o.push(In(F.key,f,te,J))}if(o.length){if(vt){if(vt<70){const O=o[0].flags;O.dependsOn=2,O.isNonSync=0}}else if(ii&&w-K<$-B&&x/$<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let O=g;for(let F=0,j=o.length;F<j;F++){const te=O+o[F].duration,X=O+o[F].cts;if(F<j-1){const J=te+o[F+1].cts;o[F].duration=J-X}else o[F].duration=F?o[F-1].duration:x;o[F].cts=0,O=te}}}f=k||!f?x:f;const G=p+f;this.nextVideoTs=u=G-h,this.videoSampleDuration=f,this.isVideoContiguous=!0;const W={data1:L.moof(e.sequenceNumber++,g,re(e,{samples:o})),data2:_,startPTS:(y-h)/r,endPTS:(E+f-h)/r,startDTS:(g-h)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,W}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return fu;case"ac3":return gu;default:return du}}remuxAudio(e,t,s,i,r){const a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,c=a/o,l=this.getSamplesPerFrame(e),h=l*c,u=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=r!==void 0;let p=e.samples,y=d?0:8,E=this.nextAudioTs||-1;const T=u.baseTime*a/u.timescale,S=T+t*a;if(this.isAudioContiguous=s=s||p.length&&E>0&&(i&&Math.abs(S-(E+T))<9e3||Math.abs(be(p[0].pts,S)-(E+T))<20*h),p.forEach(function(w){w.pts=be(w.pts,S)}),!s||E<0){const w=p.length;if(p=p.filter(G=>G.pts>=0),w!==p.length&&this.warn(`Removed ${p.length-w} of ${w} samples (initPTS ${T} / ${a})`),!p.length)return;r===0?E=0:i&&!g?E=Math.max(0,S-T):E=p[0].pts-T}if(e.segmentCodec==="aac"){const w=this.config.maxAudioFramesDrift;for(let G=0,N=E+T;G<p.length;G++){const V=p[G],W=V.pts,O=W-N,F=Math.abs(1e3*O/a);if(O<=-w*h&&g)G===0&&(this.warn(`Audio frame @ ${(W/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*O/a)} ms.`),this.nextAudioTs=E=W-T,N=W);else if(O>=w*h&&F<uu&&g){let j=Math.round(O/h);for(N=W-j*h;N<0&&j&&h;)j--,N+=h;G===0&&(this.nextAudioTs=E=N-T),this.warn(`Injecting ${j} audio frames @ ${((N-T)/a).toFixed(3)}s due to ${Math.round(1e3*O/a)} ms gap.`);for(let te=0;te<j;te++){let X=lu.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);X||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),X=V.unit.subarray()),p.splice(G,0,{unit:X,pts:N}),N+=h,G++}}V.pts=N,N+=h}}let v=null,x=null,D,A=0,b=p.length;for(;b--;)A+=p[b].unit.byteLength;for(let w=0,G=p.length;w<G;w++){const N=p[w],V=N.unit;let W=N.pts;if(x!==null){const F=f[w-1];F.duration=Math.round((W-x)/c)}else if(s&&e.segmentCodec==="aac"&&(W=E+T),v=W,A>0){A+=y;try{D=new Uint8Array(A)}catch(F){this.observer.emit(m.ERROR,m.ERROR,{type:H.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:F,bytes:A,reason:`fail allocating audio mdat ${A}`});return}d||(new DataView(D.buffer).setUint32(0,A),D.set(L.types.mdat,4))}else return;D.set(V,y);const O=V.byteLength;y+=O,f.push(In(!0,l,O,0)),x=W}const I=f.length;if(!I)return;const _=f[f.length-1];E=x-T,this.nextAudioTs=E+c*_.duration;const C=d?new Uint8Array(0):L.moof(e.sequenceNumber++,v/c,re({},e,{samples:f}));e.samples=[];const k=(v-T)/a,B=this.nextAudioTs/a,$={data1:C,data2:D,startPTS:k,endPTS:B,startDTS:k,endDTS:B,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,$}}function be(n,e){let t;if(e===null)return n;for(e<n?t=-8589934592:t=8589934592;Math.abs(n-e)>4294967296;)n+=t;return n}function mu(n){for(let e=0;e<n.length;e++)if(n[e].key)return e;return-1}function So(n,e,t,s){const i=n.samples.length;if(!i)return;const r=n.inputTimeScale;for(let o=0;o<i;o++){const c=n.samples[o];c.pts=be(c.pts-t.baseTime*r/t.timescale,e*r)/r,c.dts=be(c.dts-s.baseTime*r/s.timescale,e*r)/r}const a=n.samples;return n.samples=[],{samples:a}}function vo(n,e,t){const s=n.samples.length;if(!s)return;const i=n.inputTimeScale;for(let a=0;a<s;a++){const o=n.samples[a];o.pts=be(o.pts-t.baseTime*i/t.timescale,e*i)/i}n.samples.sort((a,o)=>a.pts-o.pts);const r=n.samples;return n.samples=[],{samples:r}}class pu extends Fe{constructor(e,t,s,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:a}=this.initData=La(e);if(t)ic(e,t);else{const c=r||a;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(s=Ln(r,ne.AUDIO,this)),a&&(i=Ln(a,ne.VIDEO,this));const o={};r&&a?o.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:r?o.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:i,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,i,r,a){var o,c;let{initPTS:l,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};M(h)||(h=this.lastEndTime=r||0);const d=t.samples;if(!d.length)return u;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(d),g=this.initData),!((c=g)!=null&&c.length))return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const p=nc(d,g,this),y=g.audio?p[g.audio.id]:null,E=g.video?p[g.video.id]:null,T=is(E,1/0),S=is(y,1/0),v=is(E,0,!0),x=is(y,0,!0);let D=r,A=0;const b=y&&(!E||!l&&S<T||l&&l.trackId===g.audio.id),I=b?y:E;if(I){const N=I.timescale,V=I.start-r*N,W=b?g.audio.id:g.video.id;D=I.start/N,A=b?x-S:v-T,(a||!l)&&(yu(l,D,r,A)||N!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${r} ${V/N} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${D-r} (${V}/${N}) trackId: ${W}`),l=null,f.initPTS=V,f.timescale=N,f.trackId=W)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(f.initPTS=l.baseTime,f.timescale=l.timescale,f.trackId=l.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=D,f.timescale=1,f.trackId=-1),this.initPTS=l={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const _=D-l.baseTime/l.timescale,C=_+A;A>0?this.lastEndTime=C:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const k=!!g.audio,B=!!g.video;let K="";k&&(K+="audio"),B&&(K+="video");const $=(g.audio?g.audio.encrypted:!1)||(g.video?g.video.encrypted:!1),w={data1:d,startPTS:_,startDTS:_,endPTS:C,endDTS:C,type:K,hasAudio:k,hasVideo:B,nb:1,dropped:0,encrypted:$};u.audio=k&&!B?w:void 0,u.video=B?w:void 0;const G=E==null?void 0:E.sampleCount;if(G){const N=E.keyFrameIndex,V=N!==-1;w.nb=G,w.dropped=N===0||this.isVideoContiguous?0:V?N:G,w.independent=V,w.firstKeyFrame=N,V&&E.keyFrameStart&&(w.firstKeyFramePTS=(E.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(u.independent=V),this.isVideoContiguous||(this.isVideoContiguous=V),w.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${N}/${G} dropped: ${w.dropped} start: ${w.firstKeyFramePTS||"NA"}`)}return u.initSegment=f,u.id3=So(s,r,l,l),i.samples.length&&(u.text=vo(i,r,l)),u}}function is(n,e,t=!1){return(n==null?void 0:n.start)!==void 0?(n.start+(t?n.duration:0))/n.timescale:e}function yu(n,e,t,s){if(n===null)return!0;const i=Math.max(s,1),r=e-n.baseTime/n.timescale;return Math.abs(r-t)>i}function Ln(n,e,t){const s=n.codec;return s&&s.length>4?s:e===ne.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?Ds(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let Qe;try{Qe=self.performance.now.bind(self.performance)}catch{Qe=Date.now}const Ts=[{demux:su,remux:pu},{demux:it,remux:Es},{demux:Zh,remux:Es},{demux:eu,remux:Es}];Ts.splice(2,0,{demux:Jh,remux:Es});class Rn{constructor(e,t,s,i,r,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=r,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=Qe();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:c}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:g}=i||o,{audioCodec:p,videoCodec:y,defaultInitPts:E,duration:T,initSegmentData:S}=c,v=Eu(a,t);if(v&&It(v.method)){const b=this.getDecrypter(),I=er(v.method);if(b.isSync()){let _=b.softwareDecrypt(a,v.key.buffer,v.iv.buffer,I);if(s.part>-1){const k=b.flush();_=k&&k.buffer}if(!_)return r.executeEnd=Qe(),ri(s);a=new Uint8Array(_)}else return this.asyncResult=!0,this.decryptionPromise=b.webCryptoDecrypt(a,v.key.buffer,v.iv.buffer,I).then(_=>{const C=this.push(_,null,s);return this.decryptionPromise=null,C}),this.decryptionPromise}const x=this.needsProbing(h,u);if(x){const b=this.configureTransmuxer(a);if(b)return this.logger.warn(`[transmuxer] ${b.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:b,reason:b.message}),r.executeEnd=Qe(),ri(s)}(h||u||g||x)&&this.resetInitSegment(S,p,y,T,t),(h||g||x)&&this.resetInitialTimestamp(E),l||this.resetContiguity();const D=this.transmux(a,v,f,d,s);this.asyncResult=Wt(D);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=Qe(),D}flush(e){const t=e.transmuxing;t.executeStart=Qe();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const a=[],{timeOffset:o}=i;if(s){const u=s.flush();u&&a.push(this.push(u.buffer,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=Qe();const u=[ri(e)];return this.asyncResult?Promise.resolve(u):u}const h=c.flush(o);return Wt(h)?(this.asyncResult=!0,h.then(u=>(this.flushRemux(a,u,e),a))):(this.flushRemux(a,h,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:a,textTrack:o}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===U.MAIN?"level":"track"} ${s.level}`);const h=this.remuxer.remux(i,r,a,o,l,c,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=Qe()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,s,i,r):a=this.transmuxUnencrypted(e,s,i,r),a}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:a,id3Track:o,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,a,o,c,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let r;for(let u=0,d=Ts.length;u<d;u++){var a;if((a=Ts[u].demux)!=null&&a.probe(e,this.logger)){r=Ts[u];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,c=this.remuxer,l=r.remux,h=r.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(s,t,i,this.logger)),(!o||!(o instanceof h))&&(this.demuxer=new h(s,t,i,this.logger),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 Zi(this.config)),e}}function Eu(n,e){let t=null;return n.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const ri=n=>({remuxResult:{},chunkMeta:n});function Wt(n){return"then"in n&&n.then instanceof Function}class Tu{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class Su{constructor(e,t,s,i,r,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=a}}let bn=0;class xo{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=bn++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=c=>{const l=c.data,h=this.hls;if(!(!h||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var u;const d=(u=this.workerContext)==null?void 0:u.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{h.logger[l.data.logType]&&h.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,h.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const l=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const a=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===m.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new ir,this.observer.on(m.FRAG_DECRYPTED,a),this.observer.on(m.ERROR,a);const o=Kr(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||_h()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=Lh(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=Ih());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:oe(r)})}catch(h){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new Rn(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new Rn(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=bn++;const t=this.hls.config,s=Kr(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:oe(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),Rh(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,r,a,o,c,l,h){var u,d;l.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,p=a?a.start:r.start,y=r.decryptdata,E=this.frag,T=!(E&&r.cc===E.cc),S=!(E&&l.level===E.level),v=E?l.sn-E.sn:-1,x=this.part?l.part-this.part.index:-1,D=v===0&&l.id>1&&l.id===(E==null?void 0:E.stats.chunkCount),A=!S&&(v===1||v===0&&(x===1||D&&x<=0)),b=self.performance.now();(S||v||r.stats.parsing.start===0)&&(r.stats.parsing.start=b),a&&(x||!A)&&(a.stats.parsing.start=b);const I=!(E&&((u=r.initSegment)==null?void 0:u.url)===((d=E.initSegment)==null?void 0:d.url)),_=new Su(T,A,c,S,p,I);if(!A||T||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===U.MAIN?"level":"track"}: ${l.level} id: ${l.id}
105105- discontinuity: ${T}
118118+${t.m3u8}`)}function dg(i,e,t=!0){const r=e.startSN+e.skippedSegments-i.startSN,s=i.fragments,n=r>=0;let a=0;if(n&&r<s.length)a=s[r].start;else if(n&&e.startSN===i.endSN+1)a=i.fragmentEnd;else if(n&&t)a=i.fragmentStart+r*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=i.fragmentStart;else return;Ua(e,a)}function Ua(i,e){if(e){const t=i.fragments;for(let r=i.skippedSegments;r<t.length;r++)t[r].addStart(e);i.fragmentHint&&i.fragmentHint.addStart(e)}}function hg(i,e=1/0){let t=1e3*i.targetduration;if(i.updated){const r=i.fragments;if(r.length&&t*4>e){const n=r[r.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function fg(i,e,t){if(!i)return null;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 Ad(i,e,t){return i?gg(i.partList,e,t):null}function gg(i,e,t){if(i)for(let r=i.length;r--;){const s=i[r];if(s.index===t&&s.fragment.sn===e)return s}return null}function mg(i){i.forEach((e,t)=>{var r;(r=e.details)==null||r.fragments.forEach(s=>{s.level=t,s.initSegment&&(s.initSegment.level=t)})})}function kE(i,e){return i!==e&&e?Id(i)!==Id(e):!1}function Id(i){return i.replace(/\?[^?]*$/,"")}function Pi(i,e){for(let r=0,s=i.length;r<s;r++){var t;if(((t=i[r])==null?void 0:t.cc)===e)return i[r]}return null}function OE(i,e){return!!(i&&e.startCC<i.endCC&&e.endCC>i.startCC)}function Dd(i,e){const t=i.start+e;i.startPTS=t,i.setStart(t),i.endPTS=t+i.duration}function pg(i,e){const t=e.fragments;for(let r=0,s=t.length;r<s;r++)Dd(t[r],i);e.fragmentHint&&Dd(e.fragmentHint,i),e.alignedSliding=!0}function ME(i,e){i&&(yg(e,i),e.alignedSliding||sn(e,i),!e.alignedSliding&&!e.skippedSegments&&dg(i,e,!1))}function yg(i,e){if(!OE(e,i))return;const t=Math.min(e.endCC,i.endCC),r=Pi(e.fragments,t),s=Pi(i.fragments,t);if(!r||!s)return;ne.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const n=r.start-s.start;pg(n,i)}function sn(i,e){if(!i.hasProgramDateTime||!e.hasProgramDateTime)return;const t=i.fragments,r=e.fragments;if(!t.length||!r.length)return;let s,n;const a=Math.min(e.endCC,i.endCC);e.startCC<a&&i.startCC<a&&(s=Pi(r,a),n=Pi(t,a)),(!s||!n)&&(s=r[Math.floor(r.length/2)],n=Pi(t,s.cc)||t[Math.floor(t.length/2)]);const o=s.programDateTime,u=n.programDateTime;if(!o||!u)return;const l=(u-o)/1e3-(n.start-s.start);pg(l,i)}function Ne(i,e,t){$e(i,e,t),i.addEventListener(e,t)}function $e(i,e,t){i.removeEventListener(e,t)}const FE={toString:function(i){let e="";const t=i.length;for(let r=0;r<t;r++)e+=`[${i.start(r).toFixed(3)}-${i.end(r).toFixed(3)}]`;return e}},k={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 Lo extends rg{constructor(e,t,r,s,n){super(s,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=k.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:a,fragCurrent:o,media:u,mediaBuffer:l,state:c}=this,d=u?u.currentTime:0,h=Y.bufferInfo(l||u,d,a.maxBufferHole),f=!h.len;if(this.log(`Media seeking to ${$(d)?d.toFixed(3):d}, state: ${c}, ${f?"out of":"in"} buffer`),this.state===k.ENDED)this.resetLoadingState();else if(o){const g=a.maxFragLookUpTolerance,p=o.start-g,m=o.start+o.duration+g;if(f||m<h.start||p>h.end){const v=d>m;(d<p||v)&&(v&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(u){this.fragmentTracker.removeFragmentsInRange(d,1/0,this.playlistType,!0);const g=this.lastCurrentTime;if(d>g&&(this.lastCurrentTime=d),!this.loadingParts){const p=Math.max(h.end,d),m=this.shouldLoadParts(this.getLevelDetails(),p);m&&(this.log(`LL-Part loading ON after seeking to ${d.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=m)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${d} for seek without enough to start`),this.nextLoadPosition=d,f&&(this.startPosition=d)),f&&this.state===k.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=e,this.fragmentLoader=new cE(e.config),this.keyLoader=r,this.fragmentTracker=t,this.config=e.config,this.decrypter=new xo(e.config)}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===k.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=k.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const r=e.end||0,s=this.config.timelineOffset||0;if(r<=s)return!1;const n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=Y.bufferedInfo(n,e.start,0));const a=e.nextStart;if(a&&a>s&&a<t.edge||this.media.currentTime<e.start)return!1;const u=t.partList;if(u!=null&&u.length){const c=u[u.length-1];return Y.isBuffered(this.media,c.start+c.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const r=this.media=this.mediaBuffer=t.media;Ne(r,"seeking",this.onMediaSeeking),Ne(r,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===k.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(e,t){const r=!!t.transferMedia,s=this.media;if(s!==null){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),$e(s,"seeking",this.onMediaSeeking),$e(s,"ended",this.onMediaEnded),this.keyLoader&&!r&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,r){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=k.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,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)}_loadFragForPlayback(e,t,r){const s=n=>{const a=n.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,!1,n.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,r,s).then(n=>{if(!n)return;const a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===k.FRAG_LOADING||!this.fragCurrent&&a===k.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=k.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(E.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===k.STOPPED||this.state===k.ERROR||(this.warn(`Frag error: ${(n==null?void 0:n.message)||n}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:r}=this;if(r.getState(e)===_e.APPENDING){const n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),u=this.backtrackFragment;((u?e.sn-u.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&r.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===_e.PARTIAL&&r.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,r=null){if(!(e-t))return;const s={startOffset:e,endOffset:t,type:r};this.hls.trigger(E.BUFFER_FLUSHING,s)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(r=>{const s=r==null?void 0:r.frag;if(!s||this.fragContextChanged(s)||!this.levels)throw new Error("init load aborted");return r}).then(r=>{const{hls:s}=this,{frag:n,payload:a}=r,o=n.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&zr(o.method)){const u=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,Io(o.method)).catch(l=>{throw s.trigger(E.ERROR,{type:q.MEDIA_ERROR,details:C.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:n}),l}).then(l=>{const c=self.performance.now();return s.trigger(E.FRAG_DECRYPTED,{frag:n,payload:l,stats:{tstart:u,tdecrypt:c}}),r.payload=l,this.completeInitSegmentLoad(r)})}return this.completeInitSegmentLoad(r)}).catch(r=>{this.state===k.STOPPED||this.state===k.ERROR||(this.warn(r),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const r=e.frag.stats;this.state!==k.STOPPED&&(this.state=k.IDLE),e.frag.data=new Uint8Array(e.payload),r.parsing.start=r.buffering.start=self.performance.now(),r.parsing.end=r.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var r,s;const n=e.tracks;if(n&&!t.encrypted&&((r=n.audio)!=null&&r.encrypted||(s=n.video)!=null&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(E.ERROR,{type:q.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${r?FE.toString(Y.getBuffered(r)):"(detached)"})`),me(e)){var s;if(e.type!==V.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=k.IDLE;return}}const n=(s=this.levels)==null?void 0:s[e.level];n!=null&&n.fragmentError&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0)}this.state=k.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:r,part:s,partsLoaded:n}=e,a=!n||n.length===0||n.some(u=>!u),o=new Ao(r.level,r.sn,r.stats.chunkCount+1,0,s?s.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,r=null,s){var n;this.fragCurrent=e;const a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((n=e.decryptdata)!=null&&n.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=k.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(E.KEY_LOADED,h),this.state===k.KEY_LOADING&&(this.state=k.IDLE),h}),this.hls.trigger(E.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const u=this.fragPrevious;if(me(e)&&(!u||e.sn!==u.sn)){const h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${u==null?void 0:u.sn}->${e.sn}`),this.loadingParts=h)}if(r=Math.max(e.start,r||0),this.loadingParts&&me(e)){const h=a.partList;if(h&&s){r>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const f=this.getNextPart(h,e,r);if(f>-1){const g=h[f];e=this.fragCurrent=g.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${g.index} (${f}/${h.length-1}) of ${this.fragInfo(e,!1,g)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=g.start+g.duration,this.state=k.FRAG_LOADING;let p;return o?p=o.then(m=>!m||this.fragContextChanged(m.frag)?null:this.doFragPartsLoad(e,g,t,s)).catch(m=>this.handleFragLoadError(m)):p=this.doFragPartsLoad(e,g,t,s).catch(m=>this.handleFragLoadError(m)),this.hls.trigger(E.FRAG_LOADING,{frag:e,part:g,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(h,r))return Promise.resolve(null)}}if(me(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${r.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=a.partList)==null?void 0:l.filter(h=>h.loaded).map(h=>`[${h.start}-${h.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(r.toFixed(3))}`),$(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=k.FRAG_LOADING;const c=this.config.progressive&&e.type!==V.SUBTITLE;let d;return c&&o?d=o.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,s)).catch(h=>this.handleFragLoadError(h)):d=Promise.all([this.fragmentLoader.load(e,c?s:void 0),o]).then(([h])=>(!c&&s&&s(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(E.FRAG_LOADING,{frag:e,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(e,t,r,s){return new Promise((n,a)=>{var o;const u=[],l=(o=r.details)==null?void 0:o.partList,c=d=>{this.fragmentLoader.loadPart(e,d,s).then(h=>{u[d.index]=h;const f=h.part;this.hls.trigger(E.FRAG_LOADED,h);const g=Ad(r.details,e.sn,d.index+1)||gg(l,e.sn,d.index+1);if(g)c(g);else return n({frag:e,part:f,partsLoaded:u})}).catch(a)};c(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===C.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===q.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(E.ERROR,t)}else this.hls.trigger(E.ERROR,{type:q.OTHER_ERROR,details:C.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==k.PARSING){!this.fragCurrent&&this.state!==k.STOPPED&&this.state!==k.ERROR&&(this.state=k.IDLE);return}const{frag:r,part:s,level:n}=t,a=self.performance.now();r.stats.parsing.end=a,s&&(s.stats.parsing.end=a);const o=this.getLevelDetails(),l=o&&r.sn>o.endSN||this.shouldLoadParts(o,r.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${r.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(r,s,n,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var r;const n=e.partList[0];if(n.fragment.type===V.SUBTITLE)return!1;const a=n.end+(((r=e.fragmentHint)==null?void 0:r.duration)||0);if(t>=a){var s;if((this.hls.hasEnoughToStart?((s=this.media)==null?void 0:s.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:r}=this,{level:s,sn:n,part:a}=e;if(!(t!=null&&t[s]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const o=t[s],u=o.details,l=a>-1?Ad(u,n,a):null,c=l?l.fragment:fg(u,n,r);return c?(r&&r!==c&&(c.stats=r.stats),{frag:c,part:l,level:o}):null}bufferFragmentData(e,t,r,s,n){if(this.state!==k.PARSING)return;const{data1:a,data2:o}=e;let u=a;if(o&&(u=Je(a,o)),!u.length)return;const l=this.initPTS[t.cc],c=l?-l.baseTime/l.timescale:void 0,d={type:e.type,frag:t,part:r,chunkMeta:s,offset:c,parent:t.type,data:u};if(this.hls.trigger(E.BUFFER_APPENDING,d),e.dropped&&e.independent&&!r){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Y.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const r=t.currentTime,s=Y.bufferInfo(t,r,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,s.end-a),r+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var r;const s=this.getLoadPosition();if(!$(s))return null;const a=this.lastCurrentTime>s||(r=this.media)!=null&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,a)}getFwdBufferInfoAtPos(e,t,r,s){const n=Y.bufferInfo(e,t,s);if(n.len===0&&n.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,r);if(a&&(n.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(n.nextStart,a.end)-t,s);return Y.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){const{config:t}=this;let r;return e?r=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):r=t.maxBufferLength,Math.min(r,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const r=this.config,s=Math.max(Math.min(e-t,r.maxBufferLength),t),n=Math.max(e-t*3,r.maxMaxBufferLength/2,s);return n>=s?(r.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(e,t=V.MAIN){const r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return r&&"fragment"in r?r.fragment:r}getNextFragment(e,t){const r=t.fragments,s=r.length;if(!s)return null;const{config:n}=this,a=r[0].start,o=n.lowLatencyMode&&!!t.partList;let u=null;if(t.live){const d=n.initialLiveManifestSize;if(s<d)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${d})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),u=this.getInitialLiveFragment(t);const h=this.hls.startPosition,f=this.hls.liveSyncPosition,g=u?(h!==-1&&h>=a?h:f)||u.start:e;this.log(`Setting startPosition to ${g} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${f} frag.start: ${(l=u)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=g}}else e<=a&&(u=r[0]);if(!u){const d=this.loadingParts?t.partEnd:t.fragmentEnd;u=this.getFragmentAtPosition(e,d,t)}let c=this.filterReplacedPrimary(u,t);if(!c&&u){const d=u.sn-t.startSN;c=this.filterReplacedPrimary(r[d+1]||null,t)}return this.mapToInitFragWhenRequired(c)}isLoopLoading(e,t){const r=this.fragmentTracker.getState(e);return(r===_e.OK||r===_e.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,r,s,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&r.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,s,0);if(o!==null&&r.len+o.len>=n){const u=a.sn;return this.loopSn!==u&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${u}`),this.loopSn=u),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(Ld(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Ld(this.config)&&e.type!==V.SUBTITLE){const r=this.hls.interstitialsManager,s=r==null?void 0:r.bufferingItem;if(s){const a=s.event;if(a){if(a.appendInPlace||Math.abs(e.start-s.start)>1||s.start===0)return null}else if(e.end<=s.start&&(t==null?void 0:t.live)===!1||e.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||e.start-s.end>1))return null}const n=r==null?void 0:r.playerQueue;if(n)for(let a=n.length;a--;){const o=n[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,r){let s=-1,n=!1,a=!0;for(let o=0,u=e.length;o<u;o++){const l=e[o];if(a=a&&!l.independent,s>-1&&r<l.start)break;const c=l.loaded;c?s=-1:(n||(l.independent||a)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${r} but next unloaded part starts at ${l.start}`),s=o),n=c}return s}loadedEndOfParts(e,t){let r;for(let s=e.length;s--;){if(r=e[s],!r.loaded)return!1;if(t>r.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,r=this.fragPrevious;let s=null;if(r){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`),s=Zv(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const n=r.sn+1;if(n>=e.startSN&&n<=e.endSN){const a=t[n-e.startSN];r.cc===a.cc&&(s=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=Jf(e,r.cc,r.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const n=this.hls.liveSyncPosition;n!==null&&(s=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,r){const{config:s}=this;let{fragPrevious:n}=this,{fragments:a,endSN:o}=r;const{fragmentHint:u}=r,{maxFragLookUpTolerance:l}=s,c=r.partList,d=!!(this.loadingParts&&c!=null&&c.length&&u);d&&!this.bitrateTest&&c[c.length-1].fragment.sn===u.sn&&(a=a.concat(u),o=u.sn);let h;if(e<t){var f;const p=e<this.lastCurrentTime||e>t-l||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:l;h=or(n,a,e,p)}else h=a[a.length-1];if(h){const g=h.sn-r.startSN,p=this.fragmentTracker.getState(h);if((p===_e.OK||p===_e.PARTIAL&&h.gap)&&(n=h),n&&h.sn===n.sn&&(!d||c[0].fragment.sn>h.sn||!r.live)&&h.level===n.level){const v=a[g+1];h.sn<o&&this.fragmentTracker.getState(v)!==_e.OK?h=v:h=null}}return h}alignPlaylists(e,t,r){const s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const n=e.fragmentStart,a=!t,o=e.alignedSliding&&$(n);if(a||!o&&!n){ME(r,e);const u=e.fragmentStart;return this.log(`Live playlist sliding: ${u.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${s}`),u}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let r=this.startPosition;r<t&&(r=-1);const s=this.timelineOffset;if(r===-1){const n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;a!==null&&$(a)?(r=t+a,a<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log(`Setting startPosition to ${r} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=r):e.live?(r=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${r}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=r=0),this.lastCurrentTime=r+s}this.nextLoadPosition=r+s}getLoadPosition(){var e;const{media:t}=this;let r=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&me(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==k.FRAG_LOADING_WAITING_RETRY)&&(this.state=k.IDLE)}onFragmentOrKeyLoadError(e,t){var r;if(t.chunkMeta&&!t.frag){const v=this.getCurrentContext(t.chunkMeta);v&&(t.frag=v.frag)}const s=t.frag;if(!s||s.type!==e||!this.levels)return;if(this.fragContextChanged(s)){var n;this.warn(`Frag load error must match current frag to retry ${s.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}const a=t.details===C.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(s,!0);const o=t.errorAction;if(!o){this.state=k.ERROR;return}const{action:u,flags:l,retryCount:c=0,retryConfig:d}=o,h=!!d,f=h&&u===Ae.RetryRequest,g=h&&!o.resolved&&l===qe.MoveAllAlternatesMatchingHost,p=(r=this.hls.latestLevelDetails)==null?void 0:r.live;if(!f&&g&&me(s)&&!s.endList&&p&&!tg(t))this.resetFragmentErrors(e),this.treatAsGap(s),o.resolved=!0;else if((f||g)&&c<d.maxNumRetry){var m;const v=Ma((m=t.response)==null?void 0:m.code),y=bo(d,c);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+y,this.state=k.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,v){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${c+1}/${d.maxNumRetry} in ${y}ms`)}else if(d)if(this.resetFragmentErrors(e),c<d.maxNumRetry)!a&&u!==Ae.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${c})`);return}else u===Ae.SendAlternateToPenaltyBox?this.state=k.WAITING_LEVEL:this.state=k.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,r=t===1/0;(!t||e>=t||r&&!Ma(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=k.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===k.PARSING||this.state===k.PARSED){const t=e.frag,r=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,r),n=s&&s.len>.5;n&&this.reduceMaxBufferLength(s.len,(t==null?void 0:t.duration)||10);const a=!n;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${r} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===V.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==k.STOPPED&&(this.state=k.IDLE)}afterBufferFlushed(e,t,r){if(!e)return;const s=Y.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,r),this.state===k.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==k.STOPPED&&(this.state=k.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,r,s){const n=r.details;if(!n){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((u,l)=>{const c=e.elementaryStreams[l];if(c){const d=c.endPTS-c.startPTS;if(d<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${d})`),u||!1;const h=s?0:cg(n,e,c.startPTS,c.endPTS,c.startDTS,c.endDTS,this);return this.hls.trigger(E.LEVEL_PTS_UPDATED,{details:n,level:r,drift:h,type:l,frag:e,start:c.startPTS,end:c.endPTS}),!0}return u},!1)){var o;const u=((o=this.transmuxer)==null?void 0:o.error)===null;if((r.fragmentError===0||u&&(r.fragmentError<2||e.endList))&&this.treatAsGap(e,r),u){const l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(E.ERROR,{type:q.MEDIA_ERROR,details:C.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=k.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(E.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===V.MAIN?"level":"track"}fragInfo(e,t=!0,r){var s,n;return`${this.playlistLabel()} ${e.level} (${r?"part":"frag"}:[${((s=t&&!r?e.startPTS:(r||e).start)!=null?s:NaN).toFixed(3)}-${((n=t&&!r?e.endPTS:(r||e).end)!=null?n:NaN).toFixed(3)}]${r&&e.type==="main"?"INDEPENDENT="+(r.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function Ld(i){return!!i.interstitialsController&&i.enableInterstitialPlayback!==!1}class vg{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let r;if(e.length)e.length===1?r=e[0]:r=NE(e,t);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}}function NE(i,e){const t=new Uint8Array(e);let r=0;for(let s=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}var na={exports:{}},Rd;function BE(){return Rd||(Rd=1,function(i){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function s(u,l,c){this.fn=u,this.context=l,this.once=c||!1}function n(u,l,c,d,h){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new s(c,d||u,h),g=t?t+l:l;return u._events[g]?u._events[g].fn?u._events[g]=[u._events[g],f]:u._events[g].push(f):(u._events[g]=f,u._eventsCount++),u}function a(u,l){--u._eventsCount===0?u._events=new r:delete u._events[l]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],c,d;if(this._eventsCount===0)return l;for(d in c=this._events)e.call(c,d)&&l.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},o.prototype.listeners=function(l){var c=t?t+l:l,d=this._events[c];if(!d)return[];if(d.fn)return[d.fn];for(var h=0,f=d.length,g=new Array(f);h<f;h++)g[h]=d[h].fn;return g},o.prototype.listenerCount=function(l){var c=t?t+l:l,d=this._events[c];return d?d.fn?1:d.length:0},o.prototype.emit=function(l,c,d,h,f,g){var p=t?t+l:l;if(!this._events[p])return!1;var m=this._events[p],v=arguments.length,y,S;if(m.fn){switch(m.once&&this.removeListener(l,m.fn,void 0,!0),v){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,c),!0;case 3:return m.fn.call(m.context,c,d),!0;case 4:return m.fn.call(m.context,c,d,h),!0;case 5:return m.fn.call(m.context,c,d,h,f),!0;case 6:return m.fn.call(m.context,c,d,h,f,g),!0}for(S=1,y=new Array(v-1);S<v;S++)y[S-1]=arguments[S];m.fn.apply(m.context,y)}else{var _=m.length,T;for(S=0;S<_;S++)switch(m[S].once&&this.removeListener(l,m[S].fn,void 0,!0),v){case 1:m[S].fn.call(m[S].context);break;case 2:m[S].fn.call(m[S].context,c);break;case 3:m[S].fn.call(m[S].context,c,d);break;case 4:m[S].fn.call(m[S].context,c,d,h);break;default:if(!y)for(T=1,y=new Array(v-1);T<v;T++)y[T-1]=arguments[T];m[S].fn.apply(m[S].context,y)}}return!0},o.prototype.on=function(l,c,d){return n(this,l,c,d,!1)},o.prototype.once=function(l,c,d){return n(this,l,c,d,!0)},o.prototype.removeListener=function(l,c,d,h){var f=t?t+l:l;if(!this._events[f])return this;if(!c)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===c&&(!h||g.once)&&(!d||g.context===d)&&a(this,f);else{for(var p=0,m=[],v=g.length;p<v;p++)(g[p].fn!==c||h&&!g[p].once||d&&g[p].context!==d)&&m.push(g[p]);m.length?this._events[f]=m.length===1?m[0]:m:a(this,f)}return this},o.prototype.removeAllListeners=function(l){var c;return l?(c=t?t+l:l,this._events[c]&&a(this,c)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,i.exports=o}(na)),na.exports}var UE=BE(),Ro=cv(UE);const $i="1.6.15",ti={};function $E(){return typeof __HLS_WORKER_BUNDLE__=="function"}function jE(){const i=ti[$i];if(i)return i.clientCount++,i;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),s={worker:new self.Worker(t),objectURL:t,clientCount:1};return ti[$i]=s,s}function GE(i){const e=ti[i];if(e)return e.clientCount++,e;const t=new self.URL(i,self.location.href).href,s={worker:new self.Worker(t),scriptURL:t,clientCount:1};return ti[i]=s,s}function VE(i){const e=ti[i||$i];if(e&&e.clientCount--===1){const{worker:r,objectURL:s}=e;delete ti[i||$i],s&&self.URL.revokeObjectURL(s),r.terminate()}}function Eg(i,e){return e+10<=i.length&&i[e]===51&&i[e+1]===68&&i[e+2]===73&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function Co(i,e){return e+10<=i.length&&i[e]===73&&i[e+1]===68&&i[e+2]===51&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function pn(i,e){let t=0;return t=(i[e]&127)<<21,t|=(i[e+1]&127)<<14,t|=(i[e+2]&127)<<7,t|=i[e+3]&127,t}function ji(i,e){const t=e;let r=0;for(;Co(i,e);){r+=10;const s=pn(i,e+6);r+=s,Eg(i,e+10)&&(r+=10),e+=r}if(r>0)return i.subarray(t,t+r)}function KE(i,e,t,r){const s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[t+2],a=n>>2&15;if(a>12){const f=new Error(`invalid ADTS sampling index:${a}`);i.emit(E.ERROR,E.ERROR,{type:q.MEDIA_ERROR,details:C.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(n>>6&3)+1,u=e[t+3]>>6&3|(n&1)<<2,l="mp4a.40."+o,c=s[a];let d=a;(o===5||o===29)&&(d-=3);const h=[o<<3|(d&14)>>1,(d&1)<<7|u<<3];return ne.log(`manifest codec:${r}, parsed codec:${l}, channels:${u}, rate:${c} (ADTS object type:${o} sampling index:${a})`),{config:h,samplerate:c,channelCount:u,codec:l,parsedCodec:l,manifestCodec:r}}function Sg(i,e){return i[e]===255&&(i[e+1]&246)===240}function _g(i,e){return i[e+1]&1?7:9}function wo(i,e){return(i[e+3]&3)<<11|i[e+4]<<3|(i[e+5]&224)>>>5}function qE(i,e){return e+5<i.length}function nn(i,e){return e+1<i.length&&Sg(i,e)}function HE(i,e){return qE(i,e)&&Sg(i,e)&&wo(i,e)<=i.length-e}function WE(i,e){if(nn(i,e)){const t=_g(i,e);if(e+t>=i.length)return!1;const r=wo(i,e);if(r<=t)return!1;const s=e+r;return s===i.length||nn(i,s)}return!1}function Tg(i,e,t,r,s){if(!i.samplerate){const n=KE(e,t,r,s);if(!n)return;ae(i,n)}}function bg(i){return 1024*9e4/i}function zE(i,e){const t=_g(i,e);if(e+t<=i.length){const r=wo(i,e)-t;if(r>0)return{headerLength:t,frameLength:r}}}function xg(i,e,t,r,s){const n=bg(i.samplerate),a=r+s*n,o=zE(e,t);let u;if(o){const{frameLength:d,headerLength:h}=o,f=h+d,g=Math.max(0,t+f-e.length);g?(u=new Uint8Array(f-h),u.set(e.subarray(t+h,e.length),0)):u=e.subarray(t+h,t+f);const p={unit:u,pts:a};return g||i.samples.push(p),{sample:p,length:f,missing:g}}const l=e.length-t;return u=new Uint8Array(l),u.set(e.subarray(t,e.length),0),{sample:{unit:u,pts:a},length:l,missing:-1}}function YE(i,e){return Co(i,e)&&pn(i,e+6)+10<=i.length-e}function XE(i){return i instanceof ArrayBuffer?i:i.byteOffset==0&&i.byteLength==i.buffer.byteLength?i.buffer:new Uint8Array(i).buffer}function aa(i,e=0,t=1/0){return QE(i,e,t,Uint8Array)}function QE(i,e,t,r){const s=ZE(i);let n=1;"BYTES_PER_ELEMENT"in r&&(n=r.BYTES_PER_ELEMENT);const a=JE(i)?i.byteOffset:0,o=(a+i.byteLength)/n,u=(a+e)/n,l=Math.floor(Math.max(0,Math.min(u,o))),c=Math.floor(Math.min(l+Math.max(t,0),o));return new r(s,l,c-l)}function ZE(i){return i instanceof ArrayBuffer?i:i.buffer}function JE(i){return i&&i.buffer instanceof ArrayBuffer&&i.byteLength!==void 0&&i.byteOffset!==void 0}function eS(i){const e={key:i.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(i.size<2)return;if(i.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const r=i.data.subarray(1).indexOf(0);if(r===-1)return;const s=Ye(aa(i.data,1,r)),n=i.data[2+r],a=i.data.subarray(3+r).indexOf(0);if(a===-1)return;const o=Ye(aa(i.data,3+r,a));let u;return s==="-->"?u=Ye(aa(i.data,4+r+a)):u=XE(i.data.subarray(4+r+a)),e.mimeType=s,e.pictureType=n,e.description=o,e.data=u,e}function tS(i){if(i.size<2)return;const e=Ye(i.data,!0),t=new Uint8Array(i.data.subarray(e.length+1));return{key:i.type,info:e,data:t.buffer}}function rS(i){if(i.size<2)return;if(i.type==="TXXX"){let t=1;const r=Ye(i.data.subarray(t),!0);t+=r.length+1;const s=Ye(i.data.subarray(t));return{key:i.type,info:r,data:s}}const e=Ye(i.data.subarray(1));return{key:i.type,info:"",data:e}}function iS(i){if(i.type==="WXXX"){if(i.size<2)return;let t=1;const r=Ye(i.data.subarray(t),!0);t+=r.length+1;const s=Ye(i.data.subarray(t));return{key:i.type,info:r,data:s}}const e=Ye(i.data);return{key:i.type,info:"",data:e}}function sS(i){return i.type==="PRIV"?tS(i):i.type[0]==="W"?iS(i):i.type==="APIC"?eS(i):rS(i)}function nS(i){const e=String.fromCharCode(i[0],i[1],i[2],i[3]),t=pn(i,4),r=10;return{type:e,size:t,data:i.subarray(r,r+t)}}const ps=10,aS=10;function Ag(i){let e=0;const t=[];for(;Co(i,e);){const r=pn(i,e+6);i[e+5]>>6&1&&(e+=ps),e+=ps;const s=e+r;for(;e+aS<s;){const n=nS(i.subarray(e)),a=sS(n);a&&t.push(a),e+=n.size+ps}Eg(i,e)&&(e+=ps)}return t}function Ig(i){return i&&i.key==="PRIV"&&i.info==="com.apple.streaming.transportStreamTimestamp"}function oS(i){if(i.data.byteLength===8){const e=new Uint8Array(i.data),t=e[3]&1;let r=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return r/=45,t&&(r+=4772185884e-2),Math.round(r)}}function Po(i){const e=Ag(i);for(let t=0;t<e.length;t++){const r=e[t];if(Ig(r))return oS(r)}}let We=function(i){return i.audioId3="org.id3",i.dateRange="com.apple.quicktime.HLS",i.emsg="https://aomedia.org/emsg/ID3",i.misbklv="urn:misb:KLV:bin:1910.1",i}({});function ct(i="",e=9e4){return{type:i,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class ko{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,r,s){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,r){}demux(e,t){this.cachedData&&(e=Je(this.cachedData,e),this.cachedData=null);let r=ji(e,0),s=r?r.length:0,n;const a=this._audioTrack,o=this._id3Track,u=r?Po(r):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&$(u))&&(this.basePTS=lS(u,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),r&&r.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:We.audioId3,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(e,s)){const c=this.appendFrame(a,e,s);c?(this.frameIndex++,this.lastPTS=c.sample.pts,s+=c.length,n=s):s=l}else YE(e,s)?(r=ji(e,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:We.audioId3,duration:Number.POSITIVE_INFINITY}),s+=r.length,n=s):s++;if(s===l&&n!==l){const c=e.slice(n);this.cachedData?this.cachedData=Je(this.cachedData,c):this.cachedData=c}}return{audioTrack:a,videoTrack:ct(),id3Track:o,textTrack:ct()}}demuxSampleAes(e,t,r){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:ct(),id3Track:this._id3Track,textTrack:ct()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const lS=(i,e,t)=>{if($(i))return i*90;const r=t?t.baseTime*9e4/t.timescale:0;return e*9e4+r};let ys=null;const uS=[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],cS=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],dS=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],hS=[0,1,1,4];function Dg(i,e,t,r,s){if(t+24>e.length)return;const n=Lg(e,t);if(n&&t+n.frameLength<=e.length){const a=n.samplesPerFrame*9e4/n.sampleRate,o=r+s*a,u={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return i.config=[],i.channelCount=n.channelCount,i.samplerate=n.sampleRate,i.samples.push(u),{sample:u,length:n.frameLength,missing:0}}}function Lg(i,e){const t=i[e+1]>>3&3,r=i[e+1]>>1&3,s=i[e+2]>>4&15,n=i[e+2]>>2&3;if(t!==1&&s!==0&&s!==15&&n!==3){const a=i[e+2]>>1&1,o=i[e+3]>>6,u=t===3?3-r:r===3?3:4,l=uS[u*14+s-1]*1e3,d=cS[(t===3?0:t===2?1:2)*3+n],h=o===3?1:2,f=dS[t][r],g=hS[r],p=f*8*g,m=Math.floor(f*l/d+a)*g;if(ys===null){const S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ys=S?parseInt(S[1]):0}return!!ys&&ys<=87&&r===2&&l>=224e3&&o===0&&(i[e+3]=i[e+3]|128),{sampleRate:d,channelCount:h,frameLength:m,samplesPerFrame:p}}}function Oo(i,e){return i[e]===255&&(i[e+1]&224)===224&&(i[e+1]&6)!==0}function Rg(i,e){return e+1<i.length&&Oo(i,e)}function fS(i,e){return Oo(i,e)&&4<=i.length-e}function Cg(i,e){if(e+1<i.length&&Oo(i,e)){const r=Lg(i,e);let s=4;r!=null&&r.frameLength&&(s=r.frameLength);const n=e+s;return n===i.length||Rg(i,n)}return!1}class gS extends ko{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,r,s){super.resetInitSegment(e,t,r,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const r=ji(e,0);let s=(r==null?void 0:r.length)||0;if(Cg(e,s))return!1;for(let n=e.length;s<n;s++)if(WE(e,s))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return HE(e,t)}appendFrame(e,t,r){Tg(e,this.observer,t,r,e.manifestCodec);const s=xg(e,t,r,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}}const wg=(i,e)=>{let t=0,r=5;e+=r;const s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;r>0;){a[0]=i[e];const o=Math.min(r,8),u=8-o;n[0]=4278190080>>>24+u<<u,s[0]=(a[0]&n[0])>>u,t=t?t<<o|s[0]:s[0],e+=1,r-=o}return t};class mS extends ko{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,r,s){super.resetInitSegment(e,t,r,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,r){const s=Pg(e,t,r,this.basePTS,this.frameIndex);if(s!==-1)return{sample:e.samples[e.samples.length-1],length:s,missing:0}}static probe(e){if(!e)return!1;const t=ji(e,0);if(!t)return!1;const r=t.length;return e[r]===11&&e[r+1]===119&&Po(t)!==void 0&&wg(e,r)<16}}function Pg(i,e,t,r,s){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],u=e[t+4]&63,c=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][u*3+n]*2;if(t+c>e.length)return-1;const d=e[t+6]>>5;let h=0;d===2?h+=2:(d&1&&d!==1&&(h+=2),d&4&&(h+=2));const f=(e[t+6]<<8|e[t+7])>>12-h&1,p=[2,1,2,3,3,4,4,5][d]+f,m=e[t+5]>>3,v=e[t+5]&7,y=new Uint8Array([n<<6|m<<1|v>>2,(v&3)<<6|d<<3|f<<2|u>>4,u<<4&224]),S=1536/o*9e4,_=r+s*S,T=e.subarray(t,t+c);return i.config=y,i.channelCount=p,i.samplerate=o,i.samples.push({unit:T,pts:_}),c}class pS extends ko{resetInitSegment(e,t,r,s){super.resetInitSegment(e,t,r,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=ji(e,0);let r=(t==null?void 0:t.length)||0;if(t&&e[r]===11&&e[r+1]===119&&Po(t)!==void 0&&wg(e,r)<=16)return!1;for(let s=e.length;r<s;r++)if(Cg(e,r))return ne.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return fS(e,t)}appendFrame(e,t,r){if(this.basePTS!==null)return Dg(e,t,r,this.basePTS,this.frameIndex)}}const yS=/\/emsg[-/]ID3/i;class vS{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,r,s){const n=this.videoTrack=ct("video",1),a=this.audioTrack=ct("audio",1),o=this.txtTrack=ct("text",1);if(this.id3Track=ct("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const u=Gf(e);if(u.video){const{id:l,timescale:c,codec:d,supplemental:h}=u.video;n.id=l,n.timescale=o.timescale=c,n.codec=d,n.supplemental=h}if(u.audio){const{id:l,timescale:c,codec:d}=u.audio;a.id=l,a.timescale=c,a.codec=d}o.id=Uf.text,n.sampleDuration=0,n.duration=a.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return mv(e)}demux(e,t){this.timeOffset=t;let r=e;const s=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=Je(this.remainderData,e));const o=Tv(r);this.remainderData=o.remainder,s.samples=o.valid||new Uint8Array}else s.samples=r;const a=this.extractID3Track(s,t);return n.samples=Wc(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(t,this.timeOffset);return r.samples=Wc(e,t),{videoTrack:t,audioTrack:ct(),id3Track:s,textTrack:ct()}}extractID3Track(e,t){const r=this.id3Track;if(e.samples.length){const s=Z(e.samples,["emsg"]);s&&s.forEach(n=>{const a=xv(n);if(yS.test(a.schemeIdUri)){const o=Cd(a,t);let u=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;u<=.001&&(u=Number.POSITIVE_INFINITY);const l=a.payload;r.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:We.emsg,duration:u})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=Cd(a,t);r.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:We.misbklv,duration:Number.POSITIVE_INFINITY})}})}return r}demuxSampleAes(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function Cd(i,e){return $(i.presentationTime)?i.presentationTime/i.timeScale:e+i.presentationTimeDelta/i.timeScale}class ES{constructor(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new xo(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Mt.cbc)}decryptAacSample(e,t,r){const s=e[t].unit;if(s.length<=16)return;const n=s.subarray(16,s.length-s.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{const u=new Uint8Array(o);s.set(u,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,r)}).catch(r)}decryptAacSamples(e,t,r){for(;;t++){if(t>=e.length){r();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,r=new Int8Array(t);let s=0;for(let n=32;n<e.length-16;n+=160,s+=16)r.set(e.subarray(n,n+16),s);return r}getAvcDecryptedUnit(e,t){const r=new Uint8Array(t);let s=0;for(let n=32;n<e.length-16;n+=160,s+=16)e.set(r.subarray(s,s+16),n);return e}decryptAvcSample(e,t,r,s,n){const a=qf(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(u=>{n.data=this.getAvcDecryptedUnit(a,u),this.decrypter.isSync()||this.decryptAvcSamples(e,t,r+1,s)}).catch(s)}decryptAvcSamples(e,t,r,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length){s();return}const n=e[t].units;for(;!(r>=n.length);r++){const a=n[r];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,r,s,a),!this.decrypter.isSync()))return}}}}class kg{constructor(){this.VideoSample=null}createVideoSample(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}}getLastNalUnit(e){var t;let r=this.VideoSample,s;if((!r||r.units.length===0)&&(r=e[e.length-1]),(t=r)!=null&&t.units){const n=r.units;s=n[n.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const r=t.samples,s=r.length;if(s){const n=r[s-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,r){const s=t.byteLength;let n=e.naluState||0;const a=n,o=[];let u=0,l,c,d,h=-1,f=0;for(n===-1&&(h=0,f=this.getNALuType(t,0),n=0,u=1);u<s;){if(l=t[u++],!n){n=l?0:1;continue}if(n===1){n=l?0:2;continue}if(!l)n=3;else if(l===1){if(c=u-n-1,h>=0){const g={data:t.subarray(h,c),type:f};o.push(g)}else{const g=this.getLastNalUnit(e.samples);g&&(a&&u<=4-a&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-a)),c>0&&(g.data=Je(g.data,t.subarray(0,c)),g.state=0))}u<s?(d=this.getNALuType(t,u),h=u,f=d,n=0):n=-1}else n=0}if(h>=0&&n>=0){const g={data:t.subarray(h,s),type:f,state:n};o.push(g)}if(o.length===0){const g=this.getLastNalUnit(e.samples);g&&(g.data=Je(g.data,t))}return e.naluState=n,o}}class ki{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,r=e.byteLength-t,s=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");s.set(e.subarray(r,r+n)),this.word=new DataView(s.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 r=this.word>>>32-t;if(e>32&&ne.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?r<<t|this.readBits(t):r}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)}}class SS extends kg{parsePES(e,t,r,s){const n=this.parseNALu(e,r.data,s);let a=this.VideoSample,o,u=!1;r.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),n.forEach(l=>{var c,d;switch(l.type){case 1:{let p=!1;o=!0;const m=l.data;if(u&&m.length>4){const v=this.readSliceType(m);(v===2||v===4||v===7||v===9)&&(p=!0)}if(p){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.frame=!0,a.key=p;break}case 5:o=!0,(c=a)!=null&&c.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,So(l.data,1,r.pts,t.samples);break}case 7:{var f,g;o=!0,u=!0;const p=l.data,m=this.readSPS(p);if(!e.sps||e.width!==m.width||e.height!==m.height||((f=e.pixelRatio)==null?void 0:f[0])!==m.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[1])!==m.pixelRatio[1]){e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.sps=[p];const v=p.subarray(1,4);let y="avc1.";for(let S=0;S<3;S++){let _=v[S].toString(16);_.length<2&&(_="0"+_),y+=_}e.codec=y}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(d=a)!=null&&d.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(l)}),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new ki(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let r=8,s=8,n;for(let a=0;a<e;a++)s!==0&&(n=t.readEG(),s=(r+n+256)%256),r=s===0?r:s}readSPS(e){const t=new ki(e);let r=0,s=0,n=0,a=0,o,u,l;const c=t.readUByte.bind(t),d=t.readBits.bind(t),h=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),p=t.skipEG.bind(t),m=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);c();const y=c();if(d(5),g(3),c(),m(),y===100||y===110||y===122||y===244||y===44||y===83||y===86||y===118||y===128){const I=h();if(I===3&&g(1),m(),m(),g(1),f())for(u=I!==3?8:12,l=0;l<u;l++)f()&&(l<6?v(16,t):v(64,t))}m();const S=h();if(S===0)h();else if(S===1)for(g(1),p(),p(),o=h(),l=0;l<o;l++)p();m(),g(1);const _=h(),T=h(),x=d(1);x===0&&g(1),g(1),f()&&(r=h(),s=h(),n=h(),a=h());let b=[1,1];if(f()&&f())switch(c()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:{b=[c()<<8|c(),c()<<8|c()];break}}return{width:Math.ceil((_+1)*16-r*2-s*2),height:(2-x)*(T+1)*16-(x?2:4)*(n+a),pixelRatio:b}}}class _S extends kg{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,r,s){const n=this.parseNALu(e,r.data,s);let a=this.VideoSample,o,u=!1;r.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),n.forEach(l=>{var c,d;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,u){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(c=a)!=null&&c.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.key=!0,a.frame=!0;break;case 39:o=!0,So(l.data,2,r.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ae(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(o=!0,u=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const f=this.readSPS(l.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const g in f.params)e.params[g]=f.params[g]}this.pushParameterSet(e.sps,l.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const f=this.readPPS(l.data);for(const g in f)e.params[g]=f[g]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(d=a)!=null&&d.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;default:o=!1;break}a&&o&&a.units.push(l)}),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let r=0;for(let s=0;s<e.byteLength;s++)s>=2&&e[s]===3&&e[s-1]===0&&e[s-2]===0||(t[r]=e[s],r++);return new Uint8Array(t.buffer,0,r)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new ki(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const r=t.readBits(3),s=t.readBoolean();return{numTemporalLayers:r+1,temporalIdNested:s}}readSPS(e){const t=new ki(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const r=t.readBits(3);t.readBoolean();const s=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),u=t.readUByte(),l=t.readUByte(),c=t.readUByte(),d=t.readUByte(),h=t.readUByte(),f=t.readUByte(),g=t.readUByte(),p=t.readUByte(),m=t.readUByte(),v=t.readUByte(),y=[],S=[];for(let re=0;re<r;re++)y.push(t.readBoolean()),S.push(t.readBoolean());if(r>0)for(let re=r;re<8;re++)t.readBits(2);for(let re=0;re<r;re++)y[re]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),S[re]&&t.readUByte();t.readUEG();const _=t.readUEG();_==3&&t.skipBits(1);const T=t.readUEG(),x=t.readUEG(),b=t.readBoolean();let I=0,A=0,D=0,L=0;b&&(I+=t.readUEG(),A+=t.readUEG(),D+=t.readUEG(),L+=t.readUEG());const P=t.readUEG(),O=t.readUEG(),G=t.readUEG(),j=t.readBoolean();for(let re=j?0:r;re<=r;re++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let Ce=0;Ce<4;Ce++)for(let Qe=0;Qe<(Ce===3?2:6);Qe++)if(!t.readBoolean())t.readUEG();else{const tt=Math.min(64,1<<4+(Ce<<1));Ce>1&&t.readEG();for(let lr=0;lr<tt;lr++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const F=t.readUEG();let K=0;for(let re=0;re<F;re++){let Ce=!1;if(re!==0&&(Ce=t.readBoolean()),Ce){re===F&&t.readUEG(),t.readBoolean(),t.readUEG();let Qe=0;for(let Nt=0;Nt<=K;Nt++){const tt=t.readBoolean();let lr=!1;tt||(lr=t.readBoolean()),(tt||lr)&&Qe++}K=Qe}else{const Qe=t.readUEG(),Nt=t.readUEG();K=Qe+Nt;for(let tt=0;tt<Qe;tt++)t.readUEG(),t.readBoolean();for(let tt=0;tt<Nt;tt++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const re=t.readUEG();for(let Ce=0;Ce<re;Ce++){for(let Qe=0;Qe<G+4;Qe++)t.readBits(1);t.readBits(1)}}let N=0,B=1,X=1,ie=!0,Q=1,ee=0;t.readBoolean(),t.readBoolean();let Re=!1;if(t.readBoolean()){if(t.readBoolean()){const Bt=t.readUByte(),Go=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],zi=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Bt>0&&Bt<16?(B=Go[Bt-1],X=zi[Bt-1]):Bt===255&&(B=t.readBits(16),X=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),Re=t.readBoolean(),Re&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(Q=t.readBits(32),ee=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const zi=t.readBoolean(),Vo=t.readBoolean();let ni=!1;(zi||Vo)&&(ni=t.readBoolean(),ni&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),ni&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Ko=0;Ko<=r;Ko++){ie=t.readBoolean();const fm=ie||t.readBoolean();let qo=!1;fm?t.readEG():qo=t.readBoolean();const Ho=qo?1:t.readUEG()+1;if(zi)for(let ai=0;ai<Ho;ai++)t.readUEG(),t.readUEG(),ni&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Vo)for(let ai=0;ai<Ho;ai++)t.readUEG(),t.readUEG(),ni&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),N=t.readUEG())}let Xe=T,at=x;if(b){let re=1,Ce=1;_===1?re=Ce=2:_==2&&(re=2),Xe=T-re*A-re*I,at=x-Ce*L-Ce*D}const Ft=s?["A","B","C"][s]:"",hm=o<<24|u<<16|l<<8|c;let vn=0;for(let re=0;re<32;re++)vn=(vn|(hm>>re&1)<<31-re)>>>0;let En=vn.toString(16);return a===1&&En==="2"&&(En="6"),{codecString:`hvc1.${Ft}${a}.${En}.${n?"H":"L"}${v}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:s,general_profile_compatibility_flags:[o,u,l,c],general_constraint_indicator_flags:[d,h,f,g,p,m],general_level_idc:v,bit_depth:P+8,bit_depth_luma_minus8:P,bit_depth_chroma_minus8:O,min_spatial_segmentation_idc:N,chroma_format_idc:_,frame_rate:{fixed:ie,fps:ee/Q}},width:Xe,height:at,pixelRatio:[B,X]}}readPPS(e){const t=new ki(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const s=t.readBoolean(),n=t.readBoolean();let a=1;return n&&s?a=0:n?a=3:s&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Te=188;class Pt{constructor(e,t,r,s){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=r,this.logger=s,this.videoParser=null}static probe(e,t){const r=Pt.syncOffset(e);return r>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),r!==-1}static syncOffset(e){const t=e.length;let r=Math.min(Te*5,t-Te)+1,s=0;for(;s<r;){let n=!1,a=-1,o=0;for(let u=s;u<t;u+=Te)if(e[u]===71&&(t-u===Te||e[u+Te]===71)){if(o++,a===-1&&(a=u,a!==0&&(r=Math.min(a+Te*99,e.length-Te)+1)),n||(n=$a(e,u)===0),n&&o>1&&(a===0&&o>2||u+Te>r))return a}else{if(o)return-1;break}s++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Uf[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,r,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Pt.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=Pt.createTrack("audio",s),this._id3Track=Pt.createTrack("id3"),this._txtTrack=Pt.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:r}=this;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,r=!1,s=!1){r||(this.sampleAes=null);let n;const a=this._videoTrack,o=this._audioTrack,u=this._id3Track,l=this._txtTrack;let c=a.pid,d=a.pesData,h=o.pid,f=u.pid,g=o.pesData,p=u.pesData,m=null,v=this.pmtParsed,y=this._pmtId,S=e.length;if(this.remainderData&&(e=Je(this.remainderData,e),S=e.length,this.remainderData=null),S<Te&&!s)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:u,textTrack:l};const _=Math.max(0,Pt.syncOffset(e));S-=(S-_)%Te,S<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,S,e.buffer.byteLength-S));let T=0;for(let b=_;b<S;b+=Te)if(e[b]===71){const I=!!(e[b+1]&64),A=$a(e,b),D=(e[b+3]&48)>>4;let L;if(D>1){if(L=b+5+e[b+4],L===b+Te)continue}else L=b+4;switch(A){case c:I&&(d&&(n=Gr(d,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,l,n,!1)),d={data:[],size:0}),d&&(d.data.push(e.subarray(L,b+Te)),d.size+=b+Te-L);break;case h:if(I){if(g&&(n=Gr(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n);break}g={data:[],size:0}}g&&(g.data.push(e.subarray(L,b+Te)),g.size+=b+Te-L);break;case f:I&&(p&&(n=Gr(p,this.logger))&&this.parseID3PES(u,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(L,b+Te)),p.size+=b+Te-L);break;case 0:I&&(L+=e[L]+1),y=this._pmtId=TS(e,L);break;case y:{I&&(L+=e[L]+1);const P=bS(e,L,this.typeSupported,r,this.observer,this.logger);c=P.videoPid,c>0&&(a.pid=c,a.segmentCodec=P.segmentVideoCodec),h=P.audioPid,h>0&&(o.pid=h,o.segmentCodec=P.segmentAudioCodec),f=P.id3Pid,f>0&&(u.pid=f),m!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${b} after unknown PID '${m}'. Backtracking to sync byte @${_} to parse all TS packets.`),m=null,b=_-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=A;break}}else T++;T>0&&ja(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=d,o.pesData=g,u.pesData=p;const x={audioTrack:o,videoTrack:a,id3Track:u,textTrack:l};return s&&this.extractRemainingSamples(x),x}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:r,id3Track:s,textTrack:n}=e,a=r.pesData,o=t.pesData,u=s.pesData;let l;if(a&&(l=Gr(a,this.logger))?(this.readyVideoParser(r.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(r,n,l,!0),r.pesData=null)):r.pesData=a,o&&(l=Gr(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;u&&(l=Gr(u,this.logger))?(this.parseID3PES(s,l),s.pesData=null):s.pesData=u}demuxSampleAes(e,t,r){const s=this.demux(e,r,!0,!this.config.progressive),n=this.sampleAes=new ES(this.observer,this.config,t);return this.decrypt(s,n)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new SS:e==="hevc"&&(this.videoParser=new _S))}decrypt(e,t){return new Promise(r=>{const{audioTrack:s,videoTrack:n}=e;s.samples&&s.segmentCodec==="aac"?t.decryptAacSamples(s.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{r(e)}):r(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{r(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let r=0;const s=this.aacOverFlow;let n=t.data;if(s){this.aacOverFlow=null;const d=s.missing,h=s.sample.unit.byteLength;if(d===-1)n=Je(s.sample.unit,n);else{const f=h-d;s.sample.unit.set(n.subarray(0,d),f),e.samples.push(s.sample),r=s.missing}}let a,o;for(a=r,o=n.length;a<o-1&&!nn(n,a);a++);if(a!==r){let d;const h=a<o-1;if(h?d=`AAC PES did not start with ADTS header,offset:${a}`:d="No ADTS header found in AAC PES",ja(this.observer,new Error(d),h,this.logger),!h)return}Tg(e,this.observer,n,a,this.audioCodec);let u;if(t.pts!==void 0)u=t.pts;else if(s){const d=bg(e.samplerate);u=s.sample.pts+d}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,c;for(;a<o;)if(c=xg(e,n,a,u,l),a+=c.length,c.missing){this.aacOverFlow=c;break}else for(l++;a<o-1&&!nn(n,a);a++);}parseMPEGPES(e,t){const r=t.data,s=r.length;let n=0,a=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<s;)if(Rg(r,a)){const u=Dg(e,r,a,o,n);if(u)a+=u.length,n++;else break}else a++}parseAC3PES(e,t){{const r=t.data,s=t.pts;if(s===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const n=r.length;let a=0,o=0,u;for(;o<n&&(u=Pg(e,r,o,s,a++))>0;)o+=u}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const r=ae({},t,{type:this._videoTrack?We.emsg:We.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}}function $a(i,e){return((i[e+1]&31)<<8)+i[e+2]}function TS(i,e){return(i[e+10]&31)<<8|i[e+11]}function bS(i,e,t,r,s,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(i[e+1]&15)<<8|i[e+2],u=e+3+o-4,l=(i[e+10]&15)<<8|i[e+11];for(e+=12+l;e<u;){const c=$a(i,e),d=(i[e+3]&15)<<8|i[e+4];switch(i[e]){case 207:if(!r){oa("ADTS AAC",n);break}case 15:a.audioPid===-1&&(a.audioPid=c);break;case 21:a.id3Pid===-1&&(a.id3Pid=c);break;case 219:if(!r){oa("H.264",n);break}case 27:a.videoPid===-1&&(a.videoPid=c);break;case 3:case 4:!t.mpeg&&!t.mp3?n.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=c,a.segmentAudioCodec="mp3");break;case 193:if(!r){oa("AC-3",n);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=c,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&d>0){let h=e+5,f=d;for(;f>2;){switch(i[h]){case 106:t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=c,a.segmentAudioCodec="ac3");break}const p=i[h+1]+2;h+=p,f-=p}}break;case 194:case 135:return ja(s,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:a.videoPid===-1&&(a.videoPid=c,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}e+=d+5}return a}function ja(i,e,t,r){r.warn(`parsing error: ${e.message}`),i.emit(E.ERROR,E.ERROR,{type:q.MEDIA_ERROR,details:C.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function oa(i,e){e.log(`${i} with AES-128-CBC encryption found in unencrypted stream`)}function Gr(i,e){let t=0,r,s,n,a,o;const u=i.data;if(!i||i.size===0)return null;for(;u[0].length<19&&u.length>1;)u[0]=Je(u[0],u[1]),u.splice(1,1);if(r=u[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(s=(r[4]<<8)+r[5],s&&s>i.size-6)return null;const c=r[7];c&192&&(a=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,c&64?(o=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=r[8];let d=n+9;if(i.size<=d)return null;i.size-=d;const h=new Uint8Array(i.size);for(let f=0,g=u.length;f<g;f++){r=u[f];let p=r.byteLength;if(d)if(d>p){d-=p;continue}else r=r.subarray(d),p-=d,d=0;h.set(r,t),t+=p}return s&&(s-=n+3),{data:h,pts:a,dts:o,len:s}}return null}class xS{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 Lt=Math.pow(2,32)-1;class R{static init(){R.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in R.types)R.types.hasOwnProperty(e)&&(R.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);R.HDLR_TYPES={video:t,audio:r};const s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);R.STTS=R.STSC=R.STCO=n,R.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),R.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),R.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),R.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),u=new Uint8Array([0,0,0,1]);R.FTYP=R.box(R.types.ftyp,a,u,a,o),R.DINF=R.box(R.types.dinf,R.box(R.types.dref,s))}static box(e,...t){let r=8,s=t.length;const n=s;for(;s--;)r+=t[s].byteLength;const a=new Uint8Array(r);for(a[0]=r>>24&255,a[1]=r>>16&255,a[2]=r>>8&255,a[3]=r&255,a.set(e,4),s=0,r=8;s<n;s++)a.set(t[s],r),r+=t[s].byteLength;return a}static hdlr(e){return R.box(R.types.hdlr,R.HDLR_TYPES[e])}static mdat(e){return R.box(R.types.mdat,e)}static mdhd(e,t){t*=e;const r=Math.floor(t/(Lt+1)),s=Math.floor(t%(Lt+1));return R.box(R.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,r>>24,r>>16&255,r>>8&255,r&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(e){return R.box(R.types.mdia,R.mdhd(e.timescale||0,e.duration||0),R.hdlr(e.type),R.minf(e))}static mfhd(e){return R.box(R.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?R.box(R.types.minf,R.box(R.types.smhd,R.SMHD),R.DINF,R.stbl(e)):R.box(R.types.minf,R.box(R.types.vmhd,R.VMHD),R.DINF,R.stbl(e))}static moof(e,t,r){return R.box(R.types.moof,R.mfhd(e),R.traf(r,t))}static moov(e){let t=e.length;const r=[];for(;t--;)r[t]=R.trak(e[t]);return R.box.apply(null,[R.types.moov,R.mvhd(e[0].timescale||0,e[0].duration||0)].concat(r).concat(R.mvex(e)))}static mvex(e){let t=e.length;const r=[];for(;t--;)r[t]=R.trex(e[t]);return R.box.apply(null,[R.types.mvex,...r])}static mvhd(e,t){t*=e;const r=Math.floor(t/(Lt+1)),s=Math.floor(t%(Lt+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,r>>24,r>>16&255,r>>8&255,r&255,s>>24,s>>16&255,s>>8&255,s&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return R.box(R.types.mvhd,n)}static sdtp(e){const t=e.samples||[],r=new Uint8Array(4+t.length);let s,n;for(s=0;s<t.length;s++)n=t[s].flags,r[s+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return R.box(R.types.sdtp,r)}static stbl(e){return R.box(R.types.stbl,R.stsd(e),R.box(R.types.stts,R.STTS),R.box(R.types.stsc,R.STSC),R.box(R.types.stsz,R.STSZ),R.box(R.types.stco,R.STCO))}static avc1(e){let t=[],r=[],s,n,a;for(s=0;s<e.sps.length;s++)n=e.sps[s],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(s=0;s<e.pps.length;s++)n=e.pps[s],a=n.byteLength,r.push(a>>>8&255),r.push(a&255),r=r.concat(Array.prototype.slice.call(n));const o=R.box(R.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(r))),u=e.width,l=e.height,c=e.pixelRatio[0],d=e.pixelRatio[1];return R.box(R.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,u&255,l>>8&255,l&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,c&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return R.box(R.types.mp4a,R.audioStsd(e),R.box(R.types.esds,R.esds(e)))}static mp3(e){return R.box(R.types[".mp3"],R.audioStsd(e))}static ac3(e){return R.box(R.types["ac-3"],R.audioStsd(e),R.box(R.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return R.box(R.types.stsd,R.STSD,R.mp4a(e));if(t==="ac3"&&e.config)return R.box(R.types.stsd,R.STSD,R.ac3(e));if(t==="mp3"&&e.codec==="mp3")return R.box(R.types.stsd,R.STSD,R.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return R.box(R.types.stsd,R.STSD,R.avc1(e));if(t==="hevc"&&e.vps)return R.box(R.types.stsd,R.STSD,R.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,r=(e.duration||0)*(e.timescale||0),s=e.width||0,n=e.height||0,a=Math.floor(r/(Lt+1)),o=Math.floor(r%(Lt+1));return R.box(R.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,s&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){const r=R.sdtp(e),s=e.id,n=Math.floor(t/(Lt+1)),a=Math.floor(t%(Lt+1));return R.box(R.types.traf,R.box(R.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),R.box(R.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),R.trun(e,r.length+16+20+8+16+8+8),r)}static trak(e){return e.duration=e.duration||4294967295,R.box(R.types.trak,R.tkhd(e),R.mdia(e))}static trex(e){const t=e.id;return R.box(R.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const r=e.samples||[],s=r.length,n=12+16*s,a=new Uint8Array(n);let o,u,l,c,d,h;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<s;o++)u=r[o],l=u.duration,c=u.size,d=u.flags,h=u.cts,a.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*o);return R.box(R.types.trun,a)}static initSegment(e){R.types||R.init();const t=R.moov(e);return Je(R.FTYP,t)}static hvc1(e){const t=e.params,r=[e.vps,e.sps,e.pps],s=4,n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),s-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),r.length]);let a=n.length;for(let g=0;g<r.length;g+=1){a+=3;for(let p=0;p<r[g].length;p+=1)a+=2+r[g][p].length}const o=new Uint8Array(a);o.set(n,0),a=n.length;const u=r.length-1;for(let g=0;g<r.length;g+=1){o.set(new Uint8Array([32+g|(g===u?128:0),0,r[g].length]),a),a+=3;for(let p=0;p<r[g].length;p+=1)o.set(new Uint8Array([r[g][p].length>>8,r[g][p].length&255]),a),a+=2,o.set(r[g][p],a),a+=r[g][p].length}const l=R.box(R.types.hvcC,o),c=e.width,d=e.height,h=e.pixelRatio[0],f=e.pixelRatio[1];return R.box(R.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}}R.types=void 0;R.HDLR_TYPES=void 0;R.STTS=void 0;R.STSC=void 0;R.STCO=void 0;R.STSZ=void 0;R.VMHD=void 0;R.SMHD=void 0;R.STSD=void 0;R.FTYP=void 0;R.DINF=void 0;const Og=9e4;function Mo(i,e,t=1,r=!1){const s=i*e*t;return r?Math.round(s):s}function AS(i,e,t=1,r=!1){return Mo(i,e,1/t,r)}function Li(i,e=!1){return Mo(i,1e3,1/Og,e)}function IS(i,e=1){return Mo(i,Og,1/e)}function wd(i){const{baseTime:e,timescale:t,trackId:r}=i;return`${e/t} (${e}/${t}) trackId: ${r}`}const DS=10*1e3,LS=1024,RS=1152,CS=1536;let Vr=null,la=null;function Pd(i,e,t,r){return{duration:e,size:t,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:i?2:1,isNonSync:i?0:1}}}class ks extends et{constructor(e,t,r,s){if(super("mp4-remuxer",s),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=r,this.ISGenerated=!1,Vr===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Vr=a?parseInt(a[1]):0}if(la===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);la=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&wd(t)} > ${e&&wd(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const r=e[0].pts,s=e.reduce((n,a)=>{let o=a.pts,u=o-n;return u<-4294967296&&(t=!0,o=He(o,r),u=o-n),u>0?n:o},r);return t&&this.debug("PTS rollover detected"),s}remux(e,t,r,s,n,a,o,u){let l,c,d,h,f,g,p=n,m=n;const v=e.pid>-1,y=t.pid>-1,S=t.samples.length,_=e.samples.length>0,T=o&&S>0||S>1;if((!v||_)&&(!y||T)||this.ISGenerated||o){if(this.ISGenerated){var b,I,A,D;const G=this.videoTrackConfig;(G&&(t.width!==G.width||t.height!==G.height||((b=t.pixelRatio)==null?void 0:b[0])!==((I=G.pixelRatio)==null?void 0:I[0])||((A=t.pixelRatio)==null?void 0:A[1])!==((D=G.pixelRatio)==null?void 0:D[1]))||!G&&T||this.nextAudioTs===null&&_)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,n,a));const L=this.isVideoContiguous;let P=-1,O;if(T&&(P=wS(t.samples),!L&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,P>0){this.warn(`Dropped ${P} out of ${S} video samples due to a missing keyframe`);const G=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(P),t.dropped+=P,m+=(t.samples[0].pts-G)/t.inputTimeScale,O=m}else P===-1&&(this.warn(`No keyframe found out of ${S} video samples`),g=!1);if(this.ISGenerated){if(_&&T){const G=this.getVideoStartPts(t.samples),M=(He(e.samples[0].pts,G)-G)/t.inputTimeScale;p+=Math.max(0,M),m+=Math.max(0,-M)}if(_){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,n,a)),c=this.remuxAudio(e,p,this.isAudioContiguous,a,y||T||u===V.AUDIO?m:void 0),T){const G=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,n,a)),l=this.remuxVideo(t,m,L,G)}}else T&&(l=this.remuxVideo(t,m,L,0));l&&(l.firstKeyFrame=P,l.independent=P!==-1,l.firstKeyFramePTS=O)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(f=Mg(r,n,this._initPTS,this._initDTS)),s.samples.length&&(h=Fg(s,n,this._initPTS))),{audio:c,video:l,initSegment:d,independent:g,text:h,id3:f}}computeInitPts(e,t,r,s){const n=Math.round(r*t);let a=He(e,n);if(a<n+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${s}`);a<n+t;)a+=8589934592;return a-n}generateIS(e,t,r,s){const n=e.samples,a=t.samples,o=this.typeSupported,u={},l=this._initPTS;let c=!l||s,d="audio/mp4",h,f,g,p=-1;if(c&&(h=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(d="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}u.audio={id:"audio",container:d,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):R.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(p=e.id,g=e.inputTimeScale,!l||g!==l.timescale?h=f=this.computeInitPts(n[0].pts,g,r,"audio"):c=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,u.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:R.initSegment([t]),metadata:{width:t.width,height:t.height}},c)if(p=t.id,g=t.inputTimeScale,!l||g!==l.timescale){const m=this.getVideoStartPts(a),v=He(a[0].dts,m),y=this.computeInitPts(v,g,r,"video"),S=this.computeInitPts(m,g,r,"video");f=Math.min(f,y),h=Math.min(h,S)}else c=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(u).length)return this.ISGenerated=!0,c?(l&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${r} ${h/g} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${h/g} (${h}/${g}) trackId: ${p}`),this._initPTS={baseTime:h,timescale:g,trackId:p},this._initDTS={baseTime:f,timescale:g,trackId:p}):h=g=void 0,{tracks:u,initPTS:h,timescale:g,trackId:p}}remuxVideo(e,t,r,s){const n=e.inputTimeScale,a=e.samples,o=[],u=a.length,l=this._initPTS,c=l.baseTime*n/l.timescale;let d=this.nextVideoTs,h=8,f=this.videoSampleDuration,g,p,m=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,y=!1;if(!r||d===null){const N=c+t*n,B=a[0].pts-He(a[0].dts,a[0].pts);Vr&&d!==null&&Math.abs(N-B-(d+c))<15e3?r=!0:d=N-B-c}const S=d+c;for(let N=0;N<u;N++){const B=a[N];B.pts=He(B.pts,S),B.dts=He(B.dts,S),B.dts<a[N>0?N-1:N].dts&&(y=!0)}y&&a.sort(function(N,B){const X=N.dts-B.dts,ie=N.pts-B.pts;return X||ie}),g=a[0].dts,p=a[a.length-1].dts;const _=p-g,T=_?Math.round(_/(u-1)):f||e.inputTimeScale/30;if(r){const N=g-S,B=N>T,X=N<-1;if((B||X)&&(B?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Li(N,!0)} ms (${N}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Li(-N,!0)} ms (${N}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!X||S>=a[0].pts||Vr)){g=S;const ie=a[0].pts-N;if(B)a[0].dts=g,a[0].pts=ie;else{let Q=!0;for(let ee=0;ee<a.length&&!(a[ee].dts>ie&&Q);ee++){const Re=a[ee].pts;if(a[ee].dts-=N,a[ee].pts-=N,ee<a.length-1){const be=a[ee+1].pts,Xe=a[ee].pts,at=be<=Xe,Ft=be<=Re;Q=at==Ft}}}this.log(`Video: Initial PTS/DTS adjusted: ${Li(ie,!0)}/${Li(g,!0)}, delta: ${Li(N,!0)} ms`)}}g=Math.max(0,g);let x=0,b=0,I=g;for(let N=0;N<u;N++){const B=a[N],X=B.units,ie=X.length;let Q=0;for(let ee=0;ee<ie;ee++)Q+=X[ee].data.length;b+=Q,x+=ie,B.length=Q,B.dts<I?(B.dts=I,I+=T/4|0||1):I=B.dts,m=Math.min(B.pts,m),v=Math.max(B.pts,v)}p=a[u-1].dts;const A=b+4*x+8;let D;try{D=new Uint8Array(A)}catch(N){this.observer.emit(E.ERROR,E.ERROR,{type:q.MUX_ERROR,details:C.REMUX_ALLOC_ERROR,fatal:!1,error:N,bytes:A,reason:`fail allocating video mdat ${A}`});return}const L=new DataView(D.buffer);L.setUint32(0,A),D.set(R.types.mdat,4);let P=!1,O=Number.POSITIVE_INFINITY,G=Number.POSITIVE_INFINITY,j=Number.NEGATIVE_INFINITY,M=Number.NEGATIVE_INFINITY;for(let N=0;N<u;N++){const B=a[N],X=B.units;let ie=0;for(let Re=0,be=X.length;Re<be;Re++){const Xe=X[Re],at=Xe.data,Ft=Xe.data.byteLength;L.setUint32(h,Ft),h+=4,D.set(at,h),h+=Ft,ie+=4+Ft}let Q;if(N<u-1)f=a[N+1].dts-B.dts,Q=a[N+1].pts-B.pts;else{const Re=this.config,be=N>0?B.dts-a[N-1].dts:T;if(Q=N>0?B.pts-a[N-1].pts:T,Re.stretchShortVideoTrack&&this.nextAudioTs!==null){const Xe=Math.floor(Re.maxBufferHole*n),at=(s?m+s*n:this.nextAudioTs+c)-B.pts;at>Xe?(f=at-be,f<0?f=be:P=!0,this.log(`It is approximately ${at/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=be}else f=be}const ee=Math.round(B.pts-B.dts);O=Math.min(O,f),j=Math.max(j,f),G=Math.min(G,Q),M=Math.max(M,Q),o.push(Pd(B.key,f,ie,ee))}if(o.length){if(Vr){if(Vr<70){const N=o[0].flags;N.dependsOn=2,N.isNonSync=0}}else if(la&&M-G<j-O&&T/j<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let N=g;for(let B=0,X=o.length;B<X;B++){const ie=N+o[B].duration,Q=N+o[B].cts;if(B<X-1){const ee=ie+o[B+1].cts;o[B].duration=ee-Q}else o[B].duration=B?o[B-1].duration:T;o[B].cts=0,N=ie}}}f=P||!f?T:f;const U=p+f;this.nextVideoTs=d=U-c,this.videoSampleDuration=f,this.isVideoContiguous=!0;const W={data1:R.moof(e.sequenceNumber++,g,ae(e,{samples:o})),data2:D,startPTS:(m-c)/n,endPTS:(v+f-c)/n,startDTS:(g-c)/n,endDTS:d/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,W}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return RS;case"ac3":return CS;default:return LS}}remuxAudio(e,t,r,s,n){const a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,u=a/o,l=this.getSamplesPerFrame(e),c=l*u,d=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=n!==void 0;let p=e.samples,m=h?0:8,v=this.nextAudioTs||-1;const y=d.baseTime*a/d.timescale,S=y+t*a;if(this.isAudioContiguous=r=r||p.length&&v>0&&(s&&Math.abs(S-(v+y))<9e3||Math.abs(He(p[0].pts,S)-(v+y))<20*c),p.forEach(function(M){M.pts=He(M.pts,S)}),!r||v<0){const M=p.length;if(p=p.filter(U=>U.pts>=0),M!==p.length&&this.warn(`Removed ${p.length-M} of ${M} samples (initPTS ${y} / ${a})`),!p.length)return;n===0?v=0:s&&!g?v=Math.max(0,S-y):v=p[0].pts-y}if(e.segmentCodec==="aac"){const M=this.config.maxAudioFramesDrift;for(let U=0,F=v+y;U<p.length;U++){const K=p[U],W=K.pts,N=W-F,B=Math.abs(1e3*N/a);if(N<=-M*c&&g)U===0&&(this.warn(`Audio frame @ ${(W/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*N/a)} ms.`),this.nextAudioTs=v=W-y,F=W);else if(N>=M*c&&B<DS&&g){let X=Math.round(N/c);for(F=W-X*c;F<0&&X&&c;)X--,F+=c;U===0&&(this.nextAudioTs=v=F-y),this.warn(`Injecting ${X} audio frames @ ${((F-y)/a).toFixed(3)}s due to ${Math.round(1e3*N/a)} ms gap.`);for(let ie=0;ie<X;ie++){let Q=xS.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);Q||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),Q=K.unit.subarray()),p.splice(U,0,{unit:Q,pts:F}),F+=c,U++}}K.pts=F,F+=c}}let _=null,T=null,x,b=0,I=p.length;for(;I--;)b+=p[I].unit.byteLength;for(let M=0,U=p.length;M<U;M++){const F=p[M],K=F.unit;let W=F.pts;if(T!==null){const B=f[M-1];B.duration=Math.round((W-T)/u)}else if(r&&e.segmentCodec==="aac"&&(W=v+y),_=W,b>0){b+=m;try{x=new Uint8Array(b)}catch(B){this.observer.emit(E.ERROR,E.ERROR,{type:q.MUX_ERROR,details:C.REMUX_ALLOC_ERROR,fatal:!1,error:B,bytes:b,reason:`fail allocating audio mdat ${b}`});return}h||(new DataView(x.buffer).setUint32(0,b),x.set(R.types.mdat,4))}else return;x.set(K,m);const N=K.byteLength;m+=N,f.push(Pd(!0,l,N,0)),T=W}const A=f.length;if(!A)return;const D=f[f.length-1];v=T-y,this.nextAudioTs=v+u*D.duration;const L=h?new Uint8Array(0):R.moof(e.sequenceNumber++,_/u,ae({},e,{samples:f}));e.samples=[];const P=(_-y)/a,O=this.nextAudioTs/a,j={data1:L,data2:x,startPTS:P,endPTS:O,startDTS:P,endDTS:O,type:"audio",hasAudio:!0,hasVideo:!1,nb:A};return this.isAudioContiguous=!0,j}}function He(i,e){let t;if(e===null)return i;for(e<i?t=-8589934592:t=8589934592;Math.abs(i-e)>4294967296;)i+=t;return i}function wS(i){for(let e=0;e<i.length;e++)if(i[e].key)return e;return-1}function Mg(i,e,t,r){const s=i.samples.length;if(!s)return;const n=i.inputTimeScale;for(let o=0;o<s;o++){const u=i.samples[o];u.pts=He(u.pts-t.baseTime*n/t.timescale,e*n)/n,u.dts=He(u.dts-r.baseTime*n/r.timescale,e*n)/n}const a=i.samples;return i.samples=[],{samples:a}}function Fg(i,e,t){const r=i.samples.length;if(!r)return;const s=i.inputTimeScale;for(let a=0;a<r;a++){const o=i.samples[a];o.pts=He(o.pts-t.baseTime*s/t.timescale,e*s)/s}i.samples.sort((a,o)=>a.pts-o.pts);const n=i.samples;return i.samples=[],{samples:n}}class PS extends et{constructor(e,t,r,s){super("passthrough-remuxer",s),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,r,s){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(e,s),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:r,videoCodec:s}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:n,video:a}=this.initData=Gf(e);if(t)Ev(e,t);else{const u=n||a;u!=null&&u.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${u.codec}")!`)}n&&(r=kd(n,oe.AUDIO,this)),a&&(s=kd(a,oe.VIDEO,this));const o={};n&&a?o.audiovideo={container:"video/mp4",codec:r+","+s,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:n?o.audio={container:"audio/mp4",codec:r,encrypted:n.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:s,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,r,s,n,a){var o,u;let{initPTS:l,lastEndTime:c}=this;const d={audio:void 0,video:void 0,text:s,id3:r,initSegment:void 0};$(c)||(c=this.lastEndTime=n||0);const h=t.samples;if(!h.length)return d;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(h),g=this.initData),!((u=g)!=null&&u.length))return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const p=_v(h,g,this),m=g.audio?p[g.audio.id]:null,v=g.video?p[g.video.id]:null,y=vs(v,1/0),S=vs(m,1/0),_=vs(v,0,!0),T=vs(m,0,!0);let x=n,b=0;const I=m&&(!v||!l&&S<y||l&&l.trackId===g.audio.id),A=I?m:v;if(A){const F=A.timescale,K=A.start-n*F,W=I?g.audio.id:g.video.id;x=A.start/F,b=I?T-S:_-y,(a||!l)&&(kS(l,x,n,b)||F!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${K/F} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${x-n} (${K}/${F}) trackId: ${W}`),l=null,f.initPTS=K,f.timescale=F,f.trackId=W)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);l?(f.initPTS=l.baseTime,f.timescale=l.timescale,f.trackId=l.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=x,f.timescale=1,f.trackId=-1),this.initPTS=l={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const D=x-l.baseTime/l.timescale,L=D+b;b>0?this.lastEndTime=L:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const P=!!g.audio,O=!!g.video;let G="";P&&(G+="audio"),O&&(G+="video");const j=(g.audio?g.audio.encrypted:!1)||(g.video?g.video.encrypted:!1),M={data1:h,startPTS:D,startDTS:D,endPTS:L,endDTS:L,type:G,hasAudio:P,hasVideo:O,nb:1,dropped:0,encrypted:j};d.audio=P&&!O?M:void 0,d.video=O?M:void 0;const U=v==null?void 0:v.sampleCount;if(U){const F=v.keyFrameIndex,K=F!==-1;M.nb=U,M.dropped=F===0||this.isVideoContiguous?0:K?F:U,M.independent=K,M.firstKeyFrame=F,K&&v.keyFrameStart&&(M.firstKeyFramePTS=(v.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(d.independent=K),this.isVideoContiguous||(this.isVideoContiguous=K),M.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${F}/${U} dropped: ${M.dropped} start: ${M.firstKeyFramePTS||"NA"}`)}return d.initSegment=f,d.id3=Mg(r,n,l,l),s.samples.length&&(d.text=Fg(s,n,l)),d}}function vs(i,e,t=!1){return(i==null?void 0:i.start)!==void 0?(i.start+(t?i.duration:0))/i.timescale:e}function kS(i,e,t,r){if(i===null)return!0;const s=Math.max(r,1),n=e-i.baseTime/i.timescale;return Math.abs(n-t)>s}function kd(i,e,t){const r=i.codec;return r&&r.length>4?r:e===oe.AUDIO?r==="ec-3"||r==="ac-3"||r==="alac"?r:r==="fLaC"||r==="Opus"?Xs(r,!1):(t.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||"mp4a"):(t.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||"avc1")}let St;try{St=self.performance.now.bind(self.performance)}catch{St=Date.now}const Os=[{demux:vS,remux:PS},{demux:Pt,remux:ks},{demux:gS,remux:ks},{demux:pS,remux:ks}];Os.splice(2,0,{demux:mS,remux:ks});class Od{constructor(e,t,r,s,n,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=r,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,r,s){const n=r.transmuxing;n.executeStart=St();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:u}=this;s&&(this.currentTransmuxState=s);const{contiguous:l,discontinuity:c,trackSwitch:d,accurateTimeOffset:h,timeOffset:f,initSegmentChange:g}=s||o,{audioCodec:p,videoCodec:m,defaultInitPts:v,duration:y,initSegmentData:S}=u,_=OS(a,t);if(_&&zr(_.method)){const I=this.getDecrypter(),A=Io(_.method);if(I.isSync()){let D=I.softwareDecrypt(a,_.key.buffer,_.iv.buffer,A);if(r.part>-1){const P=I.flush();D=P&&P.buffer}if(!D)return n.executeEnd=St(),ua(r);a=new Uint8Array(D)}else return this.asyncResult=!0,this.decryptionPromise=I.webCryptoDecrypt(a,_.key.buffer,_.iv.buffer,A).then(D=>{const L=this.push(D,null,r);return this.decryptionPromise=null,L}),this.decryptionPromise}const T=this.needsProbing(c,d);if(T){const I=this.configureTransmuxer(a);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(E.ERROR,E.ERROR,{type:q.MEDIA_ERROR,details:C.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),n.executeEnd=St(),ua(r)}(c||d||g||T)&&this.resetInitSegment(S,p,m,y,t),(c||g||T)&&this.resetInitialTimestamp(v),l||this.resetContiguity();const x=this.transmux(a,_,f,h,r);this.asyncResult=Gi(x);const b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,n.executeEnd=St(),x}flush(e){const t=e.transmuxing;t.executeStart=St();const{decrypter:r,currentTransmuxState:s,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));const a=[],{timeOffset:o}=s;if(r){const d=r.flush();d&&a.push(this.push(d.buffer,null,e))}const{demuxer:u,remuxer:l}=this;if(!u||!l){t.executeEnd=St();const d=[ua(e)];return this.asyncResult?Promise.resolve(d):d}const c=u.flush(o);return Gi(c)?(this.asyncResult=!0,c.then(d=>(this.flushRemux(a,d,e),a))):(this.flushRemux(a,c,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,r){const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:u,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id===V.MAIN?"level":"track"} ${r.level}`);const c=this.remuxer.remux(s,n,a,o,l,u,!0,this.id);e.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=St()}resetInitialTimestamp(e){const{demuxer:t,remuxer:r}=this;!t||!r||(t.resetTimeStamp(e),r.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,r,s,n){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,r,s),o.resetInitSegment(e,t,r,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,r,s,n){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,r,s,n):a=this.transmuxUnencrypted(e,r,s,n),a}transmuxUnencrypted(e,t,r,s){const{audioTrack:n,videoTrack:a,id3Track:o,textTrack:u}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,a,o,u,t,r,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,r,s,n){return this.demuxer.demuxSampleAes(e,t,r).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,r,s,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){const{config:t,observer:r,typeSupported:s}=this;let n;for(let d=0,h=Os.length;d<h;d++){var a;if((a=Os[d].demux)!=null&&a.probe(e,this.logger)){n=Os[d];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,u=this.remuxer,l=n.remux,c=n.demux;(!u||!(u instanceof l))&&(this.remuxer=new l(r,t,s,this.logger)),(!o||!(o instanceof c))&&(this.demuxer=new c(r,t,s,this.logger),this.probe=c.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new xo(this.config)),e}}function OS(i,e){let t=null;return i.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const ua=i=>({remuxResult:{},chunkMeta:i});function Gi(i){return"then"in i&&i.then instanceof Function}class MS{constructor(e,t,r,s,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=r,this.duration=s,this.defaultInitPts=n||null}}class FS{constructor(e,t,r,s,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=r,this.trackSwitch=s,this.timeOffset=n,this.initSegmentChange=a}}let Md=0;class Ng{constructor(e,t,r,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Md++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=u=>{const l=u.data,c=this.hls;if(!(!c||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var d;const h=(d=this.workerContext)==null?void 0:d.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{c.logger[l.data.logType]&&c.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,c.trigger(l.event,l.data);break}}},this.onWorkerError=u=>{if(!this.hls)return;const l=new Error(`${u.message} (${u.filename}:${u.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(E.ERROR,{type:q.OTHER_ERROR,details:C.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=r,this.onFlush=s;const a=(u,l)=>{l=l||{},l.frag=this.frag||void 0,u===E.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(u,l)};this.observer=new Ro,this.observer.on(E.FRAG_DECRYPTED,a),this.observer.on(E.ERROR,a);const o=Xc(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const u=this.hls.logger;if(n.workerPath||$E()){try{n.workerPath?(u.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=GE(n.workerPath)):(u.log(`injecting Web Worker for "${t}"`),this.workerContext=jE());const{worker:c}=this.workerContext;c.addEventListener("message",this.onWorkerMessage),c.addEventListener("error",this.onWorkerError),c.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:ue(n)})}catch(c){u.warn(`Error setting up "${t}" Web Worker, fallback to inline`,c),this.terminateWorker(),this.error=null,this.transmuxer=new Od(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new Od(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Md++;const t=this.hls.config,r=Xc(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:ue(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),VE(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,r,s,n,a,o,u,l,c){var d,h;l.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,p=a?a.start:n.start,m=n.decryptdata,v=this.frag,y=!(v&&n.cc===v.cc),S=!(v&&l.level===v.level),_=v?l.sn-v.sn:-1,T=this.part?l.part-this.part.index:-1,x=_===0&&l.id>1&&l.id===(v==null?void 0:v.stats.chunkCount),b=!S&&(_===1||_===0&&(T===1||x&&T<=0)),I=self.performance.now();(S||_||n.stats.parsing.start===0)&&(n.stats.parsing.start=I),a&&(T||!b)&&(a.stats.parsing.start=I);const A=!(v&&((d=n.initSegment)==null?void 0:d.url)===((h=v.initSegment)==null?void 0:h.url)),D=new FS(y,b,u,S,p,A);if(!b||y||A){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===V.MAIN?"level":"track"}: ${l.level} id: ${l.id}
119119+ discontinuity: ${y}
106120 trackSwitch: ${S}
107107- contiguous: ${A}
108108- accurateTimeOffset: ${c}
121121+ contiguous: ${b}
122122+ accurateTimeOffset: ${u}
109123 timeOffset: ${p}
110110- initSegmentChange: ${I}`);const C=new Tu(s,i,t,o,h);this.configureTransmuxer(C)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:y,chunkMeta:l,state:_},e instanceof ArrayBuffer?[e]:[]);else if(g){const C=g.push(e,y,l,_);Wt(C)?C.then(k=>{this.handleTransmuxComplete(k)}).catch(k=>{this.transmuxerError(k,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(C)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const i=s.flush(e);Wt(i)?i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Dn=100;class vu extends sr{constructor(e,t,s){super(e,t,s,"audio-stream-controller",U.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:a}){if(s===U.MAIN){const o=t.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:i,timescale:r,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${i/r} (${i}/${r}) trackId: ${a}`),this.mainAnchor=t,this.state===P.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&this.syncWithAnchor(t,l==null?void 0:l.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(t,c)):this.state===P.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&(i==null?void 0:i.cc)===t.cc)return;const r=(i||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),c=Na(a,r,o);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===P.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=P.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(Dn),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=P.IDLE):this.state=P.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case P.IDLE:this.doTickIdle();break;case P.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=e==null?void 0:e[t],i=s==null?void 0:s.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=P.WAITING_INIT_PTS}break}case P.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case P.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:i,complete:r}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=P.FRAG_LOADING;const o=i.flush().buffer,c={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(c),r&&super._handleFragmentLoadComplete(c)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=P.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:s,media:i,trackId:r}=this,a=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(s!=null&&s[r]))return;const o=s[r],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=P.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,ne.AUDIO,U.AUDIO));const h=this.getFwdBufferInfo(l,U.AUDIO);if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,c)){t.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=P.ENDED;return}const u=h.len,d=t.maxBufferLength,f=c.fragments,g=f[0].start,p=this.getLoadPosition(),y=this.flushing?p:h.end;if(this.switchingTrack&&i){const S=p;c.PTSKnown&&S<g&&(h.end>g||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=g+.05)}if(u>=d&&!this.switchingTrack&&y<f[f.length-1].start)return;let E=this.getNextFragment(y,c);if(E&&this.isLoopLoading(E,y)&&(E=this.getNextFragmentLoopLoading(E,c,h,U.MAIN,d)),!E){this.bufferFlushed=!0;return}let T=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&de(E)&&!E.endList&&(!c.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===me.OK&&(this.mainFragLoading=T=null),T&&de(T))){if(E.start>T.end){const v=this.fragmentTracker.getFragAtPos(y,U.MAIN);v&&v.end>T.end&&(T=v,this.mainFragLoading={frag:v,targetBufferTime:null})}if(E.start>T.end)return}this.loadFragment(E,o,y)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new Kt(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==P.STOPPED&&(this.setInterval(Dn),this.state=P.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(m.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:r,id:a,groupId:o,track:c}=t;if(!i){this.warn(`Audio tracks reset while loading track ${a} "${c.name}" of "${o}"`);return}const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==P.STOPPED&&(this.state=P.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${c.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=i[a];let u=0;if(r.live||(s=h.details)!=null&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(h.details){var d;u=this.alignPlaylists(r,h.details,(d=this.levelLastLoaded)==null?void 0:d.details)}r.alignedSliding||(to(r,l),r.alignedSliding||Ms(r,l),u=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,u),this.hls.trigger(m.AUDIO_TRACK_UPDATED,{details:r,id:a,groupId:t.groupId}),this.state===P.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=P.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{config:a,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const l=c[o];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const h=l.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const u=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new xo(this.hls,U.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[s.cc],g=(t=s.initSegment)==null?void 0:t.data;if(f!==void 0){const y=i?i.index:-1,E=y!==-1,T=new Ji(s.level,s.sn,s.stats.chunkCount,r.byteLength,y,E);d.push(r,g,u,"",s,i,h.totalduration,!1,T,f)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);const{cache:p}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new so,complete:!1};p.push(new Uint8Array(r)),this.state!==P.STOPPED&&(this.state=P.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===U.MAIN&&de(t.frag)&&(this.mainFragLoading=t,this.state===P.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==U.AUDIO){!this.audioOnly&&s.type===U.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(de(s)){this.fragPrevious=s;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,se({},r)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(U.AUDIO,t);break;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===Q.AUDIO_TRACK&&(this.state=P.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==ne.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ne.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===P.ENDED&&(this.state=P.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,U.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:c,part:l,level:h}=o,{details:u}=h,{audio:d,text:f,id3:g,initSegment:p}=r;if(this.fragContextChanged(c)||!u){this.fragmentTracker.removeFragment(c);return}if(this.state=P.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const y=c.initSegment||c;if(this.unhandledEncryptionError(p,c))return;this._bufferInitSegment(h,p.tracks,y,a),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:s,tracks:p.tracks})}if(d){const{startPTS:y,endPTS:E,startDTS:T,endDTS:S}=d;l&&(l.elementaryStreams[ne.AUDIO]={startPTS:y,endPTS:E,startDTS:T,endDTS:S}),c.setElementaryStreamInfo(ne.AUDIO,y,E,T,S),this.bufferFragmentData(d,c,l,a)}if(g!=null&&(t=g.samples)!=null&&t.length){const y=re({id:s,frag:c,details:u},g);i.trigger(m.FRAG_PARSING_METADATA,y)}if(f){const y=re({id:s,frag:c,details:u},f);i.trigger(m.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,s,i){if(this.state!==P.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=U.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a&&a.split(",").length===1&&(r.levelCodec=a),this.hls.trigger(m.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const c={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(m.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===me.NOT_LOADED||i===me.PARTIAL){var r;if(!de(e))this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=P.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Ms(t.details,a)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o}=this.bufferedTrack;gt({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o},e,ft)||(Ps(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(m.AUDIO_TRACK_SWITCHED,se({},e))}}class hr extends Fe{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=t==null?void 0:t.renditionReports;if(i){let r=-1;for(let a=0;a<i.length;a++){const o=i[a];let c;try{c=new self.URL(o.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),c=o.URI||""}if(c===e){r=a;break}else c===e.substring(0,c.length)&&(r=a)}if(r!==-1){const a=i[r],o=parseInt(a["LAST-MSN"])||t.lastPartSn;let c=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&h>t.partTarget&&(c+=1)}const l=s&&Vr(s);return new Hr(o,c>=0?c:void 0,l)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,a=self.performance.now(),o=r.loading.first?Math.max(0,a-r.loading.first):0;i.advancedDateTime=Date.now()-o;const c=this.hls.config.timelineOffset;if(c!==i.appliedTimelineOffset){const h=Math.max(c||0,0);i.appliedTimelineOffset=h,i.fragments.forEach(u=>{u.setStart(u.playlistOffset+h)})}if(i.live||s!=null&&s.live){const h="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){fh(s,i,this);const T=i.playlistParsingError;if(T){this.warn(T);const S=this.hls;if(!S.config.ignorePlaylistParsingErrors){var l;const{networkDetails:v}=t;S.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:T,reason:T.message,level:t.level||void 0,parent:(l=i.fragments[0])==null?void 0:l.type,networkDetails:v,stats:r});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=r.loading.start);const u=this.hls.mainForwardBufferInfo,d=u?u.end-u.len:0,f=(i.edge-d)*1e3,g=za(i,f);if(i.requestScheduled+g<a?i.requestScheduled=a:i.requestScheduled+=g,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let p,y,E;if(i.canBlockReload&&i.endSN&&i.advanced){const T=this.hls.config.lowLatencyMode,S=i.lastPartSn,v=i.endSN,x=i.lastPartIndex,D=x!==-1,A=S===v;D?A?(y=v+1,E=T?0:x):(y=S,E=T?x+1:i.maxPartIndex):y=v+1;const b=i.age,I=b+i.ageHeader;let _=Math.min(I-i.partTarget,i.targetduration*1.5);if(_>0){if(I>i.targetduration*3)this.log(`Playlist last advanced ${b.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,E=void 0;else if(s!=null&&s.tuneInGoal&&I-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${_} with playlist age: ${i.age}`),_=0;else{const C=Math.floor(_/i.targetduration);if(y+=C,E!==void 0){const k=Math.round(_%i.targetduration/i.partTarget);E+=k}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${b.toFixed(2)}s goal: ${_} skip sn ${C} to part ${E}`)}i.tuneInGoal=_}if(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E),T||!A){i.requestScheduled=a,this.loadingPlaylist(h,p);return}}else(i.canBlockReload||i.canSkipUntil)&&(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E));p&&y!==void 0&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(g-o*2,g/2)),this.scheduleLoading(h,p,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i){this.loadingPlaylist(e,t);return}const r=self.performance.now(),a=i.requestScheduled;if(r>=a){this.loadingPlaylist(e,t);return}const o=a-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,i){let r=Vr(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=ps.No),new Hr(s,i,r)}checkRetry(e){const t=e.details,s=ks(e),i=e.errorAction,{action:r,retryCount:a=0,retryConfig:o}=i||{},c=!!i&&!!o&&(r===Ee.RetryRequest||!i.resolved&&r===Ee.SendAlternateToPenaltyBox);if(c){var l;if(a>=o.maxNumRetry)return!1;if(s&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const h=Qi(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${h}ms`)}e.levelRetry=!0,i.resolved=!0}return c}}function Ao(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(!Yt(n[t].attrs,e[t].attrs))return!1;return!0}function Yt(n,e,t){const s=n["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>n[i]!==e[i])}function Oi(n,e){return e.label.toLowerCase()===n.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(n.lang||"").toLowerCase())}class xu extends hr{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(i==null?void 0:i.length)!==(s==null?void 0:s.length)||s!=null&&s.some(o=>(i==null?void 0:i.indexOf(o))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!s||s.indexOf(d.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,f)=>{d.id=f});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!r&&c){const d=He(c,o,ft);if(d>-1)r=o[d];else{const f=He(c,this.tracks);r=this.tracks[f]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s==null?void 0:s.join(",")}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,h);const u=this.trackId;if(l!==-1&&u===-1)this.setAudioTrack(l);else if(o.length&&u===-1){var a;const d=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}}onError(e,t){t.fatal||!t.context||t.context.type===Q.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&>(e,i,ft))return i;const r=He(e,this.tracksInGroup,ft);if(r>-1){const a=this.tracksInGroup[r];return this.setAudioTrack(r),a}else if(i){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=Oc(e,t.levels,s,a,ft);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=He(e,s);if(a>-1)return s[a]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,se({},i)),r))return;const a=this.switchParams(i.url,s==null?void 0:s.details,i.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||gt(e,i,ft)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:c}=e;for(let l=0;l<t.length;l++){const h=t[l];if(gt({name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:c},h,ft))return l}for(let l=0;l<t.length;l++){const h=t[l];if(Yt(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const h=t[l];if(Yt(e.attrs,h.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Ps(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(m.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}}class Au{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(r){var s;if(i.onError(r),this.queues===null||this.tracks===null)return;const a=(s=this.tracks[e])==null?void 0:s.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
124124+ initSegmentChange: ${A}`);const L=new MS(r,s,t,o,c);this.configureTransmuxer(L)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:m,chunkMeta:l,state:D},e instanceof ArrayBuffer?[e]:[]);else if(g){const L=g.push(e,m,l,D);Gi(L)?L.then(P=>{this.handleTransmuxComplete(P)}).catch(P=>{this.transmuxerError(P,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(L)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:r}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(r){const s=r.flush(e);Gi(s)?s.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")}):this.handleFlushResult(s,e)}}transmuxerError(e,t,r){this.hls&&(this.error=e,this.hls.trigger(E.ERROR,{type:q.MEDIA_ERROR,details:C.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:r}))}handleFlushResult(e,t){e.forEach(r=>{this.handleTransmuxComplete(r)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:r}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Fd=100;class NS extends Lo{constructor(e,t,r){super(e,t,r,"audio-stream-controller",V.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:r,initPTS:s,timescale:n,trackId:a}){if(r===V.MAIN){const o=t.cc,u=this.fragCurrent;if(this.initPTS[o]={baseTime:s,timescale:n,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${s/n} (${s}/${n}) trackId: ${a}`),this.mainAnchor=t,this.state===k.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&this.syncWithAnchor(t,l==null?void 0:l.frag)}else!this.hls.hasEnoughToStart&&u&&u.cc!==o?(u.abortRequests(),this.syncWithAnchor(t,u)):this.state===k.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var r;const s=((r=this.mainFragLoading)==null?void 0:r.frag)||null;if(t&&(s==null?void 0:s.cc)===t.cc)return;const n=(s||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),u=Jf(a,n,o);u&&(this.log(`Syncing with main frag at ${u.start} cc ${u.cc}`),this.startFragRequested=!1,this.nextLoadPosition=u.start,this.resetLoadingState(),this.state===k.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=k.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(Fd),r>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r,this.state=k.IDLE):this.state=k.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case k.IDLE:this.doTickIdle();break;case k.WAITING_TRACK:{const{levels:e,trackId:t}=this,r=e==null?void 0:e[t],s=r==null?void 0:r.details;if(s&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(s))break;this.state=k.WAITING_INIT_PTS}break}case k.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case k.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:r,cache:s,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=k.FRAG_LOADING;const o=s.flush().buffer,u={frag:t,part:r,payload:o,networkDetails:null};this._handleFragmentLoadProgress(u),n&&super._handleFragmentLoadComplete(u)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=k.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:r,media:s,trackId:n}=this,a=t.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(r!=null&&r[n]))return;const o=r[n],u=o.details;if(!u||this.waitForLive(o)||this.waitForCdnTuneIn(u)){this.state=k.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,oe.AUDIO,V.AUDIO));const c=this.getFwdBufferInfo(l,V.AUDIO);if(c===null)return;if(!this.switchingTrack&&this._streamEnded(c,u)){t.trigger(E.BUFFER_EOS,{type:"audio"}),this.state=k.ENDED;return}const d=c.len,h=t.maxBufferLength,f=u.fragments,g=f[0].start,p=this.getLoadPosition(),m=this.flushing?p:c.end;if(this.switchingTrack&&s){const S=p;u.PTSKnown&&S<g&&(c.end>g||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=g+.05)}if(d>=h&&!this.switchingTrack&&m<f[f.length-1].start)return;let v=this.getNextFragment(m,u);if(v&&this.isLoopLoading(v,m)&&(v=this.getNextFragmentLoopLoading(v,u,c,V.MAIN,h)),!v){this.bufferFlushed=!0;return}let y=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&me(v)&&!v.endList&&(!u.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===_e.OK&&(this.mainFragLoading=y=null),y&&me(y))){if(v.start>y.end){const _=this.fragmentTracker.getFragAtPos(m,V.MAIN);_&&_.end>y.end&&(y=_,this.mainFragLoading={frag:_,targetBufferTime:null})}if(v.start>y.end)return}this.loadFragment(v,o,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(r=>new Ui(r))}onAudioTrackSwitching(e,t){const r=!!t.url;this.trackId=t.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),r?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==k.STOPPED&&(this.setInterval(Fd),this.state=k.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(E.AUDIO_TRACK_LOADED,r))}onAudioTrackLoaded(e,t){var r;const{levels:s}=this,{details:n,id:a,groupId:o,track:u}=t;if(!s){this.warn(`Audio tracks reset while loading track ${a} "${u.name}" of "${o}"`);return}const l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==k.STOPPED&&(this.state=k.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${u.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const c=s[a];let d=0;if(n.live||(r=c.details)!=null&&r.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(c.details){var h;d=this.alignPlaylists(n,c.details,(h=this.levelLastLoaded)==null?void 0:h.details)}n.alignedSliding||(yg(n,l),n.alignedSliding||sn(n,l),d=n.fragmentStart)}c.details=n,this.levelLastLoaded=c,this.startFragRequested||this.setStartPosition(l,d),this.hls.trigger(E.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===k.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=k.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const r=e.frag,{part:s,payload:n}=e,{config:a,trackId:o,levels:u}=this;if(!u){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const l=u[o];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const c=l.details;if(!c){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(r.start);return}const d=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new Ng(this.hls,V.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[r.cc],g=(t=r.initSegment)==null?void 0:t.data;if(f!==void 0){const m=s?s.index:-1,v=m!==-1,y=new Ao(r.level,r.sn,r.stats.chunkCount,n.byteLength,m,v);h.push(n,g,d,"",r,s,c.totalduration,!1,y,f)}else{this.log(`Unknown video PTS for cc ${r.cc}, waiting for video PTS before demuxing audio frag ${r.sn} of [${c.startSN} ,${c.endSN}],track ${o}`);const{cache:p}=this.waitingData=this.waitingData||{frag:r,part:s,cache:new vg,complete:!1};p.push(new Uint8Array(n)),this.state!==k.STOPPED&&(this.state=k.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===V.MAIN&&me(t.frag)&&(this.mainFragLoading=t,this.state===k.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:r,part:s}=t;if(r.type!==V.AUDIO){!this.audioOnly&&r.type===V.MAIN&&!r.elementaryStreams.video&&!r.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${s?" p: "+s.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(me(r)){this.fragPrevious=r;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(E.AUDIO_TRACK_SWITCHED,se({},n)))}this.fragBufferedComplete(r,s),this.media&&this.tick()}onError(e,t){var r;if(t.fatal){this.state=k.ERROR;return}switch(t.details){case C.FRAG_GAP:case C.FRAG_PARSING_ERROR:case C.FRAG_DECRYPT_ERROR:case C.FRAG_LOAD_ERROR:case C.FRAG_LOAD_TIMEOUT:case C.KEY_LOAD_ERROR:case C.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(V.AUDIO,t);break;case C.AUDIO_TRACK_LOAD_ERROR:case C.AUDIO_TRACK_LOAD_TIMEOUT:case C.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===k.WAITING_TRACK&&((r=t.context)==null?void 0:r.type)===J.AUDIO_TRACK&&(this.state=k.IDLE);break;case C.BUFFER_ADD_CODEC_ERROR:case C.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case C.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case C.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==oe.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==oe.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===k.ENDED&&(this.state=k.IDLE);const r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,t,V.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const r="audio",{hls:s}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:u,part:l,level:c}=o,{details:d}=c,{audio:h,text:f,id3:g,initSegment:p}=n;if(this.fragContextChanged(u)||!d){this.fragmentTracker.removeFragment(u);return}if(this.state=k.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const m=u.initSegment||u;if(this.unhandledEncryptionError(p,u))return;this._bufferInitSegment(c,p.tracks,m,a),s.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:r,tracks:p.tracks})}if(h){const{startPTS:m,endPTS:v,startDTS:y,endDTS:S}=h;l&&(l.elementaryStreams[oe.AUDIO]={startPTS:m,endPTS:v,startDTS:y,endDTS:S}),u.setElementaryStreamInfo(oe.AUDIO,m,v,y,S),this.bufferFragmentData(h,u,l,a)}if(g!=null&&(t=g.samples)!=null&&t.length){const m=ae({id:r,frag:u,details:d},g);s.trigger(E.FRAG_PARSING_METADATA,m)}if(f){const m=ae({id:r,frag:u,details:d},f);s.trigger(E.FRAG_PARSING_USERDATA,m)}}_bufferInitSegment(e,t,r,s){if(this.state!==k.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const n=t.audio;n.id=V.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),a&&a.split(",").length===1&&(n.levelCodec=a),this.hls.trigger(E.BUFFER_CODECS,t);const o=n.initSegment;if(o!=null&&o.byteLength){const u={type:"audio",frag:r,part:null,chunkMeta:s,parent:r.type,data:o};this.hls.trigger(E.BUFFER_APPENDING,u)}this.tickImmediate()}loadFragment(e,t,r){const s=this.fragmentTracker.getState(e);if(this.switchingTrack||s===_e.NOT_LOADED||s===_e.PARTIAL){var n;if(!me(e))this._loadInitSegment(e,t);else if((n=t.details)!=null&&n.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=k.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&sn(t.details,a)}else super.loadFragment(e,t,r)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:r,assocLang:s,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;ar({name:t,lang:r,assocLang:s,characteristics:n,audioCodec:a,channels:o},e,nr)||(Zs(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(E.AUDIO_TRACK_SWITCHED,se({},e))}}class Fo extends et{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,r){const s=t==null?void 0:t.renditionReports;if(s){let n=-1;for(let a=0;a<s.length;a++){const o=s[a];let u;try{u=new self.URL(o.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),u=o.URI||""}if(u===e){n=a;break}else u===e.substring(0,u.length)&&(n=a)}if(n!==-1){const a=s[n],o=parseInt(a["LAST-MSN"])||t.lastPartSn;let u=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const c=Math.min(t.age-t.partTarget,t.targetduration);u>=0&&c>t.partTarget&&(u+=1)}const l=r&&Qc(r);return new Zc(o,u>=0?u:void 0,l)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(r){this.warn(`Could not construct new URL with HLS Delivery Directives: ${r}`)}return e}playlistLoaded(e,t,r){const{details:s,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;s.advancedDateTime=Date.now()-o;const u=this.hls.config.timelineOffset;if(u!==s.appliedTimelineOffset){const c=Math.max(u||0,0);s.appliedTimelineOffset=c,s.fragments.forEach(d=>{d.setStart(d.playlistOffset+c)})}if(s.live||r!=null&&r.live){const c="levelInfo"in t?t.levelInfo:t.track;if(s.reloaded(r),r&&s.fragments.length>0){RE(r,s,this);const y=s.playlistParsingError;if(y){this.warn(y);const S=this.hls;if(!S.config.ignorePlaylistParsingErrors){var l;const{networkDetails:_}=t;S.trigger(E.ERROR,{type:q.NETWORK_ERROR,details:C.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:y,reason:y.message,level:t.level||void 0,parent:(l=s.fragments[0])==null?void 0:l.type,networkDetails:_,stats:n});return}s.playlistParsingError=null}}s.requestScheduled===-1&&(s.requestScheduled=n.loading.start);const d=this.hls.mainForwardBufferInfo,h=d?d.end-d.len:0,f=(s.edge-h)*1e3,g=hg(s,f);if(s.requestScheduled+g<a?s.requestScheduled=a:s.requestScheduled+=g,this.log(`live playlist ${e} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;let p,m,v;if(s.canBlockReload&&s.endSN&&s.advanced){const y=this.hls.config.lowLatencyMode,S=s.lastPartSn,_=s.endSN,T=s.lastPartIndex,x=T!==-1,b=S===_;x?b?(m=_+1,v=y?0:T):(m=S,v=y?T+1:s.maxPartIndex):m=_+1;const I=s.age,A=I+s.ageHeader;let D=Math.min(A-s.partTarget,s.targetduration*1.5);if(D>0){if(A>s.targetduration*3)this.log(`Playlist last advanced ${I.toFixed(2)}s ago. Omitting segment and part directives.`),m=void 0,v=void 0;else if(r!=null&&r.tuneInGoal&&A-s.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${D} with playlist age: ${s.age}`),D=0;else{const L=Math.floor(D/s.targetduration);if(m+=L,v!==void 0){const P=Math.round(D%s.targetduration/s.partTarget);v+=P}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${I.toFixed(2)}s goal: ${D} skip sn ${L} to part ${v}`)}s.tuneInGoal=D}if(p=this.getDeliveryDirectives(s,t.deliveryDirectives,m,v),y||!b){s.requestScheduled=a,this.loadingPlaylist(c,p);return}}else(s.canBlockReload||s.canSkipUntil)&&(p=this.getDeliveryDirectives(s,t.deliveryDirectives,m,v));p&&m!==void 0&&s.canBlockReload&&(s.requestScheduled=n.loading.first+Math.max(g-o*2,g/2)),this.scheduleLoading(c,p,s)}else this.clearTimer()}scheduleLoading(e,t,r){const s=r||e.details;if(!s){this.loadingPlaylist(e,t);return}const n=self.performance.now(),a=s.requestScheduled;if(n>=a){this.loadingPlaylist(e,t);return}const o=a-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,r,s){let n=Qc(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,s=t.part,n=ws.No),new Zc(r,s,n)}checkRetry(e){const t=e.details,r=Js(e),s=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=s||{},u=!!s&&!!o&&(n===Ae.RetryRequest||!s.resolved&&n===Ae.SendAlternateToPenaltyBox);if(u){var l;if(a>=o.maxNumRetry)return!1;if(r&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const c=bo(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),c),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${c}ms`)}e.levelRetry=!0,s.resolved=!0}return u}}function Bg(i,e){if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++)if(!Vi(i[t].attrs,e[t].attrs))return!1;return!0}function Vi(i,e,t){const r=i["STABLE-RENDITION-ID"];return r&&!t?r===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>i[s]!==e[s])}function Ga(i,e){return e.label.toLowerCase()===i.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(i.lang||"").toLowerCase())}class BS extends Fo{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(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.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:r,groupId:s,details:n}=t,a=this.tracksInGroup[r];if(!a||a.groupId!==s){this.warn(`Audio track with id:${r} and group:${s} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${r} "${a.name}" lang:${a.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`),r===this.trackId&&this.playlistLoaded(r,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 r=t.audioGroups||null,s=this.groupIds;let n=this.currentTrack;if(!r||(s==null?void 0:s.length)!==(r==null?void 0:r.length)||r!=null&&r.some(o=>(s==null?void 0:s.indexOf(o))===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(h=>!r||r.indexOf(h.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(h=>h.default)&&(this.selectDefaultTrack=!1),o.forEach((h,f)=>{h.id=f});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const u=this.hls.config.audioPreference;if(!n&&u){const h=dt(u,o,nr);if(h>-1)n=o[h];else{const f=dt(u,this.tracks);n=this.tracks[f]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));const c={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${r==null?void 0:r.join(",")}`),this.hls.trigger(E.AUDIO_TRACKS_UPDATED,c);const d=this.trackId;if(l!==-1&&d===-1)this.setAudioTrack(l);else if(o.length&&d===-1){var a;const h=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(h.message),this.hls.trigger(E.ERROR,{type:q.MEDIA_ERROR,details:C.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===J.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){const s=this.currentTrack;if(s&&ar(e,s,nr))return s;const n=dt(e,this.tracksInGroup,nr);if(n>-1){const a=this.tracksInGroup[n];return this.setAudioTrack(n),a}else if(s){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=Xv(e,t.levels,r,a,nr);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=dt(e,r);if(a>-1)return r[a]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,s=t[e],n=s.details&&!s.details.live;if(e===this.trackId&&s===r&&n||(this.log(`Switching to audio-track ${e} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=e,this.currentTrack=s,this.hls.trigger(E.AUDIO_TRACK_SWITCHING,se({},s)),n))return;const a=this.switchParams(s.url,r==null?void 0:r.details,s.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){const s=t[r];if(!(this.selectDefaultTrack&&!s.default)&&(!e||ar(e,s,nr)))return r}if(e){const{name:r,lang:s,assocLang:n,characteristics:a,audioCodec:o,channels:u}=e;for(let l=0;l<t.length;l++){const c=t[l];if(ar({name:r,lang:s,assocLang:n,characteristics:a,audioCodec:o,channels:u},c,nr))return l}for(let l=0;l<t.length;l++){const c=t[l];if(Vi(e.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const c=t[l];if(Vi(e.attrs,c.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Zs(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=e.id,s=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading audio-track ${r} "${e.name}" lang:${e.lang} group:${s}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(E.AUDIO_TRACK_LOADING,{url:n,id:r,groupId:s,deliveryDirectives:t||null,track:e})}}class US{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,r){if(this.queues===null||this.tracks===null)return;const s=this.queues[t];s.push(e),s.length===1&&!r&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const r={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(r,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const r={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(r)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const r=(t=e[0])==null?void 0:t.label;(r==="async-blocker"||r==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const s=t[0];try{s.execute()}catch(n){var r;if(s.onError(n),this.queues===null||this.tracks===null)return;const a=(r=this.tracks[e])==null?void 0:r.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
111125${this.list("video")}
112126${this.list("audio")}
113113-${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],i=s==null?void 0:s.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}}const Cn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,_o="HlsJsTrackRemovedError";class _u extends Error{constructor(e){super(e),this.name=_o}}class Iu extends Fe{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:i,mediaSource:r}=this;s&&this.log("Media source opened"),!(!i||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:i,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:i}=this;s!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=ql(at(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_APPENDING,this.onBufferAppending,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.BUFFER_EOS,this.onBufferEos,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.FRAG_PARSED,this.onFragParsed,this),e.on(m.FRAG_CHANGED,this.onFragChanged,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_APPENDING,this.onBufferAppending,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_EOS,this.onBufferEos,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.FRAG_PARSED,this.onFragParsed,this),e.off(m.FRAG_CHANGED,this.onFragChanged,this),e.off(m.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const a=this.isQueued();(r||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?re(s,i.tracks):this.sourceBuffers.forEach(r=>{const[a]=r;a&&(s[a]=re({},this.tracks[a]),this.removeBuffer(a)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=at(this.appendSource);if(i){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const a=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(a),r)this._objectUrl=s.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{s.removeAttribute("src");const c=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||c&&a instanceof c,Pn(s),Lu(s,o),s.load()}catch{s.src=o}else s.src=o}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,a=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
114114-required tracks: ${oe(s,(c,l)=>c==="initSegment"?void 0:l)};
115115-transfer tracks: ${oe(i,(c,l)=>c==="initSegment"?void 0:l)}}`),!Ta(i,s)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,l=this.details,h=Math.max(c,(l==null?void 0:l.fragments[0].start)||0);if(h-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${h} currentTime: ${c}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(c=>{const l=c,h=i[l];if(h){const u=h.buffer;if(u){const d=this.fragmentTracker,f=h.id;if(d.hasFragments(f)||d.hasParts(f)){const y=q.getBuffered(u);d.detectEvictedFragments(l,y,f,null,!0)}const g=ni(l),p=[l,u];this.sourceBuffers[g]=p,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:a}=this;if(r){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const c=r.sourceBuffers;for(let l=c.length;l--;)o&&c[l].abort(),r.removeSourceBuffer(c[l]);o&&r.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(i.removeAttribute("src"),this.appendSource&&Pn(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(m.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[ni(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Au(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&r.some(c=>!i[c]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var l,h;const u=t[c],{id:d,codec:f,levelCodec:g,container:p,metadata:y,supplemental:E}=u;let T=i[c];const S=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[c],v=S!=null&&S.buffer?S:T,x=(v==null?void 0:v.pendingCodec)||(v==null?void 0:v.codec),D=v==null?void 0:v.levelCodec;T||(T=i[c]={buffer:void 0,listeners:[],codec:f,supplemental:E,container:p,levelCodec:g,metadata:y,id:d});const A=ms(x,D),b=A==null?void 0:A.replace(Cn,"$1");let I=ms(f,g);const _=(h=I)==null?void 0:h.replace(Cn,"$1");I&&A&&b!==_&&(c.slice(0,5)==="audio"&&(I=Ds(I,this.appendSource)),this.log(`switching codec ${x} to ${I}`),I!==(T.pendingCodec||T.codec)&&(T.pendingCodec=I),T.container=p,this.appendChangeType(c,p,I))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const a=this.tracks[e];if(a){const o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),o.changeType(i),a.codec=s,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,U.MAIN))==null?void 0:t.gap)===!0)return;const a={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>i||c!=null&&c.buffer&&q.isBuffered(c.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,U.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:a,frag:o,part:c,chunkMeta:l,offset:h}=t,u=l.buffering[r],{sn:d,cc:f}=o,g=self.performance.now();u.start=g;const p=o.stats.buffering,y=c?c.stats.buffering:null;p.start===0&&(p.start=g),y&&y.start===0&&(y.start=g);const E=s.audio;let T=!1;r==="audio"&&(E==null?void 0:E.container)==="audio/mpeg"&&(T=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const S=s.video,v=S==null?void 0:S.buffer;if(v&&d!=="initSegment"){const A=c||o,b=this.blockedAudioAppend;if(r==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(S.ending||S.ended)){const _=A.start+A.duration*.05,C=v.buffered,k=this.currentOp("video");!C.length&&!k?this.blockAudio(A):!k&&!q.isBuffered(v,_)&&this.lastVideoAppendEnd<_&&this.blockAudio(A)}else if(r==="video"){const I=A.end;if(b){const _=b.frag.start;(I>_||I<this.lastVideoAppendEnd||q.isBuffered(v,_))&&this.unblockAudio()}this.lastVideoAppendEnd=I}}const x=(c||o).start,D={label:`append-${r}`,execute:()=>{var A;u.executeStart=self.performance.now();const b=(A=this.tracks[r])==null?void 0:A.buffer;b&&(T?this.updateTimestampOffset(b,x,.1,r,d,f):h!==void 0&&M(h)&&this.updateTimestampOffset(b,h,1e-6,r,d,f)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const A=self.performance.now();u.executeEnd=u.end=A,p.first===0&&(p.first=A),y&&y.first===0&&(y.first=A);const b={};this.sourceBuffers.forEach(([I,_])=>{I&&(b[I]=q.getBuffered(_))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(m.BUFFER_APPENDED,{type:r,frag:o,part:c,chunkMeta:l,parent:o.type,timeRanges:b})},onError:A=>{var b;const I={type:H.MEDIA_ERROR,parent:o.type,details:R.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:c,chunkMeta:l,error:A,err:A,fatal:!1},_=(b=this.media)==null?void 0:b.error;if(A.code===DOMException.QUOTA_EXCEEDED_ERR||A.name=="QuotaExceededError"||"quota"in A)I.details=R.BUFFER_FULL_ERROR;else if(A.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!_)I.errorAction=_t(!0);else if(A.name===_o&&this.sourceBufferCount===0)I.errorAction=_t(!0);else{const C=++this.appendErrors[r];this.warn(`Failed ${C}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${_||"no media error"})`),(C>=this.hls.config.appendErrorMaxRetry||_)&&(I.fatal=!0)}this.hls.trigger(m.ERROR,I)}};this.log(`queuing "${r}" append sn: ${d}${c?" p: "+c.index:""} of ${o.type===U.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(D,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,i,r),a)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],a=i?i.elementaryStreams:s.elementaryStreams;a[ne.AUDIOVIDEO]?r.push("audiovideo"):(a[ne.AUDIO]&&r.push("audio"),a[ne.VIDEO]&&r.push("video"));const o=()=>{const c=self.performance.now();s.stats.buffering.end=c,i&&(i.stats.buffering.end=c);const l=i?i.stats:s.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:s,part:i,stats:l,id:s.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,r).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([a])=>{if(a){const o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});const i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(m.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(m.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===R.BUFFER_APPEND_ERROR&&t.frag){var s;const i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;M(i)&&i!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;const i=e.config,r=s.currentTime,a=t.levelTargetDuration,o=t.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(M(o)&&o>=0){const l=Math.max(o,a),h=Math.floor(r/a)*a-l;this.flushBackBuffer(r,a,h)}const c=i.frontBufferFlushThreshold;if(M(c)&&c>0){const l=Math.max(i.maxBufferLength,c),h=Math.max(l,a),u=Math.floor(r/a)*a+h;this.flushFrontBuffer(r,a,u)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const o=q.getBuffered(r);if(o.length>0&&s>o.start(0)){var a;this.hls.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:s});const c=this.tracks[i];if((a=this.details)!=null&&a.live)this.hls.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(c!=null&&c.ended){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const a=q.getBuffered(r),o=a.length;if(o<2)return;const c=a.start(o-1),l=a.end(o-1);if(s>c||e>=c&&e<=l)return;this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||(s==null?void 0:s.readyState)!=="open")return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),h=Math.max(l,i);return{duration:1/0,start:l,end:h}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return M(r)?{duration:r}:null;const a=this.media.duration,o=M(s.duration)?s.duration:0;return i>o&&i>a||!M(a)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(M(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${oe(s)}`),this.tracksReady){var i;const r=(i=this.transferData)==null?void 0:i.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(m.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const a=r,o=e[a];if(this.isPending(o)){const c=this.getTrackCodec(o,a),l=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${l})${this.currentOp(a)?" Queued":""} ${oe(o)}`);try{const h=s.addSourceBuffer(l),u=ni(a),d=[a,h];t[u]=d,o.buffer=h}catch(h){var i;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(a),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[a],this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:a,mimeType:l,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&(t==="video"||t==="audiovideo")&&$t(s,"video")&&(i=mc(i,s));const r=ms(i,e.levelCodec);return r?t.slice(0,5)==="audio"?Ds(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,a)=>{const o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(m.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s==null?void 0:s.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.currentOp(e);r&&r.onError(i)}updateTimestampOffset(e,t,s,i,r,a){const o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,a=this.tracks[e],o=a==null?void 0:a.buffer;if(!i||!r||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const c=M(i.duration)?i.duration:1/0,l=M(r.duration)?r.duration:1/0,h=Math.max(0,t),u=Math.min(s,c,l);u>h&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${h},${u}] from the ${e} SourceBuffer`),o.remove(h,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=s==null?void 0:s.buffer;if(!i)throw new _u(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,i=t.map(a=>this.appendBlocker(a));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(a=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const a=s.bind(this,e);i.listeners.push({event:t,listener:a}),r.addEventListener(t,a)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(i=>{s.removeEventListener(i.event,i.listener)}),t.listeners.length=0)}}function Pn(n){const e=n.querySelectorAll("source");[].slice.call(e).forEach(t=>{n.removeChild(t)})}function Lu(n,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,n.appendChild(t)}function ni(n){return n==="audio"?1:0}class ur{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&M(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,ur.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const i=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let r=e.length-1;const a=Math.max(t,s);for(let o=0;o<e.length;o+=1){const c=e[o];if((c.width>=a||c.height>=a)&&i(c,e[o+1])){r=o;break}}return r}}const Ru={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},_e=Ru,bu={HLS:"h"},Du=bu;class Ye{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof Ye?s:new Ye(s))),this.value=e,this.params=t}}const Cu="Dict";function Pu(n){return Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":typeof n=="object"?JSON.stringify(n):String(n)}function ku(n,e,t,s){return new Error(`failed to ${n} "${Pu(e)}" as ${t}`,{cause:s})}function qe(n,e,t){return ku("serialize",n,e,t)}class Io{constructor(e){this.description=e}}const kn="Bare Item",wu="Boolean";function Ou(n){if(typeof n!="boolean")throw qe(n,wu);return n?"?1":"?0"}function Fu(n){return btoa(String.fromCharCode(...n))}const Mu="Byte Sequence";function Nu(n){if(ArrayBuffer.isView(n)===!1)throw qe(n,Mu);return`:${Fu(n)}:`}const Bu="Integer";function Uu(n){return n<-999999999999999||999999999999999<n}function Lo(n){if(Uu(n))throw qe(n,Bu);return n.toString()}function $u(n){return`@${Lo(n.getTime()/1e3)}`}function Ro(n,e){if(n<0)return-Ro(-n,e);const t=Math.pow(10,e);if(Math.abs(n*t%1-.5)<Number.EPSILON){const i=Math.floor(n*t);return(i%2===0?i:i+1)/t}else return Math.round(n*t)/t}const Gu="Decimal";function Ku(n){const e=Ro(n,3);if(Math.floor(Math.abs(e)).toString().length>12)throw qe(n,Gu);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Vu="String",Hu=/[\x00-\x1f\x7f]+/;function Wu(n){if(Hu.test(n))throw qe(n,Vu);return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Yu(n){return n.description||n.toString().slice(7,-1)}const qu="Token";function wn(n){const e=Yu(n);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw qe(e,qu);return e}function Fi(n){switch(typeof n){case"number":if(!M(n))throw qe(n,kn);return Number.isInteger(n)?Lo(n):Ku(n);case"string":return Wu(n);case"symbol":return wn(n);case"boolean":return Ou(n);case"object":if(n instanceof Date)return $u(n);if(n instanceof Uint8Array)return Nu(n);if(n instanceof Io)return wn(n);default:throw qe(n,kn)}}const ju="Key";function Mi(n){if(/^[a-z*][a-z0-9\-_.*]*$/.test(n)===!1)throw qe(n,ju);return n}function dr(n){return n==null?"":Object.entries(n).map(([e,t])=>t===!0?`;${Mi(e)}`:`;${Mi(e)}=${Fi(t)}`).join("")}function bo(n){return n instanceof Ye?`${Fi(n.value)}${dr(n.params)}`:Fi(n)}function Xu(n){return`(${n.value.map(bo).join(" ")})${dr(n.params)}`}function zu(n,e={whitespace:!0}){if(typeof n!="object"||n==null)throw qe(n,Cu);const t=n instanceof Map?n.entries():Object.entries(n),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof Ye||(r=new Ye(r));let a=Mi(i);return r.value===!0?a+=dr(r.params):(a+="=",Array.isArray(r.value)?a+=Xu(r):a+=bo(r)),a}).join(`,${s}`)}function Do(n,e){return zu(n,e)}const Ge="CMCD-Object",ue="CMCD-Request",ut="CMCD-Session",et="CMCD-Status",Qu={br:Ge,ab:Ge,d:Ge,ot:Ge,tb:Ge,tpb:Ge,lb:Ge,tab:Ge,lab:Ge,url:Ge,pb:ue,bl:ue,tbl:ue,dl:ue,ltc:ue,mtp:ue,nor:ue,nrr:ue,rc:ue,sn:ue,sta:ue,su:ue,ttfb:ue,ttfbb:ue,ttlb:ue,cmsdd:ue,cmsds:ue,smrt:ue,df:ue,cs:ue,ts:ue,cid:ut,pr:ut,sf:ut,sid:ut,st:ut,v:ut,msd:ut,bs:et,bsd:et,cdn:et,rtp:et,bg:et,pt:et,ec:et,e:et},Zu={REQUEST:ue};function Ju(n){return Object.keys(n).reduce((e,t)=>{var s;return(s=n[t])===null||s===void 0||s.forEach(i=>e[i]=t),e},{})}function ed(n,e){const t={};if(!n)return t;const s=Object.keys(n),i=e?Ju(e):{};return s.reduce((r,a)=>{var o;const c=Qu[a]||i[a]||Zu.REQUEST,l=(o=r[c])!==null&&o!==void 0?o:r[c]={};return l[a]=n[a],r},t)}function td(n){return["ot","sf","st","e","sta"].includes(n)}function sd(n){return typeof n=="number"?M(n):n!=null&&n!==""&&n!==!1}const Co="event";function id(n,e){const t=new URL(n),s=new URL(e);if(t.origin!==s.origin)return n;const i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1);for(;i[0]===r[0];)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")+t.search+t.hash}const Ss=n=>Math.round(n),Ni=(n,e)=>Array.isArray(n)?n.map(t=>Ni(t,e)):n instanceof Ye&&typeof n.value=="string"?new Ye(Ni(n.value,e),n.params):(e.baseUrl&&(n=id(n,e.baseUrl)),e.version===1?encodeURIComponent(n):n),rs=n=>Ss(n/100)*100,rd=(n,e)=>{let t=n;return e.version>=2&&(n instanceof Ye&&typeof n.value=="string"?t=new Ye([n]):typeof n=="string"&&(t=[n])),Ni(t,e)},nd={br:Ss,d:Ss,bl:rs,dl:rs,mtp:rs,nor:rd,rtp:rs,tb:Ss},Po="request",ko="response",fr=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],ad=["e"],od=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Vs(n){return od.test(n)}function ld(n){return fr.includes(n)||ad.includes(n)||Vs(n)}const wo=["d","dl","nor","ot","rtp","su"];function cd(n){return fr.includes(n)||wo.includes(n)||Vs(n)}const hd=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function ud(n){return fr.includes(n)||wo.includes(n)||hd.includes(n)||Vs(n)}const dd=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function fd(n){return dd.includes(n)||Vs(n)}const gd={[ko]:ud,[Co]:ld,[Po]:cd};function Oo(n,e={}){const t={};if(n==null||typeof n!="object")return t;const s=e.version||n.v||1,i=e.reportingMode||Po,r=s===1?fd:gd[i];let a=Object.keys(n).filter(r);const o=e.filter;typeof o=="function"&&(a=a.filter(o));const c=i===ko||i===Co;c&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");const l=re({},nd,e.formatters),h={version:s,reportingMode:i,baseUrl:e.baseUrl};return a.sort().forEach(u=>{let d=n[u];const f=l[u];if(typeof f=="function"&&(d=f(d,h)),u==="v"){if(s===1)return;d=s}u=="pr"&&d===1||(c&&u==="ts"&&!M(d)&&(d=Date.now()),sd(d)&&(td(u)&&typeof d=="string"&&(d=new Io(d)),t[u]=d))}),t}function md(n,e={}){const t={};if(!n)return t;const s=Oo(n,e),i=ed(s,e==null?void 0:e.customHeaderMap);return Object.entries(i).reduce((r,[a,o])=>{const c=Do(o,{whitespace:!1});return c&&(r[a]=c),r},t)}function pd(n,e,t){return re(n,md(e,t))}const yd="CMCD";function Ed(n,e={}){return n?Do(Oo(n,e),{whitespace:!1}):""}function Td(n,e={}){if(!n)return"";const t=Ed(n,e);return encodeURIComponent(t)}function Sd(n,e={}){if(!n)return"";const t=Td(n,e);return`${yd}=${t}`}const On=/CMCD=[^&#]+/;function vd(n,e,t){const s=Sd(e,t);if(!s)return n;if(On.test(n))return n.replace(On,s);const i=n.includes("?")?"&":"?";return`${n}${i}${s}`}class xd{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:_e.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const{frag:r,part:a}=i,o=this.hls.levels[r.level],c=this.getObjectType(r),l={d:(a||r).duration*1e3,ot:c};(c===_e.VIDEO||c===_e.AUDIO||c==_e.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));const h=a?this.getNextPart(a):this.getNextFrag(r);h!=null&&h.url&&h.url!==r.url&&(l.nor=h.url),this.apply(i,l)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHED,this.onMediaDetached,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHED,this.onMediaDetached,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:Du.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){re(t,this.createData());const s=t.ot===_e.INIT||t.ot===_e.VIDEO||t.ot===_e.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((a,o)=>(i.includes(o)&&(a[o]=t[o]),a),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),pd(e.headers,t,r)):e.url=vd(e.url,t,r)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,r=(t=this.hls.levels[i.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:a}=i;for(let o=r.length-1;o>=0;o--){const c=r[o];if(c.index===s&&c.fragment.sn===a)return r[o+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return _e.TIMED_TEXT;if(e.sn==="initSegment")return _e.INIT;if(t==="audio")return _e.AUDIO;if(t==="main")return this.hls.audioTracks.length?_e.VIDEO:_e.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===_e.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,a=r>-1?r+1:i.levels.length;s=i.levels.slice(0,a)}return s.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===_e.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:q.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}}const Ad=3e5;class _d extends Fe{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(s=>s!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((s==null?void 0:s.action)===Ee.SendAlternateToPenaltyBox&&s.flags===Re.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:c,type:l}=t.context;o&&i?a=this.getPathwayForGroupId(o,l,a):c&&(a=c)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&i&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==a),t.details===R.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${oe(r)} penalized: ${oe(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>Ad&&delete s[r]});for(let r=0;r<e.length;r++){const a=e[r];if(a in s)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,c=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,Ja(t),this.hls.trigger(m.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[o];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===Q.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===Q.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":c}=r;if(t.some(h=>h.pathwayId===a))return;const l=this.getLevelsForPathway(o).map(h=>{const u=new le(h.attrs);u["PATHWAY-ID"]=a;const d=u.AUDIO&&`${u.AUDIO}_clone_${a}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),f&&(i[u.SUBTITLES]=f,u.SUBTITLES=f);const g=Fo(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),p=new Kt({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:g,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let y=1;y<h.audioGroups.length;y++)p.addGroupId("audio",`${h.audioGroups[y]}_clone_${a}`);if(h.subtitleGroups)for(let y=1;y<h.subtitleGroups.length;y++)p.addGroupId("text",`${h.subtitleGroups[y]}_clone_${a}`);return p});t.push(...l),Fn(this.audioTracks,s,c,a),Fn(this.subtitleTracks,i,c,a)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:i.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},c={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(h,u,d,f)=>{this.log(`Loaded steering manifest: "${i}"`);const g=h.data;if((g==null?void 0:g.VERSION)!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":E}=g;if(p)try{this.uri=new self.URL(p,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||d.url),y&&this.clonePathways(y);const T={steeringManifest:g,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,T),E&&this.updatePathwayPriority(E)},onError:(h,u,d,f)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let g=this.timeToLoad*1e3;if(h.code===429){const p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){const y=p.getResponseHeader("Retry-After");y&&(g=parseFloat(y)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,g)},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Fn(n,e,t,s){n&&Object.keys(e).forEach(i=>{const r=n.filter(a=>a.groupId===i).map(a=>{const o=re({},a);return o.details=void 0,o.attrs=new le(o.attrs),o.url=o.attrs.URI=Fo(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});n.push(...r)})}function Fo(n,e,t,s){const{HOST:i,PARAMS:r,[t]:a}=s;let o;e&&(o=a==null?void 0:a[e],o&&(n=o));const c=new self.URL(n);return i&&!o&&(c.host=i),r&&Object.keys(r).sort().forEach(l=>{l&&c.searchParams.set(l,r[l])}),c.href}class Lt extends Fe{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=Lt.CDMCleanupPromise?[Lt.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:s,initData:i}=t,r=`"${t.type}" event: init data type: "${s}"`;if(this.debug(r),i!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Ft(this.config));const o=a.map(Qs).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=ys(a);if(s!=="sinf"||o!==he.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let c;try{const f=ge(new Uint8Array(i)),g=tr(JSON.parse(f).sinf),p=ba(g);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(p.subarray(8,24))}catch(f){this.warn(`${r} Failed to parse sinf: ${f}`);return}const l=Te(c),{keyIdToKeySessionPromise:h,mediaKeySessions:u}=this;let d=h[l];for(let f=0;f<u.length;f++){const g=u[f],p=g.decryptdata;if(!p.keyId)continue;const y=Te(p.keyId);if(Os(c,p.keyId)||p.uri.replace(/-/g,"").indexOf(l)!==-1){if(d=h[y],!d)continue;if(p.pssh)break;delete h[y],p.pssh=new Uint8Array(i),p.keyId=c,d=h[l]=d.then(()=>this.generateRequestWithPreferredKeySession(g,s,i,"encrypted-event-key-match")),d.catch(E=>this.handleError(E));break}}d||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${u.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(m.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(m.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,i=t==null?void 0:t[e];if(i)return i.licenseUrl;if(e===he.WIDEVINE&&s)return s}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=t==null?void 0:t[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(a,o,c)=>!!a&&c.indexOf(a)===o,i=t.map(a=>a.audioCodec).filter(s),r=t.map(a=>a.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,o)=>{const c=l=>{const h=l.shift();this.getMediaKeysPromise(h,i,r).then(u=>a({keySystem:h,mediaKeys:u})).catch(u=>{l.length?c(l):u instanceof Le?o(u):o(new Le({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return Wa===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;const r=rh(e,t,s,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],o=(i=a)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${oe(r)}`),o=this.requestMediaKeySystemAccess(e,r);const c=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const u=c.mediaKeys=l.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,h.then(f=>f?this.setMediaKeysServerCertificate(d,e,f):d)));return u.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),u})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Te(e.keyId||[])} keyUri: ${e.uri}`);const i=s.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),i=ns(t),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${Te(e.decryptdata.keyId||[])}
116116- } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Qs(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:i})=>{const r=Qs(i);r?t(r):s(new Error(`Unable to find format for key-system "${i}"`))}).catch(s)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=Ft(this.config),s=e.map(ys).filter(i=>!!i&&t.indexOf(i)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const i=Id(e,t[s]);if(i)return i}}loadKey(e){const t=e.keyInfo.decryptdata,s=ns(t),i=this.bannedKeyIds[s];if(i||this.getKeyStatus(t)==="internal-error"){const o=Mn(i||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}const r=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);const a=this.keyIdToKeySessionPromise[s];if(!a){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:c,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(c,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:l,decryptdata:t}))))).then(c=>{const l="cenc",h=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,l,h,"playlist-key")});return o.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return a.catch(o=>{if(o instanceof Le){const c=se({},o.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const l=new Le(c,o.message);this.handleError(l,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Le){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Te(s.keyId||[])})`:""}`),this.hls.trigger(m.ERROR,e.data)}else this.error(e.message),this.hls.trigger(m.ERROR,{type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=ns(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=ys(e.keyFormat),r=i?[i]:Ft(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Ft(this.config)),e.length===0)throw new Le({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${oe({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>s.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,s,i){var r;const a=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(a)try{const g=a.call(this.hls,t,s,e);if(!g)throw new Error("Invalid response from configured generateRequest filter");t=g.initDataType,s=g.initData?g.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(g){if(this.warn(g.message),this.hls&&this.hls.config.debug)throw g}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const o=ns(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${o} URI: ${c} (init data type: ${t} length: ${s.byteLength})`);const l=new ir,h=e._onmessage=g=>{const p=e.mediaKeysSession;if(!p){l.emit("error",new Error("invalid state"));return}const{messageType:y,message:E}=g;this.log(`"${y}" message event for session "${p.sessionId}" message size: ${E.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,E).catch(T=>{l.eventNames().length?l.emit("error",T):this.handleError(T)}):y==="license-release"?e.keySystem===he.FAIRPLAY&&this.updateKeySession(e,Di("acknowledged")).then(()=>this.removeSession(e)).catch(T=>this.handleError(T)):this.warn(`unhandled media key message type "${y}"`)},u=(g,p)=>{p.keyStatus=g;let y;g.startsWith("usable")?l.emit("resolved"):g==="internal-error"||g==="output-restricted"||g==="output-downscaled"?y=Mn(g,p.decryptdata):g==="expired"?y=new Error(`key expired (keyId: ${o})`):g==="released"?y=new Error("key released"):g==="status-pending"||this.warn(`unhandled key status change "${g}" (keyId: ${o})`),y&&(l.eventNames().length?l.emit("error",y):this.handleError(y))},d=e._onkeystatuseschange=g=>{if(!e.mediaKeysSession){l.emit("error",new Error("invalid state"));return}const y=this.getKeyStatuses(e);if(!Object.keys(y).some(v=>y[v]!=="status-pending"))return;if(y[o]==="expired"){this.log(`Expired key ${oe(y)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let T=y[o];if(T)u(T,e);else{var S;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(S=e.keyStatusTimeouts)[o]||(S[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const x=this.getKeyStatus(e.decryptdata);if(x&&x!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${x} from other session.`),u(x,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),T="internal-error",u(T,e)},1e3)),this.log(`No status for keyId ${o} (${oe(y)}).`)}};Ae(e.mediaKeysSession,"message",h),Ae(e.mediaKeysSession,"keystatuseschange",d);const f=new Promise((g,p)=>{l.on("error",p),l.on("resolved",g)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(g=>{throw new Le({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_SESSION,error:g,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw g}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,i)=>{if(typeof i=="string"&&typeof s=="object"){const o=i;i=s,s=o}const r="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===he.PLAYREADY&&r.length===16){const o=Te(r);t[o]=s,Va(r)}const a=Te(r);s==="internal-error"&&(this.bannedKeyIds[a]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=s}),t}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const c={responseType:"arraybuffer",url:r},l=t.certLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,p)=>{a(d.data)},onError:(d,f,g,p)=>{o(new Le({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:se({url:c.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,g)=>{o(new Le({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,f,g)=>{o(new Error("aborted"))}};i.load(c,h,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(a=>{r(new Le({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new Le({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let u=0,d=r.length;u<d;u++){var a,o;h=r[u];const f=(a=h.querySelector("name"))==null?void 0:a.textContent,g=(o=h.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}const c=i.querySelector("Challenge"),l=c==null?void 0:c.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Di(atob(l))}setupLicenseXHR(e,t,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(a=>{if(!s.decryptdata)throw a;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const l=this.config.licenseResponseCallback;if(l)try{c=l.call(this.hls,o,a,e)}catch(h){this.error(h)}i(c)}else{const c=s.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)r(new Le({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const h=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:c,licenseChallenge:l})=>{e.keySystem==he.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(c,l)),c.send(l)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,Ae(s,"encrypted",this.onMediaEncrypted),Ae(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(Ie(e,"encrypted",this.onMediaEncrypted),Ie(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,nt.clearKeyUriToKeyIdMap();const r=i.length;Lt.CDMCleanupPromise=Promise.all(i.map(a=>this.removeSession(a)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:i}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Te((i==null?void 0:i.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(l=>self.clearTimeout(a[l]));const{drmSystemOptions:o}=this.config;return(ah(o)?new Promise((l,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l).catch(h)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>t.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}}Lt.CDMCleanupPromise=void 0;function ns(n){if(!n)throw new Error("Could not read keyId of undefined decryptdata");if(n.keyId===null)throw new Error("keyId is null");return Te(n.keyId)}function Id(n,e){if(n.keyId&&e.mediaKeysSession.keyStatuses.has(n.keyId))return e.mediaKeysSession.keyStatuses.get(n.keyId);if(n.matches(e.decryptdata))return e.keyStatus}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}}function Mn(n,e){const t=n==="output-restricted",s=t?R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:R.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Le({type:H.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${n}"`)}class Ld{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const r=i-this.lastTime,a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,c=1e3*a/r,l=this.hls;if(l.trigger(m.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),c>0&&a>l.config.fpsDroppedMonitoringThreshold*o){let h=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=h)&&(h=h-1,l.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function Mo(n,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=n,e.dispatchEvent(t)}function No(n,e){const t=n.mode;if(t==="disabled"&&(n.mode="hidden"),n.cues&&!n.cues.getCueById(e.id))try{if(n.addCue(e),!n.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){ie.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,n.addCue(i)}catch(i){ie.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(n.mode=t)}function At(n,e){const t=n.mode;if(t==="disabled"&&(n.mode="hidden"),n.cues)for(let s=n.cues.length;s--;)e&&n.cues[s].removeEventListener("enter",e),n.removeCue(n.cues[s]);t==="disabled"&&(n.mode=t)}function Bi(n,e,t,s){const i=n.mode;if(i==="disabled"&&(n.mode="hidden"),n.cues&&n.cues.length>0){const r=bd(n.cues,e,t);for(let a=0;a<r.length;a++)(!s||s(r[a]))&&n.removeCue(r[a])}i==="disabled"&&(n.mode=i)}function Rd(n,e){if(e<=n[0].startTime)return 0;const t=n.length-1;if(e>n[t].endTime)return-1;let s=0,i=t,r;for(;s<=i;)if(r=Math.floor((i+s)/2),e<n[r].startTime)i=r-1;else if(e>n[r].startTime&&s<t)s=r+1;else return r;return n[s].startTime-e<e-n[i].startTime?s:i}function bd(n,e,t){const s=[],i=Rd(n,e);if(i>-1)for(let r=i,a=n.length;r<a;r++){const o=n[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function vs(n){const e=[];for(let t=0;t<n.length;t++){const s=n[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(n[t])}return e}class Dd extends hr{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const s=vs(this.media.textTracks);for(let r=0;r<s.length;r++)if(s[r].mode==="hidden")t=s[r];else if(s[r].mode==="showing"){t=s[r];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const s=this.media;if(!s)return;const i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;vs(s.textTracks).forEach(a=>{At(a)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(i==null?void 0:i.length)!==(s==null?void 0:s.length)||s!=null&&s.some(a=>(i==null?void 0:i.indexOf(a))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,u)=>{h.id=u});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=He(o,a);if(h>-1)r=a[h];else{const u=He(o,this.tracks);r=this.tracks[u]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const l={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s==null?void 0:s.join(",")}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,l),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||gt(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(Yt(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(Yt(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(Oi(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Q.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&>(e,s))return s;const i=He(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}else{if(s)return null;{const r=He(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=vs(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(r=>Oi(s,r))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==i&&(r.mode="disabled")}),i){const r=this.subtitleDisplay?"showing":"hidden";i.mode!==r&&(i.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!M(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:a,groupId:o="",name:c,type:l,url:h}=i;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:c,type:l,url:h});const u=this.switchParams(i.url,s==null?void 0:s.details,i.details);this.loadPlaylist(u)}}function Cd(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?r:r&3|8).toString(16)})}}}function Ut(n){let e=5381,t=n.length;for(;t;)e=e*33^n.charCodeAt(--t);return(e>>>0).toString()}const Rt=.025;let Bs=function(n){return n[n.Point=0]="Point",n[n.Range=1]="Range",n}({});function Pd(n,e,t){return`${n.identifier}-${t+1}-${Ut(e)}`}class kd{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return ai(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,s=ai(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=M(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return ai(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Rt))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?Bs.Range:Bs.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return wd(this)}}function ai(n,e){return n-e.start<e.duration/2&&!(Math.abs(n-(e.start+e.duration))<Rt)?e.start:e.start+e.duration}function Bo(n,e,t){const s=new self.URL(n,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function oi(n,e){for(;(t=n.assetList[++e])!=null&&t.error;)var t;return e}function wd(n){return`["${n.identifier}" ${n.cue.pre?"<pre>":n.cue.post?"<post>":""}${n.timelineStart.toFixed(2)}-${n.resumeTime.toFixed(2)}]`}function xt(n){const e=n.timelineStart,t=n.duration||0;return`["${n.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class Od{constructor(e,t,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(m.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=s,this.assetItem=i;const a=()=>{this.hasDetails=!0};r.once(m.LEVEL_LOADED,a),r.once(m.AUDIO_TRACK_LOADED,a),r.once(m.SUBTITLE_TRACK_LOADED,a),r.on(m.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(m.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,r.trigger(m.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Bo(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,r=q.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=s-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=q.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;(i=this.hls)==null||i.on(e,t)}once(e,t,s){var i;(i=this.hls)==null||i.once(e,t)}off(e,t,s){var i;(i=this.hls)==null||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${xt(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Nn=.033;class Fd extends Fe{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(r=i[s])!=null&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(t&&t!=="primary"&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const r=s[i].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const a=s[r];if(!a.error){const o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:i}=s,r=this.events,a=this.parseDateRanges(i,{url:s.url},t),o=Object.keys(i),c=r?r.filter(l=>!o.includes(l.identifier)):[];a.length&&a.sort((l,h)=>{const u=l.cue.pre,d=l.cue.post,f=h.cue.pre,g=h.cue.post;if(u&&!f)return-1;if(f&&!u||d&&!g)return 1;if(g&&!d)return-1;if(!u&&!f&&!d&&!g){const p=l.startTime,y=h.startTime;if(p!==y)return p-y}return l.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=a,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],s=!1){const i=this.events||[];if(i.length||t.length||this.length<2){const r=this.items,a=this.parseSchedule(i,e);(s||t.length||(r==null?void 0:r.length)!==a.length||a.some((c,l)=>Math.abs(c.playout.start-r[l].playout.start)>.005||Math.abs(c.playout.end-r[l].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let a=0;a<r.length;a++){const o=r[a],c=e[o];if(c.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(c):(l=new kd(c,t),this.eventMap[o]=l,s===!1&&(l.appendInPlace=s)),i.push(l)}}return i}parseSchedule(e,t){const s=[],i=t.main.details,r=i.live?1/0:i.edge;let a=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,l=0;if(e.forEach((h,u)=>{const d=h.cue.pre,f=h.cue.post,g=e[u-1]||null,p=h.appendInPlace,y=f?r:h.startOffset,E=h.duration,T=h.timelineOccupancy===Bs.Range?E:0,S=h.resumptionOffset,v=(g==null?void 0:g.startTime)===y,x=y+h.cumulativeDuration;let D=p?x+E:y+S;if(d||!f&&y<=0){const b=l;l+=T,h.timelineStart=x;const I=a;a+=E,s.push({event:h,start:x,end:D,playout:{start:I,end:a},integrated:{start:b,end:l}})}else if(y<=r){if(!v){const _=y-c;if(_>Nn){const C=c,k=l;l+=_;const B=a;a+=_;const K={previousEvent:e[u-1]||null,nextEvent:h,start:C,end:C+_,playout:{start:B,end:a},integrated:{start:k,end:l}};s.push(K)}else _>0&&g&&(g.cumulativeDuration+=_,s[s.length-1].end=y)}f&&(D=x),h.timelineStart=x;const b=l;l+=T;const I=a;a+=E,s.push({event:h,start:x,end:D,playout:{start:I,end:a},integrated:{start:b,end:l}})}else return;const A=h.resumeTime;f||A>r?c=r:c=A}),c<r){var o;const h=c,u=l,d=r-c;l+=d;const f=a;a+=d,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:c,end:h+d,playout:{start:f,end:a},integrated:{start:u,end:l}})}this.setDurations(r,a,l)}else s.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,a=-1;e.forEach((o,c)=>{const l=o.cue.pre,h=o.cue.post,u=l?0:h?i:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=r:(r=0,a=u),!h&&o.snapOptions.in&&(o.resumeAnchor=mt(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1<e.length&&e[c+1].startTime-e[c].resumeTime<Nn&&(e[c+1].appendInPlace=!1,e[c+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=M(o.resumeOffset)?o.resumeOffset:o.duration;r+=f})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>Rt?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(a=>{const o=t[a].details,c=o.edge;if(s>=c)return this.log(`"${e.identifier}" resumption ${s} past ${a} playlist end ${c}`),!1;const l=mt(null,o.fragments,s);if(!l)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=a==="audio"?.175:0;return Math.abs(l.start-s)<Rt+h||Math.abs(l.end-s)<Rt+h?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${a} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;for(let a=0;a<e.assetList.length;a++){const o=e.assetList[a],c=t+s;o.startOffset=s,o.timelineStart=c,i||(i=o.duration===null),r||(r=!!o.error);const l=o.error?0:o.duration||0;s+=l}i&&!r?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function Ne(n){return`[${n.event?'"'+n.event.identifier+'"':"primary"}: ${n.start.toFixed(2)}-${n.end.toFixed(2)}]`}class Md{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=Bo(s,this.hls.sessionId,e.baseUrl)}catch(d){const f=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,d,s);this.hls.trigger(m.ERROR,f);return}t&&i.protocol!=="data:"&&i.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,a=r.loader,o=new a(r),c={responseType:"json",url:i.href},l=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,p)=>{const y=d.data,E=y==null?void 0:y.ASSETS;if(!Array.isArray(E)){const T=this.assignAssetListError(e,R.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,p);this.hls.trigger(m.ERROR,T);return}e.assetListResponse=y,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:y,networkDetails:p})},onError:(d,f,g,p)=>{const y=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${f.url})`),f.url,p,g);this.hls.trigger(m.ERROR,y)},onTimeout:(d,f,g)=>{const p=this.assignAssetListError(e,R.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,d,g);this.hls.trigger(m.ERROR,p)}};return o.load(c,h,u),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,r,a){return e.error=s,{type:H.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:a,stats:r}}}function Bn(n){var e;n==null||(e=n.play())==null||e.catch(()=>{})}function as(n,e){return`[${n}] Advancing timeline position to ${e}`}class Nd extends Fe{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const a=i<=-.01;this.timelinePos=s,this.bufferedPos=s;const o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),a&&s<o.start||s>=o.end){var c;const f=this.findItemIndex(o);let g=this.schedule.findItemIndexAtTime(s);if(g===-1&&(g=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${s} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!a&&g>f){const p=this.schedule.findJumpRestrictedIndex(f+1,g);if(p>f){this.setSchedulePosition(p);return}}this.setSchedulePosition(g);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}return}const h=l.timelineStart,u=l.duration||0;if(a&&s<h||s>=h+u){var d;(d=o.event)!=null&&d.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,l)}},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;const o=this.findItemIndex(i);this.setSchedulePosition(o+1)}const r=this.playingAsset;if(!r)return;const a=r.timelineStart+(r.duration||0);s>=a&&this.setScheduleToAssetAtTime(s,r)},this.onScheduleUpdate=(s,i)=>{const r=this.schedule;if(!r)return;const a=this.playingItem,o=r.events||[],c=r.items||[],l=r.durations,h=s.map(p=>p.identifier),u=!!(o.length||h.length);(u||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
117117-Schedule: ${c.map(p=>Ne(p))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let d=null,f=null;a&&(d=this.updateItem(a,this.timelinePos),this.itemsMatch(a,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const g=this.bufferingItem;if(g&&(f=this.updateItem(g,this.bufferedPos),this.itemsMatch(g,f)?this.bufferingItem=f:g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.event,null))),s.forEach(p=>{p.assetList.forEach(y=>{this.clearAssetPlayer(y.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){const y=p.assetItem.timelineStart,E=p.timelineOffset-y;if(E)try{p.timelineOffset=y}catch(T){Math.abs(E)>Rt&&this.warn(`${T} ("${p.assetId}" ${p.timelineOffset}->${y})`)}}}),u||i){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:l,removedIds:h}),this.isInterstitial(a)&&h.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(d,a),g&&f!==d&&this.trimInPlace(f,g),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Md(e),this.schedule=new Fd(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(m.MEDIA_ENDED,this.onMediaEnded,this),e.on(m.ERROR,this.onError,this),e.on(m.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(m.MEDIA_ENDED,this.onMediaEnded,this),e.off(m.ERROR,this.onError,this),e.off(m.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Ie(e,"play",this.onPlay),Ie(e,"pause",this.onPause),Ie(e,"seeking",this.onSeeking),Ie(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;Ae(s,"seeking",this.onSeeking),Ae(s,"timeupdate",this.onTimeupdate),Ae(s,"play",this.onPlay),Ae(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();const r=this.findItemIndex(s);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=u=>u&&e.getAssetPlayer(u.identifier),i=(u,d,f,g,p)=>{if(u){let y=u[d].start;const E=u.event;if(E){if(d==="playout"||E.timelineOccupancy!==Bs.Point){const T=s(f);(T==null?void 0:T.interstitial)===E&&(y+=T.assetItem.startOffset+T[p])}}else{const T=g==="bufferedPos"?a():e[g];y+=T-u.start}return y}return 0},r=(u,d)=>{var f;if(u!==0&&d!=="primary"&&(f=e.schedule)!=null&&f.length){var g;const p=e.schedule.findItemIndexAtTime(u),y=(g=e.schedule.items)==null?void 0:g[p];if(y){const E=y[d].start-y.start;return u+E}}return u},a=()=>{const u=e.bufferedPos;return u===Number.MAX_VALUE?o("primary"):Math.max(u,0)},o=u=>{var d,f;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[u])||0},c=(u,d)=>{var f,g;const p=e.effectivePlayingItem;if(p!=null&&(f=p.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${u} "${d}"`);const y=e.effectivePlayingItem,E=e.schedule.findItemIndexAtTime(u,d),T=(g=e.schedule.items)==null?void 0:g[E],S=e.getBufferingPlayer(),v=S==null?void 0:S.interstitial,x=v==null?void 0:v.appendInPlace,D=y&&e.itemsMatch(y,T);if(y&&(x||D)){const A=s(e.playingAsset),b=(A==null?void 0:A.media)||e.primaryMedia;if(b){const I=d==="primary"?b.currentTime:i(y,d,e.playingAsset,"timelinePos","currentTime"),_=u-I,C=(x?I:b.currentTime)+_;if(C>=0&&(!A||x||C<=A.duration)){b.currentTime=C;return}}}if(T){let A=u;if(d!=="primary"){const I=T[d].start,_=u-I;A=T.start+_}const b=!e.isInterstitial(T);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(b||T.event.appendInPlace)){const I=e.media||(x?S==null?void 0:S.media:null);I&&(I.currentTime=A)}else if(y){const I=e.findItemIndex(y);if(E>I){const C=e.schedule.findJumpRestrictedIndex(I+1,E);if(C>I){e.setSchedulePosition(C);return}}let _=0;if(b)e.timelinePos=A,e.checkBuffer();else{const C=T.event.assetList,k=u-(T[d]||T).start;for(let B=C.length;B--;){const K=C[B];if(K.duration&&k>=K.startOffset&&k<K.startOffset+K.duration){_=B;break}}}e.setSchedulePosition(E,_)}}},l=()=>{const u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;const d=t();return e.isInterstitial(d)?d:null},h={get bufferedEnd(){const u=t(),d=e.bufferingItem;if(d&&d===u){var f;return i(d,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const u=l(),d=e.effectivePlayingItem;return d&&d===u?i(d,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(u){const d=l(),f=e.effectivePlayingItem;f&&f===d&&c(u+f.playout.start,"playout")},get duration(){const u=l();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;const d=(u=l())==null?void 0:u.event.assetList;return d?d.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var u;const d=(u=l())==null?void 0:u.event;return d&&e.effectivePlayingAsset?d.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var u;return((u=e.schedule)==null||(u=u.events)==null?void 0:u.slice(0))||[]},get schedule(){var u;return((u=e.schedule)==null||(u=u.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return l()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return a()},get currentTime(){const u=e.timelinePos;return u>0?u:0},set currentTime(u){c(u,"primary")},get duration(){return o("primary")},get seekableStart(){var u;return((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(u){c(u,"integrated")},get duration(){return o("integrated")},get seekableStart(){var u;return r(((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0,"integrated")}},skip:()=>{const u=e.effectivePlayingItem,d=u==null?void 0:u.event;if(d&&!d.restrictions.skip){const f=e.findItemIndex(u);if(d.appendInPlace){const g=u.playout.start+u.event.duration;c(g+.001,"playout")}else e.advanceAfterAssetEnded(d,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);const r=(t=i)==null?void 0:t.currentTime;if(!(r===void 0||!M(r)))return r}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i){this.detachedData={media:i};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${oe(r)}`),this.detachedData=r}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null;const a=this.hls,o=e!==a,c=o&&e.interstitial.appendInPlace,l=(s=this.detachedData)==null?void 0:s.mediaSource;let h;if(a.media)c&&(r=a.transferMedia(),this.detachedData=r),h="Primary";else if(l){const g=this.getBufferingPlayer();g?(r=g.transferMedia(),h=`${g}`):h="detached MediaSource"}else h="detached media";if(!r){if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${oe(r)}`);else if(!this.detachedData||a.media===t){const g=this.playerQueue;g.length>1&&g.forEach(p=>{if(o&&p.interstitial.appendInPlace!==c){const y=p.interstitial;this.clearInterstitial(p.interstitial,null),y.appendInPlace=!1,y.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${y}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const u=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed",d=u&&r?r:t;this.log(`${u?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`);const f=this.schedule;if(d===r&&f){const g=o&&e.assetId===f.assetIdAtEnd;d.overrides={duration:f.duration,endOfStream:!o||g,cueRemoval:!o}}e.attachMedia(d)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e==null?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const s=this.timelinePos,i=this.effectivePlayingItem;if(s===-1){const r=this.hls.startPosition;if(this.log(as("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(r>=0||!this.primaryLive){const a=this.timelinePos=r>0?r:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(i&&!this.playingItem){const r=e.findItemIndex(i);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const s=e.event,i=s.findAssetIndex(t),r=oi(s,i);if(!s.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var a;const o=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,s){const i=oi(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const r=this.schedule.items;if(r){const a=t+1,o=r.length;if(a>=o){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos<c&&(this.log(as("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&this.advanceInPlace(c),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){const r=e.assetList[i];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const i=t.parentIdentifier,r=s.getEvent(i);if(r){const a=s.findEventIndex(i),o=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,a,o-1)}}setSchedulePosition(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(!i||this.playbackDisabled)return;const r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Ne(r)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){const h=a.event,u=this.playingAsset,d=u==null?void 0:u.identifier,f=d?this.getAssetPlayer(d):null;if(f&&d&&(!this.eventItemsMatch(a,r)||t!==void 0&&d!==h.assetList[t].identifier)){var c;const g=h.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${g+1}/${h.assetList.length} ${xt(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:g,event:h,schedule:i.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),g);return}this.retreiveMediaSource(d,r),f.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,r)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${Ne(a)}`),h.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:h,schedule:i.slice(0),scheduleIndex:e}),h.cue.once)){var l;this.updateSchedule();const g=(l=this.schedule)==null?void 0:l.items;if(r&&g){const p=this.findItemIndex(r);this.advanceSchedule(p,g,t,a,o)}return}}this.advanceSchedule(e,i,t,a,o)}advanceSchedule(e,t,s,i,r){const a=this.schedule;if(!a)return;const o=t[e]||null,c=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(h=>{const u=h.interstitial,d=a.findEventIndex(u.identifier);(d<e||d>e+1)&&this.clearInterstitial(u,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const h=o.event;if(s===void 0){s=a.findAssetIndex(h,this.timelinePos);const g=oi(h,s-1);if(h.isAssetPastPlayoutLimit(g)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,e,s);return}s=g}const u=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let d=this.preloadAssets(h,s);if(this.eventItemsMatch(o,u||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Ne(o)} ${h.appendInPlace?"append in place":""}`),this.hls.trigger(m.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const f=h.assetList[s];if(!f){this.advanceAfterAssetEnded(h,e,s||0);return}if(d||(d=this.getAssetPlayer(f.identifier)),d===null||d.destroyed){const g=h.assetList.length;this.warn(`asset ${s+1}/${g} player destroyed ${h}`),d=this.createAssetPlayer(h,f,s),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(d,s,t,e,c),this.shouldPlay&&Bn(d.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&Bn(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,s){var i,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Ne(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(as("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!s)return;const a=(r=this.schedule)==null?void 0:r.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ne(e)}`),this.hls.trigger(m.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const i=this.primaryDetails;if(t===0)return this.hls.startPosition;if(i&&(s<i.fragmentStart||s>i.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:q.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(as("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs((((s=i.mainForwardBufferInfo)==null?void 0:s.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(m.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(m.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const i=se(se({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=se(se({},this.altSelection),{},{audio:s});return}const r=se(se({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=se(se({},this.altSelection),{},{subtitles:s});return}const r=se(se({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=Yr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Yr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(t)||t.id!==-1&&i.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let i=0;i<t.length;i++){const r=t[i];if(r.cue.post){var s;const a=this.schedule.findEventIndex(r.identifier),o=(s=this.schedule.items)==null?void 0:s[a];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(e&&i){const r=this.findItemIndex(e,t);return i[r]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(r.identifier,null)});const s=e.end+.25,i=q.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Ne(e)} (was ${Ne(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s)return;const i=q.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const a=this.playingItem,o=this.findItemIndex(a);let c=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const h=this.findItemIndex(r),u=Math.min(h+1,t.length-1),d=t[u];if((c===-1&&r&&e>=r.end||(l=d.event)!=null&&l.appendInPlace&&e+.01>=d.start)&&(c=u),this.isInterstitial(r)){const f=r.event;if(u-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,c>h&&c>o)this.bufferedToItem(d);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else s&&a&&!this.itemsMatch(a,r)&&(c===o?this.bufferedToItem(a):c===o+1&&this.bufferedToItem(t[c]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{const r=this.getAssetPlayer(i.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:i,events:r}=s;if(!i||!r)return t;const a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const c=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Ne(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const l=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,u)=>{const d=this.getAssetPlayer(h.identifier);d&&(u===l&&d.loadSource(),d.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(m.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;const i=this.detachedData;i?i.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,i=s.assetList.length===0&&!s.assetListLoader,r=s.cue.once;if(i||!r){const a=this.preloadAssets(s,t);if(a!=null&&a.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,r=i===0&&!e.assetListLoader,a=e.cue.once;if(r){const c=e.timelineStart;if(e.appendInPlace){var o;const d=this.playingItem;!this.isInterstitial(d)&&(d==null||(o=d.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(c+.25)}let l,h=0;if(!this.playingItem&&this.primaryLive&&(h=this.hls.startPosition,h===-1&&(h=this.hls.liveSyncPosition||0)),h&&!(e.cue.pre||e.cue.post)){const d=h-c;d>0&&(l=Math.round(d*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${l?` live-start: ${h} start-offset: ${l}`:""}`),s)return this.createAsset(e,0,0,c,e.duration,s);const u=this.assetListLoader.loadAssetList(e,l);u&&(e.assetListLoader=u)}else if(!a&&i){for(let l=t;l<i;l++){const h=e.assetList[l],u=this.getAssetPlayerQueueIndex(h.identifier);(u===-1||this.playerQueue[u].destroyed)&&!h.error&&this.createAssetPlayer(e,h,l)}const c=e.assetList[t];if(c){const l=this.getAssetPlayer(c.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(i=>{this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,i,r,a){const o={parentIdentifier:e.identifier,identifier:Pd(e,a,t),duration:r,startOffset:s,timelineStart:i,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){const i=this.hls,r=i.userConfig;let a=r.videoPreference;const o=i.loadLevelObj||i.levels[i.currentLevel];(a||o)&&(a=re({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));const c=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const v=this.timelinePos-t.timelineStart;if(v>1){const x=t.duration;x&&v<x&&(h=v)}}const u=t.identifier,d=se(se({},r),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:c||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const f=d.cmcd;f!=null&&f.sessionId&&f.contentId&&(d.cmcd=re({},f,{contentId:Ut(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);const g=new Od(this.HlsPlayerClass,d,e,t);this.playerQueue.push(g),e.assetList[s]=t;let p=!0;const y=v=>{if(v.live){var x;const b=new Error(`Interstitials MUST be VOD assets ${e}`),I={fatal:!0,type:H.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:b},_=((x=this.schedule)==null?void 0:x.findEventIndex(e.identifier))||-1;this.handleAssetItemError(I,e,_,s,b.message);return}const D=v.edge-v.fragmentStart,A=t.duration;(p||A===null||D>A)&&(p=!1,this.log(`Interstitial asset "${u}" duration change ${A} > ${D}`),t.duration=D,this.updateSchedule())};g.on(m.LEVEL_UPDATED,(v,{details:x})=>y(x)),g.on(m.LEVEL_PTS_UPDATED,(v,{details:x})=>y(x)),g.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const E=(v,x)=>{const D=this.getAssetPlayer(u);if(D&&x.tracks){D.off(m.BUFFER_CODECS,E),D.tracks=x.tracks;const A=this.primaryMedia;this.bufferingAsset===D.assetItem&&A&&!D.media&&this.bufferAssetPlayer(D,A)}};g.on(m.BUFFER_CODECS,E);const T=()=>{var v;const x=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${x}`),!x||!this.schedule)return;const D=this.schedule.findEventIndex(e.identifier),A=(v=this.schedule.items)==null?void 0:v[D];this.isInterstitial(A)&&this.advanceAssetBuffering(A,t)};g.on(m.BUFFERED_TO_END,T);const S=v=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;const D=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,D,v)};return g.once(m.MEDIA_ENDED,S(s)),g.once(m.PLAYOUT_LIMIT_REACHED,S(1/0)),g.on(m.ERROR,(v,x)=>{if(!this.schedule)return;const D=this.getAssetPlayer(u);if(x.details===R.BUFFER_STALLED_ERROR){if(D!=null&&D.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${x.error} ${e}`)}),g.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;const x=new Error(`Asset player destroyed unexpectedly ${u}`),D={fatal:!0,type:H.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:x};this.handleAssetItemError(D,e,this.schedule.findEventIndex(e.identifier),s,x.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${xt(t)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:g}),g}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){const i=this.playerQueue[s];this.log(`clear ${i} toSegment: ${t&&Ne(t)}`),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){const{interstitial:a,assetItem:o,assetId:c}=e,l=a.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!h||h.identifier!==c)&&(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${xt(o)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s,i;if(!this.schedule)return;const{interstitial:r,assetItem:a}=e,o=this.schedule.findEventIndex(r.identifier),c=(s=this.schedule.items)==null?void 0:s[o];if(!c)return;e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=a;const l=this.getBufferingPlayer();if(l===e)return;const h=r.appendInPlace;if(h&&(l==null?void 0:l.interstitial.appendInPlace)===!1)return;const u=(l==null?void 0:l.tracks)||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(h&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(u&&!Ta(u,e.tracks)){const d=new Error(`Asset ${xt(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),f={fatal:!0,type:H.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},g=r.findAssetIndex(a);this.handleAssetItemError(f,r,o,g,d.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const i=s.currentTime,r=t.findAssetIndex(e,i),a=e.assetList[r];if(a){const o=this.getAssetPlayer(a.identifier);if(o){const c=o.currentTime||i-a.timelineStart,l=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+l} in ${o} ${e} (media.currentTime: ${i})`),c&&(l/s.playbackRate<.5||o.bufferedInPlaceToEnd(s))&&o.hls){const h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,i,r){if(e.details===R.BUFFER_STALLED_ERROR)return;const a=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&xt(a)} ${e.error}`),!this.schedule)return;const o=(a==null?void 0:a.identifier)||"",c=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[c]||null,h=this.schedule.items,u=re({},e,{fatal:!1,errorAction:_t(!0),asset:a,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:l});if(this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;const d=this.playingAsset,f=this.bufferingAsset,g=new Error(r);if(a&&(this.clearAssetPlayer(o,null),a.error=g),!t.assetList.some(p=>!p.error))t.error=g;else for(let p=i;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===o?this.advanceAfterAssetEnded(t,s,i):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;let i=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${i} playing: ${Ne(s)} error: ${e.error}`),i===-1&&(i=this.hls.startPosition);const a=this.updateItem(s,i);this.itemsMatch(s,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(i===-1){this.checkStart();return}if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(r)}onAssetListLoaded(e,t){var s,i;const r=t.event,a=r.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(a)))return;const c=r.timelineStart,l=r.duration;let h=0;o.forEach((p,y)=>{const E=parseFloat(p.DURATION);this.createAsset(r,y,h,c+h,E,p.URI),h+=E}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const u=this.waitingItem,d=(u==null?void 0:u.event.identifier)===a;this.updateSchedule();const f=(i=this.bufferingItem)==null?void 0:i.event;if(d){var g;const p=this.schedule.findEventIndex(a),y=(g=this.schedule.items)==null?void 0:g[p];if(y){if(!this.playingItem&&this.timelinePos>y.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){r.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(y)}this.setSchedulePosition(p)}else if((f==null?void 0:f.identifier)===a){const p=r.assetList[0];if(p){const y=this.getAssetPlayer(p.identifier);if(f.appendInPlace){const E=this.primaryMedia;y&&E&&this.bufferAssetPlayer(y,E)}else y&&y.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case R.ASSET_LIST_PARSING_ERROR:case R.ASSET_LIST_LOAD_ERROR:case R.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case R.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const Un=500;class Bd extends sr{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",U.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=P.IDLE,this.setInterval(Un),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,success:i}=t;if(this.fragContextChanged(s)||(de(s)&&(this.fragPrevious=s),this.state=P.IDLE),!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let a;const o=s.start;for(let l=0;l<r.length;l++)if(o>=r[l].start&&o<=r[l].end){a=r[l];break}const c=s.start+s.duration;a?a.end=c:(a={start:o,end:c},r.push(a)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=r){a.shift();continue}else if(a[o].start<r)a[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,U.SUBTITLE)}}onError(e,t){const s=t.frag;(s==null?void 0:s.type)===U.SUBTITLE&&(t.details===R.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==P.STOPPED&&(this.state=P.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Ao(this.levels,t)){this.levels=t.map(s=>new Kt(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new Kt(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,U.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==P.STOPPED&&this.setInterval(Un)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:a,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=r[o];if(o>=r.length||!c)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(a.live||(s=c.details)!=null&&s.live){if(a.deltaUpdateFailed)return;const u=this.mainDetails;if(!u){this.startFragRequested=!1;return}const d=u.fragments[0];if(!c.details)a.hasProgramDateTime&&u.hasProgramDateTime?(Ms(a,u),l=a.fragmentStart):d&&(l=d.start,Pi(a,l));else{var h;l=this.alignPlaylists(a,c.details,(h=this.levelLastLoaded)==null?void 0:h.details),l===0&&d&&(l=d.start,Pi(a,l))}u&&!this.startFragRequested&&this.setStartPosition(u,l)}c.details=a,this.levelLastLoaded=c,o===i&&(this.hls.trigger(m.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===P.IDLE&&(mt(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&i!=null&&i.key&&i.iv&&It(i.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,er(i.method)).catch(o=>{throw r.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const c=performance.now();r.trigger(m.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=P.IDLE})}}doTick(){if(!this.media){this.state=P.IDLE;return}if(this.state===P.IDLE){const{currentTrackId:e,levels:t}=this,s=t==null?void 0:t[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),a=q.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:o,len:c}=a,l=s.details,h=this.hls.maxBufferLength+l.levelTargetDuration;if(c>h)return;const u=l.fragments,d=u.length,f=l.edge;let g=null;const p=this.fragPrevious;if(o<f){const T=i.maxFragLookUpTolerance,S=o>f-T?0:T;g=mt(p,u,Math.max(u[0].start,o),S),!g&&p&&p.start<u[0].start&&(g=u[0])}else g=u[d-1];if(g=this.filterReplacedPrimary(g,s.details),!g)return;const y=g.sn-l.startSN,E=u[y-1];if(E&&E.cc===g.cc&&this.fragmentTracker.getState(E)===me.NOT_LOADED&&(g=E),this.fragmentTracker.getState(g)===me.NOT_LOADED){const T=this.mapToInitFragWhenRequired(g);T&&this.loadFragment(T,s,o)}}}loadFragment(e,t,s){de(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Ud(this.tracksBuffered[this.currentTrackId]||[])}}class Ud{constructor(e){this.buffered=void 0;const t=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}const $d={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},Uo=n=>String.fromCharCode($d[n]||n),Be=15,Xe=100,Gd={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Kd={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Vd={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Hd={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Wd=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Yd{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;ie.log(`${this.time} [${e}] ${s}`)}}}const dt=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class $o{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class qd{constructor(){this.uchar=" ",this.penState=new $o}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 jd{constructor(e){this.chars=[],this.pos=0,this.currPenState=new $o,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Xe;t++)this.chars.push(new qd);this.logger=e}equals(e){for(let t=0;t<Xe;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Xe;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Xe;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>Xe&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Xe)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Uo(e);if(this.pos>=Xe){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<Xe;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<Xe;s++){const i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class li{constructor(e){this.rows=[],this.currRow=Be-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Be;t++)this.rows.push(new jd(e));this.logger=e}reset(){for(let e=0;e<Be;e++)this.rows[e].clear();this.currRow=Be-1}equals(e){let t=!0;for(let s=0;s<Be;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<Be;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Be;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 = "+oe(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<Be;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[r].cueStartTime,c=this.logger.time;if(o!==null&&c!==null&&o<c)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(a.rows[r+l])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,a=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[a].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+oe(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",i=-1;for(let r=0;r<Be;r++){const a=this.rows[r].getTextString();a&&(i=r+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
118118-`)),s}getTextAndFormat(){return this.rows}}class $n{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new li(s),this.nonDisplayedMemory=new li(s),this.lastOutputScreen=new li(s),this.currRollUpRow=this.displayedMemory.rows[Be-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Be-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+oe(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 Gn{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=zd(),this.logger=void 0;const i=this.logger=new Yd;this.channels=[null,new $n(e,t,i),new $n(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const i=t[s]&127,r=t[s+1]&127;let a=!1,o=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+dt([t[s],t[s+1]])+"] -> ("+dt([i,r])+")");const c=this.cmdHistory;if(i>=16&&i<=31){if(Xd(i,r,c)){os(null,null,c),this.logger.log(3,()=>"Repeated command ("+dt([i,r])+") is dropped");continue}os(i,r,this.cmdHistory),a=this.parseCmd(i,r),a||(a=this.parseMidrow(i,r)),a||(a=this.parsePAC(i,r)),a||(a=this.parseBackgroundAttributes(i,r))}else os(null,null,c);if(!a&&(o=this.parseChars(i,r),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+dt([i,r])+" orig: "+dt([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;const r=e===20||e===21||e===23?1:2,a=this.channels[r];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+dt([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(i||r))return!1;const a=e<=23?1:2;t>=64&&t<=95?s=a===1?Gd[e]:Vd[e]:s=a===1?Kd[e]:Hd[e];const o=this.channels[a];return o?(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=a,!0):!1}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let a;r===17?a=t+80:r===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+Uo(a)+"' in channel "+s),i=[a]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+dt(i).join(",")),i}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let r;const a={};e===16||e===24?(r=Math.floor((t-32)/2),a.background=Wd[r],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}os(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function os(n,e,t){t.a=n,t.b=e}function Xd(n,e,t){return t.a===n&&t.b===e}function zd(){return{a:null,b:null}}var gr=function(){if(Fs!=null&&Fs.VTTCue)return self.VTTCue;const n=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,c){if(typeof c!="string"||!Array.isArray(o))return!1;const l=c.toLowerCase();return~o.indexOf(l)?l:!1}function s(o){return t(n,o)}function i(o){return t(e,o)}function r(o,...c){let l=1;for(;l<arguments.length;l++){const h=arguments[l];for(const u in h)o[u]=h[u]}return o}function a(o,c,l){const h=this,u={enumerable:!0};h.hasBeenReset=!1;let d="",f=!1,g=o,p=c,y=l,E=null,T="",S=!0,v="auto",x="start",D=50,A="middle",b=50,I="middle";Object.defineProperty(h,"id",r({},u,{get:function(){return d},set:function(_){d=""+_}})),Object.defineProperty(h,"pauseOnExit",r({},u,{get:function(){return f},set:function(_){f=!!_}})),Object.defineProperty(h,"startTime",r({},u,{get:function(){return g},set:function(_){if(typeof _!="number")throw new TypeError("Start time must be set to a number.");g=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},u,{get:function(){return p},set:function(_){if(typeof _!="number")throw new TypeError("End time must be set to a number.");p=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},u,{get:function(){return y},set:function(_){y=""+_,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},u,{get:function(){return E},set:function(_){E=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},u,{get:function(){return T},set:function(_){const C=s(_);if(C===!1)throw new SyntaxError("An invalid or illegal string was specified.");T=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},u,{get:function(){return S},set:function(_){S=!!_,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},u,{get:function(){return v},set:function(_){if(typeof _!="number"&&_!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");v=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},u,{get:function(){return x},set:function(_){const C=i(_);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");x=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},u,{get:function(){return D},set:function(_){if(_<0||_>100)throw new Error("Position must be between 0 and 100.");D=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},u,{get:function(){return A},set:function(_){const C=i(_);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");A=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},u,{get:function(){return b},set:function(_){if(_<0||_>100)throw new Error("Size must be between 0 and 100.");b=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},u,{get:function(){return I},set:function(_){const C=i(_);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");I=C,this.hasBeenReset=!0}})),h.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class Qd{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Go(n){function e(s,i,r,a){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(a||0)}const t=n.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 Zd{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function Ko(n,e,t,s){const i=s?n.split(s):[n];for(const r in i){if(typeof i[r]!="string")continue;const a=i[r].split(t);if(a.length!==2)continue;const o=a[0],c=a[1];e(o,c)}}const Ui=new gr(0,0,""),ls=Ui.align==="middle"?"middle":"center";function Jd(n,e,t){const s=n;function i(){const o=Go(n);if(o===null)throw new Error("Malformed timestamp: "+s);return n=n.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,c){const l=new Zd;Ko(o,function(d,f){let g;switch(d){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){l.set(d,t[p].region);break}break;case"vertical":l.alt(d,f,["rl","lr"]);break;case"line":g=f.split(","),l.integer(d,g[0]),l.percent(d,g[0])&&l.set("snapToLines",!1),l.alt(d,g[0],["auto"]),g.length===2&&l.alt("lineAlign",g[1],["start",ls,"end"]);break;case"position":g=f.split(","),l.percent(d,g[0]),g.length===2&&l.alt("positionAlign",g[1],["start",ls,"end","line-left","line-right","auto"]);break;case"size":l.percent(d,f);break;case"align":l.alt(d,f,["start",ls,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let h=l.get("line","auto");h==="auto"&&Ui.line===-1&&(h=-1),c.line=h,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",ls);let u=l.get("position","auto");u==="auto"&&Ui.position===50&&(u=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=u}function a(){n=n.replace(/^\s+/,"")}if(a(),e.startTime=i(),a(),n.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);n=n.slice(3),a(),e.endTime=i(),a(),r(n,e)}function Vo(n){return n.replace(/<br(?: \/)?>/gi,`
119119-`)}class ef{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Qd,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function s(){let r=t.buffer,a=0;for(r=Vo(r);a<r.length&&r[a]!=="\r"&&r[a]!==`
120120-`;)++a;const o=r.slice(0,a);return r[a]==="\r"&&++a,r[a]===`
121121-`&&++a,t.buffer=r.slice(a),o}function i(r){Ko(r,function(a,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=s();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new gr(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Jd(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
122122-`),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
127127+${this.list("audiovideo")}}`}list(e){var t,r;return(t=this.queues)!=null&&t[e]||(r=this.tracks)!=null&&r[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const r=(t=this.tracks)==null?void 0:t[e],s=r==null?void 0:r.buffer;return s?`SourceBuffer${s.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(r=>r.label).join(", "))||""}}const Nd=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Ug="HlsJsTrackRemovedError";class $S extends Error{constructor(e){super(e),this.name=Ug}}class jS extends et{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=r=>{var s;this.hls&&((s=this.mediaSource)==null?void 0:s.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=r=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=r=>{const{media:s,mediaSource:n}=this;r&&this.log("Media source opened"),!(!s||!n)&&(n.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(E.MEDIA_ATTACHED,{media:s,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:r,_objectUrl:s}=this;r!==s&&this.error(`Media element src was set while attaching MediaSource (${s} > ${r})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=uv(Ot(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_APPENDING,this.onBufferAppending,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.BUFFER_EOS,this.onBufferEos,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.FRAG_PARSED,this.onFragParsed,this),e.on(E.FRAG_CHANGED,this.onFragChanged,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_APPENDING,this.onBufferAppending,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_EOS,this.onBufferEos,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.FRAG_PARSED,this.onFragParsed,this),e.off(E.FRAG_CHANGED,this.onFragChanged,this),e.off(E.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const r={};if(this.operationQueue){const n=this.isUpdating();n||this.operationQueue.removeBlockers();const a=this.isQueued();(n||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${n?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===t?ae(r,s.tracks):this.sourceBuffers.forEach(n=>{const[a]=n;a&&(r[a]=ae({},this.tracks[a]),this.removeBuffer(a)),n[0]=n[1]=null}),{media:e,mediaSource:t,tracks:r}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var r;let s=2;(t.audio&&!t.video||!t.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),(r=this.transferData)!=null&&r.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(e,t){const r=this.media=t.media;this.transferData=this.overrides=void 0;const s=Ot(this.appendSource);if(s){const n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const a=this.mediaSource=t.mediaSource||new s;if(this.assignMediaSource(a),n)this._objectUrl=r.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{r.removeAttribute("src");const u=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||u&&a instanceof u,Bd(r),GS(r,o),r.load()}catch{r.src=o}else r.src=o}r.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,r;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(r=e.constructor)==null?void 0:r.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const r=this.tracks,s=t.tracks,n=s?Object.keys(s):null,a=n?n.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&n&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
128128+required tracks: ${ue(r,(u,l)=>u==="initSegment"?void 0:l)};
129129+transfer tracks: ${ue(s,(u,l)=>u==="initSegment"?void 0:l)}}`),!Mf(s,r)){t.mediaSource=null,t.tracks=void 0;const u=e.currentTime,l=this.details,c=Math.max(u,(l==null?void 0:l.fragments[0].start)||0);if(c-u>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${u} -> ${c}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(r)}") start time: ${c} currentTime: ${u}`),this.onMediaDetaching(E.MEDIA_DETACHING,{}),this.onMediaAttaching(E.MEDIA_ATTACHING,t),e.currentTime=c;return}this.transferData=void 0,n.forEach(u=>{const l=u,c=s[l];if(c){const d=c.buffer;if(d){const h=this.fragmentTracker,f=c.id;if(h.hasFragments(f)||h.hasParts(f)){const m=Y.getBuffered(d);h.detectEvictedFragments(l,m,f,null,!0)}const g=ca(l),p=[l,d];this.sourceBuffers[g]=p,d.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,c)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const r=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${r?"transferring":"detaching"}`),r)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=n.readyState==="open";try{const u=n.sourceBuffers;for(let l=u.length;l--;)o&&u[l].abort(),n.removeSourceBuffer(u[l]);o&&n.endOfStream()}catch(u){this.warn(`onMediaDetaching: ${u.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),r||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(s.removeAttribute("src"),this.appendSource&&Bd(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(E.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const r=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),r)try{var s;(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[ca(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new US(this.tracks)}onBufferCodecs(e,t){var r;const s=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some(u=>!s[u]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(s)}" and "${n}" SourceBuffers`);return}n.forEach(u=>{var l,c;const d=t[u],{id:h,codec:f,levelCodec:g,container:p,metadata:m,supplemental:v}=d;let y=s[u];const S=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[u],_=S!=null&&S.buffer?S:y,T=(_==null?void 0:_.pendingCodec)||(_==null?void 0:_.codec),x=_==null?void 0:_.levelCodec;y||(y=s[u]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:p,levelCodec:g,metadata:m,id:h});const b=Cs(T,x),I=b==null?void 0:b.replace(Nd,"$1");let A=Cs(f,g);const D=(c=A)==null?void 0:c.replace(Nd,"$1");A&&b&&I!==D&&(u.slice(0,5)==="audio"&&(A=Xs(A,this.appendSource)),this.log(`switching codec ${T} to ${A}`),A!==(y.pendingCodec||y.codec)&&(y.pendingCodec=A),y.container=p,this.appendChangeType(u,p,A))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((r=t.audio)==null?void 0:r.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const r=this.tracks[t];return e[t]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},e},{})}appendChangeType(e,t,r){const s=`${t};codecs=${r}`,n={label:`change-type=${s}`,execute:()=>{const a=this.tracks[e];if(a){const o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${s}`),o.changeType(s),a.codec=r,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(n,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const r=e.start,s=r+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(r,V.MAIN))==null?void 0:t.gap)===!0)return;const a={label:"block-audio",execute:()=>{var o;const u=this.tracks.video;(this.lastVideoAppendEnd>s||u!=null&&u.buffer&&Y.isBuffered(u.buffer,s)||((o=this.fragmentTracker.getAppendedFrag(s,V.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:r}=this,{data:s,type:n,parent:a,frag:o,part:u,chunkMeta:l,offset:c}=t,d=l.buffering[n],{sn:h,cc:f}=o,g=self.performance.now();d.start=g;const p=o.stats.buffering,m=u?u.stats.buffering:null;p.start===0&&(p.start=g),m&&m.start===0&&(m.start=g);const v=r.audio;let y=!1;n==="audio"&&(v==null?void 0:v.container)==="audio/mpeg"&&(y=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const S=r.video,_=S==null?void 0:S.buffer;if(_&&h!=="initSegment"){const b=u||o,I=this.blockedAudioAppend;if(n==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(S.ending||S.ended)){const D=b.start+b.duration*.05,L=_.buffered,P=this.currentOp("video");!L.length&&!P?this.blockAudio(b):!P&&!Y.isBuffered(_,D)&&this.lastVideoAppendEnd<D&&this.blockAudio(b)}else if(n==="video"){const A=b.end;if(I){const D=I.frag.start;(A>D||A<this.lastVideoAppendEnd||Y.isBuffered(_,D))&&this.unblockAudio()}this.lastVideoAppendEnd=A}}const T=(u||o).start,x={label:`append-${n}`,execute:()=>{var b;d.executeStart=self.performance.now();const I=(b=this.tracks[n])==null?void 0:b.buffer;I&&(y?this.updateTimestampOffset(I,T,.1,n,h,f):c!==void 0&&$(c)&&this.updateTimestampOffset(I,c,1e-6,n,h,f)),this.appendExecutor(s,n)},onStart:()=>{},onComplete:()=>{const b=self.performance.now();d.executeEnd=d.end=b,p.first===0&&(p.first=b),m&&m.first===0&&(m.first=b);const I={};this.sourceBuffers.forEach(([A,D])=>{A&&(I[A]=Y.getBuffered(D))}),this.appendErrors[n]=0,n==="audio"||n==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(E.BUFFER_APPENDED,{type:n,frag:o,part:u,chunkMeta:l,parent:o.type,timeRanges:I})},onError:b=>{var I;const A={type:q.MEDIA_ERROR,parent:o.type,details:C.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:u,chunkMeta:l,error:b,err:b,fatal:!1},D=(I=this.media)==null?void 0:I.error;if(b.code===DOMException.QUOTA_EXCEEDED_ERR||b.name=="QuotaExceededError"||"quota"in b)A.details=C.BUFFER_FULL_ERROR;else if(b.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!D)A.errorAction=Wr(!0);else if(b.name===Ug&&this.sourceBufferCount===0)A.errorAction=Wr(!0);else{const L=++this.appendErrors[n];this.warn(`Failed ${L}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${D||"no media error"})`),(L>=this.hls.config.appendErrorMaxRetry||D)&&(A.fatal=!0)}this.hls.trigger(E.ERROR,A)}};this.log(`queuing "${n}" append sn: ${h}${u?" p: "+u.index:""} of ${o.type===V.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(x,n,this.isPending(this.tracks[n]))}getFlushOp(e,t,r){return this.log(`queuing "${e}" remove ${t}-${r}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,r)},onStart:()=>{},onComplete:()=>{this.hls.trigger(E.BUFFER_FLUSHED,{type:e})},onError:s=>{this.warn(`Failed to remove ${t}-${r} from "${e}" SourceBuffer`,s)}}}onBufferFlushing(e,t){const{type:r,startOffset:s,endOffset:n}=t;r?this.append(this.getFlushOp(r,s,n),r):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,s,n),a)})}onFragParsed(e,t){const{frag:r,part:s}=t,n=[],a=s?s.elementaryStreams:r.elementaryStreams;a[oe.AUDIOVIDEO]?n.push("audiovideo"):(a[oe.AUDIO]&&n.push("audio"),a[oe.VIDEO]&&n.push("video"));const o=()=>{const u=self.performance.now();r.stats.buffering.end=u,s&&(s.stats.buffering.end=u);const l=s?s.stats:r.stats;this.hls.trigger(E.FRAG_BUFFERED,{frag:r,part:s,stats:l,id:r.type})};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers(o,n).catch(u=>{this.warn(`Fragment buffered callback ${u}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var r;this.sourceBuffers.forEach(([a])=>{if(a){const o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});const s=((r=this.overrides)==null?void 0:r.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(E.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(E.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===C.BUFFER_APPEND_ERROR&&t.frag){var r;const s=(r=t.errorAction)==null?void 0:r.nextAutoLevel;$(s)&&s!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:r}=this;if(!r||t===null||!this.sourceBufferCount)return;const s=e.config,n=r.currentTime,a=t.levelTargetDuration,o=t.live&&s.liveBackBufferLength!==null?s.liveBackBufferLength:s.backBufferLength;if($(o)&&o>=0){const l=Math.max(o,a),c=Math.floor(n/a)*a-l;this.flushBackBuffer(n,a,c)}const u=s.frontBufferFlushThreshold;if($(u)&&u>0){const l=Math.max(s.maxBufferLength,u),c=Math.max(l,a),d=Math.floor(n/a)*a+c;this.flushFrontBuffer(n,a,d)}}flushBackBuffer(e,t,r){this.sourceBuffers.forEach(([s,n])=>{if(n){const o=Y.getBuffered(n);if(o.length>0&&r>o.start(0)){var a;this.hls.trigger(E.BACK_BUFFER_REACHED,{bufferEnd:r});const u=this.tracks[s];if((a=this.details)!=null&&a.live)this.hls.trigger(E.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(u!=null&&u.ended){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:s})}}})}flushFrontBuffer(e,t,r){this.sourceBuffers.forEach(([s,n])=>{if(n){const a=Y.getBuffered(n),o=a.length;if(o<2)return;const u=a.start(o-1),l=a.end(o-1);if(r>u||e>=u&&e<=l)return;this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:s})}})}getDurationAndRange(){var e;const{details:t,mediaSource:r}=this;if(!t||!this.media||(r==null?void 0:r.readyState)!=="open")return null;const s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),c=Math.max(l,s);return{duration:1/0,start:l,end:c}}return{duration:1/0}}const n=(e=this.overrides)==null?void 0:e.duration;if(n)return $(n)?{duration:n}:null;const a=this.media.duration,o=$(r.duration)?r.duration:0;return s>o&&s>a||!$(a)?{duration:s}:null}updateMediaSource({duration:e,start:t,end:r}){const s=this.mediaSource;!this.media||!s||s.readyState!=="open"||(s.duration!==e&&($(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),t!==void 0&&r!==void 0&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${t}-${r}.`),s.setLiveSeekableRange(t,r)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:r}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ue(r)}`),this.tracksReady){var s;const n=(s=this.transferData)==null?void 0:s.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,r])=>{if(t){const s=this.tracks[t];e[t]={buffer:r,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(E.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(E.ERROR,{type:q.MEDIA_ERROR,details:C.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:r}=this;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in e){const a=n,o=e[a];if(this.isPending(o)){const u=this.getTrackCodec(o,a),l=`${o.container};codecs=${u}`;o.codec=u,this.log(`creating sourceBuffer(${l})${this.currentOp(a)?" Queued":""} ${ue(o)}`);try{const c=r.addSourceBuffer(l),d=ca(a),h=[a,c];t[d]=h,o.buffer=c}catch(c){var s;this.error(`error while trying to add sourceBuffer: ${c.message}`),this.shiftAndExecuteNext(a),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[a],this.hls.trigger(E.ERROR,{type:q.MEDIA_ERROR,details:C.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:c,sourceBufferName:a,mimeType:l,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){const r=e.supplemental;let s=e.codec;r&&(t==="video"||t==="audiovideo")&&Ni(r,"video")&&(s=wv(s,r));const n=Cs(s,e.levelCodec);return n?t.slice(0,5)==="audio"?Xs(n,this.appendSource):n:""}trackSourceBuffer(e,t){const r=t.buffer;if(!r)return;const s=this.getTrackCodec(t,e);this.tracks[e]={buffer:r,codec:s,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,a)=>{const o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(E.BUFFER_FLUSHED,{type:n})})}get mediaSrc(){var e,t;const r=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return r==null?void 0:r.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const r=this.currentOp(e);r&&(r.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var r;const s=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(r=this.mediaSource)==null?void 0:r.readyState}`);this.error(`${s}`,t),this.hls.trigger(E.ERROR,{type:q.MEDIA_ERROR,details:C.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});const n=this.currentOp(e);n&&n.onError(s)}updateTimestampOffset(e,t,r,s,n,a){const o=t-e.timestampOffset;Math.abs(o)>=r&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,r){const{media:s,mediaSource:n}=this,a=this.tracks[e],o=a==null?void 0:a.buffer;if(!s||!n||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const u=$(s.duration)?s.duration:1/0,l=$(n.duration)?n.duration:1/0,c=Math.max(0,t),d=Math.min(r,u,l);d>c&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${c},${d}] from the ${e} SourceBuffer`),o.remove(c,d)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const r=this.tracks[t],s=r==null?void 0:r.buffer;if(!s)throw new $S(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);r.ending=!1,r.ended=!1,s.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:r}=this,s=t.map(a=>this.appendBlocker(a));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(a=>{r===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var r;const s=(r=this.tracks[t])==null?void 0:r.buffer;!s||s.updating||this.shiftAndExecuteNext(t)})}append(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,r){const s=this.tracks[e];if(!s)return;const n=s.buffer;if(!n)return;const a=r.bind(this,e);s.listeners.push({event:t,listener:a}),n.addEventListener(t,a)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const r=t.buffer;r&&(t.listeners.forEach(s=>{r.removeEventListener(s.event,s.listener)}),t.listeners.length=0)}}function Bd(i){const e=i.querySelectorAll("source");[].slice.call(e).forEach(t=>{i.removeChild(t)})}function GS(i,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,i.appendChild(t)}function ca(i){return i==="audio"?1:0}class No{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(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.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 r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&$(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${r}: ${e[r].height}p@${e[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const r=t.filter((s,n)=>this.isLevelAllowed(s)&&n<=e);return this.clientRect=null,No.getMaxLevelByMediaSize(r,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 r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,!t.width&&!t.height&&(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(r=>e.bitrate===r.bitrate&&e.width===r.width&&e.height===r.height)}static getMaxLevelByMediaSize(e,t,r){if(!(e!=null&&e.length))return-1;const s=(o,u)=>u?o.width!==u.width||o.height!==u.height:!0;let n=e.length-1;const a=Math.max(t,r);for(let o=0;o<e.length;o+=1){const u=e[o];if((u.width>=a||u.height>=a)&&s(u,e[o+1])){n=o;break}}return n}}const VS={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Ue=VS,KS={HLS:"h"},qS=KS;class ft{constructor(e,t){Array.isArray(e)&&(e=e.map(r=>r instanceof ft?r:new ft(r))),this.value=e,this.params=t}}const HS="Dict";function WS(i){return Array.isArray(i)?JSON.stringify(i):i instanceof Map?"Map{}":i instanceof Set?"Set{}":typeof i=="object"?JSON.stringify(i):String(i)}function zS(i,e,t,r){return new Error(`failed to ${i} "${WS(e)}" as ${t}`,{cause:r})}function gt(i,e,t){return zS("serialize",i,e,t)}class $g{constructor(e){this.description=e}}const Ud="Bare Item",YS="Boolean";function XS(i){if(typeof i!="boolean")throw gt(i,YS);return i?"?1":"?0"}function QS(i){return btoa(String.fromCharCode(...i))}const ZS="Byte Sequence";function JS(i){if(ArrayBuffer.isView(i)===!1)throw gt(i,ZS);return`:${QS(i)}:`}const e_="Integer";function t_(i){return i<-999999999999999||999999999999999<i}function jg(i){if(t_(i))throw gt(i,e_);return i.toString()}function r_(i){return`@${jg(i.getTime()/1e3)}`}function Gg(i,e){if(i<0)return-Gg(-i,e);const t=Math.pow(10,e);if(Math.abs(i*t%1-.5)<Number.EPSILON){const s=Math.floor(i*t);return(s%2===0?s:s+1)/t}else return Math.round(i*t)/t}const i_="Decimal";function s_(i){const e=Gg(i,3);if(Math.floor(Math.abs(e)).toString().length>12)throw gt(i,i_);const t=e.toString();return t.includes(".")?t:`${t}.0`}const n_="String",a_=/[\x00-\x1f\x7f]+/;function o_(i){if(a_.test(i))throw gt(i,n_);return`"${i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function l_(i){return i.description||i.toString().slice(7,-1)}const u_="Token";function $d(i){const e=l_(i);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw gt(e,u_);return e}function Va(i){switch(typeof i){case"number":if(!$(i))throw gt(i,Ud);return Number.isInteger(i)?jg(i):s_(i);case"string":return o_(i);case"symbol":return $d(i);case"boolean":return XS(i);case"object":if(i instanceof Date)return r_(i);if(i instanceof Uint8Array)return JS(i);if(i instanceof $g)return $d(i);default:throw gt(i,Ud)}}const c_="Key";function Ka(i){if(/^[a-z*][a-z0-9\-_.*]*$/.test(i)===!1)throw gt(i,c_);return i}function Bo(i){return i==null?"":Object.entries(i).map(([e,t])=>t===!0?`;${Ka(e)}`:`;${Ka(e)}=${Va(t)}`).join("")}function Vg(i){return i instanceof ft?`${Va(i.value)}${Bo(i.params)}`:Va(i)}function d_(i){return`(${i.value.map(Vg).join(" ")})${Bo(i.params)}`}function h_(i,e={whitespace:!0}){if(typeof i!="object"||i==null)throw gt(i,HS);const t=i instanceof Map?i.entries():Object.entries(i),r=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([s,n])=>{n instanceof ft||(n=new ft(n));let a=Ka(s);return n.value===!0?a+=Bo(n.params):(a+="=",Array.isArray(n.value)?a+=d_(n):a+=Vg(n)),a}).join(`,${r}`)}function Kg(i,e){return h_(i,e)}const lt="CMCD-Object",ge="CMCD-Request",ir="CMCD-Session",Rt="CMCD-Status",f_={br:lt,ab:lt,d:lt,ot:lt,tb:lt,tpb:lt,lb:lt,tab:lt,lab:lt,url:lt,pb:ge,bl:ge,tbl:ge,dl:ge,ltc:ge,mtp:ge,nor:ge,nrr:ge,rc:ge,sn:ge,sta:ge,su:ge,ttfb:ge,ttfbb:ge,ttlb:ge,cmsdd:ge,cmsds:ge,smrt:ge,df:ge,cs:ge,ts:ge,cid:ir,pr:ir,sf:ir,sid:ir,st:ir,v:ir,msd:ir,bs:Rt,bsd:Rt,cdn:Rt,rtp:Rt,bg:Rt,pt:Rt,ec:Rt,e:Rt},g_={REQUEST:ge};function m_(i){return Object.keys(i).reduce((e,t)=>{var r;return(r=i[t])===null||r===void 0||r.forEach(s=>e[s]=t),e},{})}function p_(i,e){const t={};if(!i)return t;const r=Object.keys(i),s=e?m_(e):{};return r.reduce((n,a)=>{var o;const u=f_[a]||s[a]||g_.REQUEST,l=(o=n[u])!==null&&o!==void 0?o:n[u]={};return l[a]=i[a],n},t)}function y_(i){return["ot","sf","st","e","sta"].includes(i)}function v_(i){return typeof i=="number"?$(i):i!=null&&i!==""&&i!==!1}const qg="event";function E_(i,e){const t=new URL(i),r=new URL(e);if(t.origin!==r.origin)return i;const s=t.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);for(;s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")+t.search+t.hash}const Ms=i=>Math.round(i),qa=(i,e)=>Array.isArray(i)?i.map(t=>qa(t,e)):i instanceof ft&&typeof i.value=="string"?new ft(qa(i.value,e),i.params):(e.baseUrl&&(i=E_(i,e.baseUrl)),e.version===1?encodeURIComponent(i):i),Es=i=>Ms(i/100)*100,S_=(i,e)=>{let t=i;return e.version>=2&&(i instanceof ft&&typeof i.value=="string"?t=new ft([i]):typeof i=="string"&&(t=[i])),qa(t,e)},__={br:Ms,d:Ms,bl:Es,dl:Es,mtp:Es,nor:S_,rtp:Es,tb:Ms},Hg="request",Wg="response",Uo=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],T_=["e"],b_=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function yn(i){return b_.test(i)}function x_(i){return Uo.includes(i)||T_.includes(i)||yn(i)}const zg=["d","dl","nor","ot","rtp","su"];function A_(i){return Uo.includes(i)||zg.includes(i)||yn(i)}const I_=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function D_(i){return Uo.includes(i)||zg.includes(i)||I_.includes(i)||yn(i)}const L_=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function R_(i){return L_.includes(i)||yn(i)}const C_={[Wg]:D_,[qg]:x_,[Hg]:A_};function Yg(i,e={}){const t={};if(i==null||typeof i!="object")return t;const r=e.version||i.v||1,s=e.reportingMode||Hg,n=r===1?R_:C_[s];let a=Object.keys(i).filter(n);const o=e.filter;typeof o=="function"&&(a=a.filter(o));const u=s===Wg||s===qg;u&&!a.includes("ts")&&a.push("ts"),r>1&&!a.includes("v")&&a.push("v");const l=ae({},__,e.formatters),c={version:r,reportingMode:s,baseUrl:e.baseUrl};return a.sort().forEach(d=>{let h=i[d];const f=l[d];if(typeof f=="function"&&(h=f(h,c)),d==="v"){if(r===1)return;h=r}d=="pr"&&h===1||(u&&d==="ts"&&!$(h)&&(h=Date.now()),v_(h)&&(y_(d)&&typeof h=="string"&&(h=new $g(h)),t[d]=h))}),t}function w_(i,e={}){const t={};if(!i)return t;const r=Yg(i,e),s=p_(r,e==null?void 0:e.customHeaderMap);return Object.entries(s).reduce((n,[a,o])=>{const u=Kg(o,{whitespace:!1});return u&&(n[a]=u),n},t)}function P_(i,e,t){return ae(i,w_(e,t))}const k_="CMCD";function O_(i,e={}){return i?Kg(Yg(i,e),{whitespace:!1}):""}function M_(i,e={}){if(!i)return"";const t=O_(i,e);return encodeURIComponent(t)}function F_(i,e={}){if(!i)return"";const t=M_(i,e);return`${k_}=${t}`}const jd=/CMCD=[^&#]+/;function N_(i,e,t){const r=F_(e,t);if(!r)return i;if(jd.test(i))return i.replace(jd,r);const s=i.includes("?")?"&":"?";return`${i}${s}${r}`}class B_{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=s=>{try{this.apply(s,{ot:Ue.MANIFEST,su:!this.initialized})}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=s=>{try{const{frag:n,part:a}=s,o=this.hls.levels[n.level],u=this.getObjectType(n),l={d:(a||n).duration*1e3,ot:u};(u===Ue.VIDEO||u===Ue.AUDIO||u==Ue.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(u)/1e3,l.bl=this.getBufferLength(u));const c=a?this.getNextPart(a):this.getNextFrag(n);c!=null&&c.url&&c.url!==n.url&&(l.nor=c.url),this.apply(s,l)}catch(n){this.hls.logger.warn("Could not generate segment CMCD data.",n)}},this.hls=e;const t=this.config=e.config,{cmcd:r}=t;r!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||e.sessionId,this.cid=r.contentId,this.useHeaders=r.useHeaders===!0,this.includeKeys=r.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHED,this.onMediaDetached,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHED,this.onMediaDetached,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var r,s;this.audioBuffer=(r=t.tracks.audio)==null?void 0:r.buffer,this.videoBuffer=(s=t.tracks.video)==null?void 0:s.buffer}createData(){var e;return{v:1,sf:qS.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ae(t,this.createData());const r=t.ot===Ue.INIT||t.ot===Ue.VIDEO||t.ot===Ue.MUXED;this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:s}=this;s&&(t=Object.keys(t).reduce((a,o)=>(s.includes(o)&&(a[o]=t[o]),a),{}));const n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),P_(e.headers,t,n)):e.url=N_(e.url,t,n)}getNextFrag(e){var t;const r=(t=this.hls.levels[e.level])==null?void 0:t.details;if(r){const s=e.sn-r.startSN;return r.fragments[s+1]}}getNextPart(e){var t;const{index:r,fragment:s}=e,n=(t=this.hls.levels[s.level])==null||(t=t.details)==null?void 0:t.partList;if(n){const{sn:a}=s;for(let o=n.length-1;o>=0;o--){const u=n[o];if(u.index===r&&u.fragment.sn===a)return n[o+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Ue.TIMED_TEXT;if(e.sn==="initSegment")return Ue.INIT;if(t==="audio")return Ue.AUDIO;if(t==="main")return this.hls.audioTracks.length?Ue.VIDEO:Ue.MUXED}getTopBandwidth(e){let t=0,r;const s=this.hls;if(e===Ue.AUDIO)r=s.audioTracks;else{const n=s.maxAutoLevel,a=n>-1?n+1:s.levels.length;r=s.levels.slice(0,a)}return r.forEach(n=>{n.bitrate>t&&(t=n.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,r=e===Ue.AUDIO?this.audioBuffer:this.videoBuffer;return!r||!t?NaN:Y.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,r=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new r(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,r=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new r(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 U_=3e5;class $_ extends et{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(r=>r!==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:r}=t;r!==null&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:r}=t;if((r==null?void 0:r.action)===Ae.SendAlternateToPenaltyBox&&r.flags===qe.MoveAllAlternatesMatchingHost){const s=this.levels;let n=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:u,type:l}=t.context;o&&s?a=this.getPathwayForGroupId(o,l,a):u&&(a=u)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&s&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),r.resolved=this.pathwayId!==a),t.details===C.BUFFER_APPEND_ERROR&&!t.fatal?r.resolved=!0:r.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${s&&s.length} priorities: ${ue(n)} penalized: ${ue(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const r=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const r=this.penalizedPathways,s=performance.now();Object.keys(r).forEach(n=>{s-r[n]>U_&&delete r[n]});for(let n=0;n<e.length;n++){const a=e[n];if(a in r)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,u=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,mg(t),this.hls.trigger(E.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[o];u&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==u.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==u.bitrate&&this.log(`Unstable Pathways change from bitrate ${u.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,r){const s=this.getLevelsForPathway(r).concat(this.levels||[]);for(let n=0;n<s.length;n++)if(t===J.AUDIO_TRACK&&s[n].hasAudioGroup(e)||t===J.SUBTITLE_TRACK&&s[n].hasSubtitleGroup(e))return s[n].pathwayId;return r}clonePathways(e){const t=this.levels;if(!t)return;const r={},s={};e.forEach(n=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":u}=n;if(t.some(c=>c.pathwayId===a))return;const l=this.getLevelsForPathway(o).map(c=>{const d=new de(c.attrs);d["PATHWAY-ID"]=a;const h=d.AUDIO&&`${d.AUDIO}_clone_${a}`,f=d.SUBTITLES&&`${d.SUBTITLES}_clone_${a}`;h&&(r[d.AUDIO]=h,d.AUDIO=h),f&&(s[d.SUBTITLES]=f,d.SUBTITLES=f);const g=Xg(c.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",u),p=new Ui({attrs:d,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:g,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(let m=1;m<c.audioGroups.length;m++)p.addGroupId("audio",`${c.audioGroups[m]}_clone_${a}`);if(c.subtitleGroups)for(let m=1;m<c.subtitleGroups.length;m++)p.addGroupId("text",`${c.subtitleGroups[m]}_clone_${a}`);return p});t.push(...l),Gd(this.audioTracks,r,u,a),Gd(this.subtitleTracks,s,u,a)})}loadSteeringManifest(e){const t=this.hls.config,r=t.loader;this.loader&&this.loader.destroy(),this.loader=new r(t);let s;try{s=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){const c=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+c)}const n={responseType:"json",url:s.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},u={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(c,d,h,f)=>{this.log(`Loaded steering manifest: "${s}"`);const g=c.data;if((g==null?void 0:g.VERSION)!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":m,"PATHWAY-PRIORITY":v}=g;if(p)try{this.uri=new self.URL(p,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||h.url),m&&this.clonePathways(m);const y={steeringManifest:g,url:s.toString()};this.hls.trigger(E.STEERING_MANIFEST_LOADED,y),v&&this.updatePathwayPriority(v)},onError:(c,d,h,f)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${d.url})`),this.stopLoad(),c.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let g=this.timeToLoad*1e3;if(c.code===429){const p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){const m=p.getResponseHeader("Retry-After");m&&(g=parseFloat(m)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,g)},onTimeout:(c,d,h)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,u,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var r;const s=(r=this.hls)==null?void 0:r.media;if(s&&!s.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Gd(i,e,t,r){i&&Object.keys(e).forEach(s=>{const n=i.filter(a=>a.groupId===s).map(a=>{const o=ae({},a);return o.details=void 0,o.attrs=new de(o.attrs),o.url=o.attrs.URI=Xg(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[s],o.attrs["PATHWAY-ID"]=r,o});i.push(...n)})}function Xg(i,e,t,r){const{HOST:s,PARAMS:n,[t]:a}=r;let o;e&&(o=a==null?void 0:a[e],o&&(i=o));const u=new self.URL(i);return s&&!o&&(u.host=s),n&&Object.keys(n).sort().forEach(l=>{l&&u.searchParams.set(l,n[l])}),u.href}class Yr extends et{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=Yr.CDMCleanupPromise?[Yr.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:r,initData:s}=t,n=`"${t.type}" event: init data type: "${r}"`;if(this.debug(n),s!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Ri(this.config));const o=a.map(ra).filter(u=>!!u);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=Ps(a);if(r!=="sinf"||o!==fe.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${r}" for selected key-system ${o}`);return}let u;try{const f=Se(new Uint8Array(s)),g=Do(JSON.parse(f).sinf),p=Kf(g);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");u=new Uint8Array(p.subarray(8,24))}catch(f){this.warn(`${n} Failed to parse sinf: ${f}`);return}const l=Ie(u),{keyIdToKeySessionPromise:c,mediaKeySessions:d}=this;let h=c[l];for(let f=0;f<d.length;f++){const g=d[f],p=g.decryptdata;if(!p.keyId)continue;const m=Ie(p.keyId);if(tn(u,p.keyId)||p.uri.replace(/-/g,"").indexOf(l)!==-1){if(h=c[m],!h)continue;if(p.pssh)break;delete c[m],p.pssh=new Uint8Array(s),p.keyId=u,h=c[l]=h.then(()=>this.generateRequestWithPreferredKeySession(g,r,s,"encrypted-event-key-match")),h.catch(v=>this.handleError(v));break}}h||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${d.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(E.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(E.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:r}=this.config,s=t==null?void 0:t[e];if(s)return s.licenseUrl;if(e===fe.WIDEVINE&&r)return r}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,r=t==null?void 0:t[e];if(r)return r.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,r=(a,o,u)=>!!a&&u.indexOf(a)===o,s=t.map(a=>a.audioCodec).filter(r),n=t.map(a=>a.videoCodec).filter(r);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{const u=l=>{const c=l.shift();this.getMediaKeysPromise(c,s,n).then(d=>a({keySystem:c,mediaKeys:d})).catch(d=>{l.length?u(l):d instanceof Ke?o(d):o(new Ke({type:q.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.message))})};u(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:r}=this.config;if(typeof r!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${r}`;return og===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return r(e,t)}getMediaKeysPromise(e,t,r){var s;const n=SE(e,t,r,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],o=(s=a)==null?void 0:s.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ue(n)}`),o=this.requestMediaKeySystemAccess(e,n);const u=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const c=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const d=u.mediaKeys=l.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),u.hasMediaKeys=!0,c.then(f=>f?this.setMediaKeysServerCertificate(h,e,f):h)));return d.catch(h=>{this.error(`Failed to create media-keys for "${e}"}: ${h}`)}),d})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:r}){this.log(`Creating key-system session "${t}" keyId: ${Ie(e.keyId||[])} keyUri: ${e.uri}`);const s=r.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:r,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const r=this.createMediaKeySessionContext(e),s=Ss(t),n="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(r,n,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyId ${Ie(e.decryptdata.keyId||[])}
130130+ } (data length: ${t.byteLength})`),r.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>ra(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:r})=>this.attemptSetMediaKeys(t,r))}selectKeySystem(e){return new Promise((t,r)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:s})=>{const n=ra(s);n?t(n):r(new Error(`Unable to find format for key-system "${s}"`))}).catch(r)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=Ri(this.config),r=e.map(Ps).filter(s=>!!s&&t.indexOf(s)!==-1);return this.selectKeySystem(r)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let r=0;r<t.length;r++){const s=j_(e,t[r]);if(s)return s}}loadKey(e){const t=e.keyInfo.decryptdata,r=Ss(t),s=this.bannedKeyIds[r];if(s||this.getKeyStatus(t)==="internal-error"){const o=Vd(s||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}const n=`(keyId: ${r} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);const a=this.keyIdToKeySessionPromise[r];if(!a){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:u,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(u,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:u,mediaKeys:l,decryptdata:t}))))).then(u=>{const l="cenc",c=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(u,l,c,"playlist-key")});return o.catch(u=>this.handleError(u,e.frag)),this.keyIdToKeySessionPromise[r]=o,o}return a.catch(o=>{if(o instanceof Ke){const u=se({},o.data);this.getKeyStatus(t)==="internal-error"&&(u.decryptdata=t);const l=new Ke(u,o.message);this.handleError(l,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Ke){t&&(e.data.frag=t);const r=e.data.decryptdata;this.error(`${e.message}${r?` (${Ie(r.keyId||[])})`:""}`),this.hls.trigger(E.ERROR,e.data)}else this.error(e.message),this.hls.trigger(E.ERROR,{type:q.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=Ss(e),r=this.keyIdToKeySessionPromise[t];if(!r){const s=Ps(e.keyFormat),n=s?[s]:Ri(this.config);return this.attemptKeySystemAccess(n)}return r}getKeySystemSelectionPromise(e){if(e.length||(e=Ri(this.config)),e.length===0)throw new Ke({type:q.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ue({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const r=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const s=Promise.all(r).then(()=>this.media?this.media.setMediaKeys(t):new Promise((n,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(n).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),r.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>r.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,r,s){var n;const a=(n=this.config.drmSystems)==null||(n=n[e.keySystem])==null?void 0:n.generateRequest;if(a)try{const g=a.call(this.hls,t,r,e);if(!g)throw new Error("Invalid response from configured generateRequest filter");t=g.initDataType,r=g.initData?g.initData:null,e.decryptdata.pssh=r?new Uint8Array(r):null}catch(g){if(this.warn(g.message),this.hls&&this.hls.config.debug)throw g}if(r===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);const o=Ss(e.decryptdata),u=e.decryptdata.uri;this.log(`Generating key-session request for "${s}" keyId: ${o} URI: ${u} (init data type: ${t} length: ${r.byteLength})`);const l=new Ro,c=e._onmessage=g=>{const p=e.mediaKeysSession;if(!p){l.emit("error",new Error("invalid state"));return}const{messageType:m,message:v}=g;this.log(`"${m}" message event for session "${p.sessionId}" message size: ${v.byteLength}`),m==="license-request"||m==="license-renewal"?this.renewLicense(e,v).catch(y=>{l.eventNames().length?l.emit("error",y):this.handleError(y)}):m==="license-release"?e.keySystem===fe.FAIRPLAY&&this.updateKeySession(e,Na("acknowledged")).then(()=>this.removeSession(e)).catch(y=>this.handleError(y)):this.warn(`unhandled media key message type "${m}"`)},d=(g,p)=>{p.keyStatus=g;let m;g.startsWith("usable")?l.emit("resolved"):g==="internal-error"||g==="output-restricted"||g==="output-downscaled"?m=Vd(g,p.decryptdata):g==="expired"?m=new Error(`key expired (keyId: ${o})`):g==="released"?m=new Error("key released"):g==="status-pending"||this.warn(`unhandled key status change "${g}" (keyId: ${o})`),m&&(l.eventNames().length?l.emit("error",m):this.handleError(m))},h=e._onkeystatuseschange=g=>{if(!e.mediaKeysSession){l.emit("error",new Error("invalid state"));return}const m=this.getKeyStatuses(e);if(!Object.keys(m).some(_=>m[_]!=="status-pending"))return;if(m[o]==="expired"){this.log(`Expired key ${ue(m)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let y=m[o];if(y)d(y,e);else{var S;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(S=e.keyStatusTimeouts)[o]||(S[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const T=this.getKeyStatus(e.decryptdata);if(T&&T!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${T} from other session.`),d(T,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),y="internal-error",d(y,e)},1e3)),this.log(`No status for keyId ${o} (${ue(m)}).`)}};Ne(e.mediaKeysSession,"message",c),Ne(e.mediaKeysSession,"keystatuseschange",h);const f=new Promise((g,p)=>{l.on("error",p),l.on("resolved",g)});return e.mediaKeysSession.generateRequest(t,r).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${u}`)}).catch(g=>{throw new Ke({type:q.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_NO_SESSION,error:g,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw g}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((r,s)=>{if(typeof s=="string"&&typeof r=="object"){const o=s;s=r,r=o}const n="buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);if(e.keySystem===fe.PLAYREADY&&n.length===16){const o=Ie(n);t[o]=r,ng(n)}const a=Ie(n);r==="internal-error"&&(this.bannedKeyIds[a]=r),this.log(`key status change "${r}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=r}),t}fetchServerCertificate(e){const t=this.config,r=t.loader,s=new r(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const u={responseType:"arraybuffer",url:n},l=t.certLoadPolicy.default,c={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,g,p)=>{a(h.data)},onError:(h,f,g,p)=>{o(new Ke({type:q.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:se({url:u.url,data:void 0},h)},`"${e}" certificate request failed (${n}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,g)=>{o(new Ke({type:q.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:u.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(h,f,g)=>{o(new Error("aborted"))}};s.load(u,c,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,r){return new Promise((s,n)=>{e.setServerCertificate(r).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${r.byteLength}) on "${t}"`),s(e)}).catch(a=>{n(new Ke({type:q.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(r=>this.updateKeySession(e,new Uint8Array(r)).catch(s=>{throw new Ke({type:q.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:s,fatal:!1},s.message)}))}unpackPlayReadyKeyMessage(e,t){const r=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!r.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const s=new DOMParser().parseFromString(r,"application/xml"),n=s.querySelectorAll("HttpHeader");if(n.length>0){let c;for(let d=0,h=n.length;d<h;d++){var a,o;c=n[d];const f=(a=c.querySelector("name"))==null?void 0:a.textContent,g=(o=c.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}const u=s.querySelector("Challenge"),l=u==null?void 0:u.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Na(atob(l))}setupLicenseXHR(e,t,r,s){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!r.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,r,s)}).catch(a=>{if(!r.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,r,s)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||s})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,t){const r=this.config.keyLoadPolicy.default;return new Promise((s,n)=>{const a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let u=o.response;this.log(`License received ${u instanceof ArrayBuffer?u.byteLength:u}`);const l=this.config.licenseResponseCallback;if(l)try{u=l.call(this.hls,o,a,e)}catch(c){this.error(c)}s(u)}else{const u=r.errorRetry,l=u?u.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)n(new Ke({type:q.KEY_SYSTEM_ERROR,details:C.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const c=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${c} attempts left`),this.requestLicense(e,t).then(s,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:u,licenseChallenge:l})=>{e.keySystem==fe.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(u,l)),u.send(l)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const r=t.media;this.media=r,Ne(r,"encrypted",this.onMediaEncrypted),Ne(r,"waitingforkey",this.onWaitingForKey);const s=this.mediaResolved;s?s():this.mediaKeys=r.mediaKeys}onMediaDetached(){const e=this.media;e&&($e(e,"encrypted",this.onMediaEncrypted),$e(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const r=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,kt.clearKeyUriToKeyIdMap();const n=s.length;Yr.CDMCleanupPromise=Promise.all(s.map(a=>this.removeSession(a)).concat((r==null||(e=r.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(E.ERROR,{type:q.OTHER_ERROR,details:C.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(E.ERROR,{type:q.OTHER_ERROR,details:C.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const r=t.reduce((s,n)=>(s.indexOf(n.keyFormat)===-1&&s.push(n.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:r,decryptdata:s}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Ie((s==null?void 0:s.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),r&&r.readyState!==XMLHttpRequest.DONE&&r.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);const{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(l=>self.clearTimeout(a[l]));const{drmSystemOptions:o}=this.config;return(TE(o)?new Promise((l,c)=>{self.setTimeout(()=>c(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l).catch(c)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(E.ERROR,{type:q.OTHER_ERROR,details:C.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>t.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(E.ERROR,{type:q.OTHER_ERROR,details:C.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}}Yr.CDMCleanupPromise=void 0;function Ss(i){if(!i)throw new Error("Could not read keyId of undefined decryptdata");if(i.keyId===null)throw new Error("keyId is null");return Ie(i.keyId)}function j_(i,e){if(i.keyId&&e.mediaKeysSession.keyStatuses.has(i.keyId))return e.mediaKeysSession.keyStatuses.get(i.keyId);if(i.matches(e.decryptdata))return e.keyStatus}class Ke extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function Vd(i,e){const t=i==="output-restricted",r=t?C.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:C.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ke({type:q.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${i}"`)}class G_{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(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const r=this.hls.config;if(r.capLevelOnFPSDrop){const s=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,r){const s=performance.now();if(t){if(this.lastTime){const n=s-this.lastTime,a=r-this.lastDroppedFrames,o=t-this.lastDecodedFrames,u=1e3*a/n,l=this.hls;if(l.trigger(E.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:r}),u>0&&a>l.config.fpsDroppedMonitoringThreshold*o){let c=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=c)&&(c=c-1,l.trigger(E.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:l.currentLevel}),l.autoLevelCapping=c,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function Qg(i,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=i,e.dispatchEvent(t)}function Zg(i,e){const t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues&&!i.cues.getCueById(e.id))try{if(i.addCue(e),!i.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(r){ne.debug(`[texttrack-utils]: ${r}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,i.addCue(s)}catch(s){ne.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}t==="disabled"&&(i.mode=t)}function Hr(i,e){const t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues)for(let r=i.cues.length;r--;)e&&i.cues[r].removeEventListener("enter",e),i.removeCue(i.cues[r]);t==="disabled"&&(i.mode=t)}function Ha(i,e,t,r){const s=i.mode;if(s==="disabled"&&(i.mode="hidden"),i.cues&&i.cues.length>0){const n=K_(i.cues,e,t);for(let a=0;a<n.length;a++)(!r||r(n[a]))&&i.removeCue(n[a])}s==="disabled"&&(i.mode=s)}function V_(i,e){if(e<=i[0].startTime)return 0;const t=i.length-1;if(e>i[t].endTime)return-1;let r=0,s=t,n;for(;r<=s;)if(n=Math.floor((s+r)/2),e<i[n].startTime)s=n-1;else if(e>i[n].startTime&&r<t)r=n+1;else return n;return i[r].startTime-e<e-i[s].startTime?r:s}function K_(i,e,t){const r=[],s=V_(i,e);if(s>-1)for(let n=s,a=i.length;n<a;n++){const o=i[n];if(o.startTime>=e&&o.endTime<=t)r.push(o);else if(o.startTime>t)return r}return r}function Fs(i){const e=[];for(let t=0;t<i.length;t++){const r=i[t];(r.kind==="subtitles"||r.kind==="captions")&&r.label&&e.push(i[t])}return e}class q_ extends Fo{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const r=Fs(this.media.textTracks);for(let n=0;n<r.length;n++)if(r[n].mode==="hidden")t=r[n];else if(r[n].mode==="showing"){t=r[n];break}const s=this.findTrackForTextTrack(t);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},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(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const r=this.media;if(!r)return;const s=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,s)return;Fs(r.textTracks).forEach(a=>{Hr(a)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:r,groupId:s,details:n}=t,a=this.tracksInGroup[r];if(!a||a.groupId!==s){this.warn(`Subtitle track with id:${r} and group:${s} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${r} "${a.name}" lang:${a.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`),r===this.trackId&&this.playlistLoaded(r,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 r=t.subtitleGroups||null,s=this.groupIds;let n=this.currentTrack;if(!r||(s==null?void 0:s.length)!==(r==null?void 0:r.length)||r!=null&&r.some(a=>(s==null?void 0:s.indexOf(a))===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(c=>!r||r.indexOf(c.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(c=>c.default)&&(this.selectDefaultTrack=!1),a.forEach((c,d)=>{c.id=d});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;const c=dt(o,a);if(c>-1)n=a[c];else{const d=dt(o,this.tracks);n=this.tracks[d]}}let u=this.findTrackId(n);u===-1&&n&&(u=this.findTrackId(null));const l={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${r==null?void 0:r.join(",")}" group-id`),this.hls.trigger(E.SUBTITLE_TRACKS_UPDATED,l),u!==-1&&this.trackId===-1&&this.setSubtitleTrack(u)}}findTrackId(e){const t=this.tracksInGroup,r=this.selectDefaultTrack;for(let s=0;s<t.length;s++){const n=t[s];if(!(r&&!n.default||!r&&!e)&&(!e||ar(n,e)))return s}if(e){for(let s=0;s<t.length;s++){const n=t[s];if(Vi(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const n=t[s];if(Vi(e.attrs,n.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){const s=t[r];if(Ga(s,e))return r}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===J.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const r=this.currentTrack;if(r&&ar(e,r))return r;const s=dt(e,this.tracksInGroup);if(s>-1){const n=this.tracksInGroup[s];return this.setSubtitleTrack(s),n}else{if(r)return null;{const n=dt(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=e.id,s=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading subtitle ${r} "${e.name}" lang:${e.lang} group:${s}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(E.SUBTITLE_TRACK_LOADING,{url:n,id:r,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Fs(e.textTracks),r=this.currentTrack;let s;if(r&&(s=t.filter(n=>Ga(r,n))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==s&&(n.mode="disabled")}),s){const n=this.subtitleDisplay?"showing":"hidden";s.mode!==n&&(s.mode=n)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!$(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,s=t[e]||null;if(this.trackId=e,this.currentTrack=s,this.toggleTrackModes(),!s){this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:e});return}const n=!!s.details&&!s.details.live;if(e===this.trackId&&s===r&&n)return;this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:a,groupId:o="",name:u,type:l,url:c}=s;this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:u,type:l,url:c});const d=this.switchParams(s.url,r==null?void 0:r.details,s.details);this.loadPlaylist(d)}}function H_(){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,s=>{const n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(s=="x"?n:n&3|8).toString(16)})}}}function Oi(i){let e=5381,t=i.length;for(;t;)e=e*33^i.charCodeAt(--t);return(e>>>0).toString()}const Xr=.025;let an=function(i){return i[i.Point=0]="Point",i[i.Range=1]="Range",i}({});function W_(i,e,t){return`${i.identifier}-${t+1}-${Oi(e)}`}class z_{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const r=this.playoutLimit;return e<=0||isNaN(r)?!1:r===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>r}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return da(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,r=da(t,e);return t-r<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=$(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return da(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Xr))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?an.Range:an.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return Y_(this)}}function da(i,e){return i-e.start<e.duration/2&&!(Math.abs(i-(e.start+e.duration))<Xr)?e.start:e.start+e.duration}function Jg(i,e,t){const r=new self.URL(i,t);return r.protocol!=="data:"&&r.searchParams.set("_HLS_primary_id",e),r}function ha(i,e){for(;(t=i.assetList[++e])!=null&&t.error;)var t;return e}function Y_(i){return`["${i.identifier}" ${i.cue.pre?"<pre>":i.cue.post?"<post>":""}${i.timelineStart.toFixed(2)}-${i.resumeTime.toFixed(2)}]`}function qr(i){const e=i.timelineStart,t=i.duration||0;return`["${i.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class X_{constructor(e,t,r,s){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(E.PLAYOUT_LIMIT_REACHED,{})};const n=this.hls=new e(t);this.interstitial=r,this.assetItem=s;const a=()=>{this.hasDetails=!0};n.once(E.LEVEL_LOADED,a),n.once(E.AUDIO_TRACK_LOADED,a),n.once(E.SUBTITLE_TRACK_LOADED,a),n.on(E.MEDIA_ATTACHING,(o,{media:u})=>{this.removeMediaListeners(),this.mediaAttached=u,this.interstitial.playoutLimit&&(u.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(E.BUFFER_APPENDED,()=>{const c=this.bufferedEnd;this.reachedPlayout(c)&&(this._bufferedEosTime=c,n.trigger(E.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Jg(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const r=Math.min(this._bufferedEosTime||1/0,this.duration),s=this.timelineOffset,n=Y.bufferInfo(e,s,0);return this.getAssetTime(n.end)>=r-.02}reachedPlayout(e){const r=this.interstitial.playoutLimit;return this.startOffset+e>=r}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=Y.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const r=t-this.startOffset;if(r>0&&r<e)return r}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const r=e-t;if(Math.abs(r)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,e-t),r)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=r=>delete r.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,r){var s;(s=this.hls)==null||s.on(e,t)}once(e,t,r){var s;(s=this.hls)==null||s.once(e,t)}off(e,t,r){var s;(s=this.hls)==null||s.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${qr(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Kd=.033;class Q_ extends et{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((r,s)=>e<=s.startOffset&&t>s.startOffset?(delete s.error,r+1):r,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let r=-1;e.nextEvent?r=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(r=this.findEventIndex(e.previousEvent.identifier)+1);const s=this.items;if(s)for(s[r]||(t===void 0&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&(n=s[r])!=null&&n.event;){var n;r--}return r}findItemIndexAtTime(e,t){const r=this.items;if(r)for(let s=0;s<r.length;s++){let n=r[s];if(t&&t!=="primary"&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return s}return-1}findJumpRestrictedIndex(e,t){const r=this.items;if(r)for(let s=e;s<=t&&r[s];s++){const n=r[s].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return s}return-1}findEventIndex(e){const t=this.items;if(t)for(let s=t.length;s--;){var r;if(((r=t[s].event)==null?void 0:r.identifier)===e)return s}return-1}findAssetIndex(e,t){const r=e.assetList,s=r.length;if(s>1)for(let n=0;n<s;n++){const a=r[n];if(!a.error){const o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||n===s-1))return n}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const r=t.assetList,s=r[r.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t){const r=e.main.details,{dateRanges:s}=r,n=this.events,a=this.parseDateRanges(s,{url:r.url},t),o=Object.keys(s),u=n?n.filter(l=>!o.includes(l.identifier)):[];a.length&&a.sort((l,c)=>{const d=l.cue.pre,h=l.cue.post,f=c.cue.pre,g=c.cue.post;if(d&&!f)return-1;if(f&&!d||h&&!g)return 1;if(g&&!h)return-1;if(!d&&!f&&!h&&!g){const p=l.startTime,m=c.startTime;if(p!==m)return p-m}return l.dateRange.tagOrder-c.dateRange.tagOrder}),this.events=a,u.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,u)}updateSchedule(e,t=[],r=!1){const s=this.events||[];if(s.length||t.length||this.length<2){const n=this.items,a=this.parseSchedule(s,e);(r||t.length||(n==null?void 0:n.length)!==a.length||a.some((u,l)=>Math.abs(u.playout.start-n[l].playout.start)>.005||Math.abs(u.playout.end-n[l].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,n))}}parseDateRanges(e,t,r){const s=[],n=Object.keys(e);for(let a=0;a<n.length;a++){const o=n[a],u=e[o];if(u.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(u):(l=new z_(u,t),this.eventMap[o]=l,r===!1&&(l.appendInPlace=r)),s.push(l)}}return s}parseSchedule(e,t){const r=[],s=t.main.details,n=s.live?1/0:s.edge;let a=0;if(e=e.filter(u=>!u.error&&!(u.cue.once&&u.hasPlayed)),e.length){this.resolveOffsets(e,t);let u=0,l=0;if(e.forEach((c,d)=>{const h=c.cue.pre,f=c.cue.post,g=e[d-1]||null,p=c.appendInPlace,m=f?n:c.startOffset,v=c.duration,y=c.timelineOccupancy===an.Range?v:0,S=c.resumptionOffset,_=(g==null?void 0:g.startTime)===m,T=m+c.cumulativeDuration;let x=p?T+v:m+S;if(h||!f&&m<=0){const I=l;l+=y,c.timelineStart=T;const A=a;a+=v,r.push({event:c,start:T,end:x,playout:{start:A,end:a},integrated:{start:I,end:l}})}else if(m<=n){if(!_){const D=m-u;if(D>Kd){const L=u,P=l;l+=D;const O=a;a+=D;const G={previousEvent:e[d-1]||null,nextEvent:c,start:L,end:L+D,playout:{start:O,end:a},integrated:{start:P,end:l}};r.push(G)}else D>0&&g&&(g.cumulativeDuration+=D,r[r.length-1].end=m)}f&&(x=T),c.timelineStart=T;const I=l;l+=y;const A=a;a+=v,r.push({event:c,start:T,end:x,playout:{start:A,end:a},integrated:{start:I,end:l}})}else return;const b=c.resumeTime;f||b>n?u=n:u=b}),u<n){var o;const c=u,d=l,h=n-u;l+=h;const f=a;a+=h,r.push({previousEvent:((o=r[r.length-1])==null?void 0:o.event)||null,nextEvent:null,start:u,end:c+h,playout:{start:f,end:a},integrated:{start:d,end:l}})}this.setDurations(n,a,l)}else r.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n);return r}setDurations(e,t,r){this.durations={primary:e,playout:t,integrated:r}}resolveOffsets(e,t){const r=t.main.details,s=r.live?1/0:r.edge;let n=0,a=-1;e.forEach((o,u)=>{const l=o.cue.pre,c=o.cue.post,d=l?0:c?s:o.startTime;this.updateAssetDurations(o),a===d?o.cumulativeDuration=n:(n=0,a=d),!c&&o.snapOptions.in&&(o.resumeAnchor=or(null,r.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&u+1<e.length&&e[u+1].startTime-e[u].resumeTime<Kd&&(e[u+1].appendInPlace=!1,e[u+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=$(o.resumeOffset)?o.resumeOffset:o.duration;n+=f})}primaryCanResumeInPlaceAt(e,t){const r=e.resumeTime,s=e.startTime+e.resumptionOffset;return Math.abs(r-s)>Xr?(this.log(`"${e.identifier}" resumption ${r} not aligned with estimated timeline end ${s}`),!1):!Object.keys(t).some(a=>{const o=t[a].details,u=o.edge;if(r>=u)return this.log(`"${e.identifier}" resumption ${r} past ${a} playlist end ${u}`),!1;const l=or(null,o.fragments,r);if(!l)return this.log(`"${e.identifier}" resumption ${r} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const c=a==="audio"?.175:0;return Math.abs(l.start-r)<Xr+c||Math.abs(l.end-r)<Xr+c?!1:(this.log(`"${e.identifier}" resumption ${r} not aligned with ${a} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let r=0,s=!1,n=!1;for(let a=0;a<e.assetList.length;a++){const o=e.assetList[a],u=t+r;o.startOffset=r,o.timelineStart=u,s||(s=o.duration===null),n||(n=!!o.error);const l=o.error?0:o.duration||0;r+=l}s&&!n?e.duration=Math.max(r,e.duration):e.duration=r}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function it(i){return`[${i.event?'"'+i.event.identifier+'"':"primary"}: ${i.start.toFixed(2)}-${i.end.toFixed(2)}]`}class Z_{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const r=e.assetListUrl;let s;try{s=Jg(r,this.hls.sessionId,e.baseUrl)}catch(h){const f=this.assignAssetListError(e,C.ASSET_LIST_LOAD_ERROR,h,r);this.hls.trigger(E.ERROR,f);return}t&&s.protocol!=="data:"&&s.searchParams.set("_HLS_start_offset",""+t);const n=this.hls.config,a=n.loader,o=new a(n),u={responseType:"json",url:s.href},l=n.interstitialAssetListLoadPolicy.default,c={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,g,p)=>{const m=h.data,v=m==null?void 0:m.ASSETS;if(!Array.isArray(v)){const y=this.assignAssetListError(e,C.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,p);this.hls.trigger(E.ERROR,y);return}e.assetListResponse=m,this.hls.trigger(E.ASSET_LIST_LOADED,{event:e,assetListResponse:m,networkDetails:p})},onError:(h,f,g,p)=>{const m=this.assignAssetListError(e,C.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${f.url})`),f.url,p,g);this.hls.trigger(E.ERROR,m)},onTimeout:(h,f,g)=>{const p=this.assignAssetListError(e,C.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,h,g);this.hls.trigger(E.ERROR,p)}};return o.load(u,c,d),this.hls.trigger(E.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,r,s,n,a){return e.error=r,{type:q.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:s,error:r,networkDetails:a,stats:n}}}function qd(i){var e;i==null||(e=i.play())==null||e.catch(()=>{})}function _s(i,e){return`[${i}] Advancing timeline position to ${e}`}class J_ extends et{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled||!this.schedule)return;const s=r-this.timelinePos;if(Math.abs(s)<1/7056e5)return;const a=s<=-.01;this.timelinePos=r,this.bufferedPos=r;const o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(r,r-s)&&this.updateSchedule(!0),this.checkBuffer(),a&&r<o.start||r>=o.end){var u;const f=this.findItemIndex(o);let g=this.schedule.findItemIndexAtTime(r);if(g===-1&&(g=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${r} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(u=this.media)!=null&&u.paused&&(this.shouldPlay=!1),!a&&g>f){const p=this.schedule.findJumpRestrictedIndex(f+1,g);if(p>f){this.setSchedulePosition(p);return}}this.setSchedulePosition(g);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(r,f))}return}const c=l.timelineStart,d=l.duration||0;if(a&&r<c||r>=c+d){var h;(h=o.event)!=null&&h.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(r)),this.setScheduleToAssetAtTime(r,l)}},this.onTimeupdate=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled)return;if(r>this.timelinePos)this.timelinePos=r,r>this.bufferedPos&&this.checkBuffer();else return;const s=this.playingItem;if(!s||this.playingLastItem)return;if(r>=s.end){this.timelinePos=s.end;const o=this.findItemIndex(s);this.setSchedulePosition(o+1)}const n=this.playingAsset;if(!n)return;const a=n.timelineStart+(n.duration||0);r>=a&&this.setScheduleToAssetAtTime(r,n)},this.onScheduleUpdate=(r,s)=>{const n=this.schedule;if(!n)return;const a=this.playingItem,o=n.events||[],u=n.items||[],l=n.durations,c=r.map(p=>p.identifier),d=!!(o.length||c.length);(d||s)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
131131+Schedule: ${u.map(p=>it(p))} pos: ${this.timelinePos}`),c.length&&this.log(`Removed events ${c}`);let h=null,f=null;a&&(h=this.updateItem(a,this.timelinePos),this.itemsMatch(a,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const g=this.bufferingItem;if(g&&(f=this.updateItem(g,this.bufferedPos),this.itemsMatch(g,f)?this.bufferingItem=f:g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.event,null))),r.forEach(p=>{p.assetList.forEach(m=>{this.clearAssetPlayer(m.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){const m=p.assetItem.timelineStart,v=p.timelineOffset-m;if(v)try{p.timelineOffset=m}catch(y){Math.abs(v)>Xr&&this.warn(`${y} ("${p.assetId}" ${p.timelineOffset}->${m})`)}}}),d||s){if(this.hls.trigger(E.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:u.slice(0),durations:l,removedIds:c}),this.isInterstitial(a)&&c.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(h,a),g&&f!==h&&this.trimInPlace(f,g),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Z_(e),this.schedule=new Q_(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(E.MEDIA_ENDED,this.onMediaEnded,this),e.on(E.ERROR,this.onError,this),e.on(E.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(E.MEDIA_ENDED,this.onMediaEnded,this),e.off(E.ERROR,this.onError,this),e.off(E.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){$e(e,"play",this.onPlay),$e(e,"pause",this.onPause),$e(e,"seeking",this.onSeeking),$e(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const r=this.media=t.media;Ne(r,"seeking",this.onSeeking),Ne(r,"timeupdate",this.onTimeupdate),Ne(r,"play",this.onPlay),Ne(r,"pause",this.onPause)}onMediaAttached(e,t){const r=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,r===null)this.checkStart();else if(!s){this.clearScheduleState();const n=this.findItemIndex(r);this.setSchedulePosition(n)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const r=!!t.transferMedia,s=this.media;if(this.media=null,!r&&(s&&this.removeMediaListeners(s),this.detachedData)){const n=this.getBufferingPlayer();n&&(this.log(`Removing schedule state for detachedData and ${n}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,r=d=>d&&e.getAssetPlayer(d.identifier),s=(d,h,f,g,p)=>{if(d){let m=d[h].start;const v=d.event;if(v){if(h==="playout"||v.timelineOccupancy!==an.Point){const y=r(f);(y==null?void 0:y.interstitial)===v&&(m+=y.assetItem.startOffset+y[p])}}else{const y=g==="bufferedPos"?a():e[g];m+=y-d.start}return m}return 0},n=(d,h)=>{var f;if(d!==0&&h!=="primary"&&(f=e.schedule)!=null&&f.length){var g;const p=e.schedule.findItemIndexAtTime(d),m=(g=e.schedule.items)==null?void 0:g[p];if(m){const v=m[h].start-m.start;return d+v}}return d},a=()=>{const d=e.bufferedPos;return d===Number.MAX_VALUE?o("primary"):Math.max(d,0)},o=d=>{var h,f;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[d])||0},u=(d,h)=>{var f,g;const p=e.effectivePlayingItem;if(p!=null&&(f=p.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${d} "${h}"`);const m=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(d,h),y=(g=e.schedule.items)==null?void 0:g[v],S=e.getBufferingPlayer(),_=S==null?void 0:S.interstitial,T=_==null?void 0:_.appendInPlace,x=m&&e.itemsMatch(m,y);if(m&&(T||x)){const b=r(e.playingAsset),I=(b==null?void 0:b.media)||e.primaryMedia;if(I){const A=h==="primary"?I.currentTime:s(m,h,e.playingAsset,"timelinePos","currentTime"),D=d-A,L=(T?A:I.currentTime)+D;if(L>=0&&(!b||T||L<=b.duration)){I.currentTime=L;return}}}if(y){let b=d;if(h!=="primary"){const A=y[h].start,D=d-A;b=y.start+D}const I=!e.isInterstitial(y);if((!e.isInterstitial(m)||m.event.appendInPlace)&&(I||y.event.appendInPlace)){const A=e.media||(T?S==null?void 0:S.media:null);A&&(A.currentTime=b)}else if(m){const A=e.findItemIndex(m);if(v>A){const L=e.schedule.findJumpRestrictedIndex(A+1,v);if(L>A){e.setSchedulePosition(L);return}}let D=0;if(I)e.timelinePos=b,e.checkBuffer();else{const L=y.event.assetList,P=d-(y[h]||y).start;for(let O=L.length;O--;){const G=L[O];if(G.duration&&P>=G.startOffset&&P<G.startOffset+G.duration){D=O;break}}}e.setSchedulePosition(v,D)}}},l=()=>{const d=e.effectivePlayingItem;if(e.isInterstitial(d))return d;const h=t();return e.isInterstitial(h)?h:null},c={get bufferedEnd(){const d=t(),h=e.bufferingItem;if(h&&h===d){var f;return s(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const d=l(),h=e.effectivePlayingItem;return h&&h===d?s(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(d){const h=l(),f=e.effectivePlayingItem;f&&f===h&&u(d+f.playout.start,"playout")},get duration(){const d=l();return d?d.playout.end-d.playout.start:0},get assetPlayers(){var d;const h=(d=l())==null?void 0:d.event.assetList;return h?h.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var d;const h=(d=l())==null?void 0:d.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var d;return((d=e.schedule)==null||(d=d.events)==null?void 0:d.slice(0))||[]},get schedule(){var d;return((d=e.schedule)==null||(d=d.items)==null?void 0:d.slice(0))||[]},get interstitialPlayer(){return l()?c:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const d=t();return e.findItemIndex(d)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const d=e.effectivePlayingItem;return e.findItemIndex(d)},primary:{get bufferedEnd(){return a()},get currentTime(){const d=e.timelinePos;return d>0?d:0},set currentTime(d){u(d,"primary")},get duration(){return o("primary")},get seekableStart(){var d;return((d=e.primaryDetails)==null?void 0:d.fragmentStart)||0}},integrated:{get bufferedEnd(){return s(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(d){u(d,"integrated")},get duration(){return o("integrated")},get seekableStart(){var d;return n(((d=e.primaryDetails)==null?void 0:d.fragmentStart)||0,"integrated")}},skip:()=>{const d=e.effectivePlayingItem,h=d==null?void 0:d.event;if(h&&!h.restrictions.skip){const f=e.findItemIndex(d);if(h.appendInPlace){const g=d.playout.start+d.event.duration;u(g+.001,"playout")}else e.advanceAfterAssetEnded(h,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,r=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!r?!1:this.findItemIndex(t)===r.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let s=this.media;!s&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(s=this.primaryMedia);const n=(t=s)==null?void 0:t.currentTime;if(!(n===void 0||!$(n)))return n}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,t)}transferMediaFromPlayer(e,t){const r=e.interstitial.appendInPlace,s=e.media;if(r&&s===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&s){this.detachedData={media:s};return}const n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ue(n)}`),this.detachedData=n}else t&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(e,t){var r,s;if(e.media===t)return;let n=null;const a=this.hls,o=e!==a,u=o&&e.interstitial.appendInPlace,l=(r=this.detachedData)==null?void 0:r.mediaSource;let c;if(a.media)u&&(n=a.transferMedia(),this.detachedData=n),c="Primary";else if(l){const g=this.getBufferingPlayer();g?(n=g.transferMedia(),c=`${g}`):c="detached MediaSource"}else c="detached media";if(!n){if(l)n=this.detachedData,this.log(`using detachedData: MediaSource ${ue(n)}`);else if(!this.detachedData||a.media===t){const g=this.playerQueue;g.length>1&&g.forEach(p=>{if(o&&p.interstitial.appendInPlace!==u){const m=p.interstitial;this.clearInterstitial(p.interstitial,null),m.appendInPlace=!1,m.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${m}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const d=n&&"mediaSource"in n&&((s=n.mediaSource)==null?void 0:s.readyState)!=="closed",h=d&&n?n:t;this.log(`${d?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${c} (media.currentTime: ${t.currentTime})`);const f=this.schedule;if(h===n&&f){const g=o&&e.assetId===f.assetIdAtEnd;h.overrides={duration:f.duration,endOfStream:!o||g,cueRemoval:!o}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e==null?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const r=this.timelinePos,s=this.effectivePlayingItem;if(r===-1){const n=this.hls.startPosition;if(this.log(_s("checkStart",n)),this.timelinePos=n,t.length&&t[0].cue.pre){const a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(n>=0||!this.primaryLive){const a=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(s&&!this.playingItem){const n=e.findItemIndex(s);this.setSchedulePosition(n)}}advanceAssetBuffering(e,t){const r=e.event,s=r.findAssetIndex(t),n=ha(r,s);if(!r.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var a;const o=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,r){const s=ha(e,r);if(e.isAssetPastPlayoutLimit(s)){if(this.schedule){const n=this.schedule.items;if(n){const a=t+1,o=n.length;if(a>=o){this.setSchedulePosition(-1);return}const u=e.resumeTime;this.timelinePos<u&&(this.log(_s("advanceAfterAssetEnded",u)),this.timelinePos=u,e.appendInPlace&&this.advanceInPlace(u),this.checkBuffer(this.bufferedPos<u)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){const n=e.assetList[s];n&&this.advanceInPlace(n.timelineStart)}this.setSchedulePosition(t,s)}}setScheduleToAssetAtTime(e,t){const r=this.schedule;if(!r)return;const s=t.parentIdentifier,n=r.getEvent(s);if(n){const a=r.findEventIndex(s),o=r.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1)}}setSchedulePosition(e,t){var r;const s=(r=this.schedule)==null?void 0:r.items;if(!s||this.playbackDisabled)return;const n=e>=0?s[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&it(n)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){const c=a.event,d=this.playingAsset,h=d==null?void 0:d.identifier,f=h?this.getAssetPlayer(h):null;if(f&&h&&(!this.eventItemsMatch(a,n)||t!==void 0&&h!==c.assetList[t].identifier)){var u;const g=c.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${g+1}/${c.assetList.length} ${qr(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(E.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:g,event:c,schedule:s.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(c,this.findItemIndex(this.playingItem),g);return}this.retreiveMediaSource(h,n),f.media&&!((u=this.detachedData)!=null&&u.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${c} ${it(a)}`),c.hasPlayed=!0,this.hls.trigger(E.INTERSTITIAL_ENDED,{event:c,schedule:s.slice(0),scheduleIndex:e}),c.cue.once)){var l;this.updateSchedule();const g=(l=this.schedule)==null?void 0:l.items;if(n&&g){const p=this.findItemIndex(n);this.advanceSchedule(p,g,t,a,o)}return}}this.advanceSchedule(e,s,t,a,o)}advanceSchedule(e,t,r,s,n){const a=this.schedule;if(!a)return;const o=t[e]||null,u=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(c=>{const d=c.interstitial,h=a.findEventIndex(d.identifier);(h<e||h>e+1)&&this.clearInterstitial(d,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const c=o.event;if(r===void 0){r=a.findAssetIndex(c,this.timelinePos);const g=ha(c,r-1);if(c.isAssetPastPlayoutLimit(g)||c.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(c,e,r);return}r=g}const d=this.waitingItem;this.assetsBuffered(o,u)||this.setBufferingItem(o);let h=this.preloadAssets(c,r);if(this.eventItemsMatch(o,d||s)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${it(o)} ${c.appendInPlace?"append in place":""}`),this.hls.trigger(E.INTERSTITIAL_STARTED,{event:c,schedule:t.slice(0),scheduleIndex:e})),!c.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${c}`);return}if(c.assetListLoader&&(c.assetListLoader.destroy(),c.assetListLoader=void 0),!u){this.log(`Waiting for attachMedia to start Interstitial ${c}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const f=c.assetList[r];if(!f){this.advanceAfterAssetEnded(c,e,r||0);return}if(h||(h=this.getAssetPlayer(f.identifier)),h===null||h.destroyed){const g=c.assetList.length;this.warn(`asset ${r+1}/${g} player destroyed ${c}`),h=this.createAssetPlayer(c,f,r),h.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&c.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(h,r,t,e,u),this.shouldPlay&&qd(h.media)}else o?(this.resumePrimary(o,e,s),this.shouldPlay&&qd(this.hls.media)):n&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,r){var s,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${it(e)}`),!((s=this.detachedData)!=null&&s.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(_s("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!r)return;const a=(n=this.schedule)==null?void 0:n.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${it(e)}`),this.hls.trigger(E.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const r=e.start;if(this.primaryLive){const s=this.primaryDetails;if(t===0)return this.hls.startPosition;if(s&&(r<s.fragmentStart||r>s.edge))return this.hls.liveSyncPosition||-1}return r}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:Y.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,r){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const s=this.primaryMedia;if(!s)return;const n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,s),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(_s("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}startLoadingPrimaryAt(e,t){var r;const s=this.hls;!s.loadingEnabled||!s.media||Math.abs((((r=s.mainForwardBufferInfo)==null?void 0:r.start)||s.media.currentTime)-e)>.5?s.startLoad(e,t):s.bufferingEnabled||s.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(E.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(E.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const r=this.hls.levels[t.level];if(!r.details)return;const s=se(se({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=s,this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const r=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=se(se({},this.altSelection),{},{audio:r});return}const n=se(se({},s),{},{audio:r});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){const r=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=se(se({},this.altSelection),{},{subtitles:r});return}const n=se(se({},s),{},{subtitles:r});this.mediaSelection=n}onAudioTrackSwitching(e,t){const r=ed(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setAudioOption(t)||s.setAudioOption(r)))}onSubtitleTrackSwitch(e,t){const r=ed(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setSubtitleOption(t)||t.id!==-1&&s.setSubtitleOption(r)))}onBufferCodecs(e,t){const r=t.tracks;r&&(this.requiredTracks=r)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){const s=this.timelinePos;this.bufferedPos=s,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let s=0;s<t.length;s++){const n=t[s];if(n.cue.post){var r;const a=this.schedule.findEventIndex(n.identifier),o=(r=this.schedule.items)==null?void 0:r[a];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const r=this.findItemIndex(t);this.setSchedulePosition(r+1)}else this.shouldPlay=!1}updateItem(e,t){var r;const s=(r=this.schedule)==null?void 0:r.items;if(e&&s){const n=this.findItemIndex(e,t);return s[n]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((n,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(n.identifier,null)});const r=e.end+.25,s=Y.bufferInfo(this.primaryMedia,r,0);(s.end>r||(s.nextStart||0)>r)&&(this.log(`trim buffered interstitial ${it(e)} (was ${it(t)})`),this.attachPrimary(r,null,!0),this.flushFrontBuffer(r))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var r;return!!t&&(e===t||e.event.identifier===((r=t.event)==null?void 0:r.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const r=this.mediaSelection;r&&((t=this.schedule)==null||t.updateSchedule(r,[],e))}checkBuffer(e){var t;const r=(t=this.schedule)==null?void 0:t.items;if(!r)return;const s=Y.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=s.len<1),this.updateBufferedPos(s.end,r,e)}updateBufferedPos(e,t,r){const s=this.schedule,n=this.bufferingItem;if(this.bufferedPos>e||!s)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}const a=this.playingItem,o=this.findItemIndex(a);let u=s.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const c=this.findItemIndex(n),d=Math.min(c+1,t.length-1),h=t[d];if((u===-1&&n&&e>=n.end||(l=h.event)!=null&&l.appendInPlace&&e+.01>=h.start)&&(u=d),this.isInterstitial(n)){const f=n.event;if(d-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,u>c&&u>o)this.bufferedToItem(h);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&h.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0)}}else r&&a&&!this.itemsMatch(a,n)&&(u===o?this.bufferedToItem(a):u===o+1&&this.bufferedToItem(t[u]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(s=>{const n=this.getAssetPlayer(s.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(e,t)&&r){const{items:s,events:n}=r;if(!s||!n)return t;const a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const u=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${it(e)}`+(t?` (${u.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const l=r.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((c,d)=>{const h=this.getAssetPlayer(c.identifier);h&&(d===l&&h.loadSource(),h.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(E.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const r=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(r!==null){this.bufferingAsset=null;const s=this.detachedData;s?s.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),r=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(r)}bufferedToEvent(e,t){const r=e.event,s=r.assetList.length===0&&!r.assetListLoader,n=r.cue.once;if(s||!n){const a=this.preloadAssets(r,t);if(a!=null&&a.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){const r=e.assetUrl,s=e.assetList.length,n=s===0&&!e.assetListLoader,a=e.cue.once;if(n){const u=e.timelineStart;if(e.appendInPlace){var o;const h=this.playingItem;!this.isInterstitial(h)&&(h==null||(o=h.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(u+.25)}let l,c=0;if(!this.playingItem&&this.primaryLive&&(c=this.hls.startPosition,c===-1&&(c=this.hls.liveSyncPosition||0)),c&&!(e.cue.pre||e.cue.post)){const h=c-u;h>0&&(l=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${r?1:s} ${e}${l?` live-start: ${c} start-offset: ${l}`:""}`),r)return this.createAsset(e,0,0,u,e.duration,r);const d=this.assetListLoader.loadAssetList(e,l);d&&(e.assetListLoader=d)}else if(!a&&s){for(let l=t;l<s;l++){const c=e.assetList[l],d=this.getAssetPlayerQueueIndex(c.identifier);(d===-1||this.playerQueue[d].destroyed)&&!c.error&&this.createAssetPlayer(e,c,l)}const u=e.assetList[t];if(u){const l=this.getAssetPlayer(u.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(s=>{this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:s})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let r=0;r<t.length;r++)if(e===t[r].assetId)return r;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let r=0;r<e.length;r++)if(e[r].media===t)return e[r]}return null}createAsset(e,t,r,s,n,a){const o={parentIdentifier:e.identifier,identifier:W_(e,a,t),duration:n,startOffset:r,timelineStart:s,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,r){const s=this.hls,n=s.userConfig;let a=n.videoPreference;const o=s.loadLevelObj||s.levels[s.currentLevel];(a||o)&&(a=ae({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));const u=s.audioTracks[s.audioTrack],l=s.subtitleTracks[s.subtitleTrack];let c=0;if(this.primaryLive||e.appendInPlace){const _=this.timelinePos-t.timelineStart;if(_>1){const T=t.duration;T&&_<T&&(c=_)}}const d=t.identifier,h=se(se({},n),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:u||n.audioPreference,subtitlePreference:l||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(h.timelineOffset=t.timelineStart));const f=h.cmcd;f!=null&&f.sessionId&&f.contentId&&(h.cmcd=ae({},f,{contentId:Oi(t.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${e} and asset ${d}`);const g=new X_(this.HlsPlayerClass,h,e,t);this.playerQueue.push(g),e.assetList[r]=t;let p=!0;const m=_=>{if(_.live){var T;const I=new Error(`Interstitials MUST be VOD assets ${e}`),A={fatal:!0,type:q.OTHER_ERROR,details:C.INTERSTITIAL_ASSET_ITEM_ERROR,error:I},D=((T=this.schedule)==null?void 0:T.findEventIndex(e.identifier))||-1;this.handleAssetItemError(A,e,D,r,I.message);return}const x=_.edge-_.fragmentStart,b=t.duration;(p||b===null||x>b)&&(p=!1,this.log(`Interstitial asset "${d}" duration change ${b} > ${x}`),t.duration=x,this.updateSchedule())};g.on(E.LEVEL_UPDATED,(_,{details:T})=>m(T)),g.on(E.LEVEL_PTS_UPDATED,(_,{details:T})=>m(T)),g.on(E.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const v=(_,T)=>{const x=this.getAssetPlayer(d);if(x&&T.tracks){x.off(E.BUFFER_CODECS,v),x.tracks=T.tracks;const b=this.primaryMedia;this.bufferingAsset===x.assetItem&&b&&!x.media&&this.bufferAssetPlayer(x,b)}};g.on(E.BUFFER_CODECS,v);const y=()=>{var _;const T=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${T}`),!T||!this.schedule)return;const x=this.schedule.findEventIndex(e.identifier),b=(_=this.schedule.items)==null?void 0:_[x];this.isInterstitial(b)&&this.advanceAssetBuffering(b,t)};g.on(E.BUFFERED_TO_END,y);const S=_=>()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;this.shouldPlay=!0;const x=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,x,_)};return g.once(E.MEDIA_ENDED,S(r)),g.once(E.PLAYOUT_LIMIT_REACHED,S(1/0)),g.on(E.ERROR,(_,T)=>{if(!this.schedule)return;const x=this.getAssetPlayer(d);if(T.details===C.BUFFER_STALLED_ERROR){if(x!=null&&x.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(T,e,this.schedule.findEventIndex(e.identifier),r,`Asset player error ${T.error} ${e}`)}),g.on(E.DESTROYING,()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;const T=new Error(`Asset player destroyed unexpectedly ${d}`),x={fatal:!0,type:q.OTHER_ERROR,details:C.INTERSTITIAL_ASSET_ITEM_ERROR,error:T};this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),r,T.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${qr(t)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:g}),g}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(r=>{this.clearAssetPlayer(r.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const r=this.playerQueue[t];this.transferMediaFromPlayer(r,null),r.resetDetails()}}clearAssetPlayer(e,t){const r=this.getAssetPlayerQueueIndex(e);if(r!==-1){const s=this.playerQueue[r];this.log(`clear ${s} toSegment: ${t&&it(t)}`),this.transferMediaFromPlayer(s,t),this.playerQueue.splice(r,1),s.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,r,s,n){const{interstitial:a,assetItem:o,assetId:u}=e,l=a.assetList.length,c=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!c||c.identifier!==u)&&(c&&(this.clearAssetPlayer(c.identifier,r[s]),delete c.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${qr(o)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:r.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var r,s;if(!this.schedule)return;const{interstitial:n,assetItem:a}=e,o=this.schedule.findEventIndex(n.identifier),u=(r=this.schedule.items)==null?void 0:r[o];if(!u)return;e.loadSource(),this.setBufferingItem(u),this.bufferingAsset=a;const l=this.getBufferingPlayer();if(l===e)return;const c=n.appendInPlace;if(c&&(l==null?void 0:l.interstitial.appendInPlace)===!1)return;const d=(l==null?void 0:l.tracks)||((s=this.detachedData)==null?void 0:s.tracks)||this.requiredTracks;if(c&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(d&&!Mf(d,e.tracks)){const h=new Error(`Asset ${qr(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),f={fatal:!0,type:q.OTHER_ERROR,details:C.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},g=n.findAssetIndex(a);this.handleAssetItemError(f,n,o,g,h.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,r=this.primaryMedia;if(!t||!r)return;const s=r.currentTime,n=t.findAssetIndex(e,s),a=e.assetList[n];if(a){const o=this.getAssetPlayer(a.identifier);if(o){const u=o.currentTime||s-a.timelineStart,l=o.duration-u;if(this.warn(`Stalled at ${u} of ${u+l} in ${o} ${e} (media.currentTime: ${s})`),u&&(l/r.playbackRate<.5||o.bufferedInPlaceToEnd(r))&&o.hls){const c=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,c,n)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,r,s,n){if(e.details===C.BUFFER_STALLED_ERROR)return;const a=t.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&qr(a)} ${e.error}`),!this.schedule)return;const o=(a==null?void 0:a.identifier)||"",u=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[u]||null,c=this.schedule.items,d=ae({},e,{fatal:!1,errorAction:Wr(!0),asset:a,assetListIndex:s,event:t,schedule:c,scheduleIndex:r,player:l});if(this.hls.trigger(E.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;const h=this.playingAsset,f=this.bufferingAsset,g=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=g),!t.assetList.some(p=>!p.error))t.error=g;else for(let p=s;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):h&&h.identifier===o?this.advanceAfterAssetEnded(t,r,s):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){const t=e.timelineStart,r=this.effectivePlayingItem;let s=this.timelinePos;if(r){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${s} playing: ${it(r)} error: ${e.error}`),s===-1&&(s=this.hls.startPosition);const a=this.updateItem(r,s);this.itemsMatch(r,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(s===-1){this.checkStart();return}if(!this.schedule)return;const n=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(n)}onAssetListLoaded(e,t){var r,s;const n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((r=this.schedule)!=null&&r.hasEvent(a)))return;const u=n.timelineStart,l=n.duration;let c=0;o.forEach((p,m)=>{const v=parseFloat(p.DURATION);this.createAsset(n,m,c,u+c,v,p.URI),c+=v}),n.duration=c,this.log(`Loaded asset-list with duration: ${c} (was: ${l}) ${n}`);const d=this.waitingItem,h=(d==null?void 0:d.event.identifier)===a;this.updateSchedule();const f=(s=this.bufferingItem)==null?void 0:s.event;if(h){var g;const p=this.schedule.findEventIndex(a),m=(g=this.schedule.items)==null?void 0:g[p];if(m){if(!this.playingItem&&this.timelinePos>m.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){n.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${n}`),this.log(n.error.message),this.updateSchedule(!0),this.primaryFallback(n);return}this.setBufferingItem(m)}this.setSchedulePosition(p)}else if((f==null?void 0:f.identifier)===a){const p=n.assetList[0];if(p){const m=this.getAssetPlayer(p.identifier);if(f.appendInPlace){const v=this.primaryMedia;m&&v&&this.bufferAssetPlayer(m,v)}else m&&m.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case C.ASSET_LIST_PARSING_ERROR:case C.ASSET_LIST_LOAD_ERROR:case C.ASSET_LIST_LOAD_TIMEOUT:{const r=t.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break}case C.BUFFER_STALLED_ERROR:{const r=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&r.event.appendInPlace){this.handleInPlaceStall(r.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const Hd=500;class eT extends Lo{constructor(e,t,r){super(e,t,r,"subtitle-stream-controller",V.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=k.IDLE,this.setInterval(Hd),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:r,success:s}=t;if(this.fragContextChanged(r)||(me(r)&&(this.fragPrevious=r),this.state=k.IDLE),!s)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a;const o=r.start;for(let l=0;l<n.length;l++)if(o>=n[l].start&&o<=n[l].end){a=n[l];break}const u=r.start+r.duration;a?a.end=u:(a={start:o,end:u},n.push(a)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:r,endOffset:s}=t;if(r===0&&s!==Number.POSITIVE_INFINITY){const n=s-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(r,n,V.SUBTITLE)}}onError(e,t){const r=t.frag;(r==null?void 0:r.type)===V.SUBTITLE&&(t.details===C.FRAG_GAP&&this.fragmentTracker.fragBuffered(r,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==k.STOPPED&&(this.state=k.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Bg(this.levels,t)){this.levels=t.map(r=>new Ui(r));return}this.tracksBuffered=[],this.levels=t.map(r=>{const s=new Ui(r);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,V.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var r;if(this.currentTrackId=t.id,!((r=this.levels)!=null&&r.length)||this.currentTrackId===-1){this.clearInterval();return}const s=this.levels[this.currentTrackId];s!=null&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.state!==k.STOPPED&&this.setInterval(Hd)}onSubtitleTrackLoaded(e,t){var r;const{currentTrackId:s,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const u=n[o];if(o>=n.length||!u)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(a.live||(r=u.details)!=null&&r.live){if(a.deltaUpdateFailed)return;const d=this.mainDetails;if(!d){this.startFragRequested=!1;return}const h=d.fragments[0];if(!u.details)a.hasProgramDateTime&&d.hasProgramDateTime?(sn(a,d),l=a.fragmentStart):h&&(l=h.start,Ua(a,l));else{var c;l=this.alignPlaylists(a,u.details,(c=this.levelLastLoaded)==null?void 0:c.details),l===0&&h&&(l=h.start,Ua(a,l))}d&&!this.startFragRequested&&this.setStartPosition(d,l)}u.details=a,this.levelLastLoaded=u,o===s&&(this.hls.trigger(E.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===k.IDLE&&(or(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),u.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:r}=e,s=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&r&&r.byteLength>0&&s!=null&&s.key&&s.iv&&zr(s.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer,Io(s.method)).catch(o=>{throw n.trigger(E.ERROR,{type:q.MEDIA_ERROR,details:C.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const u=performance.now();n.trigger(E.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:u}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=k.IDLE})}}doTick(){if(!this.media){this.state=k.IDLE;return}if(this.state===k.IDLE){const{currentTrackId:e,levels:t}=this,r=t==null?void 0:t[e];if(!r||!t.length||!r.details||this.waitForLive(r))return;const{config:s}=this,n=this.getLoadPosition(),a=Y.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,s.maxBufferHole),{end:o,len:u}=a,l=r.details,c=this.hls.maxBufferLength+l.levelTargetDuration;if(u>c)return;const d=l.fragments,h=d.length,f=l.edge;let g=null;const p=this.fragPrevious;if(o<f){const y=s.maxFragLookUpTolerance,S=o>f-y?0:y;g=or(p,d,Math.max(d[0].start,o),S),!g&&p&&p.start<d[0].start&&(g=d[0])}else g=d[h-1];if(g=this.filterReplacedPrimary(g,r.details),!g)return;const m=g.sn-l.startSN,v=d[m-1];if(v&&v.cc===g.cc&&this.fragmentTracker.getState(v)===_e.NOT_LOADED&&(g=v),this.fragmentTracker.getState(g)===_e.NOT_LOADED){const y=this.mapToInitFragWhenRequired(g);y&&this.loadFragment(y,r,o)}}}loadFragment(e,t,r){me(e)?super.loadFragment(e,t,r):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new tT(this.tracksBuffered[this.currentTrackId]||[])}}class tT{constructor(e){this.buffered=void 0;const t=(r,s,n)=>{if(s=s>>>0,s>n-1)throw new DOMException(`Failed to execute '${r}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${n})`);return e[s][r]};this.buffered={get length(){return e.length},end(r){return t("end",r,e.length)},start(r){return t("start",r,e.length)}}}}const rT={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},em=i=>String.fromCharCode(rT[i]||i),st=15,vt=100,iT={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},sT={17:2,18:4,21:6,22:8,23:10,19:13,20:15},nT={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},aT={25:2,26:4,29:6,30:8,31:10,27:13,28:15},oT=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class lT{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const r=typeof t=="function"?t():t;ne.log(`${this.time} [${e}] ${r}`)}}}const sr=function(e){const t=[];for(let r=0;r<e.length;r++)t.push(e[r].toString(16));return t};class tm{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 r=0;r<t.length;r++){const s=t[r];e.hasOwnProperty(s)&&(this[s]=e[s])}}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 uT{constructor(){this.uchar=" ",this.penState=new tm}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 cT{constructor(e){this.chars=[],this.pos=0,this.currPenState=new tm,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<vt;t++)this.chars.push(new uT);this.logger=e}equals(e){for(let t=0;t<vt;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<vt;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<vt;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>vt&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=vt)}moveCursor(e){const t=this.pos+e;if(e>1)for(let r=this.pos+1;r<t+1;r++)this.chars[r].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=em(e);if(this.pos>=vt){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<vt;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 r=0;r<vt;r++){const s=this.chars[r].uchar;s!==" "&&(t=!1),e.push(s)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class fa{constructor(e){this.rows=[],this.currRow=st-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<st;t++)this.rows.push(new cT(e));this.logger=e}reset(){for(let e=0;e<st;e++)this.rows[e].clear();this.currRow=st-1}equals(e){let t=!0;for(let r=0;r<st;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}copy(e){for(let t=0;t<st;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<st;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+ue(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<st;o++)this.rows[o].clear();const n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[n].cueStartTime,u=this.logger.time;if(o!==null&&u!==null&&o<u)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(a.rows[n+l])}}this.currRow=t;const r=this.rows[this.currRow];if(e.indent!==null){const n=e.indent,a=Math.max(n-1,0);r.setCursor(e.indent),e.color=r.chars[a].penState.foreground}const s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+ue(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let r="",s=-1;for(let n=0;n<st;n++){const a=this.rows[n].getTextString();a&&(s=n+1,e?t.push("Row "+s+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?r="["+t.join(" | ")+"]":r=t.join(`
132132+`)),r}getTextAndFormat(){return this.rows}}class Wd{constructor(e,t,r){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 fa(r),this.nonDisplayedMemory=new fa(r),this.lastOutputScreen=new fa(r),this.currRollUpRow=this.displayedMemory.rows[st-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[st-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 r=0;r<e.length;r++)this.writeScreen.insertChar(e[r]);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 r=Math.floor(e/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=s[r]}this.logger.log(2,"MIDROW: "+ue(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class zd{constructor(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=hT(),this.logger=void 0;const s=this.logger=new lT;this.channels=[null,new Wd(e,t,s),new Wd(e+1,r,s)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let r=0;r<t.length;r+=2){const s=t[r]&127,n=t[r+1]&127;let a=!1,o=null;if(s===0&&n===0)continue;this.logger.log(3,()=>"["+sr([t[r],t[r+1]])+"] -> ("+sr([s,n])+")");const u=this.cmdHistory;if(s>=16&&s<=31){if(dT(s,n,u)){Ts(null,null,u),this.logger.log(3,()=>"Repeated command ("+sr([s,n])+") is dropped");continue}Ts(s,n,this.cmdHistory),a=this.parseCmd(s,n),a||(a=this.parseMidrow(s,n)),a||(a=this.parsePAC(s,n)),a||(a=this.parseBackgroundAttributes(s,n))}else Ts(null,null,u);if(!a&&(o=this.parseChars(s,n),o)){const c=this.currentChannel;c&&c>0?this.channels[c].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+sr([s,n])+" orig: "+sr([t[r],t[r+1]]))}}parseCmd(e,t){const r=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=33&&t<=35;if(!(r||s))return!1;const n=e===20||e===21||e===23?1:2,a=this.channels[n];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let r=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?r=1:r=2,r!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[r];return s?(s.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+sr([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let r;const s=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(s||n))return!1;const a=e<=23?1:2;t>=64&&t<=95?r=a===1?iT[e]:nT[e]:r=a===1?sT[e]:aT[e];const o=this.channels[a];return o?(o.setPAC(this.interpretPAC(r,t)),this.currentChannel=a,!0):!1}interpretPAC(e,t){let r;const s={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?r=t-96:r=t-64,s.underline=(r&1)===1,r<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(s.italics=!0,s.color="white"):s.indent=Math.floor((r-16)/2)*4,s}parseChars(e,t){let r,s=null,n=null;if(e>=25?(r=2,n=e-8):(r=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 '"+em(a)+"' in channel "+r),s=[a]}else e>=32&&e<=127&&(s=t===0?[e]:[e,t]);return s&&this.logger.log(3,()=>"Char codes = "+sr(s).join(",")),s}parseBackgroundAttributes(e,t){const r=(e===16||e===24)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=45&&t<=47;if(!(r||s))return!1;let n;const a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=oT[n],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Ts(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const r=this.channels[t];r&&r.cueSplitAtTime(e)}}}function Ts(i,e,t){t.a=i,t.b=e}function dT(i,e,t){return t.a===i&&t.b===e}function hT(){return{a:null,b:null}}var $o=function(){if(rn!=null&&rn.VTTCue)return self.VTTCue;const i=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,u){if(typeof u!="string"||!Array.isArray(o))return!1;const l=u.toLowerCase();return~o.indexOf(l)?l:!1}function r(o){return t(i,o)}function s(o){return t(e,o)}function n(o,...u){let l=1;for(;l<arguments.length;l++){const c=arguments[l];for(const d in c)o[d]=c[d]}return o}function a(o,u,l){const c=this,d={enumerable:!0};c.hasBeenReset=!1;let h="",f=!1,g=o,p=u,m=l,v=null,y="",S=!0,_="auto",T="start",x=50,b="middle",I=50,A="middle";Object.defineProperty(c,"id",n({},d,{get:function(){return h},set:function(D){h=""+D}})),Object.defineProperty(c,"pauseOnExit",n({},d,{get:function(){return f},set:function(D){f=!!D}})),Object.defineProperty(c,"startTime",n({},d,{get:function(){return g},set:function(D){if(typeof D!="number")throw new TypeError("Start time must be set to a number.");g=D,this.hasBeenReset=!0}})),Object.defineProperty(c,"endTime",n({},d,{get:function(){return p},set:function(D){if(typeof D!="number")throw new TypeError("End time must be set to a number.");p=D,this.hasBeenReset=!0}})),Object.defineProperty(c,"text",n({},d,{get:function(){return m},set:function(D){m=""+D,this.hasBeenReset=!0}})),Object.defineProperty(c,"region",n({},d,{get:function(){return v},set:function(D){v=D,this.hasBeenReset=!0}})),Object.defineProperty(c,"vertical",n({},d,{get:function(){return y},set:function(D){const L=r(D);if(L===!1)throw new SyntaxError("An invalid or illegal string was specified.");y=L,this.hasBeenReset=!0}})),Object.defineProperty(c,"snapToLines",n({},d,{get:function(){return S},set:function(D){S=!!D,this.hasBeenReset=!0}})),Object.defineProperty(c,"line",n({},d,{get:function(){return _},set:function(D){if(typeof D!="number"&&D!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");_=D,this.hasBeenReset=!0}})),Object.defineProperty(c,"lineAlign",n({},d,{get:function(){return T},set:function(D){const L=s(D);if(!L)throw new SyntaxError("An invalid or illegal string was specified.");T=L,this.hasBeenReset=!0}})),Object.defineProperty(c,"position",n({},d,{get:function(){return x},set:function(D){if(D<0||D>100)throw new Error("Position must be between 0 and 100.");x=D,this.hasBeenReset=!0}})),Object.defineProperty(c,"positionAlign",n({},d,{get:function(){return b},set:function(D){const L=s(D);if(!L)throw new SyntaxError("An invalid or illegal string was specified.");b=L,this.hasBeenReset=!0}})),Object.defineProperty(c,"size",n({},d,{get:function(){return I},set:function(D){if(D<0||D>100)throw new Error("Size must be between 0 and 100.");I=D,this.hasBeenReset=!0}})),Object.defineProperty(c,"align",n({},d,{get:function(){return A},set:function(D){const L=s(D);if(!L)throw new SyntaxError("An invalid or illegal string was specified.");A=L,this.hasBeenReset=!0}})),c.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class fT{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function rm(i){function e(r,s,n,a){return(r|0)*3600+(s|0)*60+(n|0)+parseFloat(a||0)}const t=i.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 gT{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,r){for(let s=0;s<r.length;++s)if(t===r[s]){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 r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}}function im(i,e,t,r){const s=r?i.split(r):[i];for(const n in s){if(typeof s[n]!="string")continue;const a=s[n].split(t);if(a.length!==2)continue;const o=a[0],u=a[1];e(o,u)}}const Wa=new $o(0,0,""),bs=Wa.align==="middle"?"middle":"center";function mT(i,e,t){const r=i;function s(){const o=rm(i);if(o===null)throw new Error("Malformed timestamp: "+r);return i=i.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,u){const l=new gT;im(o,function(h,f){let g;switch(h){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){l.set(h,t[p].region);break}break;case"vertical":l.alt(h,f,["rl","lr"]);break;case"line":g=f.split(","),l.integer(h,g[0]),l.percent(h,g[0])&&l.set("snapToLines",!1),l.alt(h,g[0],["auto"]),g.length===2&&l.alt("lineAlign",g[1],["start",bs,"end"]);break;case"position":g=f.split(","),l.percent(h,g[0]),g.length===2&&l.alt("positionAlign",g[1],["start",bs,"end","line-left","line-right","auto"]);break;case"size":l.percent(h,f);break;case"align":l.alt(h,f,["start",bs,"end","left","right"]);break}},/:/,/\s/),u.region=l.get("region",null),u.vertical=l.get("vertical","");let c=l.get("line","auto");c==="auto"&&Wa.line===-1&&(c=-1),u.line=c,u.lineAlign=l.get("lineAlign","start"),u.snapToLines=l.get("snapToLines",!0),u.size=l.get("size",100),u.align=l.get("align",bs);let d=l.get("position","auto");d==="auto"&&Wa.position===50&&(d=u.align==="start"||u.align==="left"?0:u.align==="end"||u.align==="right"?100:50),u.position=d}function a(){i=i.replace(/^\s+/,"")}if(a(),e.startTime=s(),a(),i.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+r);i=i.slice(3),a(),e.endTime=s(),a(),n(i,e)}function sm(i){return i.replace(/<br(?: \/)?>/gi,`
133133+`)}class pT{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new fT,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 r(){let n=t.buffer,a=0;for(n=sm(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
134134+`;)++a;const o=n.slice(0,a);return n[a]==="\r"&&++a,n[a]===`
135135+`&&++a,t.buffer=n.slice(a),o}function s(n){im(n,function(a,o){},/:/)}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=r();const o=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:n=r(),t.state){case"HEADER":/:/.test(n)?s(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new $o(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{mT(n,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=n.indexOf("-->")!==-1;if(!n||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
136136+`),t.cue.text+=n}continue;case"BADCUE":n||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
123137124124-`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const tf=/\r\n|\n\r|\n|\r/g,ci=function(e,t,s=0){return e.slice(s,s+t.length)===t},sf=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!M(t)||!M(s)||!M(i)||!M(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*i,t+=60*60*1e3*r,t};function mr(n,e,t){return Ut(n.toString())+Ut(e.toString())+Ut(t)}const rf=function(e,t,s){let i=e[t],r=e[i.prevCC];if(!r||!r.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(a=r)!=null&&a.new;){var a;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=s};function nf(n,e,t,s,i,r,a){const o=new ef,c=Ce(new Uint8Array(n)).trim().replace(tf,`
138138+`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const yT=/\r\n|\n\r|\n|\r/g,ga=function(e,t,r=0){return e.slice(r,r+t.length)===t},vT=function(e){let t=parseInt(e.slice(-3));const r=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!$(t)||!$(r)||!$(s)||!$(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*r,t+=60*1e3*s,t+=60*60*1e3*n,t};function jo(i,e,t){return Oi(i.toString())+Oi(e.toString())+Oi(t)}const ET=function(e,t,r){let s=e[t],n=e[s.prevCC];if(!n||!n.new&&s.new){e.ccOffset=e.presentationOffset=s.start,s.new=!1;return}for(;(a=n)!=null&&a.new;){var a;e.ccOffset+=s.start-n.start,s.new=!1,s=n,n=e[s.prevCC]}e.presentationOffset=r};function ST(i,e,t,r,s,n,a){const o=new pT,u=Ye(new Uint8Array(i)).trim().replace(yT,`
125139`).split(`
126126-`),l=[],h=e?hu(e.baseTime,e.timescale):0;let u="00:00.000",d=0,f=0,g,p=!0;o.oncue=function(y){const E=t[s];let T=t.ccOffset;const S=(d-h)/9e4;if(E!=null&&E.new&&(f!==void 0?T=t.ccOffset=E.start:rf(t,s,S)),S){if(!e){g=new Error("Missing initPTS for VTT MPEGTS");return}T=S-t.presentationOffset}const v=y.endTime-y.startTime,x=be((y.startTime+T-f)*9e4,i*9e4)/9e4;y.startTime=Math.max(x,0),y.endTime=Math.max(x+v,0);const D=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(D)),y.id||(y.id=mr(y.startTime,y.endTime,D)),y.endTime>0&&l.push(y)},o.onparsingerror=function(y){g=y},o.onflush=function(){if(g){a(g);return}r(l)},c.forEach(y=>{if(p)if(ci(y,"X-TIMESTAMP-MAP=")){p=!1,y.slice(16).split(",").forEach(E=>{ci(E,"LOCAL:")?u=E.slice(6):ci(E,"MPEGTS:")&&(d=parseInt(E.slice(7)))});try{f=sf(u)/1e3}catch(E){g=E}return}else y===""&&(p=!1);o.parse(y+`
127127-`)}),o.flush()}const hi="stpp.ttml.im1t",Ho=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Wo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,af={left:"start",center:"center",right:"end",start:"start",end:"end"};function Kn(n,e,t,s){const i=z(new Uint8Array(n),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>Ce(o)),a=cu(e.baseTime,1,e.timescale);try{r.forEach(o=>t(of(o,a)))}catch(o){s(o)}}function of(n,e){const i=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(r).reduce((u,d)=>(u[d]=i.getAttribute(`ttp:${d}`)||r[d],u),{}),o=i.getAttribute("xml:space")!=="preserve",c=Vn(ui(i,"styling","style")),l=Vn(ui(i,"layout","region")),h=ui(i,"body","[begin]");return[].map.call(h,u=>{const d=Yo(u,o);if(!d||!u.hasAttribute("begin"))return null;const f=fi(u.getAttribute("begin"),a),g=fi(u.getAttribute("dur"),a);let p=fi(u.getAttribute("end"),a);if(f===null)throw Hn(u);if(p===null){if(g===null)throw Hn(u);p=f+g}const y=new gr(f-e,p-e,d);y.id=mr(y.startTime,y.endTime,y.text);const E=l[u.getAttribute("region")],T=c[u.getAttribute("style")],S=lf(E,T,c),{textAlign:v}=S;if(v){const x=af[v];x&&(y.lineAlign=x),y.align=v}return re(y,S),y}).filter(u=>u!==null)}function ui(n,e,t){const s=n.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Vn(n){return n.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Yo(n,e){return[].slice.call(n.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+`
128128-`:(r=s.childNodes)!=null&&r.length?Yo(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function lf(n,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=n!=null&&n.hasAttribute("style")?n.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(i=t[a]),r.reduce((o,c)=>{const l=di(e,s,c)||di(n,s,c)||di(i,s,c);return l&&(o[c]=l),o},{})}function di(n,e,t){return n&&n.hasAttributeNS(e,t)?n.getAttributeNS(e,t):null}function Hn(n){return new Error(`Could not parse ttml timestamp ${n}`)}function fi(n,e){if(!n)return null;let t=Go(n);return t===null&&(Ho.test(n)?t=cf(n,e):Wo.test(n)&&(t=hf(n,e))),t}function cf(n,e){const t=Ho.exec(n),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function hf(n,e){const t=Wo.exec(n),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}class cs{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class uf{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(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new cs(this,"textTrack1"),t=new cs(this,"textTrack2"),s=new cs(this,"textTrack3"),i=new cs(this,"textTrack4");this.cea608Parser1=new Gn(1,e,t),this.cea608Parser2=new Gn(3,s,i)}addCues(e,t,s,i,r){let a=!1;for(let o=r.length;o--;){const c=r[o],l=df(c[0],c[1],t,s);if(l>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],s),a=!0,l/(s-t)>.5))return}if(a||r.push([t,s]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,s,i)}else{const o=this.Cues.newCue(null,t,s,i);this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:a}){const{unparsedVttFrags:o}=this;s===U.MAIN&&(this.initPTS[t.cc]={baseTime:i,timescale:r,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(m.FRAG_LOADED,c):this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(Wn(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:a}=t[e],o=this.getExistingTrack(r,a);if(o)s[e]=o,At(s[e]),Mo(s[e],i);else{const c=this.createTextTrack("captions",r,a);c&&(c[e]=!0,s[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,s){const i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:i}=this;Object.keys(i).forEach(r=>{At(i[r]),delete i[r]}),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 s=0;s<t.length;s++)At(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(r=>r.textCodec===hi);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(Ao(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const a=this.media,o=a?vs(a.textTracks):null;if(this.tracks.forEach((c,l)=>{let h;if(o){let u=null;for(let d=0;d<o.length;d++)if(o[d]&&Wn(o[d],c)){u=o[d],o[d]=null;break}u&&(h=u)}if(h)At(h);else{const u=qo(c);h=this.createTextTrack(u,c.name,c.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),o!=null&&o.length){const c=o.filter(l=>l!==null).map(l=>l.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const r=`textTrack${i[1]}`,a=this.captionsProperties[r];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===U.MAIN){var s,i;const{cea608Parser1:r,cea608Parser2:a,lastSn:o}=this,{cc:c,sn:l}=t.frag,h=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&a&&(l!==o+1||l===o&&h!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=c,this.lastSn=l,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===U.SUBTITLE)if(i.byteLength){const r=s.decryptdata,a="stats"in t;if(r==null||!r.encrypted||a){const o=this.tracks[s.level],c=this.vttCCs;c[s.cc]||(c[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===hi?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;Kn(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{s.logger.log(`Failed to parse IMSC1: ${i}`),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:a}=this,o=r.length-1;if(!r[s.cc]&&o===-1){a.push(e);return}const c=this.hls,l=(t=s.initSegment)!=null&&t.data?Oe(s.initSegment.data,new Uint8Array(i)).buffer:i;nf(l,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,h=>{this._appendCues(h,s.level),c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},h=>{const u=h.message==="Missing initPTS for VTT MPEGTS";u?a.push(e):this._fallbackToIMSC1(s,i),c.logger.log(`Failed to parse VTT cue: ${h}`),!(u&&o>s.cc)&&c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:h})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||Kn(t,this.initPTS[e.cc],()=>{s.textCodec=hi,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||i.mode==="disabled")return;e.forEach(r=>No(i,r))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(m.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===U.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(!(s.type===U.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let r=0;r<i.length;r++){const a=i[r].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(i[r].pts,o[0]),this.cea608Parser2.addData(i[r].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:a}=this;if(!(!a||a.currentTime<s)){if(!r||r==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(c=>Bi(o[c],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>Bi(o[c],t,i))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let r=0;r<s;r++){const a=e[i++],o=127&e[i++],c=127&e[i++];if(o===0&&c===0)continue;if((4&a)!==0){const h=3&a;(h===0||h===1)&&(t[h].push(o),t[h].push(c))}}return t}}function qo(n){return n.characteristics&&/transcribes-spoken-dialog/gi.test(n.characteristics)&&/describes-music-and-sound/gi.test(n.characteristics)?"captions":"subtitles"}function Wn(n,e){return!!n&&n.kind===qo(e)&&Oi(e,n)}function df(n,e,t,s){return Math.min(e,s)-Math.max(n,t)}function Yn(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const ff=/\s/,gf={newCue(n,e,t,s){const i=[];let r,a,o,c,l;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d<s.rows.length;d++)if(r=s.rows[d],o=!0,c=0,l="",!r.isEmpty()){var u;for(let p=0;p<r.chars.length;p++)ff.test(r.chars[p].uchar)&&o?c++:(l+=r.chars[p].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;const f=Vo(l.trim()),g=mr(e,t,f);n!=null&&(u=n.cues)!=null&&u.getCueById(g)||(a=new h(e,t,f),a.id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(a))}return n&&i.length&&(i.sort((d,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),i.forEach(d=>No(n,d))),i}};function mf(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const pf=/(\d+)-(\d+)\/(\d+)/;class qn{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||Sf,this.controller=new self.AbortController,this.stats=new qi}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=yf(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&M(c)?c:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},t.timeout),(Wt(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var d;this.response=this.loader=u;const f=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(f-i.loading.start)),!u.ok){const{status:p,statusText:y}=u;throw new vf(y||"fetch, bad network response",p,u)}i.loading.first=f,i.total=Tf(u.headers)||i.total;const g=(d=this.callbacks)==null?void 0:d.onProgress;return g&&M(t.highWaterMark)?this.loadProgressively(u,i,e,t.highWaterMark,g):a?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{var d,f;const g=this.response;if(!g)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const p=u[o];p&&(i.loaded=i.total=p);const y={url:g.url,data:u,code:g.status},E=(d=this.callbacks)==null?void 0:d.onProgress;E&&!M(t.highWaterMark)&&E(i,e,u,g),(f=this.callbacks)==null||f.onSuccess(y,i,e,g)}).catch(u=>{var d;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const f=u&&u.code||0,g=u?u.message:null;(d=this.callbacks)==null||d.onError({code:f,text:g},e,u?u.details:null,i)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const a=new so,o=e.body.getReader(),c=()=>o.read().then(l=>{if(l.done)return a.dataLength&&r(t,s,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const h=l.value,u=h.length;return t.loaded+=u,u<i||a.dataLength?(a.push(h),a.dataLength>=i&&r(t,s,a.flush().buffer,e)):r(t,s,h.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function yf(n,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(re({},n.headers))};return n.rangeEnd&&t.headers.set("Range","bytes="+n.rangeStart+"-"+String(n.rangeEnd-1)),t}function Ef(n){const e=pf.exec(n);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Tf(n){const e=n.get("Content-Range");if(e){const s=Ef(e);if(M(s))return s}const t=n.get("Content-Length");if(t)return parseInt(t)}function Sf(n,e){return new self.Request(n.url,e)}class vf extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const xf=/^age:\s*[\d.]+\s*$/im;class jo{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 qi,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return r(s,t.url)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),r(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=s.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&M(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,h=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const g=h??t.response;if(g!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=t.responseType==="arraybuffer"?g.byteLength:g.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const y=(a=this.callbacks)==null?void 0:a.onProgress;y&&y(s,e,g,t);const E={url:t.responseURL,data:g,code:l};(o=this.callbacks)==null||o.onSuccess(E,s,e,t);return}}const u=r.loadPolicy.errorRetry,d=s.retry,f={url:e.url,data:void 0,code:l};if(ws(u,d,!1,f))this.retry(u);else{var c;ie.error(`${l} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:l,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(ws(e,t,!0))this.retry(e);else{var s;ie.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=Qi(e,s.retry),s.retry++,ie.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&xf.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const Af={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},_f=se(se({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:jo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Fc,bufferController:Iu,capLevelController:ur,errorController:$c,fpsController:Ld,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:Wa,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:Af},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},If()),{},{subtitleStreamController:Bd,subtitleTrackController:Dd,timelineController:uf,audioStreamController:vu,audioTrackController:xu,emeController:Lt,cmcdController:xd,contentSteeringController:_d,interstitialsController:Nd});function If(){return{cueHandler:gf,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 Lf(n,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=$i(n),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,c=e[o]===void 0,l=[];r.forEach(h=>{const u=`${a}Loading${h}`,d=e[u];if(d!==void 0&&c){l.push(u);const f=s[o].default;switch(e[o]={default:f},h){case"TimeOut":f.maxLoadTimeMs=d,f.maxTimeToFirstByteMs=d;break;case"MaxRetry":f.errorRetry.maxNumRetry=d,f.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":f.errorRetry.retryDelayMs=d,f.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=d,f.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${oe(e[o])}`)}),se(se({},s),e)}function $i(n){return n&&typeof n=="object"?Array.isArray(n)?n.map($i):Object.keys(n).reduce((e,t)=>(e[t]=$i(n[t]),e),{}):n}function Rf(n,e){const t=n.loader;t!==qn&&t!==jo?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):mf()&&(n.loader=qn,n.progressive=!0,n.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const xs=2,bf=.1,Df=.05,Cf=100;class Pf extends $a{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(Cf),this.mediaSource=t.mediaSource;const s=this.media=t.media;Ae(s,"playing",this.onMediaPlaying),Ae(s,"waiting",this.onMediaWaiting),Ae(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(Ie(s,"playing",this.onMediaPlaying),Ie(s,"waiting",this.onMediaWaiting),Ie(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,i;const r=(s=this.hls)==null?void 0:s.config;if(!r)return;const a=this.media;if(!a)return;const{seeking:o}=a,c=this.seeking&&!o,l=!this.seeking&&o,h=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||c){c&&this.stallResolved(e);return}if(h){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1}));return}if(!q.getBuffered(a).length){this.nudgeRetry=0;return}const u=q.bufferInfo(a,e,0),d=u.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const D=jn(this.hls.inFlightFragments,e),A=u.len>xs,b=!d||D||d-e>xs&&!f.getPartialFragment(e);if(A||b)return;this.moved=!1}const g=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(u.len>0)&&!d)return;const A=Math.max(d,u.start||0)-e,I=!!(g!=null&&g.live)?g.targetduration*2:xs,_=hs(e,f);if(A>0&&(A<=I||_)){a.paused||this._trySkipBufferHole(_);return}}const p=r.detectStallWithCurrentTimeMs,y=self.performance.now(),E=this.waiting;let T=this.stalled;if(T===null)if(E>0&&y-E<p)T=this.stalled=E;else{this.stalled=y;return}const S=y-T;if(!o&&(S>=p||E)&&this.hls){var v;if(((v=this.mediaSource)==null?void 0:v.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(e-((g==null?void 0:g.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return}const x=q.bufferInfo(a,e,r.maxBufferHole);this._tryFixBufferStall(x,S,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(m.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&e>i.end(0)){const r=q.bufferedInfo(q.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const a=q.timeRangesToArray(i),o=q.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const c=q.bufferedInfo(a,e,0).bufferedIndex,l=a[o].end,h=a[o+1].start;if((c===-1||c>o)&&h-l<1&&e-l<2){const u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${h} buffered index: ${c}`);this.warn(u.message),this.media.currentTime+=1e-6;let d=hs(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);const f=q.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:a,media:o}=this,c=(i=this.hls)==null?void 0:i.config;if(!o||!a||!c)return;const l=(r=this.hls)==null?void 0:r.latestLevelDetails,h=hs(s,a);if((h||l!=null&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;const u=e.buffered,d=this.adjacentTraversal(e,s);(u&&u.length>1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-s<c.maxBufferHole||d))&&(t>c.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const r=s.getFragAtPos(t,U.MAIN),a=s.getFragAtPos(i,U.MAIN);if(r&&a)return a.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&r!==null&&s&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${oe(e)})`);this.warn(a.message),t.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:i}=this,r=(t=this.hls)==null?void 0:t.config;if(!i||!s||!r)return 0;const a=i.currentTime,o=q.bufferInfo(i,a,0),c=a<o.start?o.start:o.nextStart;if(c&&this.hls){const h=o.len<=r.maxBufferHole,u=o.len>0&&o.len<1&&i.readyState<3,d=c-a;if(d>0&&(h||u)){if(d>r.maxBufferHole){let g=!1;if(a===0){const p=s.getAppendedFrag(0,U.MAIN);p&&c<p.end&&(g=!0)}if(!g&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||jn(this.hls.inFlightFragments,c))return 0;let y=!1,E=e.end;for(;E<c;){const T=hs(E,s);if(T)E+=T.duration;else{y=!0;break}}if(y)return 0}}const f=Math.max(c+Df,a+bf);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,i.currentTime=f,!(e!=null&&e.gap)){const g=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),p={type:H.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:g,reason:g.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(m.ERROR,p)}return f}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=t==null?void 0:t.config;if(!s||!r)return 0;const a=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const o=a+(i+1)*r.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(c.message),s.currentTime=o,t.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_NUDGE_ON_STALL,error:c,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function jn(n,e){const t=Xn(n.main);if(t&&t.start<=e)return t;const s=Xn(n.audio);return s&&s.start<=e?s:null}function Xn(n){if(!n)return null;switch(n.state){case P.IDLE:case P.STOPPED:case P.ENDED:case P.ERROR:return null}return n.frag}function hs(n,e){return e.getAppendedFrag(n,U.MAIN)||e.getPartialFragment(n)}const kf=.25;function Gi(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function gi(n,e,t,s,i){let r=new n(e,t,"");try{r.value=s,i&&(r.type=i)}catch{r=new n(e,t,oe(i?se({type:i},s):s))}return r}const us=(()=>{const n=Gi();try{n&&new n(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class wf{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(m.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&At(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return Mo(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=Gi();if(a)for(let o=0;o<r.length;o++){const c=r[o].type;if(c===De.emsg&&!s||!i)continue;const l=co(r[o].data),h=r[o].pts;let u=h+r[o].duration;u>us&&(u=us),u-h<=0&&(u=h+kf);for(let f=0;f<l.length;f++){const g=l[f];if(!ho(g)){this.updateId3CueEnds(h,c);const p=gi(a,h,u,g,c);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var s;const i=(s=this.id3Track)==null?void 0:s.cues;if(i)for(let r=i.length;r--;){const a=i[r];a.type===t&&a.startTime<e&&a.endTime===us&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:c}}=a;if(r&&(o||c)){let l;i==="audio"?l=h=>h.type===De.audioId3&&c:i==="video"?l=h=>h.type===De.emsg&&o:l=h=>h.type===De.audioId3&&c||h.type===De.emsg&&o,Bi(r,t,s,l)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:a}=this.hls.config;if(!r)return;const o=Gi();if(s&&i&&!a){const{fragmentStart:p,fragmentEnd:y}=e;let E=this.assetCue;E?(E.startTime=p,E.endTime=y):o&&(E=this.assetCue=gi(o,p,y,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),E&&(E.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(E),E.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:l}=e,h=Object.keys(l);let u=this.dateRangeCuesAppended;if(c&&t){var d;if((d=c.cues)!=null&&d.length){const p=Object.keys(u).filter(y=>!h.includes(y));for(let y=p.length;y--;){var f;const E=p[y],T=(f=u[E])==null?void 0:f.cues;delete u[E],T&&Object.keys(T).forEach(S=>{const v=T[S];if(v){v.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(v)}catch{}}})}}else u=this.dateRangeCuesAppended={}}const g=e.fragments[e.fragments.length-1];if(!(h.length===0||!M(g==null?void 0:g.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<h.length;p++){const y=h[p],E=l[y],T=E.startTime,S=u[y],v=(S==null?void 0:S.cues)||{};let x=(S==null?void 0:S.durationKnown)||!1,D=us;const{duration:A,endDate:b}=E;if(b&&A!==null)D=T+A,x=!0;else if(E.endOnNext&&!x){const _=h.reduce((C,k)=>{if(k!==E.id){const B=l[k];if(B.class===E.class&&B.startDate>E.startDate&&(!C||E.startDate<C.startDate))return B}return C},null);_&&(D=_.startTime,x=!0)}const I=Object.keys(E.attr);for(let _=0;_<I.length;_++){const C=I[_];if(!Jc(C))continue;const k=v[C];if(k)x&&!(S!=null&&S.durationKnown)?k.endTime=D:Math.abs(k.startTime-T)>.01&&(k.startTime=T,k.endTime=D);else if(o){let B=E.attr[C];eh(C)&&(B=Sa(B));const $=gi(o,T,D,{key:C,data:B},De.dateRange);$&&($.id=y,this.id3Track.addCue($),v[C]=$,a&&(C==="X-ASSET-LIST"||C==="X-ASSET-URL")&&$.addEventListener("enter",this.onEventCueEnter))}}u[y]={cues:v,dateRange:E,durationKnown:x}}}}}class Of{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:a}=this.config;if(!r||a===1||!s.live)return;const o=this.targetLatency;if(o===null)return;const c=i-o,l=Math.min(this.maxLatency,o+s.targetduration);if(c<l&&c>.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,a)),d=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,f=Math.min(u,Math.max(1,d));this.changeMediaPlaybackRate(t,f)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let l=o&&s||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=r!==void 0?r:a*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const s=this.levelDetails;if(s===null)return null;const i=s.edge,r=e-t-this.edgeStalled,a=i-s.totalduration,o=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(a,r),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===R.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class Ff extends hr{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},a={};let o=!1,c=!1,l=!1;t.levels.forEach(h=>{const u=h.attrs;let{audioCodec:d,videoCodec:f}=h;d&&(h.audioCodec=d=Ds(d,s)||void 0),f&&(f=h.videoCodec=pc(f));const{width:g,height:p,unknownCodecs:y}=h,E=(y==null?void 0:y.length)||0;if(o||(o=!!(g&&p)),c||(c=!!f),l||(l=!!d),E||d&&!this.isAudioSupported(d)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${u.CODECS}"`);return}const{CODECS:T,"FRAME-RATE":S,"HDCP-LEVEL":v,"PATHWAY-ID":x,RESOLUTION:D,"VIDEO-RANGE":A}=u,I=`${`${x||"."}-`}${h.bitrate}-${D}-${S}-${T}-${A}-${v}`;if(r[I])if(r[I].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const _=a[I]+=1;h.attrs["PATHWAY-ID"]=new Array(_+1).join(".");const C=this.createLevel(h);r[I]=C,i.push(C)}else r[I].addGroupId("audio",u.AUDIO),r[I].addGroupId("text",u.SUBTITLES);else{const _=this.createLevel(h);r[I]=_,a[I]=1,i.push(_)}}),this.filterAndSortMediaOptions(i,t,o,c,l)}createLevel(e){const t=new Kt(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(i.message),t.supportedResult=ka(i,[])}return t}isAudioSupported(e){return $t(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return $t(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,r){var a;let o=[],c=[],l=e;const h=((a=t.stats)==null?void 0:a.parsing)||{};if((s||i)&&r&&(l=l.filter(({videoCodec:T,videoRange:S,width:v,height:x})=>(!!T||!!(v&&x))&&Lc(S))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let T="no level with compatible codecs found in manifest",S=T;t.levels.length&&(S=`one or more CODECS in variant not supported: ${oe(t.levels.map(x=>x.attrs.CODECS).filter((x,D,A)=>A.indexOf(x)===D))}`,this.warn(S),T+=` (${S})`);const v=new Error(T);this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:v,reason:S})}}),h.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(T=>!T.audioCodec||this.isAudioSupported(T.audioCodec)),zn(o)),t.subtitles&&(c=t.subtitles,zn(c));const u=l.slice(0);l.sort((T,S)=>{if(T.attrs["HDCP-LEVEL"]!==S.attrs["HDCP-LEVEL"])return(T.attrs["HDCP-LEVEL"]||"")>(S.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&T.height!==S.height)return T.height-S.height;if(T.frameRate!==S.frameRate)return T.frameRate-S.frameRate;if(T.videoRange!==S.videoRange)return Cs.indexOf(T.videoRange)-Cs.indexOf(S.videoRange);if(T.videoCodec!==S.videoCodec){const v=$r(T.videoCodec),x=$r(S.videoCodec);if(v!==x)return x-v}if(T.uri===S.uri&&T.codecSet!==S.codecSet){const v=bs(T.codecSet),x=bs(S.codecSet);if(v!==x)return x-v}return T.averageBitrate!==S.averageBitrate?T.averageBitrate-S.averageBitrate:0});let d=u[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==u.length)){for(let T=0;T<u.length;T++)if(u[T].pathwayId===l[0].pathwayId){d=u[T];break}}this._levels=l;for(let T=0;T<l.length;T++)if(l[T]===d){var f;this._firstLevel=T;const S=d.bitrate,v=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${S}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){const x=Math.min(S,this.hls.config.abrEwmaDefaultEstimateMax);x>v&&v===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=x)}break}const g=r&&!i,p=this.hls.config,y=!!(p.audioStreamController&&p.audioTrackController),E={levels:l,audioTracks:o,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:y&&!g&&o.some(T=>!!T.url)};h.end=performance.now(),this.hls.trigger(m.MANIFEST_PARSED,E)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const h=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:h,reason:h.message}),u)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&i&&r===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);const c={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(m.LEVEL_SWITCHING,c);const l=a.details;if(!l||l.live){const h=this.switchParams(a.uri,i==null?void 0:i.details,l);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(i=>t.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===Q.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===U.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let c=a.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(i,t,c)}else(s=t.deliveryDirectives)!=null&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],a=e.details,o=a==null?void 0:a.age;this.log(`Loading level index ${i}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(m.LEVEL_LOADING,{url:s,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const s=this._levels.filter((r,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));Ja(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(m.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(m.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function zn(n){const e={};n.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function Xo(){return self.SourceBuffer||self.WebKitSourceBuffer}function zo(){if(!at())return!1;const e=Xo();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Mf(){if(!zo())return!1;const n=at();return typeof(n==null?void 0:n.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>n.isTypeSupported(Gt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>n.isTypeSupported(Gt(e,"audio"))))}function Nf(){var n;const e=Xo();return typeof(e==null||(n=e.prototype)==null?void 0:n.changeType)=="function"}const Bf=100;class Uf extends sr{constructor(e,t,s){super(e,t,s,"stream-controller",U.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const i=this.media,r=i?i.currentTime:null;if(r===null||!M(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const a=this.getFwdBufferInfoAtPos(i,r,U.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(Bf),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._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=P.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=P.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case P.WAITING_LEVEL:{const{levels:e,level:t}=this,s=e==null?void 0:e[t],i=s==null?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=P.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=P.IDLE;break}break}case P.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===P.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(t===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[r]))return;const a=s[r],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(m.BUFFER_EOS,p),this.state=P.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=a.details;if(!l||this.state===P.WAITING_LEVEL||this.waitForLive(a)){this.level=r,this.state=P.WAITING_LEVEL,this.startFragRequested=!1;return}const h=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(d,l);if(this.couldBacktrack&&!this.fragPrevious&&f&&de(f)&&this.fragmentTracker.getState(f)!==me.OK){var g;const y=((g=this.backtrackFragment)!=null?g:f).sn-l.startSN,E=l.fragments[y-1];E&&f.cc===E.cc&&(f=E,this.fragmentTracker.removeFragment(E))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,d)){if(!f.gap){const y=this.audioOnly&&!this.altAudio?ne.AUDIO:ne.VIDEO,E=(y===ne.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,y,U.MAIN)}f=this.getNextFragmentLoopLoading(f,l,o,U.MAIN,u)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,d))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===me.NOT_LOADED||i===me.PARTIAL?de(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,U.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,c=e[o],l=this.fragLastKbps;l&&this.fragCurrent?s=this.fragCurrent.duration*c.maxBitrate/(1e3*l)+1:s=0}else s=0;const a=this.getBufferedFrag(t.currentTime+s);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const c=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,h=Math.max(a.end,c+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case P.KEY_LOADING:case P.FRAG_LOADING:case P.FRAG_LOADING_WAITING_RETRY:case P.PARSING:case P.PARSED:this.state=P.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;Ae(s,"playing",this.onMediaPlaying),Ae(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(Ie(s,"playing",this.onMediaPlaying),Ie(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let r=0;r<t.levels.length;r++){const a=t.levels[r].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,i=i||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&i&&!Nf(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==P.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=P.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,a=t.level,o=t.details,c=o.totalduration;if(!i){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${c}`);const l=t.levelInfo,h=this.fragCurrent;h&&(this.state===P.FRAG_LOADING||this.state===P.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let u=0;if(o.live||(s=l.details)!=null&&s.live){var d;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(l.details=o,this.levelLastLoaded=l,r||this.setStartPosition(o,u),this.hls.trigger(m.LEVEL_UPDATED,{details:o,level:a}),this.state===P.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=P.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,c=r>=a-t.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!c)){const h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!c&&s.readyState<4||r<o-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const u=q.bufferInfo(s,i,0);if(!((l=u.buffered)!=null&&l.length)){s.currentTime=i;return}if(u.start<=r){s.currentTime=i;return}const{nextStart:f}=q.bufferedInfo(u.buffered,r,0);f&&(s.currentTime=f)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=a[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}const c=o.details;if(!c){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const l=o.videoCodec,h=c.PTSKnown||!c.live,u=(t=s.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new xo(this.hls,U.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=i?i.index:-1,p=g!==-1,y=new Ji(s.level,s.sn,s.stats.chunkCount,r.byteLength,g,p),E=this.initPTS[s.cc];f.push(r,u,d,l,s,i,c.totalduration,h,y,E)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio!==0;if(Ps(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(m.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(m.AUDIO_TRACK_SWITCHED,t)}),s.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(m.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=Ps(t.url,this.hls);if(s){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,a=!1;for(const o in s){const c=s[o];if(c.id==="main"){if(r=o,i=c,o==="video"){const l=s[o];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===U.MAIN;if(r){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===P.PARSED&&(this.state=P.IDLE);return}const o=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),de(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const a=this.media;a&&(!this._hasEnoughToStart&&q.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(U.MAIN,t);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===Q.LEVEL&&(this.state=P.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=P.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ne.AUDIO||!this.altAudio){const s=(t===ne.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,U.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),a=q.getBuffered(e),o=a.length?a.start(0):0,c=o-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||c>0&&(c<l||this.loadingParts&&c<2*((r==null?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${c} to match buffer start`),s+=c,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:i}=this,r=s==null?void 0:s.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=P.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=r.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger(m.FRAG_LOADED,s),r.bitrateTest=!1}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,a=this.getCurrentContext(r);if(!a){this.resetWhenMissingContext(r);return}const{frag:o,part:c,level:l}=a,{video:h,text:u,id3:d,initSegment:f}=i,{details:g}=l,p=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=P.PARSING,f){const y=f.tracks;if(y){const v=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(l,y,v,r),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:t,tracks:y})}const E=f.initPTS,T=f.timescale,S=this.initPTS[o.cc];if(M(E)&&(!S||S.baseTime!==E||S.timescale!==T)){const v=f.trackId;this.initPTS[o.cc]={baseTime:E,timescale:T,trackId:v},s.trigger(m.INIT_PTS_FOUND,{frag:o,id:t,initPTS:E,timescale:T,trackId:v})}}if(h&&g){p&&h.type==="audiovideo"&&this.logMuxedErr(o);const y=g.fragments[o.sn-1-g.startSN],E=o.sn===g.startSN,T=!y||o.cc>y.cc;if(i.independent!==!1){const{startPTS:S,endPTS:v,startDTS:x,endDTS:D}=h;if(c)c.elementaryStreams[h.type]={startPTS:S,endPTS:v,startDTS:x,endDTS:D};else if(h.firstKeyFrame&&h.independent&&r.id===1&&!T&&(this.couldBacktrack=!0),h.dropped&&h.independent){const A=this.getMainFwdBufferInfo(),b=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,I=h.firstKeyFramePTS?h.firstKeyFramePTS:S;if(!E&&b<I-this.config.maxBufferHole&&!T){this.backtrack(o);return}else T&&(o.gap=!0);o.setElementaryStreamInfo(h.type,o.start,v,o.start,D,!0)}else E&&S-(g.appliedTimelineOffset||0)>xs&&(o.gap=!0);o.setElementaryStreamInfo(h.type,S,v,x,D),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,c,r,E||T)}else if(E||T)o.gap=!0;else{this.backtrack(o);return}}if(p){const{startPTS:y,endPTS:E,startDTS:T,endDTS:S}=p;c&&(c.elementaryStreams[ne.AUDIO]={startPTS:y,endPTS:E,startDTS:T,endDTS:S}),o.setElementaryStreamInfo(ne.AUDIO,y,E,T,S),this.bufferFragmentData(p,o,c,r)}if(g&&d!=null&&d.samples.length){const y={id:t,frag:o,details:g,samples:d.samples};s.trigger(m.FRAG_PARSING_METADATA,y)}if(g&&u){const y={id:t,frag:o,details:g,samples:u.samples};s.trigger(m.FRAG_PARSING_USERDATA,y)}}logMuxedErr(e){this.warn(`${de(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==P.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:a,audiovideo:o}=t;if(r){const l=e.audioCodec;let h=ms(r.codec,l);h==="mp4a"&&(h="mp4a.40.5");const u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const d=r.metadata;d&&"channelCount"in d&&(d.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),l&&l!==h&&this.log(`Swapping manifest audio codec "${l}" for "${h}"`),r.levelCodec=h,r.id=U.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${h||""}/${l||""}/${r.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=U.MAIN;const l=a.codec;if((l==null?void 0:l.length)===4)switch(l){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${a.codec!==l?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const c=Object.keys(t);if(c.length){if(this.hls.trigger(m.BUFFER_CODECS,t),!this.hls)return;c.forEach(l=>{const u=t[l].initSegment;u!=null&&u.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:u,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,U.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e==null?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=P.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(q.isBuffered(e,s)?t=this.getAppendedFrag(s):q.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const i=this.fragPlaying,r=t.level;(!i||t.sn!==i.sn||i.level!==r)&&(this.fragPlaying=t,this.hls.trigger(m.FRAG_CHANGED,{frag:t}),(!i||i.level!==r)&&this.hls.trigger(m.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return M(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(M(t)){const s=this.getLevelDetails(),i=this.currentFrag||(s?mt(null,s.fragments,t):null);if(i){const r=i.programDateTime;if(r!==null){const a=r+(t-i.start)*1e3;return new Date(a)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class $f extends Fe{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=R.KEY_LOAD_ERROR,s,i,r){return new ze({type:H.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){const a=t[i];if(e.cc<=a.cc&&(!de(e)||!de(a)||e.sn<a.sn)||!s&&i==r-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);const c=ys(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const i=Ft(this.config);if(i.length)return this.emeController.getKeySystemAccess(i)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const l=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,l))}const a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=mi(r);let c=this.keyIdToKeyInfo[o];if((s=c)!=null&&s.decryptdata.key)return r.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(i=c)!=null&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(h=>{const{keyInfo:u}=h;return r.key=u.decryptdata.key,{frag:e,keyInfo:u}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${r.keyId?" keyId: "+Te(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[o]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(c,e):this.loadKeyEME(c,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(c,e);default:return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&(i=t.initSegment)!=null&&i.data){const a=rc(t.initSegment.data);if(a.length){let o=a[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${Te(o)}`),nt.setKeyIdForUri(e.decryptdata.uri,o)):(o=nt.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Te(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!de(t))return Promise.resolve(s);const r=this.emeController.loadKey(s);return(e.keyLoadPromise=r.then(a=>(e.mediaKeySessionContext=a,s))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=s.loader,r=new i(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((a,o)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=s.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,p)=>{const{frag:y,keyInfo:E}=g,T=mi(E.decryptdata);if(!y.decryptdata||E!==this.keyIdToKeyInfo[T])return o(this.createKeyLoadError(y,R.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));E.decryptdata.key=y.decryptdata.key=new Uint8Array(d.data),y.keyLoader=null,E.loader=null,a({frag:y,keyInfo:E})},onError:(d,f,g,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),g,se({url:c.url,data:void 0},d)))},onTimeout:(d,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(d,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};r.load(c,h,u)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null);const a=mi(s.decryptdata)||i;delete this.keyIdToKeyInfo[a],r&&r.destroy()}}function mi(n){if(n.keyFormat!==Se.FAIRPLAY){const e=n.keyId;if(e)return Te(e)}return n.uri}function Qn(n){const{type:e}=n;switch(e){case Q.AUDIO_TRACK:return U.AUDIO;case Q.SUBTITLE_TRACK:return U.SUBTITLE;default:return U.MAIN}}function pi(n,e){let t=n.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Gf{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=s||i,a=new r(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Q.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:a,deliveryDirectives:o,levelInfo:c}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:Q.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Q.AUDIO_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Q.SUBTITLE_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const s=this.loaders[Q.LEVEL];if(s){const i=s.context;i&&!t.levels.some(r=>r===i.levelOrTrack)&&(s.abort(),delete this.loaders[Q.LEVEL])}}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const l=this.hls.logger,h=i.context;if(h&&h.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives)){h.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${h.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===Q.MANIFEST?r=s.manifestLoadPolicy.default:r=re({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),M((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===Q.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===Q.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===Q.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const h=l.partTarget,u=l.targetduration;if(h&&u){const d=Math.max(h*3,u*.8)*1e3;r=re({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},c={onSuccess:(l,h,u,d)=>{const f=this.getInternalLoader(u);this.resetInternalLoader(u.type);const g=l.data;h.parsing.start=performance.now(),We.isMediaPlaylist(g)||u.type!==Q.MANIFEST?this.handleTrackOrLevelPlaylist(l,h,u,d||null,f):this.handleMasterPlaylist(l,h,u,d)},onError:(l,h,u,d)=>{this.handleNetworkError(h,u,!1,l,d)},onTimeout:(l,h,u)=>{this.handleNetworkError(h,u,!0,void 0,l)}};i.load(e,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,a=e.data,o=pi(e,s),c=We.parseMasterPlaylist(a,o);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,c.playlistParsingError,i,t);return}const{contentSteering:l,levels:h,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:g}=c;this.variableList=g,h.forEach(T=>{const{unknownCodecs:S}=T;if(S){const{preferManagedMediaSource:v}=this.hls.config;let{audioCodec:x,videoCodec:D}=T;for(let A=S.length;A--;){const b=S[A];$t(b,"audio",v)?(T.audioCodec=x=x?`${x},${b}`:b,Ct.audio[x.substring(0,4)]=2,S.splice(A,1)):$t(b,"video",v)&&(T.videoCodec=D=D?`${D},${b}`:b,Ct.video[D.substring(0,4)]=2,S.splice(A,1))}}});const{AUDIO:p=[],SUBTITLES:y,"CLOSED-CAPTIONS":E}=We.parseMasterPlaylistMedia(a,o,c);p.length&&!p.some(S=>!S.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new le({}),bitrate:0,url:""})),r.trigger(m.MANIFEST_LOADED,{levels:h,audioTracks:p,subtitles:y,captions:E,contentSteering:l,url:o,stats:t,networkDetails:i,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,s,i,r){const a=this.hls,{id:o,level:c,type:l}=s,h=pi(e,s),u=M(c)?c:M(o)?o:0,d=Qn(s),f=We.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(l===Q.MANIFEST){const g={attrs:new le({}),bitrate:0,details:f,name:"",url:h};f.requestScheduled=t.loading.start+za(f,0),a.trigger(m.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:R.MANIFEST_PARSING_ERROR,fatal:t.type===Q.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let a=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===Q.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Q.AUDIO_TRACK||e.type===Q.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let c=R.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case Q.MANIFEST:c=s?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,l=!0;break;case Q.LEVEL:c=s?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,l=!1;break;case Q.AUDIO_TRACK:c=s?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Q.SUBTITLE_TRACK:c=s?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,l=!1;break}h&&this.resetInternalLoader(e.type);const u={type:H.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(i){const d=(t==null?void 0:t.url)||e.url;u.response=se({url:d,data:void 0},i)}this.hls.trigger(m.ERROR,u)}handlePlaylistLoaded(e,t,s,i,r,a){const o=this.hls,{type:c,level:l,levelOrTrack:h,id:u,groupId:d,deliveryDirectives:f}=i,g=pi(t,i),p=Qn(i);let y=typeof i.level=="number"&&p===U.MAIN?l:void 0;const E=e.playlistParsingError;if(E){if(this.hls.logger.warn(`${E} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:E,reason:E.message,response:t,context:i,level:y,parent:p,networkDetails:r,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const T=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:T,reason:T.message,response:t,context:i,level:y,parent:p,networkDetails:r,stats:s});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case Q.MANIFEST:case Q.LEVEL:if(y){if(!h)y=0;else if(h!==o.levels[y]){const T=o.levels.indexOf(h);T>-1&&(y=T)}}o.trigger(m.LEVEL_LOADED,{details:e,levelInfo:h||o.levels[0],level:y||0,id:u||0,stats:s,networkDetails:r,deliveryDirectives:f,withoutMultiVariant:c===Q.MANIFEST});break;case Q.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:f});break;case Q.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:f});break}}}class we{static get version(){return Vt}static isMSESupported(){return zo()}static isSupported(){return Mf()}static getMediaSource(){return at()}static get Events(){return m}static get MetadataSchema(){return De}static get ErrorTypes(){return H}static get ErrorDetails(){return R}static get DefaultConfig(){return we.defaultConfig?we.defaultConfig:_f}static set DefaultConfig(e){we.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new ir,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=Yl(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=Lf(we.DefaultConfig,e,t);this.userConfig=e,s.progressive&&Rf(s,t);const{abrController:i,bufferController:r,capLevelController:a,errorController:o,fpsController:c}=s,l=new o(this),h=this.abrController=new i(this),u=new Gc(this),d=s.interstitialsController,f=d?this.interstitialsController=new d(this,we):null,g=this.bufferController=new r(this,u),p=this.capLevelController=new a(this),y=new c(this),E=new Gf(this),T=s.contentSteeringController,S=T?new T(this):null,v=this.levelController=new Ff(this,S),x=new wf(this),D=new $f(this.config,this.logger),A=this.streamController=new Uf(this,u,D),b=this.gapController=new Pf(this,u);p.setStreamController(A),y.setStreamController(A);const I=[E,v,A];f&&I.splice(1,0,f),S&&I.splice(1,0,S),this.networkControllers=I;const _=[h,g,b,p,y,x,u];this.audioTrackController=this.createController(s.audioTrackController,I);const C=s.audioStreamController;C&&I.push(this.audioStreamController=new C(this,u,D)),this.subtitleTrackController=this.createController(s.subtitleTrackController,I);const k=s.subtitleStreamController;k&&I.push(this.subtititleStreamController=new k(this,u,D)),this.createController(s.timelineController,_),D.emeController=this.emeController=this.createController(s.emeController,_),this.cmcdController=this.createController(s.cmcdController,_),this.latencyController=this.createController(Of,_),this.coreComponents=_,I.push(l);const B=l.onErrorOut;typeof B=="function"&&this.on(m.ERROR,B,l),this.on(m.MANIFEST_LOADED,E.onManifestLoaded,E)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const i=e===m.ERROR;this.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(m.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const r=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(m.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(m.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(m.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,i=this._url=Yi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),t&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(m.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[U.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[U.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[U.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=Cd()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Ic(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){const a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const s=Fa(t);return wa(e,s,navigator.mediaCapabilities)}}we.defaultConfig=void 0;function Kf(){const n=window.location.pathname,e=n.lastIndexOf("/");return n.substring(0,e+1)}function Vf(){const n=window.location.pathname,e=n.lastIndexOf("/");return n.substring(e+1)||null}function Qo(n){const e=n.split("/");return e[e.length-1]}function Zo(n){return new Date(n.value.createdAt).toISOString().split("T")[0]}function Hf(n){const e=new Map;for(const t of n){const s=Zo(t);e.has(s)||e.set(s,[]),e.get(s).push(t)}return e}function Zn(n){const e=Kf();if(n){const t=Qo(n);history.pushState({channel:n},"",`${e}${t}`)}else history.pushState(null,"",e)}function Wf(n){const e=n.match(/(?:(\d+)h)?(?:(\d+)m)?(\d+)s?/);if(!e)return 0;const t=parseInt(e[1]||"0",10),s=parseInt(e[2]||"0",10),i=parseInt(e[3]||"0",10);return t*3600+s*60+i}function Jo(){const e=new URLSearchParams(window.location.search).get("t");return e?Wf(e):0}const Jn="https://vod-beta.stream.place/xrpc";function Yf(n,e,t,s){const[i,r]=rt(!1),[a,o]=rt(!0),[c,l]=rt(null),[h,u]=rt(null),d=Mt(0),f=Mt(null),g=Mt(!1);return vi(()=>{if(!e||n.length===0||!t.current||!s.current)return;const p=t.current,y=s.current,E=e;async function T(){if(g.current)return;g.current=!0;const S=++d.current,v=()=>S!==d.current,x=n.find(C=>C.uri===E);if(!x){g.current=!1;return}const D=x.value.title||"Unknown Video",A=x.uri,b=encodeURIComponent(A);if(console.log("[Player] Switching to:",D),l(D),u(A),o(!1),r(!0),f.current&&(f.current.destroy(),f.current=null),p.pause(),p.removeAttribute("src"),p.load(),y.pause(),y.removeAttribute("src"),await new Promise(C=>setTimeout(C,250)),v()){g.current=!1;return}const I=Jo(),_=`${Jn}/place.stream.playback.getVideoPlaylist?uri=${b}`;if(!we.isSupported()){const C=`${Jn}/place.stream.playback.getVideoPlaylist?uri=${b}`;p.src=C,p.currentTime=I;try{await p.play(),r(!1)}catch(k){console.warn("[Player] Playback error:",k),r(!1)}g.current=!1;return}f.current=new we({startPosition:I,maxBufferLength:30,maxMaxBufferLength:60}),f.current.loadSource(_),f.current.attachMedia(p),f.current.on(we.Events.MANIFEST_PARSED,()=>{v()||(console.log("[Player] Video manifest parsed"),p.muted=!0,p.play().catch(C=>console.warn("[Player] Play failed:",C)))}),f.current.on(we.Events.ERROR,(C,k)=>{var B,K;v()||(console.warn("[Player] HLS error:",k.type,k.details,k.fatal),k.fatal&&(k.type===we.ErrorTypes.MEDIA_ERROR?(B=f.current)==null||B.recoverMediaError():((K=f.current)==null||K.destroy(),f.current=null,g.current=!1,T())))}),g.current=!1}return T(),()=>{const S=t.current;S==null||S.pause()}},[e,n,t,s]),{isLoading:i,showStandby:a,currentTitle:c,currentUri:h}}function qf(){const[n,e]=rt([]),[t,s]=rt(null),[i,r]=rt(null),[a,o]=rt(!1),c=Mt(null),l=Mt(null),h=Yf(n,t,c,l),u=()=>{o(!a)};vi(()=>{async function g(){try{const p=await Tl();console.log(`Loaded ${p.length} VODs`),e(p);const y=Hf(p),E=Array.from(y.keys()).sort();E.length>0&&r(E[0]);const T=Vf();if(T){const S=p.find(v=>Qo(v.uri)===T);S&&(r(Zo(S)),s(S.uri),Zn(S.uri))}}catch(p){console.error("Failed to load VODs:",p)}}g()},[]);const d=g=>{r(g)},f=g=>{s(g),Zn(g)};return vi(()=>{const g=()=>{const p=c.current;if(!p)return;const y=Jo();y>0&&(p.currentTime=y)};return window.addEventListener("popstate",g),()=>window.removeEventListener("popstate",g)},[c]),Z("div",{class:"flex flex-col h-screen overflow-hidden",style:"background-color: #1a1a1a; color: #7dd3fc; line-height: 1.6; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif",children:[Z(Nl,{sidebarCollapsed:a,onToggleSidebar:u}),Z("div",{class:"flex flex-row flex-1 overflow-hidden",children:[Z(Rl,{vods:n,currentChannel:t,selectedDay:i,onSelectDay:d,onSelectVideo:f,collapsed:a}),Z(bl,{currentTitle:h.currentTitle,currentUri:h.currentUri,isLoading:h.isLoading,showStandby:h.showStandby,videoRef:c,audioRef:l})]})]})}const ea=document.getElementById("app-root");ea&&ll(Z(qf,{}),ea);</script>
140140+`),l=[],c=e?IS(e.baseTime,e.timescale):0;let d="00:00.000",h=0,f=0,g,p=!0;o.oncue=function(m){const v=t[r];let y=t.ccOffset;const S=(h-c)/9e4;if(v!=null&&v.new&&(f!==void 0?y=t.ccOffset=v.start:ET(t,r,S)),S){if(!e){g=new Error("Missing initPTS for VTT MPEGTS");return}y=S-t.presentationOffset}const _=m.endTime-m.startTime,T=He((m.startTime+y-f)*9e4,s*9e4)/9e4;m.startTime=Math.max(T,0),m.endTime=Math.max(T+_,0);const x=m.text.trim();m.text=decodeURIComponent(encodeURIComponent(x)),m.id||(m.id=jo(m.startTime,m.endTime,x)),m.endTime>0&&l.push(m)},o.onparsingerror=function(m){g=m},o.onflush=function(){if(g){a(g);return}n(l)},u.forEach(m=>{if(p)if(ga(m,"X-TIMESTAMP-MAP=")){p=!1,m.slice(16).split(",").forEach(v=>{ga(v,"LOCAL:")?d=v.slice(6):ga(v,"MPEGTS:")&&(h=parseInt(v.slice(7)))});try{f=vT(d)/1e3}catch(v){g=v}return}else m===""&&(p=!1);o.parse(m+`
141141+`)}),o.flush()}const ma="stpp.ttml.im1t",nm=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,am=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,_T={left:"start",center:"center",right:"end",start:"start",end:"end"};function Yd(i,e,t,r){const s=Z(new Uint8Array(i),["mdat"]);if(s.length===0){r(new Error("Could not parse IMSC1 mdat"));return}const n=s.map(o=>Ye(o)),a=AS(e.baseTime,1,e.timescale);try{n.forEach(o=>t(TT(o,a)))}catch(o){r(o)}}function TT(i,e){const s=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((d,h)=>(d[h]=s.getAttribute(`ttp:${h}`)||n[h],d),{}),o=s.getAttribute("xml:space")!=="preserve",u=Xd(pa(s,"styling","style")),l=Xd(pa(s,"layout","region")),c=pa(s,"body","[begin]");return[].map.call(c,d=>{const h=om(d,o);if(!h||!d.hasAttribute("begin"))return null;const f=va(d.getAttribute("begin"),a),g=va(d.getAttribute("dur"),a);let p=va(d.getAttribute("end"),a);if(f===null)throw Qd(d);if(p===null){if(g===null)throw Qd(d);p=f+g}const m=new $o(f-e,p-e,h);m.id=jo(m.startTime,m.endTime,m.text);const v=l[d.getAttribute("region")],y=u[d.getAttribute("style")],S=bT(v,y,u),{textAlign:_}=S;if(_){const T=_T[_];T&&(m.lineAlign=T),m.align=_}return ae(m,S),m}).filter(d=>d!==null)}function pa(i,e,t){const r=i.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(t)):[]}function Xd(i){return i.reduce((e,t)=>{const r=t.getAttribute("xml:id");return r&&(e[r]=t),e},{})}function om(i,e){return[].slice.call(i.childNodes).reduce((t,r,s)=>{var n;return r.nodeName==="br"&&s?t+`
142142+`:(n=r.childNodes)!=null&&n.length?om(r,e):e?t+r.textContent.trim().replace(/\s+/g," "):t+r.textContent},"")}function bT(i,e,t){const r="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=i!=null&&i.hasAttribute("style")?i.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(s=t[a]),n.reduce((o,u)=>{const l=ya(e,r,u)||ya(i,r,u)||ya(s,r,u);return l&&(o[u]=l),o},{})}function ya(i,e,t){return i&&i.hasAttributeNS(e,t)?i.getAttributeNS(e,t):null}function Qd(i){return new Error(`Could not parse ttml timestamp ${i}`)}function va(i,e){if(!i)return null;let t=rm(i);return t===null&&(nm.test(i)?t=xT(i,e):am.test(i)&&(t=AT(i,e))),t}function xT(i,e){const t=nm.exec(i),r=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+r/e.frameRate}function AT(i,e){const t=am.exec(i),r=Number(t[1]);switch(t[2]){case"h":return r*3600;case"m":return r*60;case"ms":return r*1e3;case"f":return r/e.frameRate;case"t":return r/e.tickRate}return r}class xs{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,r){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class IT{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=Jd(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new xs(this,"textTrack1"),t=new xs(this,"textTrack2"),r=new xs(this,"textTrack3"),s=new xs(this,"textTrack4");this.cea608Parser1=new zd(1,e,t),this.cea608Parser2=new zd(3,r,s)}addCues(e,t,r,s,n){let a=!1;for(let o=n.length;o--;){const u=n[o],l=DT(u[0],u[1],t,r);if(l>=0&&(u[0]=Math.min(u[0],t),u[1]=Math.max(u[1],r),a=!0,l/(r-t)>.5))return}if(a||n.push([t,r]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,r,s)}else{const o=this.Cues.newCue(null,t,r,s);this.hls.trigger(E.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:r,initPTS:s,timescale:n,trackId:a}){const{unparsedVttFrags:o}=this;r===V.MAIN&&(this.initPTS[t.cc]={baseTime:s,timescale:n,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(u=>{this.initPTS[u.frag.cc]?this.onFragLoaded(E.FRAG_LOADED,u):this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:u.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:r}=this;if(r)for(let s=0;s<r.textTracks.length;s++){const n=r.textTracks[s];if(Zd(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:r,media:s}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)r[e]=o,Hr(r[e]),Qg(r[e],s);else{const u=this.createTextTrack("captions",n,a);u&&(u[e]=!0,r[e]=u)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const r=t.label,s={_id:e,label:r,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,t,r){const s=this.media;if(s)return s.addTextTrack(e,t,r)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const r=!!t.transferMedia;if(this.media=null,r)return;const{captionsTracks:s}=this;Object.keys(s).forEach(n=>{Hr(s[n]),delete s[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Jd(),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 r=0;r<t.length;r++)Hr(t[r])}onSubtitleTracksUpdated(e,t){const r=t.subtitleTracks||[],s=r.some(n=>n.textCodec===ma);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Bg(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const a=this.media,o=a?Fs(a.textTracks):null;if(this.tracks.forEach((u,l)=>{let c;if(o){let d=null;for(let h=0;h<o.length;h++)if(o[h]&&Zd(o[h],u)){d=o[h],o[h]=null;break}d&&(c=d)}if(c)Hr(c);else{const d=lm(u);c=this.createTextTrack(d,u.name,u.lang),c&&(c.mode="disabled")}c&&this.textTracks.push(c)}),o!=null&&o.length){const u=o.filter(l=>l!==null).map(l=>l.label);u.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${u.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(r=>{const s=/(?:CC|SERVICE)([1-4])/.exec(r.instreamId);if(!s)return;const n=`textTrack${s[1]}`,a=this.captionsProperties[n];a&&(a.label=r.name,r.lang&&(a.languageCode=r.lang),a.media=r)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===V.MAIN){var r,s;const{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:u,sn:l}=t.frag,c=(r=(s=t.part)==null?void 0:s.index)!=null?r:-1;n&&a&&(l!==o+1||l===o&&c!==this.lastPartIndex+1||u!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=u,this.lastSn=l,this.lastPartIndex=c}}onFragLoaded(e,t){const{frag:r,payload:s}=t;if(r.type===V.SUBTITLE)if(s.byteLength){const n=r.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){const o=this.tracks[r.level],u=this.vttCCs;u[r.cc]||(u[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),o&&o.textCodec===ma?this._parseIMSC1(r,s):this._parseVTTs(t)}}else this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const r=this.hls;Yd(t,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),r.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{r.logger.log(`Failed to parse IMSC1: ${s}`),r.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:s})})}_parseVTTs(e){var t;const{frag:r,payload:s}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[r.cc]&&o===-1){a.push(e);return}const u=this.hls,l=(t=r.initSegment)!=null&&t.data?Je(r.initSegment.data,new Uint8Array(s)).buffer:s;ST(l,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,c=>{this._appendCues(c,r.level),u.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})},c=>{const d=c.message==="Missing initPTS for VTT MPEGTS";d?a.push(e):this._fallbackToIMSC1(r,s),u.logger.log(`Failed to parse VTT cue: ${c}`),!(d&&o>r.cc)&&u.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:c})})}_fallbackToIMSC1(e,t){const r=this.tracks[e.level];r.textCodec||Yd(t,this.initPTS[e.cc],()=>{r.textCodec=ma,this._parseIMSC1(e,t)},()=>{r.textCodec="wvtt"})}_appendCues(e,t){const r=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[t];if(!s||s.mode==="disabled")return;e.forEach(n=>Zg(s,n))}else{const s=this.tracks[t];if(!s)return;const n=s.default?"default":"subtitles"+t;r.trigger(E.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){const{frag:r}=t;r.type===V.SUBTITLE&&this.onFragLoaded(E.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:r,samples:s}=t;if(!(r.type===V.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let n=0;n<s.length;n++){const a=s[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(s[n].pts,o[0]),this.cea608Parser2.addData(s[n].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:r,endOffsetSubtitles:s,type:n}){const{media:a}=this;if(!(!a||a.currentTime<r)){if(!n||n==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(u=>Ha(o[u],t,r))}if(this.config.renderTextTracksNatively&&t===0&&s!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(u=>Ha(o[u],t,s))}}}extractCea608Data(e){const t=[[],[]],r=e[0]&31;let s=2;for(let n=0;n<r;n++){const a=e[s++],o=127&e[s++],u=127&e[s++];if(o===0&&u===0)continue;if((4&a)!==0){const c=3&a;(c===0||c===1)&&(t[c].push(o),t[c].push(u))}}return t}}function lm(i){return i.characteristics&&/transcribes-spoken-dialog/gi.test(i.characteristics)&&/describes-music-and-sound/gi.test(i.characteristics)?"captions":"subtitles"}function Zd(i,e){return!!i&&i.kind===lm(e)&&Ga(e,i)}function DT(i,e,t,r){return Math.min(e,r)-Math.max(i,t)}function Jd(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const LT=/\s/,RT={newCue(i,e,t,r){const s=[];let n,a,o,u,l;const c=self.VTTCue||self.TextTrackCue;for(let h=0;h<r.rows.length;h++)if(n=r.rows[h],o=!0,u=0,l="",!n.isEmpty()){var d;for(let p=0;p<n.chars.length;p++)LT.test(n.chars[p].uchar)&&o?u++:(l+=n.chars[p].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),u>=16?u--:u++;const f=sm(l.trim()),g=jo(e,t,f);i!=null&&(d=i.cues)!=null&&d.getCueById(g)||(a=new c(e,t,f),a.id=g,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(u*8/32)*10),s.push(a))}return i&&s.length&&(s.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),s.forEach(h=>Zg(i,h))),s}};function CT(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const wT=/(\d+)-(\d+)\/(\d+)/;class eh{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||MT,this.controller=new self.AbortController,this.stats=new Eo}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,r){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const n=PT(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:u,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=u&&$(u)?u:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},t.timeout),(Gi(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(d=>{var h;this.response=this.loader=d;const f=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},l-(f-s.loading.start)),!d.ok){const{status:p,statusText:m}=d;throw new FT(m||"fetch, bad network response",p,d)}s.loading.first=f,s.total=OT(d.headers)||s.total;const g=(h=this.callbacks)==null?void 0:h.onProgress;return g&&$(t.highWaterMark)?this.loadProgressively(d,s,e,t.highWaterMark,g):a?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{var h,f;const g=this.response;if(!g)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=d[o];p&&(s.loaded=s.total=p);const m={url:g.url,data:d,code:g.status},v=(h=this.callbacks)==null?void 0:h.onProgress;v&&!$(t.highWaterMark)&&v(s,e,d,g),(f=this.callbacks)==null||f.onSuccess(m,s,e,g)}).catch(d=>{var h;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const f=d&&d.code||0,g=d?d.message:null;(h=this.callbacks)==null||h.onError({code:f,text:g},e,d?d.details:null,s)})}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,r,s=0,n){const a=new vg,o=e.body.getReader(),u=()=>o.read().then(l=>{if(l.done)return a.dataLength&&n(t,r,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const c=l.value,d=c.length;return t.loaded+=d,d<s||a.dataLength?(a.push(c),a.dataLength>=s&&n(t,r,a.flush().buffer,e)):n(t,r,c.buffer,e),u()}).catch(()=>Promise.reject());return u()}}function PT(i,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ae({},i.headers))};return i.rangeEnd&&t.headers.set("Range","bytes="+i.rangeStart+"-"+String(i.rangeEnd-1)),t}function kT(i){const e=wT.exec(i);if(e)return parseInt(e[2])-parseInt(e[1])+1}function OT(i){const e=i.get("Content-Range");if(e){const r=kT(e);if($(r))return r}const t=i.get("Content-Length");if(t)return parseInt(t)}function MT(i,e){return new self.Request(i.url,e)}class FT extends Error{constructor(e,t,r){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=r}}const NT=/^age:\s*[\d.]+\s*$/im;class um{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 Eo,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,r){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=r,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const r=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==r||this.stats.aborted))return n(r,t.url)}).catch(a=>{if(!(this.loader!==r||this.stats.aborted))return r.open("GET",t.url,!0),n(r,t.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:r.status,text:a.message},t,r,s)}):this.openAndSendXhr(r,t,e)}openAndSendXhr(e,t,r){e.readyState||e.open("GET",t.url,!0);const s=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=r.loadPolicy;if(s)for(const o in s)e.setRequestHeader(o,s[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),r.timeout=n&&$(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:r}=this;if(!e||!t)return;const s=t.readyState,n=this.config;if(!r.aborted&&s>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.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-(r.loading.first-r.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,c=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const g=c??t.response;if(g!=null){var a,o;r.loading.end=Math.max(self.performance.now(),r.loading.first);const p=t.responseType==="arraybuffer"?g.byteLength:g.length;r.loaded=r.total=p,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const m=(a=this.callbacks)==null?void 0:a.onProgress;m&&m(r,e,g,t);const v={url:t.responseURL,data:g,code:l};(o=this.callbacks)==null||o.onSuccess(v,r,e,t);return}}const d=n.loadPolicy.errorRetry,h=r.retry,f={url:e.url,data:void 0,code:l};if(en(d,h,!1,f))this.retry(d);else{var u;ne.error(`${l} while loading ${e.url}`),(u=this.callbacks)==null||u.onError({code:l,text:t.statusText},e,t,r)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(en(e,t,!0))this.retry(e);else{var r;ne.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:r}=this;this.retryDelay=bo(e,r.retry),r.retry++,ne.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${r.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&&NT.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const BT={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},UT=se(se({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:um,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Qv,bufferController:jS,capLevelController:No,errorController:rE,fpsController:G_,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:og,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:BT},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},$T()),{},{subtitleStreamController:eT,subtitleTrackController:q_,timelineController:IT,audioStreamController:NS,audioTrackController:BS,emeController:Yr,cmcdController:B_,contentSteeringController:$_,interstitialsController:J_});function $T(){return{cueHandler:RT,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 jT(i,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=za(i),s=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,u=e[o]===void 0,l=[];n.forEach(c=>{const d=`${a}Loading${c}`,h=e[d];if(h!==void 0&&u){l.push(d);const f=r[o].default;switch(e[o]={default:f},c){case"TimeOut":f.maxLoadTimeMs=h,f.maxTimeToFirstByteMs=h;break;case"MaxRetry":f.errorRetry.maxNumRetry=h,f.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":f.errorRetry.retryDelayMs=h,f.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=h,f.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${ue(e[o])}`)}),se(se({},r),e)}function za(i){return i&&typeof i=="object"?Array.isArray(i)?i.map(za):Object.keys(i).reduce((e,t)=>(e[t]=za(i[t]),e),{}):i}function GT(i,e){const t=i.loader;t!==eh&&t!==um?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),i.progressive=!1):CT()&&(i.loader=eh,i.progressive=!0,i.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Ns=2,VT=.1,KT=.05,qT=100;class HT extends rg{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var r;(r=this.media)!=null&&r.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var r;this.ended=((r=this.media)==null?void 0:r.currentTime)||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(qT),this.mediaSource=t.mediaSource;const r=this.media=t.media;Ne(r,"playing",this.onMediaPlaying),Ne(r,"waiting",this.onMediaWaiting),Ne(r,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:r}=this;r&&($e(r,"playing",this.onMediaPlaying),$e(r,"waiting",this.onMediaWaiting),$e(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var r,s;const n=(r=this.hls)==null?void 0:r.config;if(!n)return;const a=this.media;if(!a)return;const{seeking:o}=a,u=this.seeking&&!o,l=!this.seeking&&o,c=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!c&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||u){u&&this.stallResolved(e);return}if(c){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1}));return}if(!Y.getBuffered(a).length){this.nudgeRetry=0;return}const d=Y.bufferInfo(a,e,0),h=d.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const x=th(this.hls.inFlightFragments,e),b=d.len>Ns,I=!h||x||h-e>Ns&&!f.getPartialFragment(e);if(b||I)return;this.moved=!1}const g=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(d.len>0)&&!h)return;const b=Math.max(h,d.start||0)-e,A=!!(g!=null&&g.live)?g.targetduration*2:Ns,D=As(e,f);if(b>0&&(b<=A||D)){a.paused||this._trySkipBufferHole(D);return}}const p=n.detectStallWithCurrentTimeMs,m=self.performance.now(),v=this.waiting;let y=this.stalled;if(y===null)if(v>0&&m-v<p)y=this.stalled=v;else{this.stalled=m;return}const S=m-y;if(!o&&(S>=p||v)&&this.hls){var _;if(((_=this.mediaSource)==null?void 0:_.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(e-((g==null?void 0:g.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return}const T=Y.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(T,S,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const r=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(E.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var r;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(r=this.buffered.audio)!=null&&r.length&&s&&s.length>1&&e>s.end(0)){const n=Y.bufferedInfo(Y.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){const a=Y.timeRangesToArray(s),o=Y.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const u=Y.bufferedInfo(a,e,0).bufferedIndex,l=a[o].end,c=a[o+1].start;if((u===-1||u>o)&&c-l<1&&e-l<2){const d=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${c} buffered index: ${u}`);this.warn(d.message),this.media.currentTime+=1e-6;let h=As(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);const f=Y.bufferInfo(this.media,e,0);this.hls.trigger(E.ERROR,{type:q.MEDIA_ERROR,details:C.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,r){var s,n;const{fragmentTracker:a,media:o}=this,u=(s=this.hls)==null?void 0:s.config;if(!o||!a||!u)return;const l=(n=this.hls)==null?void 0:n.latestLevelDetails,c=As(r,a);if((c||l!=null&&l.live&&r<l.fragmentStart)&&(this._trySkipBufferHole(c)||!this.media))return;const d=e.buffered,h=this.adjacentTraversal(e,r);(d&&d.length>1&&e.len>u.maxBufferHole||e.nextStart&&(e.nextStart-r<u.maxBufferHole||h))&&(t>u.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const r=this.fragmentTracker,s=e.nextStart;if(r&&s){const n=r.getFragAtPos(t,V.MAIN),a=r.getFragAtPos(s,V.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){const{hls:t,media:r,stallReported:s,stalled:n}=this;if(!s&&n!==null&&r&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${ue(e)})`);this.warn(a.message),t.trigger(E.ERROR,{type:q.MEDIA_ERROR,details:C.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:r,media:s}=this,n=(t=this.hls)==null?void 0:t.config;if(!s||!r||!n)return 0;const a=s.currentTime,o=Y.bufferInfo(s,a,0),u=a<o.start?o.start:o.nextStart;if(u&&this.hls){const c=o.len<=n.maxBufferHole,d=o.len>0&&o.len<1&&s.readyState<3,h=u-a;if(h>0&&(c||d)){if(h>n.maxBufferHole){let g=!1;if(a===0){const p=r.getAppendedFrag(0,V.MAIN);p&&u<p.end&&(g=!0)}if(!g&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||th(this.hls.inFlightFragments,u))return 0;let m=!1,v=e.end;for(;v<u;){const y=As(v,r);if(y)v+=y.duration;else{m=!0;break}}if(m)return 0}}const f=Math.max(u+KT,a+VT);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,s.currentTime=f,!(e!=null&&e.gap)){const g=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),p={type:q.MEDIA_ERROR,details:C.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:g,reason:g.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(E.ERROR,p)}return f}}return 0}_tryNudgeBuffer(e){const{hls:t,media:r,nudgeRetry:s}=this,n=t==null?void 0:t.config;if(!r||!n)return 0;const a=r.currentTime;if(this.nudgeRetry++,s<n.nudgeMaxRetry){const o=a+(s+1)*n.nudgeOffset,u=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(u.message),r.currentTime=o,t.trigger(E.ERROR,{type:q.MEDIA_ERROR,details:C.BUFFER_NUDGE_ON_STALL,error:u,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(E.ERROR,{type:q.MEDIA_ERROR,details:C.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function th(i,e){const t=rh(i.main);if(t&&t.start<=e)return t;const r=rh(i.audio);return r&&r.start<=e?r:null}function rh(i){if(!i)return null;switch(i.state){case k.IDLE:case k.STOPPED:case k.ENDED:case k.ERROR:return null}return i.frag}function As(i,e){return e.getAppendedFrag(i,V.MAIN)||e.getPartialFragment(i)}const WT=.25;function Ya(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Ea(i,e,t,r,s){let n=new i(e,t,"");try{n.value=r,s&&(n.type=s)}catch{n=new i(e,t,ue(s?se({type:s},r):r))}return n}const Is=(()=>{const i=Ya();try{i&&new i(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class zT{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(E.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var r;this.media=t.media,((r=t.overrides)==null?void 0:r.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Hr(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const r=e[t];if(r.kind==="metadata"&&r.label==="id3")return Qg(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:r,enableID3MetadataCues:s}=this.hls.config;if(!r&&!s)return;const{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=Ya();if(a)for(let o=0;o<n.length;o++){const u=n[o].type;if(u===We.emsg&&!r||!s)continue;const l=Ag(n[o].data),c=n[o].pts;let d=c+n[o].duration;d>Is&&(d=Is),d-c<=0&&(d=c+WT);for(let f=0;f<l.length;f++){const g=l[f];if(!Ig(g)){this.updateId3CueEnds(c,u);const p=Ea(a,c,d,g,u);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var r;const s=(r=this.id3Track)==null?void 0:r.cues;if(s)for(let n=s.length;n--;){const a=s[n];a.type===t&&a.startTime<e&&a.endTime===Is&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:r,type:s}){const{id3Track:n,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:u}}=a;if(n&&(o||u)){let l;s==="audio"?l=c=>c.type===We.audioId3&&u:s==="video"?l=c=>c.type===We.emsg&&o:l=c=>c.type===We.audioId3&&u||c.type===We.emsg&&o,Ha(n,t,r,l)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:r,timelineOffset:s,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;const o=Ya();if(r&&s&&!a){const{fragmentStart:p,fragmentEnd:m}=e;let v=this.assetCue;v?(v.startTime=p,v.endTime=m):o&&(v=this.assetCue=Ea(o,p,m,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:u}=this,{dateRanges:l}=e,c=Object.keys(l);let d=this.dateRangeCuesAppended;if(u&&t){var h;if((h=u.cues)!=null&&h.length){const p=Object.keys(d).filter(m=>!c.includes(m));for(let m=p.length;m--;){var f;const v=p[m],y=(f=d[v])==null?void 0:f.cues;delete d[v],y&&Object.keys(y).forEach(S=>{const _=y[S];if(_){_.removeEventListener("enter",this.onEventCueEnter);try{u.removeCue(_)}catch{}}})}}else d=this.dateRangeCuesAppended={}}const g=e.fragments[e.fragments.length-1];if(!(c.length===0||!$(g==null?void 0:g.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<c.length;p++){const m=c[p],v=l[m],y=v.startTime,S=d[m],_=(S==null?void 0:S.cues)||{};let T=(S==null?void 0:S.durationKnown)||!1,x=Is;const{duration:b,endDate:I}=v;if(I&&b!==null)x=y+b,T=!0;else if(v.endOnNext&&!T){const D=c.reduce((L,P)=>{if(P!==v.id){const O=l[P];if(O.class===v.class&&O.startDate>v.startDate&&(!L||v.startDate<L.startDate))return O}return L},null);D&&(x=D.startTime,T=!0)}const A=Object.keys(v.attr);for(let D=0;D<A.length;D++){const L=A[D];if(!mE(L))continue;const P=_[L];if(P)T&&!(S!=null&&S.durationKnown)?P.endTime=x:Math.abs(P.startTime-y)>.01&&(P.startTime=y,P.endTime=x);else if(o){let O=v.attr[L];pE(L)&&(O=Ff(O));const j=Ea(o,y,x,{key:L,data:O},We.dateRange);j&&(j.id=m,this.id3Track.addCue(j),_[L]=j,a&&(L==="X-ASSET-LIST"||L==="X-ASSET-URL")&&j.addEventListener("enter",this.onEventCueEnter))}}d[m]={cues:_,dateRange:v,durationKnown:T}}}}}class YT{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,r=this.levelDetails;if(!t||!r)return;this.currentTime=t.currentTime;const s=this.computeLatency();if(s===null)return;this._latency=s;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!r.live)return;const o=this.targetLatency;if(o===null)return;const u=s-o,l=Math.min(this.maxLatency,o+r.targetduration);if(u<l&&u>.05&&this.forwardBufferLength>1){const d=Math.min(2,Math.max(1,a)),h=Math.round(2/(1+Math.exp(-.75*u-this.edgeStalled))*20)/20,f=Math.min(d,Math.max(1,h));this.changeMediaPlaybackRate(t,f)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:r,targetduration:s}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,u=this.hls.userConfig;let l=o&&r||t;(this._targetLatencyUpdated||u.liveSyncDuration||u.liveSyncDurationCount||l===0)&&(l=n!==void 0?n:a*s);const c=s;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,c)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const r=this.levelDetails;if(r===null)return null;const s=r.edge,n=e-t-this.edgeStalled,a=s-r.totalduration,o=s-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,n),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var r;t.details===C.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(r=this.levelDetails)!=null&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var r,s;e.playbackRate!==t&&((r=this.hls)==null||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class XT extends Fo{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const r=this.hls.config.preferManagedMediaSource,s=[],n={},a={};let o=!1,u=!1,l=!1;t.levels.forEach(c=>{const d=c.attrs;let{audioCodec:h,videoCodec:f}=c;h&&(c.audioCodec=h=Xs(h,r)||void 0),f&&(f=c.videoCodec=Pv(f));const{width:g,height:p,unknownCodecs:m}=c,v=(m==null?void 0:m.length)||0;if(o||(o=!!(g&&p)),u||(u=!!f),l||(l=!!h),v||h&&!this.isAudioSupported(h)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}const{CODECS:y,"FRAME-RATE":S,"HDCP-LEVEL":_,"PATHWAY-ID":T,RESOLUTION:x,"VIDEO-RANGE":b}=d,A=`${`${T||"."}-`}${c.bitrate}-${x}-${S}-${y}-${b}-${_}`;if(n[A])if(n[A].uri!==c.url&&!c.attrs["PATHWAY-ID"]){const D=a[A]+=1;c.attrs["PATHWAY-ID"]=new Array(D+1).join(".");const L=this.createLevel(c);n[A]=L,s.push(L)}else n[A].addGroupId("audio",d.AUDIO),n[A].addGroupId("text",d.SUBTITLES);else{const D=this.createLevel(c);n[A]=D,a[A]=1,s.push(D)}}),this.filterAndSortMediaOptions(s,t,o,u,l)}createLevel(e){const t=new Ui(e),r=e.supplemental;if(r!=null&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){const s=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(s.message),t.supportedResult=zf(s,[])}return t}isAudioSupported(e){return Ni(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Ni(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,r,s,n){var a;let o=[],u=[],l=e;const c=((a=t.stats)==null?void 0:a.parsing)||{};if((r||s)&&n&&(l=l.filter(({videoCodec:y,videoRange:S,width:_,height:T})=>(!!y||!!(_&&T))&&Gv(S))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let y="no level with compatible codecs found in manifest",S=y;t.levels.length&&(S=`one or more CODECS in variant not supported: ${ue(t.levels.map(T=>T.attrs.CODECS).filter((T,x,b)=>b.indexOf(T)===x))}`,this.warn(S),y+=` (${S})`);const _=new Error(y);this.hls.trigger(E.ERROR,{type:q.MEDIA_ERROR,details:C.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:_,reason:S})}}),c.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(y=>!y.audioCodec||this.isAudioSupported(y.audioCodec)),ih(o)),t.subtitles&&(u=t.subtitles,ih(u));const d=l.slice(0);l.sort((y,S)=>{if(y.attrs["HDCP-LEVEL"]!==S.attrs["HDCP-LEVEL"])return(y.attrs["HDCP-LEVEL"]||"")>(S.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&y.height!==S.height)return y.height-S.height;if(y.frameRate!==S.frameRate)return y.frameRate-S.frameRate;if(y.videoRange!==S.videoRange)return Qs.indexOf(y.videoRange)-Qs.indexOf(S.videoRange);if(y.videoCodec!==S.videoCodec){const _=zc(y.videoCodec),T=zc(S.videoCodec);if(_!==T)return T-_}if(y.uri===S.uri&&y.codecSet!==S.codecSet){const _=Ys(y.codecSet),T=Ys(S.codecSet);if(_!==T)return T-_}return y.averageBitrate!==S.averageBitrate?y.averageBitrate-S.averageBitrate:0});let h=d[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==d.length)){for(let y=0;y<d.length;y++)if(d[y].pathwayId===l[0].pathwayId){h=d[y];break}}this._levels=l;for(let y=0;y<l.length;y++)if(l[y]===h){var f;this._firstLevel=y;const S=h.bitrate,_=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${S}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){const T=Math.min(S,this.hls.config.abrEwmaDefaultEstimateMax);T>_&&_===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=T)}break}const g=n&&!s,p=this.hls.config,m=!!(p.audioStreamController&&p.audioTrackController),v={levels:l,audioTracks:o,subtitleTracks:u,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:s,altAudio:m&&!g&&o.some(y=>!!y.url)};c.end=performance.now(),this.hls.trigger(E.MANIFEST_PARSED,v)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const c=new Error("invalid level idx"),d=e<0;if(this.hls.trigger(E.ERROR,{type:q.OTHER_ERROR,details:C.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:c,reason:c.message}),d)return;e=Math.min(e,t.length-1)}const r=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,r===e&&s&&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 ${r}${n?" with Pathway "+n:""}`);const u={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(E.LEVEL_SWITCHING,u);const l=a.details;if(!l||l.live){const c=this.switchParams(a.uri,s==null?void 0:s.details,l);this.loadPlaylist(c)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),r=e.filter(s=>t.indexOf(s)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=r}}onError(e,t){t.fatal||!t.context||t.context.type===J.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===V.MAIN){const r=t.elementaryStreams;if(!Object.keys(r).some(n=>!!r[n]))return;const s=this._levels[t.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var r;const{level:s,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${s}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let u=a.details;u===t.details&&u.advanced&&(u=void 0),this.playlistLoaded(s,t,u)}else(r=t.deliveryDirectives)!=null&&r.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a==null?void 0:a.age;this.log(`Loading level index ${s}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(E.LEVEL_LOADING,{url:r,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const r=this._levels.filter((n,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));mg(r),this._levels=r,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const s=r.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(E.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function ih(i){const e={};i.forEach(t=>{const r=t.groupId||"";t.id=e[r]=e[r]||0,e[r]++})}function cm(){return self.SourceBuffer||self.WebKitSourceBuffer}function dm(){if(!Ot())return!1;const e=cm();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function QT(){if(!dm())return!1;const i=Ot();return typeof(i==null?void 0:i.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>i.isTypeSupported(Bi(e,"video")))||["mp4a.40.2","fLaC"].some(e=>i.isTypeSupported(Bi(e,"audio"))))}function ZT(){var i;const e=cm();return typeof(e==null||(i=e.prototype)==null?void 0:i.changeType)=="function"}const JT=100;class eb extends Lo{constructor(e,t,r){super(e,t,r,"stream-controller",V.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const s=this.media,n=s?s.currentTime:null;if(n===null||!$(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;const a=this.getFwdBufferInfoAtPos(s,n,V.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${n} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:r,hls:s}=this;if(this.stopLoad(),this.setInterval(JT),this.level=-1,!this.startFragRequested){let n=s.startLevel;n===-1&&(s.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=s.firstAutoLevel),s.nextLoadLevel=n,this.level=s.loadLevel,this._hasEnoughToStart=!!t}r>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r),this.state=k.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=k.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case k.WAITING_LEVEL:{const{levels:e,level:t}=this,r=e==null?void 0:e[t],s=r==null?void 0:r.details;if(s&&(!s.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(s))break;this.state=k.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=k.IDLE;break}break}case k.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===k.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:r,media:s}=this;if(t===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(r!=null&&r[n]))return;const a=r[n],o=this.getMainFwdBufferInfo();if(o===null)return;const u=this.getLevelDetails();if(u&&this._streamEnded(o,u)){const p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(E.BUFFER_EOS,p),this.state=k.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;const l=a.details;if(!l||this.state===k.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=k.WAITING_LEVEL,this.startFragRequested=!1;return}const c=o.len,d=this.getMaxBufferLength(a.maxBitrate);if(c>=d)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(h,l);if(this.couldBacktrack&&!this.fragPrevious&&f&&me(f)&&this.fragmentTracker.getState(f)!==_e.OK){var g;const m=((g=this.backtrackFragment)!=null?g:f).sn-l.startSN,v=l.fragments[m-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,h)){if(!f.gap){const m=this.audioOnly&&!this.altAudio?oe.AUDIO:oe.VIDEO,v=(m===oe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,m,V.MAIN)}f=this.getNextFragmentLoopLoading(f,l,o,V.MAIN,d)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(e,t,r){const s=this.fragmentTracker.getState(e);s===_e.NOT_LOADED||s===_e.PARTIAL?me(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,r):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,V.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let r;const s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.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,u=e[o],l=this.fragLastKbps;l&&this.fragCurrent?r=this.fragCurrent.duration*u.maxBitrate/(1e3*l)+1:r=0}else r=0;const a=this.getBufferedFrag(t.currentTime+r);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const u=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,c=Math.max(a.end,u+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,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 k.KEY_LOADING:case k.FRAG_LOADING:case k.FRAG_LOADING_WAITING_RETRY:case k.PARSING:case k.PARSED:this.state=k.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const r=t.media;Ne(r,"playing",this.onMediaPlaying),Ne(r,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:r}=this;r&&($e(r,"playing",this.onMediaPlaying),$e(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(E.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let r=!1,s=!1;for(let n=0;n<t.levels.length;n++){const a=t.levels[n].audioCodec;a&&(r=r||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=r&&s&&!ZT(),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:r}=this;if(!r||this.state!==k.IDLE)return;const s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=k.WAITING_LEVEL)}onLevelLoaded(e,t){var r;const{levels:s,startFragRequested:n}=this,a=t.level,o=t.details,u=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${u}`);const l=t.levelInfo,c=this.fragCurrent;c&&(this.state===k.FRAG_LOADING||this.state===k.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let d=0;if(o.live||(r=l.details)!=null&&r.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(l.details=o,this.levelLastLoaded=l,n||this.setStartPosition(o,d),this.hls.trigger(E.LEVEL_UPDATED,{details:o,level:a}),this.state===k.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=k.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:r}=this;if(!r)return;const s=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,u=n>=a-t.maxFragLookUpTolerance&&n<=o;if(s!==null&&r.duration>s&&(n<s||!u)){const c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!u&&r.readyState<4||n<o-c)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),r.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const d=Y.bufferInfo(r,s,0);if(!((l=d.buffered)!=null&&l.length)){r.currentTime=s;return}if(d.start<=n){r.currentTime=s;return}const{nextStart:f}=Y.bufferedInfo(d.buffered,n,0);f&&(r.currentTime=f)}else r.currentTime=s}}_handleFragmentLoadProgress(e){var t;const r=e.frag,{part:s,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const o=a[r.level];if(!o){this.warn(`Level ${r.level} not found on progress`);return}const u=o.details;if(!u){this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),this.fragmentTracker.removeFragment(r);return}const l=o.videoCodec,c=u.PTSKnown||!u.live,d=(t=r.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Ng(this.hls,V.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=s?s.index:-1,p=g!==-1,m=new Ao(r.level,r.sn,r.stats.chunkCount,n.byteLength,g,p),v=this.initPTS[r.cc];f.push(n,d,h,l,r,s,u.totalduration,c,m,v)}onAudioTrackSwitching(e,t){const r=this.hls,s=this.altAudio!==0;if(Zs(t.url,r))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s){this.altAudio=0,this.fragmentTracker.removeAllFragments(),r.once(E.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(E.AUDIO_TRACK_SWITCHED,t)}),r.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(E.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const r=Zs(t.url,this.hls);if(r){const s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=r?2:0,this.tick()}onBufferCreated(e,t){const r=t.tracks;let s,n,a=!1;for(const o in r){const u=r[o];if(u.id==="main"){if(n=o,s=u,o==="video"){const l=r[o];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:r,part:s}=t,n=r.type===V.MAIN;if(n){if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${s?" p: "+s.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),this.state===k.PARSED&&(this.state=k.IDLE);return}const o=s?s.stats:r.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),me(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,s)}const a=this.media;a&&(!this._hasEnoughToStart&&Y.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var r;if(t.fatal){this.state=k.ERROR;return}switch(t.details){case C.FRAG_GAP:case C.FRAG_PARSING_ERROR:case C.FRAG_DECRYPT_ERROR:case C.FRAG_LOAD_ERROR:case C.FRAG_LOAD_TIMEOUT:case C.KEY_LOAD_ERROR:case C.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(V.MAIN,t);break;case C.LEVEL_LOAD_ERROR:case C.LEVEL_LOAD_TIMEOUT:case C.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===k.WAITING_LEVEL&&((r=t.context)==null?void 0:r.type)===J.LEVEL&&(this.state=k.IDLE);break;case C.BUFFER_ADD_CODEC_ERROR:case C.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case C.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case C.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=k.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==oe.AUDIO||!this.altAudio){const r=(t===oe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,t,V.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let r=this.startPosition;if(r>=0&&t<r){if(e.seeking){this.log(`could not seek to ${r}, already seeking at ${t}`);return}const s=this.timelineOffset;s&&r&&(r+=s);const n=this.getLevelDetails(),a=Y.getBuffered(e),o=a.length?a.start(0):0,u=o-r,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||u>0&&(u<l||this.loadingParts&&u<2*((n==null?void 0:n.partTarget)||0)))&&(this.log(`adjusting start position by ${u} to match buffer start`),r+=u,this.startPosition=r),t<r&&(this.log(`seek to target start position ${r} from current time ${t} buffer start ${o}`),e.currentTime=r)}}_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(r=>{const{hls:s}=this,n=r==null?void 0:r.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=k.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),s.trigger(E.FRAG_LOADED,r),n.bitrateTest=!1}).catch(r=>{this.state===k.STOPPED||this.state===k.ERROR||(this.warn(r),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:r}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}const{frag:o,part:u,level:l}=a,{video:c,text:d,id3:h,initSegment:f}=s,{details:g}=l,p=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=k.PARSING,f){const m=f.tracks;if(m){const _=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(l,m,_,n),r.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:_,id:t,tracks:m})}const v=f.initPTS,y=f.timescale,S=this.initPTS[o.cc];if($(v)&&(!S||S.baseTime!==v||S.timescale!==y)){const _=f.trackId;this.initPTS[o.cc]={baseTime:v,timescale:y,trackId:_},r.trigger(E.INIT_PTS_FOUND,{frag:o,id:t,initPTS:v,timescale:y,trackId:_})}}if(c&&g){p&&c.type==="audiovideo"&&this.logMuxedErr(o);const m=g.fragments[o.sn-1-g.startSN],v=o.sn===g.startSN,y=!m||o.cc>m.cc;if(s.independent!==!1){const{startPTS:S,endPTS:_,startDTS:T,endDTS:x}=c;if(u)u.elementaryStreams[c.type]={startPTS:S,endPTS:_,startDTS:T,endDTS:x};else if(c.firstKeyFrame&&c.independent&&n.id===1&&!y&&(this.couldBacktrack=!0),c.dropped&&c.independent){const b=this.getMainFwdBufferInfo(),I=(b?b.end:this.getLoadPosition())+this.config.maxBufferHole,A=c.firstKeyFramePTS?c.firstKeyFramePTS:S;if(!v&&I<A-this.config.maxBufferHole&&!y){this.backtrack(o);return}else y&&(o.gap=!0);o.setElementaryStreamInfo(c.type,o.start,_,o.start,x,!0)}else v&&S-(g.appliedTimelineOffset||0)>Ns&&(o.gap=!0);o.setElementaryStreamInfo(c.type,S,_,T,x),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(c,o,u,n,v||y)}else if(v||y)o.gap=!0;else{this.backtrack(o);return}}if(p){const{startPTS:m,endPTS:v,startDTS:y,endDTS:S}=p;u&&(u.elementaryStreams[oe.AUDIO]={startPTS:m,endPTS:v,startDTS:y,endDTS:S}),o.setElementaryStreamInfo(oe.AUDIO,m,v,y,S),this.bufferFragmentData(p,o,u,n)}if(g&&h!=null&&h.samples.length){const m={id:t,frag:o,details:g,samples:h.samples};r.trigger(E.FRAG_PARSING_METADATA,m)}if(g&&d){const m={id:t,frag:o,details:g,samples:d.samples};r.trigger(E.FRAG_PARSING_USERDATA,m)}}logMuxedErr(e){this.warn(`${me(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,r,s){if(this.state!==k.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));const{audio:n,video:a,audiovideo:o}=t;if(n){const l=e.audioCodec;let c=Cs(n.codec,l);c==="mp4a"&&(c="mp4a.40.5");const d=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){c&&(c.indexOf("mp4a.40.5")!==-1?c="mp4a.40.2":c="mp4a.40.5");const h=n.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&d.indexOf("firefox")===-1&&(c="mp4a.40.5")}c&&c.indexOf("mp4a.40.5")!==-1&&d.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(c="mp4a.40.2",this.log(`Android: force audio codec to ${c}`)),l&&l!==c&&this.log(`Swapping manifest audio codec "${l}" for "${c}"`),n.levelCodec=c,n.id=V.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${c||""}/${l||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=V.MAIN;const l=a.codec;if((l==null?void 0:l.length)===4)switch(l){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${a.codec!==l?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const u=Object.keys(t);if(u.length){if(this.hls.trigger(E.BUFFER_CODECS,t),!this.hls)return;u.forEach(l=>{const d=t[l].initSegment;d!=null&&d.byteLength&&this.hls.trigger(E.BUFFER_APPENDING,{type:l,data:d,frag:r,part:null,chunkMeta:s,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,V.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,r=e==null?void 0:e[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=k.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const r=e.currentTime;if(Y.isBuffered(e,r)?t=this.getAppendedFrag(r):Y.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;const s=this.fragPlaying,n=t.level;(!s||t.sn!==s.sn||s.level!==n)&&(this.fragPlaying=t,this.hls.trigger(E.FRAG_CHANGED,{frag:t}),(!s||s.level!==n)&&this.hls.trigger(E.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return $(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if($(t)){const r=this.getLevelDetails(),s=this.currentFrag||(r?or(null,r.fragments,t):null);if(s){const n=s.programDateTime;if(n!==null){const a=n+(t-s.start)*1e3;return new Date(a)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class tb extends et{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const r in this.keyIdToKeyInfo){const s=this.keyIdToKeyInfo[r].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=C.KEY_LOAD_ERROR,r,s,n){return new Et({type:q.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:r,networkDetails:s})}loadClear(e,t,r){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,n=t.length;s<n;s++){const a=t[s];if(e.cc<=a.cc&&(!me(e)||!me(a)||e.sn<a.sn)||!r&&s==n-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);const u=Ps(o);if(u)return this.emeController.getKeySystemAccess([u])})}if(this.config.requireKeySystemAccessOnStart){const s=Ri(this.config);if(s.length)return this.emeController.getKeySystemAccess(s)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var r,s;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const l=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,C.KEY_LOAD_ERROR,l))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,C.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=Sa(n);let u=this.keyIdToKeyInfo[o];if((r=u)!=null&&r.decryptdata.key)return n.key=u.decryptdata.key,Promise.resolve({frag:e,keyInfo:u});if(this.emeController&&(s=u)!=null&&s.keyLoadPromise)switch(this.emeController.getKeyStatus(u.decryptdata)){case"usable":case"usable-in-future":return u.keyLoadPromise.then(c=>{const{keyInfo:d}=c;return n.key=d.decryptdata.key,{frag:e,keyInfo:d}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${n.keyId?" keyId: "+Ie(n.keyId):""} URI: ${n.uri} from ${e.type} ${e.level}`),u=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(u,e):this.loadKeyEME(u,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(u,e);default:return Promise.reject(this.createKeyLoadError(e,C.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var s;if(!e.decryptdata.keyId&&(s=t.initSegment)!=null&&s.data){const a=Sv(t.initSegment.data);if(a.length){let o=a[0];o.some(u=>u!==0)?(this.log(`Using keyId found in init segment ${Ie(o)}`),kt.setKeyIdForUri(e.decryptdata.uri,o)):(o=kt.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Ie(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!me(t))return Promise.resolve(r);const n=this.emeController.loadKey(r);return(e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,r))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(r)}loadKeyHTTP(e,t){const r=this.config,s=r.loader,n=new s(r);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{const u={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=r.keyLoadPolicy.default,c={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,g,p)=>{const{frag:m,keyInfo:v}=g,y=Sa(v.decryptdata);if(!m.decryptdata||v!==this.keyIdToKeyInfo[y])return o(this.createKeyLoadError(m,C.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));v.decryptdata.key=m.decryptdata.key=new Uint8Array(h.data),m.keyLoader=null,v.loader=null,a({frag:m,keyInfo:v})},onError:(h,f,g,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,C.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),g,se({url:u.url,data:void 0},h)))},onTimeout:(h,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,C.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(h,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,C.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};n.load(u,c,d)})}resetLoader(e){const{frag:t,keyInfo:r,url:s}=e,n=r.loader;t.keyLoader===n&&(t.keyLoader=null,r.loader=null);const a=Sa(r.decryptdata)||s;delete this.keyIdToKeyInfo[a],n&&n.destroy()}}function Sa(i){if(i.keyFormat!==De.FAIRPLAY){const e=i.keyId;if(e)return Ie(e)}return i.uri}function sh(i){const{type:e}=i;switch(e){case J.AUDIO_TRACK:return V.AUDIO;case J.SUBTITLE_TRACK:return V.SUBTITLE;default:return V.MAIN}}function _a(i,e){let t=i.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class rb{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,r=t.pLoader,s=t.loader,n=r||s,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:r}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:J.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:r,level:s,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:u}=t;this.load({id:r,level:s,pathwayId:n,responseType:"text",type:J.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:u})}onAudioTrackLoading(e,t){const{id:r,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:r,groupId:s,level:null,responseType:"text",type:J.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:r,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:r,groupId:s,level:null,responseType:"text",type:J.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const r=this.loaders[J.LEVEL];if(r){const s=r.context;s&&!t.levels.some(n=>n===s.levelOrTrack)&&(r.abort(),delete this.loaders[J.LEVEL])}}load(e){var t;const r=this.hls.config;let s=this.getInternalLoader(e);if(s){const l=this.hls.logger,c=s.context;if(c&&c.levelOrTrack===e.levelOrTrack&&(c.url===e.url||c.deliveryDirectives&&!e.deliveryDirectives)){c.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${c.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let n;if(e.type===J.MANIFEST?n=r.manifestLoadPolicy.default:n=ae({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),$((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===J.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===J.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===J.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const c=l.partTarget,d=l.targetduration;if(c&&d){const h=Math.max(c*3,d*.8)*1e3;n=ae({},n,{maxTimeToFirstByteMs:Math.min(h,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,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},u={onSuccess:(l,c,d,h)=>{const f=this.getInternalLoader(d);this.resetInternalLoader(d.type);const g=l.data;c.parsing.start=performance.now(),ht.isMediaPlaylist(g)||d.type!==J.MANIFEST?this.handleTrackOrLevelPlaylist(l,c,d,h||null,f):this.handleMasterPlaylist(l,c,d,h)},onError:(l,c,d,h)=>{this.handleNetworkError(c,d,!1,l,h)},onTimeout:(l,c,d)=>{this.handleNetworkError(c,d,!0,void 0,l)}};s.load(e,o,u)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:r}=this.hls;(e||r)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,r,s){const n=this.hls,a=e.data,o=_a(e,r),u=ht.parseMasterPlaylist(a,o);if(u.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,r,u.playlistParsingError,s,t);return}const{contentSteering:l,levels:c,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:g}=u;this.variableList=g,c.forEach(y=>{const{unknownCodecs:S}=y;if(S){const{preferManagedMediaSource:_}=this.hls.config;let{audioCodec:T,videoCodec:x}=y;for(let b=S.length;b--;){const I=S[b];Ni(I,"audio",_)?(y.audioCodec=T=T?`${T},${I}`:I,ei.audio[T.substring(0,4)]=2,S.splice(b,1)):Ni(I,"video",_)&&(y.videoCodec=x=x?`${x},${I}`:I,ei.video[x.substring(0,4)]=2,S.splice(b,1))}}});const{AUDIO:p=[],SUBTITLES:m,"CLOSED-CAPTIONS":v}=ht.parseMasterPlaylistMedia(a,o,u);p.length&&!p.some(S=>!S.url)&&c[0].audioCodec&&!c[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new de({}),bitrate:0,url:""})),n.trigger(E.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:m,captions:v,contentSteering:l,url:o,stats:t,networkDetails:s,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,r,s,n){const a=this.hls,{id:o,level:u,type:l}=r,c=_a(e,r),d=$(u)?u:$(o)?o:0,h=sh(r),f=ht.parseLevelPlaylist(e.data,c,d,h,0,this.variableList);if(l===J.MANIFEST){const g={attrs:new de({}),bitrate:0,details:f,name:"",url:c};f.requestScheduled=t.loading.start+hg(f,0),a.trigger(E.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:c,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=f,this.handlePlaylistLoaded(f,e,t,r,s,n)}handleManifestParsingError(e,t,r,s,n){this.hls.trigger(E.ERROR,{type:q.NETWORK_ERROR,details:C.MANIFEST_PARSING_ERROR,fatal:t.type===J.MANIFEST,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:s,stats:n})}handleNetworkError(e,t,r=!1,s,n){let a=`A network ${r?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===J.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===J.AUDIO_TRACK||e.type===J.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let u=C.UNKNOWN,l=!1;const c=this.getInternalLoader(e);switch(e.type){case J.MANIFEST:u=r?C.MANIFEST_LOAD_TIMEOUT:C.MANIFEST_LOAD_ERROR,l=!0;break;case J.LEVEL:u=r?C.LEVEL_LOAD_TIMEOUT:C.LEVEL_LOAD_ERROR,l=!1;break;case J.AUDIO_TRACK:u=r?C.AUDIO_TRACK_LOAD_TIMEOUT:C.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case J.SUBTITLE_TRACK:u=r?C.SUBTITLE_TRACK_LOAD_TIMEOUT:C.SUBTITLE_LOAD_ERROR,l=!1;break}c&&this.resetInternalLoader(e.type);const d={type:q.NETWORK_ERROR,details:u,fatal:l,url:e.url,loader:c,context:e,error:o,networkDetails:t,stats:n};if(s){const h=(t==null?void 0:t.url)||e.url;d.response=se({url:h,data:void 0},s)}this.hls.trigger(E.ERROR,d)}handlePlaylistLoaded(e,t,r,s,n,a){const o=this.hls,{type:u,level:l,levelOrTrack:c,id:d,groupId:h,deliveryDirectives:f}=s,g=_a(t,s),p=sh(s);let m=typeof s.level=="number"&&p===V.MAIN?l:void 0;const v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(E.ERROR,{type:q.NETWORK_ERROR,details:C.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:v,reason:v.message,response:t,context:s,level:m,parent:p,networkDetails:n,stats:r});return}e.playlistParsingError=null}if(!e.fragments.length){const y=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(E.ERROR,{type:q.NETWORK_ERROR,details:C.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:y,reason:y.message,response:t,context:s,level:m,parent:p,networkDetails:n,stats:r});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),u){case J.MANIFEST:case J.LEVEL:if(m){if(!c)m=0;else if(c!==o.levels[m]){const y=o.levels.indexOf(c);y>-1&&(m=y)}}o.trigger(E.LEVEL_LOADED,{details:e,levelInfo:c||o.levels[0],level:m||0,id:d||0,stats:r,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:u===J.MANIFEST});break;case J.AUDIO_TRACK:o.trigger(E.AUDIO_TRACK_LOADED,{details:e,track:c,id:d||0,groupId:h||"",stats:r,networkDetails:n,deliveryDirectives:f});break;case J.SUBTITLE_TRACK:o.trigger(E.SUBTITLE_TRACK_LOADED,{details:e,track:c,id:d||0,groupId:h||"",stats:r,networkDetails:n,deliveryDirectives:f});break}}}class Ze{static get version(){return $i}static isMSESupported(){return dm()}static isSupported(){return QT()}static getMediaSource(){return Ot()}static get Events(){return E}static get MetadataSchema(){return We}static get ErrorTypes(){return q}static get ErrorDetails(){return C}static get DefaultConfig(){return Ze.defaultConfig?Ze.defaultConfig:UT}static set DefaultConfig(e){Ze.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Ro,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=lv(e.debug||!1,"Hls instance",e.assetPlayerId),r=this.config=jT(Ze.DefaultConfig,e,t);this.userConfig=e,r.progressive&>(r,t);const{abrController:s,bufferController:n,capLevelController:a,errorController:o,fpsController:u}=r,l=new o(this),c=this.abrController=new s(this),d=new iE(this),h=r.interstitialsController,f=h?this.interstitialsController=new h(this,Ze):null,g=this.bufferController=new n(this,d),p=this.capLevelController=new a(this),m=new u(this),v=new rb(this),y=r.contentSteeringController,S=y?new y(this):null,_=this.levelController=new XT(this,S),T=new zT(this),x=new tb(this.config,this.logger),b=this.streamController=new eb(this,d,x),I=this.gapController=new HT(this,d);p.setStreamController(b),m.setStreamController(b);const A=[v,_,b];f&&A.splice(1,0,f),S&&A.splice(1,0,S),this.networkControllers=A;const D=[c,g,I,p,m,T,d];this.audioTrackController=this.createController(r.audioTrackController,A);const L=r.audioStreamController;L&&A.push(this.audioStreamController=new L(this,d,x)),this.subtitleTrackController=this.createController(r.subtitleTrackController,A);const P=r.subtitleStreamController;P&&A.push(this.subtititleStreamController=new P(this,d,x)),this.createController(r.timelineController,D),x.emeController=this.emeController=this.createController(r.emeController,D),this.cmcdController=this.createController(r.cmcdController,D),this.latencyController=this.createController(YT,D),this.coreComponents=D,A.push(l);const O=l.onErrorOut;typeof O=="function"&&this.on(E.ERROR,O,l),this.on(E.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){const r=new e(this);return t&&t.push(r),r}return null}on(e,t,r=this){this._emitter.on(e,t,r)}once(e,t,r=this){this._emitter.once(e,t,r)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,r=this,s){this._emitter.off(e,t,r,s)}listeners(e){return this._emitter.listeners(e)}emit(e,t,r){return this._emitter.emit(e,t,r)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(r){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+r.message+'". Here is a stacktrace:',r),!this.triggeringException){this.triggeringException=!0;const s=e===E.ERROR;this.trigger(E.ERROR,{type:q.OTHER_ERROR,details:C.INTERNAL_EXCEPTION,fatal:s,event:e,error:r}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(E.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(E.ERROR,{type:q.OTHER_ERROR,details:C.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,r=t?e.media:e,s=t?e:{media:r};this._media=r,this.trigger(E.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(E.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(E.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,r=this._url,s=this._url=vo.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),t&&r&&(r!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(E.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),!(!this.started||!this.networkControllers));r++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[V.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[V.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[V.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=H_()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){jv(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 r=e.length;for(let s=0;s<r;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:r}=this;let s;if(t===-1&&e!=null&&e.length?s=e.length-1:s=t,r)for(let n=s;n--;){const a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=r)return n}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const r=Qf(t);return Yf(e,r,navigator.mediaCapabilities)}}Ze.defaultConfig=void 0;const nh="https://vod-beta.stream.place/xrpc";function ib(i,e,t,r){var v,y,S,_;const[s,n]=ze(!1),[a,o]=ze(!0),[u,l]=ze(null),[c,d]=ze(null),[h,f]=ze(null),g=Ci(0),p=Ci(null),m=Ci(!1);return Gs(()=>{if(!e||i.length===0||!t.current||!r.current)return;const T=t.current,x=r.current,b=e;async function I(){if(m.current)return;m.current=!0;const A=++g.current,D=()=>A!==g.current,L=i.find(U=>U.uri===b);if(!L){m.current=!1;return}const P=L.value.title||"Unknown Video",O=L.uri,G=encodeURIComponent(O);if(console.log("[Player] Switching to:",P),l(P),d(O),o(!1),n(!0),p.current&&(p.current.destroy(),p.current=null),T.pause(),T.removeAttribute("src"),T.load(),x.pause(),x.removeAttribute("src"),await new Promise(U=>setTimeout(U,250)),D()){m.current=!1;return}const j=Of(),M=`${nh}/place.stream.playback.getVideoPlaylist?uri=${G}`;if(!Ze.isSupported()){const U=`${nh}/place.stream.playback.getVideoPlaylist?uri=${G}`;T.src=U,T.currentTime=j;try{await T.play(),n(!1)}catch(F){console.warn("[Player] Playback error:",F),n(!1)}m.current=!1;return}p.current=new Ze({startPosition:j,maxBufferLength:30,maxMaxBufferLength:60}),p.current.loadSource(M),p.current.attachMedia(T),p.current.on(Ze.Events.MANIFEST_PARSED,()=>{D()||(console.log("[Player] Video manifest parsed"),T.muted=!0,T.play().catch(U=>console.warn("[Player] Play failed:",U)))}),p.current.on(Ze.Events.ERROR,(U,F)=>{var K,W;D()||(console.warn("[Player] HLS error:",F.type,F.details,F.fatal),F.fatal&&(F.type===Ze.ErrorTypes.MEDIA_ERROR?(K=p.current)==null||K.recoverMediaError():((W=p.current)==null||W.destroy(),p.current=null,m.current=!1,I())))}),m.current=!1}return I(),()=>{const A=t.current;A==null||A.pause()}},[e,i,t,r]),Gs(()=>{if(!e){f(null);return}const T=i.find(x=>x.uri===e);if(!(T!=null&&T.value.creator)){f(null);return}wf(T.value.creator).then(x=>{f(x)})},[e,i]),{isLoading:s,showStandby:a,currentTitle:u,currentUri:c,currentDescription:e?((v=i.find(T=>T.uri===e))==null?void 0:v.value.description)??null:null,currentCreator:e?((y=i.find(T=>T.uri===e))==null?void 0:y.value.creator)??null:null,currentHandle:h,currentCreatedAt:e?((S=i.find(T=>T.uri===e))==null?void 0:S.value.createdAt)??null:null,currentDuration:e?((_=i.find(T=>T.uri===e))==null?void 0:_.value.duration)??null:null}}function sb(){const[i,e]=ze([]),[t,r]=ze(new Map),[s,n]=ze(null),[a,o]=ze(null),u=typeof window<"u"&&window.innerWidth<1024,[l,c]=ze(()=>u),d=Ci(null),h=Ci(null),f=ib(i,s,d,h),g=()=>{c(!l)};Gs(()=>{async function v(){try{const y=await $y();console.log(`Loaded ${y.length} VODs`),e(y);const S=[...new Set(y.map(I=>I.value.creator))],_=new Map;await Promise.all(S.map(async I=>{const A=await wf(I);A&&_.set(I,A)})),r(_);const T=kf(y),x=Array.from(T.keys()).sort();x.length>0&&o(x[0]);const b=jy();if(b){const I=y.find(A=>po(A.uri)===b);I&&(o(yo(I)),n(I.uri),$c(I.uri))}}catch(y){console.error("Failed to load VODs:",y)}}v()},[]);const p=v=>{o(v)},m=v=>{n(v),$c(v),u&&c(!0)};return Gs(()=>{const v=()=>{const y=d.current;if(!y)return;const S=Of();S>0&&(y.currentTime=S)};return window.addEventListener("popstate",v),()=>window.removeEventListener("popstate",v)},[d]),H("div",{class:"flex flex-col h-screen overflow-hidden",style:"background-color: #1a1a1a; color: #7dd3fc; line-height: 1.6; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif",children:[H("h1",{class:"font-sans text-2xl font-semibold text-[#7dd3fc] m-0 py-4 px-5 tracking-wide shrink-0 flex items-center justify-between bg-[#141414] border-b border-white/10",children:[H("div",{class:"flex items-center gap-3",children:[H("button",{onClick:g,class:"p-1 hover:bg-[rgba(125,211,252,0.1)] rounded transition-colors text-[#7dd3fc] cursor-pointer","aria-label":l?"Expand sidebar":"Collapse sidebar",children:l?H(Fm,{size:24}):H(Mm,{size:24})}),H("span",{children:"AtmosphereConf 2026"})]}),H("a",{class:"font-sans text-sm text-white/70 no-underline hover:text-white bg-white/10 hover:bg-white/20 rounded px-4 py-2 transition-colors",href:"https://tangled.org/timryan.org/atmosphereconf2026",target:"_blank",rel:"noopener",children:"View Source"})]}),H("div",{class:"flex flex-row flex-1 overflow-hidden relative",children:[!l&&H("div",{class:"fixed inset-0 bg-black/50 z-40 lg:hidden",onClick:g}),H(Yy,{vods:i,handles:t,currentChannel:s,selectedDay:a,onSelectDay:p,onSelectVideo:m,collapsed:l}),H(Jy,{currentTitle:f.currentTitle,currentUri:f.currentUri,currentDescription:f.currentDescription,currentCreator:f.currentCreator,currentHandle:f.currentHandle,currentCreatedAt:f.currentCreatedAt,currentDuration:f.currentDuration,isLoading:f.isLoading,showStandby:f.showStandby,videoRef:d,audioRef:h})]})]})}const ah=document.getElementById("app-root");ah&&Tm(H(sb,{}),ah);</script>
129143 </head>
130144 <body>
131145 <div id="app-root"></div>