PageSourceSearch

https://www.svr-pr.de/_nuxt/B-ENhL2O.js

js svr-pr.de collected 2026-10-06 15:27:27 UTC 541,717 bytes, 233 lines download raw bytes

1import{L as Pn,M as Io,N as hs,P as Ai,Q as Ro,R as bo,U as ot,V as wn,m as le,s as Li,W as _o,r as Ae,o as Ut,c as Rs,K as On,b as qe,X as tr,u as ue,Y as Do,_ as Mn,i as Ct,n as ds,g as Fn,S as Nn,a as Ii,w as Co,Z as ko,d as Po,$ as wo,f as Bn,F as Oo,h as si,a0 as me,a1 as fs,a2 as Mo,a3 as Fo,a4 as No,a5 as sr,a6 as Bo,a7 as ir,a8 as Uo,a9 as $o,aa as Go,ab as Vo,x as Ko,ac as rr,ad as Ho,ae as Wo,af as Yo}from"./Dq6-f57W.js";const dg=`
2  seo{
3    notIndexed,
4    metaTitle,
5    metaDescription,
6    'ogImage': ogImage.asset->url,
7  },
8`,fg=`
9  "global": *[_type == "global"][0]{
10    siteTitle,
11  },
12`,Un=`
13  'thumbTime': video.asset->thumbTime,
14  'aspectRatio': video.asset->data.aspect_ratio,
15  'playbackId': video.asset->playbackId,
16  'mp4Supported': video.asset->data.mp4_support == "standard",
17`,qo=`
18  type == "video" => {
19    ${Un}
20  },
21`,ii=`
22  _key,
23  _type,
24  _type == "mainImage" => {
25    'imageUrl': asset->url,
26    'image': asset._ref,
27    'alt': alt,
28    'crop': crop,
29    'hotspot': hotspot,
30    'dimensions': asset->metadata.dimensions,
31    'originalFilename': asset->originalFilename,
32  },
33  _type == "mainVideo" => {
34    ${Un}
35  },
36`,gt=n=>`
37  ${n}[]{
38    ...,
39    _type == "block" => {
40      markDefs[]{
41        _type == "externalLink" => {
42          ...,
43        },
44        _type == "internalLink" => {
45          ...,
46          'page': page->_type,
47          'slug': page->slug.current,
48        },
49      },
50    },
51    _type == "image" => {
52      ...,
53      'src': image.asset->url,
54      'crop': image.crop,
55      'hotspot': image.hotspot,
56      'dimensions': image.asset->metadata.dimensions,
57    },
58  },
59`,gg=`
60  "global": *[_type == "global"][0]{
61    siteTitle,
62    metaDescription,
63    'favicon': favicon.asset->url,
64    'ogImage': ogImage.asset->url,
65    introGallery[]{
66      ${ii}
67    },
68    navigation[]->{
69      _id,
70      _type,
71      title,
72      slug,
73    },
74    navigationGallery[]{
75      ${ii}
76    },
77    instagram,
78    copyright,
79    footerTitle,
80    contactPage->{
81      _id,
82      _type,
83      title,
84      slug,
85    },
86    legalPage->{
87      _id,
88      _type,
89      title,
90      slug,
91    },
92    ${gt("address")}
93    "contact": *[_type == "contact"][0]{title, slug},
94    "legal": *[_type == "legal"][0]{title, slug},
95  },
96`,jo=`
97  type == "image" => {
98    'image': image.asset._ref,
99    'alt': image.alt,
100    'crop': image.crop,
101    'hotspot': image.hotspot,
102    'dimensions': image.asset->metadata.dimensions,
103    'originalFilename': image.asset->originalFilename,
104  },
105  `,ks=`
106  mediaGallery[]{
107    ${ii}
108  },
109`,zo=`
110  _key,
111  type,
112  ${jo}
113  ${qo}
114`,Xo=`
115  media{
116    ${zo}
117  },
118`,Qo=`
119  type,
120  title,
121  type == "internalLink" => {
122    'slug': page->slug.current,
123    'page': page->_type,
124  },
125  type == "externalLink" => {
126    href,
127  },
128`,Zo=`
129  cta{
130    ${Qo}
131  },
132`,mg=`
133  _type,
134  _type == "eventsGallery" => {
135    ${ks}
136  },
137  _type == "textBlock" => {
138    position,
139    overline,
140    ${gt("text")}
141  },
142  _type == "instagramPosts" => {
143    ${gt("text")}
144    ${ks}
145  },
146  _type == "year" => {
147    year,
148    description,
149  },
150  _type == "largeCta" => {
151    overline,
152    ${gt("title")}
153    ${Xo}
154    ${Zo}
155  },
156  _type == "fullscreenCarousel" => {
157    slides[]{
158      _key,
159      title,
160      items,
161      ${ks}
162    },
163  },
164  _type == "clients" => {
165    "clients": *[_type == "client"][]|order(title asc){_id,title,slug,category[]->{_id,title}},
166    "clientCategories": *[_type == "clientCategory"][]|order(orderRank){_id,title},
167  },
168  _type == "copy" => {
169    textBlocks[]{
170      _key,
171      overline,
172      ${gt("text")}
173    },
174  },
175  _type == "openPositions" => {
176    title,
177    ${gt("text")}
178    positions[]{
179      title,
180      url,
181    },
182  },
183  _type == "contact" => {
184    items[]{
185      _key,
186      overline,
187      phone,
188    },
189  },
190`;async function Jo(n,e){return await el(e).catch(s=>(console.error("Failed to get image meta for "+e,s+""),{width:0,height:0,ratio:0}))}async function el(n){if(typeof Image>"u")throw new TypeError("Image not supported");return new Promise((e,t)=>{const s=new Image;s.onload=()=>{const i={width:s.width,height:s.height,ratio:s.width/s.height};e(i)},s.onerror=i=>t(i),s.src=n})}function nr(n){return e=>e?n[e]||e:n.missingValue}function $n({formatter:n,keyMap:e,joinWith:t="/",valueMap:s}={}){n||(n=(r,a)=>`${r}=${a}`),e&&typeof e!="function"&&(e=nr(e));const i=s||{};
190return Object.keys(i).forEach(r=>{typeof i[r]!="function"&&(i[r]=nr(i[r]))}),(r={})=>Object.entries(r).filter(([o,c])=>typeof c<"u").map(([o,c])=>{const l=i[o];return typeof l=="function"&&(c=l(r[o])),o=typeof e=="function"?e(o):o,n(o,c)}).join(t)}function Ne(n=""){if(typeof n=="number")return n;if(typeof n=="string"&&n.replace("px","").match(/^\d+$/g))return Number.parseInt(n,10)}function tl(n=""){if(n===void 0||!n.length)return[];const e=new Set;for(const t of n.split(" ")){const s=Number.parseInt(t.replace("x",""));s&&e.add(s)}return Array.from(e)}function sl(n){if(n.length===0)throw new Error("`densities` must not be empty, configure to `1` to render regular size only (DPR 1.0)")}function il(n){const e={};if(typeof n=="string")for(const t of n.split(/[\s,]+/).filter(s=>s)){const s=t.split(":");s.length!==2?e["1px"]=s[0].trim():e[s[0].trim()]=s[1].trim()}else Object.assign(e,n);return e}function rl(n){const e={options:n},t=(i,r={})=>Gn(e,i,r),s=(i,r={},a={})=>t(i,{...a,modifiers:Pn(r,a.modifiers||{})}).url;for(const i in n.presets)s[i]=(r,a,o)=>s(r,a,{...n.presets[i],...o});return s.options=n,s.getImage=t,s.getMeta=(i,r)=>nl(e,i,r),s.getSizes=(i,r)=>ll(e,i,r),e.$img=s,s}async function nl(n,e,t){const s=Gn(n,e,{...t});return typeof s.getMeta=="function"?await s.getMeta():await Jo(n,s.url)}function Gn(n,e,t){var l,u;if(e&&typeof e!="string")throw new TypeError(`input must be a string (received ${typeof e}: ${JSON.stringify(e)})`);if(!e||e.startsWith("data:"))return{url:e};const{provider:s,defaults:i}=al(n,t.provider||n.options.provider),r=ol(n,t.preset);if(e=hs(e)?e:Io(e),!s.supportsAlias){for(const h in n.options.alias)if(e.startsWith(h)){const d=n.options.alias[h];d&&(e=Ai(d,e.slice(h.length)))}}if(s.validateDomains&&hs(e)){const h=Ro(e).host;if(!n.options.domains.find(d=>d===h))return{url:e}}const a=Pn(t,r,i);a.modifiers={...a.modifiers};const o=a.modifiers.format;(l=a.modifiers)!=null&&l.width&&(a.modifiers.width=Ne(a.modifiers.width)),(u=a.modifiers)!=null&&u.height&&(a.modifiers.height=Ne(a.modifiers.height));const c=s.getImage(e,a,n);return c.format=c.format||o||"",c}function al(n,e){const t=n.options.providers[e];if(!t)throw new Error("Unknown provider: "+e);return t}function ol(n,e){if(!e)return{};if(!n.options.presets[e])throw new Error("Unknown preset: "+e);return n.options.presets[e]}function ll(n,e,t){var g,y,p,E,T;const s=Ne((g=t.modifiers)==null?void 0:g.width),i=Ne((y=t.modifiers)==null?void 0:y.height),r=il(t.sizes),a=(p=t.densities)!=null&&p.trim()?tl(t.densities.trim()):n.options.densities;sl(a);const o=s&&i?i/s:0,c=[],l=[];if(Object.keys(r).length>=1){for(const v in r){const S=ar(v,String(r[v]),i,o,n);if(S!==void 0){c.push({size:S.size,screenMaxWidth:S.screenMaxWidth,media:`(max-width: ${S.screenMaxWidth}px)`});for(const x of a)l.push({width:S._cWidth*x,src:or(n,e,t,S,x)})}}cl(c)}else for(const v of a){const S=Object.keys(r)[0];let x=S?ar(S,String(r[S]),i,o,n):void 0;x===void 0&&(x={size:"",screenMaxWidth:0,_cWidth:(E=t.modifiers)==null?void 0:E.width,_cHeight:(T=t.modifiers)==null?void 0:T.height}),l.push({width:v,src:or(n,e,t,x,v)})}ul(l);const u=l[l.length-1],h=c.length?c.map(v=>`${v.media?v.media+" ":""}${v.size}`).join(", "):void 0,d=h?"w":"x",f=l.map(v=>`${v.src} ${v.width}${d}`).join(", ");return{sizes:h,srcset:f,src:u==null?void 0:u.src}}function ar(n,e,t,s,i){const r=i.options.screens&&i.options.screens[n]||Number.parseInt(n),a=e.endsWith("vw");if(!a&&/^\d+$/.test(e)&&(e=e+"px"),!a&&!e.endsWith("px"))return;let o=Number.parseInt(e);if(!r||!o)return;a&&(o=Math.round(o/100*r));const c=s?Math.round(o*s):t;return{size:e,screenMaxWidth:r,_cWidth:o,_cHeight:c}}function or(n,e,t,s,i){return n.$img(e,{...t.modifiers,width:s._cWidth?s._cWidth*i:void 0,height:s._cHeight?s._cHeight*i:void 0},t)}function cl(n){var t;n.sort((s,i)=>s.screenMaxWidth-i.screenMaxWidth);let e=null;for(let s=n.length-1;s>=0;s--){const i=n[s];i.media===e&&n.splice(s,1),e=i.media}for(let s=0;s<n.length;s++)n[s].media=((t=n[s+1])==null?void 0:t.media)||""}function ul(n){n.sort((t,s)=>t.width-s.width);let e=null;for(let t=n.length-1;t>=0;t--){const s=n[t];s.width===e&&n.splice(t,1),e=s.width}}const hl="https://cdn.sanity.io/images",dl=$n({keyMap:{format:"fm",height:"h",quality:"q",width:"w",background:"bg",download:"dl",dpr:"dpr",sharpen:"sharp",orientation:"or","min-height":"min-h","max-height":"max-h","min-width":"min-w","max-width":"max-w",minHeight:"min-h",maxHeight:"max-h",minWidth:"min-w",maxWidth:"max-w",saturation:"sat"},valueMap:{format:{jpeg:"jpg"},fit:{cover:"crop",contain:"fill",fill:"scale",inside:"min",outside:"max"}},joinWith:"&",formatter:(n,e)=>String(e)==="true"?n:`${n}=${e}`}),fl=n=>{const e=n.match(/-(?<width>\d*)x(?<height>\d*)-(?<format>.*)$/);if(!e||!e.groups)return{width:void 0,height:void 0,format:void 0};const t=Number(e.groups.width),s=Number(e.groups.height);return{width:t,height:s,format:e.groups.format}},gl=(n,{modifiers:e={},projectId:t,dataset:s="production"}={})=>{const{height:i,width:r}=fl(n);if(e.crop&&typeof e.crop!="string"&&r&&i){const u=e.crop.left*r,h=e.crop.top*i,d=r-e.crop.right*r,f=i-e.crop.bottom*i;e.rect=[u,h,d-u,f-h].map(g=>g.toFixed(0)).join(","),delete e.crop}e.hotspot&&typeof e.hotspot!="string"&&(e["fp-x"]=e.hotspot.x,e["fp-y"]=e.hotspot.y,delete e.hotspot),(!e.format||e.format==="auto")&&(e.format==="auto"&&delete e.format,e.auto="format"),e.fit==="contain"&&!e.bg&&(e.bg="ffffff");const a=dl(e),o=n.split("-").slice(1),c=o.pop(),l=o.join("-")+"."+c+(a?"?"+a:"");return{url:Ai(hl,t,s,l)}},ml=Object.freeze(Object.defineProperty({__proto__:null,getImage:gl},Symbol.toStringTag,{value:"Module"})),Vn=$n({keyMap:{width:"w",height:"h",format:"fm",quality:"q",position:"position",fit:"fit"},valueMap:{fit:{fill:"fill",cover:"cover",contain:"contain"},format:{avif:"avif",gif:"gif",jpg:"jpg",jpeg:"jpg",png:"png",webp:"webp"},position:{top:"top",right:"right",bottom:"bottom",left:"left",center:"center"}},joinWith:"&",formatter:(n,e)=>bo(n,e)}),pl=(n,{modifiers:e={},baseURL:t}={})=>{const s={...e};s.url=n,e.width&&(s.width=e.width.toString()),e.height&&(s.height=e.height.toString());const i=Vn(s);return{url:`${t||"/.netlify/images"}?${i}`}},yl=Object.freeze(Object.defineProperty({__proto__:null,getImage:pl,operationsGenerator:Vn},Symbol.toStringTag,{value:"Module"})),El=(n,{modifiers:e={}}={})=>{const t=n,s=e.width||"5",i=e.time||"0";return{url:`https://image.mux.com${t}/thumbnail.webp?time=${i}&width=${s}`}},vl=Object.freeze(Object.defineProperty({__proto__:null,getImage:El},Symbol.toStringTag,{value:"Module"})),Kn={screens:{320:320,640:640,768:768,1024:1024,1280:1280,1536:1536,1920:1920,2560:2560,3200:3200,3201:3201,xs:320,sm:640,md:768,lg:1024,xl
190:1280,xxl:1536,"2xl":1536},presets:{},provider:"netlify",domains:[],alias:{},densities:[1,2],format:["webp"]};Kn.providers={sanity:{provider:ml,defaults:{projectId:"6j7wi2c9"}},netlify:{provider:yl,defaults:{}},mux:{provider:vl,defaults:void 0}};const Hn=()=>{const n=wn(),e=ot();return e.$img||e._img||(e._img=rl({...Kn,nuxt:{baseURL:n.app.baseURL},runtimeConfig:n}))};function Tl(n){var e;(e=performance==null?void 0:performance.mark)==null||e.call(performance,"mark_feature_usage",{detail:{feature:n}})}const Sl={src:{type:String,required:!1},format:{type:String,required:!1},quality:{type:[Number,String],required:!1},background:{type:String,required:!1},fit:{type:String,required:!1},modifiers:{type:Object,required:!1},preset:{type:String,required:!1},provider:{type:String,required:!1},sizes:{type:[Object,String],required:!1},densities:{type:String,required:!1},preload:{type:[Boolean,Object],required:!1},width:{type:[String,Number],required:!1},height:{type:[String,Number],required:!1},alt:{type:String,required:!1},referrerpolicy:{type:String,required:!1},usemap:{type:String,required:!1},longdesc:{type:String,required:!1},ismap:{type:Boolean,required:!1},loading:{type:String,required:!1,validator:n=>["lazy","eager"].includes(n)},crossorigin:{type:[Boolean,String],required:!1,validator:n=>["anonymous","use-credentials","",!0,!1].includes(n)},decoding:{type:String,required:!1,validator:n=>["async","auto","sync"].includes(n)},nonce:{type:[String],required:!1}},xl=n=>{const e=le(()=>({provider:n.provider,preset:n.preset})),t=le(()=>({width:Ne(n.width),height:Ne(n.height),alt:n.alt,referrerpolicy:n.referrerpolicy,usemap:n.usemap,longdesc:n.longdesc,ismap:n.ismap,crossorigin:n.crossorigin===!0?"anonymous":n.crossorigin||void 0,loading:n.loading,decoding:n.decoding,nonce:n.nonce})),s=Hn(),i=le(()=>({...n.modifiers,width:Ne(n.width),height:Ne(n.height),format:n.format,quality:n.quality||s.options.quality,background:n.background,fit:n.fit}));return{options:e,attrs:t,modifiers:i}},Al={...Sl,placeholder:{type:[Boolean,String,Number,Array],required:!1},placeholderClass:{type:String,required:!1},custom:{type:Boolean,required:!1}},Ll=["src"],Wn=Li({__name:"NuxtImg",props:Al,emits:["load","error"],setup(n,{emit:e}){const t=n,s=_o(),i=e,r=!1,a=Hn(),o=xl(t),c=Ae(!1),l=Ae(),u=le(()=>a.getSizes(t.src,{...o.options.value,sizes:t.sizes,densities:t.densities,modifiers:{...o.modifiers.value,width:Ne(t.width),height:Ne(t.height)}})),h=le(()=>{const E={...o.attrs.value,"data-nuxt-img":""};return(!t.placeholder||c.value)&&(E.sizes=u.value.sizes,E.srcset=u.value.srcset),E}),d=le(()=>{let E=t.placeholder;if(E===""&&(E=!0),!E||c.value)return!1;if(typeof E=="string")return E;const T=Array.isArray(E)?E:typeof E=="number"?[E,E]:[10,10];return a(t.src,{...o.modifiers.value,width:T[0],height:T[1],quality:T[2]||50,blur:T[3]||3},o.options.value)}),f=le(()=>t.sizes?u.value.src:a(t.src,o.modifiers.value,o.options.value)),g=le(()=>d.value?d.value:f.value),p=ot().isHydrating;return Ut(()=>{if(d.value||t.custom){const E=new Image;f.value&&(E.src=f.value),t.sizes&&(E.sizes=u.value.sizes||"",E.srcset=u.value.srcset),E.onload=T=>{c.value=!0,i("load",T)},E.onerror=T=>{i("error",T)},Tl("nuxt-image");return}l.value&&(l.value.complete&&p&&(l.value.getAttribute("data-error")?i("error",new Event("error")):i("load",new Event("load"))),l.value.onload=E=>{i("load",E)},l.value.onerror=E=>{i("error",E)})}),(E,T)=>E.custom?On(E.$slots,"default",Do(tr({key:1},{...ue(r)?{onerror:"this.setAttribute('data-error', 1)"}:{},imgAttrs:{...h.value,...ue(s)},isLoaded:c.value,src:g.value}))):(qe(),Rs("img",tr({key:0,ref_key:"imgEl",ref:l,class:d.value&&!c.value?E.placeholderClass:void 0},{...ue(r)?{onerror:"this.setAttribute('data-error', 1)"}:{},...h.value,...ue(s)},{src:g.value}),null,16,Ll))}}),Il="640:320px 768:640px 1024:768px 1280:1024px 1536:1280px 1920:1536px 2560:1920px 3200:2560px 3201:3200px",Rl={__name:"Img",props:{src:String,alt:String,media:Object,width:Number,classNames:[String,Array,Object],width:Number,preload:{type:Boolean,default:!1},lazy:{type:Boolean,default:!1}},setup(n){const{$urlFor:e}=ot(),t=n,s=le(()=>e(t.src).rect(r.value.cropLeft||0,r.value.cropTop||0,r.value.width,r.value.height).width(10).blur(10).quality(10).auto("format").url()),i=le(()=>{var c,l;return t.media.hotspot?{x:((c=t.media.hotspot)==null?void 0:c.x)*100,y:((l=t.media.hotspot)==null?void 0:l.y)*100}:{x:50,y:50}}),r=le(()=>{var p,E,T,v,S,x;const c=t.media.dimensions.width,l=t.media.dimensions.height,u=Math.floor(c*((p=t.media.crop)==null?void 0:p.left)),h=Math.floor(l*((E=t.media.crop)==null?void 0:E.top)),d=Math.floor(c-c*((T
190=t.media.crop)==null?void 0:T.left)-c*((v=t.media.crop)==null?void 0:v.right)),f=Math.floor(l-l*((S=t.media.crop)==null?void 0:S.top)-l*((x=t.media.crop)==null?void 0:x.bottom));return{width:d||c,height:f||l,cropLeft:u,cropTop:h}}),a=le(()=>({crop:t.media.crop||"",hotspot:t.media.hotspot||""})),o=`aspect-ratio:${r.value.width/r.value.height}; object-position: ${i.value.x}% ${i.value.y}%`;return(c,l)=>{const u=Wn;return qe(),Ct(u,{provider:"sanity",preload:!!(n.preload&&!n.lazy),loading:!n.preload&&n.lazy?"lazy":"eager",placeholder:ue(s),"placeholder-class":"placeholder-active",width:n.width?n.width:ue(r).width,height:n.width?"":ue(r).height,densities:"x1",src:n.src,modifiers:ue(a),alt:n.alt||"SVR PR",class:ds([n.classNames,{portrait:ue(r).width<ue(r).height,landscape:ue(r).width>ue(r).height}]),style:o,sizes:n.width?!1:Il},null,8,["preload","loading","placeholder","width","height","src","modifiers","alt","class","sizes"])}}},bl=Mn(Rl,[["__scopeId","data-v-8dd7c72c"]]),M=Number.isFinite||function(n){return typeof n=="number"&&isFinite(n)},_l=Number.isSafeInteger||function(n){return typeof n=="number"&&Math.abs(n)<=Dl},Dl=Number.MAX_SAFE_INTEGER||9007199254740991;let U=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",
vendor: 21,235 bytes, line 190
190n.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 X={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},N={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class ut{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 Cl{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 ut(e),this.fast_=new ut(t),this.defaultTTFB_=i,this.ttfb_=new ut(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new ut(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new ut(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new ut(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 kl(n,e,t){return(e=wl(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 lr(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 te(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?lr(Object(t),!0).forEach(function(s){kl(n,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):lr(Object(t)).forEach(function(s){Object.defineProperty(n,s,Object.getOwnPropertyDescriptor(t,s))})}return n}function Pl(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 wl(n){var e=Pl(n,"string");return typeof e=="symbol"?e:e+""}class je{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=Ze,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 Ze=function(){},Ol={trace:Ze,debug:Ze,log:Ze,warn:Ze,info:Ze,error:Ze};function ri(){return re({},Ol)}function Ml(n,e){const t=self.console[n];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${n}] >`):Ze}function cr(n,e,t){return e[n]?e[n].bind(e):Ml(n,t)}const ni=ri();function Fl(n,e,t){const s=ri();if(typeof console=="object"&&n===!0||typeof n=="object"){const i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=cr(r,n,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.2`)}catch{return ri()}i.forEach(r=>{ni[r]=cr(r,n)})}else re(ni,s);return s}const Q=ni;function et(n=!0){return typeof self>"u"?void 0:(n||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Nl(n){return typeof self<"u"&&n===self.ManagedMediaSource}function Yn(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 Le(n,e=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(n);if(e){const u=l.indexOf("\0");return u!==-1?l.substring(0,u):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}const Oe={hexDump:function(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 Bl(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Ps={exports:{}},ur;function Ul(){return ur||(ur=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,u){if(u=u||{},c=c.trim(),l=l.trim(),!l){if(!u.alwaysNormalize)return c;var h=o.parseURL(c);if(!h)throw new Error("Error trying to parse base URL.");return h.path=o.normalizePath(h.path),o.buildURLFromParts(h)}var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return u.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):l;var f=o.parseURL(c);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=i.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var y={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(y.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)y.path=f.path,d.params||(y.params=f.params,d.query||(y.query=f.query));else{var p=f.path,E=p.substring(0,p.lastIndexOf("/")+1)+d.path;y.path=o.normalizePath(E)}return y.path===null&&(y.path=u.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(y)},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})()}(Ps)),Ps.exports}var Ri=Ul();class bi{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 ie={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class qn{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,Gl(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={[ie.AUDIO]:null,[ie.VIDEO]:null,[ie.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 bi),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Ri.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ie.AUDIO]=null,e[ie.VIDEO]=null,e[ie.AUDIOVIDEO]=null}}function ge(n){return n.sn!=="initSegment"}class ws extends qn{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){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(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const s=Object.keys(this.levelkeys);if(s.length===1)return this._decryptdata=this.levelkeys[s[0]].getDecryptData(this.sn)}}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){const t=Object.keys(this.levelkeys),s=t.length;if(s>1||s===1&&this.levelkeys[t[0]].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 ge(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,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 $l extends qn{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 jn(n,e){const t=Object.getPrototypeOf(n);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||jn(t,e)}}function Gl(n,e){const t=jn(n,e);t&&(t.enumerable=!0,Object.defineProperty(n,e,t))}const gs=Math.pow(2,32)-1,Vl=[].push,zn={video:1,audio:2,id3:3,text:4};function ce(n){return String.fromCharCode.apply(null,n)}function Xn(n,e){const t=n[e]<<8|n[e+1];return t<0?65536+t:t}function V(n,e){const t=Qn(n,e);return t<0?4294967296+t:t}function hr(n,e){let t=V(n,e);return t*=Math.pow(2,32),t+=V(n,e+4),t}function Qn(n,e){return n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3]}function Os(n,e,t){n[e]=t>>24,n[e+1]=t>>16&255,n[e+2]=t>>8&255,n[e+3]=t&255}function Kl(n){const e=n.byteLength;for(let t=0;t<e;){const s=V(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 Y(n,e){const t=[];if(!e.length)return t;const s=n.byteLength;for(let i=0;i<s;){const r=V(n,i),a=ce(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=Y(n.subarray(i+8,o),e.slice(1));c.length&&Vl.apply(t,c)}i=o}return t}function Hl(n){const e=[],t=n[0];let s=8;const i=V(n,s);s+=4;let r=0,a=0;t===0?(r=V(n,s),a=V(n,s+4),s+=8):(r=hr(n,s),a=hr(n,s+8),s+=16),s+=2;let o=n.length+a;const c=Xn(n,s);s+=2;for(let l=0;l<c;l++){let u=s;const h=V(n,u);u+=4;const d=h&2147483647;if((h&2147483648)>>>31===1)return Q.warn("SIDX has hierarchical references (not supported)"),null;const g=V(n,u);u+=4,e.push({referenceSize:d,subsegmentDuration:g,info:{duration:g/i,start:o,end:o+d-1}}),o+=d,u+=4,s=u}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:c,references:e}}function Zn(n){const e=[],t=Y(n,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],a=Y(r,["tkhd"])[0];if(a){let o=a[0];const c=V(a,o===0?12:20),l=Y(r,["mdia","mdhd"])[0];if(l){o=l[0];const u=V(l,o===0?12:20),h=Y(r,["mdia","hdlr"])[0];if(h){const d=ce(h.subarray(8,12)),f={soun:ie.AUDIO,vide:ie.VIDEO}[d],g=Y(r,["mdia","minf","stbl","stsd"])[0],y=Wl(g);f?(e[c]={timescale:u,type:f,stsd:y},e[f]=te({timescale:u,id:c},y)):e[c]={timescale:u,type:d,stsd:y}}}}}return Y(n,["moov","mvex","trex"]).forEach(i=>{const r=V(i,4),a=e[r];a&&(a.default={duration:V(i,12),flags:V(i,20)})}),e}function Wl(n){const e=n.subarray(8),t=e.subarray(86),s=ce(e.subarray(4,8));let i=s,r;const a=s==="enca"||s==="encv";if(a){const l=Y(e,[s])[0].subarray(s==="enca"?28:78);Y(l,["sinf"]).forEach(h=>{const d=Y(h,["schm"])[0];if(d){const f=ce(d.subarray(4,8));if(f==="cbcs"||f==="cenc"){const g=Y(h,["frma"])[0];g&&(i=ce(g))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const c=Y(t,["avcC"])[0];c&&c.length>3&&(i+="."+Kt(c[1])+Kt(c[2])+Kt(c[3]),r=Vt(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=Y(e,[s])[0],l=Y(c.subarray(28),["esds"])[0];if(l&&l.length>7){let u=4;if(l[u++]!==3)break;u=Ms(l,u),u+=2;const h=l[u++];if(h&128&&(u+=2),h&64&&(u+=l[u++]),l[u++]!==4)break;u=Ms(l,u);const d=l[u++];if(d===64)i+="."+Kt(d);else break;if(u+=12,l[u++]!==5)break;u=Ms(l,u);const f=l[u++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((l[u]&224)>>5)),i+="."+g}break}case"hvc1":case"hev1":{const c=Y(t,["hvcC"])[0];if(c&&c.length>12){const l=c[1],u=["","A","B","C"][l>>6],h=l&31,d=V(c,2),f=(l&32)>>5?"H":"L",g=c[12],y=c.subarray(6,12);i+="."+u+h,i+="."+d.toString(16).toUpperCase(),i+="."+f+g;let p="";for(let E=y.length;E--;){const T=y[E];(T||p)&&(p="."+T.toString(16).toUpperCase()+p)}i+=p}r=Vt(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=Vt(i,t)||i;break}case"vp09":{const c=Y(t,["vpcC"])[0];if(c&&c.length>6){const l=c[4],u=c[5],h=c[6]>>4&15;i+="."+we(l)+"."+we(u)+"."+we(h)}break}case"av01":{const c=Y(t,["av1C"])[0];if(c&&c.length>2){const l=c[1]>>>5,u=c[1]&31,h=c[2]>>>7?"H":"M",d=(c[2]&64)>>6,f=(c[2]&32)>>5,g=l===2&&d?f?12:10:d?10:8,y=(c[2]&16)>>4,p=(c[2]&8)>>3,E=(c[2]&4)>>2,T=c[2]&3;i+="."+l+"."+we(u)+h+"."+we(g)+"."+y+"."+p+E+T+"."+we(1)+"."+we(1)+"."+we(1)+"."+0,r=Vt("dav1",t)}break}}return{codec:i,encrypted:a,supplemental:r}}function Vt(n,e){const t=Y(e,["dvvC"]),s=t.length?t[0]:Y(e,["dvcC"])[0];if(s){const i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return n+"."+we(i)+"."+we(r)}}function Ms(n,e){const t=e+5;for(;n[e++]&128&&e<t;);return e}function Kt(n){return("0"+n.toString(16).toUpperCase()).slice(-2)}function we(n){return(n<10?"0":"")+n}function Yl(n,e){if(!n||!e)return n;const t=e.keyId;return t&&e.isCommonEncryption&&Y(n,["moov","trak"]).forEach(i=>{const a=Y(i,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=Y(a,["enca"]);const c=o.length>0;c||(o=Y(a,["encv"])),o.forEach(l=>{const u=c?l.subarray(28):l.subarray(78);Y(u,["sinf"]).forEach(d=>{const f=Jn(d);if(f){const g=f.subarray(8,24);g.some(y=>y!==0)||(Q.log(`[eme] Patching keyId in 'enc${c?"a":"v"}>sinf>>tenc' box: ${Oe.hexDump(g)} -> ${Oe.hexDump(t)}`),f.set(t,8))}})})}),n}function Jn(n){const e=Y(n,["schm"])[0];if(e){const t=ce(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return Y(n,["schi","tenc"])[0]}return null}function ql(n,e){return Y(e,["moof","traf"]).reduce((t,s)=>{const i=Y(s,["tfdt"])[0],r=i[0],a=Y(s,["tfhd"]).reduce((o,c)=>{const l=V(c,4),u=n[l];if(u){let h=V(i,4);if(r===1){if(h===gs)return Q.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;h*=gs+1,h+=V(i,8)}const d=u.timescale||9e4,f=h/d;if(M(f)&&(o===null||f<o))return f}return o},null);return a!==null&&M(a)&&(t===null||a<t)?a:t},null)}function jl(n,e){let t=0,s=0,i=0;const r=Y(n,["moof","traf"]);for(let a=0;a<r.length;a++){const o=r[a],c=Y(o,["tfhd"])[0],l=V(c,4),u=e[l];if(!u)continue;const h=u.default,d=V(c,0)|(h==null?void 0:h.flags);let f=h==null?void 0:h.duration;d&8&&(d&2?f=V(c,12):f=V(c,8));const g=u.timescale||9e4,y=Y(o,["trun"]);for(let p=0;p<y.length;p++){if(t=zl(y[p]),!t&&f){const E=V(y[p],4);t=f*E}u.type===ie.VIDEO?s+=t/g:u.type===ie.AUDIO&&(i+=t/g)}}if(s===0&&i===0){let a=1/0,o=0,c=0;const l=Y(n,["sidx"]);for(let u=0;u<l.length;u++){const h=Hl(l[u]);if(h!=null&&h.references){a=Math.min(a,h.earliestPresentationTime/h.timescale);const d=h.references.reduce((f,g)=>f+g.info.duration||0,0);o=Math.max(o,d+h.earliestPresentationTime/h.timescale),c=o-a}}if(c&&M(c))return c}return s||i}function zl(n){const e=V(n,0);let t=8;e&1&&(t+=4),e&4&&(t+=4);let s=0;const i=V(n,4);for(let r=0;r<i;r++){if(e&256){const a=V(n,t);s+=a,t+=4}e&512&&(t+=4),e&1024&&(t+=4),e&2048&&(t+=4)}return s}function Xl(n,e,t){Y(e,["moof","traf"]).forEach(s=>{Y(s,["tfhd"]).forEach(i=>{const r=V(i,4),a=n[r];if(!a)return;const o=a.timescale||9e4;
vendor: 4,518 bytes, line 190
190Y(s,["tfdt"]).forEach(c=>{const l=c[0],u=t*o;if(u){let h=V(c,4);if(l===0)h-=u,h=Math.max(h,0),Os(c,4,h);else{h*=Math.pow(2,32),h+=V(c,8),h-=u,h=Math.max(h,0);const d=Math.floor(h/(gs+1)),f=Math.floor(h%(gs+1));Os(c,4,d),Os(c,8,f)}}})})})}function Ql(n){const e={valid:null,remainder:null},t=Y(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 _e(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function dr(n,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let a=!1;return Y(s,["moof"]).map(c=>{const l=c.byteOffset-8;Y(c,["traf"]).map(h=>{const d=Y(h,["tfdt"]).map(f=>{const g=f[0];let y=V(f,4);return g===1&&(y*=Math.pow(2,32),y+=V(f,8)),y/i})[0];return d!==void 0&&(n=d),Y(h,["tfhd"]).map(f=>{const g=V(f,4),y=V(f,0)&16777215,p=(y&1)!==0,E=(y&2)!==0,T=(y&8)!==0;let v=0;const S=(y&16)!==0;let x=0;const _=(y&32)!==0;let A=8;g===r&&(p&&(A+=8),E&&(A+=4),T&&(v=V(f,A),A+=4),S&&(x=V(f,A),A+=4),_&&(A+=4),e.type==="video"&&(a=bs(e.codec)),Y(h,["trun"]).map(b=>{const D=b[0],L=V(b,0)&16777215,k=(L&1)!==0;let O=0;const z=(L&4)!==0,K=(L&256)!==0;let $=0;const F=(L&512)!==0;let G=0;const B=(L&1024)!==0,P=(L&2048)!==0;let w=0;const W=V(b,4);let H=8;k&&(O=V(b,H),H+=4),z&&(H+=4);let j=O+l;for(let Z=0;Z<W;Z++){if(K?($=V(b,H),H+=4):$=v,F?(G=V(b,H),H+=4):G=x,B&&(H+=4),P&&(D===0?w=V(b,H):w=Qn(b,H),H+=4),e.type===ie.VIDEO){let ee=0;for(;ee<G;){const ne=V(s,j);if(j+=4,Zl(a,s[j])){const Ee=s.subarray(j,j+ne);_i(Ee,a?2:1,n+w/i,t)}j+=ne,ee+=ne+4}}n+=$/i}}))})})}),t}function bs(n){if(!n)return!1;const e=n.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Zl(n,e){if(n){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function _i(n,e,t,s){const i=ea(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 u=r;if(o<l)r+=o;else if(o>l){Q.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(a===4){if(i[u++]===181){const d=Xn(i,u);if(u+=2,d===49){const f=V(i,u);if(u+=4,f===1195456820){const g=i[u++];if(g===3){const y=i[u++],p=31&y,E=64&y,T=E?2+p*3:0,v=new Uint8Array(T);if(E){v[0]=y;for(let S=1;S<T;S++)v[S]=i[u++]}s.push({type:g,payloadType:a,pts:t,bytes:v})}}}}}else if(a===5&&o>16){const h=[];for(let g=0;g<16;g++){const y=i[u++].toString(16);h.push(y.length==1?"0"+y:y),(g===3||g===5||g===7||g===9)&&h.push("-")}const d=o-16,f=new Uint8Array(d);for(let g=0;g<d;g++)f[g]=i[u++];s.push({payloadType:a,pts:t,uuid:h.join(""),userData:Le(f),userDataBytes:f})}}}function ea(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 Jl(n){const e=n[0];let t="",s="",i=0,r=0,a=0,o=0,c=0,l=0;if(e===0){for(;ce(n.subarray(l,l+1))!=="\0";)t+=ce(n.subarray(l,l+1)),l+=1;for(t+=ce(n.subarray(l,l+1)),l+=1;ce(n.subarray(l,l+1))!=="\0";)s+=ce(n.subarray(l,l+1)),l+=1;s+=ce(n.subarray(l,l+1)),l+=1,i=V(n,12),r=V(n,16),o=V(n,20),c=V(n,24),l=28}else if(e===1){l+=4,i=V(n,l),l+=4;const h=V(n,l);l+=4;const d=V(n,l);for(l+=4,a=2**32*h+d,_l(a)||(a=Number.MAX_SAFE_INTEGER,Q.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=V(n,l),l+=4,c=V(n,l),l+=4;ce(n.subarray(l,l+1))!=="\0";)t+=ce(n.subarray(l,l+1)),l+=1;for(t+=ce(n.subarray(l,l+1)),l+=1;ce(n.subarray(l,l+1))!=="\0";)s+=ce(n.subarray(l,l+1)),l+=1;s+=ce(n.subarray(l,l+1)),l+=1}const u=n.subarray(l,n.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:a,presentationTimeDelta:r,eventDuration:o,id:c,payload:u}}function ec(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 tc(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&&t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),ec([112,115,115,104],new Uint8Array([s,0,0,0]),n,r,i,a,t||new Uint8Array)}function sc(n){const e=[];
vendor: 10,264 bytes, line 190
190if(n instanceof ArrayBuffer){const t=n.byteLength;let s=0;for(;s+32<t;){const i=new DataView(n,s),r=ic(i);e.push(r),s+=r.size}}return e}function ic(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=Oe.hexDump(new Uint8Array(a,t+12,16)),c=n.getUint32(28);let l=null,u=null;if(r===0){if(e-32<c||c<22)return{offset:t,size:e};u=new Uint8Array(a,t+32,c)}else if(r===1){if(!c||s<t+32+c*16+16)return{offset:t,size:e};l=[];for(let h=0;h<c;h++)l.push(new Uint8Array(a,t+32+h*16,16))}return{version:r,systemId:o,kids:l,data:u,offset:t,size:e}}const ta=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),vt={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 sa(n,e){const t=vt[e];return!!t&&!!t[n.slice(0,4)]}function ai(n,e,t=!0){return!n.split(",").some(s=>!ia(s,e,t))}function ia(n,e,t=!0){var s;const i=et(t);return(s=i==null?void 0:i.isTypeSupported(kt(n,e)))!=null?s:!1}function kt(n,e){return`${e}/mp4;codecs=${n}`}function fr(n){if(n){const e=n.substring(0,4);return vt.video[e]}return 2}function ms(n){const e=ta();return n.split(",").reduce((t,s)=>{const r=e&&bs(s)?9:vt.video[s];return r?(r*2+t)/(t?3:2):(vt.audio[s]+t)/(t?2:1)},0)}const Fs={};function rc(n,e=!0){if(Fs[n])return Fs[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(ia(t[i],"audio",e))return Fs[n]=t[i],t[i];if(t[i]==="mp3"&&(s=et(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return n}const nc=/flac|opus|mp4a\.40\.34/i;function ps(n,e=!0){return n.replace(nc,t=>rc(t.toLowerCase(),e))}function ac(n,e){const t=[];if(n){const s=n.split(",");for(let i=0;i<s.length;i++)sa(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function rs(n,e){if(n&&(n.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(n)!==-1))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 oc(n){const e=n.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");if(s.length>2){let i=s.shift()+".";i+=parseInt(s.shift()).toString(16),i+=("000"+parseInt(s.shift()).toString(16)).slice(-4),e[t]=i}}return e.join(",")}function lc(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 gr(n){const e=et(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 ra(n){return n.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const na={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function aa(n,e){return{supported:!1,configurations:e,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:n}}const mr={};function cc(n,e,t,s,i,r){const a=n.audioCodec?n.audioGroups:null,o=r==null?void 0:r.audioCodec,c=r==null?void 0:r.channels,l=c?parseInt(c):o?1/0:2;let u=null;if(a!=null&&a.length)try{a.length===1&&a[0]?u=e.groups[a[0]].channels:u=a.reduce((h,d)=>{if(d){const f=e.groups[d];if(!f)throw new Error(`Audio track group ${d} not found`);Object.keys(f.channels).forEach(g=>{h[g]=(h[g]||0)+f.channels[g]})}return h},{2:0})}catch{return!0}return n.videoCodec!==void 0&&(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(l)&&Object.keys(u).some(h=>parseInt(h)>l)}function oa(n,e,t){const s=n.videoCodec,i=n.audioCodec;if(!s&&!i||!t)return Promise.resolve(na);const r=[];if(s){const a={width:n.width,height:n.height,bitrate:Math.ceil(Math.max(n.bitrate*.9,n.averageBitrate)),framerate:n.frameRate||30},o=n.videoRange;o!=="SDR"&&(a.transferFunction=o.toLowerCase());const c=s.split(","),l=navigator.userAgent;if(c.some(u=>bs(u))&&ta())return Promise.resolve(aa(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: (${l})`),r));r.push.apply(r,c.map(u=>({type:"media-source",video:te(te({},a),{},{contentType:kt(lc(u),"video")})})))}return i&&n.audioGroups&&n.audioGroups.forEach(a=>{var o;a&&((o=e.groups[a])==null||o.tracks.forEach(c=>{if(c.groupId===a){const l=c.channels||"",u=parseFloat(l);M(u)&&u>2&&r.push.apply(r,i.split(",").map(h=>({type:"media-source",audio:{contentType:kt(h,"audio"),channels:""+u}})))}}))}),Promise.all(r.map(a=>{const o=uc(a);return mr[o]||(mr[o]=t.decodingInfo(a))})).then(a=>({supported:!a.some(o=>!o.supported),configurations:r,decodingInfoResults:a})).catch(a=>({supported:!1,configurations:r,decodingInfoResults:[],error:a}))}function uc(n){const{audio:e,video:t}=n,s=t||e;if(s){const i=ra(s.contentType);if(t)return`r${t.height}x${t.width}f${Math.ceil(t.framerate)}${t.transferFunction||"sd"}_${i}_${Math.ceil(t.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${i}`}return""}const oi=["NONE","TYPE-0","TYPE-1",null];function hc(n){return oi.indexOf(n)>-1}const ys=["SDR","PQ","HLG"];function dc(n){return!!n&&ys.indexOf(n)>-1}var ns={No:"",Yes:"YES",v2:"v2"};function pr(n){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=n,i=s<e/2;return e&&i?t?ns.v2:ns.Yes:ns.No}class yr{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 Pt{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 Er(this._audioGroups,e)}hasSubtitleGroup(e){return Er(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 Er(n,e){return!e||!n?!1:n.indexOf(e)!==-1}function fc(){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 gc(n,e){let t=!1,s=[];if(n&&(t=n!=="SDR",s=[n]),e){s=e.allowedVideoRanges||ys.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&fc(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const mc=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}},ae=(n,e)=>JSON.stringify(n,mc(e));function pc(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 u=!1,h=!1,d=1/0,f=1/0,g=1/0,y=1/0,p=0,E=[];const{preferHDR:T,allowedVideoRanges:v}=gc(e,i);for(let b=r.length;b--;){const D=n[r[b]];u||(u=D.channels[2]>0),d=Math.min(d,D.minHeight),f=Math.min(f,D.minFramerate),g=Math.min(g,D.minBitrate),v.filter(k=>D.videoRanges[k]>0).length>0&&(h=!0)}d=M(d)?d:0,f=M(f)?f:0;const S=Math.max(1080,d),x=Math.max(30,f);g=M(g)?g:t,t=Math.max(g,t),h||(e=void 0);const _=r.length>1;return{codecSet:r.reduce((b,D)=>{const L=n[D];if(D===b)return b;if(E=h?v.filter(k=>L.videoRanges[k]>0):[],_){if(L.minBitrate>t)return Pe(D,`min bitrate of ${L.minBitrate} > current estimate of ${t}`),b;if(!L.hasDefaultAudio)return Pe(D,"no renditions with default or auto-select sound found"),b;if(o&&D.indexOf(o.substring(0,4))%5!==0)return Pe(D,`audio codec preference "${o}" not found`),b;if(a&&!l){if(!L.channels[a])return Pe(D,`no renditions with ${a}
190 channel sound found (channels options: ${Object.keys(L.channels)})`),b}else if((!o||l)&&u&&L.channels[2]===0)return Pe(D,"no renditions with stereo sound found"),b;if(L.minHeight>S)return Pe(D,`min resolution of ${L.minHeight} > maximum of ${S}`),b;if(L.minFramerate>x)return Pe(D,`min framerate of ${L.minFramerate} > maximum of ${x}`),b;if(!E.some(k=>L.videoRanges[k]>0))return Pe(D,`no variants with VIDEO-RANGE of ${ae(E)} found`),b;if(c&&D.indexOf(c.substring(0,4))%5!==0)return Pe(D,`video codec preference "${c}" not found`),b;if(L.maxScore<p)return Pe(D,`max score of ${L.maxScore} < selected max of ${p}`),b}return b&&(ms(D)>=ms(b)||L.fragmentError>n[b].fragmentError)?b:(y=L.minIndex,p=L.maxScore,D)},void 0),videoRanges:E,preferHDR:T,minFramerate:f,minBitrate:g,minIndex:y}}function Pe(n,e){Q.log(`[abr] start candidates with "${n}" ignored because ${e}`)}function la(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 yc(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(u=>{if(!u)return;const h=e.groups[u];h&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(h.channels).forEach(d=>{c.channels[d]=(c.channels[d]||0)+h.channels[d]}))}),i},{})}function vr(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 Be(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(at(n,i,t))return s}return-1}function at(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||Ec(r,e.lang))&&(r===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in n)||vc(n.characteristics||"",e.characteristics))&&(t===void 0||t(n,e))}function Ec(n,e="--"){return n.length===e.length?n===e:n.startsWith(e)||e.startsWith(n)}function vc(n,e=""){const t=n.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function nt(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 Tc(n,e,t,s,i){const r=e[s],o=e.reduce((d,f,g)=>{const y=f.uri;return(d[y]||(d[y]=[])).push(g),d},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const c=r.videoRange,l=r.frameRate,u=r.codecSet.substring(0,4),h=Tr(e,s,d=>{if(d.videoRange!==c||d.frameRate!==l||d.codecSet.substring(0,4)!==u)return!1;const f=d.audioGroups,g=t.filter(y=>!f||f.indexOf(y.groupId)!==-1);return Be(n,g,i)>-1});return h>-1?h:Tr(e,s,d=>{const f=d.audioGroups,g=t.filter(y=>!f||f.indexOf(y.groupId)!==-1);return Be(n,g,i)>-1})}function Tr(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 Es(n,e){var t;return!!n&&n!==((t=e.loadLevelObj)==null?void 0:t.uri)}class Sc extends je{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.co
vendor: 8,008 bytes, lines 190-200
190decTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,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(),u=r?r.stats:i.stats,h=r?r.duration:i.duration,d=l-u.loading.start,f=a.minAutoLevel,g=i.level,y=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const p=y>-1&&y!==g,E=!!t||p;if(!E&&(c.paused||!c.playbackRate||!c.readyState))return;const T=a.mainForwardBufferInfo;if(!E&&T===null)return;const v=this.bwEstimator.getEstimateTTFB(),S=Math.abs(c.playbackRate);if(d<=Math.max(v,1e3*(h/(S*2))))return;const x=T?T.len/S:0,_=u.loading.first?u.loading.first-u.loading.start:-1,A=u.loaded&&_>-1,b=this.getBwEstimate(),D=a.levels,L=D[g],k=Math.max(u.loaded,Math.round(h*(i.bitrate||L.averageBitrate)/8));let O=A?d-_:d;O<1&&A&&(O=Math.min(d,u.loaded*8/b));const z=A?u.loaded*1e3/O:0,K=v/1e3,$=z?(k-u.loaded)/z:k*8/b+K;if($<=x)return;const F=z?z*8:b,G=((s=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,B=this.hls.config.abrBandWidthUpFactor;let P=Number.POSITIVE_INFINITY,w;for(w=g-1;w>f;w--){const Z=D[w].maxBitrate,ee=!D[w].details||G;if(P=this.getTimeToLoadFrag(K,F,h*Z,ee),P<Math.min(x,h+K))break}if(P>=$||P>h*10)return;A?this.bwEstimator.sample(d-Math.min(v,_),u.loaded):this.bwEstimator.sampleTTFB(d);const W=D[w].maxBitrate;this.getBwEstimate()*B>W&&this.resetEstimator(W);const H=this.findBestLevel(W,f,w,0,x,1,1);H>-1&&(w=H),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;
191      Fragment duration: ${i.duration.toFixed(3)}
192      Time to underbuffer: ${x.toFixed(3)} s
193      Estimated load time for current fragment: ${$.toFixed(3)} s
194      Estimated load time for down switch fragment: ${P.toFixed(3)} s
195      TTFB estimate: ${_|0} ms
196      Current BW estimate: ${M(b)?b|0:"Unknown"} bps
197      New BW estimate: ${this.getBwEstimate()|0} bps
198      Switching to level ${w} @ ${W|0} bps`),a.nextLoadLevel=a.nextAutoLevel=w,this.clearTimer();const j=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===w&&w>0){const Z=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${w>0?"and switching down":""}
199      Fragment duration: ${i.duration.toFixed(3)} s
200      Time to underbuffer: ${Z.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,w>f){let ee=this.findBestLevel(this.hls.levels[f].bitrate,f,w,0,Z,1,1);ee===-1&&(ee=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=ee,this.resetEstimator(this.hls.levels[ee].bitrate)}}};p||$>P*2?j():this.timer=self.setInterval(j,P*1e3),a.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new Cl(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=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const 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 h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(h,l),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,s,i){const 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===N.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!==N.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()}
200_${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 u=r.abrBandWidthFactor,h=r.abrBandWidthUpFactor;if(l){const p=this.findBestLevel(c,a,i,l,0,u,h);if(p>=0)return this.rebufferNotice=-1,p}let d=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const p=this.bitrateTestDelay;p&&(d=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-p,this.info(`bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),u=h=1)}const f=this.findBestLevel(c,a,i,l,d,u,h);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const g=s.levels[a],y=s.loadLevelObj;return y&&(g==null?void 0:g.bitrate)<y.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,u=this.lastLoadedFragLevel,h=u===-1?this.hls.firstLevel:u,{fragCurrent:d,partCurrent:f}=this,{levels:g,allAudioTracks:y,loadLevel:p,config:E}=this.hls;if(g.length===1)return 0;const T=g[h],v=!!((c=this.hls.latestLevelDetails)!=null&&c.live),S=p===-1||u===-1;let x,_="SDR",A=(T==null?void 0:T.frameRate)||0;const{audioPreference:b,videoPreference:D}=E,L=this.audioTracksByGroup||(this.audioTracksByGroup=la(y));let k=-1;if(S){if(this.firstSelection!==-1)return this.firstSelection;const F=this.codecTiers||(this.codecTiers=yc(g,L,t,s)),G=pc(F,_,e,b,D),{codecSet:B,videoRanges:P,minFramerate:w,minBitrate:W,minIndex:H,preferHDR:j}=G;k=H,x=B,_=j?P[P.length-1]:P[0],A=w,e=Math.max(e,W),this.log(`picked start tier ${ae(G)}`)}else x=T==null?void 0:T.codecSet,_=T==null?void 0:T.videoRange;const O=f?f.duration:d?d.duration:0,z=this.bwEstimator.getEstimateTTFB()/1e3,K=[];for(let F=s;F>=t;F--){var $;const G=g[F],B=F>h;if(!G)continue;
vendor: 56,341 bytes, line 200
200if(E.useMediaCapabilities&&!G.supportedResult&&!G.supportedPromise){const ee=navigator.mediaCapabilities;typeof(ee==null?void 0:ee.decodingInfo)=="function"&&(cc(G,L,_,A,e,b)||bs(G.videoCodec))?(G.supportedPromise=oa(G,L,ee),G.supportedPromise.then(ne=>{if(!this.hls)return;G.supportedResult=ne;const Ee=this.hls.levels,ve=Ee.indexOf(G);ne.error?this.warn(`MediaCapabilities decodingInfo error: "${ne.error}" for level ${ve} ${ae(ne)}`):ne.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ve} ${ae(ne)}`),ve>-1&&Ee.length>1&&(this.log(`Removing unsupported level ${ve}`),this.hls.removeLevel(ve),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))})):G.supportedResult=na}if((x&&G.codecSet!==x||_&&G.videoRange!==_||B&&A>G.frameRate||!B&&A>0&&A<G.frameRate||G.supportedResult&&!(($=G.supportedResult.decodingInfoResults)!=null&&$[0].smooth))&&(!S||F!==k)){K.push(F);continue}const P=G.details,w=(f?P==null?void 0:P.partTarget:P==null?void 0:P.averagetargetduration)||O;let W;B?W=o*e:W=a*e;const H=O&&i>=O*2&&r===0?G.averageBitrate:G.maxBitrate,j=this.getTimeToLoadFrag(z,W,H*w,P===void 0);if(W>=H&&(F===u||G.loadError===0&&G.fragmentError===0)&&(j<=z||!M(j)||v&&!this.bitrateTestDelay||j<l)){const ee=this.forcedAutoLevel;return F!==p&&(ee===-1||ee!==p)&&(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}" ${_}`),this.info(`switch candidate:${h}->${F} adjustedbw(${Math.round(W)})-bitrate=${Math.round(W-H)} ttfb:${z.toFixed(1)} avgDuration:${w.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${j.toFixed(1)} firstSelection:${S} codecSet:${G.codecSet} videoRange:${G.videoRange} hls.loadLevel:${p}`)),S&&(this.firstSelection=F),F}}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 Di={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 xc(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;t=t||0;for(let r=0;r<n.length;++r){const a=n[r];if(Lc(e,t,a))return a}return null}function lt(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)&&Sr(t,s,r)===0||Ac(r,n,Math.min(i,s))))return r;const a=Di.search(e,Sr.bind(null,t,s));return a&&(a!==n||!r)?a:r}function Ac(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 Sr(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 Lc(n,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>n}function ca(n,e){return Di.search(n,t=>t.cc<e?1:t.cc>e?-1:0)}function Ic(n,e,t){if(n&&n.startCC<=e&&n.endCC>=e){const s=t.start,i=t.end;let r=n.fragments;if(!t.relurl){const{fragmentHint:a}=n;a&&(r=r.concat(a))}return Di.search(r,a=>a.cc<e||a.end<=s?1:a.cc>e||a.start>=i?-1:0)}return null}function vs(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 xr(n,e){const t=vs(e);return n.default[`${t?"timeout":"error"}Retry`]}function Ci(n,e){const t=n.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*n.retryDelayMs,n.maxRetryDelayMs)}function Ar(n){return te(te({},n),{errorRetry:null,timeoutRetry:null})}function Ts(n,e,t,s){if(!n)return!1;const i=s==null?void 0:s.code,r=e<n.maxNumRetry&&(Rc(i)||!!t);return n.shouldRetry?n.shouldRetry(n,e,t,s,r):r}function Rc(n){return n===0&&navigator.onLine===!1||!!n&&(n<400||n>499)}var ye={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},ke={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2};class bc extends je{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},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,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===N.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}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=wt();return}case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ye.SendAlternateToPenaltyBox;return}case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:{var a,o;const l=t.parent===N.MAIN?t.level:i.loadLevel;t.details===R.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(o=a.levelDetails)!=null&&o.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l))}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 l=i.loadLevelObj;if(l&&(r.type===X.AUDIO_TRACK&&l.hasAudioGroup(r.groupId)||r.type===X.SUBTITLE_TRACK&&l.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=ye.SendAlternateToPenaltyBox,t.errorAction.flags=ke.MoveAllAlternatesMatchingHost;return}}return;case R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const l=i.loadLevelObj,u=l==null?void 0:l.attrs["HDCP-LEVEL"];u?t.errorAction={action:ye.SendAlternateToPenaltyBox,flags:ke.MoveAllAlternatesMatchingHDCP,hdcpLevel:u}:this.keySystemError(t)}return;case R.BUFFER_ADD_CODEC_ERROR:case R.REMUX_ALLOC_ERROR:case R.BUFFER_APPEND_ERROR:if(!t.errorAction){var c;t.errorAction=this.getLevelSwitchAction(t,(c=t.level)!=null?c: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=wt();return}t.type===U.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=xr(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(Ts(i,r,vs(e),e.response))return{action:ye.RetryRequest,flags:ke.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(e.details.startsWith("key")?a:r,e),c=t.levels.reduce((u,h)=>u+h.fragmentError,0);if(i&&(e.details!==R.FRAG_GAP&&i.fragmentError++,Ts(o,c,vs(e),e.response)))return{action:ye.RetryRequest,flags:ke.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 u=-1;const{levels:h,loadLevel:d,minAutoLevel:f,maxAutoLevel:g}=s;s.autoLevelEnabled||(s.loadLevel=-1);const y=(r=e.frag)==null?void 0:r.type,E=(y===N.AUDIO&&l===R.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===R.BUFFER_ADD_CODEC_ERROR||l===R.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:_})=>i.audioCodec!==_),v=e.sourceBufferName==="video"&&(l===R.BUFFER_ADD_CODEC_ERROR||l===R.BUFFER_APPEND_ERROR)&&h.some(({codecSet:_,audioCodec:A})=>i.codecSet!==_&&i.audioCodec===A),{type:S,groupId:x}=(a=e.context)!=null?a:{};for(let _=h.length;_--;){const A=(_+d)%h.length;if(A!==d&&A>=f&&A<=g&&h[A].loadError===0){var o,c;const b=h[A];if(l===R.FRAG_GAP&&y===N.MAIN&&e.frag){const D=h[A].details;if(D){const L=lt(e.frag,D.fragments,e.frag.start);if(L!=null&&L.gap)continue}}else{if(S===X.AUDIO_TRACK&&b.hasAudioGroup(x)||S===X.SUBTITLE_TRACK&&b.hasSubtitleGroup(x))continue;if(y===N.AUDIO&&(o=i.audioGroups)!=null&&o.some(D=>b.hasAudioGroup(D))||y===N.SUBTITLE&&(c=i.subtitleGroups)!=null&&c.some(D=>b.hasSubtitleGroup(D))||E&&i.audioCodec===b.audioCodec||!E&&i.audioCodec!==b.audioCodec||v&&i.codecSet===b.codecSet)continue}u=A;break}}if(u>-1&&s.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:ye.SendAlternateToPenaltyBox,flags:ke.None,nextAutoLevel:u}}return{action:ye.SendAlternateToPenaltyBox,flags:ke.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case ye.DoNothing:break;case ye.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,hdcpLevel:r,nextAutoLevel:a}=s;switch(i){case ke.None:this.switchLevel(e,a);break;case ke.MoveAllAlternatesMatchingHDCP:r&&(t.maxHdcpLevel=oi[oi.indexOf(r)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}s.resolved||this.switchLevel(e,a)}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=ra(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===s&&this.hls.removeLevel(r)}}}function wt(n){const e={action:ye.DoNothing,flags:ke.None};return n&&(e.resolved=!0),e}var he={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class _c{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(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.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.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;const a=r.end;if(r.start<=e&&a!==null&&e<=a)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(u=>{const h=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return h&&this.removeFragment(c.body),h})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,i=ht(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],u=a||c.partial===!0;r.range[o]=this.getBufferedTimes(s,e.part,u,l)}),r.loaded=null,Object.keys(r.range).length?(r.buffered=!0,(r.body.endList=s.endList||r.body.endList)&&(this.endListFragments[r.body.type]=r),Ht(r)||this.removeParts(s.sn-1,s.type)):this.removeFragment(r.body)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Lr(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=ht(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},a=e.start,o=e.end,c=e.minEndPTS||o,l=e.maxStartPTS||a;for(let u=0;u<i.length;u++){const h=i.start(u)-this.bufferPadding,d=i.end(u)+this.bufferPadding;if(l>=h&&c<=d){r.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(o,i.end(u))});break}else if(a<d&&o>h){const f=Math.max(a,i.start(u)),g=Math.min(o,i.end(u));g>f&&(r.partial=!0,r.time.push({startPTS:f,endPTS:g}))}else if(o<=h)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 u=c[l];u&&Ht(u)&&(i=u.body.start-o,r=u.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),a<=s&&(t=u.body,a=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Ht(t))}getState(e){const t=ht(e),s=this.fragments[t];return s?s.buffered?Ht(s)?he.PARTIAL:he.OK:he.APPENDING:he.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=ht(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=ht(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=ht(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=Lr(s,r=>r.fragment.sn!==i)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e,t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const s=(e=this.hls)==null||(t=e.latestLevelDetails)==null?void 0:t.partList;s&&s.forEach(i=>i.clearElementaryStreamInfo())}}function Ht(n){var e,t,s;return n.buffered&&(n.body.gap||((e=n.range.video)==null?void 0:e.partial)||((t=n.range.audio)==null?void 0:t.partial)||((s=n.range.audiovideo)==null?void 0:s.partial))}function ht(n){return`${n.type}_${n.level}_${n.sn}`}function Lr(n,e){return n.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var tt={cbc:0,ctr:1};class Dc{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 tt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case tt.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 Cc(n){const e=n.byteLength,t=e&&new DataView(n.buffer).getUint8(e-1);return t?n.slice(0,e-t):n}class kc{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],u=c[1],h=c[2],d=c[3],f=new Uint32Array(256);let g=0,y=0,p=0;for(p=0;p<256;p++)p<128?f[p]=p<<1:f[p]=p<<1^283;for(p=0;p<256;p++){let E=y^y<<1^y<<2^y<<3^y<<4;E=E>>>8^E&255^99,e[g]=E,t[E]=g;const T=f[g],v=f[T],S=f[v];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=S*16843009^v*65537^T*257^g*16843008,l[E]=x<<24|x>>>8,u[E]=x<<16|x>>>16,h[E]=x<<8|x>>>24,d[E]=x,g?(g=T^f[f[f[S^T]]],y^=f[f[y]]):g=y=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),u=this.invKeySchedule=new Uint32Array(a),h=this.sBox,d=this.rcon,f=this.invSubMix,g=f[0],y=f[1],p=f[2],E=f[3];let T,v;for(o=0;o<a;o++){if(o<r){T=l[o]=t[o];continue}v=T,o%r===0?(v=v<<8|v>>>24,v=h[v>>>24]<<24|h[v>>>16&255]<<16|h[v>>>8&255]<<8|h[v&255],v^=d[o/r|0]<<24):r>6&&o%r===4&&(v=h[v>>>24]<<24|h[v>>>16&255]<<16|h[v>>>8&255]<<8|h[v&255]),l[o]=T=(l[o-r]^v)>>>0}for(c=0;c<a;c++)o=a-c,c&3?v=l[o]:v=l[o-4],c<4||o<=4?u[c]=v:u[c]=g[h[v>>>24]]^y[h[v>>>16&255]]^p[h[v>>>8&255]]^E[h[v&255]],u[c]=u[c]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,c=o[0],l=o[1],u=o[2],h=o[3],d=this.uint8ArrayToUint32Array_(s);let f=d[0],g=d[1],y=d[2],p=d[3];const E=new Int32Array(e),T=new Int32Array(E.length);let v,S,x,_,A,b,D,L,k,O,z,K,$,F;const G=this.networkToHostOrderSwap;for(;t<E.length;){for(k=G(E[t]),O=G(E[t+1]),z=G(E[t+2]),K=G(E[t+3]),A=k^r[0],b=K^r[1],D=z^r[2],L=O^r[3],$=4,F=1;F<i;F++)v=c[A>>>24]^l[b>>16&255]^u[D>>8&255]^h[L&255]^r[$],S=c[b>>>24]^l[D>>16&255]^u[L>>8&255]^h[A&255]^r[$+1],x=c[D>>>24]^l[L>>16&255]^u[A>>8&255]^h[b&255]^r[$+2],_=c[L>>>24]^l[A>>16&255]^u[b>>8&255]^h[D&255]^r[$+3],A=v,b=S,D=x,L=_,$=$+4;v=a[A>>>24]<<24^a[b>>16&255]<<16^a[D>>8&255]<<8^a[L&255]^r[$],S=a[b>>>24]<<24^a[D>>16&255]<<16^a[L>>8&255]<<8^a[A&255]^r[$+1],x=a[D>>>24]<<24^a[L>>16&255]<<16^a[A>>8&255]<<8^a[b&255]^r[$+2],_=a[L>>>24]<<24^a[A>>16&255]<<16^a[b>>8&255]<<8^a[D&255]^r[$+3],T[t]=G(v^f),T[t+1]=G(_^g),T[t+2]=G(x^y),T[t+3]=G(S^p),f=k,g=O,y=z,p=K,t=t+4}return T.buffer}}class Pc{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=wc(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function wc(n){switch(n){case tt.cbc:return"AES-CBC";case tt.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${n}`)}}const Oc=16;class ki{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?Cc(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!==tt.cbc||t.byteLength!==16)return Q.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=_e(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 kc),l.expandKey(t);const u=a;return this.currentResult=l.decrypt(c.buffer,0,s),this.currentIV=c.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Pc(this.subtle,t,i)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Dc(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(Q.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%Oc;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(Q.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Ir=Math.pow(2,17);class Mc{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 He({type:U.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(br(e));return}else e.gap=!1;const l=this.loader=r?new r(i):new a(i),u=Rr(e);e.loader=l;const h=Ar(i.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Ir};e.stats=l.stats;const f={onSuccess:(g,y,p,E)=>{this.resetLoader(e,l);let T=g.data;p.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,y,p,E)=>{this.resetLoader(e,l),c(new He({type:U.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:te({url:s,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:p,stats:E}))},onAbort:(g,y,p)=>{this.resetLoader(e,l),c(new He({type:U.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:p,stats:g}))},onTimeout:(g,y,p)=>{this.resetLoader(e,l),c(new He({type:U.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:p,stats:g}))}};t&&(f.onProgress=(g,y,p,E)=>t({frag:e,part:null,payload:p,networkDetails:E})),l.load(u,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(br(e,t));return}const l=this.loader=r?new r(i):new a(i),u=Rr(e,t);e.loader=l;const h=Ar(i.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ir};t.stats=l.stats,l.load(u,d,{onSuccess:(f,g,y,p)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const E={frag:e,part:t,payload:f.data,networkDetails:p};s(E),o(E)},onError:(f,g,y,p)=>{this.resetLoader(e,l),c(new He({type:U.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:te({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:y,stats:p}))},onAbort:(f,g,y)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new He({type:U.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:y,stats:f}))},onTimeout:(f,g,y)=>{this.resetLoader(e,l),c(new He({type:U.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:y,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),h=(c-l)*Math.round(s.loaded/l);s.total=s.loaded+h}else s.total=Math.max(s.loaded,s.total);const a=s.loading,o=i.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Rr(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"&&Fc((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 br(n,e){const t=new Error(`GAP ${n.gap?"tag":"attribute"} found`),s={type:U.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 He(s)}function Fc(n){return n==="AES-128"||n==="AES-256"}class He extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class ua extends je{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 Pi{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=Wt(),this.buffering={audio:Wt(),video:Wt(),audiovideo:Wt()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=a}}function Wt(){return{start:0,executeStart:0,executeEnd:0,end:0}}const _r={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((u,h)=>u.start-h.start||h.end-u.end);let i=-1,r=[];if(s)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(i=u);const h=r.length;if(h){const d=r[h-1].end;e[u].start-d<s?e[u].end>d&&(r[h-1].end=e[u].end):r.push(e[u])}else r.push(e[u])}else r=e;let a=0,o,c=t,l=t;for(let u=0;u<r.length;u++){const h=r[u].start,d=r[u].end;if(i===-1&&t>=h&&t<=d&&(i=u),t+s>=h&&t<d)c=h,l=d,a=l-t;else if(t+s<h){o=h;break}}return{len:a,start:c||0,end:l||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||_r}catch(t){return Q.log("failed to get media.buffered",t),_r}}}const ha=/\{\$([a-zA-Z0-9-_]+)\}/g;function Dr(n){return ha.test(n)}function li(n,e){if(n.variableList!==null||n.hasVariableRefs){const t=n.variableList;return e.replace(ha,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 Cr(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 Nc(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 Bc=/^(\d+)x(\d+)$/,kr=/(.+?)=(".*?"|.*?)(?:,|$)/g;class oe{constructor(e,t){typeof e=="string"&&(e=oe.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=Bc.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(kr.lastIndex=0;(s=kr.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=li(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":Q.warn(`${e}: attribute ${a} is missing quotes`)}i[a]=o}return i}}const Uc="com.apple.hls.interstitial";function $c(n){return n!=="ID"&&n!=="CLASS"&&n!=="CUE"&&n!=="START-DATE"&&n!=="DURATION"&&n!=="END-DATE"&&n!=="END-ON-NEXT"}function Gc(n){return n==="SCTE35-OUT"||n==="SCTE35-IN"||n==="SCTE35-CMD"}class da{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]){Q.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=re(new oe({}),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?(Q.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===Uc}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 Vc=10;class Kc{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}get hasProgramDateTime(){return this.fragments.length?M(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Vc}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){var e;return(e=this.fragments)!=null&&e.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 pt(n){return n==="AES-128"||n==="AES-256"||n==="AES-256-CTR"}function wi(n){switch(n){case"AES-128":case"AES-256":return tt.cbc;case"AES-256-CTR":return tt.ctr;default:throw new Error(`invalid full segment method ${n}`)}}function Oi(n){return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}function ci(n){return Uint8Array.from(unescape(encodeURIComponent(n)),e=>e.charCodeAt(0))}function Hc(n){const e=ci(n).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Wc(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 Yc(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=Oi(a)):t=Hc(a)}}return t}const Ss=typeof self<"u"?self:void 0;var se={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 Ns(n){switch(n){case Se.FAIRPLAY:return se.FAIRPLAY;case Se.PLAYREADY:return se.PLAYREADY;case Se.WIDEVINE:return se.WIDEVINE;case Se.CLEARKEY:return se.CLEARKEY}}var Yt={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Bs(n){if(n===Yt.WIDEVINE)return se.WIDEVINE;if(n===Yt.PLAYREADY)return se.PLAYREADY;if(n===Yt.CENC||n===Yt.CLEARKEY)return se.CLEARKEY}function Us(n){switch(n){case se.FAIRPLAY:return Se.FAIRPLAY;case se.PLAYREADY:return Se.PLAYREADY;case se.WIDEVINE:return Se.WIDEVINE;case se.CLEARKEY:return Se.CLEARKEY}}function qt(n){const{drmSystems:e,widevineLicenseUrl:t}=n,s=e?[se.FAIRPLAY,se.WIDEVINE,se.PLAYREADY,se.CLEARKEY].filter(i=>!!e[i]):[];return!s[se.WIDEVINE]&&t&&s.push(se.WIDEVINE),s}const fa=function(n){return Ss!=null&&(n=Ss.navigator)!=null&&n.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function qc(n,e,t,s){let i;switch(n){case se.FAIRPLAY:i=["cenc","sinf"];break;case se.WIDEVINE:case se.PLAYREADY:i=["cenc"];break;case se.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${n}`)}return jc(i,e,t,s)}function jc(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 zc(n){var e;return n.sessionType==="persistent-license"||!!((e=n.sessionTypes)!=null&&e.some(t=>t==="persistent-license"))}function ga(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=Oi(o).subarray(0,16);return Wc(c),c}}return null}let jt={};class Ot{static clearKeyUriToKeyIdMap(){jt={}}constructor(e,t,s,i=[1],r=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!pt(e)}isSupported(){if(this.method){if(pt(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["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(pt(this.method)&&this.uri&&!this.iv){typeof e!="number"&&(Q.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const s=Xc(e);return new Ot(this.method,this.uri,"identity",this.keyFormatVersions,s)}const t=Yc(this.uri);if(t)switch(this.keyFormat){case Se.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Se.PLAYREADY:{const s=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=tc(s,null,t),this.keyId=ga(t);break}default:{let s=t.subarray(0,16);if(s.length!==16){const i=new Uint8Array(16);i.set(s,16-s.length),s=i}this.keyId=s;break}}if(!this.keyId||this.keyId.byteLength!==16){let s=jt[this.uri];if(!s){const i=Object.keys(jt).length%Number.MAX_SAFE_INTEGER;s=new Uint8Array(16),new DataView(s.buffer,12,4).setUint32(0,i),jt[this.uri]=s}this.keyId=s}return this}}function Xc(n){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=n>>8*(15-t)&255;return e}const Pr=/#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,wr=/#EXT-X-MEDIA:(.*)/g,Qc=/^#EXT(?:INF|-X-TARGETDURATION):/m,$s=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Zc=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 Ue{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 Ri.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Qc.test(e)}static parseMasterPlaylist(e,t){const s=Dr(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];Pr.lastIndex=0;let a;for(;(a=Pr.exec(e))!=null;)if(a[1]){var o;const l=new oe(a[1],i),u=li(i,a[2]),h={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:Ue.resolve(u,t)},d=l.decimalResolution("RESOLUTION");d&&(h.width=d.width,h.height=d.height),Fr(l.CODECS,h);const f=l["SUPPLEMENTAL-CODECS"];f&&(h.supplemental={},Fr(f,h.supplemental)),(o=h.unknownCodecs)!=null&&o.length||r.push(h),i.levels.push(h)}else if(a[3]){const l=a[3],u=a[4];switch(l){case"SESSION-DATA":{const h=new oe(u,i),d=h["DATA-ID"];d&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[d]=h);break}case"SESSION-KEY":{const h=Or(u,t,i);h.encrypted&&h.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(h)):Q.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const h=new oe(u,i);Cr(i,h,t)}break}case"CONTENT-STEERING":{const h=new oe(u,i);i.contentSteering={uri:Ue.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=Mr(u);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(wr.lastIndex=0;(i=wr.exec(e))!==null;){const l=new oe(i[1],s),u=l.TYPE;if(u){const h=o[u],d=r[u]||[];r[u]=d;const f=l.LANGUAGE,g=l["ASSOC-LANGUAGE"],y=l.CHANNELS,p=l.CHARACTERISTICS,E=l["INSTREAM-ID"],T={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||f||"",type:u,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:f,url:l.URI?Ue.resolve(l.URI,t):""};if(g&&(T.assocLang=g),y&&(T.channels=y),p&&(T.characteristics=p),E&&(T.instreamId=E),h!=null&&h.length){const v=Ue.findGroup(h,T.groupId)||h[0];Nr(T,v,"audioCodec"),Nr(T,v,"textCodec")}d.push(T)}}return r}static parseLevelPlaylist(e,t,s,i,r,a){var o;const c={url:t},l=new Kc(t),u=l.fragments,h=[];let d=null,f=0,g=0,y=0,p=0,E=0,T=null,v=new ws(i,c),S,x,_,A=-1,b=!1,D=null,L;if($s.lastIndex=0,l.m3u8=e,l.hasVariableRefs=Dr(e),((o=$s.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(S=$s.exec(e))!==null;){b&&(b=!1,v=new ws(i,c),v.playlistOffset=y,v.start=y,v.sn=f,v.cc=p,E&&(v.bitrate=E),v.level=s,d&&(v.initSegment=d,d.rawProgramDateTime&&(v.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),D&&(v.setByteRange(D),D=null)));const K=S[1];if(K){v.duration=parseFloat(K);const $=(" "+S[2]).slice(1);v.title=$||null,v.tagList.push($?["INF",K,$]:["INF",K])}else if(S[3]){if(M(v.duration)){v.playlistOffset=y,v.start=y,_&&Ur(v,_,l),v.sn=f,v.level=s,v.cc=p,u.push(v);const $=(" "+S[3]).slice(1);v.relurl=li(l,$),ui(v,T,h),T=v,y+=v.duration,f++,g=0,b=!0}}else{if(S=S[0].match(Zc),!S){Q.warn("No matches on slow regex match for level playlist!");continue}for(x=1;x<S.length&&S[x]===void 0;x++);const $=(" "+S[x]).slice(1),F=(" "+S[x+1]).slice(1),G=S[x+2]?(" "+S[x+2]).slice(1):null;switch($){case"BYTERANGE":T?v.setByteRange(F,T):v.setByteRange(F);break;case"PROGRAM-DATE-TIME":v.rawProgramDateTime=F,v.tagList.push(["PROGRAM-DATE-TIME",F]),A===-1&&(A=u.length);break;case"PLAYLIST-TYPE":l.type&&Ve(l,$,S),l.type=F.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?Ve(l,$,S):u.length>0&&$r(l,$,S),f=l.startSN=parseInt(F);break;case"SKIP":{l.skippedSegments&&Ve(l,$,S);const B=new oe(F,l),P=B.decimalInteger("SKIPPED-SEGMENTS");if(M(P)){l.skippedSegments+=P;for(let W=P;W--;)u.push(null);f+=P}const w=B.enumeratedString("RECENTLY-REMOVED-DATERANGES");w&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(w.split("	")));break}case"TARGETDURATION":l.targetduration!==0&&Ve(l,$,S),l.targetduration=Math.max(parseInt(F),1);break;case"VERSION":l.version!==null&&Ve(l,$,S),l.version=parseInt(F);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Ve(l,$,S),l.live=!1;break;case"#":(F||G)&&v.tagList.push(G?[F,G]:[F]);break;case"DISCONTINUITY":p++,v.tagList.push(["DIS"]);break;case"GAP":v.gap=!0,v.tagList.push([$]);break;case"BITRATE":v.tagList.push([$,F]),E=parseInt(F)*1e3,M(E)?v.bitrate=E:E=0;break;case"DATERANGE":{const B=new oe(F,l),P=new da(B,l.dateRanges[B.ID],l.dateRangeTagCount);l.dateRangeTagCount++,P.isValid||l.skippedSegments?l.dateRanges[P.id]=P:Q.warn(`Ignoring invalid DATERANGE tag: "${F}"`),v.tagList.push(["EXT-X-DATERANGE",F]);break}case"DEFINE":{{const B=new oe(F,l);"IMPORT"in B?Nc(l,B,a):Cr(l,B,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?Ve(l,$,S):u.length>0&&$r(l,$,S),l.startCC=p=parseInt(F);break;case"KEY":{const B=Or(F,t,l);if(B.isSupported()){if(B.method==="NONE"){_=void 0;break}_||(_={}),_[B.keyFormat]&&(_=re({},_)),_[B.keyFormat]=B}else Q.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${F}"`);break}case"START":l.startTimeOffset=Mr(F);break;case"MAP":{const B=new oe(F,l);if(v.duration){const P=new ws(i,c);Br(P,B,s,_),d=P,v.initSegment=d,d.rawProgramDateTime&&!v.rawProgramDateTime&&(v.rawProgramDateTime=d.rawProgramDateTime)}else{const P=v.byteRangeEndOffset;if(P){const w=v.byteRangeStartOffset;D=`${P-w}@${w}`}else D=null;Br(v,B,s,_),d=v,b=!0}d.cc=p;break}case"SERVER-CONTROL":{L&&Ve(l,$,S),L=new oe(F),l.canBlockReload=L.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=L.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&L.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=L.optionalFloat("PART-HOLD-BACK",0),l.holdBack=L.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&Ve(l,$,S);const B=new oe(F);l.partTarget=B.decimalFloatingPoint("PART-TARGET");break}case"PART":{let B=l.partList;B||(B=l.partList=[]);const P=g>0?B[B.length-1]:void 0,w=g++,W=new oe(F,l),H=new $l(W,v,c,w,P);B.push(H),v.duration+=H.duration;break}case"PRELOAD-HINT":{const B=new oe(F,l);l.preloadHint=B;break}case"RENDITION-REPORT":{const B=new oe(F,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(B);break}default:Q.warn(`line parsed but not handled: ${S}`);break}}}T&&!T.relurl?(u.pop(),y-=T.duration,l.partList&&(l.fragmentHint=T)):l.partList&&(ui(v,T,h),v.cc=p,l.fragmentHint=v,_&&Ur(v,_,l)),l.targetduration||(l.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const k=u.length,O=u[0],z=u[k-1];if(y+=l.skippedSegments*l.targetduration,y>0&&k&&z){l.averagetargetduration=y/k;const K=z.sn;l.endSN=K!=="initSegment"?K:0,l.live||(z.endList=!0),O&&l.startCC===void 0&&(l.startCC=O.cc),A>0&&(eu(u,A),O&&h.unshift(O))}else l.endSN=0,l.startCC=0;return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,h.length&&l.dateRangeTagCount&&O&&ma(h,l),l.endCC=p,l}}function ma(n,e){const t=n.length,s=n[t-1],i=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let a=r.length;a--;){const o=e.dateRanges[r[a]],c=o.startDate.getTime();o.tagAnchor=s.ref;for(let l=t;l--;){const u=Jc(e,c,n,l,i);if(u!==-1){o.tagAnchor=e.fragments[u].ref;break}}}}function Jc(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,u=n.fragments;if(u.length>t.length){const d=(t[s+1]||u[u.length-1]).sn-n.startSN;for(let f=d;f>l;f--){const g=u[f].programDateTime;if(e>=g&&e<g+u[f].duration*1e3)return f}}return l}}}return-1}function Or(n,e,t){var s,i;const r=new oe(n,t),a=(s=r.METHOD)!=null?s:"",o=r.URI,c=r.hexadecimalInteger("IV"),l=r.KEYFORMATVERSIONS,u=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!c&&Q.error(`Invalid IV: ${r.IV}`);const h=o?Ue.resolve(o,e):"",d=(l||"1").split("/").map(Number).filter(Number.isFinite);return new Ot(a,h,u,d,c)}function Mr(n){const t=new oe(n).decimalFloatingPoint("TIME-OFFSET");return M(t)?t:null}function Fr(n,e){let t=(n||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const i=t.filter(r=>sa(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 Nr(n,e,t){const s=e[t];s&&(n[t]=s)}function eu(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 ui(n,e,t){n.rawProgramDateTime?t.push(n):e!=null&&e.programDateTime&&(n.programDateTime=e.endProgramDateTime)}function Br(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 Ur(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 Ve(n,e,t){n.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function $r(n,e,t){n.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Gs(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 pa(n,e,t,s,i,r){s-t<=0&&(Q.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let o=t,c=s;const l=e.startPTS,u=e.endPTS;if(M(l)){const p=Math.abs(l-t);M(e.deltaPTS)?e.deltaPTS=Math.max(p,e.deltaPTS):e.deltaPTS=p,o=Math.max(t,l),t=Math.min(t,l),i=Math.min(i,e.startDTS),c=Math.min(s,u),s=Math.max(s,u),r=Math.max(r,e.endDTS)}const h=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=o,e.startDTS=i,e.endPTS=s,e.minEndPTS=c,e.endDTS=r;const d=e.sn;if(!n||d<n.startSN||d>n.endSN)return 0;let f;const g=d-n.startSN,y=n.fragments;for(y[g]=e,f=g;f>0;f--)Gs(y[f],y[f-1]);for(f=g;f<y.length-1;f++)Gs(y[f],y[f+1]);return n.fragmentHint&&Gs(y[y.length-1],n.fragmentHint),n.PTSKnown=n.alignedSliding=!0,h}function tu(n,e){if(n===e)return;let t=null;const s=n.fragments;for(let c=s.length-1;c>=0;c--){const l=s[c].initSegment;if(l){t=l;break}}n.fragmentHint&&delete n.fragmentHint.endPTS;let i;ru(n,e,(c,l,u,h)=>{if(!e.startCC&&l.cc!==c.cc){var d,f;const g=c.cc-l.cc;for(let y=u;y<h.length;y++)h[y].cc+=g;e.startCC=(d=(f=va(n,e.startSN-1))==null?void 0:f.cc)!=null?d:h[0].cc,e.endCC=h[h.length-1].cc}M(c.startPTS)&&M(c.endPTS)&&(l.setStart(l.startPTS=c.startPTS),l.startDTS=c.startDTS,l.maxStartPTS=c.maxStartPTS,l.endPTS=c.endPTS,l.endDTS=c.endDTS,l.minEndPTS=c.minEndPTS,l.setDuration(c.endPTS-c.startPTS),l.duration&&(i=l),e.PTSKnown=e.alignedSliding=!0),c.hasStreams&&(l.elementaryStreams=c.elementaryStreams),l.loader=c.loader,c.hasStats&&(l.stats=c.stats),c.initSegment&&(l.initSegment=c.initSegment,t=c.initSegment)});const r=e.fragments,a=e.fragmentHint?r.concat(e.fragmentHint):r;if(t&&a.forEach(c=>{var l;c&&(!c.initSegment||c.initSegment.relurl===((l=t)==null?void 0:l.relurl))&&(c.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=r.some(c=>!c),e.deltaUpdateFailed){Q.warn("[level-helper] Previous playlist missing segments ski
200pped in delta playlist");for(let c=e.skippedSegments;c--;)r.shift();e.startSN=r[0].sn}else{e.endCC=r[r.length-1].cc,e.canSkipDateRanges&&(e.dateRanges=su(n.dateRanges,e));const c=n.fragments.filter(l=>l.rawProgramDateTime);if(n.hasProgramDateTime&&!e.hasProgramDateTime)for(let l=1;l<a.length;l++)a[l].programDateTime===null&&ui(a[l],a[l-1],c);ma(c,e)}iu(n.partList,e.partList,(c,l)=>{l.elementaryStreams=c.elementaryStreams,l.stats=c.stats}),i?pa(e,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS):ya(n,e),r.length&&(e.totalduration=e.edge-r[0].start),e.driftStartTime=n.driftStartTime,e.driftStart=n.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const c=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=c),e.driftEndTime=o,e.driftEnd=c}else e.driftEndTime=n.driftEndTime,e.driftEnd=n.driftEnd,e.advancedDateTime=n.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=n.requestScheduled)}function su(n,e){const{dateRanges:t,recentlyRemovedDateranges:s}=e,i=re({},n);s&&s.forEach(o=>{delete i[o]});const a=Object.keys(i).length;return a&&Object.keys(t).forEach(o=>{const c=i[o],l=new da(t[o].attr,c);l.isValid?(i[o]=l,c||(l.tagOrder+=a)):Q.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ae(t[o].attr)}"`)}),i}function iu(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 ru(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 u=c[a+l];let h=o[l];if(s&&!h&&u&&(h=e.fragments[l]=u),u&&h){if(t(u,h,l,o),u.url&&u.url!==h.url){e.playlistParsingError=Gr(`media sequence mismatch ${h.sn}:`,n,e,u,h);return}else if(u.cc!==h.cc){e.playlistParsingError=Gr(`discontinuity sequence mismatch (${u.cc}!=${h.cc})`,n,e,u,h);return}}}}function Gr(n,e,t,s,i){return new Error(`${n} ${i.url}
201Playlist starting @${e.startSN}
202${e.m3u8}
203
204Playlist starting @${t.startSN}
205${t.m3u8}`)}function ya(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;hi(e,a)}function hi(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 Ea(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 va(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 Vr(n,e,t){return n?Ta(n.partList,e,t):null}function Ta(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 Sa(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 bt(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 nu(n,e){return!!(n&&e.startCC<n.endCC&&e.endCC>n.startCC)}function Kr(n,e){if(n){const t=n.start+e;n.start=n.startPTS=t,n.endPTS=t+n.duration}}function xa(n,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)Kr(t[s],n);e.fragmentHint&&Kr(e.fragmentHint,n),e.alignedSliding=!0}function au(n,e){n&&(Aa(e,n),!e.alignedSliding&&n&&xs(e,n),!e.alignedSliding&&n&&!e.skippedSegments&&ya(n,e,!1))}function Aa(n,e){if(!nu(e,n))return;const t=Math.min(e.endCC,n.endCC),s=bt(e.fragments,t),i=bt(n.fragments,t);if(!s||!i)return;Q.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const r=s.start-i.start;xa(r,n)}function xs(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=bt(s,a),r=bt(t,a)),(!i||!r)&&(i=s[Math.floor(s.length/2)],r=bt(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);xa(l,n)}const ou={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}},C={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 Mi extends ua{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=C.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:a,fragCurrent:o,media:c,mediaBuffer:l,state:u}=this,h=c?c.currentTime:0,d=q.bufferInfo(l||c,h,a.maxBufferHole);if(this.log(`media seeking to ${M(h)?h.toFixed(3):h}, state: ${u}`),this.state===C.ENDED)this.resetLoadingState();else if(o){const f=a.maxFragLookUpTolerance,g=o.start-f,y=o.start+o.duration+f;if(!d.len||y<d.start||g>d.end){const p=h>y;(h<g||p)&&(p&&o.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(h,1/0,this.playlistType,!0);const f=this.lastCurrentTime;if(h>f&&(this.lastCurrentTime=h),!this.loadingParts){const g=Math.max(d.end,h),y=this.shouldLoadParts(this.getLevelDetails(),g);y&&(this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${g.toFixed(2)}`),this.loadingParts=y)}}!this.hls.hasEnoughToStart&&!d.len&&(this.log(`setting startPosition to ${h} because of seek before start`),this.nextLoadPosition=this.startPosition=h),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 Mc(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new ki(e.config)}registerListeners(){const{hls:e}=this;
vendor: 26,837 bytes, line 205
205e.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===C.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=C.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.nextStart;if(r&&r>i&&r<t.edge||this.media.currentTime<e.start)return!1;const o=t.partList;if(o!=null&&o.length){const l=o[o.length-1];return q.isBuffered(this.media,l.start+l.duration/2)}const c=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(c)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levelLastLoaded)==null?void 0:e.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;s.removeEventListener("seeking",this.onMediaSeeking),s.removeEventListener("ended",this.onMediaEnded),s.addEventListener("seeking",this.onMediaSeeking),s.addEventListener("ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===C.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),i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("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=C.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===C.FRAG_LOADING||!this.fragCurrent&&a===C.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=C.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===C.STOPPED||this.state===C.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)===he.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)===he.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&&pt(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,wi(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:U.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{const u=self.performance.now();return i.trigger(m.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:c,tdecrypt:u}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===C.STOPPED||this.state===C.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!==C.STOPPED&&(this.state=C.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()}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?ou.toString(q.getBuffered(s)):"(detached)"})`),ge(e)){var i;if(e.type!==N.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=C.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=C.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 Pi(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==null?void 0:t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;e.encrypted&&!((r=e.decryptdata)!=null&&r.key)?(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=C.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(m.KEY_LOADED,h),this.state===C.KEY_LOADING&&(this.state=C.IDLE),h}),this.hls.trigger(m.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(e,a.encryptedFragments);const c=this.fragPrevious;if(ge(e)&&(!c||e.sn!==c.sn)){const h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${e.sn}`),this.loadingParts=h)}if(s=Math.max(e.start,s||0),this.loadingParts&&ge(e)){const h=a.partList;if(h&&i){s>e.end&&a.fragmentHint&&(e=a.fragmentHint);const d=this.getNextPart(h,e,s);if(d>-1){const f=h[d];e=this.fragCurrent=f.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${f.index} (${d}/${h.length-1}) of ${this.fragInfo(e,!1,f)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=C.FRAG_LOADING;let g;return o?g=o.then(y=>!y||this.fragContextChanged(y.frag)?null:this.doFragPartsLoad(e,f,t,i)).catch(y=>this.handleFragLoadError(y)):g=this.doFragPartsLoad(e,f,t,i).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:f,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):g}else if(!e.url||this.loadedEndOfParts(h,s))return Promise.resolve(null)}}if(ge(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)}`),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?"["+a.startSN+"-"+a.endSN+"]":""}, target: ${parseFloat(s.toFixed(3))}`),M(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=C.FRAG_LOADING;const l=this.config.progressive;let u;return l&&o?u=o.then(h=>!h||this.fragContextChanged(h==null?void 0:h.frag)?null:this.fragmentLoader.load(e,i)).catch(h=>this.handleFragLoadError(h)):u=Promise.all([this.fragmentLoader.load(e,l?i:void 0),o]).then(([h])=>(!l&&h&&i&&i(h),h)).catch(h=>this.handleFragLoadError(h)),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,u=h=>{this.fragmentLoader.loadPart(e,h,i).then(d=>{c[h.index]=d;const f=d.part;this.hls.trigger(m.FRAG_LOADED,d);const g=Vr(s.details,e.sn,h.index+1)||Ta(l,e.sn,h.index+1);if(g)u(g);else return r({frag:e,part:f,partsLoaded:c})}).catch(a)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===R.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(m.ERROR,t)}else this.hls.trigger(m.ERROR,{type:U.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!==C.PARSING){!this.fragCurrent&&this.state!==C.STOPPED&&this.state!==C.ERROR&&(this.state=C.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!=null&&e.partList){var s;const r=e.partList[0],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?Vr(c,r,a):null,u=l?l.fragment:va(c,r,s);return u?(s&&s!==u&&(u.stats=s.stats),{frag:u,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){var a;if(!e||this.state!==C.PARSING)return;const{data1:o,data2:c}=e;let l=o;if(o&&c&&(l=_e(o,c)),!((a=l)!=null&&a.length))return;const u={type:e.type,frag:t,part:s,chunkMeta:i,parent:t.type,data:l};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=N.MAIN){var s;const i=(s=this.fragmentTracker)==null?void 0:s.getAppendedFrag(e,t);return i&&"fragment"in i?i.fragment:i}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 h=r.initialLiveManifestSize;if(i<h)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${h})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),c=this.getInitialLiveFragment(t,s);const d=this.hls.startPosition,f=this.hls.liveSyncPosition,g=c?(d!==-1&&d>=a?d:f)||c.start:e;this.log(`Setting startPosition to ${g} to match start frag at live edge. mainStart: ${d} liveSyncPosition: ${f} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=g}}else e<=a&&(c=s[0]);if(!c){const h=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,h,t)}let u=this.filterReplacedPrimary(c,t);if(!u&&c){const h=c.sn-t.startSN;u=this.filterReplacedPrimary(s[h+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===he.OK||s===he.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(Hr(this.hls.config)){var e,t;if((e=this.hls.interstitialsManager)==null||(t=e.playingItem)==null?void 0:t.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Hr(this.hls.config)&&e.type!==N.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!=null&&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 u=l.loaded;u?i=-1:(r||l.independent||a)&&l.fragment===t&&(i=o),r=u}return i}loadedEndOfParts(e,t){const s=e[e.length-1];return s&&t>s.start&&s.loaded}getInitialLiveFragment(e,t){const 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=xc(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=ca(t,s.cc),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,u=s.partList,h=!!(this.loadingParts&&u!=null&&u.length&&c);h&&c&&!this.bitrateTest&&u[u.length-1].fragment.sn===c.sn&&(a=a.concat(c),o=c.sn);let d;if(e<t){var f;const y=e<this.lastCurrentTime||e>t-l||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:l;d=lt(r,a,e,y)}else d=a[a.length-1];if(d){const g=d.sn-s.startSN,y=this.fragmentTracker.getState(d);if((y===he.OK||y===he.PARTIAL&&d.gap)&&(r=d),r&&d.sn===r.sn&&(!h||u[0].fragment.sn>d.sn||!s.live&&!h)&&r&&d.level===r.level){const E=a[g+1];d.sn<o&&this.fragmentTracker.getState(E)!==he.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){au(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&&ge(e)&&e.stats.aborted&&(this.warn(`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!==C.FRAG_LOADING_WAITING_RETRY)&&(this.state=C.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const g=this.getCurrentContext(t.chunkMeta);g&&(t.frag=g.frag)}const s=t.frag;if(!s||s.type!==e||!this.levels)return;if(this.fragContextChanged(s)){var i;this.warn(`Frag load error must match current frag to retry ${s.url} > ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const r=t.details===R.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(s,!0);const a=t.errorAction,{action:o,flags:c,retryCount:l=0,retryConfig:u}=a||{},h=!!a&&!!u,d=h&&o===ye.RetryRequest,f=h&&!a.resolved&&c===ke.MoveAllAlternatesMatchingHost;if(!d&&f&&ge(s)&&!s.endList)this.resetFragmentErrors(e),this.treatAsGap(s),a.resolved=!0;else if((d||f)&&l<u.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const g=Ci(u,l);this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${l+1}/${u.maxNumRetry} in ${g}ms`),a.resolved=!0,this.retryDate=self.performance.now()+g,this.state=C.FRAG_LOADING_WAITING_RETRY}else if(u&&a)if(this.resetFragmentErrors(e),l<u.maxNumRetry)!r&&o!==ye.RemoveAlternatePermanently&&(a.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${l})`);return}else o===ye.SendAlternateToPenaltyBox?this.state=C.WAITING_LEVEL:this.state=C.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===C.PARSING||this.state===C.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 is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===N.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==C.STOPPED&&(this.state=C.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=q.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===C.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==C.STOPPED&&(this.state=C.IDLE)}resetStartWhenNotLoaded(e){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const 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.warn(`The loading context changed while buffering fragment ${e.sn} of ${this.playlistLabel()} ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const r=s.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{const u=e.elementaryStreams[l];if(u){const h=u.endPTS-u.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${h})`),c||!1;const d=i?0:pa(r,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:r,level:s,drift:d,type:l,frag:e,start:u.startPTS,end:u.endPTS}),!0}return c},!1)){var o;if(s.fragmentError===0&&this.treatAsGap(e,s),((o=this.transmuxer)==null?void 0:o.error)===null){const c=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(c.message),this.hls.trigger(m.ERROR,{type:U.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:c,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=C.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===N.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.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function Hr(n){return!!n.interstitialsController&&n.enableInterstitialPlayback!==!1}class La{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=lu(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function lu(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 Vs={exports:{}},Wr;function cu(){return Wr||(Wr=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,u){this.fn=c,this.context=l,this.once=u||!1}function r(c,l,u,h,d){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new i(u,h||c,d),g=t?t+l:l;return c._events[g]?c._events[g].fn?c._events[g]=[c._events[g],f]:c._events[g].push(f):(c._events[g]=f,c._eventsCount++),c}function a(c,l){--c._eventsCount===0?c._events=new s:delete c._events[l]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],u,h;if(this._eventsCount===0)return l;for(h in u=this._events)e.call(u,h)&&l.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(u)):l},o.prototype.listeners=function(l){var u=t?t+l:l,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var d=0,f=h.length,g=new Array(f);d<f;d++)g[d]=h[d].fn;return g},o.prototype.listenerCount=function(l){var u=t?t+l:l,h=this._events[u];return h?h.fn?1:h.length:0},o.prototype.emit=function(l,u,h,d,f,g){var y=t?t+l:l;if(!this._events[y])return!1;var p=this._events[y],E=arguments.length,T,v;if(p.fn){switch(p.once&&this.removeListener(l,p.fn,void 0,!0),E){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,u),!0;case 3:return p.fn.call(p.context,u,h),!0;case 4:return p.fn.call(p.context,u,h,d),!0;case 5:return p.fn.call(p.context,u,h,d,f),!0;case 6:return p.fn.call(p.context,u,h,d,f,g),!0}for(v=1,T=new Array(E-1);v<E;v++)T[v-1]=arguments[v];
vendor: 8,842 bytes, line 205
205p.fn.apply(p.context,T)}else{var S=p.length,x;for(v=0;v<S;v++)switch(p[v].once&&this.removeListener(l,p[v].fn,void 0,!0),E){case 1:p[v].fn.call(p[v].context);break;case 2:p[v].fn.call(p[v].context,u);break;case 3:p[v].fn.call(p[v].context,u,h);break;case 4:p[v].fn.call(p[v].context,u,h,d);break;default:if(!T)for(x=1,T=new Array(E-1);x<E;x++)T[x-1]=arguments[x];p[v].fn.apply(p[v].context,T)}}return!0},o.prototype.on=function(l,u,h){return r(this,l,u,h,!1)},o.prototype.once=function(l,u,h){return r(this,l,u,h,!0)},o.prototype.removeListener=function(l,u,h,d){var f=t?t+l:l;if(!this._events[f])return this;if(!u)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===u&&(!d||g.once)&&(!h||g.context===h)&&a(this,f);else{for(var y=0,p=[],E=g.length;y<E;y++)(g[y].fn!==u||d&&!g[y].once||h&&g[y].context!==h)&&p.push(g[y]);p.length?this._events[f]=p.length===1?p[0]:p:a(this,f)}return this},o.prototype.removeAllListeners=function(l){var u;return l?(u=t?t+l:l,this._events[u]&&a(this,u)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,n.exports=o}(Vs)),Vs.exports}var uu=cu(),Fi=Bl(uu);const Mt="1.6.2",Tt={};function hu(){return typeof __HLS_WORKER_BUNDLE__=="function"}function du(){const n=Tt[Mt];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 Tt[Mt]=i,i}function fu(n){const e=Tt[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 Tt[n]=i,i}function gu(n){const e=Tt[n||Mt];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete Tt[n||Mt],i&&self.URL.revokeObjectURL(i),s.terminate()}}function Ia(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 Ni(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 _s(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 Ft(n,e){const t=e;let s=0;for(;Ni(n,e);){s+=10;const i=_s(n,e+6);s+=i,Ia(n,e+10)&&(s+=10),e+=s}if(s>0)return n.subarray(t,t+s)}function mu(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:U.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,u=i[a];let h=a;(o===5||o===29)&&(h-=3);const d=[o<<3|(h&14)>>1,(h&1)<<7|c<<3];return Q.log(`manifest codec:${s}, parsed codec:${l}, channels:${c}, rate:${u} (ADTS object type:${o} sampling index:${a})`),{config:d,samplerate:u,channelCount:c,codec:l,parsedCodec:l,manifestCodec:s}}function Ra(n,e){return n[e]===255&&(n[e+1]&246)===240}function ba(n,e){return n[e+1]&1?7:9}function Bi(n,e){return(n[e+3]&3)<<11|n[e+4]<<3|(n[e+5]&224)>>>5}function pu(n,e){return e+5<n.length}function As(n,e){return e+1<n.length&&Ra(n,e)}function yu(n,e){return pu(n,e)&&Ra(n,e)&&Bi(n,e)<=n.length-e}function Eu(n,e){if(As(n,e)){const t=ba(n,e);if(e+t>=n.length)return!1;const s=Bi(n,e);if(s<=t)return!1;const i=e+s;return i===n.length||As(n,i)}return!1}function _a(n,e,t,s,i){if(!n.samplerate){const r=mu(e,t,s,i);if(!r)return;re(n,r)}}function Da(n){return 1024*9e4/n}function vu(n,e){const t=ba(n,e);if(e+t<=n.length){const s=Bi(n,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function Ca(n,e,t,s,i){const r=Da(n.samplerate),a=s+i*r,o=vu(e,t);let c;if(o){const{frameLength:h,headerLength:d}=o,f=d+h,g=Math.max(0,t+f-e.length);g?(c=new Uint8Array(f-d),c.set(e.subarray(t+d,e.length),0)):c=e.subarray(t+d,t+f);const y={unit:c,pts:a};return g||n.samples.push(y),{sample:y,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 Tu(n,e){return Ni(n,e)&&_s(n,e+6)+10<=n.length-e}function Su(n){if(n.size<2)return;const e=Le(n.data,!0),t=new Uint8Array(n.data.subarray(e.length+1));return{key:n.type,info:e,data:t.buffer}}function xu(n){if(n.size<2)return;if(n.type==="TXXX"){let t=1;const s=Le(n.data.subarray(t),!0);t+=s.length+1;const i=Le(n.data.subarray(t));return{key:n.type,info:s,data:i}}const e=Le(n.data.subarray(1));return{key:n.type,info:"",data:e}}function Au(n){if(n.type==="WXXX"){if(n.size<2)return;let t=1;const s=Le(n.data.subarray(t),!0);t+=s.length+1;const i=Le(n.data.subarray(t));return{key:n.type,info:s,data:i}}const e=Le(n.data);return{key:n.type,info:"",data:e}}function Lu(n){return btoa(String.fromCharCode(...n))}function ka(n,e){if(n<0)return-ka(-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}function Iu(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("/")}function Ru(){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 bu(n){return n instanceof ArrayBuffer?n:n.byteOffset==0&&n.byteLength==n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer}function Ks(n,e=0,t=1/0){return _u(n,e,t,Uint8Array)}function _u(n,e,t,s){const i=Du(n);let r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);const a=Cu(n)?n.byteOffset:0,o=(a+n.byteLength)/r,c=(a+e)/r,l=Math.floor(Math.max(0,Math.min(c,o))),u=Math.floor(Math.min(l+Math.max(t,0),o));return new s(i,l,u-l)}function Du(n){return n instanceof ArrayBuffer?n:n.buffer}function Cu(n){return n&&n.buffer instanceof ArrayBuffer&&n.byteLength!==void 0&&n.byteOffset!==void 0}function ku(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=Le(Ks(n.data,1,s)),r=n.data[2+s],a=n.data.subarray(3+s).indexOf(0);if(a===-1)return;const o=Le(Ks(n.data,3+s,a));let c;return i==="-->"?c=Le(Ks(n.data,4+s+a)):c=bu(n.data.subarray(4+s+a)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=c,e}function Pu(n){return n.type==="PRIV"?Su(n):n.type[0]==="W"?Au(n):n.type==="APIC"?ku(n):xu(n)}function wu(n){const e=String.fromCharCode(n[0],n[1],n[2],n[3]),t=_s(n,4),s=10;return{type:e,size:t,data:n.subarray(s,s+t)}}const zt=10,Ou=10;function Pa(n){let e=0;const t=[];for(;Ni(n,e);){const s=_s(n,e+6);n[e+5]>>6&1&&(e+=zt),e+=zt;const i=e+s;for(;e+Ou<i;){const r=wu(n.subarray(e)),a=Pu(r);a&&t.push(a),e+=r.size+zt}Ia(n,e)&&(e+=zt)}return t}function wa(n){return n&&n.key==="PRIV"&&n.info==="com.apple.streaming.transportStreamTimestamp"}function Mu(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 Ui(n){const e=Pa(n);for(let t=0;t<e.length;t++){const s=e[t];if(wa(s))return Mu(s)}}let xe=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 Me(n="",e=9e4){return{type:n,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class $i{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=_e(this.cachedData,e),this.cachedData=null);let s=Ft(e,0),i=s?s.length:0,r;const a=this._audioTrack,o=this._id3Track,c=s?Ui(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&M(c))&&(this.basePTS=Fu(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:xe.audio
vendor: 30,637 bytes, line 205
205Id3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const u=this.appendFrame(a,e,i);u?(this.frameIndex++,this.lastPTS=u.sample.pts,i+=u.length,r=i):i=l}else Tu(e,i)?(s=Ft(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:xe.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===l&&r!==l){const u=e.slice(r);this.cachedData?this.cachedData=_e(this.cachedData,u):this.cachedData=u}}return{audioTrack:a,videoTrack:Me(),id3Track:o,textTrack:Me()}}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:Me(),id3Track:this._id3Track,textTrack:Me()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Fu=(n,e,t)=>{if(M(n))return n*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let Xt=null;const Nu=[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],Bu=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Uu=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],$u=[0,1,1,4];function Oa(n,e,t,s,i){if(t+24>e.length)return;const r=Ma(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 Ma(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=Nu[c*14+i-1]*1e3,h=Bu[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,f=Uu[t][s],g=$u[s],y=f*8*g,p=Math.floor(f*l/h+a)*g;if(Xt===null){const v=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Xt=v?parseInt(v[1]):0}return!!Xt&&Xt<=87&&s===2&&l>=224e3&&o===0&&(n[e+3]=n[e+3]|128),{sampleRate:h,channelCount:d,frameLength:p,samplesPerFrame:y}}}function Gi(n,e){return n[e]===255&&(n[e+1]&224)===224&&(n[e+1]&6)!==0}function Fa(n,e){return e+1<n.length&&Gi(n,e)}function Gu(n,e){return Gi(n,e)&&4<=n.length-e}function Na(n,e){if(e+1<n.length&&Gi(n,e)){const s=Ma(n,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===n.length||Fa(n,r)}return!1}class Vu extends $i{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=Ft(e,0);let i=(s==null?void 0:s.length)||0;if(Na(e,i))return!1;for(let r=e.length;i<r;i++)if(Eu(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return yu(e,t)}appendFrame(e,t,s){_a(e,this.observer,t,s,e.manifestCodec);const i=Ca(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const Ba=(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 Ku extends $i{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=Ua(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=Ft(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&Ui(t)!==void 0&&Ba(e,s)<16}}function Ua(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,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][c*3+r]*2;if(t+u>e.length)return-1;const h=e[t+6]>>5;let d=0;h===2?d+=2:(h&1&&h!==1&&(d+=2),h&4&&(d+=2));const f=(e[t+6]<<8|e[t+7])>>12-d&1,y=[2,1,2,3,3,4,4,5][h]+f,p=e[t+5]>>3,E=e[t+5]&7,T=new Uint8Array([r<<6|p<<1|E>>2,(E&3)<<6|h<<3|f<<2|c>>4,c<<4&224]),v=1536/o*9e4,S=s+i*v,x=e.subarray(t,t+u);return n.config=T,n.channelCount=y,n.samplerate=o,n.samples.push({unit:x,pts:S}),u}class Hu extends $i{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=Ft(e,0);let s=(t==null?void 0:t.length)||0;if(t&&e[s]===11&&e[s+1]===119&&Ui(t)!==void 0&&Ba(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(Na(e,s))return Q.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Gu(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return Oa(e,t,s,this.basePTS,this.frameIndex)}}const Wu=/\/emsg[-/]ID3/i;class Yu{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=Me("video",1),a=this.audioTrack=Me("audio",1),o=this.txtTrack=Me("text",1);if(this.id3Track=Me("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=Zn(e);if(c.video){const{id:l,timescale:u,codec:h,supplemental:d}=c.video;r.id=l,r.timescale=o.timescale=u,r.codec=h,r.supplemental=d}if(c.audio){const{id:l,timescale:u,codec:h}=c.audio;a.id=l,a.timescale=u,a.codec=h}o.id=zn.text,r.sampleDuration=0,r.duration=a.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return Kl(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=_e(this.remainderData,e));const o=Ql(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const a=this.extractID3Track(i,t);return r.samples=dr(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=dr(e,t),{videoTrack:t,audioTrack:Me(),id3Track:i,textTrack:Me()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=Y(e.samples,["emsg"]);i&&i.forEach(r=>{const a=Jl(r);if(Wu.test(a.schemeIdUri)){const o=Yr(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:xe.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=Yr(a,t);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:xe.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 Yr(n,e){return M(n.presentationTime)?n.presentationTime/n.timeScale:e+n.presentationTimeDelta/n.timeScale}class qu{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new ki(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,tt.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)})}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=ea(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)})}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 $a{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,u,h,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(u=c-r-1,d>=0){const g={data:t.subarray(d,u),type:f};o.push(g)}else{const g=this.getLastNalUnit(e.samples);g&&(a&&c<=4-a&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-a)),u>0&&(g.data=_e(g.data,t.subarray(0,u)),g.state=0))}c<i?(h=this.getNALuType(t,c),d=c,f=h,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=_e(g.data,t))}return e.naluState=r,o}}class _t{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&&Q.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class qr extends $a{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 u,h;switch(l.type){case 1:{let y=!1;o=!0;const p=l.data;if(c&&p.length>4){const E=this.readSliceType(p);(E===2||E===4||E===7||E===9)&&(y=!0)}if(y){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=y;break}case 5:o=!0,(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,_i(l.data,1,s.pts,t.samples);break}case 7:{var f,g;o=!0,c=!0;const y=l.data,p=this.readSPS(y);if(!e.sps||e.width!==p.width||e.height!==p.height||((f=e.pixelRatio)==null?void 0:f[0])!==p.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[1])!==p.pixelRatio[1]){e.width=p.width,e.height=p.height,e.pixelRatio=p.pixelRatio,e.sps=[y];const E=y.subarray(1,4);let T="avc1.";for(let v=0;v<3;v++){let S=E[v].toString(16);S.length<2&&(S="0"+S),T+=S}e.codec=T}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(h=a)!=null&&h.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(l)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new _t(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 _t(e);let s=0,i=0,r=0,a=0,o,c,l;const u=t.readUByte.bind(t),h=t.readBits.bind(t),d=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),y=t.skipEG.bind(t),p=t.skipUEG.bind(t),E=this.skipScalingList.bind(this);u();const T=u();if(h(5),g(3),u(),p(),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),p(),p(),g(1),f())for(c=b!==3?8:12,l=0;l<c;l++)f()&&(l<6?E(16,t):E(64,t))}p();const v=d();if(v===0)d();else if(v===1)for(g(1),y(),y(),o=d(),l=0;l<o;l++)y();p(),g(1);const S=d(),x=d(),_=h(1);_===0&&g(1),g(1),f()&&(s=d(),i=d(),r=d(),a=d());let A=[1,1];if(f()&&f())switch(u()){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=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((S+1)*16-s*2-i*2),height:(2-_)*(x+1)*16-(_?2:4)*(r+a),pixelRatio:A}}}class jr extends $a{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 u,h;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var d;(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 39:o=!0,_i(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,(h=a)!=null&&h.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:o=!1;break}a&&o&&a.units.push(l)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new _t(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 _t(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(),u=t.readUByte(),h=t.readUByte(),d=t.readUByte(),f=t.readUByte(),g=t.readUByte(),y=t.readUByte(),p=t.readUByte(),E=t.readUByte(),T=[],v=[];for(let J=0;J<s;J++)T.push(t.readBoolean()),v.push(t.readBoolean());if(s>0)for(let J=s;J<8;J++)t.readBits(2);for(let J=0;J<s;J++)T[J]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),v[J]&&t.readUByte();t.readUEG();const S=t.readUEG();S==3&&t.skipBits(1);const x=t.readUEG(),_=t.readUEG(),A=t.readBoolean();let b=0,D=0,L=0,k=0;A&&(b+=t.readUEG(),D+=t.readUEG(),L+=t.readUEG(),k+=t.readUEG());const O=t.readUEG(),z=t.readUEG(),K=t.readUEG(),$=t.readBoolean();for(let J=$?0:s;J<=s;J++)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 pe=0;pe<4;pe++)for(let Ie=0;Ie<(pe===3?2:6);Ie++)if(!t.readBoolean())t.readUEG();else{const De=Math.min(64,1<<4+(pe<<1));pe>1&&t.readEG();for(let ct=0;ct<De;ct++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const B=t.readUEG();let P=0;for(let J=0;J<B;J++){let pe=!1;if(J!==0&&(pe=t.readBoolean()),pe){J===B&&t.readUEG(),t.readBoolean(),t.readUEG();let Ie=0;for(let st=0;st<=P;st++){const De=t.readBoolean();let ct=!1;De||(ct=t.readBoolean()),(De||ct)&&Ie++}P=Ie}else{const Ie=t.readUEG(),st=t.readUEG();P=Ie+st;for(let De=0;De<Ie;De++)t.readUEG(),t.readBoolean();for(let De=0;De<st;De++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const J=t.readUEG();for(let pe=0;pe<J;pe++){for(let Ie=0;Ie<K+4;Ie++)t.readBits(1);t.readBits(1)}}let W=0,H=1,j=1,Z=!0,ee=1,ne=0;t.readBoolean(),t.readBoolean();let Ee=!1;if(t.readBoolean()){if(t.readBoolean()){const it=t.readUByte(),Xi=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Gt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];it>0&&it<16?(H=Xi[it-1],j=Gt[it-1]):it===255&&(H=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(),Ee=t.readBoolean(),Ee&&(b+=t.readUEG(),D+=t.readUEG(),L+=t.readUEG(),k+=t.readUEG()),t.readBoolean()&&(ee=t.readBits(32),ne=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Gt=t.readBoolean(),Qi=t.readBoolean();let xt=!1;(Gt||Qi)&&(xt=t.readBoolean(),xt&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),xt&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Zi=0;Zi<=s;Zi++){Z=t.readBoolean();const Lo=Z||t.readBoolean();let Ji=!1;Lo?t.readEG():Ji=t.readBoolean();const er=Ji?1:t.readUEG()+1;if(Gt)for(let At=0;At<er;At++)t.readUEG(),t.readUEG(),xt&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Qi)for(let At=0;At<er;At++)t.readUEG(),t.readUEG(),xt&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),W=t.readUEG())}let ze=x,zi=_;if(A||Ee){let J=1,pe=1;S===1?J=pe=2:S==2&&(J=2),ze=x-J*D-J*b,zi=_-pe*k-pe*L}const xo=i?["A","B","C"][i]:"",Ao=o<<24|c<<16|l<<8|u;let Ds=0;for(let J=0;J<32;J++)Ds=(Ds|(Ao>>J&1)<<31-J)>>>0;let Cs=Ds.toString(16);return a===1&&Cs==="2"&&(Cs="6"),{codecString:`hvc1.${xo}${a}.${Cs}.${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,u],general_constraint_indicator_flags:[h,d,f,g,y,p],general_level_idc:E,bit_depth:O+8,bit_depth_luma_minus8:O,bit_depth_chroma_minus8:z,min_spatial_segmentation_idc:W,chroma_format_idc:S,frame_rate:{fixed:Z,fps:ne/ee}},width:ze,height:zi,pixelRatio:[H,j]}}readPPS(e){const t=new _t(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 de=188;class Je{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=Je.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(de*5,t-de)+1,i=0;for(;i<s;){let r=!1,a=-1,o=0;for(let c=i;c<t;c+=de)if(e[c]===71&&(t-c===de||e[c+de]===71)){if(o++,a===-1&&(a=c,a!==0&&(s=Math.min(a+de*99,e.length-de)+1)),r||(r=di(e,c)===0),r&&o>1&&(a===0&&o>2||c+de>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:zn[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=Je.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=Je.createTrack("audio",i),this._id3Track=Je.createTrack("id3"),this._txtTrack=Je.createTrack("text"),this._audioTrack.segmentCodec="aac",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 u=a.pid,h=a.pesData,d=o.pid,f=c.pid,g=o.pesData,y=c.pesData,p=null,E=this.pmtParsed,T=this._pmtId,v=e.length;if(this.remainderData&&(e=_e(this.remainderData,e),v=e.length,this.remainderData=null),v<de&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};const S=Math.max(0,Je.syncOffset(e));v-=(v-S)%de,v<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,v,e.buffer.byteLength-v));let x=0;for(let A=S;A<v;A+=de)if(e[A]===71){const b=!!(e[A+1]&64),D=di(e,A),L=(e[A+3]&48)>>4;let k;if(L>1){if(k=A+5+e[A+4],k===A+de)continue}else k=A+4;switch(D){case u:if(b){if(h&&(r=dt(h,this.logger))){if(this.videoParser===null)switch(a.segmentCodec){case"avc":this.videoParser=new qr;break;case"hevc":this.videoParser=new jr;break}this.videoParser!==null&&this.videoParser.parsePES(a,l,r,!1)}h={data:[],size:0}}h&&(h.data.push(e.subarray(k,A+de)),h.size+=A+de-k);break;case d:if(b){if(g&&(r=dt(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(k,A+de)),g.size+=A+de-k);break;case f:b&&(y&&(r=dt(y,this.logger))&&this.parseID3PES(c,r),y={data:[],size:0}),y&&(y.data.push(e.subarray(k,A+de)),y.size+=A+de-k);break;case 0:b&&(k+=e[k]+1),T=this._pmtId=ju(e,k);break;case T:{b&&(k+=e[k]+1);const O=zu(e,k,this.typeSupported,s,this.observer,this.logger);u=O.videoPid,u>0&&(a.pid=u,a.segmentCodec=O.segmentVideoCodec),d=O.audioPid,d>0&&(o.pid=d,o.segmentCodec=O.segmentAudioCodec),f=O.id3Pid,f>0&&(c.pid=f),p!==null&&!E&&(this.logger.warn(`MPEG-TS PMT found at ${A} after unknown PID '${p}'. Backtracking to sync byte @${S} to parse all TS packets.`),p=null,A=S-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=D;break}}else x++;x>0&&fi(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=h,o.pesData=g,c.pesData=y;const _={audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(_),_}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=dt(a,this.logger))){if(this.videoParser===null)switch(s.segmentCodec){case"avc":this.videoParser=new qr;break;case"hevc":this.videoParser=new jr;break}this.videoParser!==null&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)}else s.pesData=a;if(o&&(l=dt(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=dt(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 qu(this.observer,this.config,t);return this.decrypt(i,r)}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 h=i.missing,d=i.sample.unit.byteLength;if(h===-1)r=_e(i.sample.unit,r);else{const f=d-h;i.sample.unit.set(r.subarray(0,h),f),e.samples.push(i.sample),s=i.missing}}let a,o;for(a=s,o=r.length;a<o-1&&!As(r,a);a++);if(a!==s){let h;const d=a<o-1;if(d?h=`AAC PES did not start with ADTS header,offset:${a}`:h="No ADTS header found in AAC PES",fi(this.observer,new Error(h),d,this.logger),!d)return}_a(e,this.observer,r,a,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){const h=Da(e.samplerate);c=i.sample.pts+h}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,u;for(;a<o;)if(u=Ca(e,r,a,c,l),a+=u.length,u.missing){this.aacOverFlow=u;break}else for(l++;a<o-1&&!As(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(Fa(s,a)){const c=Oa(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=Ua(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?xe.emsg:xe.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function di(n,e){return((n[e+1]&31)<<8)+n[e+2]}function ju(n,e){return(n[e+10]&31)<<8|n[e+11]}function zu(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 u=di(n,e),h=(n[e+3]&15)<<8|n[e+4];switch(n[e]){case 207:if(!s){Hs("ADTS AAC",r);break}case 15:a.audioPid===-1&&(a.audioPid=u);break;case 21:a.id3Pid===-1&&(a.id3Pid=u);break;case 219:if(!s){Hs("H.264",r);break}case 27:a.videoPid===-1&&(a.videoPid=u);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=u,a.segmentAudioCodec="mp3");break;case 193:if(!s){Hs("AC-3",r);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=u,a.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&h>0){let d=e+5,f=h;for(;f>2;){switch(n[d]){case 106:t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=u,a.segmentAudioCodec="ac3");break}const y=n[d+1]+2;d+=y,f-=y}}break;case 194:case 135:return fi(i,new Error("Unsupported EC-3 in M2TS found"),void 0,r),a;case 36:a.videoPid===-1&&(a.videoPid=u,a.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=h+5}return a}function fi(n,e,t,s){s.warn(`parsing error: ${e.message}
205`),n.emit(m.ERROR,m.ERROR,{type:U.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Hs(n,e){e.log(`${n} with AES-128-CBC encryption found in unencrypted stream`)}function dt(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]=_e(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 u=s[7];u&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,u&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),r=s[8];let h=r+9;if(n.size<=h)return null;n.size-=h;const d=new Uint8Array(n.size);for(let f=0,g=c.length;f<g;f++){s=c[f];let y=s.byteLength;if(h)if(h>y){h-=y;continue}else s=s.subarray(h),y-=h,h=0;d.set(s,t),t+=y}return i&&(i-=r+3),{data:d,pts:a,dts:o,len:i}}return null}class Xu{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 Xe=Math.pow(2,32)-1;class I{static init(){I.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 I.types)I.types.hasOwnProperty(e)&&(I.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]);I.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]);I.STTS=I.STSC=I.STCO=r,I.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),I.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),I.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),I.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]);I.FTYP=I.box(I.types.ftyp,a,c,a,o),I.DINF=I.box(I.types.dinf,I.box(I.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 I.box(I.types.hdlr,I.HDLR_TYPES[e])}static mdat(e){return I.box(I.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(Xe+1)),i=Math.floor(t%(Xe+1));return I.box(I.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 I.box(I.types.mdia,I.mdhd(e.timescale||0,e.duration||0),I.hdlr(e.type),I.minf(e))}static mfhd(e){return I.box(I.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"?I.box(I.types.minf,I.box(I.types.smhd,I.SMHD),I.DINF,I.stbl(e)):I.box(I.types.minf,I.box(I.types.vmhd,I.
vendor: 7,298 bytes, line 205
205VMHD),I.DINF,I.stbl(e))}static moof(e,t,s){return I.box(I.types.moof,I.mfhd(e),I.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=I.trak(e[t]);return I.box.apply(null,[I.types.moov,I.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(I.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=I.trex(e[t]);return I.box.apply(null,[I.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(Xe+1)),i=Math.floor(t%(Xe+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 I.box(I.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 I.box(I.types.sdtp,s)}static stbl(e){return I.box(I.types.stbl,I.stsd(e),I.box(I.types.stts,I.STTS),I.box(I.types.stsc,I.STSC),I.box(I.types.stsz,I.STSZ),I.box(I.types.stco,I.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=I.box(I.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),c=e.width,l=e.height,u=e.pixelRatio[0],h=e.pixelRatio[1];return I.box(I.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,I.box(I.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),I.box(I.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return I.box(I.types.mp4a,I.audioStsd(e),I.box(I.types.esds,I.esds(e)))}static mp3(e){return I.box(I.types[".mp3"],I.audioStsd(e))}static ac3(e){return I.box(I.types["ac-3"],I.audioStsd(e),I.box(I.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return I.box(I.types.stsd,I.STSD,I.mp4a(e));if(t==="ac3"&&e.config)return I.box(I.types.stsd,I.STSD,I.ac3(e));if(t==="mp3"&&e.codec==="mp3")return I.box(I.types.stsd,I.STSD,I.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return I.box(I.types.stsd,I.STSD,I.avc1(e));if(t==="hevc"&&e.vps)return I.box(I.types.stsd,I.STSD,I.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/(Xe+1)),o=Math.floor(s%(Xe+1));return I.box(I.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=I.sdtp(e),i=e.id,r=Math.floor(t/(Xe+1)),a=Math.floor(t%(Xe+1));return I.box(I.types.traf,I.box(I.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),I.box(I.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])),I.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,I.box(I.types.trak,I.tkhd(e),I.mdia(e))}static trex(e){const t=e.id;return I.box(I.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,u,h,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,u=c.size,h=c.flags,d=c.cts,a.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return I.box(I.types.trun,a)}static initSegment(e){I.types||I.init();const t=I.moov(e);return _e(I.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 y=0;y<s[g].length;y+=1)a+=2+s[g][y].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 y=0;y<s[g].length;y+=1)o.set(new Uint8Array([s[g][y].length>>8,s[g][y].length&255]),a),a+=2,o.set(s[g][y],a),a+=s[g][y].length}const l=I.box(I.types.hvcC,o),u=e.width,h=e.height,d=e.pixelRatio[0],f=e.pixelRatio[1];return I.box(I.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,u&255,h>>8&255,h&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,I.box(I.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),I.box(I.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}}I.types=void 0;I.HDLR_TYPES=void 0;I.STTS=void 0;I.STSC=void 0;I.STCO=void 0;I.STSZ=void 0;I.VMHD=void 0;I.SMHD=void 0;I.STSD=void 0;I.FTYP=void 0;I.DINF=void 0;const Ga=9e4;function Vi(n,e,t=1,s=!1){const i=n*e*t;return s?Math.round(i):i}function Qu(n,e,t=1,s=!1){return Vi(n,e,1/t,s)}function Lt(n,e=!1){return Vi(n,1e3,1/Ga,e)}function Zu(n,e=1){return Vi(n,Ga,1/e)}const Ju=10*1e3,eh=1024,th=1152,sh=1536;let ft=null,Ws=null;function zr(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 as{constructor(e,t,s,i){if(this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupp
vendor: 18,652 bytes, line 205
205orted=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.ISGenerated=!1,ft===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ft=a?parseInt(a[1]):0}if(Ws===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);Ws=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.logger.log("[mp4-remuxer]: 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.logger.debug("PTS rollover detected"),i}remux(e,t,s,i,r,a,o,c){let l,u,h,d,f,g,y=r,p=r;const E=e.pid>-1,T=t.pid>-1,v=t.samples.length,S=e.samples.length>0,x=o&&v>0||v>1;if((!E||S)&&(!T||x)||this.ISGenerated||o){if(this.ISGenerated){var A,b,D,L;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])||((D=t.pixelRatio)==null?void 0:D[1])!==((L=K.pixelRatio)==null?void 0:L[1]))||!K&&x||this.nextAudioPts===null&&S)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,r,a));const k=this.isVideoContiguous;let O=-1,z;if(x&&(O=ih(t.samples),!k&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,O>0){this.logger.warn(`[mp4-remuxer]: Dropped ${O} out of ${v} video samples due to a missing keyframe`);const K=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(O),t.dropped+=O,p+=(t.samples[0].pts-K)/t.inputTimeScale,z=p}else O===-1&&(this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${v} video samples`),g=!1);if(this.ISGenerated){if(S&&x){const K=this.getVideoStartPts(t.samples),F=(be(e.samples[0].pts,K)-K)/t.inputTimeScale;y+=Math.max(0,F),p+=Math.max(0,-F)}if(S){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),h=this.generateIS(e,t,r,a)),u=this.remuxAudio(e,y,this.isAudioContiguous,a,T||x||c===N.AUDIO?p:void 0),x){const K=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),h=this.generateIS(e,t,r,a)),l=this.remuxVideo(t,p,k,K)}}else x&&(l=this.remuxVideo(t,p,k,0));l&&(l.firstKeyFrame=O,l.independent=O!==-1,l.firstKeyFramePTS=z)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=Va(s,r,this._initPTS,this._initDTS)),i.samples.length&&(d=Ka(i,r,this._initPTS))),{audio:u,video:l,initSegment:h,independent:g,text:d,id3:f}}generateIS(e,t,s,i){const r=e.samples,a=t.samples,o=this.typeSupported,c={},l=this._initPTS;let u=!l||i,h="audio/mp4",d,f,g;if(u&&(d=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(h="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):I.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(g=e.inputTimeScale,!l||g!==l.timescale?d=f=r[0].pts-Math.round(g*s):u=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:I.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(g=t.inputTimeScale,!l||g!==l.timescale){const y=this.getVideoStartPts(a),p=Math.round(g*s);f=Math.min(f,be(a[0].dts,y)-p),d=Math.min(d,y-p)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:d,timescale:g},this._initDTS={baseTime:f,timescale:g}):d=g=void 0,{tracks:c,initPTS:d,timescale:g}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,a=e.samples,o=[],c=a.length,l=this._initPTS;let u=this.nextAvcDts,h=8,d=this.videoSampleDuration,f,g,y=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,E=!1;if(!s||u===null){const P=t*r,w=a[0].pts-be(a[0].dts,a[0].pts);ft&&u!==null&&Math.abs(P-w-u)<15e3?s=!0:u=P-w}const T=l.baseTime*r/l.timescale;for(let P=0;P<c;P++){const w=a[P];w.pts=be(w.pts-T,u),w.dts=be(w.dts-T,u),w.dts<a[P>0?P-1:P].dts&&(E=!0)}E&&a.sort(function(P,w){const W=P.dts-w.dts,H=P.pts-w.pts;return W||H}),f=a[0].dts,g=a[a.length-1].dts;const v=g-f,S=v?Math.round(v/(c-1)):d||e.inputTimeScale/30;if(s){const P=f-u,w=P>S,W=P<-1;if((w||W)&&(w?this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Lt(P,!0)} ms (${P}dts) hole between fragments detected at ${t.toFixed(3)}`):this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Lt(-P,!0)} ms (${P}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!W||u>=a[0].pts||ft)){f=u;const H=a[0].pts-P;if(w)a[0].dts=f,a[0].pts=H;else{let j=!0;for(let Z=0;Z<a.length&&!(a[Z].dts>H&&j);Z++){const ee=a[Z].pts;if(a[Z].dts-=P,a[Z].pts-=P,Z<a.length-1){const ne=a[Z+1].pts,Ee=a[Z].pts,ve=ne<=Ee,ze=ne<=ee;j=ve==ze}}}this.logger.log(`Video: Initial PTS/DTS adjusted: ${Lt(H,!0)}/${Lt(f,!0)}, delta: ${Lt(P,!0)} ms`)}}f=Math.max(0,f);let x=0,_=0,A=f;for(let P=0;P<c;P++){const w=a[P],W=w.units,H=W.length;let j=0;for(let Z=0;Z<H;Z++)j+=W[Z].data.length;_+=j,x+=H,w.length=j,w.dts<A?(w.dts=A,A+=S/4|0||1):A=w.dts,y=Math.min(w.pts,y),p=Math.max(w.pts,p)}g=a[c-1].dts;const b=_+4*x+8;let D;try{D=new Uint8Array(b)}catch(P){this.observer.emit(m.ERROR,m.ERROR,{type:U.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:P,bytes:b,reason:`fail allocating video mdat ${b}`});return}const L=new DataView(D.buffer);L.setUint32(0,b),D.set(I.types.mdat,4);let k=!1,O=Number.POSITIVE_INFINITY,z=Number.POSITIVE_INFINITY,K=Number.NEGATIVE_INFINITY,$=Number.NEGATIVE_INFINITY;for(let P=0;P<c;P++){const w=a[P],W=w.units;let H=0;for(let ee=0,ne=W.length;ee<ne;ee++){const Ee=W[ee],ve=Ee.data,ze=Ee.data.byteLength;L.setUint32(h,ze),h+=4,D.set(ve,h),h+=ze,H+=4+ze}let j;if(P<c-1)d=a[P+1].dts-w.dts,j=a[P+1].pts-w.pts;else{const ee=this.config,ne=P>0?w.dts-a[P-1].dts:S;if(j=P>0?w.pts-a[P-1].pts:S,ee.stretchShortVideoTrack&&this.nextAudioPts!==null){const Ee=Math.floor(ee.maxBufferHole*r),ve=(i?y+i*r:this.nextAudioPts)-w.pts;ve>Ee?(d=ve-ne,d<0?d=ne:k=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${ve/90} ms to the next segment; using duration ${d/90} ms for the last video frame.`)):d=ne}else d=ne}const Z=Math.round(w.pts-w.dts);O=Math.min(O,d),K=Math.max(K,d),z=Math.min(z,j),$=Math.max($,j),o.push(zr(w.key,d,H,Z))}if(o.length){if(ft){if(ft<70){const P=o[0].flags;P.dependsOn=2,P.isNonSync=0}}else if(Ws&&$-z<K-O&&S/K<.025&&o[0].cts===0){this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let P=f;for(let w=0,W=o.length;w<W;w++){const H=P+o[w].duration,j=P+o[w].cts;if(w<W-1){const Z=H+o[w+1].cts;o[w].duration=Z-j}else o[w].duration=w?o[w-1].duration:S;o[w].cts=0,P=H}}}d=k||!d?S:d,this.nextAvcDts=u=g+d,this.videoSampleDuration=d,this.isVideoContiguous=!0;const B={data1:I.moof(e.sequenceNumber++,f,re(e,{samples:o})),data2:D,startPTS:y/r,endPTS:(p+d)/r,startDTS:f/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,B}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return th;case"ac3":return sh;default:return eh}}remuxAudio(e,t,s,i,r){const a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,c=a/o,l=this.getSamplesPerFrame(e),u=l*c,h=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=r!==void 0;let y=e.samples,p=d?0:8,E=this.nextAudioPts||-1;const T=t*a,v=h.baseTime*a/h.timescale;if(this.isAudioContiguous=s=s||y.length&&E>0&&(i&&Math.abs(T-E)<9e3||Math.abs(be(y[0].pts-v,T)-E)<20*u),y.forEach(function(F){F.pts=be(F.pts-v,T)}),!s||E<0){if(y=y.filter(F=>F.pts>=0),!y.length)return;r===0?E=0:i&&!g?E=Math.max(0,T):E=y[0].pts}if(e.segmentCodec==="aac"){const F=this.config.maxAudioFramesDrift;for(let G=0,B=E;G<y.length;G++){const P=y[G],w=P.pts,W=w-B,H=Math.abs(1e3*W/a);if(W<=-F*u&&g)G===0&&(this.logger.warn(`Audio frame @ ${(w/a).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*W/a)} ms.`),this.nextAudioPts=E=B=w);else if(W>=F*u&&H<Ju&&g){let j=Math.round(W/u);B=w-j*u,B<0&&(j--,B+=u),G===0&&(this.nextAudioPts=E=B),this.logger.warn(`[mp4-remuxer]: Injecting ${j} audio frame @ ${(B/a).toFixed(3)}s due to ${Math.round(1e3*W/a)} ms gap.`);for(let Z=0;Z<j;Z++){const ee=Math.max(B,0);let ne=Xu.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);ne||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),ne=P.unit.subarray()),y.splice(G,0,{unit:ne,pts:ee}),B+=u,G++}}P.pts=B,B+=u}}let S=null,x=null,_,A=0,b=y.length;for(;b--;)A+=y[b].unit.byteLength;for(let F=0,G=y.length;F<G;F++){const B=y[F],P=B.unit;let w=B.pts;if(x!==null){const H=f[F-1];H.duration=Math.round((w-x)/c)}else if(s&&e.segmentCodec==="aac"&&(w=E),S=w,A>0){A+=p;try{_=new Uint8Array(A)}catch(H){this.observer.emit(m.ERROR,m.ERROR,{type:U.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:H,bytes:A,reason:`fail allocating audio mdat ${A}`});return}d||(new DataView(_.buffer).setUint32(0,A),_.set(I.types.mdat,4))}else return;_.set(P,p);const W=P.byteLength;p+=W,f.push(zr(!0,l,W,0)),x=w}const D=f.length;if(!D)return;const L=f[f.length-1];this.nextAudioPts=E=x+c*L.duration;const k=d?new Uint8Array(0):I.moof(e.sequenceNumber++,S/c,re({},e,{samples:f}));e.samples=[];const O=S/a,z=E/a,$={data1:k,data2:_,startPTS:O,endPTS:z,startDTS:O,endDTS:z,type:"audio",hasAudio:!0,hasVideo:!1,nb:D};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 ih(n){for(let e=0;e<n.length;e++)if(n[e].key)return e;return-1}function Va(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 Ka(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 rh{constructor(e,t,s,i){this.logger=void 0,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.logger=i}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(Yl(e,i)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:s}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const i=this.initData=Zn(e);i.audio&&(t=Xr(i.audio,ie.AUDIO)),i.video&&(s=Xr(i.video,ie.VIDEO));const r={};i.audio&&i.video?r.audiovideo={container:"video/mp4",codec:t+","+s,supplemental:i.video.supplemental,initSegment:e,id:"main"}:i.audio?r.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:i.video?r.video={container:"video/mp4",codec:s,supplemental:i.video.supplemental,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(e,t,s,i,r,a){var o,c;let{initPTS:l,lastEndTime:u}=this;const h={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};M(u)||(u=this.lastEndTime=r||0);const d=t.samples;if(!(d!=null&&d.length))return h;const f={initPTS:void 0,timescale:1};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(d),g=this.initData),!((c=g)!=null&&c.length))return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),h;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const y=jl(d,g),p=ql(g,d),E=p===null?r:p;(a||!l)&&(nh(l,E,r,y)||f.timescale!==l.timescale)&&(f.initPTS=E-r,l&&l.timescale===1&&this.logger.warn(`Adjusting initPTS @${r} from ${l.baseTime/l.timescale} to ${f.initPTS}`),this.initPTS=l={baseTime:f.initPTS,timescale:1});const T=e?E-l.baseTime/l.timescale:u,v=T+y;Xl(g,d,l.baseTime/l.timescale),y>0?this.lastEndTime=v:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const S=!!g.audio,x=!!g.video;let _="";S&&(_+="audio"),x&&(_+="video");const A={data1:d,startPTS:T,startDTS:T,endPTS:v,endDTS:v,type:_,hasAudio:S,hasVideo:x,nb:1,dropped:0};return h.audio=A.type==="audio"?A:void 0,h.video=A.type!=="audio"?A:void 0,h.initSegment=f,h.id3=Va(s,r,l,l),i.samples.length&&(h.text=Ka(i,r,l)),h}}function nh(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 Xr(n,e){const t=n==null?void 0:n.codec;return t&&t.length>4?t:e===ie.AUDIO?t==="ec-3"||t==="ac-3"||t==="alac"?t:t==="fLaC"||t==="Opus"?ps(t,!1):(Q.warn(`Unhandled audio codec "${t}" in mp4 MAP`),t||"mp4a"):(Q.warn(`Unhandled video codec "${t}" in mp4 MAP`),t||"avc1")}let We;try{We=self.performance.now.bind(self.performance)}catch{We=Date.now}const os=[{demux:Yu,remux:rh},{demux:Je,remux:as},{demux:Vu,remux:as},{demux:Hu,remux:as}];os.splice(2,0,{demux:Ku,remux:as});class Qr{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=We();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:c}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:u,trackSwitch:h,accurateTimeOffset:d,timeOffset:f,initSegmentChange:g}=i||o,{audioCodec:y,videoCodec:p,defaultInitPts:E,duration:T,initSegmentData:v}=c,S=ah(a,t);if(S&&pt(S.method)){const b=this.getDecrypter(),D=wi(S.method);if(b.isSync()){let L=b.softwareDecrypt(a,S.key.buffer,S.iv.buffer,D);if(s.part>-1){const O=b.flush();L=O&&O.buffer}if(!L)return r.executeEnd=We(),Ys(s);a=new Uint8Array(L)}else return this.asyncResult=!0,this.decryptionPromise=b.webCryptoDecrypt(a,S.key.buffer,S.iv.buffer,D).then(L=>{const k=this.push(L,null,s);return this.decryptionPromise=null,k}),this.decryptionPromise}const x=this.needsProbing(u,h);if(x){const b=this.configureTransmuxer(a);if(b)return this.logger.warn(`[transmuxer] ${b.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:U.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:b,reason:b.message}),r.executeEnd=We(),Ys(s)}(u||h||g||x)&&this.resetInitSegment(v,y,p,T,t),(u||g||x)&&this.resetInitialTimestamp(E),l||this.resetContiguity();const _=this.transmux(a,S,f,d,s);this.asyncResult=Nt(_);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=We(),_}flush(e){const t=e.transmuxing;t.executeStart=We();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 h=s.flush();h&&a.push(this.push(h.buffer,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=We();const h=[Ys(e)];return this.asyncResult?Promise.resolve(h):h}const u=c.flush(o);return Nt(u)?(this.asyncResult=!0,u.then(h=>(this.flushRemux(a,h,e),a))):(this.flushRemux(a,u,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,s){const{audioTrack:i,videoTrack: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===N.MAIN?"level":"track"} ${s.level}`);const u=this.remuxer.remux(i,r,a,o,l,c,!0,this.id);e.push({remuxResult:u,chunkMeta:s}),s.transmuxing.executeEnd=We()}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 h=0,d=os.length;h<d;h++){var a;if((a=os[h].demux)!=null&&a.probe(e,this.logger)){r=os[h];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,c=this.remuxer,l=r.remux,u=r.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(s,t,i,this.logger)),(!o||!(o instanceof u))&&(this.demuxer=new u(s,t,i,this.logger),this.probe=u.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new ki(this.config)),e}}function ah(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 Ys=n=>({remuxResult:{},chunkMeta:n});function Nt(n){return"then"in n&&n.then instanceof Function}class oh{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 lh{constructor(e,t,s,i,r,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOff
vendor: 2,761 bytes, line 205
205set=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 Zr=0;class Ha{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Zr++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=c=>{const l=c.data,u=this.hls;if(!(!u||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var h;const d=(h=this.workerContext)==null?void 0:h.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{u.logger[l.data.logType]&&u.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,u.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const l=new Error(`${c.message}  (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(m.ERROR,{type:U.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 Fi,this.observer.on(m.FRAG_DECRYPTED,a),this.observer.on(m.ERROR,a);const o=gr(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||hu()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=fu(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=du());const{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:ae(r)})}catch(u){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new Qr(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new Qr(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Zr++;const t=this.hls.config,s=gr(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,c
vendor: 43,896 bytes, lines 205-216
205onfig:ae(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),gu(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,u){var h,d;l.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,y=a?a.start:r.start,p=r.decryptdata,E=this.frag,T=!(E&&r.cc===E.cc),v=!(E&&l.level===E.level),S=E?l.sn-E.sn:-1,x=this.part?l.part-this.part.index:-1,_=S===0&&l.id>1&&l.id===(E==null?void 0:E.stats.chunkCount),A=!v&&(S===1||S===0&&(x===1||_&&x<=0)),b=self.performance.now();(v||S||r.stats.parsing.start===0)&&(r.stats.parsing.start=b),a&&(x||!A)&&(a.stats.parsing.start=b);const D=!(E&&((h=r.initSegment)==null?void 0:h.url)===((d=E.initSegment)==null?void 0:d.url)),L=new lh(T,A,c,v,y,D);if(!A||T||D){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===N.MAIN?"level":"track"}: ${l.level} id: ${l.id}
206        discontinuity: ${T}
207        trackSwitch: ${v}
208        contiguous: ${A}
209        accurateTimeOffset: ${c}
210        timeOffset: ${y}
211        initSegmentChange: ${D}`);const k=new oh(s,i,t,o,u);this.configureTransmuxer(k)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:L},e instanceof ArrayBuffer?[e]:[]);else if(g){const k=g.push(e,p,l,L);Nt(k)?k.then(O=>{this.handleTransmuxComplete(O)}).catch(O=>{this.transmuxerError(O,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(k)}}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);Nt(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:U.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 Jr=100;class ch extends Mi{constructor(e,t,s){super(e,t,s,"audio-stream-controller",N.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}){if(s===N.MAIN){const a=t.cc,o=this.fragCurrent;if(this.initPTS[a]={baseTime:i,timescale:r},this.log(`InitPTS for cc: ${a} found from main: ${i}/${r}`),this.mainAnchor=t,this.state===C.WAITING_INIT_PTS){const c=this.waitingData;(!c&&!this.loadingParts||c&&c.frag.cc!==a)&&(this.nextLoadPosition=this.findSyncFrag(t).start),this.tick()}else!this.hls.hasEnoughToStart&&o&&o.cc!==a?(this.startFragRequested=!1,this.nextLoadPosition=this.findSyncFrag(t).start,o.abortRequests(),this.resetLoadingState()):this.state===C.IDLE&&this.tick()}}findSyncFrag(e){const t=this.getLevelDetails(),s=e.cc;return Ic(t,s,e)||t&&ca(t.fragments,s)||e}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=C.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(Jr),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=C.IDLE):this.state=C.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case C.IDLE:this.doTickIdle();break;case C.WAITING_TRACK:{const{levels:t,trackId:s}=this,i=t==null?void 0:t[s],r=i==null?void 0:i.details;if(r&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(r))break;this.state=C.WAITING_INIT_PTS}break}case C.FRAG_LOADING_WAITING_RETRY:{var e;const t=performance.now(),s=this.retryDate;if(!s||t>=s||(e=this.media)!=null&&e.seeking){const{levels:i,trackId:r}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((i==null?void 0:i[r])||null),this.state=C.IDLE}break}case C.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:s,part:i,cache:r,complete:a}=t,o=this.mainAnchor;if(this.initPTS[s.cc]!==void 0){this.waitingData=null,this.state=C.FRAG_LOADING;const c=r.flush().buffer,l={frag:s,part:i,payload:c,networkDetails:null};this._handleFragmentLoadProgress(l),a&&super._handleFragmentLoadComplete(l)}else o&&o.cc!==t.frag.cc&&(this.log(`Waiting fragment cc (${s.cc}) cancelled because video is at cc ${o.cc}`),this.nextLoadPosition=this.findSyncFrag(o).start,this.clearWaitingFragment())}else this.state=C.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.state!==C.STOPPED&&(this.state=C.IDLE))}resetLoadingState(){this.clearWaitingFragment(),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=C.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,ie.AUDIO,N.AUDIO));const u=this.getFwdBufferInfo(l,N.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,c)){t.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=C.ENDED;return}const h=u.len,d=t.maxBufferLength,f=c.fragments,g=f[0].start,y=this.getLoadPosition(),p=this.flushing?y:u.end;if(this.switchingTrack&&i){const v=y;c.PTSKnown&&v<g&&(u.end>g||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=g+.05)}if(h>=d&&!this.switchingTrack&&p<f[f.length-1].start)return;let E=this.getNextFragment(p,c);if(E&&this.isLoopLoading(E,p)&&(E=this.getNextFragmentLoopLoading(E,c,u,N.MAIN,d)),!E){this.bufferFlushed=!0;return}let T=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&ge(E)&&!E.endList&&(!c.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===he.OK&&(this.mainFragLoading=T=null),T&&ge(T))){if(E.start>T.end){const S=this.fragmentTracker.getFragAtPos(p,N.MAIN);S&&S.end>T.end&&(T=S,this.mainFragLoading={frag:S,targetBufferTime:null})}if(E.start>T.end)return}this.loadFragment(E,o,p)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new Pt(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!==C.STOPPED&&(this.setInterval(Jr),this.state=C.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!==C.STOPPED&&(this.state=C.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 u=i[a];let h=0;if(r.live||(s=u.details)!=null&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(u.details){var d;h=this.alignPlaylists(r,u.details,(d=this.levelLastLoaded)==null?void 0:d.details)}r.alignedSliding||(Aa(r,l),r.alignedSliding||xs(r,l),h=r.fragmentStart)}u.details=r,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(l,h),this.hls.trigger(m.AUDIO_TRACK_UPDATED,{details:r,id:a,groupId:t.groupId}),this.state===C.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=C.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 u=l.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const h=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new Ha(this.hls,N.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 p=i?i.index:-1,E=p!==-1,T=new Pi(s.level,s.sn,s.stats.chunkCount,r.byteLength,p,E);d.push(r,g,h,"",s,i,u.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 [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:y}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new La,complete:!1};y.push(new Uint8Array(r)),this.state!==C.STOPPED&&(this.state=C.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===N.MAIN&&ge(t.frag)&&(this.mainFragLoading=t,this.state===C.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==N.AUDIO){!this.audioOnly&&s.type===N.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(ge(s)){this.fragPrevious=s;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,te({},r)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=C.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(N.AUDIO,t);break;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===X.AUDIO_TRACK&&(this.state=C.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;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!==ie.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ie.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===C.ENDED&&(this.state=C.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,N.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:u}=o,{details:h}=u,{audio:d,text:f,id3:g,initSegment:y}=r;if(this.fragContextChanged(c)||!h){this.fragmentTracker.removeFragment(c);return}if(this.state=C.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),y!=null&&y.tracks){const p=c.initSegment||c;this._bufferInitSegment(u,y.tracks,p,a),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:s,tracks:y.tracks})}if(d){const{startPTS:p,endPTS:E,startDTS:T,endDTS:v}=d;l&&(l.elementaryStreams[ie.AUDIO]={startPTS:p,endPTS:E,startDTS:T,endDTS:v}),c.setElementaryStreamInfo(ie.AUDIO,p,E,T,v),this.bufferFragmentData(d,c,l,a)}if(g!=null&&(t=g.samples)!=null&&t.length){const p=re({id:s,frag:c,details:h},g);i.trigger(m.FRAG_PARSING_METADATA,p)}if(f){const p=re({id:s,frag:c,details:h},f);i.trigger(m.FRAG_PARSING_USERDATA,p)}}_bufferInitSegment(e,t,s,i){if(this.state!==C.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=N.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===he.NOT_LOADED||i===he.PARTIAL){var r;if(!ge(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=C.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&xs(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;at({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o},e,nt)||(Es(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,te({},e))}}class Ki extends je{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==null?void 0:t.lastPartSn);let c=parseInt(a["LAST-PART"])||(t==null?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const u=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&u>t.partTarget&&(c+=1)}const l=s&&pr(s);return new yr(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 u=Math.max(c||0,0);i.appliedTimelineOffset=u,i.fragments.forEach(h=>{h.start=h.playlistOffset+u})}if(i.live||s!=null&&s.live){const u="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){tu(s,i);const T=i.playlistParsingError;if(T){this.warn(T);const v=this.hls;if(!v.config.ignorePlaylistParsingErrors){var l;const{networkDetails:S}=t;v.trigger(m.ERROR,{type:U.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:S,stats:r});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=r.loading.start);const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,f=(i.edge-d)*1e3,g=Ea(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 y,p,E;if(i.canBlockReload&&i.endSN&&i.advanced){const T=this.hls.config.lowLatencyMode,v=i.lastPartSn,S=i.endSN,x=i.lastPartIndex,_=x!==-1,A=v===S;_?A?(p=S+1,E=T?0:x):(p=v,E=T?x+1:i.maxPartIndex):p=S+1;const b=i.age,D=b+i.ageHeader;let L=Math.min(D-i.partTarget,i.targetduration*1.5);if(L>0){if(D>i.targetduration*3)this.log(`Playlist last advanced ${b.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,E=void 0;else if(s!=null&&s.tuneInGoal&&D-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${L} with playlist age: ${i.age}`),L=0;else{const k=Math.floor(L/i.targetduration);if(p+=k,E!==void 0){const O=Math.round(L%i.targetduration/i.partTarget);E+=O}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${b.toFixed(2)}s goal: ${L} skip sn ${k} to part ${E}`)}i.tuneInGoal=L}if(y=this.getDeliveryDirectives(i,t.deliveryDirectives,p,E),T||!A){i.requestScheduled=a,this.loadingPlaylist(u,y);return}}else(i.canBlockReload||i.canSkipUntil)&&(y=this.getDeliveryDirectives(i,t.deliveryDirectives,p,E));y&&p!==void 0&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(g-o*2,g/2)),this.scheduleLoading(u,y,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=pr(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=ns.No),new yr(s,i,r)}checkRetry(e){const t=e.details,s=vs(e),i=e.errorAction,{action:r,retryCount:a=0,retryConfig:o}=i||{},c=!!i&&!!o&&(r===ye.RetryRequest||!i.resolved&&r===ye.SendAlternateToPenaltyBox);if(c){var l;if(a>=o.maxNumRetry)return!1;if(s&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const u=Ci(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${u}ms`)}e.levelRetry=!0,i.resolved=!0}return c}}function Wa(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(!Bt(n[t].attrs,e[t].attrs))return!1;return!0}function Bt(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 gi(n,e){return e.label.toLowerCase()===n.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(n.lang||"").toLowerCase())}class uh extends Ki{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=Be(c,o,nt);if(d>-1)r=o[d];else{const f=Be(c,this.tracks);r=this.tracks[f]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const u={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,u);const h=this.trackId;if(l!==-1&&h===-1)this.setAudioTrack(l);else if(o.length&&h===-1){var a;const d=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(m.ERROR,{type:U.MEDIA_ERROR,details:R.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}}onError(e,t){t.fatal||!t.context||t.context.type===X.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&&at(e,i,nt))return i;const r=Be(e,this.tracksInGroup,nt);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=Tc(e,t.levels,s,a,nt);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=Be(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,te({},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||at(e,i,nt)))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 u=t[l];if(at({name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:c},u,nt))return l}for(let l=0;l<t.length;l++){const u=t[l];if(Bt(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const u=t[l];if(Bt(e.attrs,u.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Es(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 hh{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>":`
212${this.list("video")}
213${this.list("audio")}
214${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 en=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Ya="HlsJsTrackRemovedError";class dh extends Error{constructor(e){super(e),this.name=Ya}}class fh extends je{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=Nl(et(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,i=et(this.appendSource);if(this.transferData=this.overrides=void 0,s&&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,tn(s),gh(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=()=>{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})
215required tracks: ${ae(s,(c,l)=>c==="initSegment"?void 0:l)};
216transfer tracks: ${ae(i,(c,l)=>c==="initSegment"?void 0:l)}}`),!Yn(i,s)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,l=this.details,u=Math.max(c,(l==null?void 0:l.fragments[0].start)||0);if(u-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${u} currentTime: ${c}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,r.forEach(c=>{const l=c,u=i[l];if(u){const h=u.buffer;if(h){const d=this.fragmentTracker,f=u.id;if(d.hasFragments(f)||d.hasParts(f)){const p=q.getBuffered(h);d.detectEvictedFragments(l,p,f,null,!0)}const g=qs(l),y=[l,h];this.sourceBuffers[g]=y,h.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,u)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource: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&&tn(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[qs(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new hh(this.tracks)}onBufferCodecs(e,t){const s=this.tracks,i=Object.keys(t);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const r="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),a=!r&&this.sourceBufferCount&&this.media&&i.some(o=>!s[o]);if(r||a){this.warn(`Unsupported transition between "${Object.keys(s)}" and "${i}" SourceBuffers`);return}i.forEach(o=>{var c,l,u;const h=t[o],{id:d,codec:f,levelCodec:g,container:y,metadata:p,supplemental:E}=h;let T=s[o];const v=(c=this.transferData)==null||(l=c.tracks)==null?void 0:l[o],S=v!=null&&v.buffer?v:T,x=(S==null?void 0:S.pendingCodec)||(S==null?void 0:S.codec),_=S==null?void 0:S.levelCodec;T||(T=s[o]={buffer:void 0,listeners:[],codec:f,supplemental:E,container:y,levelCodec:g,metadata:p,id:d});const A=rs(x,_),b=A==null?void 0:A.replace(en,"$1");let D=rs(f,g);const L=(u=D)==null?void 0:u.replace(en,"$1");D&&A&&b!==L&&(o.slice(0,5)==="audio"&&(D=ps(D,this.appendSource)),this.log(`switching codec ${x} to ${D}`),D!==(T.pendingCodec||T.codec)&&(T.pendingCodec=D),T.container=y,this.appendChangeType(o,y,D))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&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,N.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,N.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}=t,u=l.buffering[r],h=o.sn,d=self.performance.now();u.start=d;const f=o.stats.buffering,g=c?c.stats.buffering:null;f.start===0&&(f.start=d),g&&g.start===0&&(g.start=d);const y=s.audio;let p=!1;r==="audio"&&(y==null?void 0:y.container)==="audio/mpeg"&&(p=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const E=this.tracks.video,T=E==null?void 0:E.buffer;if(T&&h!=="initSegment"){const x=c||o,_=this.blockedAudioAppend;if(r==="audio"&&a!=="main"&&!this.blockedAudioAppend){const b=x.start+x.duration*.05,D=T.buffered,L=this.currentOp("video");!D.length&&!L?this.blockAudio(x):!L&&!q.isBuffered(T,b)&&this.lastVideoAppendEnd<b&&this.blockAudio(x)}else if(r==="video"){const A=x.end;if(_){const b=_.frag.start;(A>b||A<this.lastVideoAppendEnd||q.isBuffered(T,b))&&this.unblockAudio()}this.lastVideoAppendEnd=A}}const v=(c||o).start,S={label:`append-${r}`,execute:()=>{if(u.executeStart=self.performance.now(),p){const x=this.tracks[r];if(x){const _=x.buffer;if(_){const A=v-_.timestampOffset;Math.abs(A)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${v} (delta: ${A}) sn: ${h})`),_.timestampOffset=v)}}}this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const x=self.performance.now();u.executeEnd=u.end=x,f.first===0&&(f.first=x),g&&g.first===0&&(g.first=x);const _={};this.sourceBuffers.forEach(([A,b])=>{A&&(_[A]=q.getBuffered(b))}),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:_})},onError:x=>{var _;const A={type:U.MEDIA_ERROR,parent:o.type,details:R.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:c,chunkMeta:l,error:x,err:x,fatal:!1},b=(_=this.media)==null?void 0:_.error;if(x.code===DOMException.QUOTA_EXCEEDED_ERR)A.details=R.BUFFER_FULL_ERROR;else if(x.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!b)A.errorAction=wt(!0);else if(x.name===Ya&&this.sourceBufferCount===0)A.errorAction=wt(!0);else{const D=++this.appendErrors[r];this.warn(`Failed ${D}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${b||"no media error"}
216)`),(D>=this.hls.config.appendErrorMaxRetry||b)&&(A.fatal=!0)}this.hls.trigger(m.ERROR,A)}};this.append(S,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[ie.AUDIOVIDEO]?r.push("audiovideo"):(a[ie.AUDIO]&&r.push("audio"),a[ie.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])=>{var t,s;return e&&(!((t=this.tracks[e])!=null&&t.ended)||((s=this.tracks[e])==null?void 0:s.ending))})}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)))}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(){const e=this.getDurationAndRange();e&&this.blockUntilOpen(()=>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 c=Math.max(o,a),l=Math.floor(r/a)*a-c;this.flushBackBuffer(r,a,l)}if(M(i.frontBufferFlushThreshold)&&i.frontBufferFlushThreshold>0){const c=Math.max(i.maxBufferLength,i.frontBufferFlushThreshold),l=Math.max(c,a),u=Math.floor(r/a)*a+l;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;
vendor: 4,990 bytes, line 216
216if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&s.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),u=Math.max(l,i);return{duration:1/0,start:l,end:u}}return{duration:1/0}}const 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}) ${ae(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:U.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":""} ${ae(o)}`);try{const u=s.addSourceBuffer(l),h=qs(a),d=[a,u];t[h]=d,o.buffer=u}catch(u){var i;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(a),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[a],this.hls.trigger(m.ERROR,{type:U.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:a,mimeType:l,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&(t==="video"||t==="audiovideo")&&ai(s,"video")&&(i=ac(i,s));const r=rs(i,e.levelCodec);return r?t.slice(0,5)==="audio"?ps(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:U.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.currentOp(e);r&&r.onError(i)}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,u=Math.max(0,t),h=Math.min(s,c,l);h>u&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${u},${h}] from the ${e} SourceBuffer`),o.remove(u,h)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=s==null?void 0:s.buffer;if(!i)throw new dh(`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}
216`),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 tn(n){const e=n.querySelectorAll("source");[].slice.call(e).forEach(t=>{n.removeChild(t)})}function gh(n,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,n.appendChild(t)}function qs(n){return n==="audio"?1:0}class Hi{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_ATTA
vendor: 3,501 bytes, line 216
216CHING,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,Hi.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 mh={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",
vendor: 5,477 bytes, line 216
216KEY:"k",OTHER:"o"},Te=mh,ph={HLS:"h"},yh=ph,Eh="CMCD-Object",vh="CMCD-Request",Th="CMCD-Session",Sh="CMCD-Status",Rt={OBJECT:Eh,REQUEST:vh,SESSION:Th,STATUS:Sh},xh={[Rt.OBJECT]:["br","d","ot","tb"],[Rt.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Rt.SESSION]:["cid","pr","sf","sid","st","v"],[Rt.STATUS]:["bs","rtp"]};class St{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof St?s:new St(s))),this.value=e,this.params=t}}const Ah="Dict";function Lh(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 Ih(n,e,t,s){return new Error(`failed to ${n} "${Lh(e)}" as ${t}`,{cause:s})}function Ge(n,e,t){return Ih("serialize",n,e,t)}class qa{constructor(e){this.description=e}}const sn="Bare Item",Rh="Boolean";function bh(n){if(typeof n!="boolean")throw Ge(n,Rh);return n?"?1":"?0"}const _h="Byte Sequence";function Dh(n){if(ArrayBuffer.isView(n)===!1)throw Ge(n,_h);return`:${Lu(n)}:`}const Ch="Integer";function kh(n){return n<-999999999999999||999999999999999<n}function ja(n){if(kh(n))throw Ge(n,Ch);return n.toString()}function Ph(n){return`@${ja(n.getTime()/1e3)}`}const wh="Decimal";function Oh(n){const e=ka(n,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Ge(n,wh);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Mh="String",Fh=/[\x00-\x1f\x7f]+/;function Nh(n){if(Fh.test(n))throw Ge(n,Mh);return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Bh(n){return n.description||n.toString().slice(7,-1)}const Uh="Token";function rn(n){const e=Bh(n);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Ge(e,Uh);return e}function mi(n){switch(typeof n){case"number":if(!M(n))throw Ge(n,sn);return Number.isInteger(n)?ja(n):Oh(n);case"string":return Nh(n);case"symbol":return rn(n);case"boolean":return bh(n);case"object":if(n instanceof Date)return Ph(n);if(n instanceof Uint8Array)return Dh(n);if(n instanceof qa)return rn(n);default:throw Ge(n,sn)}}const $h="Key";function pi(n){if(/^[a-z*][a-z0-9\-_.*]*$/.test(n)===!1)throw Ge(n,$h);return n}function Wi(n){return n==null?"":Object.entries(n).map(([e,t])=>t===!0?`;${pi(e)}`:`;${pi(e)}=${mi(t)}`).join("")}function za(n){return n instanceof St?`${mi(n.value)}${Wi(n.params)}`:mi(n)}function Gh(n){return`(${n.value.map(za).join(" ")})${Wi(n.params)}`}function Vh(n,e={whitespace:!0}){if(typeof n!="object")throw Ge(n,Ah);const t=n instanceof Map?n.entries():Object.entries(n),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof St||(r=new St(r));let a=pi(i);return r.value===!0?a+=Wi(r.params):(a+="=",Array.isArray(r.value)?a+=Gh(r):a+=za(r)),a}).join(`,${s}`)}function Kh(n,e){return Vh(n,e)}function Hh(n){return n==="ot"||n==="sf"||n==="st"}function Wh(n){return typeof n=="number"?M(n):n!=null&&n!==""&&n!==!1}const ls=n=>Math.round(n),Yh=(n,e)=>(e!=null&&e.baseUrl&&(n=Iu(n,e.baseUrl)),encodeURIComponent(n)),Qt=n=>ls(n/100)*100,qh={br:ls,d:ls,bl:Qt,dl:Qt,mtp:Qt,nor:Yh,rtp:Qt,tb:ls};function jh(n,e){const t={};if(n==null||typeof n!="object")return t;const s=Object.keys(n).sort(),i=re({},qh,e==null?void 0:e.formatters),r=e==null?void 0:e.filter;return s.forEach(a=>{if(r!=null&&r(a))return;let o=n[a];const c=i[a];c&&(o=c(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||Wh(o)&&(Hh(a)&&typeof o=="string"&&(o=new qa(o)),t[a]=o))}),t}function Xa(n,e={}){return n?Kh(jh(n,e),re({whitespace:!1},e)):""}function zh(n,e={}){const t={};if(!n)return t;const s=Object.entries(n),i=Object.entries(xh).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),r=s.reduce((a,o)=>{var c,l;const[u,h]=o,d=((c=i.find(f=>f[1].includes(u)))===null||c===void 0?void 0:c[0])||Rt.REQUEST;return(l=a[d])!==null&&l!==void 0||(a[d]={}),a[d][u]=h,a},{});return Object.entries(r).reduce((a,[o,c])=>(a[o]=Xa(c,e),a),t)}function Xh(n,e,t){return re(n,zh(e,t))}const Qh="CMCD";function Zh(n,e={}){if(!n)return"";const t=Xa(n,e);return`${Qh}=${encodeURIComponent(t)}`}const nn=/CMCD=[^&#]+/;function Jh(n,e,t){const s=Zh(e,t);if(!s)return n;if(nn.test(n))return n.replace(nn,s);const i=n.includes("?")?"&":"?";return`${n}${i}${s}`}class ed{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:Te.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===Te.VIDEO||c===Te.AUDIO||c==Te.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));const u=a?this.getNextPart(a):this.getNextFrag(r);u!=null&&u.url&&u.url!==r.url&&(l.nor=u.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;
216e.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:yh.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===Te.INIT||t.ot===Te.VIDEO||t.ot===Te.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={}),Xh(e.headers,t,r)):e.url=Jh(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,s;const{index:i,fragment:r}=e,a=(t=this.hls.levels[r.level])==null||(s=t.details)==null?void 0:s.partList;if(a){const{sn:o}=r;for(let c=a.length-1;c>=0;c--){const l=a[c];if(l.index===i&&l.fragment.sn===o)return a[c+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Te.TIMED_TEXT;if(e.sn==="initSegment")return Te.INIT;if(t==="audio")return Te.AUDIO;if(t==="main")return this.hls.audioTracks.length?Te.VIDEO:Te.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===Te.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,a=r>-1?r+1:i.levels.length;s=i.levels.slice(0,a)}for(const r of s)r.bitrate>t&&(t=r.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===Te.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 td=3e5;class sd extends je{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)}
vendor: 3,518 bytes, line 216
216startLoad(){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)===ye.SendAlternateToPenaltyBox&&s.flags===ke.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),s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${ae(r)} penalized: ${ae(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]>td&&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,Sa(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===X.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===X.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(u=>u.pathwayId===a))return;const l=this.getLevelsForPathway(o).map(u=>{const h=new oe(u.attrs);h["PATHWAY-ID"]=a;const d=h.AUDIO&&`${h.AUDIO}_clone_${a}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;d&&(s[h.AUDIO]=d,h.AUDIO=d),f&&(i[h.SUBTITLES]=f,h.SUBTITLES=f);
216const g=Qa(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),y=new Pt({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:g,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let p=1;p<u.audioGroups.length;p++)y.addGroupId("audio",`${u.audioGroups[p]}_clone_${a}`);if(u.subtitleGroups)for(let p=1;p<u.subtitleGroups.length;p++)y.addGroupId("text",`${u.subtitleGroups[p]}_clone_${a}`);return y});t.push(...l),an(this.audioTracks,s,c,a),an(this.subtitleTracks,i,c,a)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+u)}const 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:(u,h,d,f)=>{this.log(`Loaded steering manifest: "${i}"`);const g=u.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":y,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":E}=g;if(y)try{this.uri=new self.URL(y,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${y}`);return}this.scheduleRefresh(this.uri||d.url),p&&this.clonePathways(p);const T={steeringManifest:g,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,T),E&&this.updatePathwayPriority(E)},onError:(u,h,d,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${h.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let g=this.timeToLoad*1e3;if(u.code===429){const y=this.loader;if(typeof(y==null?void 0:y.getResponseHeader)=="function"){const p=y.getResponseHeader("Retry-After");p&&(g=parseFloat(p)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},onTimeout:(u,h,d)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(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 an(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 oe(o.attrs),o.url=o.attrs.URI=Qa(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 Qa(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 yt extends je{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=yt.CDMCleanupPromise?[yt.CDMCleanupPromise]:[],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=qt(this.config));const o=a.map(Us).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=Ns(a);let c,l;if(s==="sinf"){if(o!==se.FAIRPLAY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}const g=ce(new Uint8Array(i));try{const y=Oi(JSON.parse(g).sinf),p=Jn(y);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(p.subarray(8,24)),l=se.FAIRPLAY}catch(y){this.warn(`${r} Failed to parse sinf: ${y}`);return}}else{if(o!==se.WIDEVINE&&o!==se.PLAYREADY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}const g=sc(i),y=g.filter(E=>!!E.systemId&&Bs(E.systemId)===o);y.length>1&&this.warn(`${r} Using first of ${y.length} pssh found for selected key-system ${o}`);const p=y[0];if(!p){g.length===0||g.some(E=>!E.systemId)?this.warn(`${r} contains incomplete or invalid pssh data`):this.log(`ignoring ${r} for ${g.map(E=>
216Bs(E.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(l=Bs(p.systemId),p.version===0&&p.data)if(l===se.WIDEVINE){const E=p.data.length-22;c=new Uint8Array(p.data.subarray(E,E+16))}else l===se.PLAYREADY&&(c=ga(p.data))}if(!l||!c)return;const u=Oe.hexDump(c),{keyIdToKeySessionPromise:h,mediaKeySessions:d}=this;let f=h[u];for(let g=0;g<d.length;g++){const y=d[g],p=y.decryptdata;if(!p.keyId)continue;const E=Oe.hexDump(p.keyId);if(u===E||p.uri.replace(/-/g,"").indexOf(u)!==-1){if(f=h[E],p.pssh)break;delete h[E],p.pssh=new Uint8Array(i),p.keyId=c,f=h[u]=f.then(()=>this.generateRequestWithPreferredKeySession(y,s,i,"encrypted-event-key-match")),f.catch(T=>this.handleError(T));break}}if(!f){if(l!==o){this.log(`Ignoring "${t.type}" event with ${l} init data for selected key-system ${o}`);return}f=h[u]=this.getKeySystemSelectionPromise([l]).then(({keySystem:g,mediaKeys:y})=>{var p;this.throwIfDestroyed();const E=new Ot("ISO-23001-7",u,(p=Us(g))!=null?p:"");return E.pssh=new Uint8Array(i),E.keyId=c,this.attemptSetMediaKeys(g,y).then(()=>{this.throwIfDestroyed();const T=this.createMediaKeySessionContext({decryptdata:E,keySystem:g,mediaKeys:y});return this.generateRequestWithPreferredKeySession(T,s,i,"encrypted-event-no-match")})}),f.catch(g=>this.handleError(g))}})}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){const e=this.media;this.unregisterListeners(),this.onMediaDetached(),this._clear(e);const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}
216registerListeners(){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)}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)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,i=t[e];if(i)return i.licenseUrl;if(e===se.WIDEVINE&&s)return s}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=t[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(a,o,c)=>!!a&&c.indexOf(a)===o,i=t.map(a=>a.audioCodec).filter(s),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 u=l.shift();this.getMediaKeysPromise(u,i,r).then(h=>a({keySystem:u,mediaKeys:h})).catch(h=>{l.length?c(l):h instanceof Re?o(h):o(new Re({type:U.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return fa===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){const i=qc(e,t,s,this.config.drmSystemOptions),r=this.keySystemAccessPromises[e];let a=r==null?void 0:r.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ae(i)}`),a=this.requestMediaKeySystemAccess(e,i);const o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(c=>{this.log(`Failed to obtain access to key-system "${e}": ${c}`)}),a.then(c=>{this.log(`Access for key-system "${c.keySystem}" obtained`);const l=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=c.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),l.then(h=>h?this.setMediaKeysServerCertificate(u,e,h):u))),o.mediaKeys.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),o.mediaKeys})}return a.then(()=>r.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Oe.hexDump(e.keyId||[])}`);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=this.getKeyIdString(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)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return Oe.hexDump(e.keyId)}updateKeySession(e,t){var s;const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyID ${Oe.hexDump(((s=e.decryptdata)==null?void 0:s.keyId)||[])}
217      } (data length: ${t&&t.byteLength})`),i.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,s)=>{const i=qt(this.config),r=e.map(Ns).filter(a=>!!a&&i.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(r).then(({keySystem:a})=>{const o=Us(a);o?t(o):s(new Error(`Unable to find format for key-system "${a}"`))}).catch(s)})}loadKey(e){const t=e.keyInfo.decryptdata,s=this.getKeyIdString(t),i=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${i}`);let r=this.keyIdToKeySessionPromise[s];return r||(r=this.getKeySystemForKeyPromise(t).then(({keySystem:o,mediaKeys:c})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(o,c).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:o,mediaKeys:c,decryptdata:t}))))),(this.keyIdToKeySessionPromise[s]=r.then(o=>{const c="cenc",l=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(o,c,l,"playlist-key")}
vendor: 9,235 bytes, line 217
217)).catch(o=>this.handleError(o))),r}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Re?this.hls.trigger(m.ERROR,e.data):this.hls.trigger(m.ERROR,{type:U.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=Ns(e.keyFormat),r=i?[i]:qt(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=qt(this.config)),e.length===0)throw new Re({type:U.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ae({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return 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,a;const o=(r=this.config.drmSystems)==null||(a=r[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const g=o.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){var c;if(this.warn(g.message),(c=this.hls)!=null&&c.config.debug)throw g}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${i}": ${l} (init data type: ${t} length: ${s?s.byteLength:null})`);const u=new Fi,h=e._onmessage=g=>{const y=e.mediaKeysSession;if(!y){u.emit("error",new Error("invalid state"));return}const{messageType:p,message:E}=g;this.log(`"${p}" message event for session "${y.sessionId}" message size: ${E.byteLength}`),p==="license-request"||p==="license-renewal"?this.renewLicense(e,E).catch(T=>{u.eventNames().length?u.emit("error",T):this.handleError(T)}):p==="license-release"?e.keySystem===se.FAIRPLAY&&(this.updateKeySession(e,ci("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${p}"`)},d=e._onkeystatuseschange=g=>{if(!e.mediaKeysSession){u.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const p=e.keyStatus;u.emit("keyStatus",p),p==="expired"&&(this.warn(`${e.keySystem} expired for key ${l}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",h),e.mediaKeysSession.addEventListener("keystatuseschange",d);const f=new Promise((g,y)=>{u.on("error",y),u.on("keyStatus",p=>{p.startsWith("usable")?g():p==="output-restricted"?y(new Re({type:U.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):p==="internal-error"?y(new Re({type:U.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${p}"`)):p==="expired"?y(new Error("key expired while generating request")):this.warn(`unhandled key status change "${p}"`)})});return e.mediaKeysSession.generateRequest(t,s).then(()=>{var g;this.log(`Request generated for key-session "${(g=e.mediaKeysSession)==null?void 0:g.sessionId}" keyId: ${l}`)}).catch(g=>{throw new Re({type:U.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_SESSION,error:g,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>{throw u.removeAllListeners(),this.removeSession(e),g}).then(()=>(u.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,s)=>{if(typeof s=="string"&&typeof t=="object"){const i=s;s=t,t=i}this.log(`key status change "${t}" for keyStatuses keyId: ${Oe.hexDump("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${Oe.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=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,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,f,g,y)=>{a(d.data)},onError:(d,f,g,y)=>{o(new Re({type:U.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:te({url:c.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,g)=>{o(new Re({type:U.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,u,h)})):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==null?void 0:s.byteLength}) on "${t}"`),i(e)}).catch(a=>{r(new Re({type:U.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 Re({type:U.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:i,fatal:!0},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 u;for(let h=0,d=r.length;h<d;h++){var a,o;u=r[h];const f=(a=u.querySelector("name"))==null?void 0:a.textContent,g=(o=u.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}const c=i.querySelector("Challenge"),l=c==null?void 0:c.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return ci(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(u){this.error(u)}i(c)}else{const c=s.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)r(new Re({type:U.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const u=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} 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==se.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(c,l)),c.send(l)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,s.removeEventListener("encrypted",this.onMediaEncrypted),s.removeEventListener("waitingforkey",this.onWaitingForKey),s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null)}_clear(e){var t;const s=this.mediaKeySessions;this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Ot.clearKeyUriToKeyIdMap();const i=s.length;yt.CDMCleanupPromise=Promise.all(s.map(r=>this.removeSession(r)).concat(e==null||(t=e.setMediaKeys(null))==null?void 0:t.catch(r=>{var a;this.log(`Could not clear media keys: ${r}`),(a=this.hls)==null||a.trigger(m.ERROR,{type:U.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media ke
217ys: ${r}`)})}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),s.length=0)}).catch(r=>{var a;this.log(`Could not close sessions and clear media keys: ${r}`),(a=this.hls)==null||a.trigger(m.ERROR,{type:U.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${r}`)})})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const 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}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);const{drmSystemOptions:r}=this.config;return(zc(r)?new Promise((o,c)=>{self.setTimeout(()=>c(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(o)}):Promise.resolve()).catch(o=>{var c;this.log(`Could not remove session: ${o}`),(c=this.hls)==null||c.trigger(m.ERROR,{type:U.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${o}`)})}).then(()=>t.close()).catch(o=>{var c;this.log(`Could not close session: ${o}`),(c=this.hls)==null||c.trigger(m.ERROR,{type:U.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${o}`)})})}}}yt.CDMCleanupPromise=void 0;class Re 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}}class id{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}
vendor: 15,048 bytes, line 217
217registerListeners(){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 u=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=u)&&(u=u-1,l.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function Za(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 Ja(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){Q.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){Q.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(n.mode=t)}function mt(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 yi(n,e,t,s){const i=n.mode;if(i==="disabled"&&(n.mode="hidden"),n.cues&&n.cues.length>0){const r=nd(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 nd(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 cs(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 ad extends Ki{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=cs(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;cs(s.textTracks).forEach(a=>{mt(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(u=>!s||s.indexOf(u.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(u=>u.default)&&(this.selectDefaultTrack=!1),a.forEach((u,h)=>{u.id=h});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const u=Be(o,a);if(u>-1)r=a[u];else{const h=Be(o,this.tracks);r=this.tracks[h]}}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||at(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(Bt(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(Bt(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(gi(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===X.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&&at(e,s))return s;const i=Be(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}else{if(s)return null;{const r=Be(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=cs(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(r=>gi(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:u}=i;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:c,type:l,url:u});const h=this.switchParams(i.url,s==null?void 0:s.details,i.details);this.loadPlaylist(h)}}function Dt(n){let e=5381,t=n.length;for(;t;)e=e*33^n.charCodeAt(--t);return(e>>>0).toString()}const Et=.025;let Ls=function(n){return n[n.Point=0]="Point",n[n.Range=1]="Range",n}({});function od(n,e,t){return`${n.identifier}-${t+1}-${Dt(e)}`}class ld{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){if(e>=this.assetList.length)return!0;const t=this.playoutLimit;return e<=0||isNaN(t)?!1:this.assetList[e].startOffset>t}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 js(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=js(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 js(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)<Et))}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"?Ls.Range:Ls.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 cd(this)}}function js(n,e){return n-e.start<e.duration/2&&!(Math.abs(n-(e.start+e.duration))<Et)?e.start:e.start+e.duration}function eo(n,e,t){const s=new self.URL(n,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function cd(n){return`["${n.identifier}" ${n.cue.pre?"<pre>":n.cue.post?"<post>":""}${n.timelineStart.toFixed(2)}-${n.resumeTime.toFixed(2)}]`}function Ei(n){const e=n.timelineStart,t=n.duration||0;return`["${n.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class ud{constructor(e,t,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetail
vendor: 4,293 bytes, line 217
217s=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{const l=this.interstitial.playoutLimit,u=this.currentTime;this.startOffset+u>=l&&this.hls.trigger(m.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=s,this.assetItem=i;let a=i.uri;try{a=eo(a,r.sessionId).href}catch{}r.loadSource(a);const o=()=>{this.hasDetails=!0};r.once(m.LEVEL_LOADED,o),r.once(m.AUDIO_TRACK_LOADED,o),r.once(m.SUBTITLE_TRACK_LOADED,o),r.on(m.MEDIA_ATTACHING,(c,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&l.addEventListener("timeupdate",this.checkPlayout)})}bufferedInPlaceToEnd(e){var t;if(!this.interstitial.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e||!this._bufferedEosTime)return!1;const s=this.timelineOffset,i=q.bufferInfo(e,s,0);return this.getAssetTime(i.end)>=this._bufferedEosTime-.02}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;return e||0}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){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.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){this.hls.attachMedia(e)}detachMedia(){this.removeMediaListeners(),this.mediaAttached=null,this.hls.detachMedia()}resumeBuffering(){this.hls.resumeBuffering()}pauseBuffering(){this.hls.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls.transferMedia()}on(e,t,s){this.hls.on(e,t)}once(e,t,s){this.hls.once(e,t)}off(e,t,s){this.hls.off(e,t)}toString(){var e,t;return`HlsAssetPlayer: ${Ei(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${(t=this.interstitial)!=null&&t.appendInPlace?"append-in-place":""}`}}const on=.033;class hd extends je{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>
vendor: 170,237 bytes, lines 217-229
217r.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))return r}}return 0}get assetIdAtEnd(){var e,t;const s=(e=this.items)==null||(t=e[this.length-1])==null?void 0:t.event;if(s){const i=s.assetList,r=i[i.length-1];if(r)return r.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,u)=>{const h=l.cue.pre,d=l.cue.post,f=u.cue.pre,g=u.cue.post;if(h&&!f)return-1;if(f&&!h||d&&!g)return 1;if(g&&!d)return-1;if(!h&&!f&&!d&&!g){const y=l.startTime,p=u.startTime;if(y!==p)return y-p}return l.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=a,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[]){const s=this.events||[];if(s.length||t.length||this.length<2){const i=this.items,r=this.parseSchedule(s,e);(t.length||(i==null?void 0:i.length)!==r.length||r.some((o,c)=>Math.abs(o.playout.start-i[c].playout.start)>.005||Math.abs(o.playout.end-i[c].playout.end)>.005))&&(this.items=r,this.onScheduleUpdate(t,i))}}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 ld(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((u,h)=>{const d=u.cue.pre,f=u.cue.post,g=e[h-1]||null,y=u.appendInPlace,p=f?r:u.startOffset,E=u.duration,T=u.timelineOccupancy===Ls.Range?E:0,v=u.resumptionOffset,S=(g==null?void 0:g.startTime)===p,x=p+u.cumulativeDuration;let _=y?x+E:p+v;if(d||!f&&p<=0){const b=l;l+=T,u.timelineStart=x;const D=a;a+=E,s.push({event:u,start:x,end:_,playout:{start:D,end:a},integrated:{start:b,end:l}})}else if(p<=r){if(!S){const L=p-c;if(L>on){const k=c,O=l;l+=L;const z=a;a+=L;const K={previousEvent:e[h-1]||null,nextEvent:u,start:k,end:k+L,playout:{start:z,end:a},integrated:{start:O,end:l}};s.push(K)}else L>0&&g&&(g.cumulativeDuration+=L,s[s.length-1].end=p)}f&&(_=x),u.timelineStart=x;const b=l;l+=T;const D=a;a+=E,s.push({event:u,start:x,end:_,playout:{start:D,end:a},integrated:{start:b,end:l}})}else return;const A=u.resumeTime;f||A>r?c=r:c=A}),c<r){var o;const u=c,h=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:u+d,playout:{start:f,end:a},integrated:{start:h,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,u=o.cue.post,h=l?0:u?i:o.startTime;this.updateAssetDurations(o),a===h?o.cumulativeDuration=r:(r=0,a=h),!u&&o.snapOptions.in&&(o.resumeAnchor=lt(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<on&&(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)>Et?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):t?!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=lt(null,o.fragments,s);if(!l)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const u=a==="audio"?.175:0;return Math.abs(l.start-s)<Et+u||Math.abs(l.end-s)<Et+u?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${a} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)}):(this.log(`"${e.identifier}" resumption ${s} can not be aligned with media (none selected)`),!1)}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;e.assetList.forEach((a,o)=>{const c=t+s;a.startOffset=s,a.timelineStart=c,i||(i=a.duration===null),r||(r=!!a.error);const l=a.error?0:a.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 Qe(n){return`[${n.event?'"'+n.event.identifier+'"':"primary"}: ${n.start.toFixed(2)}-${n.end.toFixed(2)}]`}class dd{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=eo(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,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,f,g,y)=>{const p=d.data,E=p==null?void 0:p.ASSETS;if(!Array.isArray(E)){const T=this.assignAssetListError(e,R.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,y);this.hls.trigger(m.ERROR,T);return}e.assetListResponse=p,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:p,networkDetails:y})},onError:(d,f,g,y)=>{const p=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,y,g);this.hls.trigger(m.ERROR,p)},onTimeout:(d,f,g)=>{const y=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,y)}};return o.load(c,u,h),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,r,a){return e.error=s,{type:U.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:a,stats:r}}}function Ye(n,e,t){$e(n,e,t),n.addEventListener(e,t)}function $e(n,e,t){n.removeEventListener(e,t)}function ln(n){n==null||n.play().catch(()=>{})}class fd extends je{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)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(),this.checkBuffer(),a&&s<o.start||s>=o.end){var c;const d=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!a){const f=this.findItemIndex(o);if(d>f){const g=this.schedule.findJumpRestrictedIndex(f+1,d);if(g>f){this.setSchedulePosition(g);return}}}this.setSchedulePosition(d);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const d=o.event.assetList[0];d&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,d))}return}const u=l.timelineStart,h=l.duration||0;(a&&s<u||s>=u+h)&&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,a=this.playingItem,o=r.events||[],c=r.items||[],l=r.durations,u=s.map(f=>f.identifier),h=!!(o.length||u.length);if(h&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
218Schedule: ${c.map(f=>Qe(f))}`),u.length&&this.log(`Removed events ${u}`),this.playerQueue.forEach(f=>{if(f.interstitial.appendInPlace){const g=f.assetItem.timelineStart,y=f.timelineOffset-g;if(y)try{f.timelineOffset=g}catch(p){Math.abs(y)>Et&&this.warn(`${p} ("${f.assetId}" ${f.timelineOffset}->${g})`)}}}),a){const f=this.updateItem(a,this.timelinePos);this.itemsMatch(a,f)&&(this.playingItem=f,this.waitingItem=this.endedItem=null)}else this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const d=this.bufferingItem;if(d){const f=this.updateItem(d,this.bufferedPos);this.itemsMatch(d,f)?this.bufferingItem=f:d.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(d.event,null))}if(s.forEach(f=>{f.assetList.forEach(g=>{this.clearAssetPlayer(g.identifier,null)})}),h||i){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:l,removedIds:u}),this.isInterstitial(a)&&u.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new dd(e),this.schedule=new hd(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;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.manager=null,this.hls=this.HlsPlayerClass=this.schedule=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 s=this.media=t.media;Ye(s,"seeking",this.onSeeking),Ye(s,"timeupdate",this.onTimeupdate),Ye(s,"play",this.onPlay),Ye(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.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.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.manager){if(!this.hls)return null;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=h=>h&&e.getAssetPlayer(h.identifier),i=(h,d,f,g,y)=>{if(h){let p=h[d].start;const E=h.event;if(E){if(d==="playout"||E.timelineOccupancy!==Ls.Point){const T=s(f);(T==null?void 0:T.interstitial)===E&&(p+=T.assetItem.startOffset+T[y])}}else{const T=g==="bufferedPos"?a():e[g];p+=T-h.start}return p}return 0},r=(h,d)=>{if(h!==0&&d!=="primary"&&e.schedule.length){var f;const g=e.schedule.findItemIndexAtTime(h),y=(f=e.schedule.items)==null?void 0:f[g];if(y){const p=y[d].start-y.start;return h+p}}return h},a=()=>{const h=e.bufferedPos;return h===Number.MAX_VALUE?o("primary"):Math.max(h,0)},o=h=>{var d;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:e.schedule.durations[h]},c=(h,d)=>{var f,g;const y=e.effectivePlayingItem;if(y!=null&&(f=y.event)!=null&&f.restrictions.skip)return;e.log(`seek to ${h} "${d}"`);const p=e.effectivePlayingItem,E=e.schedule.findItemIndexAtTime(h,d),T=(g=e.schedule.items)==null?void 0:g[E],v=e.getBufferingPlayer(),S=v==null?void 0:v.interstitial,x=S==null?void 0:S.appendInPlace,_=p&&e.itemsMatch(p,T);if(p&&(x||_)){const b=s(e.playingAsset),D=(b==null?void 0:b.media)||e.primaryMedia;if(D){const L=d==="primary"?D.currentTime:i(p,d,e.playingAsset,"timelinePos","currentTime"),k=h-L,O=(x?L:D.currentTime)+k;if(O>=0&&(!b||x||O<=b.duration)){D.currentTime=O;return}}}if(T){let b=h;if(d!=="primary"){const L=T[d].start,k=h-L;b=T.start+k}const D=!e.isInterstitial(T);if((!e.isInterstitial(p)||p.event.appendInPlace)&&(D||T.event.appendInPlace)){const L=e.media||(x?v==null?void 0:v.media:null);L&&(L.currentTime=b)}else if(p){const L=e.findItemIndex(p);if(E>L){const O=e.schedule.findJumpRestrictedIndex(L+1,E);if(O>L){e.setSchedulePosition(O);return}}let k=0;if(D)e.timelinePos=b,e.checkBuffer();else{var A;const O=T==null||(A=T.event)==null?void 0:A.assetList;if(O){const z=h-(T[d]||T).start;for(let K=O.length;K--;){const $=O[K];if($.duration&&z>=$.startOffset&&z<$.startOffset+$.duration){k=K;break}}}}e.setSchedulePosition(E,k)}}},l=()=>{const h=e.effectivePlayingItem;if(e.isInterstitial(h))return h;const d=t();return e.isInterstitial(d)?d:null},u={get currentTime(){const h=l(),d=e.effectivePlayingItem;return d&&d===h?i(d,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(h){const d=l(),f=e.effectivePlayingItem;f&&f===d&&c(h+f.playout.start,"playout")},get duration(){const h=l();return h?h.playout.end-h.playout.start:0},get assetPlayers(){var h;const d=(h=l())==null?void 0:h.event.assetList;return d?d.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var h;const d=(h=l())==null?void 0:h.event;return d&&e.effectivePlayingAsset?d.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};this.manager={get events(){var h,d;return((h=e.schedule)==null||(d=h.events)==null?void 0:d.slice(0))||[]},get schedule(){var h,d;return((h=e.schedule)==null||(d=h.items)==null?void 0:d.slice(0))||[]},get interstitialPlayer(){return l()?u:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const h=t();return e.findItemIndex(h)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const h=e.effectivePlayingItem;return e.findItemIndex(h)},primary:{get bufferedEnd(){return a()},get currentTime(){const h=e.timelinePos;return h>0?h:0},set currentTime(h){c(h,"primary")},get duration(){return o("primary")},get seekableStart(){var h;return((h=e.primaryDetails)==null?void 0:h.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(h){c(h,"integrated")},get duration(){return o("integrated")},get seekableStart(){var h;return r(((h=e.primaryDetails)==null?void 0:h.fragmentStart)||0,"integrated")}},skip:()=>{const h=e.effectivePlayingItem,d=h==null?void 0:h.event;if(d&&!d.restrictions.skip){const f=e.findItemIndex(h);if(d.appendInPlace){const g=h.playout.start+h.event.duration;c(g+.001,"playout")}else e.advanceAfterAssetEnded(d,f,1/0)}}}}return this.manager}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,s;if(this.mediaSelection===null)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let r=this.media;!r&&(e=this.bufferingItem)!=null&&(t=e.event)!=null&&t.appendInPlace&&(r=this.primaryMedia);const a=(s=r)==null?void 0:s.currentTime;if(!(a===void 0||!M(a)))return a}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} ${ae(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 u;if(a.media)c&&(r=a.transferMedia(),this.detachedData=r),u="Primary";else if(l){const f=this.getBufferingPlayer();f?(r=f.transferMedia(),u=`${f}`):u="detached MediaSource"}else u="detached media";if(!r){if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${ae(r)}`);else if(!this.detachedData||a.media===t){const f=this.playerQueue;f.length>1&&f.forEach(g=>{if(o&&g.interstitial.appendInPlace!==c){const y=g.interstitial;this.clearInterstitial(g.interstitial,null),y.appendInPlace=!1,y.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${y}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const h=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed",d=h&&r?r:t;if(this.log(`${h?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${u}`),d===r){const f=o&&e.assetId===this.schedule.assetIdAtEnd;d.overrides={duration:this.schedule.duration,endOfStream:!o||f,cueRemoval:!o}}e.attachMedia(d)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const s=this.timelinePos,i=this.effectivePlayingItem;if(s===-1){const r=this.hls.startPosition;if(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)}}advanceAfterAssetEnded(e,t,s){const i=s+1;if(!e.isAssetPastPlayoutLimit(i)&&!e.assetList[i].error)this.setSchedulePosition(t,i);else{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.timelinePos=c,this.checkBuffer()),this.setSchedulePosition(a)}}}setScheduleToAssetAtTime(e,t){const s=this.schedule,i=t.parentIdentifier,r=s.getEvent(i);if(r){const a=s.findEventIndex(i),o=s.findAssetIndex(r,e);this.setSchedulePosition(a,o)}}setSchedulePosition(e,t){const s=this.schedule.items;if(!s||this.playbackDisabled)return;this.log(`setSchedulePosition ${e}, ${t}`);const i=e>=0?s[e]:null,r=this.playingItem,a=this.playingLastItem;if(this.isInterstitial(r)){var o;const l=r.event,u=this.playingAsset,h=u==null?void 0:u.identifier,d=h?this.getAssetPlayer(h):null;if(d&&h&&(!this.eventItemsMatch(r,i)||t!==void 0&&h!==((o=l.assetList)==null?void 0:o[t].identifier))){var c;const f=l.findAssetIndex(u);this.log(`INTERSTITIAL_ASSET_ENDED ${f+1}/${l.assetList.length} ${Ei(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:f,event:l,schedule:s.slice(0),scheduleIndex:e,player:d}),this.retreiveMediaSource(h,i),d.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&d.detachMedia()}if(!this.eventItemsMatch(r,i)&&(this.endedItem=r,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${l} ${Qe(r)}`),l.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:l,schedule:s.slice(0),scheduleIndex:e}),l.cue.once)){this.updateSchedule();const f=this.schedule.items;if(i&&f){const g=this.schedule.findItemIndex(i);this.advanceSchedule(g,f,t,r,a)}return}}this.advanceSchedule(e,s,t,r,a)}advanceSchedule(e,t,s,i,r){const a=e>=0?t[e]:null,o=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(l=>{const u=l.interstitial,h=this.schedule.findEventIndex(u.identifier);(h<e||h>e+1)&&this.clearInterstitial(u,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const l=a.event;s===void 0&&(s=this.schedule.findAssetIndex(l,this.timelinePos));const u=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let h=this.preloadAssets(l,s);if(this.eventItemsMatch(a,u||i)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${Qe(a)} ${l.appendInPlace?"append in place":""}`),this.hls.trigger(m.INTERSTITIAL_STARTED,{event:l,schedule:t.slice(0),scheduleIndex:e})),!l.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${l}`);return}if(l.assetListLoader&&(l.assetListLoader.destroy(),l.assetListLoader=void 0),!o){this.log(`Waiting for attachMedia to start Interstitial ${l}`);return}this.waitingItem=this.endedItem=null,this.playingItem=a;const d=l.assetList[s];if(!d){const f=t[e+1],g=this.media;f&&g&&!this.isInterstitial(f)&&g.currentTime<f.start&&(g.currentTime=this.timelinePos=f.start),this.advanceAfterAssetEnded(l,e,s||0);return}if(h||(h=this.getAssetPlayer(d.identifier)),h===null||h.destroyed){const f=l.assetList.length;this.warn(`asset ${s+1}/${f} player destroyed ${l}`),h=this.createAssetPlayer(l,d,s)}if(!this.eventItemsMatch(a,this.bufferingItem)&&l.appendInPlace&&this.isAssetBuffered(d))return;this.startAssetPlayer(h,s,t,e,o),this.shouldPlay&&ln(h.media)}else a!==null?(this.resumePrimary(a,e,i),this.shouldPlay&&ln(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(this.schedule.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e,t;return(e=this.mediaSelection)==null||(t=e.main)==null?void 0:t.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,s){var i;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Qe(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let a=this.timelinePos;(a<e.start||a>=e.end)&&(a=this.getPrimaryResumption(e,t),this.timelinePos=a),this.attachPrimary(a,e)}if(!s)return;const r=this.schedule.items;r&&(this.log(`resumed ${Qe(e)}`),this.hls.trigger(m.INTERSTITIALS_PRIMARY_RESUMED,{schedule:r.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.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(){this.stopLoad(),this.schedule.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)return;const s=this.hls.levels[t.level],i=te(te({},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=te(te({},this.altSelection),{},{audio:s});return}const r=te(te({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=te(te({},this.altSelection),{},{subtitles:s});return}const r=te(te({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=vr(t);this.playerQueue.forEach(i=>i.hls.setAudioOption(t)||i.hls.setAudioOption(s))}onSubtitleTrackSwitch(e,t){const s=vr(t);this.playerQueue.forEach(i=>i.hls.setSubtitleOption(t)||t.id!==-1&&i.hls.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){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){const s=this.schedule.items;if(e&&s){const i=this.findItemIndex(e,t);return s[i]||null}return null}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.findItemIndex(e,t):-1}updateSchedule(){const e=this.mediaSelection;e&&this.schedule.updateSchedule(e,[])}checkBuffer(e){const t=this.schedule.items;if(!t)return;const s=q.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=s.len<1),this.updateBufferedPos(s.end,t,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e)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,u;const h=this.findItemIndex(r),d=Math.min(h+1,t.length-1),f=t[d];if((c===-1&&r&&e>=r.end||(l=f.event)!=null&&l.appendInPlace&&e+.01>=f.start)&&(c=d),d-o>1&&(r==null||(u=r.event)==null?void 0:u.appendInPlace)===!1)return;if(this.bufferedPos=e,c>h&&c>o)this.bufferedToItem(f);else{const g=this.primaryDetails;this.primaryLive&&g&&e>g.edge-g.targetduration&&f.start<g.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(f)&&this.preloadAssets(f.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))this.bufferingItem!==e&&(this.bufferingItem=e);else{const{items:i,events:r}=s;if(!i||!r)return t;const a=this.isInterstitial(e),o=this.getBufferingPlayer();if(this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos)),!this.playbackDisabled){const c=o?o.remaining:t?t.end-this.timelinePos:0;this.log(`buffered to boundary ${Qe(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),a?e.event.assetList.forEach(l=>{const u=this.getAssetPlayer(l.identifier);u&&u.resumeBuffering()}):(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)})}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=s.assetList[t],c=this.primaryMedia;o&&c&&this.bufferAssetPlayer(a,c)}}}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,u=0;if(!this.playingItem&&this.primaryLive&&(u=this.hls.startPosition,u===-1&&(u=this.hls.liveSyncPosition||0)),u&&!(e.cue.pre||e.cue.post)){const d=u-c;d>0&&(l=Math.round(d*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${l?` live-start: ${u} start-offset: ${l}`:""}`),s)return this.createAsset(e,0,0,c,e.duration,s);const h=this.assetListLoader.loadAssetList(e,l);h&&(e.assetListLoader=h)}else if(!a&&i){for(let c=t;c<i;c++){const l=e.assetList[c],u=this.getAssetPlayerQueueIndex(l.identifier);(u===-1||this.playerQueue[u].destroyed)&&!l.error&&this.createAssetPlayer(e,l,c)}return this.getAssetPlayer(e.assetList[t].identifier)}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:od(e,a,t),duration:r,startOffset:s,timelineStart:i,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){this.log(`create HLSAssetPlayer for ${Ei(t)}`);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 u=0;if(this.primaryLive||e.appendInPlace){const v=this.timelinePos-t.timelineStart;if(v>1){const S=t.duration;S&&v<S&&(u=v)}}const h=t.identifier,d=te(te({},r),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:c||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:Dt(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);const g=new ud(this.HlsPlayerClass,d,e,t);this.playerQueue.push(g),e.assetList[s]=t;const y=v=>{if(v.live){const _=new Error(`Interstitials MUST be VOD assets ${e}`),A={fatal:!0,type:U.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:_};this.handleAssetItemError(A,e,this.schedule.findEventIndex(e.identifier),s,_.message);return}const S=v.edge-v.fragmentStart,x=t.duration;(x===null||S>x)&&(this.log(`Interstitial asset "${h}" duration change ${x} > ${S}`),t.duration=S,this.updateSchedule())};g.on(m.LEVEL_UPDATED,(v,{details:S})=>y(S)),g.on(m.LEVEL_PTS_UPDATED,(v,{details:S})=>y(S));const p=(v,S)=>{const x=this.getAssetPlayer(h);if(x&&S.tracks){x.off(m.BUFFER_CODECS,p),x.tracks=S.tracks;const _=this.primaryMedia;this.bufferingAsset===x.assetItem&&_&&!x.media&&this.bufferAssetPlayer(x,_)}};g.on(m.BUFFER_CODECS,p);const E=()=>{var v;const S=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${S}`),!S)return;const x=this.schedule.findEventIndex(e.identifier),_=e.findAssetIndex(t),A=_+1,b=(v=this.schedule.items)==null?void 0:v[x];if(this.isInterstitial(b))if(_!==-1&&!e.isAssetPastPlayoutLimit(A)&&!e.assetList[A].error)this.bufferedToItem(b,A);else{var D;const L=(D=this.schedule.items)==null?void 0:D[x+1];L&&this.bufferedToItem(L)}};g.on(m.BUFFERED_TO_END,E);const T=v=>()=>{if(!this.getAssetPlayer(h))return;this.shouldPlay=!0;const x=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,x,v)};return g.once(m.MEDIA_ENDED,T(s)),g.once(m.PLAYOUT_LIMIT_REACHED,T(1/0)),g.on(m.ERROR,(v,S)=>{const x=this.getAssetPlayer(h);if(S.details===R.BUFFER_STALLED_ERROR){if(x!=null&&x.media){const _=x.currentTime,A=x.duration-_;_&&e.appendInPlace&&A/x.media.playbackRate<.5?(this.log(`Advancing buffer past end of asset ${h} ${e} at ${x.media.currentTime}`),E()):(this.warn(`Stalled at ${_} of ${_+A} in asset ${h} ${e}`),this.onTimeupdate(),this.checkBuffer(!0))}return}this.handleAssetItemError(S,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${S.error} ${e}`)}),g.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(h))return;const S=new Error(`Asset player destroyed unexpectedly ${h}`),x={fatal:!0,type:U.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:S};this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),s,S.message)}),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:g}),g}clearInterstitial(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)}),e.reset()}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){this.log(`clearAssetPlayer "${e}" toSegment: ${t&&Qe(t)}`);const i=this.playerQueue[s];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,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!u||u.identifier!==c)&&(u&&(this.clearAssetPlayer(u.identifier,s[i]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${e}`),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;const{interstitial:r,assetItem:a,assetId:o}=e,c=this.schedule.findEventIndex(r.identifier),l=(s=this.schedule.items)==null?void 0:s[c];if(!l)return;this.setBufferingItem(l),this.bufferingAsset=a;const u=this.getBufferingPlayer();if(u===e)return;const h=r.appendInPlace;if(h&&(u==null?void 0:u.interstitial.appendInPlace)===!1)return;const d=(u==null?void 0:u.tracks)||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(h&&a!==this.playingAsset){if(!e.tracks)return;if(d&&!Yn(d,e.tracks)){const f=new Error(`Asset "${o}" SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),g={fatal:!0,type:U.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:f},y=r.findAssetIndex(a);this.handleAssetItemError(g,r,c,y,f.message);return}}this.transferMediaTo(e,t)}handleAssetItemError(e,t,s,i,r){if(e.details===R.BUFFER_STALLED_ERROR)return;const a=t.assetList[i]||null;let o=null;if(a){const h=this.getAssetPlayerQueueIndex(a.identifier);o=this.playerQueue[h]||null}const c=this.schedule.items,l=re({},e,{fatal:!1,errorAction:wt(!0),asset:a,assetListIndex:i,event:t,schedule:c,scheduleIndex:s,player:o});if(this.warn(`Asset item error: ${e.error}`),this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,l),!e.fatal)return;const u=new Error(r);a&&(this.playingAsset!==a&&this.clearAssetPlayer(a.identifier,null),a.error=u),t.assetList.some(h=>!h.error)?t.appendInPlace&&(t.error=u):t.error=u,this.primaryFallback(t)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;if(this.updateSchedule(),s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${s?Qe(s):"<none>"} error: ${e.error}`),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t));let i=this.timelinePos;i===-1&&(i=this.hls.startPosition);const r=this.updateItem(s,i);if(this.itemsMatch(s,r))this.clearInterstitial(e,null);else{const a=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(a)}}else this.checkStart()}onAssetListLoaded(e,t){var s;const i=t.event,r=i.identifier,a=t.assetListResponse.ASSETS;if(!this.schedule.hasEvent(r))return;const o=i.timelineStart,c=i.duration;let l=0;a.forEach((g,y)=>{const p=parseFloat(g.DURATION);this.createAsset(i,y,l,o+l,p,g.URI),l+=p}),i.duration=l,this.log(`Loaded asset-list with duration: ${l} (was: ${c}) ${i}`);const u=this.waitingItem,h=(u==null?void 0:u.event.identifier)===r;this.updateSchedule();const d=(s=this.bufferingItem)==null?void 0:s.event;if(h){var f;const g=this.schedule.findEventIndex(r),y=(f=this.schedule.items)==null?void 0:f[g];if(y){if(!this.playingItem&&this.timelinePos>y.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g){i.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${i}`),this.primaryFallback(i);return}this.setBufferingItem(y)}this.setSchedulePosition(g)}else if((d==null?void 0:d.identifier)===r&&d.appendInPlace){const g=i.assetList[0],y=this.getAssetPlayer(g.identifier),p=this.primaryMedia;g&&y&&p&&this.bufferAssetPlayer(y,p)}}onError(e,t){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.primaryFallback(s);break}case R.BUFFER_STALLED_ERROR:{this.onTimeupdate(),this.checkBuffer(!0);break}}}}const cn=500;class gd extends Mi{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",N.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=C.IDLE,this.setInterval(cn),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(ge(s)&&(this.fragPrevious=s),this.state=C.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,N.SUBTITLE)}}onError(e,t){const s=t.frag;(s==null?void 0:s.type)===N.SUBTITLE&&(t.details===R.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==C.STOPPED&&(this.state=C.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Wa(this.levels,t)){this.levels=t.map(s=>new Pt(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new Pt(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,N.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!==C.STOPPED&&this.setInterval(cn)}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){const h=this.mainDetails;if(a.deltaUpdateFailed||!h)return;const d=h.fragments[0];if(!c.details)a.hasProgramDateTime&&h.hasProgramDateTime?(xs(a,h),l=a.fragmentStart):d&&(l=d.start,hi(a,l));else{var u;l=this.alignPlaylists(a,c.details,(u=this.levelLastLoaded)==null?void 0:u.details),l===0&&d&&(l=d.start,hi(a,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===C.IDLE&&(lt(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&&pt(i.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,wi(i.method)).catch(o=>{throw r.trigger(m.ERROR,{type:U.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=C.IDLE})}}doTick(){if(!this.media){this.state=C.IDLE;return}if(this.state===C.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,u=this.hls.maxBufferLength+l.levelTargetDuration;if(c>u)return;const h=l.fragments,d=h.length,f=l.edge;let g=null;const y=this.fragPrevious;if(o<f){const T=i.maxFragLookUpTolerance,v=o>f-T?0:T;g=lt(y,h,Math.max(h[0].start,o),v),!g&&y&&y.start<h[0].start&&(g=h[0])}else g=h[d-1];if(g=this.filterReplacedPrimary(g,s.details),!g)return;const p=g.sn-l.startSN,E=h[p-1];if(E&&E.cc===g.cc&&this.fragmentTracker.getState(E)===he.NOT_LOADED&&(g=E),this.fragmentTracker.getState(g)===he.NOT_LOADED){const T=this.mapToInitFragWhenRequired(g);T&&this.loadFragment(T,s,o)}}}loadFragment(e,t,s){ge(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new md(this.tracksBuffered[this.currentTrackId]||[])}}class md{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 pd={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},to=n=>String.fromCharCode(pd[n]||n),Ce=15,Ke=100,yd={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Ed={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},Td={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Sd=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class xd{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;Q.log(`${this.time} [${e}] ${s}`)}}}const rt=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class so{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 Ad{constructor(){this.uchar=" ",this.penState=new so}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 Ld{constructor(e){this.chars=[],this.pos=0,this.currPenState=new so,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ke;t++)this.chars.push(new Ad);this.logger=e}equals(e){for(let t=0;t<Ke;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Ke;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Ke;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Ke&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ke)}moveCursor(e){const t=this.pos+e;if(e>1)for(let 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=to(e);if(this.pos>=Ke){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Ke;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<Ke;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 zs{constructor(e){this.rows=[],this.currRow=Ce-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Ce;t++)this.rows.push(new Ld(e));this.logger=e}reset(){for(let e=0;e<Ce;e++)this.rows[e].clear();this.currRow=Ce-1}equals(e){let t=!0;for(let s=0;s<Ce;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<Ce;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Ce;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 = "+ae(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<Ce;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 = "+ae(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<Ce;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(`
219`)),s}getTextAndFormat(){return this.rows}}class un{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 zs(s),this.nonDisplayedMemory=new zs(s),this.lastOutputScreen=new zs(s),this.currRollUpRow=this.displayedMemory.rows[Ce-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[Ce-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: "+ae(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 hn{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Rd(),this.logger=void 0;const i=this.logger=new xd;this.channels=[null,new un(e,t,i),new un(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,()=>"["+rt([t[s],t[s+1]])+"] -> ("+rt([i,r])+")");const c=this.cmdHistory;if(i>=16&&i<=31){if(Id(i,r,c)){Zt(null,null,c),this.logger.log(3,()=>"Repeated command ("+rt([i,r])+") is dropped");continue}Zt(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 Zt(null,null,c);if(!a&&(o=this.parseChars(i,r),o)){const u=this.currentChannel;u&&u>0?this.channels[u].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+rt([i,r])+" orig: "+rt([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 ("+rt([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?yd[e]:vd[e]:s=a===1?Ed[e]:Td[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 '"+to(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 =  "+rt(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=Sd[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()}Zt(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 Zt(n,e,t){t.a=n,t.b=e}function Id(n,e,t){return t.a===n&&t.b===e}function Rd(){return{a:null,b:null}}var Yi=function(){if(Ss!=null&&Ss.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 u=arguments[l];for(const h in u)o[h]=u[h]}return o}function a(o,c,l){const u=this,h={enumerable:!0};u.hasBeenReset=!1;let d="",f=!1,g=o,y=c,p=l,E=null,T="",v=!0,S="auto",x="start",_=50,A="middle",b=50,D="middle";Object.defineProperty(u,"id",r({},h,{get:function(){return d},set:function(L){d=""+L}})),Object.defineProperty(u,"pauseOnExit",r({},h,{get:function(){return f},set:function(L){f=!!L}})),Object.defineProperty(u,"startTime",r({},h,{get:function(){return g},set:function(L){if(typeof L!="number")throw new TypeError("Start time must be set to a number.");g=L,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",r({},h,{get:function(){return y},set:function(L){if(typeof L!="number")throw new TypeError("End time must be set to a number.");y=L,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",r({},h,{get:function(){return p},set:function(L){p=""+L,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",r({},h,{get:function(){return E},set:function(L){E=L,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",r({},h,{get:function(){return T},set:function(L){const k=s(L);if(k===!1)throw new SyntaxError("An invalid or illegal string was specified.");T=k,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",r({},h,{get:function(){return v},set:function(L){v=!!L,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",r({},h,{get:function(){return S},set:function(L){if(typeof L!="number"&&L!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=L,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",r({},h,{get:function(){return x},set:function(L){const k=i(L);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");x=k,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",r({},h,{get:function(){return _},set:function(L){if(L<0||L>100)throw new Error("Position must be between 0 and 100.");_=L,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",r({},h,{get:function(){return A},set:function(L){const k=i(L);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");A=k,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",r({},h,{get:function(){return b},set:function(L){if(L<0||L>100)throw new Error("Size must be between 0 and 100.");b=L,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",r({},h,{get:function(){return D},set:function(L){const k=i(L);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");D=k,this.hasBeenReset=!0}})),u.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class bd{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function io(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 _d{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 ro(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 vi=new Yi(0,0,""),Jt=vi.align==="middle"?"middle":"center";function Dd(n,e,t){const s=n;function i(){const o=io(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 _d;ro(o,function(d,f){let g;switch(d){case"region":for(let y=t.length-1;y>=0;y--)if(t[y].id===f){l.set(d,t[y].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",Jt,"end"]);break;case"position":g=f.split(","),l.percent(d,g[0]),g.length===2&&l.alt("positionAlign",g[1],["start",Jt,"end","line-left","line-right","auto"]);break;case"size":l.percent(d,f);break;case"align":l.alt(d,f,["start",Jt,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let u=l.get("line","auto");u==="auto"&&vi.line===-1&&(u=-1),c.line=u,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",Jt);let h=l.get("position","auto");h==="auto"&&vi.position===50&&(h=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=h}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 no(n){return n.replace(/<br(?: \/)?>/gi,`
220`)}class Cd{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new bd,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=no(r);a<r.length&&r[a]!=="\r"&&r[a]!==`
221`;)++a;const o=r.slice(0,a);return r[a]==="\r"&&++a,r[a]===`
222`&&++a,t.buffer=r.slice(a),o}function i(r){ro(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 Yi(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Dd(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+=`
223`),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+=`
224
225`,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 kd=/\r\n|\n\r|\n|\r/g,Xs=function(e,t,s=0){return e.slice(s,s+t.length)===t},Pd=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 qi(n,e,t){return Dt(n.toString())+Dt(e.toString())+Dt(t)}const wd=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 Od(n,e,t,s,i,r,a){const o=new Cd,c=Le(new Uint8Array(n)).trim().replace(kd,`
226`).split(`
227`),l=[],u=e?Zu(e.baseTime,e.timescale):0;let h="00:00.000",d=0,f=0,g,y=!0;o.oncue=function(p){const E=t[s];let T=t.ccOffset;const v=(d-u)/9e4;if(E!=null&&E.new&&(f!==void 0?T=t.ccOffset=E.start:wd(t,s,v)),v){if(!e){g=new Error("Missing initPTS for VTT MPEGTS");return}T=v-t.presentationOffset}const S=p.endTime-p.startTime,x=be((p.startTime+T-f)*9e4,i*9e4)/9e4;p.startTime=Math.max(x,0),p.endTime=Math.max(x+S,0);const _=p.text.trim();p.text=decodeURIComponent(encodeURIComponent(_)),p.id||(p.id=qi(p.startTime,p.endTime,_)),p.endTime>0&&l.push(p)},o.onparsingerror=function(p){g=p},o.onflush=function(){if(g){a(g);return}r(l)},c.forEach(p=>{if(y)if(Xs(p,"X-TIMESTAMP-MAP=")){y=!1,p.slice(16).split(",").forEach(E=>{Xs(E,"LOCAL:")?h=E.slice(6):Xs(E,"MPEGTS:")&&(d=parseInt(E.slice(7)))});try{f=Pd(h)/1e3}catch(E){g=E}return}else p===""&&(y=!1);o.parse(p+`
228`)}),o.flush()}const Qs="stpp.ttml.im1t",ao=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,oo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Md={left:"start",center:"center",right:"end",start:"start",end:"end"};function dn(n,e,t,s){const i=Y(new Uint8Array(n),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>Le(o)),a=Qu(e.baseTime,1,e.timescale);try{r.forEach(o=>t(Fd(o,a)))}catch(o){s(o)}}function Fd(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((h,d)=>(h[d]=i.getAttribute(`ttp:${d}`)||r[d],h),{}),o=i.getAttribute("xml:space")!=="preserve",c=fn(Zs(i,"styling","style")),l=fn(Zs(i,"layout","region")),u=Zs(i,"body","[begin]");return[].map.call(u,h=>{const d=lo(h,o);if(!d||!h.hasAttribute("begin"))return null;const f=ei(h.getAttribute("begin"),a),g=ei(h.getAttribute("dur"),a);let y=ei(h.getAttribute("end"),a);if(f===null)throw gn(h);if(y===null){if(g===null)throw gn(h);y=f+g}const p=new Yi(f-e,y-e,d);p.id=qi(p.startTime,p.endTime,p.text);const E=l[h.getAttribute("region")],T=c[h.getAttribute("style")],v=Nd(E,T,c),{textAlign:S}=v;if(S){const x=Md[S];x&&(p.lineAlign=x),p.align=S}return re(p,v),p}).filter(h=>h!==null)}function Zs(n,e,t){const s=n.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function fn(n){return n.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function lo(n,e){return[].slice.call(n.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+`
229`:(r=s.childNodes)!=null&&r.length?lo(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function Nd(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=Js(e,s,c)||Js(n,s,c)||Js(i,s,c);return l&&(o[c]=l),o},{})}function Js(n,e,t){return n&&n.hasAttributeNS(e,t)?n.getAttributeNS(e,t):null}function gn(n){return new Error(`Could not parse ttml timestamp ${n}`)}function ei(n,e){if(!n)return null;let t=io(n);return t===null&&(ao.test(n)?t=Bd(n,e):oo.test(n)&&(t=Ud(n,e))),t}function Bd(n,e){const t=ao.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 Ud(n,e){const t=oo.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 es{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 $d{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=pn(),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 es(this,"textTrack1"),t=new es(this,"textTrack2"),s=new es(this,"textTrack3"),i=new es(this,"textTrack4");this.cea608Parser1=new hn(1,e,t),this.cea608Parser2=new hn(3,s,i)}addCues(e,t,s,i,r){let a=!1;for(let o=r.length;o--;){const c=r[o],l=Gd(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}){const{unparsedVttFrags:a}=this;s===N.MAIN&&(this.initPTS[t.cc]={baseTime:i,timescale:r}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(m.FRAG_LOADED,o)}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(mn(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,mt(s[e]),Za(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=>{mt(i[r]),delete i[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=pn(),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++)mt(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(r=>r.textCodec===Qs);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(Wa(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const a=this.media,o=a?cs(a.textTracks):null;if(this.tracks.forEach((c,l)=>{let u;if(o){let h=null;for(let d=0;d<o.length;d++)if(o[d]&&mn(o[d],c)){h=o[d],o[d]=null;break}h&&(u=h)}if(u)mt(u);else{const h=co(c);u=this.createTextTrack(h,c.name,c.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),o!=null&&o.length){const c=o.filter(l=>l!==null).map(l=>l.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const 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===N.MAIN){var s,i;const{cea608Parser1:r,cea608Parser2:a,lastSn:o}=this,{cc:c,sn:l}=t.frag,u=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&a&&(l!==o+1||l===o&&u!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=c,this.lastSn=l,this.lastPartIndex=u}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===N.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===Qs?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;dn(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?_e(s.initSegment.data,new Uint8Array(i)).buffer:i;Od(l,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,u=>{this._appendCues(u,s.level),c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},u=>{const h=u.message==="Missing initPTS for VTT MPEGTS";h?a.push(e):this._fallbackToIMSC1(s,i),c.logger.log(`Failed to parse VTT cue: ${u}`),!(h&&o>s.cc)&&c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:u})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||dn(t,this.initPTS[e.cc],()=>{s.textCodec=Qs,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=>Ja(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===N.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===N.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=>yi(o[c],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>yi(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 u=3&a;(u===0||u===1)&&(t[u].push(o),t[u].push(c))}}return t}}function co(n){return n.characteristics&&/transcribes-spoken-dialog/gi.test(n.characteristics)&&/describes-music-and-sound/gi.test(n.characteristics)?"captions":"subtitles"}function mn(n,e){return!!n&&n.kind===co(e)&&gi(e,n)}function Gd(n,e,t,s){return Math.min(e,s)-Math.max(n,t)}function pn(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const Vd=/\s/,Kd={newCue(n,e,t,s){const i=[];let r,a,o,c,l;const u=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 h;for(let y=0;y<r.chars.length;y++)Vd.test(r.chars[y].uchar)&&o?c++:(l+=r.chars[y].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;const f=no(l.trim()),g=qi(e,t,f);n!=null&&(h=n.cues)!=null&&h.getCueById(g)||(a=new u(e,t,f),a.id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(a))}return 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=>Ja(n,d))),i}};function Hd(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Wd=/(\d+)-(\d+)\/(\d+)/;class yn{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||zd,this.controller=new self.AbortController,this.stats=new bi}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=Yd(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),(Nt(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var d;this.response=this.loader=h;const f=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(f-i.loading.start)),!h.ok){const{status:y,statusText:p}=h;throw new Xd(p||"fetch, bad network response",y,h)}i.loading.first=f,i.total=jd(h.headers)||i.total;const g=(d=this.callbacks)==null?void 0:d.onProgress;return g&&M(t.highWaterMark)?this.loadProgressively(h,i,e,t.highWaterMark,g):a?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{var d,f;const g=this.response;if(!g)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const y=h[o];y&&(i.loaded=i.total=y);const p={url:g.url,data:h,code:g.status},E=(d=this.callbacks)==null?void 0:d.onProgress;E&&!M(t.highWaterMark)&&E(i,e,h,g),(f=this.callbacks)==null||f.onSuccess(p,i,e,g)}).catch(h=>{var d;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const f=h&&h.code||0,g=h?h.message:null;(d=this.callbacks)==null||d.onError({code:f,text:g},e,h?h.details:null,i)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const a=new La,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 u=l.value,h=u.length;return t.loaded+=h,h<i||a.dataLength?(a.push(u),a.dataLength>=i&&r(t,s,a.flush().buffer,e)):r(t,s,u.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function Yd(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 qd(n){const e=Wd.exec(n);if(e)return parseInt(e[2])-parseInt(e[1])+1}function jd(n){const e=n.get("Content-Range");if(e){const s=qd(e);if(M(s))return s}const t=n.get("Content-Length");if(t)return parseInt(t)}function zd(n,e){return new self.Request(n.url,e)}class Xd extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const Qd=/^age:\s*[\d.]+\s*$/im;class uo{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 bi,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,u=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const g=u??t.response;if(g!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const y=t.responseType==="arraybuffer"?g.byteLength:g.length;s.loaded=s.total=y,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const p=(a=this.callbacks)==null?void 0:a.onProgress;p&&p(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 h=r.loadPolicy.errorRetry,d=s.retry,f={url:e.url,data:void 0,code:l};if(Ts(h,d,!1,f))this.retry(h);else{var c;Q.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(Ts(e,t,!0))this.retry(e);else{var s;Q.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=Ci(e,s.retry),s.retry++,Q.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&&Qd.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 Zd={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Jd=te(te({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,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,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:uo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Sc,bufferController:fh,capLevelController:Hi,errorController:bc,fpsController:id,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:fa,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,certLoadPolicy:{default:Zd},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},ef()),{},{subtitleStreamController:gd,subtitleTrackController:ad,timelineController:$d,audioStreamController:ch,audioTrackController:uh,emeController:yt,cmcdController:ed,contentSteeringController:sd,interstitialsController:fd});function ef(){return{cueHandler:Kd,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 tf(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=Ti(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(u=>{const h=`${a}Loading${u}`,d=e[h];if(d!==void 0&&c){l.push(h);const f=s[o].default;switch(e[o]={default:f},u){case"TimeOut":f.maxLoadTimeMs=d,f.maxTimeToFirstByteMs=d;break;case"MaxRetry":f.errorRetry.maxNumRetry=d,f.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":f.errorRetry.retryDelayMs=d,f.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=d,f.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${ae(e[o])}`)}),te(te({},s),e)}function Ti(n){return n&&typeof n=="object"?Array.isArray(n)?n.map(Ti):Object.keys(n).reduce((e,t)=>(e[t]=Ti(n[t]),e),{}):n}function sf(n,e){const t=n.loader;t!==yn&&t!==uo?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):Hd()&&(n.loader=yn,n.progressive=!0,n.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const us=2,rf=.1,nf=.05,af=100;class of extends ua{constructor(e,t){super("gap-controller",e.logger),this.hls=null,this.fragmentTracker=null,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(af),this.mediaSource=t.mediaSource;const s=this.media=t.media;Ye(s,"playing",this.onMediaPlaying),Ye(s,"waiting",this.onMediaWaiting),Ye(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&($e(s,"playing",this.onMediaPlaying),$e(s,"waiting",this.onMediaWaiting),$e(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{media:a,stalled:o}=this;if(!a)return;const{seeking:c}=a,l=this.seeking&&!c,u=!this.seeking&&c,h=a.paused&&!c||a.ended||a.playbackRate===0;if(this.seeking=c,e!==t){t&&(this.ended=0),this.moved=!0,c||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(u||l){l&&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 d=q.bufferInfo(a,e,0),f=d.nextStart||0,g=this.fragmentTracker;if(c&&g&&this.hls){const _=En(this.hls.inFlightFragments,e),A=d.len>us,b=!f||_||f-e>us&&!g.getPartialFragment(e);if(A||b)return;this.moved=!1}const y=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&g){if(!(d.len>0)&&!f)return;const A=Math.max(f,d.start||0)-e,D=!!(y!=null&&y.live)?y.targetduration*2:us,L=g.getPartialFragment(e);if(A>0&&(A<=D||L)){a.paused||this._trySkipBufferHole(L);return}}const p=r.detectStallWithCurrentTimeMs,E=self.performance.now(),T=this.waiting;if(o===null){T>0&&E-T<p?this.stalled=T:this.stalled=E;return}const v=E-o;if(!c&&(v>=p||T)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(y!=null&&y.live)&&Math.abs(e-((y==null?void 0:y.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return}const x=q.bufferInfo(a,e,r.maxBufferHole);this._tryFixBufferStall(x,v)}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,u=a[o+1].start;if((c===-1||c>o)&&u-l<1&&e-l<2){const h=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${u} buffered index: ${c}`);this.warn(h.message),this.media.currentTime+=1e-6;const d=this.fragmentTracker.getPartialFragment(e)||void 0,f=q.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:U.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:d,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t){var s,i;const{fragmentTracker:r,media:a}=this,o=(s=this.hls)==null?void 0:s.config;if(!a||!r||!o)return;const c=a.currentTime,l=(i=this.hls)==null?void 0:i.latestLevelDetails,u=r.getPartialFragment(c);if((u||l!=null&&l.live&&c<l.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;const h=e.buffered;(h&&h.length>1&&e.len>o.maxBufferHole||e.nextStart&&e.nextStart-c<o.maxBufferHole)&&(t>o.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}_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 (${ae(e)})`);this.warn(a.message),t.trigger(m.ERROR,{type:U.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 u=o.len<=r.maxBufferHole,h=o.len>0&&o.len<1&&i.readyState<3,d=c-a;if(d>0&&(u||h)){if(d>r.maxBufferHole){let g=!1;if(a===0){const y=s.getAppendedFrag(0,N.MAIN);y&&c<y.end&&(g=!0)}if(!g){const y=e||s.getAppendedFrag(a,N.MAIN);if(y){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||En(this.hls.inFlightFragments,c))return 0;let E=!1,T=y.end;for(;T<c;){const v=s.getPartialFragment(T);if(v)T+=v.duration;else{E=!0;break}}if(E)return 0}}}const f=Math.max(c+nf,a+rf);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}`);this.hls.trigger(m.ERROR,{type:U.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:g,reason:g.message,frag:e||void 0,buffer:o.len,bufferInfo:o})}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:U.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:U.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function En(n,e){const t=vn(n.main);if(t&&t.start<=e)return t;const s=vn(n.audio);return s&&s.start<=e?s:null}function vn(n){if(!n)return null;switch(n.state){case C.IDLE:case C.STOPPED:case C.ENDED:case C.ERROR:return null}return n.frag}const lf=.25;function Si(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Tn(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,ae(i?te({type:i},s):s))}return r}const ts=(()=>{const n=Si();try{n&&new n(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function cf(n){return Uint8Array.from(n.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class uf{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!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.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.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(){const e=this.hls.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&mt(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 Za(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:s,enableID3MetadataCues:i}}}=this;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=Si();if(a)for(let o=0;o<r.length;o++){const c=r[o].type;if(c===xe.emsg&&!s||!i)continue;const l=Pa(r[o].data);if(l){const u=r[o].pts;let h=u+r[o].duration;h>ts&&(h=ts),h-u<=0&&(h=u+lf);for(let f=0;f<l.length;f++){const g=l[f];if(!wa(g)){this.updateId3CueEnds(u,c);const y=Tn(a,u,h,g,c);y&&this.id3Track.addCue(y)}}}}}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===ts&&(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=u=>u.type===xe.audioId3&&c:i==="video"?l=u=>u.type===xe.emsg&&o:l=u=>u.type===xe.audioId3&&c||u.type===xe.emsg&&o,yi(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.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{id3Track:s}=this,{dateRanges:i}=e,r=Object.keys(i);let a=this.dateRangeCuesAppended;if(s&&t){var o;if((o=s.cues)!=null&&o.length){const u=Object.keys(a).filter(h=>!r.includes(h));for(let h=u.length;h--;){const d=u[h],f=a[d].cues;delete a[d],Object.keys(f).forEach(g=>{try{const y=f[g];y.removeEventListener("enter",this.onEventCueEnter),s.removeCue(y)}catch{}})}}else a=this.dateRangeCuesAppended={}}const c=e.fragments[e.fragments.length-1];if(r.length===0||!M(c==null?void 0:c.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=Si();for(let u=0;u<r.length;u++){const h=r[u],d=i[h],f=d.startTime,g=a[h],y=(g==null?void 0:g.cues)||{};let p=(g==null?void 0:g.durationKnown)||!1,E=ts;const{duration:T,endDate:v}=d;if(v&&T!==null)E=f+T,p=!0;else if(d.endOnNext&&!p){const x=r.reduce((_,A)=>{if(A!==d.id){const b=i[A];if(b.class===d.class&&b.startDate>d.startDate&&(!_||d.startDate<_.startDate))return b}return _},null);x&&(E=x.startTime,p=!0)}const S=Object.keys(d.attr);for(let x=0;x<S.length;x++){const _=S[x];if(!$c(_))continue;const A=y[_];if(A)p&&!g.durationKnown?A.endTime=E:Math.abs(A.startTime-f)>.01&&(A.startTime=f,A.endTime=E);else if(l){let b=d.attr[_];Gc(_)&&(b=cf(b));const L=Tn(l,f,E,{key:_,data:b},xe.dateRange);L&&(L.id=h,this.id3Track.addCue(L),y[_]=L,this.hls.config.interstitialsController&&(_==="X-ASSET-LIST"||_==="X-ASSET-URL")&&L.addEventListener("enter",this.onEventCueEnter))}}a[h]={cues:y,dateRange:d,durationKnown:p}}}}class hf{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 h=Math.min(2,Math.max(1,a)),d=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,f=Math.min(h,Math.max(1,d));this.changeMediaPlaybackRate(t,f)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration: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 u=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const s=this.levelDetails;if(s===null)return null;const i=s.edge,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 df extends Ki{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(u=>{var h;const d=u.attrs;let{audioCodec:f,videoCodec:g}=u;f&&(u.audioCodec=f=ps(f,s)||void 0),((h=g)==null?void 0:h.indexOf("avc1"))===0&&(g=u.videoCodec=oc(g));const{width:y,height:p,unknownCodecs:E}=u;let T=E?E.length:0;if(E)for(let k=T;k--;){const O=E[k];this.isAudioSupported(O)?(u.audioCodec=f=f?`${f},${O}`:O,T--,vt.audio[f.substring(0,4)]=2):this.isVideoSupported(O)&&(u.videoCodec=g=g?`${g},${O}`:O,T--,vt.video[g.substring(0,4)]=2)}if(o||(o=!!(y&&p)),c||(c=!!g),l||(l=!!f),T||f&&!this.isAudioSupported(f)||g&&!this.isVideoSupported(g)){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}const{CODECS:v,"FRAME-RATE":S,"HDCP-LEVEL":x,"PATHWAY-ID":_,RESOLUTION:A,"VIDEO-RANGE":b}=d,L=`${`${_||"."}-`}${u.bitrate}-${A}-${S}-${v}-${b}-${x}`;if(r[L])if(r[L].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const k=a[L]+=1;u.attrs["PATHWAY-ID"]=new Array(k+1).join(".");const O=this.createLevel(u);r[L]=O,i.push(O)}else r[L].addGroupId("audio",d.AUDIO),r[L].addGroupId("text",d.SUBTITLES);else{const k=this.createLevel(u);r[L]=k,a[L]=1,i.push(k)}}),this.filterAndSortMediaOptions(i,t,o,c,l)}createLevel(e){const t=new Pt(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=aa(i,[])}return t}isAudioSupported(e){return ai(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return ai(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,r){let a=[],o=[],c=e;if((s||i)&&r&&(c=c.filter(({videoCodec:p,videoRange:E,width:T,height:v})=>(!!p||!!(T&&v))&&dc(E))),c.length===0){Promise.resolve().then(()=>{if(this.hls){let p="no level with compatible codecs found in manifest",E=p;t.levels.length&&(E=`one or more CODECS in variant not supported: ${ae(t.levels.map(v=>v.attrs.CODECS).filter((v,S,x)=>x.indexOf(v)===S))}`,this.warn(E),p+=` (${E})`);const T=new Error(p);this.hls.trigger(m.ERROR,{type:U.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:T,reason:E})}});return}t.audioTracks&&(a=t.audioTracks.filter(p=>!p.audioCodec||this.isAudioSupported(p.audioCodec)),Sn(a)),t.subtitles&&(o=t.subtitles,Sn(o));const l=c.slice(0);c.sort((p,E)=>{if(p.attrs["HDCP-LEVEL"]!==E.attrs["HDCP-LEVEL"])return(p.attrs["HDCP-LEVEL"]||"")>(E.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&p.height!==E.height)return p.height-E.height;if(p.frameRate!==E.frameRate)return p.frameRate-E.frameRate;if(p.videoRange!==E.videoRange)return ys.indexOf(p.videoRange)-ys.indexOf(E.videoRange);if(p.videoCodec!==E.videoCodec){const T=fr(p.videoCodec),v=fr(E.videoCodec);if(T!==v)return v-T}if(p.uri===E.uri&&p.codecSet!==E.codecSet){const T=ms(p.codecSet),v=ms(E.codecSet);if(T!==v)return v-T}return p.averageBitrate!==E.averageBitrate?p.averageBitrate-E.averageBitrate:0});let u=l[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==l.length)){for(let p=0;p<l.length;p++)if(l[p].pathwayId===c[0].pathwayId){u=l[p];break}}this._levels=c;for(let p=0;p<c.length;p++)if(c[p]===u){var h;this._firstLevel=p;const E=u.bitrate,T=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${E}`),((h=this.hls.userConfig)==null?void 0:h.abrEwmaDefaultEstimate)===void 0){const v=Math.min(E,this.hls.config.abrEwmaDefaultEstimateMax);v>T&&T===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=v)}break}const d=r&&!i,f=this.hls.config,g=!!(f.audioStreamController&&f.audioTrackController),y={levels:c,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:g&&!d&&a.some(p=>!!p.url)};this.hls.trigger(m.MANIFEST_PARSED,y)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const u=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(m.ERROR,{type:U.OTHER_ERROR,details:R.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:u,reason:u.message}),h)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,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 u=this.switchParams(a.uri,i==null?void 0:i.details,l);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(i=>t.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===X.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===N.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));Sa(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 Sn(n){const e={};n.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function ho(){return self.SourceBuffer||self.WebKitSourceBuffer}function fo(){if(!et())return!1;const e=ho();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function ff(){if(!fo())return!1;const n=et();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(kt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>n.isTypeSupported(kt(e,"audio"))))}function gf(){var n;const e=ho();return typeof(e==null||(n=e.prototype)==null?void 0:n.changeType)=="function"}const mf=100;class pf extends Mi{constructor(e,t,s){super(e,t,s,"stream-controller",N.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,N.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(mf),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=C.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=C.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case C.WAITING_LEVEL:{const{levels:t,level:s}=this,i=t==null?void 0:t[s],r=i==null?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))break;this.state=C.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=C.IDLE;break}break}case C.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),s=this.retryDate;if(!s||t>=s||(e=this.media)!=null&&e.seeking){const{levels:i,level:r}=this,a=i==null?void 0:i[r];this.resetStartWhenNotLoaded(a||null),this.state=C.IDLE}}break}this.state===C.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 y={};this.altAudio===2&&(y.type="video"),this.hls.trigger(m.BUFFER_EOS,y),this.state=C.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===C.WAITING_LEVEL||this.waitForLive(a)){this.level=r,this.state=C.WAITING_LEVEL,this.startFragRequested=!1;return}const u=o.len,h=this.getMaxBufferLength(a.maxBitrate);if(u>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(d,l);if(this.couldBacktrack&&!this.fragPrevious&&f&&ge(f)&&this.fragmentTracker.getState(f)!==he.OK){var g;const p=((g=this.backtrackFragment)!=null?g:f).sn-l.startSN,E=l.fragments[p-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 p=this.audioOnly&&!this.altAudio?ie.AUDIO:ie.VIDEO,E=(p===ie.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,p,N.MAIN)}f=this.getNextFragmentLoopLoading(f,l,o,N.MAIN,h)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,d))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===he.NOT_LOADED||i===he.PARTIAL?ge(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,N.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,u=Math.max(a.end,c+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(u,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case C.KEY_LOADING:case C.FRAG_LOADING:case C.FRAG_LOADING_WAITING_RETRY:case C.PARSING:case C.PARSED:this.state=C.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;Ye(s,"playing",this.onMediaPlaying),Ye(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&($e(s,"playing",this.onMediaPlaying),$e(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;t.levels.forEach(r=>{const a=r.audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,i=i||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=s&&i&&!gf(),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!==C.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=C.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,u=this.fragCurrent;u&&(this.state===C.FRAG_LOADING||this.state===C.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let h=0;if(o.live||(s=l.details)!=null&&s.live){var d;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;h=this.alignPlaylists(o,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(l.details=o,this.levelLastLoaded=l,r||this.setStartPosition(o,h),this.hls.trigger(m.LEVEL_UPDATED,{details:o,level:a}),this.state===C.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=C.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 l=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!c&&s.readyState<4||r<o-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState&&(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),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,u=c.PTSKnown||!c.live,h=(t=s.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Ha(this.hls,N.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=i?i.index:-1,y=g!==-1,p=new Pi(s.level,s.sn,s.stats.chunkCount,r.byteLength,g,y),E=this.initPTS[s.cc];f.push(r,h,d,l,s,i,c.totalduration,u,p,E)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio===2;if(Es(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.fragmentTracker.removeAllFragments(),s.once(m.BUFFER_FLUSHED,()=>{var a;(a=this.hls)==null||a.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=Es(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===N.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===C.PARSED&&(this.state=C.IDLE);return}const o=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),ge(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=C.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(N.MAIN,t);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===X.LEVEL&&(this.state=C.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=C.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ie.AUDIO||!this.altAudio){const s=(t===ie.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,N.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);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=C.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})}_handleTransmuxComplete(e){var t;const s=this.playlistType,{hls:i}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:c,part:l,level:u}=o,{video:h,text:d,id3:f,initSegment:g}=r,{details:y}=u,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(c)){this.fragmentTracker.removeFragment(c);return}if(this.state=C.PARSING,g){if(g!=null&&g.tracks){const v=c.initSegment||c;this._bufferInitSegment(u,g.tracks,v,a),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:s,tracks:g.tracks})}const E=g.initPTS,T=g.timescale;M(E)&&(this.initPTS[c.cc]={baseTime:E,timescale:T},i.trigger(m.INIT_PTS_FOUND,{frag:c,id:s,initPTS:E,timescale:T}))}if(h&&y){p&&h.type==="audiovideo"&&this.logMuxedErr(c);const E=y.fragments[c.sn-1-y.startSN],T=c.sn===y.startSN,v=!E||c.cc>E.cc;if(r.independent!==!1){const{startPTS:S,endPTS:x,startDTS:_,endDTS:A}=h;if(l)l.elementaryStreams[h.type]={startPTS:S,endPTS:x,startDTS:_,endDTS:A};else if(h.firstKeyFrame&&h.independent&&a.id===1&&!v&&(this.couldBacktrack=!0),h.dropped&&h.independent){const b=this.getMainFwdBufferInfo(),D=(b?b.end:this.getLoadPosition())+this.config.maxBufferHole,L=h.firstKeyFramePTS?h.firstKeyFramePTS:S;if(!T&&D<L-this.config.maxBufferHole&&!v){this.backtrack(c);return}else v&&(c.gap=!0);c.setElementaryStreamInfo(h.type,c.start,x,c.start,A,!0)}else T&&S-(y.appliedTimelineOffset||0)>us&&(c.gap=!0);c.setElementaryStreamInfo(h.type,S,x,_,A),this.backtrackFragment&&(this.backtrackFragment=c),this.bufferFragmentData(h,c,l,a,T||v)}else if(T||v)c.gap=!0;else{this.backtrack(c);return}}if(p){const{startPTS:E,endPTS:T,startDTS:v,endDTS:S}=p;l&&(l.elementaryStreams[ie.AUDIO]={startPTS:E,endPTS:T,startDTS:v,endDTS:S}),c.setElementaryStreamInfo(ie.AUDIO,E,T,v,S),this.bufferFragmentData(p,c,l,a)}if(y&&f!=null&&(t=f.samples)!=null&&t.length){const E={id:s,frag:c,details:y,samples:f.samples};i.trigger(m.FRAG_PARSING_METADATA,E)}if(y&&d){const E={id:s,frag:c,details:y,samples:d.samples};i.trigger(m.FRAG_PARSING_USERDATA,E)}}logMuxedErr(e){this.warn(`${ge(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==C.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){let l=rs(r.codec,e.audioCodec);l==="mp4a"&&(l="mp4a.40.5");const u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5");const h=r.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(l="mp4a.40.5")}l&&l.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),r.levelCodec=l,r.id=N.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${r.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=N.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 h=t[l].initSegment;h!=null&&h.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:h,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,N.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=C.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?lt(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 yf{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[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.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=R.KEY_LOAD_ERROR,s,i,r){return new He({type:U.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:i}=e;for(let r=0;r<t.length;r++){const a=t[r];if(i<=a.cc&&(s==="initSegment"||a.sn==="initSegment"||s<a.sn)){this.emeController.selectKeySystemFormat(a).then(o=>{a.setKeyFormat(o)});break}}}}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");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}"`)));let o=this.keyUriToKeyInfo[a];if((s=o)!=null&&s.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((i=o)!=null&&i.keyLoadPromise){var c;switch((c=o.mediaKeySessionContext)==null?void 0:c.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(l=>(r.key=l.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,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){const i=this.emeController.loadKey(s);if(i)return(e.keyLoadPromise=i.then(r=>(e.mediaKeySessionContext=r,s))).catch(r=>{throw e.keyLoadPromise=null,r})}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,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,f,g,y)=>{const{frag:p,keyInfo:E,url:T}=g;if(!p.decryptdata||E!==this.keyUriToKeyInfo[T])return o(this.createKeyLoadError(p,R.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),y));E.decryptdata.key=p.decryptdata.key=new Uint8Array(d.data),p.keyLoader=null,E.loader=null,a({frag:p,keyInfo:E})},onError:(d,f,g,y)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),g,te({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,u,h)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[i],r&&r.destroy()}}function xn(n){const{type:e}=n;switch(e){case X.AUDIO_TRACK:return N.AUDIO;case X.SUBTITLE_TRACK:return N.SUBTITLE;default:return N.MAIN}}function ti(n,e){let t=n.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Ef{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:X.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:X.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:X.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:X.SUBTITLE_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const s=this.loaders[X.LEVEL];if(s){const i=s.context;i&&!t.levels.some(r=>r===i.levelOrTrack)&&(s.abort(),delete this.loaders[X.LEVEL])}}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const l=this.hls.logger,u=i.context;if(u&&u.levelOrTrack===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===X.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===X.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===X.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===X.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const u=l.partTarget,h=l.targetduration;if(u&&h){const d=Math.max(u*3,h*.8)*1e3;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,u,h,d)=>{const f=this.getInternalLoader(h);this.resetInternalLoader(h.type);const g=l.data;if(g.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(l,h,new Error("no EXTM3U delimiter"),d||null,u);return}u.parsing.start=performance.now(),Ue.isMediaPlaylist(g)||h.type!==X.MANIFEST?this.handleTrackOrLevelPlaylist(l,u,h,d||null,f):this.handleMasterPlaylist(l,u,h,d)},onError:(l,u,h,d)=>{this.handleNetworkError(u,h,!1,l,d)},onTimeout:(l,u,h)=>{this.handleNetworkError(u,h,!0,void 0,l)}};i.load(e,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,a=e.data,o=ti(e,s),c=Ue.parseMasterPlaylist(a,o);if(c.playlistParsingError){this.handleManifestParsingError(e,s,c.playlistParsingError,i,t);return}const{contentSteering:l,levels:u,sessionData:h,sessionKeys:d,startTimeOffset:f,variableList:g}=c;this.variableList=g;const{AUDIO:y=[],SUBTITLES:p,"CLOSED-CAPTIONS":E}=Ue.parseMasterPlaylistMedia(a,o,c);y.length&&!y.some(v=>!v.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),y.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new oe({}),bitrate:0,url:""})),r.trigger(m.MANIFEST_LOADED,{levels:u,audioTracks:y,subtitles:p,captions:E,contentSteering:l,url:o,stats:t,networkDetails:i,sessionData:h,sessionKeys:d,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,s,i,r){const a=this.hls,{id:o,level:c,type:l}=s,u=ti(e,s),h=M(c)?c:M(o)?o:0,d=xn(s),f=Ue.parseLevelPlaylist(e.data,u,h,d,0,this.variableList);if(l===X.MANIFEST){const g={attrs:new oe({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=t.loading.start+Ea(f,0),a.trigger(m.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:u,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(m.ERROR,{type:U.NETWORK_ERROR,details:R.MANIFEST_PARSING_ERROR,fatal:t.type===X.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===X.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===X.AUDIO_TRACK||e.type===X.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let c=R.UNKNOWN,l=!1;const u=this.getInternalLoader(e);switch(e.type){case X.MANIFEST:c=s?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,l=!0;break;case X.LEVEL:c=s?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,l=!1;break;case X.AUDIO_TRACK:c=s?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case X.SUBTITLE_TRACK:c=s?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,l=!1;break}u&&this.resetInternalLoader(e.type);const h={type:U.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:r};if(i){const d=(t==null?void 0:t.url)||e.url;h.response=te({url:d,data:void 0},i)}this.hls.trigger(m.ERROR,h)}handlePlaylistLoaded(e,t,s,i,r,a){const o=this.hls,{type:c,level:l,id:u,groupId:h,deliveryDirectives:d}=i,f=ti(t,i),g=xn(i),y=typeof i.level=="number"&&g===N.MAIN?l:void 0;if(!e.fragments.length){const E=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:U.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:E,reason:E.message,response:t,context:i,level:y,parent:g,networkDetails:r,stats:s});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const p=e.playlistParsingError;if(p){if(this.hls.logger.warn(p),!o.config.ignorePlaylistParsingErrors){o.trigger(m.ERROR,{type:U.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:i,level:y,parent:g,networkDetails:r,stats:s});return}e.playlistParsingError=null}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case X.MANIFEST:case X.LEVEL:o.trigger(m.LEVEL_LOADED,{details:e,levelInfo:i.levelOrTrack||o.levels[0],level:y||0,id:u||0,stats:s,networkDetails:r,deliveryDirectives:d,withoutMultiVariant:c===X.MANIFEST});break;case X.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:e,track:i.levelOrTrack,id:u||0,groupId:h||"",stats:s,networkDetails:r,deliveryDirectives:d});break;case X.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:e,track:i.levelOrTrack,id:u||0,groupId:h||"",stats:s,networkDetails:r,deliveryDirectives:d});break}}}class Fe{static get version(){return Mt}static isMSESupported(){return fo()}static isSupported(){return ff()}static getMediaSource(){return et()}static get Events(){return m}static get MetadataSchema(){return xe}static get ErrorTypes(){return U}static get ErrorDetails(){return R}static get DefaultConfig(){return Fe.defaultConfig?Fe.defaultConfig:Jd}static set DefaultConfig(e){Fe.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 Fi,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=Fl(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=tf(Fe.DefaultConfig,e,t);this.userConfig=e,s.progressive&&sf(s,t);const{abrController:i,bufferController:r,capLevelController:a,errorController:o,fpsController:c}=s,l=new o(this),u=this.abrController=new i(this),h=new _c(this),d=s.interstitialsController,f=d?this.interstitialsController=new d(this,Fe):null,g=this.bufferController=new r(this,h),y=this.capLevelController=new a(this),p=new c(this),E=new Ef(this),T=s.contentSteeringController,v=T?new T(this):null,S=this.levelController=new df(this,v),x=new uf(this),_=new yf(this.config),A=this.streamController=new pf(this,h,_),b=this.gapController=new of(this,h);y.setStreamController(A),p.setStreamController(A);const D=[E,S,A];f&&D.splice(1,0,f),v&&D.splice(1,0,v),this.networkControllers=D;const L=[u,g,b,y,p,x,h];this.audioTrackController=this.createController(s.audioTrackController,D);const k=s.audioStreamController;k&&D.push(this.audioStreamController=new k(this,h,_)),this.subtitleTrackController=this.createController(s.subtitleTrackController,D);const O=s.subtitleStreamController;O&&D.push(this.subtititleStreamController=new O(this,h,_)),this.createController(s.timelineController,L),_.emeController=this.emeController=this.createController(s.emeController,L),this.cmcdController=this.createController(s.cmcdController,L),this.latencyController=this.createController(hf,L),this.coreComponents=L,D.push(l);const z=l.onErrorOut;typeof z=="function"&&this.on(m.ERROR,z,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:U.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:U.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=Ri.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={[N.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[N.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[N.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=Ru()),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){hc(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;
229if(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=la(t);return oa(e,s,navigator.mediaCapabilities)}}Fe.defaultConfig=void 0;Fn.registerPlugin(Nn);function vf(n){const e=Ae(!1);let t;return Ut(()=>{const s=n();s&&Fn.delayedCall(1,()=>{t=Nn.create({trigger:s,start:"top bottom",onEnter:()=>e.value=!0})})}),Ii(()=>{t&&t.kill()}),{isInView:e}}const Tf=["playsinline","muted","loop"],Sf={__name:"Video",props:{media:Object,classNames:[String,Object,Array],lazyVideo:{type:Boolean,default:!1},autoplay:{type:Boolean,default:!0},playsinline:{type:Boolean,default:!0},muted:{type:Boolean,default:!0},loop:{type:Boolean,default:!0}},setup(n){const e=n,{isInView:t}=vf(()=>e.lazyVideo?i.value:null),s=Ae(!0),i=Ae(null);le(()=>`https://image.mux.com/${e.media.playbackId}/thumbnail.webp?time=${e.media.thumbTime}&width=5`);const r=`aspect-ratio:${e.media.aspectRatio.split(":")[0]/e.media.aspectRatio.split(":")[1]}`,a=()=>{i.value.play().catch(o=>console.log("video play error",o))};return Ut(()=>{const{playbackId:o}=e.media;if(e.media.mp4Supported){const c=`https://stream.mux.com/${o}/high.mp4`;i.value.src=c}else{const c=`https://stream.mux.com/${o}.m3u8`;if(Fe.isSupported()){const l=new Fe;l.loadSource(c),l.attachMedia(i.value),l.on(Fe.Events.MANIFEST_PARSED,(u,h)=>{const d=h.levels.length-1;l.currentLevel=d})}else i.value.canPlayType("application/vnd.apple.mpegurl")&&(i.value.src=c)}i.value.addEventListener("loadeddata",()=>s.value=!1),!e.lazyVideo&&e.autoplay&&a()}),Co(t,o=>{o&&e.lazyVideo&&a()}),(o,c)=>{const l=Wn;return qe(),Rs(Oo,null,[ko(Bn(l,{src:e.media.playbackId,class:ds([n.classNames,"absolute inset-0"]),loading:"lazy",style:r,provider:"mux",alt:"Mux Thumbnail"},null,8,["src","class"]),[[wo,ue(s)]]),Po("video",{ref_key:"video",ref:i,class:ds(n.classNames),playsinline:n.playsinline,muted:n.muted,loop:n.loop,style:r},null,10,Tf)],64)}}},xf=Mn(Sf,[["__scopeId","data-v-58e9a739"]]),Eg={__name:"Media",props:{media:Object,assetClassNames:[String,Object,Array],width:Number,preload:{type:Boolean,default:!1},lazy:{type:Boolean,default:!1},lazyVideo:{type:Boolean,default:!1},autoplay:{type:Boolean,default:!0},isRelative:{type:Boolean,default:!0}},setup(n){const e=n.media.type==="image"||n.media._type==="mainImage",t=n.media.type==="video"||n.media._type==="mainVideo";return(s,i)=>{const r=bl,a=xf;return qe(),Rs("figure",{class:ds({"overflow-hidden":ue(t)&&n.media.playbackId,relative:ue(t)&&n.media.playbackId&&n.isRelative})},[ue(e)&&n.media.image?(qe(),Ct(r,{key:0,preload:n.preload,lazy:n.lazy,width:n.width,media:n.media,src:n.media.image,alt:n.media.alt,"class-names":n.assetClassNames},null,8,["preload","lazy","width","media","src","alt","class-names"])):si("",!0),ue(t)&&n.media.playbackId?(qe(),Ct(a,{key:1,media:n.media,autoplay:n.autoplay,"lazy-video":n.lazyVideo,"class-names":n.assetClassNames}
229,null,8,["media","autoplay","lazy-video","class-names"])):si("",!0)],2)}}};function An(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 Ln(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?An(Object(t),!0).forEach(function(s){Af(n,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):An(Object(t)).forEach(function(s){Object.defineProperty(n,s,Object.getOwnPropertyDescriptor(t,s))})}return n}function Af(n,e,t){return(e=Lf(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function Lf(n){var e=If(n,"string");return typeof e=="symbol"?e:e+""}function If(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 Is(n){return n._type==="span"&&"text"in n&&typeof n.text=="string"&&(typeof n.marks>"u"||Array.isArray(n.marks)&&n.marks.every(e=>typeof e=="string"))}function go(n){return typeof n._type=="string"&&n._type[0]!=="@"&&(!("markDefs"in n)||!n.markDefs||Array.isArray(n.markDefs)&&n.markDefs.every(e=>typeof e._key=="string"))&&"children"in n&&Array.isArray(n.children)&&n.children.every(e=>typeof e=="object"&&"_type"in e)}function mo(n){return go(n)&&"listItem"in n&&typeof n.listItem=="string"&&(typeof n.level>"u"||typeof n.level=="number")}function po(n){return n._type==="@list"}function yo(n){return n._type==="@span"}function Eo(n){return n._type==="@text"}const In=["strong","em","code","underline","strike-through"];function Rf(n,e,t){if(!Is(n)||!n.marks)return[];if(!n.marks.length)return[];const s=n.marks.slice(),i={};return s.forEach(r=>{i[r]=1;for(let a=e+1;a<t.length;a++){const o=t[a];if(o&&Is(o)&&Array.isArray(o.marks)&&o.marks.indexOf(r)!==-1)i[r]++;else break}}),s.sort((r,a)=>bf(i,r,a))}function bf(n,e,t){const s=n[e],i=n[t];if(s!==i)return i-s;const r=In.indexOf(e),a=In.indexOf(t);return r!==a?r-a:e.localeCompare(t)}function _f(n){var e,t;const{children:s}=n,i=(e=n.markDefs)!=null?e:[];if(!s||!s.length)return[];const r=s.map(Rf),a={_type:"@span",children:[],markType:"<unknown>"};let o=[a];for(let c=0;c<s.length;c++){const l=s[c];if(!l)continue;const u=r[c]||[];let h=1;if(o.length>1)for(h;h<o.length;h++){const f=((t=o[h])==null?void 0:t.markKey)||"",g=u.indexOf(f);if(g===-1)break;u.splice(g,1)}o=o.slice(0,h);let d=o[o.length-1];if(d){for(const f of u){const g=i==null?void 0:i.find(E=>E._key===f),y=g?g._type:f,p={_type:"@span",_key:l._key,children:[],markDef:g,markType:y,markKey:f};d.children.push(p),o.push(p),d=p}if(Is(l)){const f=l.text.split(`
230`);for(let g=f.length;g-- >1;)f.splice(g,0,`
231`);d.children=d.children.concat(f.map(g=>({_type:"@text",text:g})))}else d.children=d.children.concat(l)}}return a.children}function Df(n,e){const t=[];let s;for(let i=0;i<n.length;i++){const r=n[i];if(r){if(!mo(r)){t.push(r),s=void 0;continue}if(!s){s=ss(r,i,e),t.push(s);continue}if(Cf(r,s)){s.children.push(r);continue}if((r.level||1)>s.level){const a=ss(r,i,e);if(e==="html"){const o=s.children[s.children.length-1],c=Ln(Ln({},o),{},{children:[...o.children,a]});s.children[s.children.length-1]=c}else s.children.push(a);s=a;continue}if((r.level||1)<s.level){const a=t[t.length-1],o=a&&xi(a,r);if(o){s=o,s.children.push(r);continue}s=ss(r,i,e),t.push(s);continue}if(r.listItem!==s.listItem){const a=t[t.length-1],o=a&&xi(a,{level:r.level||1});if(o&&o.listItem===r.listItem){s=o,s.children.push(r);continue}else{s=ss(r,i,e),t.push(s);continue}}console.warn("Unknown state encountered for block",r),t.push(r)}}return t}function Cf(n,e){return(n.level||1)===e.level&&n.listItem===e.listItem}function ss(n,e,t){return{_type:"@list",_key:`${n._key||`${e}`}-parent`,mode:t,level:n.level||1,listItem:n.listItem,children:[n]}}function xi(n,e){const t=e.level||1,s=e.listItem||"normal",i=typeof e.listItem=="string";if(po(n)&&(n.level||1)===t&&i&&(n.listItem||"normal")===s)return n;if(!("children"in n))return;const r=n.children[n.children.length-1];return r&&!Is(r)?xi(r,e):void 0}function vo(n){let e="";
231return n.children.forEach(t=>{Eo(t)?e+=t.text:yo(t)&&(e+=vo(t))}),e}const kf="html";function Pf(n,e){const{block:t,list:s,listItem:i,marks:r,types:a,...o}=e;return{...n,block:It(n,e,"block"),list:It(n,e,"list"),listItem:It(n,e,"listItem"),marks:It(n,e,"marks"),types:It(n,e,"types"),...o}}function It(n,e,t){const s=e[t],i=n[t];return typeof s=="function"||s&&typeof i=="function"?s:s?{...i,...s}:i}const fe=n=>(e,{slots:t})=>{var s;return me(n,(s=t.default)==null?void 0:s.call(t))},wf=({value:n},{slots:e})=>{var t;return me("a",{href:n==null?void 0:n.href},(t=e.default)==null?void 0:t.call(e))},Of={textDecoration:"underline"},Mf={code:fe("code"),em:fe("em"),link:wf,"strike-through":fe("del"),strong:fe("strong"),underline:(n,{slots:e})=>{var t;return me("span",{style:Of},(t=e.default)==null?void 0:t.call(e))}},Ff={number:fe("ol"),bullet:fe("ul")},Nf=fe("li"),$t=(n,e)=>`[@portabletext/vue] Unknown ${n}, specify a component for it in the \`components.${e}\` prop`,To=n=>$t(`block type "${n}"`,"types"),Bf=n=>$t(`mark type "${n}"`,"marks"),Uf=n=>$t(`block style "${n}"`,"block"),$f=n=>$t(`list style "${n}"`,"list"),Gf=n=>$t(`list item style "${n}"`,"listItem");function Vf(n){console.warn(n)}const Rn={display:"none"},Kf=({value:n,isInline:e})=>{const t=To(n._type);return e?me("span",{style:Rn},t):me("div",{style:Rn},t)},Hf=({markType:n},{slots:e})=>{var t;return me("span",{class:`unknown__pt__mark__${n}`},(t=e.default)==null?void 0:t.call(e))},Wf=fe("p"),Yf=fe("ul"),qf=fe("li"),jf=()=>me("br"),zf={normal:fe("p"),blockquote:fe("blockquote"),h1:fe("h1"),h2:fe("h2"),h3:fe("h3"),h4:fe("h4"),h5:fe("h5"),h6:fe("h6")},bn={types:{},block:zf,marks:Mf,list:Ff,listItem:Nf,hardBreak:jf,unknownType:Kf,unknownMark:Hf,unknownList:Yf,unknownListItem:qf,unknownBlockStyle:Wf},Xf=(n,e)=>{function t(h){const{node:d,index:f,isInline:g}=h,y=d._key||`node-${f}`;return po(d)?r(d,f,y):mo(d)?i(d,f,y):yo(d)?a(d,f,y):s(d)?u(d,f,y,g):go(d)?o(d,f,y,g):Eo(d)?c(d,y):l(d,f,y,g)}function s(h){return h._type in n.types}function i(h,d,f){const g=_n({node:h,index:d,isInline:!1,renderNode:t}),y=n.listItem,p=(typeof y=="function"?y:y[h.listItem])||n.unknownListItem;if(p===n.unknownListItem){const T=h.listItem||"bullet";e(Gf(T),{type:T,nodeType:"listItemStyle"})}let E=g.children;if(h.style&&h.style!=="normal"){const{listItem:T,...v}=h;E=t({node:v,index:d,isInline:!1})}return me(p,{key:f,value:h,index:d,isInline:!1,renderNode:t},()=>E)}function r(h,d,f){const g=h.children.map((E,T)=>t({node:E._key?E:{...E,_key:`li-${d}-${T}`},index:T,isInline:!1})),y=n.list,p=(typeof y=="function"?y:y[h.listItem])||n.unknownList;if(p===n.unknownList){const E=h.listItem||"bullet";e($f(E),{nodeType:"listStyle",type:E})}return me(p,{key:f,value:h,index:d,isInline:!1,renderNode:t},()=>g)}function a(h,d,f){const{markDef:g,markType:y,markKey:p}=h,E=n.marks[y]||n.unknownMark,T=h.children.map((v,S)=>t({node:v,index:S,isInline:!0}));return E===n.unknownMark&&e(Bf(y),{nodeType:"mark",type:y}),me(E,{key:f,text:vo(h),value:g,markType:y,markKey:p,renderNode:t},()=>T)}function o(h,d,f,g){const{_key:y,children:p,...E}=_n({node:h,index:d,isInline:g,renderNode:t}),T=E.node.style||"normal",v=(typeof n.block=="function"?n.block:n.block[T])||n.unknownBlockStyle;return v===n.unknownBlockStyle&&e(Uf(T),{nodeType:"blockStyle",type:T}),me(v,{key:f,...E,value:E.node,renderNode:t},()=>p)}function c(h,d){if(h.text===`
232`){const f=n.hardBreak;return f?me(f,{key:d}):`
233`}return h.text}function l(h,d,f,g){const y={value:h,isInline:g,index:d,renderNode:t};e(To(h._type),{nodeType:"block",type:h._type});const p=n.unknownType;return me(p,{key:f,...y})}function u(h,d,f,g){const y={value:h,isInline:g,index:d,renderNode:t},p=n.types[h._type];return p?me(p,{key:f,...y}):void 0}return t};function _n(n){const{node:e,index:t,isInline:s,renderNode:i}=n,r=_f(e).map((a,o)=>i({node:a,isInline:!0,index:o,renderNode:i}));return{_key:e._key||`block-${t}`,children:r,index:t,isInline:s,node:e}}const Qf=Li({__name:"vue-portable-text",props:{value:{},components:{},onMissingComponent:{type:[Function,Boolean],default:()=>Vf},listNestingMode:{}},setup(n){function e(){}const t=n,s=()=>{const i=t.onMissingComponent||e,r=Array.isArray(t.value)?t.value:[t.value],a=Df(r,t.listNestingMode||kf),o=t.components?Pf(bn,t.components):bn,c=Xf(o,i);return a.map((l,u)=>c({node:l,index:u,isInline:!1,renderNode:c}))};return(i,r)=>
233(qe(),Ct(s))}});async function So(n,e=fs()){const{path:t,matched:s}=e.resolve(n);if(!s.length||(e._routePreloaded||(e._routePreloaded=new Set),e._routePreloaded.has(t)))return;const i=e._preloadPromises||(e._preloadPromises=[]);if(i.length>4)return Promise.all(i).then(()=>So(n,e));e._routePreloaded.add(t);const r=s.map(a=>{var o;return(o=a.components)==null?void 0:o.default}).filter(a=>typeof a=="function");for(const a of r){const o=Promise.resolve(a()).catch(()=>{}).finally(()=>i.splice(i.indexOf(o)));i.push(o)}await Promise.all(i)}const Zf=(...n)=>n.find(e=>e!==void 0);function Jf(n){const e=n.componentName||"NuxtLink";function t(r){return typeof r=="string"&&r.startsWith("#")}function s(r,a,o){const c=o??n.trailingSlash;if(!r||c!=="append"&&c!=="remove")return r;if(typeof r=="string")return is(r,c);const l="path"in r&&r.path!==void 0?r.path:a(r).path;return{...r,name:void 0,path:is(l,c)}}function i(r){const a=fs(),o=wn(),c=le(()=>!!r.target&&r.target!=="_self"),l=le(()=>{const p=r.to||r.href||"";return typeof p=="string"&&hs(p,{acceptRelative:!0})}),u=sr("RouterLink"),h=typeof u!="string"?u.useLink:void 0,d=le(()=>{if(r.external)return!0;const p=r.to||r.href||"";return typeof p=="object"?!1:p===""||l.value}),f=le(()=>{const p=r.to||r.href||"";return d.value?p:s(p,a.resolve,r.trailingSlash)}),g=d.value||h==null?void 0:h({...r,to:f}),y=le(()=>{var E;const p=r.trailingSlash??n.trailingSlash;if(!f.value||l.value||t(f.value))return f.value;if(d.value){const T=typeof f.value=="object"&&"path"in f.value?ir(f.value):f.value,v=typeof T=="object"?a.resolve(T).href:T;return is(v,p)}return typeof f.value=="object"?((E=a.resolve(f.value))==null?void 0:E.href)??null:is(Ai(o.app.baseURL,f.value),p)});return{to:f,hasTarget:c,isAbsoluteUrl:l,isExternal:d,href:y,isActive:(g==null?void 0:g.isActive)??le(()=>f.value===a.currentRoute.value.path),isExactActive:(g==null?void 0:g.isExactActive)??le(()=>f.value===a.currentRoute.value.path),route:(g==null?void 0:g.route)??le(()=>a.resolve(f.value)),async navigate(p){await Uo(y.value,{replace:r.replace,external:d.value||c.value})}}}return Li({name:e,props:{to:{type:[String,Object],default:void 0,required:!1},href:{type:[String,Object],default:void 0,required:!1},target:{type:String,default:void 0,required:!1},rel:{type:String,default:void 0,required:!1},noRel:{type:Boolean,default:void 0,required:!1},prefetch:{type:Boolean,default:void 0,required:!1},prefetchOn:{type:[String,Object],default:void 0,required:!1},noPrefetch:{type:Boolean,default:void 0,required:!1},activeClass:{type:String,default:void 0,required:!1},exactActiveClass:{type:String,default:void 0,required:!1},prefetchedClass:{type:String,default:void 0,required:!1},replace:{type:Boolean,default:void 0,required:!1},ariaCurrentValue:{type:String,default:void 0,required:!1},external:{type:Boolean,default:void 0,required:!1},custom:{type:Boolean,default:void 0,required:!1},trailingSlash:{type:String,default:void 0,required:!1}},useLink:i,setup(r,{slots:a}){const o=fs(),{to:c,href:l,navigate:u,isExternal:h,hasTarget:d,isAbsoluteUrl:f}=i(r),g=Ae(!1),y=Ae(null),p=v=>{var S;y.value=r.custom?(S=v==null?void 0:v.$el)==null?void 0:S.nextElementSibling:v==null?void 0:v.$el};function E(v){var S,x;return!g.value&&(typeof r.prefetchOn=="string"?r.prefetchOn===v:((S=r.prefetchOn)==null?void 0:S[v])??((x=n.prefetchOn)==null?void 0:x[v]))&&(r.prefetch??n.prefetch)!==!1&&r.noPrefetch!==!0&&r.target!=="_blank"&&!ig()}async function T(v=ot()){if(g.value)return;g.value=!0;const S=typeof c.value=="string"?c.value:h.value?ir(c.value):o.resolve(c.value).fullPath,x=h.value?new URL(S,window.location.href).href:S;await Promise.all([v.hooks.callHook("link:prefetch",x).catch(()=>{}),!h.value&&!d.value&&So(c.value,o).catch(()=>{})])}if(E("visibility")){const v=ot();let S,x=null;Ut(()=>{const _=tg();Mo(()=>{S=Fo(()=>{var A;(A=y==null?void 0:y.value)!=null&&A.tagName&&(x=_.observe(y.value,async()=>{x==null||x(),x=null,await T(v)}))})})}),Ii(()=>{S&&No(S),x==null||x(),x=null})}return()=>{var x;if(!h.value&&!d.value&&!t(c.value)){const _={ref:p,to:c.value,activeClass:r.activeClass||n.activeClass,exactActiveClass:r.exactActiveClass||n.exactActiveClass,replace:r.replace,ariaCurrentValue:r.ariaCurrentValue,custom:r.custom};
233return r.custom||(E("interaction")&&(_.onPointerenter=T.bind(null,void 0),_.onFocus=T.bind(null,void 0)),g.value&&(_.class=r.prefetchedClass||n.prefetchedClass),_.rel=r.rel||void 0),me(sr("RouterLink"),_,a.default)}const v=r.target||null,S=Zf(r.noRel?"":r.rel,n.externalRelAttribute,f.value||d.value?"noopener noreferrer":"")||null;return r.custom?a.default?a.default({href:l.value,navigate:u,prefetch:T,get route(){if(!l.value)return;const _=new URL(l.value,window.location.href);return{path:_.pathname,fullPath:_.pathname,get query(){return Bo(_.search)},hash:_.hash,params:{},name:void 0,matched:[],redirectedFrom:void 0,meta:{},href:l.value}},rel:S,target:v,isExternal:h.value||d.value,isActive:!1,isExactActive:!1}):null:me("a",{ref:y,href:l.value||null,rel:S,target:v},(x=a.default)==null?void 0:x.call(a))}}})}const eg=Jf(Vo);function is(n,e){const t=e==="append"?$o:Go;return hs(n)&&!n.startsWith("http")?n:t(n,!0)}function tg(){const n=ot();if(n._observer)return n._observer;let e=null;const t=new Map,s=(r,a)=>(e||(e=new IntersectionObserver(o=>{for(const c of o){const l=t.get(c.target);(c.isIntersecting||c.intersectionRatio>0)&&l&&l()}})),t.set(r,a),e.observe(r),()=>{t.delete(r),e==null||e.unobserve(r),t.size===0&&(e==null||e.disconnect(),e=null)});return n._observer={observe:s}}const sg=/2g/;function ig(){const n=navigator.connection;return!!(n&&(n.saveData||sg.test(n.effectiveType)))}const Dn={__name:"BlockContentLink",props:{value:Object},setup(n){const e=n,t=le(()=>{if(e.value._type==="internalLink")return e.value.page==="homepage"?"/":e.value.slug;if(e.value._type==="externalLink")return e.value.href});return(s,i)=>{const r=eg;return qe(),Ct(r,{to:ue(t),target:n.value._type==="externalLink"?"_blank":""},{default:Ko(()=>[On(s.$slots,"default")]),_:3},8,["to","target"])}}},rg={key:0,class:"block-content"},vg={__name:"BlockContent",props:{blocks:Array},setup(n){const e={styles:{},marks:{externalLink:Dn,internalLink:Dn,highlight:(t,{slots:s})=>{var i;return me("span",{class:"block-highlight"},(i=s.default)==null?void 0:i.call(s))}}};return(t,s)=>n.blocks?(qe(),Rs("div",rg,[Bn(ue(Qf),{value:n.blocks,components:e},null,8,["value"])])):si("",!0)}};typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const Cn=()=>{};function ng(n,e){function t(...s){return new Promise((i,r)=>{Promise.resolve(n(()=>e.apply(this,s),{fn:e,thisArg:this,args:s})).then(i).catch(r)})}return t}function ag(n,e={}){let t,s,i=Cn;const r=c=>{clearTimeout(c),i(),i=Cn};let a;return c=>{const l=rr(n),u=rr(e.maxWait);return t&&r(t),l<=0||u!==void 0&&u<=0?(s&&(r(s),s=null),Promise.resolve(c())):new Promise((h,d)=>{i=e.rejectOnCancel?d:h,a=c,u&&!s&&(s=setTimeout(()=>{t&&r(t),s=null,h(a())},u)),t=setTimeout(()=>{s&&r(s),s=null,h(c())},l)})}}function og(n,e=200,t={}){return ng(ag(e,t),n)}const kn={md:768};function Tg(){const n=Ae(0),e=Ae(0),t=Ae(!1),s=Ae(!1);function i(){n.value=window.innerWidth,e.value=window.innerHeight,s.value=n.value>kn.md,t.value=n.value<kn.md}const r=og(i,300);return Ut(()=>{i(),window.addEventListener("resize",r)}),Ii(()=>{window.removeEventListener("resize",r)}),{width:n,height:e,isMobile:t,isTablet:s}}function Sg(n,e=document){return e.querySelector(n)}function xg(n,e=document){return e.querySelectorAll(n)}const Ag=n=>{if(n._type==="mainVideo"){const[e,t]=n.aspectRatio.split(":").map(Number);return e==t?"square":e>t?"landscape":"portrait"}if(n._type==="mainImage"){const{width:e,height:t}=n.dimensions;return e==t?"square":e>t?"landscape":"portrait"}},Lg=n=>(n==null?void 0:n.type)==="image"&&(n==null?void 0:n.image)||(n==null?void 0:n.type)==="video"&&(n==null?void 0:n.playbackId),lg="$s";function ji(...n){const e=typeof n[n.length-1]=="string"?n.pop():void 0;typeof n[0]!="string"&&n.unshift(e);const[t,s]=n;if(!t||typeof t!="string")throw new TypeError("[nuxt] [useState] key must be a string: "+t);if(s!==void 0&&typeof s!="function")throw new Error("[nuxt] [useState] init must be a function: "+s);const i=lg+t,r=ot(),a=Ho(r.payload.state,i);if(a.value===void 0&&s){const o=s();if(Wo(o))return r.payload.state[i]=o,o;a.value=o}return a}const cg=()=>ji("showPreviewBanner",()=>!1),Ig=()=>ji("isMenuOpen",()=>!1),Rg=()=>ji("isIntroComplete",()=>!1),bg=String.raw||((n,...e)=>{const t=n.length-1;return n.slice(0,t).reduce((s,i,r)=>s+i+e[r],"")+n[t]});
233function _g(){const n=cg(),e=Yo(),t=Ae(!1),s=Ae(null);return{previewMode:t,previewData:s,startPreviewMode:async(a,o)=>{n.value=!0,t.value=!0;const c=e.client.withConfig({useCdn:!1,withCredentials:!0,perspective:"previewDrafts"});try{const l=await c.fetch(a,{slug:o});s.value=l}catch(l){console.log("preview error:",l.message)}},stopPreviewMode:()=>{var a;n.value=!1,(a=fs())==null||a.push({}),t.value=!1,s.value=null,setTimeout(()=>{window.location.reload()},200)}}}export{Eg as _,vg as a,gt as b,Ag as c,xg as d,fg as e,dg as f,bg as g,Lg as h,eg as i,Rg as j,_g as k,Ig as l,mg as m,cg as n,gg as o,Sg as s,Tg as u};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.