@epic-web/workshop-app 6.71.2 → 6.71.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/client/assets/{_exerciseNumber-DOydVFcz.js → _exerciseNumber-C58hYSdV.js} +2 -2
- package/build/client/assets/{_exerciseNumber-DOydVFcz.js.map → _exerciseNumber-C58hYSdV.js.map} +1 -1
- package/build/client/assets/{_exerciseNumber_.finished-OYmKydkm.js → _exerciseNumber_.finished-DVf75w3X.js} +2 -2
- package/build/client/assets/{_exerciseNumber_.finished-OYmKydkm.js.map → _exerciseNumber_.finished-DVf75w3X.js.map} +1 -1
- package/build/client/assets/{_extra-DAAdPX1Q.js → _extra-CmVs6tmo.js} +2 -2
- package/build/client/assets/{_extra-DAAdPX1Q.js.map → _extra-CmVs6tmo.js.map} +1 -1
- package/build/client/assets/{_layout-CeuWC4em.js → _layout-CJyRNKAj.js} +2 -2
- package/build/client/assets/{_layout-CeuWC4em.js.map → _layout-CJyRNKAj.js.map} +1 -1
- package/build/client/assets/{diff-DrdM1MAZ.js → diff-3q6KRqb7.js} +2 -2
- package/build/client/assets/{diff-DrdM1MAZ.js.map → diff-3q6KRqb7.js.map} +1 -1
- package/build/client/assets/{diff-CLewaNfR.js → diff-fa2bITPN.js} +2 -2
- package/build/client/assets/{diff-CLewaNfR.js.map → diff-fa2bITPN.js.map} +1 -1
- package/build/client/assets/{epic-video-Ca_s42j5.js → epic-video-CBv5iEXI.js} +53 -53
- package/build/client/assets/{epic-video-Ca_s42j5.js.map → epic-video-CBv5iEXI.js.map} +1 -1
- package/build/client/assets/{epic-video-BO6oqwle.js → epic-video-DIGPEHcb.js} +2 -2
- package/build/client/assets/{epic-video-BO6oqwle.js.map → epic-video-DIGPEHcb.js.map} +1 -1
- package/build/client/assets/{finished-CqdoWQ9b.js → finished-DGfVVpQU.js} +2 -2
- package/build/client/assets/{finished-CqdoWQ9b.js.map → finished-DGfVVpQU.js.map} +1 -1
- package/build/client/assets/{index-BRVfMMSd.js → index-DMRReIK9.js} +2 -2
- package/build/client/assets/{index-BRVfMMSd.js.map → index-DMRReIK9.js.map} +1 -1
- package/build/client/assets/{index-BHfJ4hna.js → index-wvRiA6Xc.js} +2 -2
- package/build/client/assets/{index-BHfJ4hna.js.map → index-wvRiA6Xc.js.map} +1 -1
- package/build/client/assets/{index-o922xZRF.js → index-zj3sBJAL.js} +2 -2
- package/build/client/assets/{index-o922xZRF.js.map → index-zj3sBJAL.js.map} +1 -1
- package/build/client/assets/{manifest-49708768.js → manifest-aa421597.js} +1 -1
- package/build/client/assets/{mdx-BGwe7vvs.js → mdx-CBZiy4CE.js} +2 -2
- package/build/client/assets/{mdx-BGwe7vvs.js.map → mdx-CBZiy4CE.js.map} +1 -1
- package/build/client/assets/{test-CvHPFyBI.js → test-D2sy_BT2.js} +2 -2
- package/build/client/assets/{test-CvHPFyBI.js.map → test-D2sy_BT2.js.map} +1 -1
- package/build/client/assets/{tests-DlDV-wXQ.js → tests-DAdbACc4.js} +2 -2
- package/build/client/assets/{tests-DlDV-wXQ.js.map → tests-DAdbACc4.js.map} +1 -1
- package/build/server/index.js +20 -12
- package/build/server/index.js.map +1 -1
- package/package.json +3 -3
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{j as N}from"./jsx-runtime-C5WNSv3b.js";import{R as ve,r as Se}from"./index-CqIc3cxq.js";import{g as M_,f as Bv,A as P_,L as Ln}from"./chunk-EPOLDU6W-BCLmut3y.js";import{u as O_}from"./use-event-source-BuD4_2SF.js";import{t as $p}from"./index-DzdDahau.js";import{u as Hv}from"./index-CdzVFL-Z.js";import{r as N_,c as th,I as Jf}from"./misc-W4055b-0.js";import{u as Gv}from"./root-loader-BOzEMapJ.js";import{o as U_,s as $_,n as F_}from"./schemas-Uj5SZtvt.js";import{u as Kv}from"./online-DiNLkgTC.js";import{L as yu}from"./loading-CDNzW5oO.js";import{S as B_}from"./tooltip-Tlsyx2YO.js";import{c as H_}from"./user-BsPobzjB.js";import{u as G_}from"./workshop-config-Zfc8zU0x.js";const K_=new Set(["style","children","ref","key","suppressContentEditableWarning","suppressHydrationWarning","dangerouslySetInnerHTML"]),V_={className:"class",htmlFor:"for"};function W_(i){return i.toLowerCase()}function Fp(i){if(typeof i=="boolean")return i?"":void 0;if(typeof i!="function"&&!(typeof i=="object"&&i!==null))return i}function Le({react:i,tagName:e,elementClass:t,events:s,displayName:r,defaultProps:n,toAttributeName:a=W_,toAttributeValue:o=Fp}){const l=Number.parseInt(i.version)>=19,d=i.forwardRef((u,c)=>{const h=i.useRef(null),f=i.useRef(new Map),m={},p={},g={},v={};for(const[b,E]of Object.entries(u)){if(K_.has(b)){g[b]=E;continue}const T=a(V_[b]??b);if(t.prototype&&b in t.prototype&&!(b in(globalThis.HTMLElement?.prototype??{}))&&!t.observedAttributes?.some(x=>x===T)){v[b]=E;continue}if(b.startsWith("on")){m[b]=E;continue}const A=o(E);if(T&&A!=null&&(p[T]=String(A),l||(g[T]=A)),T&&l){const x=Fp(E);A!==x?g[T]=A:g[T]=E}}if(typeof window<"u"){for(const b in m){const E=m[b],T=b.endsWith("Capture"),A=(s?.[b]??b.slice(2).toLowerCase()).slice(0,T?-7:void 0);i.useLayoutEffect(()=>{const x=h?.current;if(!(!x||typeof E!="function"))return x.addEventListener(A,E,T),()=>{x.removeEventListener(A,E,T)}},[h?.current,E])}i.useLayoutEffect(()=>{if(h.current===null)return;const b=new Map;for(const E in v)Bp(h.current,E,v[E]),f.current.delete(E),b.set(E,v[E]);for(const[E,T]of f.current)Bp(h.current,E,void 0);f.current=b})}if(typeof window>"u"&&t?.getTemplateHTML&&t?.shadowRootOptions){const{mode:b,delegatesFocus:E}=t.shadowRootOptions,T=i.createElement("template",{shadowrootmode:b,shadowrootdelegatesfocus:E,dangerouslySetInnerHTML:{__html:t.getTemplateHTML(p,u)},key:"ce-la-react-ssr-template-shadow-root"});g.children=[T,g.children]}return i.createElement(e,{...n,...g,ref:i.useCallback(b=>{h.current=b,typeof c=="function"?c(b):c!==null&&(c.current=b)},[c])},g.children)});return d.displayName=r??t.name,d}function Bp(i,e,t){i[e]=t,t==null&&e in(globalThis.HTMLElement?.prototype??{})&&i.removeAttribute(e)}const z={MEDIA_PLAY_REQUEST:"mediaplayrequest",MEDIA_PAUSE_REQUEST:"mediapauserequest",MEDIA_MUTE_REQUEST:"mediamuterequest",MEDIA_UNMUTE_REQUEST:"mediaunmuterequest",MEDIA_LOOP_REQUEST:"medialooprequest",MEDIA_VOLUME_REQUEST:"mediavolumerequest",MEDIA_SEEK_REQUEST:"mediaseekrequest",MEDIA_AIRPLAY_REQUEST:"mediaairplayrequest",MEDIA_ENTER_FULLSCREEN_REQUEST:"mediaenterfullscreenrequest",MEDIA_EXIT_FULLSCREEN_REQUEST:"mediaexitfullscreenrequest",MEDIA_PREVIEW_REQUEST:"mediapreviewrequest",MEDIA_ENTER_PIP_REQUEST:"mediaenterpiprequest",MEDIA_EXIT_PIP_REQUEST:"mediaexitpiprequest",MEDIA_ENTER_CAST_REQUEST:"mediaentercastrequest",MEDIA_EXIT_CAST_REQUEST:"mediaexitcastrequest",MEDIA_SHOW_TEXT_TRACKS_REQUEST:"mediashowtexttracksrequest",MEDIA_HIDE_TEXT_TRACKS_REQUEST:"mediahidetexttracksrequest",MEDIA_SHOW_SUBTITLES_REQUEST:"mediashowsubtitlesrequest",MEDIA_DISABLE_SUBTITLES_REQUEST:"mediadisablesubtitlesrequest",MEDIA_TOGGLE_SUBTITLES_REQUEST:"mediatogglesubtitlesrequest",MEDIA_PLAYBACK_RATE_REQUEST:"mediaplaybackraterequest",MEDIA_RENDITION_REQUEST:"mediarenditionrequest",MEDIA_AUDIO_TRACK_REQUEST:"mediaaudiotrackrequest",MEDIA_SEEK_TO_LIVE_REQUEST:"mediaseektoliverequest",REGISTER_MEDIA_STATE_RECEIVER:"registermediastatereceiver",UNREGISTER_MEDIA_STATE_RECEIVER:"unregistermediastatereceiver"},xe={MEDIA_CHROME_ATTRIBUTES:"mediachromeattributes",MEDIA_CONTROLLER:"mediacontroller"},Vv={MEDIA_AIRPLAY_UNAVAILABLE:"mediaAirplayUnavailable",MEDIA_AUDIO_TRACK_ENABLED:"mediaAudioTrackEnabled",MEDIA_AUDIO_TRACK_LIST:"mediaAudioTrackList",MEDIA_AUDIO_TRACK_UNAVAILABLE:"mediaAudioTrackUnavailable",MEDIA_BUFFERED:"mediaBuffered",MEDIA_CAST_UNAVAILABLE:"mediaCastUnavailable",MEDIA_CHAPTERS_CUES:"mediaChaptersCues",MEDIA_CURRENT_TIME:"mediaCurrentTime",MEDIA_DURATION:"mediaDuration",MEDIA_ENDED:"mediaEnded",MEDIA_ERROR:"mediaError",MEDIA_ERROR_CODE:"mediaErrorCode",MEDIA_ERROR_MESSAGE:"mediaErrorMessage",MEDIA_FULLSCREEN_UNAVAILABLE:"mediaFullscreenUnavailable",MEDIA_HAS_PLAYED:"mediaHasPlayed",MEDIA_HEIGHT:"mediaHeight",MEDIA_IS_AIRPLAYING:"mediaIsAirplaying",MEDIA_IS_CASTING:"mediaIsCasting",MEDIA_IS_FULLSCREEN:"mediaIsFullscreen",MEDIA_IS_PIP:"mediaIsPip",MEDIA_LOADING:"mediaLoading",MEDIA_MUTED:"mediaMuted",MEDIA_LOOP:"mediaLoop",MEDIA_PAUSED:"mediaPaused",MEDIA_PIP_UNAVAILABLE:"mediaPipUnavailable",MEDIA_PLAYBACK_RATE:"mediaPlaybackRate",MEDIA_PREVIEW_CHAPTER:"mediaPreviewChapter",MEDIA_PREVIEW_COORDS:"mediaPreviewCoords",MEDIA_PREVIEW_IMAGE:"mediaPreviewImage",MEDIA_PREVIEW_TIME:"mediaPreviewTime",MEDIA_RENDITION_LIST:"mediaRenditionList",MEDIA_RENDITION_SELECTED:"mediaRenditionSelected",MEDIA_RENDITION_UNAVAILABLE:"mediaRenditionUnavailable",MEDIA_SEEKABLE:"mediaSeekable",MEDIA_STREAM_TYPE:"mediaStreamType",MEDIA_SUBTITLES_LIST:"mediaSubtitlesList",MEDIA_SUBTITLES_SHOWING:"mediaSubtitlesShowing",MEDIA_TARGET_LIVE_WINDOW:"mediaTargetLiveWindow",MEDIA_TIME_IS_LIVE:"mediaTimeIsLive",MEDIA_VOLUME:"mediaVolume",MEDIA_VOLUME_LEVEL:"mediaVolumeLevel",MEDIA_VOLUME_UNAVAILABLE:"mediaVolumeUnavailable",MEDIA_LANG:"mediaLang",MEDIA_WIDTH:"mediaWidth"},Wv=Object.entries(Vv),_=Wv.reduce((i,[e,t])=>(i[e]=t.toLowerCase(),i),{}),q_={USER_INACTIVE_CHANGE:"userinactivechange",BREAKPOINTS_CHANGE:"breakpointchange",BREAKPOINTS_COMPUTED:"breakpointscomputed"},ys=Wv.reduce((i,[e,t])=>(i[e]=t.toLowerCase(),i),{...q_});Object.entries(ys).reduce((i,[e,t])=>{const s=_[e];return s&&(i[t]=s),i},{userinactivechange:"userinactive"});const Y_=Object.entries(_).reduce((i,[e,t])=>{const s=ys[e];return s&&(i[t]=s),i},{userinactive:"userinactivechange"}),ts={SUBTITLES:"subtitles",CAPTIONS:"captions",CHAPTERS:"chapters",METADATA:"metadata"},Pn={DISABLED:"disabled",SHOWING:"showing"},oc={MOUSE:"mouse",PEN:"pen",TOUCH:"touch"},Ht={UNAVAILABLE:"unavailable",UNSUPPORTED:"unsupported"},hs={LIVE:"live",ON_DEMAND:"on-demand",UNKNOWN:"unknown"},j_={FULLSCREEN:"fullscreen"};function z_(i){return i?.map(X_).join(" ")}function Q_(i){return i?.split(/\s+/).map(Z_)}function X_(i){if(i){const{id:e,width:t,height:s}=i;return[e,t,s].filter(r=>r!=null).join(":")}}function Z_(i){if(i){const[e,t,s]=i.split(":");return{id:e,width:+t,height:+s}}}function J_(i){return i?.map(tA).join(" ")}function eA(i){return i?.split(/\s+/).map(iA)}function tA(i){if(i){const{id:e,kind:t,language:s,label:r}=i;return[e,t,s,r].filter(n=>n!=null).join(":")}}function iA(i){if(i){const[e,t,s,r]=i.split(":");return{id:e,kind:t,language:s,label:r}}}function sA(i){return i.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase())}function em(i){return typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i)}function qv(i){return typeof i!="string"?!1:!isNaN(i)&&!isNaN(parseFloat(i))}const Yv=i=>new Promise(e=>setTimeout(e,i)),Hp=[{singular:"hour",plural:"hours"},{singular:"minute",plural:"minutes"},{singular:"second",plural:"seconds"}],rA=(i,e)=>{const t=i===1?Hp[e].singular:Hp[e].plural;return`${i} ${t}`},Ka=i=>{if(!em(i))return"";const e=Math.abs(i),t=e!==i,s=new Date(0,0,0,0,0,e,0);return`${[s.getHours(),s.getMinutes(),s.getSeconds()].map((o,l)=>o&&rA(o,l)).filter(o=>o).join(", ")}${t?" remaining":""}`};function qs(i,e){let t=!1;i<0&&(t=!0,i=0-i),i=i<0?0:i;let s=Math.floor(i%60),r=Math.floor(i/60%60),n=Math.floor(i/3600);const a=Math.floor(e/60%60),o=Math.floor(e/3600);return(isNaN(i)||i===1/0)&&(n=r=s="0"),n=n>0||o>0?n+":":"",r=((n||a>=10)&&r<10?"0"+r:r)+":",s=s<10?"0"+s:s,(t?"-":"")+n+r+s}const nA={"Start airplay":"Start airplay","Stop airplay":"Stop airplay",Audio:"Audio",Captions:"Captions","Enable captions":"Enable captions","Disable captions":"Disable captions","Start casting":"Start casting","Stop casting":"Stop casting","Enter fullscreen mode":"Enter fullscreen mode","Exit fullscreen mode":"Exit fullscreen mode",Mute:"Mute",Unmute:"Unmute",Loop:"Loop","Enter picture in picture mode":"Enter picture in picture mode","Exit picture in picture mode":"Exit picture in picture mode",Play:"Play",Pause:"Pause","Playback rate":"Playback rate","Playback rate {playbackRate}":"Playback rate {playbackRate}",Quality:"Quality","Seek backward":"Seek backward","Seek forward":"Seek forward",Settings:"Settings",Auto:"Auto","audio player":"audio player","video player":"video player",volume:"volume",seek:"seek","closed captions":"closed captions","current playback rate":"current playback rate","playback time":"playback time","media loading":"media loading",settings:"settings","audio tracks":"audio tracks",quality:"quality",play:"play",pause:"pause",mute:"mute",unmute:"unmute","chapter: {chapterName}":"chapter: {chapterName}",live:"live",Off:"Off","start airplay":"start airplay","stop airplay":"stop airplay","start casting":"start casting","stop casting":"stop casting","enter fullscreen mode":"enter fullscreen mode","exit fullscreen mode":"exit fullscreen mode","enter picture in picture mode":"enter picture in picture mode","exit picture in picture mode":"exit picture in picture mode","seek to live":"seek to live","playing live":"playing live","seek back {seekOffset} seconds":"seek back {seekOffset} seconds","seek forward {seekOffset} seconds":"seek forward {seekOffset} seconds","Network Error":"Network Error","Decode Error":"Decode Error","Source Not Supported":"Source Not Supported","Encryption Error":"Encryption Error","A network error caused the media download to fail.":"A network error caused the media download to fail.","A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.":"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.","An unsupported error occurred. The server or network failed, or your browser does not support this format.":"An unsupported error occurred. The server or network failed, or your browser does not support this format.","The media is encrypted and there are no keys to decrypt it.":"The media is encrypted and there are no keys to decrypt it."};var Gp;const lc={en:nA};let ih=((Gp=globalThis.navigator)==null?void 0:Gp.language)||"en";const aA=i=>{ih=i},oA=i=>{var e,t,s;const[r]=ih.split("-");return((e=lc[ih])==null?void 0:e[i])||((t=lc[r])==null?void 0:t[i])||((s=lc.en)==null?void 0:s[i])||i},te=(i,e={})=>oA(i).replace(/\{(\w+)\}/g,(t,s)=>s in e?String(e[s]):`{${s}}`);let jv=class{addEventListener(){}removeEventListener(){}dispatchEvent(){return!0}};class zv extends jv{}let Kp=class extends zv{constructor(){super(...arguments),this.role=null}};class lA{observe(){}unobserve(){}disconnect(){}}const Qv={createElement:function(){return new io.HTMLElement},createElementNS:function(){return new io.HTMLElement},addEventListener(){},removeEventListener(){},dispatchEvent(i){return!1}},io={ResizeObserver:lA,document:Qv,Node:zv,Element:Kp,HTMLElement:class extends Kp{constructor(){super(...arguments),this.innerHTML=""}get content(){return new io.DocumentFragment}},DocumentFragment:class extends jv{},customElements:{get:function(){},define:function(){},whenDefined:function(){}},localStorage:{getItem(i){return null},setItem(i,e){},removeItem(i){}},CustomEvent:function(){},getComputedStyle:function(){},navigator:{languages:[],get userAgent(){return""}},matchMedia(i){return{matches:!1,media:i}},DOMParser:class{parseFromString(e,t){return{body:{textContent:e}}}}},Xv="global"in globalThis&&globalThis?.global===globalThis||typeof window>"u"||typeof window.customElements>"u",Zv=Object.keys(io).every(i=>i in globalThis),k=Xv&&!Zv?io:globalThis,lt=Xv&&!Zv?Qv:globalThis.document,Vp=new WeakMap,tm=i=>{let e=Vp.get(i);return e||Vp.set(i,e=new Set),e},Jv=new k.ResizeObserver(i=>{for(const e of i)for(const t of tm(e.target))t(e)});function Yn(i,e){tm(i).add(e),Jv.observe(i)}function jn(i,e){const t=tm(i);t.delete(e),t.size||Jv.unobserve(i)}function Zt(i){const e={};for(const t of i)e[t.name]=t.value;return e}function Ut(i){var e;return(e=sh(i))!=null?e:ia(i,"media-controller")}function sh(i){var e;const{MEDIA_CONTROLLER:t}=xe,s=i.getAttribute(t);if(s)return(e=bu(i))==null?void 0:e.getElementById(s)}const eE=(i,e,t=".value")=>{const s=i.querySelector(t);s&&(s.textContent=e)},dA=(i,e)=>{const t=`slot[name="${e}"]`,s=i.shadowRoot.querySelector(t);return s?s.children:[]},tE=(i,e)=>dA(i,e)[0],Ts=(i,e)=>!i||!e?!1:i?.contains(e)?!0:Ts(i,e.getRootNode().host),ia=(i,e)=>{if(!i)return null;const t=i.closest(e);return t||ia(i.getRootNode().host,e)};function im(i=document){var e;const t=i?.activeElement;return t?(e=im(t.shadowRoot))!=null?e:t:null}function bu(i){var e;const t=(e=i?.getRootNode)==null?void 0:e.call(i);return t instanceof ShadowRoot||t instanceof Document?t:null}function iE(i,{depth:e=3,checkOpacity:t=!0,checkVisibilityCSS:s=!0}={}){if(i.checkVisibility)return i.checkVisibility({checkOpacity:t,checkVisibilityCSS:s});let r=i;for(;r&&e>0;){const n=getComputedStyle(r);if(t&&n.opacity==="0"||s&&n.visibility==="hidden"||n.display==="none")return!1;r=r.parentElement,e--}return!0}function uA(i,e,t,s){const r=s.x-t.x,n=s.y-t.y,a=r*r+n*n;if(a===0)return 0;const o=((i-t.x)*r+(e-t.y)*n)/a;return Math.max(0,Math.min(1,o))}function pt(i,e){const t=cA(i,s=>s===e);return t||sm(i,e)}function cA(i,e){var t,s;let r;for(r of(t=i.querySelectorAll("style:not([media])"))!=null?t:[]){let n;try{n=(s=r.sheet)==null?void 0:s.cssRules}catch{continue}for(const a of n??[])if(e(a.selectorText))return a}}function sm(i,e){var t,s;const r=(t=i.querySelectorAll("style:not([media])"))!=null?t:[],n=r?.[r.length-1];return n?.sheet?(n?.sheet.insertRule(`${e}{}`,n.sheet.cssRules.length),(s=n.sheet.cssRules)==null?void 0:s[n.sheet.cssRules.length-1]):(console.warn("Media Chrome: No style sheet found on style tag of",i),{style:{setProperty:()=>{},removeProperty:()=>"",getPropertyValue:()=>""}})}function Be(i,e,t=Number.NaN){const s=i.getAttribute(e);return s!=null?+s:t}function Xe(i,e,t){const s=+t;if(t==null||Number.isNaN(s)){i.hasAttribute(e)&&i.removeAttribute(e);return}Be(i,e,void 0)!==s&&i.setAttribute(e,`${s}`)}function ye(i,e){return i.hasAttribute(e)}function be(i,e,t){if(t==null){i.hasAttribute(e)&&i.removeAttribute(e);return}ye(i,e)!=t&&i.toggleAttribute(e,t)}function He(i,e,t=null){var s;return(s=i.getAttribute(e))!=null?s:t}function Ge(i,e,t){if(t==null){i.hasAttribute(e)&&i.removeAttribute(e);return}const s=`${t}`;He(i,e,void 0)!==s&&i.setAttribute(e,s)}var sE=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Is=(i,e,t)=>(sE(i,e,"read from private field"),t?t.call(i):e.get(i)),hA=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Mo=(i,e,t,s)=>(sE(i,e,"write to private field"),e.set(i,t),t),Pt;function fA(i){return`
|
|
1
|
+
import{j as O}from"./jsx-runtime-C5WNSv3b.js";import{R as ve,r as Se}from"./index-CqIc3cxq.js";import{g as M_,f as Bv,A as P_,L as Ln}from"./chunk-EPOLDU6W-BCLmut3y.js";import{u as O_}from"./use-event-source-BuD4_2SF.js";import{t as $p}from"./index-DzdDahau.js";import{u as Hv}from"./index-CdzVFL-Z.js";import{r as N_,c as th,I as Jf}from"./misc-W4055b-0.js";import{u as Gv}from"./root-loader-BOzEMapJ.js";import{o as U_,s as $_,n as F_}from"./schemas-Uj5SZtvt.js";import{u as Kv}from"./online-DiNLkgTC.js";import{L as yu}from"./loading-CDNzW5oO.js";import{S as B_}from"./tooltip-Tlsyx2YO.js";import{c as H_}from"./user-BsPobzjB.js";import{u as G_}from"./workshop-config-Zfc8zU0x.js";const K_=new Set(["style","children","ref","key","suppressContentEditableWarning","suppressHydrationWarning","dangerouslySetInnerHTML"]),V_={className:"class",htmlFor:"for"};function W_(i){return i.toLowerCase()}function Fp(i){if(typeof i=="boolean")return i?"":void 0;if(typeof i!="function"&&!(typeof i=="object"&&i!==null))return i}function Le({react:i,tagName:e,elementClass:t,events:s,displayName:r,defaultProps:n,toAttributeName:a=W_,toAttributeValue:o=Fp}){const l=Number.parseInt(i.version)>=19,d=i.forwardRef((u,c)=>{const h=i.useRef(null),f=i.useRef(new Map),m={},p={},g={},v={};for(const[b,E]of Object.entries(u)){if(K_.has(b)){g[b]=E;continue}const T=a(V_[b]??b);if(t.prototype&&b in t.prototype&&!(b in(globalThis.HTMLElement?.prototype??{}))&&!t.observedAttributes?.some(x=>x===T)){v[b]=E;continue}if(b.startsWith("on")){m[b]=E;continue}const A=o(E);if(T&&A!=null&&(p[T]=String(A),l||(g[T]=A)),T&&l){const x=Fp(E);A!==x?g[T]=A:g[T]=E}}if(typeof window<"u"){for(const b in m){const E=m[b],T=b.endsWith("Capture"),A=(s?.[b]??b.slice(2).toLowerCase()).slice(0,T?-7:void 0);i.useLayoutEffect(()=>{const x=h?.current;if(!(!x||typeof E!="function"))return x.addEventListener(A,E,T),()=>{x.removeEventListener(A,E,T)}},[h?.current,E])}i.useLayoutEffect(()=>{if(h.current===null)return;const b=new Map;for(const E in v)Bp(h.current,E,v[E]),f.current.delete(E),b.set(E,v[E]);for(const[E,T]of f.current)Bp(h.current,E,void 0);f.current=b})}if(typeof window>"u"&&t?.getTemplateHTML&&t?.shadowRootOptions){const{mode:b,delegatesFocus:E}=t.shadowRootOptions,T=i.createElement("template",{shadowrootmode:b,shadowrootdelegatesfocus:E,dangerouslySetInnerHTML:{__html:t.getTemplateHTML(p,u)},key:"ce-la-react-ssr-template-shadow-root"});g.children=[T,g.children]}return i.createElement(e,{...n,...g,ref:i.useCallback(b=>{h.current=b,typeof c=="function"?c(b):c!==null&&(c.current=b)},[c])},g.children)});return d.displayName=r??t.name,d}function Bp(i,e,t){i[e]=t,t==null&&e in(globalThis.HTMLElement?.prototype??{})&&i.removeAttribute(e)}const Q={MEDIA_PLAY_REQUEST:"mediaplayrequest",MEDIA_PAUSE_REQUEST:"mediapauserequest",MEDIA_MUTE_REQUEST:"mediamuterequest",MEDIA_UNMUTE_REQUEST:"mediaunmuterequest",MEDIA_LOOP_REQUEST:"medialooprequest",MEDIA_VOLUME_REQUEST:"mediavolumerequest",MEDIA_SEEK_REQUEST:"mediaseekrequest",MEDIA_AIRPLAY_REQUEST:"mediaairplayrequest",MEDIA_ENTER_FULLSCREEN_REQUEST:"mediaenterfullscreenrequest",MEDIA_EXIT_FULLSCREEN_REQUEST:"mediaexitfullscreenrequest",MEDIA_PREVIEW_REQUEST:"mediapreviewrequest",MEDIA_ENTER_PIP_REQUEST:"mediaenterpiprequest",MEDIA_EXIT_PIP_REQUEST:"mediaexitpiprequest",MEDIA_ENTER_CAST_REQUEST:"mediaentercastrequest",MEDIA_EXIT_CAST_REQUEST:"mediaexitcastrequest",MEDIA_SHOW_TEXT_TRACKS_REQUEST:"mediashowtexttracksrequest",MEDIA_HIDE_TEXT_TRACKS_REQUEST:"mediahidetexttracksrequest",MEDIA_SHOW_SUBTITLES_REQUEST:"mediashowsubtitlesrequest",MEDIA_DISABLE_SUBTITLES_REQUEST:"mediadisablesubtitlesrequest",MEDIA_TOGGLE_SUBTITLES_REQUEST:"mediatogglesubtitlesrequest",MEDIA_PLAYBACK_RATE_REQUEST:"mediaplaybackraterequest",MEDIA_RENDITION_REQUEST:"mediarenditionrequest",MEDIA_AUDIO_TRACK_REQUEST:"mediaaudiotrackrequest",MEDIA_SEEK_TO_LIVE_REQUEST:"mediaseektoliverequest",REGISTER_MEDIA_STATE_RECEIVER:"registermediastatereceiver",UNREGISTER_MEDIA_STATE_RECEIVER:"unregistermediastatereceiver"},xe={MEDIA_CHROME_ATTRIBUTES:"mediachromeattributes",MEDIA_CONTROLLER:"mediacontroller"},Vv={MEDIA_AIRPLAY_UNAVAILABLE:"mediaAirplayUnavailable",MEDIA_AUDIO_TRACK_ENABLED:"mediaAudioTrackEnabled",MEDIA_AUDIO_TRACK_LIST:"mediaAudioTrackList",MEDIA_AUDIO_TRACK_UNAVAILABLE:"mediaAudioTrackUnavailable",MEDIA_BUFFERED:"mediaBuffered",MEDIA_CAST_UNAVAILABLE:"mediaCastUnavailable",MEDIA_CHAPTERS_CUES:"mediaChaptersCues",MEDIA_CURRENT_TIME:"mediaCurrentTime",MEDIA_DURATION:"mediaDuration",MEDIA_ENDED:"mediaEnded",MEDIA_ERROR:"mediaError",MEDIA_ERROR_CODE:"mediaErrorCode",MEDIA_ERROR_MESSAGE:"mediaErrorMessage",MEDIA_FULLSCREEN_UNAVAILABLE:"mediaFullscreenUnavailable",MEDIA_HAS_PLAYED:"mediaHasPlayed",MEDIA_HEIGHT:"mediaHeight",MEDIA_IS_AIRPLAYING:"mediaIsAirplaying",MEDIA_IS_CASTING:"mediaIsCasting",MEDIA_IS_FULLSCREEN:"mediaIsFullscreen",MEDIA_IS_PIP:"mediaIsPip",MEDIA_LOADING:"mediaLoading",MEDIA_MUTED:"mediaMuted",MEDIA_LOOP:"mediaLoop",MEDIA_PAUSED:"mediaPaused",MEDIA_PIP_UNAVAILABLE:"mediaPipUnavailable",MEDIA_PLAYBACK_RATE:"mediaPlaybackRate",MEDIA_PREVIEW_CHAPTER:"mediaPreviewChapter",MEDIA_PREVIEW_COORDS:"mediaPreviewCoords",MEDIA_PREVIEW_IMAGE:"mediaPreviewImage",MEDIA_PREVIEW_TIME:"mediaPreviewTime",MEDIA_RENDITION_LIST:"mediaRenditionList",MEDIA_RENDITION_SELECTED:"mediaRenditionSelected",MEDIA_RENDITION_UNAVAILABLE:"mediaRenditionUnavailable",MEDIA_SEEKABLE:"mediaSeekable",MEDIA_STREAM_TYPE:"mediaStreamType",MEDIA_SUBTITLES_LIST:"mediaSubtitlesList",MEDIA_SUBTITLES_SHOWING:"mediaSubtitlesShowing",MEDIA_TARGET_LIVE_WINDOW:"mediaTargetLiveWindow",MEDIA_TIME_IS_LIVE:"mediaTimeIsLive",MEDIA_VOLUME:"mediaVolume",MEDIA_VOLUME_LEVEL:"mediaVolumeLevel",MEDIA_VOLUME_UNAVAILABLE:"mediaVolumeUnavailable",MEDIA_LANG:"mediaLang",MEDIA_WIDTH:"mediaWidth"},Wv=Object.entries(Vv),_=Wv.reduce((i,[e,t])=>(i[e]=t.toLowerCase(),i),{}),q_={USER_INACTIVE_CHANGE:"userinactivechange",BREAKPOINTS_CHANGE:"breakpointchange",BREAKPOINTS_COMPUTED:"breakpointscomputed"},ys=Wv.reduce((i,[e,t])=>(i[e]=t.toLowerCase(),i),{...q_});Object.entries(ys).reduce((i,[e,t])=>{const s=_[e];return s&&(i[t]=s),i},{userinactivechange:"userinactive"});const Y_=Object.entries(_).reduce((i,[e,t])=>{const s=ys[e];return s&&(i[t]=s),i},{userinactive:"userinactivechange"}),ts={SUBTITLES:"subtitles",CAPTIONS:"captions",CHAPTERS:"chapters",METADATA:"metadata"},Pn={DISABLED:"disabled",SHOWING:"showing"},oc={MOUSE:"mouse",PEN:"pen",TOUCH:"touch"},Ht={UNAVAILABLE:"unavailable",UNSUPPORTED:"unsupported"},hs={LIVE:"live",ON_DEMAND:"on-demand",UNKNOWN:"unknown"},j_={FULLSCREEN:"fullscreen"};function z_(i){return i?.map(X_).join(" ")}function Q_(i){return i?.split(/\s+/).map(Z_)}function X_(i){if(i){const{id:e,width:t,height:s}=i;return[e,t,s].filter(r=>r!=null).join(":")}}function Z_(i){if(i){const[e,t,s]=i.split(":");return{id:e,width:+t,height:+s}}}function J_(i){return i?.map(tA).join(" ")}function eA(i){return i?.split(/\s+/).map(iA)}function tA(i){if(i){const{id:e,kind:t,language:s,label:r}=i;return[e,t,s,r].filter(n=>n!=null).join(":")}}function iA(i){if(i){const[e,t,s,r]=i.split(":");return{id:e,kind:t,language:s,label:r}}}function sA(i){return i.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase())}function em(i){return typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i)}function qv(i){return typeof i!="string"?!1:!isNaN(i)&&!isNaN(parseFloat(i))}const Yv=i=>new Promise(e=>setTimeout(e,i)),Hp=[{singular:"hour",plural:"hours"},{singular:"minute",plural:"minutes"},{singular:"second",plural:"seconds"}],rA=(i,e)=>{const t=i===1?Hp[e].singular:Hp[e].plural;return`${i} ${t}`},Ka=i=>{if(!em(i))return"";const e=Math.abs(i),t=e!==i,s=new Date(0,0,0,0,0,e,0);return`${[s.getHours(),s.getMinutes(),s.getSeconds()].map((o,l)=>o&&rA(o,l)).filter(o=>o).join(", ")}${t?" remaining":""}`};function qs(i,e){let t=!1;i<0&&(t=!0,i=0-i),i=i<0?0:i;let s=Math.floor(i%60),r=Math.floor(i/60%60),n=Math.floor(i/3600);const a=Math.floor(e/60%60),o=Math.floor(e/3600);return(isNaN(i)||i===1/0)&&(n=r=s="0"),n=n>0||o>0?n+":":"",r=((n||a>=10)&&r<10?"0"+r:r)+":",s=s<10?"0"+s:s,(t?"-":"")+n+r+s}const nA={"Start airplay":"Start airplay","Stop airplay":"Stop airplay",Audio:"Audio",Captions:"Captions","Enable captions":"Enable captions","Disable captions":"Disable captions","Start casting":"Start casting","Stop casting":"Stop casting","Enter fullscreen mode":"Enter fullscreen mode","Exit fullscreen mode":"Exit fullscreen mode",Mute:"Mute",Unmute:"Unmute",Loop:"Loop","Enter picture in picture mode":"Enter picture in picture mode","Exit picture in picture mode":"Exit picture in picture mode",Play:"Play",Pause:"Pause","Playback rate":"Playback rate","Playback rate {playbackRate}":"Playback rate {playbackRate}",Quality:"Quality","Seek backward":"Seek backward","Seek forward":"Seek forward",Settings:"Settings",Auto:"Auto","audio player":"audio player","video player":"video player",volume:"volume",seek:"seek","closed captions":"closed captions","current playback rate":"current playback rate","playback time":"playback time","media loading":"media loading",settings:"settings","audio tracks":"audio tracks",quality:"quality",play:"play",pause:"pause",mute:"mute",unmute:"unmute","chapter: {chapterName}":"chapter: {chapterName}",live:"live",Off:"Off","start airplay":"start airplay","stop airplay":"stop airplay","start casting":"start casting","stop casting":"stop casting","enter fullscreen mode":"enter fullscreen mode","exit fullscreen mode":"exit fullscreen mode","enter picture in picture mode":"enter picture in picture mode","exit picture in picture mode":"exit picture in picture mode","seek to live":"seek to live","playing live":"playing live","seek back {seekOffset} seconds":"seek back {seekOffset} seconds","seek forward {seekOffset} seconds":"seek forward {seekOffset} seconds","Network Error":"Network Error","Decode Error":"Decode Error","Source Not Supported":"Source Not Supported","Encryption Error":"Encryption Error","A network error caused the media download to fail.":"A network error caused the media download to fail.","A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.":"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.","An unsupported error occurred. The server or network failed, or your browser does not support this format.":"An unsupported error occurred. The server or network failed, or your browser does not support this format.","The media is encrypted and there are no keys to decrypt it.":"The media is encrypted and there are no keys to decrypt it."};var Gp;const lc={en:nA};let ih=((Gp=globalThis.navigator)==null?void 0:Gp.language)||"en";const aA=i=>{ih=i},oA=i=>{var e,t,s;const[r]=ih.split("-");return((e=lc[ih])==null?void 0:e[i])||((t=lc[r])==null?void 0:t[i])||((s=lc.en)==null?void 0:s[i])||i},te=(i,e={})=>oA(i).replace(/\{(\w+)\}/g,(t,s)=>s in e?String(e[s]):`{${s}}`);let jv=class{addEventListener(){}removeEventListener(){}dispatchEvent(){return!0}};class zv extends jv{}let Kp=class extends zv{constructor(){super(...arguments),this.role=null}};class lA{observe(){}unobserve(){}disconnect(){}}const Qv={createElement:function(){return new io.HTMLElement},createElementNS:function(){return new io.HTMLElement},addEventListener(){},removeEventListener(){},dispatchEvent(i){return!1}},io={ResizeObserver:lA,document:Qv,Node:zv,Element:Kp,HTMLElement:class extends Kp{constructor(){super(...arguments),this.innerHTML=""}get content(){return new io.DocumentFragment}},DocumentFragment:class extends jv{},customElements:{get:function(){},define:function(){},whenDefined:function(){}},localStorage:{getItem(i){return null},setItem(i,e){},removeItem(i){}},CustomEvent:function(){},getComputedStyle:function(){},navigator:{languages:[],get userAgent(){return""}},matchMedia(i){return{matches:!1,media:i}},DOMParser:class{parseFromString(e,t){return{body:{textContent:e}}}}},Xv="global"in globalThis&&globalThis?.global===globalThis||typeof window>"u"||typeof window.customElements>"u",Zv=Object.keys(io).every(i=>i in globalThis),k=Xv&&!Zv?io:globalThis,lt=Xv&&!Zv?Qv:globalThis.document,Vp=new WeakMap,tm=i=>{let e=Vp.get(i);return e||Vp.set(i,e=new Set),e},Jv=new k.ResizeObserver(i=>{for(const e of i)for(const t of tm(e.target))t(e)});function Yn(i,e){tm(i).add(e),Jv.observe(i)}function jn(i,e){const t=tm(i);t.delete(e),t.size||Jv.unobserve(i)}function Zt(i){const e={};for(const t of i)e[t.name]=t.value;return e}function Ut(i){var e;return(e=sh(i))!=null?e:ia(i,"media-controller")}function sh(i){var e;const{MEDIA_CONTROLLER:t}=xe,s=i.getAttribute(t);if(s)return(e=bu(i))==null?void 0:e.getElementById(s)}const eE=(i,e,t=".value")=>{const s=i.querySelector(t);s&&(s.textContent=e)},dA=(i,e)=>{const t=`slot[name="${e}"]`,s=i.shadowRoot.querySelector(t);return s?s.children:[]},tE=(i,e)=>dA(i,e)[0],Ts=(i,e)=>!i||!e?!1:i?.contains(e)?!0:Ts(i,e.getRootNode().host),ia=(i,e)=>{if(!i)return null;const t=i.closest(e);return t||ia(i.getRootNode().host,e)};function im(i=document){var e;const t=i?.activeElement;return t?(e=im(t.shadowRoot))!=null?e:t:null}function bu(i){var e;const t=(e=i?.getRootNode)==null?void 0:e.call(i);return t instanceof ShadowRoot||t instanceof Document?t:null}function iE(i,{depth:e=3,checkOpacity:t=!0,checkVisibilityCSS:s=!0}={}){if(i.checkVisibility)return i.checkVisibility({checkOpacity:t,checkVisibilityCSS:s});let r=i;for(;r&&e>0;){const n=getComputedStyle(r);if(t&&n.opacity==="0"||s&&n.visibility==="hidden"||n.display==="none")return!1;r=r.parentElement,e--}return!0}function uA(i,e,t,s){const r=s.x-t.x,n=s.y-t.y,a=r*r+n*n;if(a===0)return 0;const o=((i-t.x)*r+(e-t.y)*n)/a;return Math.max(0,Math.min(1,o))}function pt(i,e){const t=cA(i,s=>s===e);return t||sm(i,e)}function cA(i,e){var t,s;let r;for(r of(t=i.querySelectorAll("style:not([media])"))!=null?t:[]){let n;try{n=(s=r.sheet)==null?void 0:s.cssRules}catch{continue}for(const a of n??[])if(e(a.selectorText))return a}}function sm(i,e){var t,s;const r=(t=i.querySelectorAll("style:not([media])"))!=null?t:[],n=r?.[r.length-1];return n?.sheet?(n?.sheet.insertRule(`${e}{}`,n.sheet.cssRules.length),(s=n.sheet.cssRules)==null?void 0:s[n.sheet.cssRules.length-1]):(console.warn("Media Chrome: No style sheet found on style tag of",i),{style:{setProperty:()=>{},removeProperty:()=>"",getPropertyValue:()=>""}})}function Be(i,e,t=Number.NaN){const s=i.getAttribute(e);return s!=null?+s:t}function Xe(i,e,t){const s=+t;if(t==null||Number.isNaN(s)){i.hasAttribute(e)&&i.removeAttribute(e);return}Be(i,e,void 0)!==s&&i.setAttribute(e,`${s}`)}function ye(i,e){return i.hasAttribute(e)}function be(i,e,t){if(t==null){i.hasAttribute(e)&&i.removeAttribute(e);return}ye(i,e)!=t&&i.toggleAttribute(e,t)}function He(i,e,t=null){var s;return(s=i.getAttribute(e))!=null?s:t}function Ge(i,e,t){if(t==null){i.hasAttribute(e)&&i.removeAttribute(e);return}const s=`${t}`;He(i,e,void 0)!==s&&i.setAttribute(e,s)}var sE=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Is=(i,e,t)=>(sE(i,e,"read from private field"),t?t.call(i):e.get(i)),hA=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Mo=(i,e,t,s)=>(sE(i,e,"write to private field"),e.set(i,t),t),Pt;function fA(i){return`
|
|
2
2
|
<style>
|
|
3
3
|
:host {
|
|
4
4
|
display: var(--media-control-display, var(--media-gesture-receiver-display, inline-block));
|
|
5
5
|
box-sizing: border-box;
|
|
6
6
|
}
|
|
7
7
|
</style>
|
|
8
|
-
`}class Tu extends k.HTMLElement{constructor(){if(super(),hA(this,Pt,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);const e=Zt(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e)}}static get observedAttributes(){return[xe.MEDIA_CONTROLLER,_.MEDIA_PAUSED]}attributeChangedCallback(e,t,s){var r,n,a,o,l;e===xe.MEDIA_CONTROLLER&&(t&&((n=(r=Is(this,Pt))==null?void 0:r.unassociateElement)==null||n.call(r,this),Mo(this,Pt,null)),s&&this.isConnected&&(Mo(this,Pt,(a=this.getRootNode())==null?void 0:a.getElementById(s)),(l=(o=Is(this,Pt))==null?void 0:o.associateElement)==null||l.call(o,this)))}connectedCallback(){var e,t,s,r;this.tabIndex=-1,this.setAttribute("aria-hidden","true"),Mo(this,Pt,mA(this)),this.getAttribute(xe.MEDIA_CONTROLLER)&&((t=(e=Is(this,Pt))==null?void 0:e.associateElement)==null||t.call(e,this)),(s=Is(this,Pt))==null||s.addEventListener("pointerdown",this),(r=Is(this,Pt))==null||r.addEventListener("click",this)}disconnectedCallback(){var e,t,s,r;this.getAttribute(xe.MEDIA_CONTROLLER)&&((t=(e=Is(this,Pt))==null?void 0:e.unassociateElement)==null||t.call(e,this)),(s=Is(this,Pt))==null||s.removeEventListener("pointerdown",this),(r=Is(this,Pt))==null||r.removeEventListener("click",this),Mo(this,Pt,null)}handleEvent(e){var t;const s=(t=e.composedPath())==null?void 0:t[0];if(["video","media-controller"].includes(s?.localName)){if(e.type==="pointerdown")this._pointerType=e.pointerType;else if(e.type==="click"){const{clientX:n,clientY:a}=e,{left:o,top:l,width:d,height:u}=this.getBoundingClientRect(),c=n-o,h=a-l;if(c<0||h<0||c>d||h>u||d===0&&u===0)return;const f=this._pointerType||"mouse";if(this._pointerType=void 0,f===oc.TOUCH){this.handleTap(e);return}else if(f===oc.MOUSE||f===oc.PEN){this.handleMouseClick(e);return}}}}get mediaPaused(){return ye(this,_.MEDIA_PAUSED)}set mediaPaused(e){be(this,_.MEDIA_PAUSED,e)}handleTap(e){}handleMouseClick(e){const t=this.mediaPaused?
|
|
8
|
+
`}class Tu extends k.HTMLElement{constructor(){if(super(),hA(this,Pt,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);const e=Zt(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e)}}static get observedAttributes(){return[xe.MEDIA_CONTROLLER,_.MEDIA_PAUSED]}attributeChangedCallback(e,t,s){var r,n,a,o,l;e===xe.MEDIA_CONTROLLER&&(t&&((n=(r=Is(this,Pt))==null?void 0:r.unassociateElement)==null||n.call(r,this),Mo(this,Pt,null)),s&&this.isConnected&&(Mo(this,Pt,(a=this.getRootNode())==null?void 0:a.getElementById(s)),(l=(o=Is(this,Pt))==null?void 0:o.associateElement)==null||l.call(o,this)))}connectedCallback(){var e,t,s,r;this.tabIndex=-1,this.setAttribute("aria-hidden","true"),Mo(this,Pt,mA(this)),this.getAttribute(xe.MEDIA_CONTROLLER)&&((t=(e=Is(this,Pt))==null?void 0:e.associateElement)==null||t.call(e,this)),(s=Is(this,Pt))==null||s.addEventListener("pointerdown",this),(r=Is(this,Pt))==null||r.addEventListener("click",this)}disconnectedCallback(){var e,t,s,r;this.getAttribute(xe.MEDIA_CONTROLLER)&&((t=(e=Is(this,Pt))==null?void 0:e.unassociateElement)==null||t.call(e,this)),(s=Is(this,Pt))==null||s.removeEventListener("pointerdown",this),(r=Is(this,Pt))==null||r.removeEventListener("click",this),Mo(this,Pt,null)}handleEvent(e){var t;const s=(t=e.composedPath())==null?void 0:t[0];if(["video","media-controller"].includes(s?.localName)){if(e.type==="pointerdown")this._pointerType=e.pointerType;else if(e.type==="click"){const{clientX:n,clientY:a}=e,{left:o,top:l,width:d,height:u}=this.getBoundingClientRect(),c=n-o,h=a-l;if(c<0||h<0||c>d||h>u||d===0&&u===0)return;const f=this._pointerType||"mouse";if(this._pointerType=void 0,f===oc.TOUCH){this.handleTap(e);return}else if(f===oc.MOUSE||f===oc.PEN){this.handleMouseClick(e);return}}}}get mediaPaused(){return ye(this,_.MEDIA_PAUSED)}set mediaPaused(e){be(this,_.MEDIA_PAUSED,e)}handleTap(e){}handleMouseClick(e){const t=this.mediaPaused?Q.MEDIA_PLAY_REQUEST:Q.MEDIA_PAUSE_REQUEST;this.dispatchEvent(new k.CustomEvent(t,{composed:!0,bubbles:!0}))}}Pt=new WeakMap;Tu.shadowRootOptions={mode:"open"};Tu.getTemplateHTML=fA;function mA(i){var e;const t=i.getAttribute(xe.MEDIA_CONTROLLER);return t?(e=i.getRootNode())==null?void 0:e.getElementById(t):ia(i,"media-controller")}k.customElements.get("media-gesture-receiver")||k.customElements.define("media-gesture-receiver",Tu);var rh=Tu,rm=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Yt=(i,e,t)=>(rm(i,e,"read from private field"),t?t.call(i):e.get(i)),Gt=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},ar=(i,e,t,s)=>(rm(i,e,"write to private field"),e.set(i,t),t),oi=(i,e,t)=>(rm(i,e,"access private method"),t),Cd,en,so,Rn,pl,nh,rE,ya,gl,ah,nE,oh,aE,ro,_u,Au,nm,zn,no;const ne={AUDIO:"audio",AUTOHIDE:"autohide",BREAKPOINTS:"breakpoints",GESTURES_DISABLED:"gesturesdisabled",KEYBOARD_CONTROL:"keyboardcontrol",NO_AUTOHIDE:"noautohide",USER_INACTIVE:"userinactive",AUTOHIDE_OVER_CONTROLS:"autohideovercontrols"};function pA(i){return`
|
|
9
9
|
<style>
|
|
10
10
|
|
|
11
11
|
:host([${_.MEDIA_IS_FULLSCREEN}]) ::slotted([slot=media]) {
|
|
@@ -156,7 +156,7 @@ import{j as N}from"./jsx-runtime-C5WNSv3b.js";import{R as ve,r as Se}from"./inde
|
|
|
156
156
|
<slot part="bottom chrome"></slot>
|
|
157
157
|
</span>
|
|
158
158
|
<slot name="dialog" part="layer dialog-layer"></slot>
|
|
159
|
-
`}const gA=Object.values(_),vA="sm:384 md:576 lg:768 xl:960";function EA(i){oE(i.target,i.contentRect.width)}function oE(i,e){var t;if(!i.isConnected)return;const s=(t=i.getAttribute(ne.BREAKPOINTS))!=null?t:vA,r=yA(s),n=bA(r,e);let a=!1;if(Object.keys(r).forEach(o=>{if(n.includes(o)){i.hasAttribute(`breakpoint${o}`)||(i.setAttribute(`breakpoint${o}`,""),a=!0);return}i.hasAttribute(`breakpoint${o}`)&&(i.removeAttribute(`breakpoint${o}`),a=!0)}),a){const o=new CustomEvent(ys.BREAKPOINTS_CHANGE,{detail:n});i.dispatchEvent(o)}i.breakpointsComputed||(i.breakpointsComputed=!0,i.dispatchEvent(new CustomEvent(ys.BREAKPOINTS_COMPUTED,{bubbles:!0,composed:!0})))}function yA(i){const e=i.split(/\s+/);return Object.fromEntries(e.map(t=>t.split(":")))}function bA(i,e){return Object.keys(i).filter(t=>e>=parseInt(i[t]))}class xo extends k.HTMLElement{constructor(){if(super(),Gt(this,nh),Gt(this,ah),Gt(this,oh),Gt(this,ro),Gt(this,Au),Gt(this,zn),Gt(this,Cd,0),Gt(this,en,null),Gt(this,so,null),Gt(this,Rn,void 0),this.breakpointsComputed=!1,Gt(this,pl,new MutationObserver(oi(this,nh,rE).bind(this))),Gt(this,ya,!1),Gt(this,gl,t=>{Yt(this,ya)||(setTimeout(()=>{EA(t),ar(this,ya,!1)},0),ar(this,ya,!0))}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);const t=Zt(this.attributes),s=this.constructor.getTemplateHTML(t);this.shadowRoot.setHTMLUnsafe?this.shadowRoot.setHTMLUnsafe(s):this.shadowRoot.innerHTML=s}const e=this.querySelector(":scope > slot[slot=media]");e&&e.addEventListener("slotchange",()=>{if(!e.assignedElements({flatten:!0}).length){Yt(this,en)&&this.mediaUnsetCallback(Yt(this,en));return}this.handleMediaUpdated(this.media)})}static get observedAttributes(){return[ne.AUTOHIDE,ne.GESTURES_DISABLED].concat(gA).filter(e=>![_.MEDIA_RENDITION_LIST,_.MEDIA_AUDIO_TRACK_LIST,_.MEDIA_CHAPTERS_CUES,_.MEDIA_WIDTH,_.MEDIA_HEIGHT,_.MEDIA_ERROR,_.MEDIA_ERROR_MESSAGE].includes(e))}attributeChangedCallback(e,t,s){e.toLowerCase()==ne.AUTOHIDE&&(this.autohide=s)}get media(){let e=this.querySelector(":scope > [slot=media]");return e?.nodeName=="SLOT"&&(e=e.assignedElements({flatten:!0})[0]),e}async handleMediaUpdated(e){e&&(ar(this,en,e),e.localName.includes("-")&&await k.customElements.whenDefined(e.localName),this.mediaSetCallback(e))}connectedCallback(){var e;Yt(this,pl).observe(this,{childList:!0,subtree:!0}),Yn(this,Yt(this,gl));const t=this.getAttribute(ne.AUDIO)!=null,s=te(t?"audio player":"video player");this.setAttribute("role","region"),this.setAttribute("aria-label",s),this.handleMediaUpdated(this.media),this.setAttribute(ne.USER_INACTIVE,""),oE(this,this.getBoundingClientRect().width),this.addEventListener("pointerdown",this),this.addEventListener("pointermove",this),this.addEventListener("pointerup",this),this.addEventListener("mouseleave",this),this.addEventListener("keyup",this),(e=k.window)==null||e.addEventListener("mouseup",this)}disconnectedCallback(){var e;Yt(this,pl).disconnect(),jn(this,Yt(this,gl)),this.media&&this.mediaUnsetCallback(this.media),(e=k.window)==null||e.removeEventListener("mouseup",this)}mediaSetCallback(e){}mediaUnsetCallback(e){ar(this,en,null)}handleEvent(e){switch(e.type){case"pointerdown":ar(this,Cd,e.timeStamp);break;case"pointermove":oi(this,ah,nE).call(this,e);break;case"pointerup":oi(this,oh,aE).call(this,e);break;case"mouseleave":oi(this,ro,_u).call(this);break;case"mouseup":this.removeAttribute(ne.KEYBOARD_CONTROL);break;case"keyup":oi(this,zn,no).call(this),this.setAttribute(ne.KEYBOARD_CONTROL,"");break}}set autohide(e){const t=Number(e);ar(this,Rn,isNaN(t)?0:t)}get autohide(){return(Yt(this,Rn)===void 0?2:Yt(this,Rn)).toString()}get breakpoints(){return He(this,ne.BREAKPOINTS)}set breakpoints(e){Ge(this,ne.BREAKPOINTS,e)}get audio(){return ye(this,ne.AUDIO)}set audio(e){be(this,ne.AUDIO,e)}get gesturesDisabled(){return ye(this,ne.GESTURES_DISABLED)}set gesturesDisabled(e){be(this,ne.GESTURES_DISABLED,e)}get keyboardControl(){return ye(this,ne.KEYBOARD_CONTROL)}set keyboardControl(e){be(this,ne.KEYBOARD_CONTROL,e)}get noAutohide(){return ye(this,ne.NO_AUTOHIDE)}set noAutohide(e){be(this,ne.NO_AUTOHIDE,e)}get autohideOverControls(){return ye(this,ne.AUTOHIDE_OVER_CONTROLS)}set autohideOverControls(e){be(this,ne.AUTOHIDE_OVER_CONTROLS,e)}get userInteractive(){return ye(this,ne.USER_INACTIVE)}set userInteractive(e){be(this,ne.USER_INACTIVE,e)}}Cd=new WeakMap;en=new WeakMap;so=new WeakMap;Rn=new WeakMap;pl=new WeakMap;nh=new WeakSet;rE=function(i){const e=this.media;for(const t of i){if(t.type!=="childList")continue;const s=t.removedNodes;for(const r of s){if(r.slot!="media"||t.target!=this)continue;let n=t.previousSibling&&t.previousSibling.previousElementSibling;if(!n||!e)this.mediaUnsetCallback(r);else{let a=n.slot!=="media";for(;(n=n.previousSibling)!==null;)n.slot=="media"&&(a=!1);a&&this.mediaUnsetCallback(r)}}if(e)for(const r of t.addedNodes)r===e&&this.handleMediaUpdated(e)}};ya=new WeakMap;gl=new WeakMap;ah=new WeakSet;nE=function(i){if(i.pointerType!=="mouse"&&i.timeStamp-Yt(this,Cd)<250)return;oi(this,Au,nm).call(this),clearTimeout(Yt(this,so));const e=this.hasAttribute(ne.AUTOHIDE_OVER_CONTROLS);([this,this.media].includes(i.target)||e)&&oi(this,zn,no).call(this)};oh=new WeakSet;aE=function(i){if(i.pointerType==="touch"){const e=!this.hasAttribute(ne.USER_INACTIVE);[this,this.media].includes(i.target)&&e?oi(this,ro,_u).call(this):oi(this,zn,no).call(this)}else i.composedPath().some(e=>["media-play-button","media-fullscreen-button"].includes(e?.localName))&&oi(this,zn,no).call(this)};ro=new WeakSet;_u=function(){if(Yt(this,Rn)<0||this.hasAttribute(ne.USER_INACTIVE))return;this.setAttribute(ne.USER_INACTIVE,"");const i=new k.CustomEvent(ys.USER_INACTIVE_CHANGE,{composed:!0,bubbles:!0,detail:!0});this.dispatchEvent(i)};Au=new WeakSet;nm=function(){if(!this.hasAttribute(ne.USER_INACTIVE))return;this.removeAttribute(ne.USER_INACTIVE);const i=new k.CustomEvent(ys.USER_INACTIVE_CHANGE,{composed:!0,bubbles:!0,detail:!1});this.dispatchEvent(i)};zn=new WeakSet;no=function(){oi(this,Au,nm).call(this),clearTimeout(Yt(this,so));const i=parseInt(this.autohide);i<0||ar(this,so,setTimeout(()=>{oi(this,ro,_u).call(this)},i*1e3))};xo.shadowRootOptions={mode:"open"};xo.getTemplateHTML=pA;k.customElements.get("media-container")||k.customElements.define("media-container",xo);var TA=xo,lE=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},bt=(i,e,t)=>(lE(i,e,"read from private field"),t?t.call(i):e.get(i)),na=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Po=(i,e,t,s)=>(lE(i,e,"write to private field"),e.set(i,t),t),tn,sn,wd,Er,us,Cs;class am{constructor(e,t,{defaultValue:s}={defaultValue:void 0}){na(this,us),na(this,tn,void 0),na(this,sn,void 0),na(this,wd,void 0),na(this,Er,new Set),Po(this,tn,e),Po(this,sn,t),Po(this,wd,new Set(s))}[Symbol.iterator](){return bt(this,us,Cs).values()}get length(){return bt(this,us,Cs).size}get value(){var e;return(e=[...bt(this,us,Cs)].join(" "))!=null?e:""}set value(e){var t;e!==this.value&&(Po(this,Er,new Set),this.add(...(t=e?.split(" "))!=null?t:[]))}toString(){return this.value}item(e){return[...bt(this,us,Cs)][e]}values(){return bt(this,us,Cs).values()}forEach(e,t){bt(this,us,Cs).forEach(e,t)}add(...e){var t,s;e.forEach(r=>bt(this,Er).add(r)),!(this.value===""&&!((t=bt(this,tn))!=null&&t.hasAttribute(`${bt(this,sn)}`)))&&((s=bt(this,tn))==null||s.setAttribute(`${bt(this,sn)}`,`${this.value}`))}remove(...e){var t;e.forEach(s=>bt(this,Er).delete(s)),(t=bt(this,tn))==null||t.setAttribute(`${bt(this,sn)}`,`${this.value}`)}contains(e){return bt(this,us,Cs).has(e)}toggle(e,t){return typeof t<"u"?t?(this.add(e),!0):(this.remove(e),!1):this.contains(e)?(this.remove(e),!1):(this.add(e),!0)}replace(e,t){return this.remove(e),this.add(t),e===t}}tn=new WeakMap;sn=new WeakMap;wd=new WeakMap;Er=new WeakMap;us=new WeakSet;Cs=function(){return bt(this,Er).size?bt(this,Er):bt(this,wd)};const _A=(i="")=>i.split(/\s+/),dE=(i="")=>{const[e,t,s]=i.split(":"),r=s?decodeURIComponent(s):void 0;return{kind:e==="cc"?ts.CAPTIONS:ts.SUBTITLES,language:t,label:r}},Su=(i="",e={})=>_A(i).map(t=>{const s=dE(t);return{...e,...s}}),uE=i=>i?Array.isArray(i)?i.map(e=>typeof e=="string"?dE(e):e):typeof i=="string"?Su(i):[i]:[],lh=({kind:i,label:e,language:t}={kind:"subtitles"})=>e?`${i==="captions"?"cc":"sb"}:${t}:${encodeURIComponent(e)}`:t,ao=(i=[])=>Array.prototype.map.call(i,lh).join(" "),AA=(i,e)=>t=>t[i]===e,cE=i=>{const e=Object.entries(i).map(([t,s])=>AA(t,s));return t=>e.every(s=>s(t))},Va=(i,e=[],t=[])=>{const s=uE(t).map(cE),r=n=>s.some(a=>a(n));Array.from(e).filter(r).forEach(n=>{n.mode=i})},Iu=(i,e=()=>!0)=>{if(!i?.textTracks)return[];const t=typeof e=="function"?e:cE(e);return Array.from(i.textTracks).filter(t)},hE=i=>{var e;return!!((e=i.mediaSubtitlesShowing)!=null&&e.length)||i.hasAttribute(_.MEDIA_SUBTITLES_SHOWING)},SA=i=>{var e;const{media:t,fullscreenElement:s}=i;try{const r=s&&"requestFullscreen"in s?"requestFullscreen":s&&"webkitRequestFullScreen"in s?"webkitRequestFullScreen":void 0;if(r){const n=(e=s[r])==null?void 0:e.call(s);if(n instanceof Promise)return n.catch(()=>{})}else t?.webkitEnterFullscreen?t.webkitEnterFullscreen():t?.requestFullscreen&&t.requestFullscreen()}catch(r){console.error(r)}},Wp="exitFullscreen"in lt?"exitFullscreen":"webkitExitFullscreen"in lt?"webkitExitFullscreen":"webkitCancelFullScreen"in lt?"webkitCancelFullScreen":void 0,IA=i=>{var e;const{documentElement:t}=i;if(Wp){const s=(e=t?.[Wp])==null?void 0:e.call(t);if(s instanceof Promise)return s.catch(()=>{})}},ba="fullscreenElement"in lt?"fullscreenElement":"webkitFullscreenElement"in lt?"webkitFullscreenElement":void 0,xA=i=>{const{documentElement:e,media:t}=i,s=e?.[ba];return!s&&"webkitDisplayingFullscreen"in t&&"webkitPresentationMode"in t&&t.webkitDisplayingFullscreen&&t.webkitPresentationMode===j_.FULLSCREEN?t:s},LA=i=>{var e;const{media:t,documentElement:s,fullscreenElement:r=t}=i;if(!t||!s)return!1;const n=xA(i);if(!n)return!1;if(n===r||n===t)return!0;if(n.localName.includes("-")){let a=n.shadowRoot;if(!(ba in a))return Ts(n,r);for(;a?.[ba];){if(a[ba]===r)return!0;a=(e=a[ba])==null?void 0:e.shadowRoot}}return!1},RA="fullscreenEnabled"in lt?"fullscreenEnabled":"webkitFullscreenEnabled"in lt?"webkitFullscreenEnabled":void 0,kA=i=>{const{documentElement:e,media:t}=i;return!!e?.[RA]||t&&"webkitSupportsFullscreen"in t};let Oo;const om=()=>{var i,e;return Oo||(Oo=(e=(i=lt)==null?void 0:i.createElement)==null?void 0:e.call(i,"video"),Oo)},DA=async(i=om())=>{if(!i)return!1;const e=i.volume;i.volume=e/2+.1;const t=new AbortController,s=await Promise.race([CA(i,t.signal),wA(i,e)]);return t.abort(),s},CA=(i,e)=>new Promise(t=>{i.addEventListener("volumechange",()=>t(!0),{signal:e})}),wA=async(i,e)=>{for(let t=0;t<10;t++){if(i.volume===e)return!1;await Yv(10)}return i.volume!==e},MA=/.*Version\/.*Safari\/.*/.test(k.navigator.userAgent),fE=(i=om())=>k.matchMedia("(display-mode: standalone)").matches&&MA?!1:typeof i?.requestPictureInPicture=="function",mE=(i=om())=>kA({documentElement:lt,media:i}),PA=mE(),OA=fE(),NA=!!k.WebKitPlaybackTargetAvailabilityEvent,UA=!!k.chrome,Md=i=>Iu(i.media,e=>[ts.SUBTITLES,ts.CAPTIONS].includes(e.kind)).sort((e,t)=>e.kind>=t.kind?1:-1),pE=i=>Iu(i.media,e=>e.mode===Pn.SHOWING&&[ts.SUBTITLES,ts.CAPTIONS].includes(e.kind)),gE=(i,e)=>{const t=Md(i),s=pE(i),r=!!s.length;if(t.length){if(e===!1||r&&e!==!0)Va(Pn.DISABLED,t,s);else if(e===!0||!r&&e!==!1){let n=t[0];const{options:a}=i;if(!a?.noSubtitlesLangPref){const u=globalThis.localStorage.getItem("media-chrome-pref-subtitles-lang"),c=u?[u,...globalThis.navigator.languages]:globalThis.navigator.languages,h=t.filter(f=>c.some(m=>f.language.toLowerCase().startsWith(m.split("-")[0]))).sort((f,m)=>{const p=c.findIndex(v=>f.language.toLowerCase().startsWith(v.split("-")[0])),g=c.findIndex(v=>m.language.toLowerCase().startsWith(v.split("-")[0]));return p-g});h[0]&&(n=h[0])}const{language:o,label:l,kind:d}=n;Va(Pn.DISABLED,t,s),Va(Pn.SHOWING,t,[{language:o,label:l,kind:d}])}}},lm=(i,e)=>i===e?!0:i==null||e==null||typeof i!=typeof e?!1:typeof i=="number"&&Number.isNaN(i)&&Number.isNaN(e)?!0:typeof i!="object"?!1:Array.isArray(i)?$A(i,e):Object.entries(i).every(([t,s])=>t in e&&lm(s,e[t])),$A=(i,e)=>{const t=Array.isArray(i),s=Array.isArray(e);return t!==s?!1:t||s?i.length!==e.length?!1:i.every((r,n)=>lm(r,e[n])):!0},FA=Object.values(hs);let Pd;const BA=DA().then(i=>(Pd=i,Pd)),HA=async(...i)=>{await Promise.all(i.filter(e=>e).map(async e=>{if(!("localName"in e&&e instanceof k.HTMLElement))return;const t=e.localName;if(!t.includes("-"))return;const s=k.customElements.get(t);s&&e instanceof s||(await k.customElements.whenDefined(t),k.customElements.upgrade(e))}))},GA=new k.DOMParser,KA=i=>i&&(GA.parseFromString(i,"text/html").body.textContent||i),Ta={mediaError:{get(i,e){const{media:t}=i;if(e?.type!=="playing")return t?.error},mediaEvents:["emptied","error","playing"]},mediaErrorCode:{get(i,e){var t;const{media:s}=i;if(e?.type!=="playing")return(t=s?.error)==null?void 0:t.code},mediaEvents:["emptied","error","playing"]},mediaErrorMessage:{get(i,e){var t,s;const{media:r}=i;if(e?.type!=="playing")return(s=(t=r?.error)==null?void 0:t.message)!=null?s:""},mediaEvents:["emptied","error","playing"]},mediaWidth:{get(i){var e;const{media:t}=i;return(e=t?.videoWidth)!=null?e:0},mediaEvents:["resize"]},mediaHeight:{get(i){var e;const{media:t}=i;return(e=t?.videoHeight)!=null?e:0},mediaEvents:["resize"]},mediaPaused:{get(i){var e;const{media:t}=i;return(e=t?.paused)!=null?e:!0},set(i,e){var t;const{media:s}=e;s&&(i?s.pause():(t=s.play())==null||t.catch(()=>{}))},mediaEvents:["play","playing","pause","emptied"]},mediaHasPlayed:{get(i,e){const{media:t}=i;return t?e?e.type==="playing":!t.paused:!1},mediaEvents:["playing","emptied"]},mediaEnded:{get(i){var e;const{media:t}=i;return(e=t?.ended)!=null?e:!1},mediaEvents:["seeked","ended","emptied"]},mediaPlaybackRate:{get(i){var e;const{media:t}=i;return(e=t?.playbackRate)!=null?e:1},set(i,e){const{media:t}=e;t&&Number.isFinite(+i)&&(t.playbackRate=+i)},mediaEvents:["ratechange","loadstart"]},mediaMuted:{get(i){var e;const{media:t}=i;return(e=t?.muted)!=null?e:!1},set(i,e){const{media:t,options:{noMutedPref:s}={}}=e;if(t){t.muted=i;try{const r=k.localStorage.getItem("media-chrome-pref-muted")!==null,n=t.hasAttribute("muted");if(s){r&&k.localStorage.removeItem("media-chrome-pref-muted");return}if(n&&!r)return;k.localStorage.setItem("media-chrome-pref-muted",i?"true":"false")}catch(r){console.debug("Error setting muted pref",r)}}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(i,e)=>{const{options:{noMutedPref:t}}=e,{media:s}=e;if(!(!s||s.muted||t))try{const r=k.localStorage.getItem("media-chrome-pref-muted")==="true";Ta.mediaMuted.set(r,e),i(r)}catch(r){console.debug("Error getting muted pref",r)}}]},mediaLoop:{get(i){const{media:e}=i;return e?.loop},set(i,e){const{media:t}=e;t&&(t.loop=i)},mediaEvents:["medialooprequest"]},mediaVolume:{get(i){var e;const{media:t}=i;return(e=t?.volume)!=null?e:1},set(i,e){const{media:t,options:{noVolumePref:s}={}}=e;if(t){try{i==null?k.localStorage.removeItem("media-chrome-pref-volume"):!t.hasAttribute("muted")&&!s&&k.localStorage.setItem("media-chrome-pref-volume",i.toString())}catch(r){console.debug("Error setting volume pref",r)}Number.isFinite(+i)&&(t.volume=+i)}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(i,e)=>{const{options:{noVolumePref:t}}=e;if(!t)try{const{media:s}=e;if(!s)return;const r=k.localStorage.getItem("media-chrome-pref-volume");if(r==null)return;Ta.mediaVolume.set(+r,e),i(+r)}catch(s){console.debug("Error getting volume pref",s)}}]},mediaVolumeLevel:{get(i){const{media:e}=i;return typeof e?.volume>"u"?"high":e.muted||e.volume===0?"off":e.volume<.5?"low":e.volume<.75?"medium":"high"},mediaEvents:["volumechange"]},mediaCurrentTime:{get(i){var e;const{media:t}=i;return(e=t?.currentTime)!=null?e:0},set(i,e){const{media:t}=e;!t||!em(i)||(t.currentTime=i)},mediaEvents:["timeupdate","loadedmetadata"]},mediaDuration:{get(i){const{media:e,options:{defaultDuration:t}={}}=i;return t&&(!e||!e.duration||Number.isNaN(e.duration)||!Number.isFinite(e.duration))?t:Number.isFinite(e?.duration)?e.duration:Number.NaN},mediaEvents:["durationchange","loadedmetadata","emptied"]},mediaLoading:{get(i){const{media:e}=i;return e?.readyState<3},mediaEvents:["waiting","playing","emptied"]},mediaSeekable:{get(i){var e;const{media:t}=i;if(!((e=t?.seekable)!=null&&e.length))return;const s=t.seekable.start(0),r=t.seekable.end(t.seekable.length-1);if(!(!s&&!r))return[Number(s.toFixed(3)),Number(r.toFixed(3))]},mediaEvents:["loadedmetadata","emptied","progress","seekablechange"]},mediaBuffered:{get(i){var e;const{media:t}=i,s=(e=t?.buffered)!=null?e:[];return Array.from(s).map((r,n)=>[Number(s.start(n).toFixed(3)),Number(s.end(n).toFixed(3))])},mediaEvents:["progress","emptied"]},mediaStreamType:{get(i){const{media:e,options:{defaultStreamType:t}={}}=i,s=[hs.LIVE,hs.ON_DEMAND].includes(t)?t:void 0;if(!e)return s;const{streamType:r}=e;if(FA.includes(r))return r===hs.UNKNOWN?s:r;const n=e.duration;return n===1/0?hs.LIVE:Number.isFinite(n)?hs.ON_DEMAND:s},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange"]},mediaTargetLiveWindow:{get(i){const{media:e}=i;if(!e)return Number.NaN;const{targetLiveWindow:t}=e,s=Ta.mediaStreamType.get(i);return(t==null||Number.isNaN(t))&&s===hs.LIVE?0:t},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange","targetlivewindowchange"]},mediaTimeIsLive:{get(i){const{media:e,options:{liveEdgeOffset:t=10}={}}=i;if(!e)return!1;if(typeof e.liveEdgeStart=="number")return Number.isNaN(e.liveEdgeStart)?!1:e.currentTime>=e.liveEdgeStart;if(!(Ta.mediaStreamType.get(i)===hs.LIVE))return!1;const r=e.seekable;if(!r)return!0;if(!r.length)return!1;const n=r.end(r.length-1)-t;return e.currentTime>=n},mediaEvents:["playing","timeupdate","progress","waiting","emptied"]},mediaSubtitlesList:{get(i){return Md(i).map(({kind:e,label:t,language:s})=>({kind:e,label:t,language:s}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack"]},mediaSubtitlesShowing:{get(i){return pE(i).map(({kind:e,label:t,language:s})=>({kind:e,label:t,language:s}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(i,e)=>{var t,s;const{media:r,options:n}=e;if(!r)return;const a=o=>{var l;!n.defaultSubtitles||o&&![ts.CAPTIONS,ts.SUBTITLES].includes((l=o?.track)==null?void 0:l.kind)||gE(e,!0)};return r.addEventListener("loadstart",a),(t=r.textTracks)==null||t.addEventListener("addtrack",a),(s=r.textTracks)==null||s.addEventListener("removetrack",a),()=>{var o,l;r.removeEventListener("loadstart",a),(o=r.textTracks)==null||o.removeEventListener("addtrack",a),(l=r.textTracks)==null||l.removeEventListener("removetrack",a)}}]},mediaChaptersCues:{get(i){var e;const{media:t}=i;if(!t)return[];const[s]=Iu(t,{kind:ts.CHAPTERS});return Array.from((e=s?.cues)!=null?e:[]).map(({text:r,startTime:n,endTime:a})=>({text:KA(r),startTime:n,endTime:a}))},mediaEvents:["loadstart","loadedmetadata"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(i,e)=>{var t;const{media:s}=e;if(!s)return;const r=s.querySelector('track[kind="chapters"][default][src]'),n=(t=s.shadowRoot)==null?void 0:t.querySelector(':is(video,audio) > track[kind="chapters"][default][src]');return r?.addEventListener("load",i),n?.addEventListener("load",i),()=>{r?.removeEventListener("load",i),n?.removeEventListener("load",i)}}]},mediaIsPip:{get(i){var e,t;const{media:s,documentElement:r}=i;if(!s||!r||!r.pictureInPictureElement)return!1;if(r.pictureInPictureElement===s)return!0;if(r.pictureInPictureElement instanceof HTMLMediaElement)return(e=s.localName)!=null&&e.includes("-")?Ts(s,r.pictureInPictureElement):!1;if(r.pictureInPictureElement.localName.includes("-")){let n=r.pictureInPictureElement.shadowRoot;for(;n?.pictureInPictureElement;){if(n.pictureInPictureElement===s)return!0;n=(t=n.pictureInPictureElement)==null?void 0:t.shadowRoot}}return!1},set(i,e){const{media:t}=e;if(t)if(i){if(!lt.pictureInPictureEnabled){console.warn("MediaChrome: Picture-in-picture is not enabled");return}if(!t.requestPictureInPicture){console.warn("MediaChrome: The current media does not support picture-in-picture");return}const s=()=>{console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a readyState > 0.")};t.requestPictureInPicture().catch(r=>{if(r.code===11){if(!t.src){console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a src set.");return}if(t.readyState===0&&t.preload==="none"){const n=()=>{t.removeEventListener("loadedmetadata",a),t.preload="none"},a=()=>{t.requestPictureInPicture().catch(s),n()};t.addEventListener("loadedmetadata",a),t.preload="metadata",setTimeout(()=>{t.readyState===0&&s(),n()},1e3)}else throw r}else throw r})}else lt.pictureInPictureElement&<.exitPictureInPicture()},mediaEvents:["enterpictureinpicture","leavepictureinpicture"]},mediaRenditionList:{get(i){var e;const{media:t}=i;return[...(e=t?.videoRenditions)!=null?e:[]].map(s=>({...s}))},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaRenditionSelected:{get(i){var e,t,s;const{media:r}=i;return(s=(t=r?.videoRenditions)==null?void 0:t[(e=r.videoRenditions)==null?void 0:e.selectedIndex])==null?void 0:s.id},set(i,e){const{media:t}=e;if(!t?.videoRenditions){console.warn("MediaController: Rendition selection not supported by this media.");return}const s=i,r=Array.prototype.findIndex.call(t.videoRenditions,n=>n.id==s);t.videoRenditions.selectedIndex!=r&&(t.videoRenditions.selectedIndex=r)},mediaEvents:["emptied"],videoRenditionsEvents:["addrendition","removerendition","change"]},mediaAudioTrackList:{get(i){var e;const{media:t}=i;return[...(e=t?.audioTracks)!=null?e:[]]},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaAudioTrackEnabled:{get(i){var e,t;const{media:s}=i;return(t=[...(e=s?.audioTracks)!=null?e:[]].find(r=>r.enabled))==null?void 0:t.id},set(i,e){const{media:t}=e;if(!t?.audioTracks){console.warn("MediaChrome: Audio track selection not supported by this media.");return}const s=i;for(const r of t.audioTracks)r.enabled=s==r.id},mediaEvents:["emptied"],audioTracksEvents:["addtrack","removetrack","change"]},mediaIsFullscreen:{get(i){return LA(i)},set(i,e,t){var s;i?(SA(e),t.detail&&((s=e.media)==null||s.focus())):IA(e)},rootEvents:["fullscreenchange","webkitfullscreenchange"],mediaEvents:["webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"]},mediaIsCasting:{get(i){var e;const{media:t}=i;return!t?.remote||((e=t.remote)==null?void 0:e.state)==="disconnected"?!1:!!t.remote.state},set(i,e){var t,s;const{media:r}=e;if(r&&!(i&&((t=r.remote)==null?void 0:t.state)!=="disconnected")&&!(!i&&((s=r.remote)==null?void 0:s.state)!=="connected")){if(typeof r.remote.prompt!="function"){console.warn("MediaChrome: Casting is not supported in this environment");return}r.remote.prompt().catch(()=>{})}},remoteEvents:["connect","connecting","disconnect"]},mediaIsAirplaying:{get(){return!1},set(i,e){const{media:t}=e;if(t){if(!(t.webkitShowPlaybackTargetPicker&&k.WebKitPlaybackTargetAvailabilityEvent)){console.error("MediaChrome: received a request to select AirPlay but AirPlay is not supported in this environment");return}t.webkitShowPlaybackTargetPicker()}},mediaEvents:["webkitcurrentplaybacktargetiswirelesschanged"]},mediaFullscreenUnavailable:{get(i){const{media:e}=i;if(!PA||!mE(e))return Ht.UNSUPPORTED}},mediaPipUnavailable:{get(i){const{media:e}=i;if(!OA||!fE(e))return Ht.UNSUPPORTED;if(e?.disablePictureInPicture)return Ht.UNAVAILABLE}},mediaVolumeUnavailable:{get(i){const{media:e}=i;if(Pd===!1||e?.volume==null)return Ht.UNSUPPORTED},stateOwnersUpdateHandlers:[i=>{Pd==null&&BA.then(e=>i(e?void 0:Ht.UNSUPPORTED))}]},mediaCastUnavailable:{get(i,{availability:e="not-available"}={}){var t;const{media:s}=i;if(!UA||!((t=s?.remote)!=null&&t.state))return Ht.UNSUPPORTED;if(!(e==null||e==="available"))return Ht.UNAVAILABLE},stateOwnersUpdateHandlers:[(i,e)=>{var t;const{media:s}=e;return s?(s.disableRemotePlayback||s.hasAttribute("disableremoteplayback")||(t=s?.remote)==null||t.watchAvailability(n=>{i({availability:n?"available":"not-available"})}).catch(n=>{n.name==="NotSupportedError"?i({availability:null}):i({availability:"not-available"})}),()=>{var n;(n=s?.remote)==null||n.cancelWatchAvailability().catch(()=>{})}):void 0}]},mediaAirplayUnavailable:{get(i,e){if(!NA)return Ht.UNSUPPORTED;if(e?.availability==="not-available")return Ht.UNAVAILABLE},mediaEvents:["webkitplaybacktargetavailabilitychanged"],stateOwnersUpdateHandlers:[(i,e)=>{var t;const{media:s}=e;return s?(s.disableRemotePlayback||s.hasAttribute("disableremoteplayback")||(t=s?.remote)==null||t.watchAvailability(n=>{i({availability:n?"available":"not-available"})}).catch(n=>{n.name==="NotSupportedError"?i({availability:null}):i({availability:"not-available"})}),()=>{var n;(n=s?.remote)==null||n.cancelWatchAvailability().catch(()=>{})}):void 0}]},mediaRenditionUnavailable:{get(i){var e;const{media:t}=i;if(!t?.videoRenditions)return Ht.UNSUPPORTED;if(!((e=t.videoRenditions)!=null&&e.length))return Ht.UNAVAILABLE},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaAudioTrackUnavailable:{get(i){var e,t;const{media:s}=i;if(!s?.audioTracks)return Ht.UNSUPPORTED;if(((t=(e=s.audioTracks)==null?void 0:e.length)!=null?t:0)<=1)return Ht.UNAVAILABLE},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaLang:{get(i){const{options:{mediaLang:e}={}}=i;return e??"en"}}},VA={[z.MEDIA_PREVIEW_REQUEST](i,e,{detail:t}){var s,r,n;const{media:a}=e,o=t??void 0;let l,d;if(a&&o!=null){const[f]=Iu(a,{kind:ts.METADATA,label:"thumbnails"}),m=Array.prototype.find.call((s=f?.cues)!=null?s:[],(p,g,v)=>g===0?p.endTime>o:g===v.length-1?p.startTime<=o:p.startTime<=o&&p.endTime>o);if(m){const p=/'^(?:[a-z]+:)?\/\//i.test(m.text)||(r=a?.querySelector('track[label="thumbnails"]'))==null?void 0:r.src,g=new URL(m.text,p);d=new URLSearchParams(g.hash).get("#xywh").split(",").map(b=>+b),l=g.href}}const u=i.mediaDuration.get(e);let h=(n=i.mediaChaptersCues.get(e).find((f,m,p)=>m===p.length-1&&u===f.endTime?f.startTime<=o&&f.endTime>=o:f.startTime<=o&&f.endTime>o))==null?void 0:n.text;return t!=null&&h==null&&(h=""),{mediaPreviewTime:o,mediaPreviewImage:l,mediaPreviewCoords:d,mediaPreviewChapter:h}},[z.MEDIA_PAUSE_REQUEST](i,e){i["mediaPaused"].set(!0,e)},[z.MEDIA_PLAY_REQUEST](i,e){var t,s,r,n;const a="mediaPaused",l=i.mediaStreamType.get(e)===hs.LIVE,d=!((t=e.options)!=null&&t.noAutoSeekToLive),u=i.mediaTargetLiveWindow.get(e)>0;if(l&&d&&!u){const c=(s=i.mediaSeekable.get(e))==null?void 0:s[1];if(c){const h=(n=(r=e.options)==null?void 0:r.seekToLiveOffset)!=null?n:0,f=c-h;i.mediaCurrentTime.set(f,e)}}i[a].set(!1,e)},[z.MEDIA_PLAYBACK_RATE_REQUEST](i,e,{detail:t}){const s="mediaPlaybackRate",r=t;i[s].set(r,e)},[z.MEDIA_MUTE_REQUEST](i,e){i["mediaMuted"].set(!0,e)},[z.MEDIA_UNMUTE_REQUEST](i,e){const t="mediaMuted";i.mediaVolume.get(e)||i.mediaVolume.set(.25,e),i[t].set(!1,e)},[z.MEDIA_LOOP_REQUEST](i,e,{detail:t}){const s="mediaLoop",r=!!t;return i[s].set(r,e),{mediaLoop:r}},[z.MEDIA_VOLUME_REQUEST](i,e,{detail:t}){const s="mediaVolume",r=t;r&&i.mediaMuted.get(e)&&i.mediaMuted.set(!1,e),i[s].set(r,e)},[z.MEDIA_SEEK_REQUEST](i,e,{detail:t}){const s="mediaCurrentTime",r=t;i[s].set(r,e)},[z.MEDIA_SEEK_TO_LIVE_REQUEST](i,e){var t,s,r;const n="mediaCurrentTime",a=(t=i.mediaSeekable.get(e))==null?void 0:t[1];if(Number.isNaN(Number(a)))return;const o=(r=(s=e.options)==null?void 0:s.seekToLiveOffset)!=null?r:0,l=a-o;i[n].set(l,e)},[z.MEDIA_SHOW_SUBTITLES_REQUEST](i,e,{detail:t}){var s;const{options:r}=e,n=Md(e),a=uE(t),o=(s=a[0])==null?void 0:s.language;o&&!r.noSubtitlesLangPref&&k.localStorage.setItem("media-chrome-pref-subtitles-lang",o),Va(Pn.SHOWING,n,a)},[z.MEDIA_DISABLE_SUBTITLES_REQUEST](i,e,{detail:t}){const s=Md(e),r=t??[];Va(Pn.DISABLED,s,r)},[z.MEDIA_TOGGLE_SUBTITLES_REQUEST](i,e,{detail:t}){gE(e,t)},[z.MEDIA_RENDITION_REQUEST](i,e,{detail:t}){const s="mediaRenditionSelected",r=t;i[s].set(r,e)},[z.MEDIA_AUDIO_TRACK_REQUEST](i,e,{detail:t}){const s="mediaAudioTrackEnabled",r=t;i[s].set(r,e)},[z.MEDIA_ENTER_PIP_REQUEST](i,e){const t="mediaIsPip";i.mediaIsFullscreen.get(e)&&i.mediaIsFullscreen.set(!1,e),i[t].set(!0,e)},[z.MEDIA_EXIT_PIP_REQUEST](i,e){i["mediaIsPip"].set(!1,e)},[z.MEDIA_ENTER_FULLSCREEN_REQUEST](i,e,t){const s="mediaIsFullscreen";i.mediaIsPip.get(e)&&i.mediaIsPip.set(!1,e),i[s].set(!0,e,t)},[z.MEDIA_EXIT_FULLSCREEN_REQUEST](i,e){i["mediaIsFullscreen"].set(!1,e)},[z.MEDIA_ENTER_CAST_REQUEST](i,e){const t="mediaIsCasting";i.mediaIsFullscreen.get(e)&&i.mediaIsFullscreen.set(!1,e),i[t].set(!0,e)},[z.MEDIA_EXIT_CAST_REQUEST](i,e){i["mediaIsCasting"].set(!1,e)},[z.MEDIA_AIRPLAY_REQUEST](i,e){i["mediaIsAirplaying"].set(!0,e)}},WA=({media:i,fullscreenElement:e,documentElement:t,stateMediator:s=Ta,requestMap:r=VA,options:n={},monitorStateOwnersOnlyWithSubscriptions:a=!0})=>{const o=[],l={options:{...n}};let d=Object.freeze({mediaPreviewTime:void 0,mediaPreviewImage:void 0,mediaPreviewCoords:void 0,mediaPreviewChapter:void 0});const u=p=>{p!=null&&(lm(p,d)||(d=Object.freeze({...d,...p}),o.forEach(g=>g(d))))},c=()=>{const p=Object.entries(s).reduce((g,[v,{get:b}])=>(g[v]=b(l),g),{});u(p)},h={};let f;const m=async(p,g)=>{var v,b,E,T,A,x,S,L,R,I,M,B,W,j,K,F;const Y=!!f;if(f={...l,...f??{},...p},Y)return;await HA(...Object.values(p));const P=o.length>0&&g===0&&a,G=l.media!==f.media,Z=((v=l.media)==null?void 0:v.textTracks)!==((b=f.media)==null?void 0:b.textTracks),$=((E=l.media)==null?void 0:E.videoRenditions)!==((T=f.media)==null?void 0:T.videoRenditions),H=((A=l.media)==null?void 0:A.audioTracks)!==((x=f.media)==null?void 0:x.audioTracks),se=((S=l.media)==null?void 0:S.remote)!==((L=f.media)==null?void 0:L.remote),ge=l.documentElement!==f.documentElement,ce=!!l.media&&(G||P),me=!!((R=l.media)!=null&&R.textTracks)&&(Z||P),ut=!!((I=l.media)!=null&&I.videoRenditions)&&($||P),tt=!!((M=l.media)!=null&&M.audioTracks)&&(H||P),Dt=!!((B=l.media)!=null&&B.remote)&&(se||P),Ft=!!l.documentElement&&(ge||P),ci=ce||me||ut||tt||Dt||Ft,Ss=o.length===0&&g===1&&a,$r=!!f.media&&(G||Ss),Fr=!!((W=f.media)!=null&&W.textTracks)&&(Z||Ss),nc=!!((j=f.media)!=null&&j.videoRenditions)&&($||Ss),Te=!!((K=f.media)!=null&&K.audioTracks)&&(H||Ss),ct=!!((F=f.media)!=null&&F.remote)&&(se||Ss),Ct=!!f.documentElement&&(ge||Ss),xi=$r||Fr||nc||Te||ct||Ct;if(!(ci||xi)){Object.entries(f).forEach(([_e,Bt])=>{l[_e]=Bt}),c(),f=void 0;return}Object.entries(s).forEach(([_e,{get:Bt,mediaEvents:Ro=[],textTracksEvents:Br=[],videoRenditionsEvents:ko=[],audioTracksEvents:Js=[],remoteEvents:Do=[],rootEvents:ac=[],stateOwnersUpdateHandlers:Co=[]}])=>{h[_e]||(h[_e]={});const Lt=We=>{const it=Bt(l,We);u({[_e]:it})};let Ve;Ve=h[_e].mediaEvents,Ro.forEach(We=>{Ve&&ce&&(l.media.removeEventListener(We,Ve),h[_e].mediaEvents=void 0),$r&&(f.media.addEventListener(We,Lt),h[_e].mediaEvents=Lt)}),Ve=h[_e].textTracksEvents,Br.forEach(We=>{var it,hi;Ve&&me&&((it=l.media.textTracks)==null||it.removeEventListener(We,Ve),h[_e].textTracksEvents=void 0),Fr&&((hi=f.media.textTracks)==null||hi.addEventListener(We,Lt),h[_e].textTracksEvents=Lt)}),Ve=h[_e].videoRenditionsEvents,ko.forEach(We=>{var it,hi;Ve&&ut&&((it=l.media.videoRenditions)==null||it.removeEventListener(We,Ve),h[_e].videoRenditionsEvents=void 0),nc&&((hi=f.media.videoRenditions)==null||hi.addEventListener(We,Lt),h[_e].videoRenditionsEvents=Lt)}),Ve=h[_e].audioTracksEvents,Js.forEach(We=>{var it,hi;Ve&&tt&&((it=l.media.audioTracks)==null||it.removeEventListener(We,Ve),h[_e].audioTracksEvents=void 0),Te&&((hi=f.media.audioTracks)==null||hi.addEventListener(We,Lt),h[_e].audioTracksEvents=Lt)}),Ve=h[_e].remoteEvents,Do.forEach(We=>{var it,hi;Ve&&Dt&&((it=l.media.remote)==null||it.removeEventListener(We,Ve),h[_e].remoteEvents=void 0),ct&&((hi=f.media.remote)==null||hi.addEventListener(We,Lt),h[_e].remoteEvents=Lt)}),Ve=h[_e].rootEvents,ac.forEach(We=>{Ve&&Ft&&(l.documentElement.removeEventListener(We,Ve),h[_e].rootEvents=void 0),Ct&&(f.documentElement.addEventListener(We,Lt),h[_e].rootEvents=Lt)});const wo=h[_e].stateOwnersUpdateHandlers;if(wo&&ci&&(Array.isArray(wo)?wo:[wo]).forEach(it=>{typeof it=="function"&&it()}),xi){const We=Co.map(it=>it(Lt,f)).filter(it=>typeof it=="function");h[_e].stateOwnersUpdateHandlers=We.length===1?We[0]:We}else ci&&(h[_e].stateOwnersUpdateHandlers=void 0)}),Object.entries(f).forEach(([_e,Bt])=>{l[_e]=Bt}),c(),f=void 0};return m({media:i,fullscreenElement:e,documentElement:t,options:n}),{dispatch(p){const{type:g,detail:v}=p;if(r[g]&&d.mediaErrorCode==null){u(r[g](s,l,p));return}g==="mediaelementchangerequest"?m({media:v}):g==="fullscreenelementchangerequest"?m({fullscreenElement:v}):g==="documentelementchangerequest"?m({documentElement:v}):g==="optionschangerequest"&&(Object.entries(v??{}).forEach(([b,E])=>{l.options[b]=E}),c())},getState(){return d},subscribe(p){return m({},o.length+1),o.push(p),p(d),()=>{const g=o.indexOf(p);g>=0&&(m({},o.length-1),o.splice(g,1))}}}};var dm=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},oe=(i,e,t)=>(dm(i,e,"read from private field"),t?t.call(i):e.get(i)),ti=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Mi=(i,e,t,s)=>(dm(i,e,"write to private field"),e.set(i,t),t),qi=(i,e,t)=>(dm(i,e,"access private method"),t),Gs,_a,Ae,yr,Aa,Pi,vl,Sa,El,dh,Sr,On,yl,uh,ch,vE;const EE=["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Enter"," ","f","m","k","c","l","j",">","<","p"],qp=10,Yp=.025,jp=.25,qA=.25,YA=2,V={DEFAULT_SUBTITLES:"defaultsubtitles",DEFAULT_STREAM_TYPE:"defaultstreamtype",DEFAULT_DURATION:"defaultduration",FULLSCREEN_ELEMENT:"fullscreenelement",HOTKEYS:"hotkeys",KEYBOARD_BACKWARD_SEEK_OFFSET:"keyboardbackwardseekoffset",KEYBOARD_FORWARD_SEEK_OFFSET:"keyboardforwardseekoffset",KEYBOARD_DOWN_VOLUME_STEP:"keyboarddownvolumestep",KEYBOARD_UP_VOLUME_STEP:"keyboardupvolumestep",KEYS_USED:"keysused",LANG:"lang",LOOP:"loop",LIVE_EDGE_OFFSET:"liveedgeoffset",NO_AUTO_SEEK_TO_LIVE:"noautoseektolive",NO_DEFAULT_STORE:"nodefaultstore",NO_HOTKEYS:"nohotkeys",NO_MUTED_PREF:"nomutedpref",NO_SUBTITLES_LANG_PREF:"nosubtitleslangpref",NO_VOLUME_PREF:"novolumepref",SEEK_TO_LIVE_OFFSET:"seektoliveoffset"};let yE=class extends xo{constructor(){super(),ti(this,El),ti(this,Sr),ti(this,yl),ti(this,ch),this.mediaStateReceivers=[],this.associatedElementSubscriptions=new Map,ti(this,Gs,new am(this,V.HOTKEYS)),ti(this,_a,void 0),ti(this,Ae,void 0),ti(this,yr,null),ti(this,Aa,void 0),ti(this,Pi,void 0),ti(this,vl,t=>{var s;(s=oe(this,Ae))==null||s.dispatch(t)}),ti(this,Sa,void 0),this.associateElement(this);let e={};Mi(this,Aa,t=>{Object.entries(t).forEach(([s,r])=>{if(s in e&&e[s]===r)return;this.propagateMediaState(s,r);const n=s.toLowerCase(),a=new k.CustomEvent(Y_[n],{composed:!0,detail:r});this.dispatchEvent(a)}),e=t}),this.hasAttribute(V.NO_HOTKEYS)?this.disableHotkeys():this.enableHotkeys()}static get observedAttributes(){return super.observedAttributes.concat(V.NO_HOTKEYS,V.HOTKEYS,V.DEFAULT_STREAM_TYPE,V.DEFAULT_SUBTITLES,V.DEFAULT_DURATION,V.NO_MUTED_PREF,V.NO_VOLUME_PREF,V.LANG,V.LOOP)}get mediaStore(){return oe(this,Ae)}set mediaStore(e){var t,s;if(oe(this,Ae)&&((t=oe(this,Pi))==null||t.call(this),Mi(this,Pi,void 0)),Mi(this,Ae,e),!oe(this,Ae)&&!this.hasAttribute(V.NO_DEFAULT_STORE)){qi(this,El,dh).call(this);return}Mi(this,Pi,(s=oe(this,Ae))==null?void 0:s.subscribe(oe(this,Aa)))}get fullscreenElement(){var e;return(e=oe(this,_a))!=null?e:this}set fullscreenElement(e){var t;this.hasAttribute(V.FULLSCREEN_ELEMENT)&&this.removeAttribute(V.FULLSCREEN_ELEMENT),Mi(this,_a,e),(t=oe(this,Ae))==null||t.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement})}get defaultSubtitles(){return ye(this,V.DEFAULT_SUBTITLES)}set defaultSubtitles(e){be(this,V.DEFAULT_SUBTITLES,e)}get defaultStreamType(){return He(this,V.DEFAULT_STREAM_TYPE)}set defaultStreamType(e){Ge(this,V.DEFAULT_STREAM_TYPE,e)}get defaultDuration(){return Be(this,V.DEFAULT_DURATION)}set defaultDuration(e){Xe(this,V.DEFAULT_DURATION,e)}get noHotkeys(){return ye(this,V.NO_HOTKEYS)}set noHotkeys(e){be(this,V.NO_HOTKEYS,e)}get keysUsed(){return He(this,V.KEYS_USED)}set keysUsed(e){Ge(this,V.KEYS_USED,e)}get liveEdgeOffset(){return Be(this,V.LIVE_EDGE_OFFSET)}set liveEdgeOffset(e){Xe(this,V.LIVE_EDGE_OFFSET,e)}get noAutoSeekToLive(){return ye(this,V.NO_AUTO_SEEK_TO_LIVE)}set noAutoSeekToLive(e){be(this,V.NO_AUTO_SEEK_TO_LIVE,e)}get noVolumePref(){return ye(this,V.NO_VOLUME_PREF)}set noVolumePref(e){be(this,V.NO_VOLUME_PREF,e)}get noMutedPref(){return ye(this,V.NO_MUTED_PREF)}set noMutedPref(e){be(this,V.NO_MUTED_PREF,e)}get noSubtitlesLangPref(){return ye(this,V.NO_SUBTITLES_LANG_PREF)}set noSubtitlesLangPref(e){be(this,V.NO_SUBTITLES_LANG_PREF,e)}get noDefaultStore(){return ye(this,V.NO_DEFAULT_STORE)}set noDefaultStore(e){be(this,V.NO_DEFAULT_STORE,e)}attributeChangedCallback(e,t,s){var r,n,a,o,l,d,u,c,h,f,m,p;if(super.attributeChangedCallback(e,t,s),e===V.NO_HOTKEYS)s!==t&&s===""?(this.hasAttribute(V.HOTKEYS)&&console.warn("Media Chrome: Both `hotkeys` and `nohotkeys` have been set. All hotkeys will be disabled."),this.disableHotkeys()):s!==t&&s===null&&this.enableHotkeys();else if(e===V.HOTKEYS)oe(this,Gs).value=s;else if(e===V.DEFAULT_SUBTITLES&&s!==t)(r=oe(this,Ae))==null||r.dispatch({type:"optionschangerequest",detail:{defaultSubtitles:this.hasAttribute(V.DEFAULT_SUBTITLES)}});else if(e===V.DEFAULT_STREAM_TYPE)(a=oe(this,Ae))==null||a.dispatch({type:"optionschangerequest",detail:{defaultStreamType:(n=this.getAttribute(V.DEFAULT_STREAM_TYPE))!=null?n:void 0}});else if(e===V.LIVE_EDGE_OFFSET)(o=oe(this,Ae))==null||o.dispatch({type:"optionschangerequest",detail:{liveEdgeOffset:this.hasAttribute(V.LIVE_EDGE_OFFSET)?+this.getAttribute(V.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(V.SEEK_TO_LIVE_OFFSET)?void 0:+this.getAttribute(V.LIVE_EDGE_OFFSET)}});else if(e===V.SEEK_TO_LIVE_OFFSET)(l=oe(this,Ae))==null||l.dispatch({type:"optionschangerequest",detail:{seekToLiveOffset:this.hasAttribute(V.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(V.SEEK_TO_LIVE_OFFSET):void 0}});else if(e===V.NO_AUTO_SEEK_TO_LIVE)(d=oe(this,Ae))==null||d.dispatch({type:"optionschangerequest",detail:{noAutoSeekToLive:this.hasAttribute(V.NO_AUTO_SEEK_TO_LIVE)}});else if(e===V.FULLSCREEN_ELEMENT){const g=s?(u=this.getRootNode())==null?void 0:u.getElementById(s):void 0;Mi(this,_a,g),(c=oe(this,Ae))==null||c.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement})}else e===V.LANG&&s!==t?(aA(s),(h=oe(this,Ae))==null||h.dispatch({type:"optionschangerequest",detail:{mediaLang:s}})):e===V.LOOP&&s!==t?(f=oe(this,Ae))==null||f.dispatch({type:z.MEDIA_LOOP_REQUEST,detail:s!=null}):e===V.NO_VOLUME_PREF&&s!==t?(m=oe(this,Ae))==null||m.dispatch({type:"optionschangerequest",detail:{noVolumePref:this.hasAttribute(V.NO_VOLUME_PREF)}}):e===V.NO_MUTED_PREF&&s!==t&&((p=oe(this,Ae))==null||p.dispatch({type:"optionschangerequest",detail:{noMutedPref:this.hasAttribute(V.NO_MUTED_PREF)}}))}connectedCallback(){var e,t;!oe(this,Ae)&&!this.hasAttribute(V.NO_DEFAULT_STORE)&&qi(this,El,dh).call(this),(e=oe(this,Ae))==null||e.dispatch({type:"documentelementchangerequest",detail:lt}),super.connectedCallback(),oe(this,Ae)&&!oe(this,Pi)&&Mi(this,Pi,(t=oe(this,Ae))==null?void 0:t.subscribe(oe(this,Aa))),oe(this,Sa)!==void 0&&oe(this,Ae)&&this.media&&setTimeout(()=>{var s,r,n;(r=(s=this.media)==null?void 0:s.textTracks)!=null&&r.length&&((n=oe(this,Ae))==null||n.dispatch({type:z.MEDIA_TOGGLE_SUBTITLES_REQUEST,detail:oe(this,Sa)}))},0),this.hasAttribute(V.NO_HOTKEYS)?this.disableHotkeys():this.enableHotkeys()}disconnectedCallback(){var e,t,s,r,n;if((e=super.disconnectedCallback)==null||e.call(this),oe(this,Ae)){const a=oe(this,Ae).getState();Mi(this,Sa,!!((t=a.mediaSubtitlesShowing)!=null&&t.length)),(s=oe(this,Ae))==null||s.dispatch({type:"documentelementchangerequest",detail:void 0}),(r=oe(this,Ae))==null||r.dispatch({type:z.MEDIA_TOGGLE_SUBTITLES_REQUEST,detail:!1})}oe(this,Pi)&&((n=oe(this,Pi))==null||n.call(this),Mi(this,Pi,void 0))}mediaSetCallback(e){var t;super.mediaSetCallback(e),(t=oe(this,Ae))==null||t.dispatch({type:"mediaelementchangerequest",detail:e}),e.hasAttribute("tabindex")||(e.tabIndex=-1)}mediaUnsetCallback(e){var t;super.mediaUnsetCallback(e),(t=oe(this,Ae))==null||t.dispatch({type:"mediaelementchangerequest",detail:void 0})}propagateMediaState(e,t){Xp(this.mediaStateReceivers,e,t)}associateElement(e){if(!e)return;const{associatedElementSubscriptions:t}=this;if(t.has(e))return;const s=this.registerMediaStateReceiver.bind(this),r=this.unregisterMediaStateReceiver.bind(this),n=JA(e,s,r);Object.values(z).forEach(a=>{e.addEventListener(a,oe(this,vl))}),t.set(e,n)}unassociateElement(e){if(!e)return;const{associatedElementSubscriptions:t}=this;if(!t.has(e))return;t.get(e)(),t.delete(e),Object.values(z).forEach(r=>{e.removeEventListener(r,oe(this,vl))})}registerMediaStateReceiver(e){if(!e)return;const t=this.mediaStateReceivers;t.indexOf(e)>-1||(t.push(e),oe(this,Ae)&&Object.entries(oe(this,Ae).getState()).forEach(([r,n])=>{Xp([e],r,n)}))}unregisterMediaStateReceiver(e){const t=this.mediaStateReceivers,s=t.indexOf(e);s<0||t.splice(s,1)}enableHotkeys(){this.addEventListener("keydown",qi(this,yl,uh))}disableHotkeys(){this.removeEventListener("keydown",qi(this,yl,uh)),this.removeEventListener("keyup",qi(this,Sr,On))}get hotkeys(){return He(this,V.HOTKEYS)}set hotkeys(e){Ge(this,V.HOTKEYS,e)}keyboardShortcutHandler(e){var t,s,r,n,a,o,l,d,u;const c=e.target;if(((r=(s=(t=c.getAttribute(V.KEYS_USED))==null?void 0:t.split(" "))!=null?s:c?.keysUsed)!=null?r:[]).map(v=>v==="Space"?" ":v).filter(Boolean).includes(e.key))return;let f,m,p;if(!(oe(this,Gs).contains(`no${e.key.toLowerCase()}`)||e.key===" "&&oe(this,Gs).contains("nospace")||e.shiftKey&&(e.key==="/"||e.key==="?")&&oe(this,Gs).contains("noshift+/")))switch(e.key){case" ":case"k":f=oe(this,Ae).getState().mediaPaused?z.MEDIA_PLAY_REQUEST:z.MEDIA_PAUSE_REQUEST,this.dispatchEvent(new k.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"m":f=this.mediaStore.getState().mediaVolumeLevel==="off"?z.MEDIA_UNMUTE_REQUEST:z.MEDIA_MUTE_REQUEST,this.dispatchEvent(new k.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"f":f=this.mediaStore.getState().mediaIsFullscreen?z.MEDIA_EXIT_FULLSCREEN_REQUEST:z.MEDIA_ENTER_FULLSCREEN_REQUEST,this.dispatchEvent(new k.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"c":this.dispatchEvent(new k.CustomEvent(z.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:!0,bubbles:!0}));break;case"ArrowLeft":case"j":{const v=this.hasAttribute(V.KEYBOARD_BACKWARD_SEEK_OFFSET)?+this.getAttribute(V.KEYBOARD_BACKWARD_SEEK_OFFSET):qp;m=Math.max(((n=this.mediaStore.getState().mediaCurrentTime)!=null?n:0)-v,0),p=new k.CustomEvent(z.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowRight":case"l":{const v=this.hasAttribute(V.KEYBOARD_FORWARD_SEEK_OFFSET)?+this.getAttribute(V.KEYBOARD_FORWARD_SEEK_OFFSET):qp;m=Math.max(((a=this.mediaStore.getState().mediaCurrentTime)!=null?a:0)+v,0),p=new k.CustomEvent(z.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowUp":{const v=this.hasAttribute(V.KEYBOARD_UP_VOLUME_STEP)?+this.getAttribute(V.KEYBOARD_UP_VOLUME_STEP):Yp;m=Math.min(((o=this.mediaStore.getState().mediaVolume)!=null?o:1)+v,1),p=new k.CustomEvent(z.MEDIA_VOLUME_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowDown":{const v=this.hasAttribute(V.KEYBOARD_DOWN_VOLUME_STEP)?+this.getAttribute(V.KEYBOARD_DOWN_VOLUME_STEP):Yp;m=Math.max(((l=this.mediaStore.getState().mediaVolume)!=null?l:1)-v,0),p=new k.CustomEvent(z.MEDIA_VOLUME_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"<":{const v=(d=this.mediaStore.getState().mediaPlaybackRate)!=null?d:1;m=Math.max(v-jp,qA).toFixed(2),p=new k.CustomEvent(z.MEDIA_PLAYBACK_RATE_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case">":{const v=(u=this.mediaStore.getState().mediaPlaybackRate)!=null?u:1;m=Math.min(v+jp,YA).toFixed(2),p=new k.CustomEvent(z.MEDIA_PLAYBACK_RATE_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"/":case"?":{e.shiftKey&&qi(this,ch,vE).call(this);break}case"p":{f=this.mediaStore.getState().mediaIsPip?z.MEDIA_EXIT_PIP_REQUEST:z.MEDIA_ENTER_PIP_REQUEST,p=new k.CustomEvent(f,{composed:!0,bubbles:!0}),this.dispatchEvent(p);break}}}};Gs=new WeakMap;_a=new WeakMap;Ae=new WeakMap;yr=new WeakMap;Aa=new WeakMap;Pi=new WeakMap;vl=new WeakMap;Sa=new WeakMap;El=new WeakSet;dh=function(){var i;this.mediaStore=WA({media:this.media,fullscreenElement:this.fullscreenElement,options:{defaultSubtitles:this.hasAttribute(V.DEFAULT_SUBTITLES),defaultDuration:this.hasAttribute(V.DEFAULT_DURATION)?+this.getAttribute(V.DEFAULT_DURATION):void 0,defaultStreamType:(i=this.getAttribute(V.DEFAULT_STREAM_TYPE))!=null?i:void 0,liveEdgeOffset:this.hasAttribute(V.LIVE_EDGE_OFFSET)?+this.getAttribute(V.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(V.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(V.SEEK_TO_LIVE_OFFSET):this.hasAttribute(V.LIVE_EDGE_OFFSET)?+this.getAttribute(V.LIVE_EDGE_OFFSET):void 0,noAutoSeekToLive:this.hasAttribute(V.NO_AUTO_SEEK_TO_LIVE),noVolumePref:this.hasAttribute(V.NO_VOLUME_PREF),noMutedPref:this.hasAttribute(V.NO_MUTED_PREF),noSubtitlesLangPref:this.hasAttribute(V.NO_SUBTITLES_LANG_PREF)}})};Sr=new WeakSet;On=function(i){const{key:e,shiftKey:t}=i;if(!(t&&(e==="/"||e==="?")||EE.includes(e))){this.removeEventListener("keyup",qi(this,Sr,On));return}this.keyboardShortcutHandler(i)};yl=new WeakSet;uh=function(i){var e;const{metaKey:t,altKey:s,key:r,shiftKey:n}=i,a=n&&(r==="/"||r==="?");if(a&&((e=oe(this,yr))!=null&&e.open)){this.removeEventListener("keyup",qi(this,Sr,On));return}if(t||s||!a&&!EE.includes(r)){this.removeEventListener("keyup",qi(this,Sr,On));return}const o=i.target,l=o instanceof HTMLElement&&(o.tagName.toLowerCase()==="media-volume-range"||o.tagName.toLowerCase()==="media-time-range");[" ","ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(r)&&!(oe(this,Gs).contains(`no${r.toLowerCase()}`)||r===" "&&oe(this,Gs).contains("nospace"))&&!l&&i.preventDefault(),this.addEventListener("keyup",qi(this,Sr,On),{once:!0})};ch=new WeakSet;vE=function(){oe(this,yr)||(Mi(this,yr,lt.createElement("media-keyboard-shortcuts-dialog")),this.appendChild(oe(this,yr))),oe(this,yr).open=!0};const jA=Object.values(_),zA=Object.values(Vv),bE=i=>{var e,t,s,r;let{observedAttributes:n}=i.constructor;!n&&((e=i.nodeName)!=null&&e.includes("-"))&&(k.customElements.upgrade(i),{observedAttributes:n}=i.constructor);const a=(r=(s=(t=i?.getAttribute)==null?void 0:t.call(i,xe.MEDIA_CHROME_ATTRIBUTES))==null?void 0:s.split)==null?void 0:r.call(s,/\s+/);return Array.isArray(n||a)?(n||a).filter(o=>jA.includes(o)):[]},QA=i=>{var e,t;return(e=i.nodeName)!=null&&e.includes("-")&&k.customElements.get((t=i.nodeName)==null?void 0:t.toLowerCase())&&!(i instanceof k.customElements.get(i.nodeName.toLowerCase()))&&k.customElements.upgrade(i),zA.some(s=>s in i)},hh=i=>QA(i)||!!bE(i).length,zp=i=>{var e;return(e=i?.join)==null?void 0:e.call(i,":")},Qp={[_.MEDIA_SUBTITLES_LIST]:ao,[_.MEDIA_SUBTITLES_SHOWING]:ao,[_.MEDIA_SEEKABLE]:zp,[_.MEDIA_BUFFERED]:i=>i?.map(zp).join(" "),[_.MEDIA_PREVIEW_COORDS]:i=>i?.join(" "),[_.MEDIA_RENDITION_LIST]:z_,[_.MEDIA_AUDIO_TRACK_LIST]:J_},XA=async(i,e,t)=>{var s,r;if(i.isConnected||await Yv(0),typeof t=="boolean"||t==null)return be(i,e,t);if(typeof t=="number")return Xe(i,e,t);if(typeof t=="string")return Ge(i,e,t);if(Array.isArray(t)&&!t.length)return i.removeAttribute(e);const n=(r=(s=Qp[e])==null?void 0:s.call(Qp,t))!=null?r:t;return i.setAttribute(e,n)},ZA=i=>{var e;return!!((e=i.closest)!=null&&e.call(i,'*[slot="media"]'))},or=(i,e)=>{if(ZA(i))return;const t=(r,n)=>{var a,o;hh(r)&&n(r);const{children:l=[]}=r??{},d=(o=(a=r?.shadowRoot)==null?void 0:a.children)!=null?o:[];[...l,...d].forEach(c=>or(c,n))},s=i?.nodeName.toLowerCase();if(s.includes("-")&&!hh(i)){k.customElements.whenDefined(s).then(()=>{t(i,e)});return}t(i,e)},Xp=(i,e,t)=>{i.forEach(s=>{if(e in s){s[e]=t;return}const r=bE(s),n=e.toLowerCase();r.includes(n)&&XA(s,n,t)})},JA=(i,e,t)=>{or(i,e);const s=u=>{var c;const h=(c=u?.composedPath()[0])!=null?c:u.target;e(h)},r=u=>{var c;const h=(c=u?.composedPath()[0])!=null?c:u.target;t(h)};i.addEventListener(z.REGISTER_MEDIA_STATE_RECEIVER,s),i.addEventListener(z.UNREGISTER_MEDIA_STATE_RECEIVER,r);const n=u=>{u.forEach(c=>{const{addedNodes:h=[],removedNodes:f=[],type:m,target:p,attributeName:g}=c;m==="childList"?(Array.prototype.forEach.call(h,v=>or(v,e)),Array.prototype.forEach.call(f,v=>or(v,t))):m==="attributes"&&g===xe.MEDIA_CHROME_ATTRIBUTES&&(hh(p)?e(p):t(p))})};let a=[];const o=u=>{const c=u.target;c.name!=="media"&&(a.forEach(h=>or(h,t)),a=[...c.assignedElements({flatten:!0})],a.forEach(h=>or(h,e)))};i.addEventListener("slotchange",o);const l=new MutationObserver(n);return l.observe(i,{childList:!0,attributes:!0,subtree:!0}),()=>{or(i,t),i.removeEventListener("slotchange",o),l.disconnect(),i.removeEventListener(z.REGISTER_MEDIA_STATE_RECEIVER,s),i.removeEventListener(z.UNREGISTER_MEDIA_STATE_RECEIVER,r)}};k.customElements.get("media-controller")||k.customElements.define("media-controller",yE);var TE=yE;const Hr={PLACEMENT:"placement",BOUNDS:"bounds"};function eS(i){return`
|
|
159
|
+
`}const gA=Object.values(_),vA="sm:384 md:576 lg:768 xl:960";function EA(i){oE(i.target,i.contentRect.width)}function oE(i,e){var t;if(!i.isConnected)return;const s=(t=i.getAttribute(ne.BREAKPOINTS))!=null?t:vA,r=yA(s),n=bA(r,e);let a=!1;if(Object.keys(r).forEach(o=>{if(n.includes(o)){i.hasAttribute(`breakpoint${o}`)||(i.setAttribute(`breakpoint${o}`,""),a=!0);return}i.hasAttribute(`breakpoint${o}`)&&(i.removeAttribute(`breakpoint${o}`),a=!0)}),a){const o=new CustomEvent(ys.BREAKPOINTS_CHANGE,{detail:n});i.dispatchEvent(o)}i.breakpointsComputed||(i.breakpointsComputed=!0,i.dispatchEvent(new CustomEvent(ys.BREAKPOINTS_COMPUTED,{bubbles:!0,composed:!0})))}function yA(i){const e=i.split(/\s+/);return Object.fromEntries(e.map(t=>t.split(":")))}function bA(i,e){return Object.keys(i).filter(t=>e>=parseInt(i[t]))}class xo extends k.HTMLElement{constructor(){if(super(),Gt(this,nh),Gt(this,ah),Gt(this,oh),Gt(this,ro),Gt(this,Au),Gt(this,zn),Gt(this,Cd,0),Gt(this,en,null),Gt(this,so,null),Gt(this,Rn,void 0),this.breakpointsComputed=!1,Gt(this,pl,new MutationObserver(oi(this,nh,rE).bind(this))),Gt(this,ya,!1),Gt(this,gl,t=>{Yt(this,ya)||(setTimeout(()=>{EA(t),ar(this,ya,!1)},0),ar(this,ya,!0))}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);const t=Zt(this.attributes),s=this.constructor.getTemplateHTML(t);this.shadowRoot.setHTMLUnsafe?this.shadowRoot.setHTMLUnsafe(s):this.shadowRoot.innerHTML=s}const e=this.querySelector(":scope > slot[slot=media]");e&&e.addEventListener("slotchange",()=>{if(!e.assignedElements({flatten:!0}).length){Yt(this,en)&&this.mediaUnsetCallback(Yt(this,en));return}this.handleMediaUpdated(this.media)})}static get observedAttributes(){return[ne.AUTOHIDE,ne.GESTURES_DISABLED].concat(gA).filter(e=>![_.MEDIA_RENDITION_LIST,_.MEDIA_AUDIO_TRACK_LIST,_.MEDIA_CHAPTERS_CUES,_.MEDIA_WIDTH,_.MEDIA_HEIGHT,_.MEDIA_ERROR,_.MEDIA_ERROR_MESSAGE].includes(e))}attributeChangedCallback(e,t,s){e.toLowerCase()==ne.AUTOHIDE&&(this.autohide=s)}get media(){let e=this.querySelector(":scope > [slot=media]");return e?.nodeName=="SLOT"&&(e=e.assignedElements({flatten:!0})[0]),e}async handleMediaUpdated(e){e&&(ar(this,en,e),e.localName.includes("-")&&await k.customElements.whenDefined(e.localName),this.mediaSetCallback(e))}connectedCallback(){var e;Yt(this,pl).observe(this,{childList:!0,subtree:!0}),Yn(this,Yt(this,gl));const t=this.getAttribute(ne.AUDIO)!=null,s=te(t?"audio player":"video player");this.setAttribute("role","region"),this.setAttribute("aria-label",s),this.handleMediaUpdated(this.media),this.setAttribute(ne.USER_INACTIVE,""),oE(this,this.getBoundingClientRect().width),this.addEventListener("pointerdown",this),this.addEventListener("pointermove",this),this.addEventListener("pointerup",this),this.addEventListener("mouseleave",this),this.addEventListener("keyup",this),(e=k.window)==null||e.addEventListener("mouseup",this)}disconnectedCallback(){var e;Yt(this,pl).disconnect(),jn(this,Yt(this,gl)),this.media&&this.mediaUnsetCallback(this.media),(e=k.window)==null||e.removeEventListener("mouseup",this)}mediaSetCallback(e){}mediaUnsetCallback(e){ar(this,en,null)}handleEvent(e){switch(e.type){case"pointerdown":ar(this,Cd,e.timeStamp);break;case"pointermove":oi(this,ah,nE).call(this,e);break;case"pointerup":oi(this,oh,aE).call(this,e);break;case"mouseleave":oi(this,ro,_u).call(this);break;case"mouseup":this.removeAttribute(ne.KEYBOARD_CONTROL);break;case"keyup":oi(this,zn,no).call(this),this.setAttribute(ne.KEYBOARD_CONTROL,"");break}}set autohide(e){const t=Number(e);ar(this,Rn,isNaN(t)?0:t)}get autohide(){return(Yt(this,Rn)===void 0?2:Yt(this,Rn)).toString()}get breakpoints(){return He(this,ne.BREAKPOINTS)}set breakpoints(e){Ge(this,ne.BREAKPOINTS,e)}get audio(){return ye(this,ne.AUDIO)}set audio(e){be(this,ne.AUDIO,e)}get gesturesDisabled(){return ye(this,ne.GESTURES_DISABLED)}set gesturesDisabled(e){be(this,ne.GESTURES_DISABLED,e)}get keyboardControl(){return ye(this,ne.KEYBOARD_CONTROL)}set keyboardControl(e){be(this,ne.KEYBOARD_CONTROL,e)}get noAutohide(){return ye(this,ne.NO_AUTOHIDE)}set noAutohide(e){be(this,ne.NO_AUTOHIDE,e)}get autohideOverControls(){return ye(this,ne.AUTOHIDE_OVER_CONTROLS)}set autohideOverControls(e){be(this,ne.AUTOHIDE_OVER_CONTROLS,e)}get userInteractive(){return ye(this,ne.USER_INACTIVE)}set userInteractive(e){be(this,ne.USER_INACTIVE,e)}}Cd=new WeakMap;en=new WeakMap;so=new WeakMap;Rn=new WeakMap;pl=new WeakMap;nh=new WeakSet;rE=function(i){const e=this.media;for(const t of i){if(t.type!=="childList")continue;const s=t.removedNodes;for(const r of s){if(r.slot!="media"||t.target!=this)continue;let n=t.previousSibling&&t.previousSibling.previousElementSibling;if(!n||!e)this.mediaUnsetCallback(r);else{let a=n.slot!=="media";for(;(n=n.previousSibling)!==null;)n.slot=="media"&&(a=!1);a&&this.mediaUnsetCallback(r)}}if(e)for(const r of t.addedNodes)r===e&&this.handleMediaUpdated(e)}};ya=new WeakMap;gl=new WeakMap;ah=new WeakSet;nE=function(i){if(i.pointerType!=="mouse"&&i.timeStamp-Yt(this,Cd)<250)return;oi(this,Au,nm).call(this),clearTimeout(Yt(this,so));const e=this.hasAttribute(ne.AUTOHIDE_OVER_CONTROLS);([this,this.media].includes(i.target)||e)&&oi(this,zn,no).call(this)};oh=new WeakSet;aE=function(i){if(i.pointerType==="touch"){const e=!this.hasAttribute(ne.USER_INACTIVE);[this,this.media].includes(i.target)&&e?oi(this,ro,_u).call(this):oi(this,zn,no).call(this)}else i.composedPath().some(e=>["media-play-button","media-fullscreen-button"].includes(e?.localName))&&oi(this,zn,no).call(this)};ro=new WeakSet;_u=function(){if(Yt(this,Rn)<0||this.hasAttribute(ne.USER_INACTIVE))return;this.setAttribute(ne.USER_INACTIVE,"");const i=new k.CustomEvent(ys.USER_INACTIVE_CHANGE,{composed:!0,bubbles:!0,detail:!0});this.dispatchEvent(i)};Au=new WeakSet;nm=function(){if(!this.hasAttribute(ne.USER_INACTIVE))return;this.removeAttribute(ne.USER_INACTIVE);const i=new k.CustomEvent(ys.USER_INACTIVE_CHANGE,{composed:!0,bubbles:!0,detail:!1});this.dispatchEvent(i)};zn=new WeakSet;no=function(){oi(this,Au,nm).call(this),clearTimeout(Yt(this,so));const i=parseInt(this.autohide);i<0||ar(this,so,setTimeout(()=>{oi(this,ro,_u).call(this)},i*1e3))};xo.shadowRootOptions={mode:"open"};xo.getTemplateHTML=pA;k.customElements.get("media-container")||k.customElements.define("media-container",xo);var TA=xo,lE=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},bt=(i,e,t)=>(lE(i,e,"read from private field"),t?t.call(i):e.get(i)),na=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Po=(i,e,t,s)=>(lE(i,e,"write to private field"),e.set(i,t),t),tn,sn,wd,Er,us,Cs;class am{constructor(e,t,{defaultValue:s}={defaultValue:void 0}){na(this,us),na(this,tn,void 0),na(this,sn,void 0),na(this,wd,void 0),na(this,Er,new Set),Po(this,tn,e),Po(this,sn,t),Po(this,wd,new Set(s))}[Symbol.iterator](){return bt(this,us,Cs).values()}get length(){return bt(this,us,Cs).size}get value(){var e;return(e=[...bt(this,us,Cs)].join(" "))!=null?e:""}set value(e){var t;e!==this.value&&(Po(this,Er,new Set),this.add(...(t=e?.split(" "))!=null?t:[]))}toString(){return this.value}item(e){return[...bt(this,us,Cs)][e]}values(){return bt(this,us,Cs).values()}forEach(e,t){bt(this,us,Cs).forEach(e,t)}add(...e){var t,s;e.forEach(r=>bt(this,Er).add(r)),!(this.value===""&&!((t=bt(this,tn))!=null&&t.hasAttribute(`${bt(this,sn)}`)))&&((s=bt(this,tn))==null||s.setAttribute(`${bt(this,sn)}`,`${this.value}`))}remove(...e){var t;e.forEach(s=>bt(this,Er).delete(s)),(t=bt(this,tn))==null||t.setAttribute(`${bt(this,sn)}`,`${this.value}`)}contains(e){return bt(this,us,Cs).has(e)}toggle(e,t){return typeof t<"u"?t?(this.add(e),!0):(this.remove(e),!1):this.contains(e)?(this.remove(e),!1):(this.add(e),!0)}replace(e,t){return this.remove(e),this.add(t),e===t}}tn=new WeakMap;sn=new WeakMap;wd=new WeakMap;Er=new WeakMap;us=new WeakSet;Cs=function(){return bt(this,Er).size?bt(this,Er):bt(this,wd)};const _A=(i="")=>i.split(/\s+/),dE=(i="")=>{const[e,t,s]=i.split(":"),r=s?decodeURIComponent(s):void 0;return{kind:e==="cc"?ts.CAPTIONS:ts.SUBTITLES,language:t,label:r}},Su=(i="",e={})=>_A(i).map(t=>{const s=dE(t);return{...e,...s}}),uE=i=>i?Array.isArray(i)?i.map(e=>typeof e=="string"?dE(e):e):typeof i=="string"?Su(i):[i]:[],lh=({kind:i,label:e,language:t}={kind:"subtitles"})=>e?`${i==="captions"?"cc":"sb"}:${t}:${encodeURIComponent(e)}`:t,ao=(i=[])=>Array.prototype.map.call(i,lh).join(" "),AA=(i,e)=>t=>t[i]===e,cE=i=>{const e=Object.entries(i).map(([t,s])=>AA(t,s));return t=>e.every(s=>s(t))},Va=(i,e=[],t=[])=>{const s=uE(t).map(cE),r=n=>s.some(a=>a(n));Array.from(e).filter(r).forEach(n=>{n.mode=i})},Iu=(i,e=()=>!0)=>{if(!i?.textTracks)return[];const t=typeof e=="function"?e:cE(e);return Array.from(i.textTracks).filter(t)},hE=i=>{var e;return!!((e=i.mediaSubtitlesShowing)!=null&&e.length)||i.hasAttribute(_.MEDIA_SUBTITLES_SHOWING)},SA=i=>{var e;const{media:t,fullscreenElement:s}=i;try{const r=s&&"requestFullscreen"in s?"requestFullscreen":s&&"webkitRequestFullScreen"in s?"webkitRequestFullScreen":void 0;if(r){const n=(e=s[r])==null?void 0:e.call(s);if(n instanceof Promise)return n.catch(()=>{})}else t?.webkitEnterFullscreen?t.webkitEnterFullscreen():t?.requestFullscreen&&t.requestFullscreen()}catch(r){console.error(r)}},Wp="exitFullscreen"in lt?"exitFullscreen":"webkitExitFullscreen"in lt?"webkitExitFullscreen":"webkitCancelFullScreen"in lt?"webkitCancelFullScreen":void 0,IA=i=>{var e;const{documentElement:t}=i;if(Wp){const s=(e=t?.[Wp])==null?void 0:e.call(t);if(s instanceof Promise)return s.catch(()=>{})}},ba="fullscreenElement"in lt?"fullscreenElement":"webkitFullscreenElement"in lt?"webkitFullscreenElement":void 0,xA=i=>{const{documentElement:e,media:t}=i,s=e?.[ba];return!s&&"webkitDisplayingFullscreen"in t&&"webkitPresentationMode"in t&&t.webkitDisplayingFullscreen&&t.webkitPresentationMode===j_.FULLSCREEN?t:s},LA=i=>{var e;const{media:t,documentElement:s,fullscreenElement:r=t}=i;if(!t||!s)return!1;const n=xA(i);if(!n)return!1;if(n===r||n===t)return!0;if(n.localName.includes("-")){let a=n.shadowRoot;if(!(ba in a))return Ts(n,r);for(;a?.[ba];){if(a[ba]===r)return!0;a=(e=a[ba])==null?void 0:e.shadowRoot}}return!1},RA="fullscreenEnabled"in lt?"fullscreenEnabled":"webkitFullscreenEnabled"in lt?"webkitFullscreenEnabled":void 0,kA=i=>{const{documentElement:e,media:t}=i;return!!e?.[RA]||t&&"webkitSupportsFullscreen"in t};let Oo;const om=()=>{var i,e;return Oo||(Oo=(e=(i=lt)==null?void 0:i.createElement)==null?void 0:e.call(i,"video"),Oo)},DA=async(i=om())=>{if(!i)return!1;const e=i.volume;i.volume=e/2+.1;const t=new AbortController,s=await Promise.race([CA(i,t.signal),wA(i,e)]);return t.abort(),s},CA=(i,e)=>new Promise(t=>{i.addEventListener("volumechange",()=>t(!0),{signal:e})}),wA=async(i,e)=>{for(let t=0;t<10;t++){if(i.volume===e)return!1;await Yv(10)}return i.volume!==e},MA=/.*Version\/.*Safari\/.*/.test(k.navigator.userAgent),fE=(i=om())=>k.matchMedia("(display-mode: standalone)").matches&&MA?!1:typeof i?.requestPictureInPicture=="function",mE=(i=om())=>kA({documentElement:lt,media:i}),PA=mE(),OA=fE(),NA=!!k.WebKitPlaybackTargetAvailabilityEvent,UA=!!k.chrome,Md=i=>Iu(i.media,e=>[ts.SUBTITLES,ts.CAPTIONS].includes(e.kind)).sort((e,t)=>e.kind>=t.kind?1:-1),pE=i=>Iu(i.media,e=>e.mode===Pn.SHOWING&&[ts.SUBTITLES,ts.CAPTIONS].includes(e.kind)),gE=(i,e)=>{const t=Md(i),s=pE(i),r=!!s.length;if(t.length){if(e===!1||r&&e!==!0)Va(Pn.DISABLED,t,s);else if(e===!0||!r&&e!==!1){let n=t[0];const{options:a}=i;if(!a?.noSubtitlesLangPref){const u=globalThis.localStorage.getItem("media-chrome-pref-subtitles-lang"),c=u?[u,...globalThis.navigator.languages]:globalThis.navigator.languages,h=t.filter(f=>c.some(m=>f.language.toLowerCase().startsWith(m.split("-")[0]))).sort((f,m)=>{const p=c.findIndex(v=>f.language.toLowerCase().startsWith(v.split("-")[0])),g=c.findIndex(v=>m.language.toLowerCase().startsWith(v.split("-")[0]));return p-g});h[0]&&(n=h[0])}const{language:o,label:l,kind:d}=n;Va(Pn.DISABLED,t,s),Va(Pn.SHOWING,t,[{language:o,label:l,kind:d}])}}},lm=(i,e)=>i===e?!0:i==null||e==null||typeof i!=typeof e?!1:typeof i=="number"&&Number.isNaN(i)&&Number.isNaN(e)?!0:typeof i!="object"?!1:Array.isArray(i)?$A(i,e):Object.entries(i).every(([t,s])=>t in e&&lm(s,e[t])),$A=(i,e)=>{const t=Array.isArray(i),s=Array.isArray(e);return t!==s?!1:t||s?i.length!==e.length?!1:i.every((r,n)=>lm(r,e[n])):!0},FA=Object.values(hs);let Pd;const BA=DA().then(i=>(Pd=i,Pd)),HA=async(...i)=>{await Promise.all(i.filter(e=>e).map(async e=>{if(!("localName"in e&&e instanceof k.HTMLElement))return;const t=e.localName;if(!t.includes("-"))return;const s=k.customElements.get(t);s&&e instanceof s||(await k.customElements.whenDefined(t),k.customElements.upgrade(e))}))},GA=new k.DOMParser,KA=i=>i&&(GA.parseFromString(i,"text/html").body.textContent||i),Ta={mediaError:{get(i,e){const{media:t}=i;if(e?.type!=="playing")return t?.error},mediaEvents:["emptied","error","playing"]},mediaErrorCode:{get(i,e){var t;const{media:s}=i;if(e?.type!=="playing")return(t=s?.error)==null?void 0:t.code},mediaEvents:["emptied","error","playing"]},mediaErrorMessage:{get(i,e){var t,s;const{media:r}=i;if(e?.type!=="playing")return(s=(t=r?.error)==null?void 0:t.message)!=null?s:""},mediaEvents:["emptied","error","playing"]},mediaWidth:{get(i){var e;const{media:t}=i;return(e=t?.videoWidth)!=null?e:0},mediaEvents:["resize"]},mediaHeight:{get(i){var e;const{media:t}=i;return(e=t?.videoHeight)!=null?e:0},mediaEvents:["resize"]},mediaPaused:{get(i){var e;const{media:t}=i;return(e=t?.paused)!=null?e:!0},set(i,e){var t;const{media:s}=e;s&&(i?s.pause():(t=s.play())==null||t.catch(()=>{}))},mediaEvents:["play","playing","pause","emptied"]},mediaHasPlayed:{get(i,e){const{media:t}=i;return t?e?e.type==="playing":!t.paused:!1},mediaEvents:["playing","emptied"]},mediaEnded:{get(i){var e;const{media:t}=i;return(e=t?.ended)!=null?e:!1},mediaEvents:["seeked","ended","emptied"]},mediaPlaybackRate:{get(i){var e;const{media:t}=i;return(e=t?.playbackRate)!=null?e:1},set(i,e){const{media:t}=e;t&&Number.isFinite(+i)&&(t.playbackRate=+i)},mediaEvents:["ratechange","loadstart"]},mediaMuted:{get(i){var e;const{media:t}=i;return(e=t?.muted)!=null?e:!1},set(i,e){const{media:t,options:{noMutedPref:s}={}}=e;if(t){t.muted=i;try{const r=k.localStorage.getItem("media-chrome-pref-muted")!==null,n=t.hasAttribute("muted");if(s){r&&k.localStorage.removeItem("media-chrome-pref-muted");return}if(n&&!r)return;k.localStorage.setItem("media-chrome-pref-muted",i?"true":"false")}catch(r){console.debug("Error setting muted pref",r)}}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(i,e)=>{const{options:{noMutedPref:t}}=e,{media:s}=e;if(!(!s||s.muted||t))try{const r=k.localStorage.getItem("media-chrome-pref-muted")==="true";Ta.mediaMuted.set(r,e),i(r)}catch(r){console.debug("Error getting muted pref",r)}}]},mediaLoop:{get(i){const{media:e}=i;return e?.loop},set(i,e){const{media:t}=e;t&&(t.loop=i)},mediaEvents:["medialooprequest"]},mediaVolume:{get(i){var e;const{media:t}=i;return(e=t?.volume)!=null?e:1},set(i,e){const{media:t,options:{noVolumePref:s}={}}=e;if(t){try{i==null?k.localStorage.removeItem("media-chrome-pref-volume"):!t.hasAttribute("muted")&&!s&&k.localStorage.setItem("media-chrome-pref-volume",i.toString())}catch(r){console.debug("Error setting volume pref",r)}Number.isFinite(+i)&&(t.volume=+i)}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(i,e)=>{const{options:{noVolumePref:t}}=e;if(!t)try{const{media:s}=e;if(!s)return;const r=k.localStorage.getItem("media-chrome-pref-volume");if(r==null)return;Ta.mediaVolume.set(+r,e),i(+r)}catch(s){console.debug("Error getting volume pref",s)}}]},mediaVolumeLevel:{get(i){const{media:e}=i;return typeof e?.volume>"u"?"high":e.muted||e.volume===0?"off":e.volume<.5?"low":e.volume<.75?"medium":"high"},mediaEvents:["volumechange"]},mediaCurrentTime:{get(i){var e;const{media:t}=i;return(e=t?.currentTime)!=null?e:0},set(i,e){const{media:t}=e;!t||!em(i)||(t.currentTime=i)},mediaEvents:["timeupdate","loadedmetadata"]},mediaDuration:{get(i){const{media:e,options:{defaultDuration:t}={}}=i;return t&&(!e||!e.duration||Number.isNaN(e.duration)||!Number.isFinite(e.duration))?t:Number.isFinite(e?.duration)?e.duration:Number.NaN},mediaEvents:["durationchange","loadedmetadata","emptied"]},mediaLoading:{get(i){const{media:e}=i;return e?.readyState<3},mediaEvents:["waiting","playing","emptied"]},mediaSeekable:{get(i){var e;const{media:t}=i;if(!((e=t?.seekable)!=null&&e.length))return;const s=t.seekable.start(0),r=t.seekable.end(t.seekable.length-1);if(!(!s&&!r))return[Number(s.toFixed(3)),Number(r.toFixed(3))]},mediaEvents:["loadedmetadata","emptied","progress","seekablechange"]},mediaBuffered:{get(i){var e;const{media:t}=i,s=(e=t?.buffered)!=null?e:[];return Array.from(s).map((r,n)=>[Number(s.start(n).toFixed(3)),Number(s.end(n).toFixed(3))])},mediaEvents:["progress","emptied"]},mediaStreamType:{get(i){const{media:e,options:{defaultStreamType:t}={}}=i,s=[hs.LIVE,hs.ON_DEMAND].includes(t)?t:void 0;if(!e)return s;const{streamType:r}=e;if(FA.includes(r))return r===hs.UNKNOWN?s:r;const n=e.duration;return n===1/0?hs.LIVE:Number.isFinite(n)?hs.ON_DEMAND:s},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange"]},mediaTargetLiveWindow:{get(i){const{media:e}=i;if(!e)return Number.NaN;const{targetLiveWindow:t}=e,s=Ta.mediaStreamType.get(i);return(t==null||Number.isNaN(t))&&s===hs.LIVE?0:t},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange","targetlivewindowchange"]},mediaTimeIsLive:{get(i){const{media:e,options:{liveEdgeOffset:t=10}={}}=i;if(!e)return!1;if(typeof e.liveEdgeStart=="number")return Number.isNaN(e.liveEdgeStart)?!1:e.currentTime>=e.liveEdgeStart;if(!(Ta.mediaStreamType.get(i)===hs.LIVE))return!1;const r=e.seekable;if(!r)return!0;if(!r.length)return!1;const n=r.end(r.length-1)-t;return e.currentTime>=n},mediaEvents:["playing","timeupdate","progress","waiting","emptied"]},mediaSubtitlesList:{get(i){return Md(i).map(({kind:e,label:t,language:s})=>({kind:e,label:t,language:s}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack"]},mediaSubtitlesShowing:{get(i){return pE(i).map(({kind:e,label:t,language:s})=>({kind:e,label:t,language:s}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(i,e)=>{var t,s;const{media:r,options:n}=e;if(!r)return;const a=o=>{var l;!n.defaultSubtitles||o&&![ts.CAPTIONS,ts.SUBTITLES].includes((l=o?.track)==null?void 0:l.kind)||gE(e,!0)};return r.addEventListener("loadstart",a),(t=r.textTracks)==null||t.addEventListener("addtrack",a),(s=r.textTracks)==null||s.addEventListener("removetrack",a),()=>{var o,l;r.removeEventListener("loadstart",a),(o=r.textTracks)==null||o.removeEventListener("addtrack",a),(l=r.textTracks)==null||l.removeEventListener("removetrack",a)}}]},mediaChaptersCues:{get(i){var e;const{media:t}=i;if(!t)return[];const[s]=Iu(t,{kind:ts.CHAPTERS});return Array.from((e=s?.cues)!=null?e:[]).map(({text:r,startTime:n,endTime:a})=>({text:KA(r),startTime:n,endTime:a}))},mediaEvents:["loadstart","loadedmetadata"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(i,e)=>{var t;const{media:s}=e;if(!s)return;const r=s.querySelector('track[kind="chapters"][default][src]'),n=(t=s.shadowRoot)==null?void 0:t.querySelector(':is(video,audio) > track[kind="chapters"][default][src]');return r?.addEventListener("load",i),n?.addEventListener("load",i),()=>{r?.removeEventListener("load",i),n?.removeEventListener("load",i)}}]},mediaIsPip:{get(i){var e,t;const{media:s,documentElement:r}=i;if(!s||!r||!r.pictureInPictureElement)return!1;if(r.pictureInPictureElement===s)return!0;if(r.pictureInPictureElement instanceof HTMLMediaElement)return(e=s.localName)!=null&&e.includes("-")?Ts(s,r.pictureInPictureElement):!1;if(r.pictureInPictureElement.localName.includes("-")){let n=r.pictureInPictureElement.shadowRoot;for(;n?.pictureInPictureElement;){if(n.pictureInPictureElement===s)return!0;n=(t=n.pictureInPictureElement)==null?void 0:t.shadowRoot}}return!1},set(i,e){const{media:t}=e;if(t)if(i){if(!lt.pictureInPictureEnabled){console.warn("MediaChrome: Picture-in-picture is not enabled");return}if(!t.requestPictureInPicture){console.warn("MediaChrome: The current media does not support picture-in-picture");return}const s=()=>{console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a readyState > 0.")};t.requestPictureInPicture().catch(r=>{if(r.code===11){if(!t.src){console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a src set.");return}if(t.readyState===0&&t.preload==="none"){const n=()=>{t.removeEventListener("loadedmetadata",a),t.preload="none"},a=()=>{t.requestPictureInPicture().catch(s),n()};t.addEventListener("loadedmetadata",a),t.preload="metadata",setTimeout(()=>{t.readyState===0&&s(),n()},1e3)}else throw r}else throw r})}else lt.pictureInPictureElement&<.exitPictureInPicture()},mediaEvents:["enterpictureinpicture","leavepictureinpicture"]},mediaRenditionList:{get(i){var e;const{media:t}=i;return[...(e=t?.videoRenditions)!=null?e:[]].map(s=>({...s}))},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaRenditionSelected:{get(i){var e,t,s;const{media:r}=i;return(s=(t=r?.videoRenditions)==null?void 0:t[(e=r.videoRenditions)==null?void 0:e.selectedIndex])==null?void 0:s.id},set(i,e){const{media:t}=e;if(!t?.videoRenditions){console.warn("MediaController: Rendition selection not supported by this media.");return}const s=i,r=Array.prototype.findIndex.call(t.videoRenditions,n=>n.id==s);t.videoRenditions.selectedIndex!=r&&(t.videoRenditions.selectedIndex=r)},mediaEvents:["emptied"],videoRenditionsEvents:["addrendition","removerendition","change"]},mediaAudioTrackList:{get(i){var e;const{media:t}=i;return[...(e=t?.audioTracks)!=null?e:[]]},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaAudioTrackEnabled:{get(i){var e,t;const{media:s}=i;return(t=[...(e=s?.audioTracks)!=null?e:[]].find(r=>r.enabled))==null?void 0:t.id},set(i,e){const{media:t}=e;if(!t?.audioTracks){console.warn("MediaChrome: Audio track selection not supported by this media.");return}const s=i;for(const r of t.audioTracks)r.enabled=s==r.id},mediaEvents:["emptied"],audioTracksEvents:["addtrack","removetrack","change"]},mediaIsFullscreen:{get(i){return LA(i)},set(i,e,t){var s;i?(SA(e),t.detail&&((s=e.media)==null||s.focus())):IA(e)},rootEvents:["fullscreenchange","webkitfullscreenchange"],mediaEvents:["webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"]},mediaIsCasting:{get(i){var e;const{media:t}=i;return!t?.remote||((e=t.remote)==null?void 0:e.state)==="disconnected"?!1:!!t.remote.state},set(i,e){var t,s;const{media:r}=e;if(r&&!(i&&((t=r.remote)==null?void 0:t.state)!=="disconnected")&&!(!i&&((s=r.remote)==null?void 0:s.state)!=="connected")){if(typeof r.remote.prompt!="function"){console.warn("MediaChrome: Casting is not supported in this environment");return}r.remote.prompt().catch(()=>{})}},remoteEvents:["connect","connecting","disconnect"]},mediaIsAirplaying:{get(){return!1},set(i,e){const{media:t}=e;if(t){if(!(t.webkitShowPlaybackTargetPicker&&k.WebKitPlaybackTargetAvailabilityEvent)){console.error("MediaChrome: received a request to select AirPlay but AirPlay is not supported in this environment");return}t.webkitShowPlaybackTargetPicker()}},mediaEvents:["webkitcurrentplaybacktargetiswirelesschanged"]},mediaFullscreenUnavailable:{get(i){const{media:e}=i;if(!PA||!mE(e))return Ht.UNSUPPORTED}},mediaPipUnavailable:{get(i){const{media:e}=i;if(!OA||!fE(e))return Ht.UNSUPPORTED;if(e?.disablePictureInPicture)return Ht.UNAVAILABLE}},mediaVolumeUnavailable:{get(i){const{media:e}=i;if(Pd===!1||e?.volume==null)return Ht.UNSUPPORTED},stateOwnersUpdateHandlers:[i=>{Pd==null&&BA.then(e=>i(e?void 0:Ht.UNSUPPORTED))}]},mediaCastUnavailable:{get(i,{availability:e="not-available"}={}){var t;const{media:s}=i;if(!UA||!((t=s?.remote)!=null&&t.state))return Ht.UNSUPPORTED;if(!(e==null||e==="available"))return Ht.UNAVAILABLE},stateOwnersUpdateHandlers:[(i,e)=>{var t;const{media:s}=e;return s?(s.disableRemotePlayback||s.hasAttribute("disableremoteplayback")||(t=s?.remote)==null||t.watchAvailability(n=>{i({availability:n?"available":"not-available"})}).catch(n=>{n.name==="NotSupportedError"?i({availability:null}):i({availability:"not-available"})}),()=>{var n;(n=s?.remote)==null||n.cancelWatchAvailability().catch(()=>{})}):void 0}]},mediaAirplayUnavailable:{get(i,e){if(!NA)return Ht.UNSUPPORTED;if(e?.availability==="not-available")return Ht.UNAVAILABLE},mediaEvents:["webkitplaybacktargetavailabilitychanged"],stateOwnersUpdateHandlers:[(i,e)=>{var t;const{media:s}=e;return s?(s.disableRemotePlayback||s.hasAttribute("disableremoteplayback")||(t=s?.remote)==null||t.watchAvailability(n=>{i({availability:n?"available":"not-available"})}).catch(n=>{n.name==="NotSupportedError"?i({availability:null}):i({availability:"not-available"})}),()=>{var n;(n=s?.remote)==null||n.cancelWatchAvailability().catch(()=>{})}):void 0}]},mediaRenditionUnavailable:{get(i){var e;const{media:t}=i;if(!t?.videoRenditions)return Ht.UNSUPPORTED;if(!((e=t.videoRenditions)!=null&&e.length))return Ht.UNAVAILABLE},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaAudioTrackUnavailable:{get(i){var e,t;const{media:s}=i;if(!s?.audioTracks)return Ht.UNSUPPORTED;if(((t=(e=s.audioTracks)==null?void 0:e.length)!=null?t:0)<=1)return Ht.UNAVAILABLE},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaLang:{get(i){const{options:{mediaLang:e}={}}=i;return e??"en"}}},VA={[Q.MEDIA_PREVIEW_REQUEST](i,e,{detail:t}){var s,r,n;const{media:a}=e,o=t??void 0;let l,d;if(a&&o!=null){const[f]=Iu(a,{kind:ts.METADATA,label:"thumbnails"}),m=Array.prototype.find.call((s=f?.cues)!=null?s:[],(p,g,v)=>g===0?p.endTime>o:g===v.length-1?p.startTime<=o:p.startTime<=o&&p.endTime>o);if(m){const p=/'^(?:[a-z]+:)?\/\//i.test(m.text)||(r=a?.querySelector('track[label="thumbnails"]'))==null?void 0:r.src,g=new URL(m.text,p);d=new URLSearchParams(g.hash).get("#xywh").split(",").map(b=>+b),l=g.href}}const u=i.mediaDuration.get(e);let h=(n=i.mediaChaptersCues.get(e).find((f,m,p)=>m===p.length-1&&u===f.endTime?f.startTime<=o&&f.endTime>=o:f.startTime<=o&&f.endTime>o))==null?void 0:n.text;return t!=null&&h==null&&(h=""),{mediaPreviewTime:o,mediaPreviewImage:l,mediaPreviewCoords:d,mediaPreviewChapter:h}},[Q.MEDIA_PAUSE_REQUEST](i,e){i["mediaPaused"].set(!0,e)},[Q.MEDIA_PLAY_REQUEST](i,e){var t,s,r,n;const a="mediaPaused",l=i.mediaStreamType.get(e)===hs.LIVE,d=!((t=e.options)!=null&&t.noAutoSeekToLive),u=i.mediaTargetLiveWindow.get(e)>0;if(l&&d&&!u){const c=(s=i.mediaSeekable.get(e))==null?void 0:s[1];if(c){const h=(n=(r=e.options)==null?void 0:r.seekToLiveOffset)!=null?n:0,f=c-h;i.mediaCurrentTime.set(f,e)}}i[a].set(!1,e)},[Q.MEDIA_PLAYBACK_RATE_REQUEST](i,e,{detail:t}){const s="mediaPlaybackRate",r=t;i[s].set(r,e)},[Q.MEDIA_MUTE_REQUEST](i,e){i["mediaMuted"].set(!0,e)},[Q.MEDIA_UNMUTE_REQUEST](i,e){const t="mediaMuted";i.mediaVolume.get(e)||i.mediaVolume.set(.25,e),i[t].set(!1,e)},[Q.MEDIA_LOOP_REQUEST](i,e,{detail:t}){const s="mediaLoop",r=!!t;return i[s].set(r,e),{mediaLoop:r}},[Q.MEDIA_VOLUME_REQUEST](i,e,{detail:t}){const s="mediaVolume",r=t;r&&i.mediaMuted.get(e)&&i.mediaMuted.set(!1,e),i[s].set(r,e)},[Q.MEDIA_SEEK_REQUEST](i,e,{detail:t}){const s="mediaCurrentTime",r=t;i[s].set(r,e)},[Q.MEDIA_SEEK_TO_LIVE_REQUEST](i,e){var t,s,r;const n="mediaCurrentTime",a=(t=i.mediaSeekable.get(e))==null?void 0:t[1];if(Number.isNaN(Number(a)))return;const o=(r=(s=e.options)==null?void 0:s.seekToLiveOffset)!=null?r:0,l=a-o;i[n].set(l,e)},[Q.MEDIA_SHOW_SUBTITLES_REQUEST](i,e,{detail:t}){var s;const{options:r}=e,n=Md(e),a=uE(t),o=(s=a[0])==null?void 0:s.language;o&&!r.noSubtitlesLangPref&&k.localStorage.setItem("media-chrome-pref-subtitles-lang",o),Va(Pn.SHOWING,n,a)},[Q.MEDIA_DISABLE_SUBTITLES_REQUEST](i,e,{detail:t}){const s=Md(e),r=t??[];Va(Pn.DISABLED,s,r)},[Q.MEDIA_TOGGLE_SUBTITLES_REQUEST](i,e,{detail:t}){gE(e,t)},[Q.MEDIA_RENDITION_REQUEST](i,e,{detail:t}){const s="mediaRenditionSelected",r=t;i[s].set(r,e)},[Q.MEDIA_AUDIO_TRACK_REQUEST](i,e,{detail:t}){const s="mediaAudioTrackEnabled",r=t;i[s].set(r,e)},[Q.MEDIA_ENTER_PIP_REQUEST](i,e){const t="mediaIsPip";i.mediaIsFullscreen.get(e)&&i.mediaIsFullscreen.set(!1,e),i[t].set(!0,e)},[Q.MEDIA_EXIT_PIP_REQUEST](i,e){i["mediaIsPip"].set(!1,e)},[Q.MEDIA_ENTER_FULLSCREEN_REQUEST](i,e,t){const s="mediaIsFullscreen";i.mediaIsPip.get(e)&&i.mediaIsPip.set(!1,e),i[s].set(!0,e,t)},[Q.MEDIA_EXIT_FULLSCREEN_REQUEST](i,e){i["mediaIsFullscreen"].set(!1,e)},[Q.MEDIA_ENTER_CAST_REQUEST](i,e){const t="mediaIsCasting";i.mediaIsFullscreen.get(e)&&i.mediaIsFullscreen.set(!1,e),i[t].set(!0,e)},[Q.MEDIA_EXIT_CAST_REQUEST](i,e){i["mediaIsCasting"].set(!1,e)},[Q.MEDIA_AIRPLAY_REQUEST](i,e){i["mediaIsAirplaying"].set(!0,e)}},WA=({media:i,fullscreenElement:e,documentElement:t,stateMediator:s=Ta,requestMap:r=VA,options:n={},monitorStateOwnersOnlyWithSubscriptions:a=!0})=>{const o=[],l={options:{...n}};let d=Object.freeze({mediaPreviewTime:void 0,mediaPreviewImage:void 0,mediaPreviewCoords:void 0,mediaPreviewChapter:void 0});const u=p=>{p!=null&&(lm(p,d)||(d=Object.freeze({...d,...p}),o.forEach(g=>g(d))))},c=()=>{const p=Object.entries(s).reduce((g,[v,{get:b}])=>(g[v]=b(l),g),{});u(p)},h={};let f;const m=async(p,g)=>{var v,b,E,T,A,x,S,L,R,I,M,B,q,z,K,H;const j=!!f;if(f={...l,...f??{},...p},j)return;await HA(...Object.values(p));const G=o.length>0&&g===0&&a,N=l.media!==f.media,W=((v=l.media)==null?void 0:v.textTracks)!==((b=f.media)==null?void 0:b.textTracks),U=((E=l.media)==null?void 0:E.videoRenditions)!==((T=f.media)==null?void 0:T.videoRenditions),$=((A=l.media)==null?void 0:A.audioTracks)!==((x=f.media)==null?void 0:x.audioTracks),re=((S=l.media)==null?void 0:S.remote)!==((L=f.media)==null?void 0:L.remote),he=l.documentElement!==f.documentElement,ce=!!l.media&&(N||G),pe=!!((R=l.media)!=null&&R.textTracks)&&(W||G),ut=!!((I=l.media)!=null&&I.videoRenditions)&&(U||G),tt=!!((M=l.media)!=null&&M.audioTracks)&&($||G),Dt=!!((B=l.media)!=null&&B.remote)&&(re||G),Ft=!!l.documentElement&&(he||G),ci=ce||pe||ut||tt||Dt||Ft,Ss=o.length===0&&g===1&&a,$r=!!f.media&&(N||Ss),Fr=!!((q=f.media)!=null&&q.textTracks)&&(W||Ss),nc=!!((z=f.media)!=null&&z.videoRenditions)&&(U||Ss),Te=!!((K=f.media)!=null&&K.audioTracks)&&($||Ss),ct=!!((H=f.media)!=null&&H.remote)&&(re||Ss),Ct=!!f.documentElement&&(he||Ss),xi=$r||Fr||nc||Te||ct||Ct;if(!(ci||xi)){Object.entries(f).forEach(([_e,Bt])=>{l[_e]=Bt}),c(),f=void 0;return}Object.entries(s).forEach(([_e,{get:Bt,mediaEvents:Ro=[],textTracksEvents:Br=[],videoRenditionsEvents:ko=[],audioTracksEvents:Js=[],remoteEvents:Do=[],rootEvents:ac=[],stateOwnersUpdateHandlers:Co=[]}])=>{h[_e]||(h[_e]={});const Lt=We=>{const it=Bt(l,We);u({[_e]:it})};let Ve;Ve=h[_e].mediaEvents,Ro.forEach(We=>{Ve&&ce&&(l.media.removeEventListener(We,Ve),h[_e].mediaEvents=void 0),$r&&(f.media.addEventListener(We,Lt),h[_e].mediaEvents=Lt)}),Ve=h[_e].textTracksEvents,Br.forEach(We=>{var it,hi;Ve&&pe&&((it=l.media.textTracks)==null||it.removeEventListener(We,Ve),h[_e].textTracksEvents=void 0),Fr&&((hi=f.media.textTracks)==null||hi.addEventListener(We,Lt),h[_e].textTracksEvents=Lt)}),Ve=h[_e].videoRenditionsEvents,ko.forEach(We=>{var it,hi;Ve&&ut&&((it=l.media.videoRenditions)==null||it.removeEventListener(We,Ve),h[_e].videoRenditionsEvents=void 0),nc&&((hi=f.media.videoRenditions)==null||hi.addEventListener(We,Lt),h[_e].videoRenditionsEvents=Lt)}),Ve=h[_e].audioTracksEvents,Js.forEach(We=>{var it,hi;Ve&&tt&&((it=l.media.audioTracks)==null||it.removeEventListener(We,Ve),h[_e].audioTracksEvents=void 0),Te&&((hi=f.media.audioTracks)==null||hi.addEventListener(We,Lt),h[_e].audioTracksEvents=Lt)}),Ve=h[_e].remoteEvents,Do.forEach(We=>{var it,hi;Ve&&Dt&&((it=l.media.remote)==null||it.removeEventListener(We,Ve),h[_e].remoteEvents=void 0),ct&&((hi=f.media.remote)==null||hi.addEventListener(We,Lt),h[_e].remoteEvents=Lt)}),Ve=h[_e].rootEvents,ac.forEach(We=>{Ve&&Ft&&(l.documentElement.removeEventListener(We,Ve),h[_e].rootEvents=void 0),Ct&&(f.documentElement.addEventListener(We,Lt),h[_e].rootEvents=Lt)});const wo=h[_e].stateOwnersUpdateHandlers;if(wo&&ci&&(Array.isArray(wo)?wo:[wo]).forEach(it=>{typeof it=="function"&&it()}),xi){const We=Co.map(it=>it(Lt,f)).filter(it=>typeof it=="function");h[_e].stateOwnersUpdateHandlers=We.length===1?We[0]:We}else ci&&(h[_e].stateOwnersUpdateHandlers=void 0)}),Object.entries(f).forEach(([_e,Bt])=>{l[_e]=Bt}),c(),f=void 0};return m({media:i,fullscreenElement:e,documentElement:t,options:n}),{dispatch(p){const{type:g,detail:v}=p;if(r[g]&&d.mediaErrorCode==null){u(r[g](s,l,p));return}g==="mediaelementchangerequest"?m({media:v}):g==="fullscreenelementchangerequest"?m({fullscreenElement:v}):g==="documentelementchangerequest"?m({documentElement:v}):g==="optionschangerequest"&&(Object.entries(v??{}).forEach(([b,E])=>{l.options[b]=E}),c())},getState(){return d},subscribe(p){return m({},o.length+1),o.push(p),p(d),()=>{const g=o.indexOf(p);g>=0&&(m({},o.length-1),o.splice(g,1))}}}};var dm=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},oe=(i,e,t)=>(dm(i,e,"read from private field"),t?t.call(i):e.get(i)),ti=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Mi=(i,e,t,s)=>(dm(i,e,"write to private field"),e.set(i,t),t),qi=(i,e,t)=>(dm(i,e,"access private method"),t),Gs,_a,Ae,yr,Aa,Pi,vl,Sa,El,dh,Sr,On,yl,uh,ch,vE;const EE=["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Enter"," ","f","m","k","c","l","j",">","<","p"],qp=10,Yp=.025,jp=.25,qA=.25,YA=2,V={DEFAULT_SUBTITLES:"defaultsubtitles",DEFAULT_STREAM_TYPE:"defaultstreamtype",DEFAULT_DURATION:"defaultduration",FULLSCREEN_ELEMENT:"fullscreenelement",HOTKEYS:"hotkeys",KEYBOARD_BACKWARD_SEEK_OFFSET:"keyboardbackwardseekoffset",KEYBOARD_FORWARD_SEEK_OFFSET:"keyboardforwardseekoffset",KEYBOARD_DOWN_VOLUME_STEP:"keyboarddownvolumestep",KEYBOARD_UP_VOLUME_STEP:"keyboardupvolumestep",KEYS_USED:"keysused",LANG:"lang",LOOP:"loop",LIVE_EDGE_OFFSET:"liveedgeoffset",NO_AUTO_SEEK_TO_LIVE:"noautoseektolive",NO_DEFAULT_STORE:"nodefaultstore",NO_HOTKEYS:"nohotkeys",NO_MUTED_PREF:"nomutedpref",NO_SUBTITLES_LANG_PREF:"nosubtitleslangpref",NO_VOLUME_PREF:"novolumepref",SEEK_TO_LIVE_OFFSET:"seektoliveoffset"};let yE=class extends xo{constructor(){super(),ti(this,El),ti(this,Sr),ti(this,yl),ti(this,ch),this.mediaStateReceivers=[],this.associatedElementSubscriptions=new Map,ti(this,Gs,new am(this,V.HOTKEYS)),ti(this,_a,void 0),ti(this,Ae,void 0),ti(this,yr,null),ti(this,Aa,void 0),ti(this,Pi,void 0),ti(this,vl,t=>{var s;(s=oe(this,Ae))==null||s.dispatch(t)}),ti(this,Sa,void 0),this.associateElement(this);let e={};Mi(this,Aa,t=>{Object.entries(t).forEach(([s,r])=>{if(s in e&&e[s]===r)return;this.propagateMediaState(s,r);const n=s.toLowerCase(),a=new k.CustomEvent(Y_[n],{composed:!0,detail:r});this.dispatchEvent(a)}),e=t}),this.hasAttribute(V.NO_HOTKEYS)?this.disableHotkeys():this.enableHotkeys()}static get observedAttributes(){return super.observedAttributes.concat(V.NO_HOTKEYS,V.HOTKEYS,V.DEFAULT_STREAM_TYPE,V.DEFAULT_SUBTITLES,V.DEFAULT_DURATION,V.NO_MUTED_PREF,V.NO_VOLUME_PREF,V.LANG,V.LOOP)}get mediaStore(){return oe(this,Ae)}set mediaStore(e){var t,s;if(oe(this,Ae)&&((t=oe(this,Pi))==null||t.call(this),Mi(this,Pi,void 0)),Mi(this,Ae,e),!oe(this,Ae)&&!this.hasAttribute(V.NO_DEFAULT_STORE)){qi(this,El,dh).call(this);return}Mi(this,Pi,(s=oe(this,Ae))==null?void 0:s.subscribe(oe(this,Aa)))}get fullscreenElement(){var e;return(e=oe(this,_a))!=null?e:this}set fullscreenElement(e){var t;this.hasAttribute(V.FULLSCREEN_ELEMENT)&&this.removeAttribute(V.FULLSCREEN_ELEMENT),Mi(this,_a,e),(t=oe(this,Ae))==null||t.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement})}get defaultSubtitles(){return ye(this,V.DEFAULT_SUBTITLES)}set defaultSubtitles(e){be(this,V.DEFAULT_SUBTITLES,e)}get defaultStreamType(){return He(this,V.DEFAULT_STREAM_TYPE)}set defaultStreamType(e){Ge(this,V.DEFAULT_STREAM_TYPE,e)}get defaultDuration(){return Be(this,V.DEFAULT_DURATION)}set defaultDuration(e){Xe(this,V.DEFAULT_DURATION,e)}get noHotkeys(){return ye(this,V.NO_HOTKEYS)}set noHotkeys(e){be(this,V.NO_HOTKEYS,e)}get keysUsed(){return He(this,V.KEYS_USED)}set keysUsed(e){Ge(this,V.KEYS_USED,e)}get liveEdgeOffset(){return Be(this,V.LIVE_EDGE_OFFSET)}set liveEdgeOffset(e){Xe(this,V.LIVE_EDGE_OFFSET,e)}get noAutoSeekToLive(){return ye(this,V.NO_AUTO_SEEK_TO_LIVE)}set noAutoSeekToLive(e){be(this,V.NO_AUTO_SEEK_TO_LIVE,e)}get noVolumePref(){return ye(this,V.NO_VOLUME_PREF)}set noVolumePref(e){be(this,V.NO_VOLUME_PREF,e)}get noMutedPref(){return ye(this,V.NO_MUTED_PREF)}set noMutedPref(e){be(this,V.NO_MUTED_PREF,e)}get noSubtitlesLangPref(){return ye(this,V.NO_SUBTITLES_LANG_PREF)}set noSubtitlesLangPref(e){be(this,V.NO_SUBTITLES_LANG_PREF,e)}get noDefaultStore(){return ye(this,V.NO_DEFAULT_STORE)}set noDefaultStore(e){be(this,V.NO_DEFAULT_STORE,e)}attributeChangedCallback(e,t,s){var r,n,a,o,l,d,u,c,h,f,m,p;if(super.attributeChangedCallback(e,t,s),e===V.NO_HOTKEYS)s!==t&&s===""?(this.hasAttribute(V.HOTKEYS)&&console.warn("Media Chrome: Both `hotkeys` and `nohotkeys` have been set. All hotkeys will be disabled."),this.disableHotkeys()):s!==t&&s===null&&this.enableHotkeys();else if(e===V.HOTKEYS)oe(this,Gs).value=s;else if(e===V.DEFAULT_SUBTITLES&&s!==t)(r=oe(this,Ae))==null||r.dispatch({type:"optionschangerequest",detail:{defaultSubtitles:this.hasAttribute(V.DEFAULT_SUBTITLES)}});else if(e===V.DEFAULT_STREAM_TYPE)(a=oe(this,Ae))==null||a.dispatch({type:"optionschangerequest",detail:{defaultStreamType:(n=this.getAttribute(V.DEFAULT_STREAM_TYPE))!=null?n:void 0}});else if(e===V.LIVE_EDGE_OFFSET)(o=oe(this,Ae))==null||o.dispatch({type:"optionschangerequest",detail:{liveEdgeOffset:this.hasAttribute(V.LIVE_EDGE_OFFSET)?+this.getAttribute(V.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(V.SEEK_TO_LIVE_OFFSET)?void 0:+this.getAttribute(V.LIVE_EDGE_OFFSET)}});else if(e===V.SEEK_TO_LIVE_OFFSET)(l=oe(this,Ae))==null||l.dispatch({type:"optionschangerequest",detail:{seekToLiveOffset:this.hasAttribute(V.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(V.SEEK_TO_LIVE_OFFSET):void 0}});else if(e===V.NO_AUTO_SEEK_TO_LIVE)(d=oe(this,Ae))==null||d.dispatch({type:"optionschangerequest",detail:{noAutoSeekToLive:this.hasAttribute(V.NO_AUTO_SEEK_TO_LIVE)}});else if(e===V.FULLSCREEN_ELEMENT){const g=s?(u=this.getRootNode())==null?void 0:u.getElementById(s):void 0;Mi(this,_a,g),(c=oe(this,Ae))==null||c.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement})}else e===V.LANG&&s!==t?(aA(s),(h=oe(this,Ae))==null||h.dispatch({type:"optionschangerequest",detail:{mediaLang:s}})):e===V.LOOP&&s!==t?(f=oe(this,Ae))==null||f.dispatch({type:Q.MEDIA_LOOP_REQUEST,detail:s!=null}):e===V.NO_VOLUME_PREF&&s!==t?(m=oe(this,Ae))==null||m.dispatch({type:"optionschangerequest",detail:{noVolumePref:this.hasAttribute(V.NO_VOLUME_PREF)}}):e===V.NO_MUTED_PREF&&s!==t&&((p=oe(this,Ae))==null||p.dispatch({type:"optionschangerequest",detail:{noMutedPref:this.hasAttribute(V.NO_MUTED_PREF)}}))}connectedCallback(){var e,t;!oe(this,Ae)&&!this.hasAttribute(V.NO_DEFAULT_STORE)&&qi(this,El,dh).call(this),(e=oe(this,Ae))==null||e.dispatch({type:"documentelementchangerequest",detail:lt}),super.connectedCallback(),oe(this,Ae)&&!oe(this,Pi)&&Mi(this,Pi,(t=oe(this,Ae))==null?void 0:t.subscribe(oe(this,Aa))),oe(this,Sa)!==void 0&&oe(this,Ae)&&this.media&&setTimeout(()=>{var s,r,n;(r=(s=this.media)==null?void 0:s.textTracks)!=null&&r.length&&((n=oe(this,Ae))==null||n.dispatch({type:Q.MEDIA_TOGGLE_SUBTITLES_REQUEST,detail:oe(this,Sa)}))},0),this.hasAttribute(V.NO_HOTKEYS)?this.disableHotkeys():this.enableHotkeys()}disconnectedCallback(){var e,t,s,r,n;if((e=super.disconnectedCallback)==null||e.call(this),oe(this,Ae)){const a=oe(this,Ae).getState();Mi(this,Sa,!!((t=a.mediaSubtitlesShowing)!=null&&t.length)),(s=oe(this,Ae))==null||s.dispatch({type:"documentelementchangerequest",detail:void 0}),(r=oe(this,Ae))==null||r.dispatch({type:Q.MEDIA_TOGGLE_SUBTITLES_REQUEST,detail:!1})}oe(this,Pi)&&((n=oe(this,Pi))==null||n.call(this),Mi(this,Pi,void 0))}mediaSetCallback(e){var t;super.mediaSetCallback(e),(t=oe(this,Ae))==null||t.dispatch({type:"mediaelementchangerequest",detail:e}),e.hasAttribute("tabindex")||(e.tabIndex=-1)}mediaUnsetCallback(e){var t;super.mediaUnsetCallback(e),(t=oe(this,Ae))==null||t.dispatch({type:"mediaelementchangerequest",detail:void 0})}propagateMediaState(e,t){Xp(this.mediaStateReceivers,e,t)}associateElement(e){if(!e)return;const{associatedElementSubscriptions:t}=this;if(t.has(e))return;const s=this.registerMediaStateReceiver.bind(this),r=this.unregisterMediaStateReceiver.bind(this),n=JA(e,s,r);Object.values(Q).forEach(a=>{e.addEventListener(a,oe(this,vl))}),t.set(e,n)}unassociateElement(e){if(!e)return;const{associatedElementSubscriptions:t}=this;if(!t.has(e))return;t.get(e)(),t.delete(e),Object.values(Q).forEach(r=>{e.removeEventListener(r,oe(this,vl))})}registerMediaStateReceiver(e){if(!e)return;const t=this.mediaStateReceivers;t.indexOf(e)>-1||(t.push(e),oe(this,Ae)&&Object.entries(oe(this,Ae).getState()).forEach(([r,n])=>{Xp([e],r,n)}))}unregisterMediaStateReceiver(e){const t=this.mediaStateReceivers,s=t.indexOf(e);s<0||t.splice(s,1)}enableHotkeys(){this.addEventListener("keydown",qi(this,yl,uh))}disableHotkeys(){this.removeEventListener("keydown",qi(this,yl,uh)),this.removeEventListener("keyup",qi(this,Sr,On))}get hotkeys(){return He(this,V.HOTKEYS)}set hotkeys(e){Ge(this,V.HOTKEYS,e)}keyboardShortcutHandler(e){var t,s,r,n,a,o,l,d,u;const c=e.target;if(((r=(s=(t=c.getAttribute(V.KEYS_USED))==null?void 0:t.split(" "))!=null?s:c?.keysUsed)!=null?r:[]).map(v=>v==="Space"?" ":v).filter(Boolean).includes(e.key))return;let f,m,p;if(!(oe(this,Gs).contains(`no${e.key.toLowerCase()}`)||e.key===" "&&oe(this,Gs).contains("nospace")||e.shiftKey&&(e.key==="/"||e.key==="?")&&oe(this,Gs).contains("noshift+/")))switch(e.key){case" ":case"k":f=oe(this,Ae).getState().mediaPaused?Q.MEDIA_PLAY_REQUEST:Q.MEDIA_PAUSE_REQUEST,this.dispatchEvent(new k.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"m":f=this.mediaStore.getState().mediaVolumeLevel==="off"?Q.MEDIA_UNMUTE_REQUEST:Q.MEDIA_MUTE_REQUEST,this.dispatchEvent(new k.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"f":f=this.mediaStore.getState().mediaIsFullscreen?Q.MEDIA_EXIT_FULLSCREEN_REQUEST:Q.MEDIA_ENTER_FULLSCREEN_REQUEST,this.dispatchEvent(new k.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"c":this.dispatchEvent(new k.CustomEvent(Q.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:!0,bubbles:!0}));break;case"ArrowLeft":case"j":{const v=this.hasAttribute(V.KEYBOARD_BACKWARD_SEEK_OFFSET)?+this.getAttribute(V.KEYBOARD_BACKWARD_SEEK_OFFSET):qp;m=Math.max(((n=this.mediaStore.getState().mediaCurrentTime)!=null?n:0)-v,0),p=new k.CustomEvent(Q.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowRight":case"l":{const v=this.hasAttribute(V.KEYBOARD_FORWARD_SEEK_OFFSET)?+this.getAttribute(V.KEYBOARD_FORWARD_SEEK_OFFSET):qp;m=Math.max(((a=this.mediaStore.getState().mediaCurrentTime)!=null?a:0)+v,0),p=new k.CustomEvent(Q.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowUp":{const v=this.hasAttribute(V.KEYBOARD_UP_VOLUME_STEP)?+this.getAttribute(V.KEYBOARD_UP_VOLUME_STEP):Yp;m=Math.min(((o=this.mediaStore.getState().mediaVolume)!=null?o:1)+v,1),p=new k.CustomEvent(Q.MEDIA_VOLUME_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowDown":{const v=this.hasAttribute(V.KEYBOARD_DOWN_VOLUME_STEP)?+this.getAttribute(V.KEYBOARD_DOWN_VOLUME_STEP):Yp;m=Math.max(((l=this.mediaStore.getState().mediaVolume)!=null?l:1)-v,0),p=new k.CustomEvent(Q.MEDIA_VOLUME_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"<":{const v=(d=this.mediaStore.getState().mediaPlaybackRate)!=null?d:1;m=Math.max(v-jp,qA).toFixed(2),p=new k.CustomEvent(Q.MEDIA_PLAYBACK_RATE_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case">":{const v=(u=this.mediaStore.getState().mediaPlaybackRate)!=null?u:1;m=Math.min(v+jp,YA).toFixed(2),p=new k.CustomEvent(Q.MEDIA_PLAYBACK_RATE_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"/":case"?":{e.shiftKey&&qi(this,ch,vE).call(this);break}case"p":{f=this.mediaStore.getState().mediaIsPip?Q.MEDIA_EXIT_PIP_REQUEST:Q.MEDIA_ENTER_PIP_REQUEST,p=new k.CustomEvent(f,{composed:!0,bubbles:!0}),this.dispatchEvent(p);break}}}};Gs=new WeakMap;_a=new WeakMap;Ae=new WeakMap;yr=new WeakMap;Aa=new WeakMap;Pi=new WeakMap;vl=new WeakMap;Sa=new WeakMap;El=new WeakSet;dh=function(){var i;this.mediaStore=WA({media:this.media,fullscreenElement:this.fullscreenElement,options:{defaultSubtitles:this.hasAttribute(V.DEFAULT_SUBTITLES),defaultDuration:this.hasAttribute(V.DEFAULT_DURATION)?+this.getAttribute(V.DEFAULT_DURATION):void 0,defaultStreamType:(i=this.getAttribute(V.DEFAULT_STREAM_TYPE))!=null?i:void 0,liveEdgeOffset:this.hasAttribute(V.LIVE_EDGE_OFFSET)?+this.getAttribute(V.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(V.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(V.SEEK_TO_LIVE_OFFSET):this.hasAttribute(V.LIVE_EDGE_OFFSET)?+this.getAttribute(V.LIVE_EDGE_OFFSET):void 0,noAutoSeekToLive:this.hasAttribute(V.NO_AUTO_SEEK_TO_LIVE),noVolumePref:this.hasAttribute(V.NO_VOLUME_PREF),noMutedPref:this.hasAttribute(V.NO_MUTED_PREF),noSubtitlesLangPref:this.hasAttribute(V.NO_SUBTITLES_LANG_PREF)}})};Sr=new WeakSet;On=function(i){const{key:e,shiftKey:t}=i;if(!(t&&(e==="/"||e==="?")||EE.includes(e))){this.removeEventListener("keyup",qi(this,Sr,On));return}this.keyboardShortcutHandler(i)};yl=new WeakSet;uh=function(i){var e;const{metaKey:t,altKey:s,key:r,shiftKey:n}=i,a=n&&(r==="/"||r==="?");if(a&&((e=oe(this,yr))!=null&&e.open)){this.removeEventListener("keyup",qi(this,Sr,On));return}if(t||s||!a&&!EE.includes(r)){this.removeEventListener("keyup",qi(this,Sr,On));return}const o=i.target,l=o instanceof HTMLElement&&(o.tagName.toLowerCase()==="media-volume-range"||o.tagName.toLowerCase()==="media-time-range");[" ","ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(r)&&!(oe(this,Gs).contains(`no${r.toLowerCase()}`)||r===" "&&oe(this,Gs).contains("nospace"))&&!l&&i.preventDefault(),this.addEventListener("keyup",qi(this,Sr,On),{once:!0})};ch=new WeakSet;vE=function(){oe(this,yr)||(Mi(this,yr,lt.createElement("media-keyboard-shortcuts-dialog")),this.appendChild(oe(this,yr))),oe(this,yr).open=!0};const jA=Object.values(_),zA=Object.values(Vv),bE=i=>{var e,t,s,r;let{observedAttributes:n}=i.constructor;!n&&((e=i.nodeName)!=null&&e.includes("-"))&&(k.customElements.upgrade(i),{observedAttributes:n}=i.constructor);const a=(r=(s=(t=i?.getAttribute)==null?void 0:t.call(i,xe.MEDIA_CHROME_ATTRIBUTES))==null?void 0:s.split)==null?void 0:r.call(s,/\s+/);return Array.isArray(n||a)?(n||a).filter(o=>jA.includes(o)):[]},QA=i=>{var e,t;return(e=i.nodeName)!=null&&e.includes("-")&&k.customElements.get((t=i.nodeName)==null?void 0:t.toLowerCase())&&!(i instanceof k.customElements.get(i.nodeName.toLowerCase()))&&k.customElements.upgrade(i),zA.some(s=>s in i)},hh=i=>QA(i)||!!bE(i).length,zp=i=>{var e;return(e=i?.join)==null?void 0:e.call(i,":")},Qp={[_.MEDIA_SUBTITLES_LIST]:ao,[_.MEDIA_SUBTITLES_SHOWING]:ao,[_.MEDIA_SEEKABLE]:zp,[_.MEDIA_BUFFERED]:i=>i?.map(zp).join(" "),[_.MEDIA_PREVIEW_COORDS]:i=>i?.join(" "),[_.MEDIA_RENDITION_LIST]:z_,[_.MEDIA_AUDIO_TRACK_LIST]:J_},XA=async(i,e,t)=>{var s,r;if(i.isConnected||await Yv(0),typeof t=="boolean"||t==null)return be(i,e,t);if(typeof t=="number")return Xe(i,e,t);if(typeof t=="string")return Ge(i,e,t);if(Array.isArray(t)&&!t.length)return i.removeAttribute(e);const n=(r=(s=Qp[e])==null?void 0:s.call(Qp,t))!=null?r:t;return i.setAttribute(e,n)},ZA=i=>{var e;return!!((e=i.closest)!=null&&e.call(i,'*[slot="media"]'))},or=(i,e)=>{if(ZA(i))return;const t=(r,n)=>{var a,o;hh(r)&&n(r);const{children:l=[]}=r??{},d=(o=(a=r?.shadowRoot)==null?void 0:a.children)!=null?o:[];[...l,...d].forEach(c=>or(c,n))},s=i?.nodeName.toLowerCase();if(s.includes("-")&&!hh(i)){k.customElements.whenDefined(s).then(()=>{t(i,e)});return}t(i,e)},Xp=(i,e,t)=>{i.forEach(s=>{if(e in s){s[e]=t;return}const r=bE(s),n=e.toLowerCase();r.includes(n)&&XA(s,n,t)})},JA=(i,e,t)=>{or(i,e);const s=u=>{var c;const h=(c=u?.composedPath()[0])!=null?c:u.target;e(h)},r=u=>{var c;const h=(c=u?.composedPath()[0])!=null?c:u.target;t(h)};i.addEventListener(Q.REGISTER_MEDIA_STATE_RECEIVER,s),i.addEventListener(Q.UNREGISTER_MEDIA_STATE_RECEIVER,r);const n=u=>{u.forEach(c=>{const{addedNodes:h=[],removedNodes:f=[],type:m,target:p,attributeName:g}=c;m==="childList"?(Array.prototype.forEach.call(h,v=>or(v,e)),Array.prototype.forEach.call(f,v=>or(v,t))):m==="attributes"&&g===xe.MEDIA_CHROME_ATTRIBUTES&&(hh(p)?e(p):t(p))})};let a=[];const o=u=>{const c=u.target;c.name!=="media"&&(a.forEach(h=>or(h,t)),a=[...c.assignedElements({flatten:!0})],a.forEach(h=>or(h,e)))};i.addEventListener("slotchange",o);const l=new MutationObserver(n);return l.observe(i,{childList:!0,attributes:!0,subtree:!0}),()=>{or(i,t),i.removeEventListener("slotchange",o),l.disconnect(),i.removeEventListener(Q.REGISTER_MEDIA_STATE_RECEIVER,s),i.removeEventListener(Q.UNREGISTER_MEDIA_STATE_RECEIVER,r)}};k.customElements.get("media-controller")||k.customElements.define("media-controller",yE);var TE=yE;const Hr={PLACEMENT:"placement",BOUNDS:"bounds"};function eS(i){return`
|
|
160
160
|
<style>
|
|
161
161
|
:host {
|
|
162
162
|
--_tooltip-background-color: var(--media-tooltip-background-color, var(--media-secondary-color, rgba(20, 20, 30, .7)));
|
|
@@ -376,7 +376,7 @@ import{j as N}from"./jsx-runtime-C5WNSv3b.js";import{R as ve,r as Se}from"./inde
|
|
|
376
376
|
`}function oS(){return`
|
|
377
377
|
<slot name="tooltip-enter">${te("start airplay")}</slot>
|
|
378
378
|
<slot name="tooltip-exit">${te("stop airplay")}</slot>
|
|
379
|
-
`}const Jp=i=>{const e=i.mediaIsAirplaying?te("stop airplay"):te("start airplay");i.setAttribute("aria-label",e)};class Lu extends vt{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_IS_AIRPLAYING,_.MEDIA_AIRPLAY_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),Jp(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_IS_AIRPLAYING&&Jp(this)}get mediaIsAirplaying(){return ye(this,_.MEDIA_IS_AIRPLAYING)}set mediaIsAirplaying(e){be(this,_.MEDIA_IS_AIRPLAYING,e)}get mediaAirplayUnavailable(){return He(this,_.MEDIA_AIRPLAY_UNAVAILABLE)}set mediaAirplayUnavailable(e){Ge(this,_.MEDIA_AIRPLAY_UNAVAILABLE,e)}handleClick(){const e=new k.CustomEvent(
|
|
379
|
+
`}const Jp=i=>{const e=i.mediaIsAirplaying?te("stop airplay"):te("start airplay");i.setAttribute("aria-label",e)};class Lu extends vt{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_IS_AIRPLAYING,_.MEDIA_AIRPLAY_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),Jp(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_IS_AIRPLAYING&&Jp(this)}get mediaIsAirplaying(){return ye(this,_.MEDIA_IS_AIRPLAYING)}set mediaIsAirplaying(e){be(this,_.MEDIA_IS_AIRPLAYING,e)}get mediaAirplayUnavailable(){return He(this,_.MEDIA_AIRPLAY_UNAVAILABLE)}set mediaAirplayUnavailable(e){Ge(this,_.MEDIA_AIRPLAY_UNAVAILABLE,e)}handleClick(){const e=new k.CustomEvent(Q.MEDIA_AIRPLAY_REQUEST,{composed:!0,bubbles:!0});this.dispatchEvent(e)}}Lu.getSlotTemplateHTML=aS;Lu.getTooltipContentHTML=oS;k.customElements.get("media-airplay-button")||k.customElements.define("media-airplay-button",Lu);var lS=Lu;const dS=`<svg aria-hidden="true" viewBox="0 0 26 24">
|
|
380
380
|
<path d="M22.83 5.68a2.58 2.58 0 0 0-2.3-2.5c-3.62-.24-11.44-.24-15.06 0a2.58 2.58 0 0 0-2.3 2.5c-.23 4.21-.23 8.43 0 12.64a2.58 2.58 0 0 0 2.3 2.5c3.62.24 11.44.24 15.06 0a2.58 2.58 0 0 0 2.3-2.5c.23-4.21.23-8.43 0-12.64Zm-11.39 9.45a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.92 3.92 0 0 1 .92-2.77 3.18 3.18 0 0 1 2.43-1 2.94 2.94 0 0 1 2.13.78c.364.359.62.813.74 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.17 1.61 1.61 0 0 0-1.29.58 2.79 2.79 0 0 0-.5 1.89 3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.48 1.48 0 0 0 1-.37 2.1 2.1 0 0 0 .59-1.14l1.4.44a3.23 3.23 0 0 1-1.07 1.69Zm7.22 0a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.88 3.88 0 0 1 .93-2.77 3.14 3.14 0 0 1 2.42-1 3 3 0 0 1 2.16.82 2.8 2.8 0 0 1 .73 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.21 1.61 1.61 0 0 0-1.29.58A2.79 2.79 0 0 0 15 12a3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.44 1.44 0 0 0 1-.37 2.1 2.1 0 0 0 .6-1.15l1.4.44a3.17 3.17 0 0 1-1.1 1.7Z"/>
|
|
381
381
|
</svg>`,uS=`<svg aria-hidden="true" viewBox="0 0 26 24">
|
|
382
382
|
<path d="M17.73 14.09a1.4 1.4 0 0 1-1 .37 1.579 1.579 0 0 1-1.27-.58A3 3 0 0 1 15 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34A2.89 2.89 0 0 0 19 9.07a3 3 0 0 0-2.14-.78 3.14 3.14 0 0 0-2.42 1 3.91 3.91 0 0 0-.93 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.17 3.17 0 0 0 1.07-1.74l-1.4-.45c-.083.43-.3.822-.62 1.12Zm-7.22 0a1.43 1.43 0 0 1-1 .37 1.58 1.58 0 0 1-1.27-.58A3 3 0 0 1 7.76 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34a2.81 2.81 0 0 0-.74-1.32 2.94 2.94 0 0 0-2.13-.78 3.18 3.18 0 0 0-2.43 1 4 4 0 0 0-.92 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.23 3.23 0 0 0 1.07-1.74l-1.4-.45a2.06 2.06 0 0 1-.6 1.07Zm12.32-8.41a2.59 2.59 0 0 0-2.3-2.51C18.72 3.05 15.86 3 13 3c-2.86 0-5.72.05-7.53.17a2.59 2.59 0 0 0-2.3 2.51c-.23 4.207-.23 8.423 0 12.63a2.57 2.57 0 0 0 2.3 2.5c1.81.13 4.67.19 7.53.19 2.86 0 5.72-.06 7.53-.19a2.57 2.57 0 0 0 2.3-2.5c.23-4.207.23-8.423 0-12.63Zm-1.49 12.53a1.11 1.11 0 0 1-.91 1.11c-1.67.11-4.45.18-7.43.18-2.98 0-5.76-.07-7.43-.18a1.11 1.11 0 0 1-.91-1.11c-.21-4.14-.21-8.29 0-12.43a1.11 1.11 0 0 1 .91-1.11C7.24 4.56 10 4.49 13 4.49s5.76.07 7.43.18a1.11 1.11 0 0 1 .91 1.11c.21 4.14.21 8.29 0 12.43Z"/>
|
|
@@ -404,7 +404,7 @@ import{j as N}from"./jsx-runtime-C5WNSv3b.js";import{R as ve,r as Se}from"./inde
|
|
|
404
404
|
`}function hS(){return`
|
|
405
405
|
<slot name="tooltip-enable">${te("Enable captions")}</slot>
|
|
406
406
|
<slot name="tooltip-disable">${te("Disable captions")}</slot>
|
|
407
|
-
`}const eg=i=>{i.setAttribute("aria-checked",hE(i).toString())};class Ru extends vt{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_SUBTITLES_LIST,_.MEDIA_SUBTITLES_SHOWING]}connectedCallback(){super.connectedCallback(),this.setAttribute("role","switch"),this.setAttribute("aria-label",te("closed captions")),eg(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_SUBTITLES_SHOWING&&eg(this)}get mediaSubtitlesList(){return tg(this,_.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){ig(this,_.MEDIA_SUBTITLES_LIST,e)}get mediaSubtitlesShowing(){return tg(this,_.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){ig(this,_.MEDIA_SUBTITLES_SHOWING,e)}handleClick(){this.dispatchEvent(new k.CustomEvent(
|
|
407
|
+
`}const eg=i=>{i.setAttribute("aria-checked",hE(i).toString())};class Ru extends vt{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_SUBTITLES_LIST,_.MEDIA_SUBTITLES_SHOWING]}connectedCallback(){super.connectedCallback(),this.setAttribute("role","switch"),this.setAttribute("aria-label",te("closed captions")),eg(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_SUBTITLES_SHOWING&&eg(this)}get mediaSubtitlesList(){return tg(this,_.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){ig(this,_.MEDIA_SUBTITLES_LIST,e)}get mediaSubtitlesShowing(){return tg(this,_.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){ig(this,_.MEDIA_SUBTITLES_SHOWING,e)}handleClick(){this.dispatchEvent(new k.CustomEvent(Q.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:!0,bubbles:!0}))}}Ru.getSlotTemplateHTML=cS;Ru.getTooltipContentHTML=hS;const tg=(i,e)=>{const t=i.getAttribute(e);return t?Su(t):[]},ig=(i,e,t)=>{if(!t?.length){i.removeAttribute(e);return}const s=ao(t);i.getAttribute(e)!==s&&i.setAttribute(e,s)};k.customElements.get("media-captions-button")||k.customElements.define("media-captions-button",Ru);var fS=Ru;const mS='<svg aria-hidden="true" viewBox="0 0 24 24"><g><path class="cast_caf_icon_arch0" d="M1,18 L1,21 L4,21 C4,19.3 2.66,18 1,18 L1,18 Z"/><path class="cast_caf_icon_arch1" d="M1,14 L1,16 C3.76,16 6,18.2 6,21 L8,21 C8,17.13 4.87,14 1,14 L1,14 Z"/><path class="cast_caf_icon_arch2" d="M1,10 L1,12 C5.97,12 10,16.0 10,21 L12,21 C12,14.92 7.07,10 1,10 L1,10 Z"/><path class="cast_caf_icon_box" d="M21,3 L3,3 C1.9,3 1,3.9 1,5 L1,8 L3,8 L3,5 L21,5 L21,19 L14,19 L14,21 L21,21 C22.1,21 23,20.1 23,19 L23,5 C23,3.9 22.1,3 21,3 L21,3 Z"/></g></svg>',pS='<svg aria-hidden="true" viewBox="0 0 24 24"><g><path class="cast_caf_icon_arch0" d="M1,18 L1,21 L4,21 C4,19.3 2.66,18 1,18 L1,18 Z"/><path class="cast_caf_icon_arch1" d="M1,14 L1,16 C3.76,16 6,18.2 6,21 L8,21 C8,17.13 4.87,14 1,14 L1,14 Z"/><path class="cast_caf_icon_arch2" d="M1,10 L1,12 C5.97,12 10,16.0 10,21 L12,21 C12,14.92 7.07,10 1,10 L1,10 Z"/><path class="cast_caf_icon_box" d="M21,3 L3,3 C1.9,3 1,3.9 1,5 L1,8 L3,8 L3,5 L21,5 L21,19 L14,19 L14,21 L21,21 C22.1,21 23,20.1 23,19 L23,5 C23,3.9 22.1,3 21,3 L21,3 Z"/><path class="cast_caf_icon_boxfill" d="M5,7 L5,8.63 C8,8.6 13.37,14 13.37,17 L19,17 L19,7 Z"/></g></svg>';function gS(i){return`
|
|
408
408
|
<style>
|
|
409
409
|
:host([${_.MEDIA_IS_CASTING}]) slot[name=icon] slot:not([name=exit]) {
|
|
410
410
|
display: none !important;
|
|
@@ -428,7 +428,7 @@ import{j as N}from"./jsx-runtime-C5WNSv3b.js";import{R as ve,r as Se}from"./inde
|
|
|
428
428
|
`}function vS(){return`
|
|
429
429
|
<slot name="tooltip-enter">${te("Start casting")}</slot>
|
|
430
430
|
<slot name="tooltip-exit">${te("Stop casting")}</slot>
|
|
431
|
-
`}const sg=i=>{const e=i.mediaIsCasting?te("stop casting"):te("start casting");i.setAttribute("aria-label",e)};class ku extends vt{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_IS_CASTING,_.MEDIA_CAST_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),sg(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_IS_CASTING&&sg(this)}get mediaIsCasting(){return ye(this,_.MEDIA_IS_CASTING)}set mediaIsCasting(e){be(this,_.MEDIA_IS_CASTING,e)}get mediaCastUnavailable(){return He(this,_.MEDIA_CAST_UNAVAILABLE)}set mediaCastUnavailable(e){Ge(this,_.MEDIA_CAST_UNAVAILABLE,e)}handleClick(){const e=this.mediaIsCasting?
|
|
431
|
+
`}const sg=i=>{const e=i.mediaIsCasting?te("stop casting"):te("start casting");i.setAttribute("aria-label",e)};class ku extends vt{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_IS_CASTING,_.MEDIA_CAST_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),sg(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_IS_CASTING&&sg(this)}get mediaIsCasting(){return ye(this,_.MEDIA_IS_CASTING)}set mediaIsCasting(e){be(this,_.MEDIA_IS_CASTING,e)}get mediaCastUnavailable(){return He(this,_.MEDIA_CAST_UNAVAILABLE)}set mediaCastUnavailable(e){Ge(this,_.MEDIA_CAST_UNAVAILABLE,e)}handleClick(){const e=this.mediaIsCasting?Q.MEDIA_EXIT_CAST_REQUEST:Q.MEDIA_ENTER_CAST_REQUEST;this.dispatchEvent(new k.CustomEvent(e,{composed:!0,bubbles:!0}))}}ku.getSlotTemplateHTML=gS;ku.getTooltipContentHTML=vS;k.customElements.get("media-cast-button")||k.customElements.define("media-cast-button",ku);var ES=ku,cm=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Ir=(i,e,t)=>(cm(i,e,"read from private field"),e.get(i)),as=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},hm=(i,e,t,s)=>(cm(i,e,"write to private field"),e.set(i,t),t),er=(i,e,t)=>(cm(i,e,"access private method"),t),Od,oo,wr,Tl,ph,gh,AE,vh,SE,Eh,IE,yh,xE,bh,LE;function yS(i){return`
|
|
432
432
|
<style>
|
|
433
433
|
:host {
|
|
434
434
|
font: var(--media-font,
|
|
@@ -909,7 +909,7 @@ import{j as N}from"./jsx-runtime-C5WNSv3b.js";import{R as ve,r as Se}from"./inde
|
|
|
909
909
|
`}function JS(){return`
|
|
910
910
|
<slot name="tooltip-enter">${te("Enter fullscreen mode")}</slot>
|
|
911
911
|
<slot name="tooltip-exit">${te("Exit fullscreen mode")}</slot>
|
|
912
|
-
`}const og=i=>{const e=i.mediaIsFullscreen?te("exit fullscreen mode"):te("enter fullscreen mode");i.setAttribute("aria-label",e)};let Mu=class extends vt{constructor(){super(...arguments),jS(this,Dl,null)}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_IS_FULLSCREEN,_.MEDIA_FULLSCREEN_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),og(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_IS_FULLSCREEN&&og(this)}get mediaFullscreenUnavailable(){return He(this,_.MEDIA_FULLSCREEN_UNAVAILABLE)}set mediaFullscreenUnavailable(e){Ge(this,_.MEDIA_FULLSCREEN_UNAVAILABLE,e)}get mediaIsFullscreen(){return ye(this,_.MEDIA_IS_FULLSCREEN)}set mediaIsFullscreen(e){be(this,_.MEDIA_IS_FULLSCREEN,e)}handleClick(e){zS(this,Dl,e);const t=YS(this,Dl)instanceof PointerEvent,s=this.mediaIsFullscreen?new k.CustomEvent(
|
|
912
|
+
`}const og=i=>{const e=i.mediaIsFullscreen?te("exit fullscreen mode"):te("enter fullscreen mode");i.setAttribute("aria-label",e)};let Mu=class extends vt{constructor(){super(...arguments),jS(this,Dl,null)}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_IS_FULLSCREEN,_.MEDIA_FULLSCREEN_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),og(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_IS_FULLSCREEN&&og(this)}get mediaFullscreenUnavailable(){return He(this,_.MEDIA_FULLSCREEN_UNAVAILABLE)}set mediaFullscreenUnavailable(e){Ge(this,_.MEDIA_FULLSCREEN_UNAVAILABLE,e)}get mediaIsFullscreen(){return ye(this,_.MEDIA_IS_FULLSCREEN)}set mediaIsFullscreen(e){be(this,_.MEDIA_IS_FULLSCREEN,e)}handleClick(e){zS(this,Dl,e);const t=YS(this,Dl)instanceof PointerEvent,s=this.mediaIsFullscreen?new k.CustomEvent(Q.MEDIA_EXIT_FULLSCREEN_REQUEST,{composed:!0,bubbles:!0}):new k.CustomEvent(Q.MEDIA_ENTER_FULLSCREEN_REQUEST,{composed:!0,bubbles:!0,detail:t});this.dispatchEvent(s)}};Dl=new WeakMap;Mu.getSlotTemplateHTML=ZS;Mu.getTooltipContentHTML=JS;k.customElements.get("media-fullscreen-button")||k.customElements.define("media-fullscreen-button",Mu);var e1=Mu;const{MEDIA_TIME_IS_LIVE:Cl,MEDIA_PAUSED:Wa}=_,{MEDIA_SEEK_TO_LIVE_REQUEST:t1,MEDIA_PLAY_REQUEST:i1}=Q,s1='<svg viewBox="0 0 6 12"><circle cx="3" cy="6" r="2"></circle></svg>';function r1(i){return`
|
|
913
913
|
<style>
|
|
914
914
|
:host { --media-tooltip-display: none; }
|
|
915
915
|
|
|
@@ -1040,7 +1040,7 @@ import{j as N}from"./jsx-runtime-C5WNSv3b.js";import{R as ve,r as Se}from"./inde
|
|
|
1040
1040
|
`}function h1(){return`
|
|
1041
1041
|
<slot name="tooltip-mute">${te("Mute")}</slot>
|
|
1042
1042
|
<slot name="tooltip-unmute">${te("Unmute")}</slot>
|
|
1043
|
-
`}const cg=i=>{const e=i.mediaVolumeLevel==="off",t=te(e?"unmute":"mute");i.setAttribute("aria-label",t)};let Ou=class extends vt{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_VOLUME_LEVEL]}connectedCallback(){super.connectedCallback(),cg(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_VOLUME_LEVEL&&cg(this)}get mediaVolumeLevel(){return He(this,_.MEDIA_VOLUME_LEVEL)}set mediaVolumeLevel(e){Ge(this,_.MEDIA_VOLUME_LEVEL,e)}handleClick(){const e=this.mediaVolumeLevel==="off"?
|
|
1043
|
+
`}const cg=i=>{const e=i.mediaVolumeLevel==="off",t=te(e?"unmute":"mute");i.setAttribute("aria-label",t)};let Ou=class extends vt{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_VOLUME_LEVEL]}connectedCallback(){super.connectedCallback(),cg(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_VOLUME_LEVEL&&cg(this)}get mediaVolumeLevel(){return He(this,_.MEDIA_VOLUME_LEVEL)}set mediaVolumeLevel(e){Ge(this,_.MEDIA_VOLUME_LEVEL,e)}handleClick(){const e=this.mediaVolumeLevel==="off"?Q.MEDIA_UNMUTE_REQUEST:Q.MEDIA_MUTE_REQUEST;this.dispatchEvent(new k.CustomEvent(e,{composed:!0,bubbles:!0}))}};Ou.getSlotTemplateHTML=c1;Ou.getTooltipContentHTML=h1;k.customElements.get("media-mute-button")||k.customElements.define("media-mute-button",Ou);var f1=Ou;const hg=`<svg aria-hidden="true" viewBox="0 0 28 24">
|
|
1044
1044
|
<path d="M24 3H4a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h20a1 1 0 0 0 1-1V4a1 1 0 0 0-1-1Zm-1 16H5V5h18v14Zm-3-8h-7v5h7v-5Z"/>
|
|
1045
1045
|
</svg>`;function m1(i){return`
|
|
1046
1046
|
<style>
|
|
@@ -1065,7 +1065,7 @@ import{j as N}from"./jsx-runtime-C5WNSv3b.js";import{R as ve,r as Se}from"./inde
|
|
|
1065
1065
|
`}function p1(){return`
|
|
1066
1066
|
<slot name="tooltip-enter">${te("Enter picture in picture mode")}</slot>
|
|
1067
1067
|
<slot name="tooltip-exit">${te("Exit picture in picture mode")}</slot>
|
|
1068
|
-
`}const fg=i=>{const e=i.mediaIsPip?te("exit picture in picture mode"):te("enter picture in picture mode");i.setAttribute("aria-label",e)};let Nu=class extends vt{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_IS_PIP,_.MEDIA_PIP_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),fg(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_IS_PIP&&fg(this)}get mediaPipUnavailable(){return He(this,_.MEDIA_PIP_UNAVAILABLE)}set mediaPipUnavailable(e){Ge(this,_.MEDIA_PIP_UNAVAILABLE,e)}get mediaIsPip(){return ye(this,_.MEDIA_IS_PIP)}set mediaIsPip(e){be(this,_.MEDIA_IS_PIP,e)}handleClick(){const e=this.mediaIsPip?
|
|
1068
|
+
`}const fg=i=>{const e=i.mediaIsPip?te("exit picture in picture mode"):te("enter picture in picture mode");i.setAttribute("aria-label",e)};let Nu=class extends vt{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_IS_PIP,_.MEDIA_PIP_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),fg(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_IS_PIP&&fg(this)}get mediaPipUnavailable(){return He(this,_.MEDIA_PIP_UNAVAILABLE)}set mediaPipUnavailable(e){Ge(this,_.MEDIA_PIP_UNAVAILABLE,e)}get mediaIsPip(){return ye(this,_.MEDIA_IS_PIP)}set mediaIsPip(e){be(this,_.MEDIA_IS_PIP,e)}handleClick(){const e=this.mediaIsPip?Q.MEDIA_EXIT_PIP_REQUEST:Q.MEDIA_ENTER_PIP_REQUEST;this.dispatchEvent(new k.CustomEvent(e,{composed:!0,bubbles:!0}))}};Nu.getSlotTemplateHTML=m1;Nu.getTooltipContentHTML=p1;k.customElements.get("media-pip-button")||k.customElements.define("media-pip-button",Nu);var g1=Nu,v1=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Kr=(i,e,t)=>(v1(i,e,"read from private field"),t?t.call(i):e.get(i)),E1=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Ms;const dc={RATES:"rates"},GE=[1,1.2,1.5,1.7,2],Dn=1;function y1(i){return`
|
|
1069
1069
|
<style>
|
|
1070
1070
|
:host {
|
|
1071
1071
|
min-width: 5ch;
|
|
@@ -1073,7 +1073,7 @@ import{j as N}from"./jsx-runtime-C5WNSv3b.js";import{R as ve,r as Se}from"./inde
|
|
|
1073
1073
|
}
|
|
1074
1074
|
</style>
|
|
1075
1075
|
<slot name="icon">${i.mediaplaybackrate||Dn}x</slot>
|
|
1076
|
-
`}function b1(){return te("Playback rate")}let Uu=class extends vt{constructor(){var e;super(),E1(this,Ms,new am(this,dc.RATES,{defaultValue:GE})),this.container=this.shadowRoot.querySelector('slot[name="icon"]'),this.container.innerHTML=`${(e=this.mediaPlaybackRate)!=null?e:Dn}x`}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PLAYBACK_RATE,dc.RATES]}attributeChangedCallback(e,t,s){if(super.attributeChangedCallback(e,t,s),e===dc.RATES&&(Kr(this,Ms).value=s),e===_.MEDIA_PLAYBACK_RATE){const r=s?+s:Number.NaN,n=Number.isNaN(r)?Dn:r;this.container.innerHTML=`${n}x`,this.setAttribute("aria-label",te("Playback rate {playbackRate}",{playbackRate:n}))}}get rates(){return Kr(this,Ms)}set rates(e){e?Array.isArray(e)?Kr(this,Ms).value=e.join(" "):typeof e=="string"&&(Kr(this,Ms).value=e):Kr(this,Ms).value=""}get mediaPlaybackRate(){return Be(this,_.MEDIA_PLAYBACK_RATE,Dn)}set mediaPlaybackRate(e){Xe(this,_.MEDIA_PLAYBACK_RATE,e)}handleClick(){var e,t;const s=Array.from(Kr(this,Ms).values(),a=>+a).sort((a,o)=>a-o),r=(t=(e=s.find(a=>a>this.mediaPlaybackRate))!=null?e:s[0])!=null?t:Dn,n=new k.CustomEvent(
|
|
1076
|
+
`}function b1(){return te("Playback rate")}let Uu=class extends vt{constructor(){var e;super(),E1(this,Ms,new am(this,dc.RATES,{defaultValue:GE})),this.container=this.shadowRoot.querySelector('slot[name="icon"]'),this.container.innerHTML=`${(e=this.mediaPlaybackRate)!=null?e:Dn}x`}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PLAYBACK_RATE,dc.RATES]}attributeChangedCallback(e,t,s){if(super.attributeChangedCallback(e,t,s),e===dc.RATES&&(Kr(this,Ms).value=s),e===_.MEDIA_PLAYBACK_RATE){const r=s?+s:Number.NaN,n=Number.isNaN(r)?Dn:r;this.container.innerHTML=`${n}x`,this.setAttribute("aria-label",te("Playback rate {playbackRate}",{playbackRate:n}))}}get rates(){return Kr(this,Ms)}set rates(e){e?Array.isArray(e)?Kr(this,Ms).value=e.join(" "):typeof e=="string"&&(Kr(this,Ms).value=e):Kr(this,Ms).value=""}get mediaPlaybackRate(){return Be(this,_.MEDIA_PLAYBACK_RATE,Dn)}set mediaPlaybackRate(e){Xe(this,_.MEDIA_PLAYBACK_RATE,e)}handleClick(){var e,t;const s=Array.from(Kr(this,Ms).values(),a=>+a).sort((a,o)=>a-o),r=(t=(e=s.find(a=>a>this.mediaPlaybackRate))!=null?e:s[0])!=null?t:Dn,n=new k.CustomEvent(Q.MEDIA_PLAYBACK_RATE_REQUEST,{composed:!0,bubbles:!0,detail:r});this.dispatchEvent(n)}};Ms=new WeakMap;Uu.getSlotTemplateHTML=y1;Uu.getTooltipContentHTML=b1;k.customElements.get("media-playback-rate-button")||k.customElements.define("media-playback-rate-button",Uu);var T1=Uu;const _1=`<svg aria-hidden="true" viewBox="0 0 24 24">
|
|
1077
1077
|
<path d="m6 21 15-9L6 3v18Z"/>
|
|
1078
1078
|
</svg>`,A1=`<svg aria-hidden="true" viewBox="0 0 24 24">
|
|
1079
1079
|
<path d="M6 20h4V4H6v16Zm8-16v16h4V4h-4Z"/>
|
|
@@ -1097,7 +1097,7 @@ import{j as N}from"./jsx-runtime-C5WNSv3b.js";import{R as ve,r as Se}from"./inde
|
|
|
1097
1097
|
`}function I1(){return`
|
|
1098
1098
|
<slot name="tooltip-play">${te("Play")}</slot>
|
|
1099
1099
|
<slot name="tooltip-pause">${te("Pause")}</slot>
|
|
1100
|
-
`}const mg=i=>{const e=i.mediaPaused?te("play"):te("pause");i.setAttribute("aria-label",e)};let $u=class extends vt{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PAUSED,_.MEDIA_ENDED]}connectedCallback(){super.connectedCallback(),mg(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),(e===_.MEDIA_PAUSED||e===_.MEDIA_LANG)&&mg(this)}get mediaPaused(){return ye(this,_.MEDIA_PAUSED)}set mediaPaused(e){be(this,_.MEDIA_PAUSED,e)}handleClick(){const e=this.mediaPaused?
|
|
1100
|
+
`}const mg=i=>{const e=i.mediaPaused?te("play"):te("pause");i.setAttribute("aria-label",e)};let $u=class extends vt{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PAUSED,_.MEDIA_ENDED]}connectedCallback(){super.connectedCallback(),mg(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),(e===_.MEDIA_PAUSED||e===_.MEDIA_LANG)&&mg(this)}get mediaPaused(){return ye(this,_.MEDIA_PAUSED)}set mediaPaused(e){be(this,_.MEDIA_PAUSED,e)}handleClick(){const e=this.mediaPaused?Q.MEDIA_PLAY_REQUEST:Q.MEDIA_PAUSE_REQUEST;this.dispatchEvent(new k.CustomEvent(e,{composed:!0,bubbles:!0}))}};$u.getSlotTemplateHTML=S1;$u.getTooltipContentHTML=I1;k.customElements.get("media-play-button")||k.customElements.define("media-play-button",$u);var x1=$u;const Li={PLACEHOLDER_SRC:"placeholdersrc",SRC:"src"};function L1(i){return`
|
|
1101
1101
|
<style>
|
|
1102
1102
|
:host {
|
|
1103
1103
|
pointer-events: none;
|
|
@@ -1142,7 +1142,7 @@ import{j as N}from"./jsx-runtime-C5WNSv3b.js";import{R as ve,r as Se}from"./inde
|
|
|
1142
1142
|
<path d="M10 6V3L4.37 7 10 10.94V8a5.54 5.54 0 0 1 1.9 10.48v2.12A7.5 7.5 0 0 0 10 6Z"/>
|
|
1143
1143
|
</svg>`;function H1(i,e){return`
|
|
1144
1144
|
<slot name="icon">${B1(e.seekOffset)}</slot>
|
|
1145
|
-
`}function G1(){return te("Seek backward")}const K1=0;let Hu=class extends vt{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_CURRENT_TIME,Vr.SEEK_OFFSET]}connectedCallback(){super.connectedCallback(),this.seekOffset=Be(this,Vr.SEEK_OFFSET,uc)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===Vr.SEEK_OFFSET&&(this.seekOffset=Be(this,Vr.SEEK_OFFSET,uc))}get seekOffset(){return Be(this,Vr.SEEK_OFFSET,uc)}set seekOffset(e){Xe(this,Vr.SEEK_OFFSET,e),this.setAttribute("aria-label",te("seek back {seekOffset} seconds",{seekOffset:this.seekOffset})),eE(tE(this,"icon"),this.seekOffset)}get mediaCurrentTime(){return Be(this,_.MEDIA_CURRENT_TIME,K1)}set mediaCurrentTime(e){Xe(this,_.MEDIA_CURRENT_TIME,e)}handleClick(){const e=Math.max(this.mediaCurrentTime-this.seekOffset,0),t=new k.CustomEvent(
|
|
1145
|
+
`}function G1(){return te("Seek backward")}const K1=0;let Hu=class extends vt{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_CURRENT_TIME,Vr.SEEK_OFFSET]}connectedCallback(){super.connectedCallback(),this.seekOffset=Be(this,Vr.SEEK_OFFSET,uc)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===Vr.SEEK_OFFSET&&(this.seekOffset=Be(this,Vr.SEEK_OFFSET,uc))}get seekOffset(){return Be(this,Vr.SEEK_OFFSET,uc)}set seekOffset(e){Xe(this,Vr.SEEK_OFFSET,e),this.setAttribute("aria-label",te("seek back {seekOffset} seconds",{seekOffset:this.seekOffset})),eE(tE(this,"icon"),this.seekOffset)}get mediaCurrentTime(){return Be(this,_.MEDIA_CURRENT_TIME,K1)}set mediaCurrentTime(e){Xe(this,_.MEDIA_CURRENT_TIME,e)}handleClick(){const e=Math.max(this.mediaCurrentTime-this.seekOffset,0),t=new k.CustomEvent(Q.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:e});this.dispatchEvent(t)}};Hu.getSlotTemplateHTML=H1;Hu.getTooltipContentHTML=G1;k.customElements.get("media-seek-backward-button")||k.customElements.define("media-seek-backward-button",Hu);var V1=Hu;const Wr={SEEK_OFFSET:"seekoffset"},cc=30,W1=i=>`
|
|
1146
1146
|
<svg aria-hidden="true" viewBox="0 0 20 24">
|
|
1147
1147
|
<defs>
|
|
1148
1148
|
<style>.text{font-size:8px;font-family:Arial-BoldMT, Arial;font-weight:700;}</style>
|
|
@@ -1151,7 +1151,7 @@ import{j as N}from"./jsx-runtime-C5WNSv3b.js";import{R as ve,r as Se}from"./inde
|
|
|
1151
1151
|
<path d="M10 6V3l5.61 4L10 10.94V8a5.54 5.54 0 0 0-1.9 10.48v2.12A7.5 7.5 0 0 1 10 6Z"/>
|
|
1152
1152
|
</svg>`;function q1(i,e){return`
|
|
1153
1153
|
<slot name="icon">${W1(e.seekOffset)}</slot>
|
|
1154
|
-
`}function Y1(){return te("Seek forward")}const j1=0;let Gu=class extends vt{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_CURRENT_TIME,Wr.SEEK_OFFSET]}connectedCallback(){super.connectedCallback(),this.seekOffset=Be(this,Wr.SEEK_OFFSET,cc)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===Wr.SEEK_OFFSET&&(this.seekOffset=Be(this,Wr.SEEK_OFFSET,cc))}get seekOffset(){return Be(this,Wr.SEEK_OFFSET,cc)}set seekOffset(e){Xe(this,Wr.SEEK_OFFSET,e),this.setAttribute("aria-label",te("seek forward {seekOffset} seconds",{seekOffset:this.seekOffset})),eE(tE(this,"icon"),this.seekOffset)}get mediaCurrentTime(){return Be(this,_.MEDIA_CURRENT_TIME,j1)}set mediaCurrentTime(e){Xe(this,_.MEDIA_CURRENT_TIME,e)}handleClick(){const e=this.mediaCurrentTime+this.seekOffset,t=new k.CustomEvent(
|
|
1154
|
+
`}function Y1(){return te("Seek forward")}const j1=0;let Gu=class extends vt{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_CURRENT_TIME,Wr.SEEK_OFFSET]}connectedCallback(){super.connectedCallback(),this.seekOffset=Be(this,Wr.SEEK_OFFSET,cc)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===Wr.SEEK_OFFSET&&(this.seekOffset=Be(this,Wr.SEEK_OFFSET,cc))}get seekOffset(){return Be(this,Wr.SEEK_OFFSET,cc)}set seekOffset(e){Xe(this,Wr.SEEK_OFFSET,e),this.setAttribute("aria-label",te("seek forward {seekOffset} seconds",{seekOffset:this.seekOffset})),eE(tE(this,"icon"),this.seekOffset)}get mediaCurrentTime(){return Be(this,_.MEDIA_CURRENT_TIME,j1)}set mediaCurrentTime(e){Xe(this,_.MEDIA_CURRENT_TIME,e)}handleClick(){const e=this.mediaCurrentTime+this.seekOffset,t=new k.CustomEvent(Q.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:e});this.dispatchEvent(t)}};Gu.getSlotTemplateHTML=q1;Gu.getTooltipContentHTML=Y1;k.customElements.get("media-seek-forward-button")||k.customElements.define("media-seek-forward-button",Gu);var z1=Gu,jE=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},hc=(i,e,t)=>(jE(i,e,"read from private field"),t?t.call(i):e.get(i)),Q1=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},X1=(i,e,t,s)=>(jE(i,e,"write to private field"),e.set(i,t),t),on;const lr={REMAINING:"remaining",SHOW_DURATION:"showduration",NO_TOGGLE:"notoggle"},gg=[...Object.values(lr),_.MEDIA_CURRENT_TIME,_.MEDIA_DURATION,_.MEDIA_SEEKABLE],vg=["Enter"," "],Z1=" / ",Rh=(i,{timesSep:e=Z1}={})=>{var t,s;const r=(t=i.mediaCurrentTime)!=null?t:0,[,n]=(s=i.mediaSeekable)!=null?s:[];let a=0;Number.isFinite(i.mediaDuration)?a=i.mediaDuration:Number.isFinite(n)&&(a=n);const o=i.remaining?qs(0-(a-r)):qs(r);return i.showDuration?`${o}${e}${qs(a)}`:o},J1="video not loaded, unknown time.",eI=i=>{var e;const t=i.mediaCurrentTime,[,s]=(e=i.mediaSeekable)!=null?e:[];let r=null;if(Number.isFinite(i.mediaDuration)?r=i.mediaDuration:Number.isFinite(s)&&(r=s),t==null||r===null){i.setAttribute("aria-valuetext",J1);return}const n=i.remaining?Ka(0-(r-t)):Ka(t);if(!i.showDuration){i.setAttribute("aria-valuetext",n);return}const a=Ka(r),o=`${n} of ${a}`;i.setAttribute("aria-valuetext",o)};function tI(i,e){return`
|
|
1155
1155
|
<slot>${Rh(e)}</slot>
|
|
1156
1156
|
`}let bm=class extends _s{constructor(){super(),Q1(this,on,void 0),X1(this,on,this.shadowRoot.querySelector("slot")),hc(this,on).innerHTML=`${Rh(this)}`}static get observedAttributes(){return[...super.observedAttributes,...gg,"disabled"]}connectedCallback(){const{style:e}=pt(this.shadowRoot,":host(:hover:not([notoggle]))");e.setProperty("cursor","var(--media-cursor, pointer)"),e.setProperty("background","var(--media-control-hover-background, rgba(50 50 70 / .7))"),this.hasAttribute("disabled")||this.enable(),this.setAttribute("role","progressbar"),this.setAttribute("aria-label",te("playback time"));const t=s=>{const{key:r}=s;if(!vg.includes(r)){this.removeEventListener("keyup",t);return}this.toggleTimeDisplay()};this.addEventListener("keydown",s=>{const{metaKey:r,altKey:n,key:a}=s;if(r||n||!vg.includes(a)){this.removeEventListener("keyup",t);return}this.addEventListener("keyup",t)}),this.addEventListener("click",this.toggleTimeDisplay),super.connectedCallback()}toggleTimeDisplay(){this.noToggle||(this.hasAttribute("remaining")?this.removeAttribute("remaining"):this.setAttribute("remaining",""))}disconnectedCallback(){this.disable(),super.disconnectedCallback()}attributeChangedCallback(e,t,s){gg.includes(e)?this.update():e==="disabled"&&s!==t&&(s==null?this.enable():this.disable()),super.attributeChangedCallback(e,t,s)}enable(){this.tabIndex=0}disable(){this.tabIndex=-1}get remaining(){return ye(this,lr.REMAINING)}set remaining(e){be(this,lr.REMAINING,e)}get showDuration(){return ye(this,lr.SHOW_DURATION)}set showDuration(e){be(this,lr.SHOW_DURATION,e)}get noToggle(){return ye(this,lr.NO_TOGGLE)}set noToggle(e){be(this,lr.NO_TOGGLE,e)}get mediaDuration(){return Be(this,_.MEDIA_DURATION)}set mediaDuration(e){Xe(this,_.MEDIA_DURATION,e)}get mediaCurrentTime(){return Be(this,_.MEDIA_CURRENT_TIME)}set mediaCurrentTime(e){Xe(this,_.MEDIA_CURRENT_TIME,e)}get mediaSeekable(){const e=this.getAttribute(_.MEDIA_SEEKABLE);if(e)return e.split(":").map(t=>+t)}set mediaSeekable(e){if(e==null){this.removeAttribute(_.MEDIA_SEEKABLE);return}this.setAttribute(_.MEDIA_SEEKABLE,e.join(":"))}update(){const e=Rh(this);eI(this),e!==hc(this,on).innerHTML&&(hc(this,on).innerHTML=e)}};on=new WeakMap;bm.getSlotTemplateHTML=tI;k.customElements.get("media-time-display")||k.customElements.define("media-time-display",bm);var iI=bm,zE=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},yt=(i,e,t)=>(zE(i,e,"read from private field"),e.get(i)),Ri=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Kt=(i,e,t,s)=>(zE(i,e,"write to private field"),e.set(i,t),t),sI=(i,e,t,s)=>({set _(r){Kt(i,e,r)},get _(){return yt(i,e)}}),ln,Pl,dn,La,Ol,Nl,Ul,un,dr,$l;class rI{constructor(e,t,s){Ri(this,ln,void 0),Ri(this,Pl,void 0),Ri(this,dn,void 0),Ri(this,La,void 0),Ri(this,Ol,void 0),Ri(this,Nl,void 0),Ri(this,Ul,void 0),Ri(this,un,void 0),Ri(this,dr,0),Ri(this,$l,(r=performance.now())=>{Kt(this,dr,requestAnimationFrame(yt(this,$l))),Kt(this,La,performance.now()-yt(this,dn));const n=1e3/this.fps;if(yt(this,La)>n){Kt(this,dn,r-yt(this,La)%n);const a=1e3/((r-yt(this,Pl))/++sI(this,Ol)._),o=(r-yt(this,Nl))/1e3/this.duration;let l=yt(this,Ul)+o*this.playbackRate;l-yt(this,ln).valueAsNumber>0?Kt(this,un,this.playbackRate/this.duration/a):(Kt(this,un,.995*yt(this,un)),l=yt(this,ln).valueAsNumber+yt(this,un)),this.callback(l)}}),Kt(this,ln,e),this.callback=t,this.fps=s}start(){yt(this,dr)===0&&(Kt(this,dn,performance.now()),Kt(this,Pl,yt(this,dn)),Kt(this,Ol,0),yt(this,$l).call(this))}stop(){yt(this,dr)!==0&&(cancelAnimationFrame(yt(this,dr)),Kt(this,dr,0))}update({start:e,duration:t,playbackRate:s}){const r=e-yt(this,ln).valueAsNumber,n=Math.abs(t-this.duration);(r>0||r<-.03||n>=.5)&&this.callback(e),Kt(this,Ul,e),Kt(this,Nl,performance.now()),this.duration=t,this.playbackRate=s}}ln=new WeakMap;Pl=new WeakMap;dn=new WeakMap;La=new WeakMap;Ol=new WeakMap;Nl=new WeakMap;Ul=new WeakMap;un=new WeakMap;dr=new WeakMap;$l=new WeakMap;var Tm=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Je=(i,e,t)=>(Tm(i,e,"read from private field"),t?t.call(i):e.get(i)),ht=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},si=(i,e,t,s)=>(Tm(i,e,"write to private field"),e.set(i,t),t),kt=(i,e,t)=>(Tm(i,e,"access private method"),t),cn,xr,$d,qa,Fd,Fl,lo,uo,hn,fn,mn,Ra,_m,QE,kh,Bd,Am,Hd,Sm,Gd,Im,Dh,XE,co,Kd,Ch,ZE;const nI="video not loaded, unknown time.",aI=i=>{const e=i.range,t=Ka(+JE(i)),s=Ka(+i.mediaSeekableEnd),r=t&&s?`${t} of ${s}`:nI;e.setAttribute("aria-valuetext",r)};function oI(i){return`
|
|
1157
1157
|
<style>
|
|
@@ -1370,7 +1370,7 @@ import{j as N}from"./jsx-runtime-C5WNSv3b.js";import{R as ve,r as Se}from"./inde
|
|
|
1370
1370
|
|
|
1371
1371
|
</slot>
|
|
1372
1372
|
</div>
|
|
1373
|
-
`}const Vo=(i,e=i.mediaCurrentTime)=>{const t=Number.isFinite(i.mediaSeekableStart)?i.mediaSeekableStart:0,s=Number.isFinite(i.mediaDuration)?i.mediaDuration:i.mediaSeekableEnd;if(Number.isNaN(s))return 0;const r=(e-t)/(s-t);return Math.max(0,Math.min(r,1))},JE=(i,e=i.range.valueAsNumber)=>{const t=Number.isFinite(i.mediaSeekableStart)?i.mediaSeekableStart:0,s=Number.isFinite(i.mediaDuration)?i.mediaDuration:i.mediaSeekableEnd;return Number.isNaN(s)?0:e*(s-t)+t};let Ku=class extends Or{constructor(){super(),ht(this,mn),ht(this,_m),ht(this,Bd),ht(this,Hd),ht(this,Gd),ht(this,Dh),ht(this,co),ht(this,Ch),ht(this,cn,void 0),ht(this,xr,void 0),ht(this,$d,void 0),ht(this,qa,void 0),ht(this,Fd,void 0),ht(this,Fl,void 0),ht(this,lo,void 0),ht(this,uo,void 0),ht(this,hn,void 0),ht(this,fn,void 0),ht(this,kh,s=>{this.dragging||(em(s)&&(this.range.valueAsNumber=s),Je(this,fn)||this.updateBar())}),this.shadowRoot.querySelector("#track").insertAdjacentHTML("afterbegin",'<div id="buffered" part="buffered"></div>'),si(this,$d,this.shadowRoot.querySelectorAll('[part~="box"]')),si(this,Fd,this.shadowRoot.querySelector('[part~="preview-box"]')),si(this,Fl,this.shadowRoot.querySelector('[part~="current-box"]'));const t=getComputedStyle(this);si(this,lo,parseInt(t.getPropertyValue("--media-box-padding-left"))),si(this,uo,parseInt(t.getPropertyValue("--media-box-padding-right"))),si(this,xr,new rI(this.range,Je(this,kh),60))}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PAUSED,_.MEDIA_DURATION,_.MEDIA_SEEKABLE,_.MEDIA_CURRENT_TIME,_.MEDIA_PREVIEW_IMAGE,_.MEDIA_PREVIEW_TIME,_.MEDIA_PREVIEW_CHAPTER,_.MEDIA_BUFFERED,_.MEDIA_PLAYBACK_RATE,_.MEDIA_LOADING,_.MEDIA_ENDED]}connectedCallback(){var e;super.connectedCallback(),this.range.setAttribute("aria-label",te("seek")),kt(this,mn,Ra).call(this),si(this,cn,this.getRootNode()),(e=Je(this,cn))==null||e.addEventListener("transitionstart",this)}disconnectedCallback(){var e;super.disconnectedCallback(),kt(this,mn,Ra).call(this),(e=Je(this,cn))==null||e.removeEventListener("transitionstart",this),si(this,cn,null)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),t!=s&&(e===_.MEDIA_CURRENT_TIME||e===_.MEDIA_PAUSED||e===_.MEDIA_ENDED||e===_.MEDIA_LOADING||e===_.MEDIA_DURATION||e===_.MEDIA_SEEKABLE?(Je(this,xr).update({start:Vo(this),duration:this.mediaSeekableEnd-this.mediaSeekableStart,playbackRate:this.mediaPlaybackRate}),kt(this,mn,Ra).call(this),aI(this)):e===_.MEDIA_BUFFERED&&this.updateBufferedBar(),(e===_.MEDIA_DURATION||e===_.MEDIA_SEEKABLE)&&(this.mediaChaptersCues=Je(this,hn),this.updateBar()))}get mediaChaptersCues(){return Je(this,hn)}set mediaChaptersCues(e){var t;si(this,hn,e),this.updateSegments((t=Je(this,hn))==null?void 0:t.map(s=>({start:Vo(this,s.startTime),end:Vo(this,s.endTime)})))}get mediaPaused(){return ye(this,_.MEDIA_PAUSED)}set mediaPaused(e){be(this,_.MEDIA_PAUSED,e)}get mediaLoading(){return ye(this,_.MEDIA_LOADING)}set mediaLoading(e){be(this,_.MEDIA_LOADING,e)}get mediaDuration(){return Be(this,_.MEDIA_DURATION)}set mediaDuration(e){Xe(this,_.MEDIA_DURATION,e)}get mediaCurrentTime(){return Be(this,_.MEDIA_CURRENT_TIME)}set mediaCurrentTime(e){Xe(this,_.MEDIA_CURRENT_TIME,e)}get mediaPlaybackRate(){return Be(this,_.MEDIA_PLAYBACK_RATE,1)}set mediaPlaybackRate(e){Xe(this,_.MEDIA_PLAYBACK_RATE,e)}get mediaBuffered(){const e=this.getAttribute(_.MEDIA_BUFFERED);return e?e.split(" ").map(t=>t.split(":").map(s=>+s)):[]}set mediaBuffered(e){if(!e){this.removeAttribute(_.MEDIA_BUFFERED);return}const t=e.map(s=>s.join(":")).join(" ");this.setAttribute(_.MEDIA_BUFFERED,t)}get mediaSeekable(){const e=this.getAttribute(_.MEDIA_SEEKABLE);if(e)return e.split(":").map(t=>+t)}set mediaSeekable(e){if(e==null){this.removeAttribute(_.MEDIA_SEEKABLE);return}this.setAttribute(_.MEDIA_SEEKABLE,e.join(":"))}get mediaSeekableEnd(){var e;const[,t=this.mediaDuration]=(e=this.mediaSeekable)!=null?e:[];return t}get mediaSeekableStart(){var e;const[t=0]=(e=this.mediaSeekable)!=null?e:[];return t}get mediaPreviewImage(){return He(this,_.MEDIA_PREVIEW_IMAGE)}set mediaPreviewImage(e){Ge(this,_.MEDIA_PREVIEW_IMAGE,e)}get mediaPreviewTime(){return Be(this,_.MEDIA_PREVIEW_TIME)}set mediaPreviewTime(e){Xe(this,_.MEDIA_PREVIEW_TIME,e)}get mediaEnded(){return ye(this,_.MEDIA_ENDED)}set mediaEnded(e){be(this,_.MEDIA_ENDED,e)}updateBar(){super.updateBar(),this.updateBufferedBar(),this.updateCurrentBox()}updateBufferedBar(){var e;const t=this.mediaBuffered;if(!t.length)return;let s;if(this.mediaEnded)s=1;else{const n=this.mediaCurrentTime,[,a=this.mediaSeekableStart]=(e=t.find(([o,l])=>o<=n&&n<=l))!=null?e:[];s=Vo(this,a)}const{style:r}=pt(this.shadowRoot,"#buffered");r.setProperty("width",`${s*100}%`)}updateCurrentBox(){if(!this.shadowRoot.querySelector('slot[name="current"]').assignedElements().length)return;const t=pt(this.shadowRoot,"#current-rail"),s=pt(this.shadowRoot,'[part~="current-box"]'),r=kt(this,Bd,Am).call(this,Je(this,Fl)),n=kt(this,Hd,Sm).call(this,r,this.range.valueAsNumber),a=kt(this,Gd,Im).call(this,r,this.range.valueAsNumber);t.style.transform=`translateX(${n})`,t.style.setProperty("--_range-width",`${r.range.width}`),s.style.setProperty("--_box-shift",`${a}`),s.style.setProperty("--_box-width",`${r.box.width}px`),s.style.setProperty("visibility","initial")}handleEvent(e){switch(super.handleEvent(e),e.type){case"input":kt(this,Ch,ZE).call(this);break;case"pointermove":kt(this,Dh,XE).call(this,e);break;case"pointerup":Je(this,fn)&&si(this,fn,!1);break;case"pointerdown":si(this,fn,!0);break;case"pointerleave":kt(this,co,Kd).call(this,null);break;case"transitionstart":Ts(e.target,this)&&setTimeout(()=>kt(this,mn,Ra).call(this),0);break}}};cn=new WeakMap;xr=new WeakMap;$d=new WeakMap;qa=new WeakMap;Fd=new WeakMap;Fl=new WeakMap;lo=new WeakMap;uo=new WeakMap;hn=new WeakMap;fn=new WeakMap;mn=new WeakSet;Ra=function(){kt(this,_m,QE).call(this)?Je(this,xr).start():Je(this,xr).stop()};_m=new WeakSet;QE=function(){return this.isConnected&&!this.mediaPaused&&!this.mediaLoading&&!this.mediaEnded&&this.mediaSeekableEnd>0&&iE(this)};kh=new WeakMap;Bd=new WeakSet;Am=function(i){var e;const s=((e=this.getAttribute("bounds")?ia(this,`#${this.getAttribute("bounds")}`):this.parentElement)!=null?e:this).getBoundingClientRect(),r=this.range.getBoundingClientRect(),n=i.offsetWidth,a=-(r.left-s.left-n/2),o=s.right-r.left-n/2;return{box:{width:n,min:a,max:o},bounds:s,range:r}};Hd=new WeakSet;Sm=function(i,e){let t=`${e*100}%`;const{width:s,min:r,max:n}=i.box;if(!s)return t;if(Number.isNaN(r)||(t=`max(${`calc(1 / var(--_range-width) * 100 * ${r}% + var(--media-box-padding-left))`}, ${t})`),!Number.isNaN(n)){const o=`calc(1 / var(--_range-width) * 100 * ${n}% - var(--media-box-padding-right))`;t=`min(${t}, ${o})`}return t};Gd=new WeakSet;Im=function(i,e){const{width:t,min:s,max:r}=i.box,n=e*i.range.width;if(n<s+Je(this,lo)){const a=i.range.left-i.bounds.left-Je(this,lo);return`${n-t/2+a}px`}if(n>r-Je(this,uo)){const a=i.bounds.right-i.range.right-Je(this,uo);return`${n+t/2-a-i.range.width}px`}return 0};Dh=new WeakSet;XE=function(i){const e=[...Je(this,$d)].some(u=>i.composedPath().includes(u));if(!this.dragging&&(e||!i.composedPath().includes(this))){kt(this,co,Kd).call(this,null);return}const t=this.mediaSeekableEnd;if(!t)return;const s=pt(this.shadowRoot,"#preview-rail"),r=pt(this.shadowRoot,'[part~="preview-box"]'),n=kt(this,Bd,Am).call(this,Je(this,Fd));let a=(i.clientX-n.range.left)/n.range.width;a=Math.max(0,Math.min(1,a));const o=kt(this,Hd,Sm).call(this,n,a),l=kt(this,Gd,Im).call(this,n,a);s.style.transform=`translateX(${o})`,s.style.setProperty("--_range-width",`${n.range.width}`),r.style.setProperty("--_box-shift",`${l}`),r.style.setProperty("--_box-width",`${n.box.width}px`);const d=Math.round(Je(this,qa))-Math.round(a*t);Math.abs(d)<1&&a>.01&&a<.99||(si(this,qa,a*t),kt(this,co,Kd).call(this,Je(this,qa)))};co=new WeakSet;Kd=function(i){this.dispatchEvent(new k.CustomEvent(
|
|
1373
|
+
`}const Vo=(i,e=i.mediaCurrentTime)=>{const t=Number.isFinite(i.mediaSeekableStart)?i.mediaSeekableStart:0,s=Number.isFinite(i.mediaDuration)?i.mediaDuration:i.mediaSeekableEnd;if(Number.isNaN(s))return 0;const r=(e-t)/(s-t);return Math.max(0,Math.min(r,1))},JE=(i,e=i.range.valueAsNumber)=>{const t=Number.isFinite(i.mediaSeekableStart)?i.mediaSeekableStart:0,s=Number.isFinite(i.mediaDuration)?i.mediaDuration:i.mediaSeekableEnd;return Number.isNaN(s)?0:e*(s-t)+t};let Ku=class extends Or{constructor(){super(),ht(this,mn),ht(this,_m),ht(this,Bd),ht(this,Hd),ht(this,Gd),ht(this,Dh),ht(this,co),ht(this,Ch),ht(this,cn,void 0),ht(this,xr,void 0),ht(this,$d,void 0),ht(this,qa,void 0),ht(this,Fd,void 0),ht(this,Fl,void 0),ht(this,lo,void 0),ht(this,uo,void 0),ht(this,hn,void 0),ht(this,fn,void 0),ht(this,kh,s=>{this.dragging||(em(s)&&(this.range.valueAsNumber=s),Je(this,fn)||this.updateBar())}),this.shadowRoot.querySelector("#track").insertAdjacentHTML("afterbegin",'<div id="buffered" part="buffered"></div>'),si(this,$d,this.shadowRoot.querySelectorAll('[part~="box"]')),si(this,Fd,this.shadowRoot.querySelector('[part~="preview-box"]')),si(this,Fl,this.shadowRoot.querySelector('[part~="current-box"]'));const t=getComputedStyle(this);si(this,lo,parseInt(t.getPropertyValue("--media-box-padding-left"))),si(this,uo,parseInt(t.getPropertyValue("--media-box-padding-right"))),si(this,xr,new rI(this.range,Je(this,kh),60))}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PAUSED,_.MEDIA_DURATION,_.MEDIA_SEEKABLE,_.MEDIA_CURRENT_TIME,_.MEDIA_PREVIEW_IMAGE,_.MEDIA_PREVIEW_TIME,_.MEDIA_PREVIEW_CHAPTER,_.MEDIA_BUFFERED,_.MEDIA_PLAYBACK_RATE,_.MEDIA_LOADING,_.MEDIA_ENDED]}connectedCallback(){var e;super.connectedCallback(),this.range.setAttribute("aria-label",te("seek")),kt(this,mn,Ra).call(this),si(this,cn,this.getRootNode()),(e=Je(this,cn))==null||e.addEventListener("transitionstart",this)}disconnectedCallback(){var e;super.disconnectedCallback(),kt(this,mn,Ra).call(this),(e=Je(this,cn))==null||e.removeEventListener("transitionstart",this),si(this,cn,null)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),t!=s&&(e===_.MEDIA_CURRENT_TIME||e===_.MEDIA_PAUSED||e===_.MEDIA_ENDED||e===_.MEDIA_LOADING||e===_.MEDIA_DURATION||e===_.MEDIA_SEEKABLE?(Je(this,xr).update({start:Vo(this),duration:this.mediaSeekableEnd-this.mediaSeekableStart,playbackRate:this.mediaPlaybackRate}),kt(this,mn,Ra).call(this),aI(this)):e===_.MEDIA_BUFFERED&&this.updateBufferedBar(),(e===_.MEDIA_DURATION||e===_.MEDIA_SEEKABLE)&&(this.mediaChaptersCues=Je(this,hn),this.updateBar()))}get mediaChaptersCues(){return Je(this,hn)}set mediaChaptersCues(e){var t;si(this,hn,e),this.updateSegments((t=Je(this,hn))==null?void 0:t.map(s=>({start:Vo(this,s.startTime),end:Vo(this,s.endTime)})))}get mediaPaused(){return ye(this,_.MEDIA_PAUSED)}set mediaPaused(e){be(this,_.MEDIA_PAUSED,e)}get mediaLoading(){return ye(this,_.MEDIA_LOADING)}set mediaLoading(e){be(this,_.MEDIA_LOADING,e)}get mediaDuration(){return Be(this,_.MEDIA_DURATION)}set mediaDuration(e){Xe(this,_.MEDIA_DURATION,e)}get mediaCurrentTime(){return Be(this,_.MEDIA_CURRENT_TIME)}set mediaCurrentTime(e){Xe(this,_.MEDIA_CURRENT_TIME,e)}get mediaPlaybackRate(){return Be(this,_.MEDIA_PLAYBACK_RATE,1)}set mediaPlaybackRate(e){Xe(this,_.MEDIA_PLAYBACK_RATE,e)}get mediaBuffered(){const e=this.getAttribute(_.MEDIA_BUFFERED);return e?e.split(" ").map(t=>t.split(":").map(s=>+s)):[]}set mediaBuffered(e){if(!e){this.removeAttribute(_.MEDIA_BUFFERED);return}const t=e.map(s=>s.join(":")).join(" ");this.setAttribute(_.MEDIA_BUFFERED,t)}get mediaSeekable(){const e=this.getAttribute(_.MEDIA_SEEKABLE);if(e)return e.split(":").map(t=>+t)}set mediaSeekable(e){if(e==null){this.removeAttribute(_.MEDIA_SEEKABLE);return}this.setAttribute(_.MEDIA_SEEKABLE,e.join(":"))}get mediaSeekableEnd(){var e;const[,t=this.mediaDuration]=(e=this.mediaSeekable)!=null?e:[];return t}get mediaSeekableStart(){var e;const[t=0]=(e=this.mediaSeekable)!=null?e:[];return t}get mediaPreviewImage(){return He(this,_.MEDIA_PREVIEW_IMAGE)}set mediaPreviewImage(e){Ge(this,_.MEDIA_PREVIEW_IMAGE,e)}get mediaPreviewTime(){return Be(this,_.MEDIA_PREVIEW_TIME)}set mediaPreviewTime(e){Xe(this,_.MEDIA_PREVIEW_TIME,e)}get mediaEnded(){return ye(this,_.MEDIA_ENDED)}set mediaEnded(e){be(this,_.MEDIA_ENDED,e)}updateBar(){super.updateBar(),this.updateBufferedBar(),this.updateCurrentBox()}updateBufferedBar(){var e;const t=this.mediaBuffered;if(!t.length)return;let s;if(this.mediaEnded)s=1;else{const n=this.mediaCurrentTime,[,a=this.mediaSeekableStart]=(e=t.find(([o,l])=>o<=n&&n<=l))!=null?e:[];s=Vo(this,a)}const{style:r}=pt(this.shadowRoot,"#buffered");r.setProperty("width",`${s*100}%`)}updateCurrentBox(){if(!this.shadowRoot.querySelector('slot[name="current"]').assignedElements().length)return;const t=pt(this.shadowRoot,"#current-rail"),s=pt(this.shadowRoot,'[part~="current-box"]'),r=kt(this,Bd,Am).call(this,Je(this,Fl)),n=kt(this,Hd,Sm).call(this,r,this.range.valueAsNumber),a=kt(this,Gd,Im).call(this,r,this.range.valueAsNumber);t.style.transform=`translateX(${n})`,t.style.setProperty("--_range-width",`${r.range.width}`),s.style.setProperty("--_box-shift",`${a}`),s.style.setProperty("--_box-width",`${r.box.width}px`),s.style.setProperty("visibility","initial")}handleEvent(e){switch(super.handleEvent(e),e.type){case"input":kt(this,Ch,ZE).call(this);break;case"pointermove":kt(this,Dh,XE).call(this,e);break;case"pointerup":Je(this,fn)&&si(this,fn,!1);break;case"pointerdown":si(this,fn,!0);break;case"pointerleave":kt(this,co,Kd).call(this,null);break;case"transitionstart":Ts(e.target,this)&&setTimeout(()=>kt(this,mn,Ra).call(this),0);break}}};cn=new WeakMap;xr=new WeakMap;$d=new WeakMap;qa=new WeakMap;Fd=new WeakMap;Fl=new WeakMap;lo=new WeakMap;uo=new WeakMap;hn=new WeakMap;fn=new WeakMap;mn=new WeakSet;Ra=function(){kt(this,_m,QE).call(this)?Je(this,xr).start():Je(this,xr).stop()};_m=new WeakSet;QE=function(){return this.isConnected&&!this.mediaPaused&&!this.mediaLoading&&!this.mediaEnded&&this.mediaSeekableEnd>0&&iE(this)};kh=new WeakMap;Bd=new WeakSet;Am=function(i){var e;const s=((e=this.getAttribute("bounds")?ia(this,`#${this.getAttribute("bounds")}`):this.parentElement)!=null?e:this).getBoundingClientRect(),r=this.range.getBoundingClientRect(),n=i.offsetWidth,a=-(r.left-s.left-n/2),o=s.right-r.left-n/2;return{box:{width:n,min:a,max:o},bounds:s,range:r}};Hd=new WeakSet;Sm=function(i,e){let t=`${e*100}%`;const{width:s,min:r,max:n}=i.box;if(!s)return t;if(Number.isNaN(r)||(t=`max(${`calc(1 / var(--_range-width) * 100 * ${r}% + var(--media-box-padding-left))`}, ${t})`),!Number.isNaN(n)){const o=`calc(1 / var(--_range-width) * 100 * ${n}% - var(--media-box-padding-right))`;t=`min(${t}, ${o})`}return t};Gd=new WeakSet;Im=function(i,e){const{width:t,min:s,max:r}=i.box,n=e*i.range.width;if(n<s+Je(this,lo)){const a=i.range.left-i.bounds.left-Je(this,lo);return`${n-t/2+a}px`}if(n>r-Je(this,uo)){const a=i.bounds.right-i.range.right-Je(this,uo);return`${n+t/2-a-i.range.width}px`}return 0};Dh=new WeakSet;XE=function(i){const e=[...Je(this,$d)].some(u=>i.composedPath().includes(u));if(!this.dragging&&(e||!i.composedPath().includes(this))){kt(this,co,Kd).call(this,null);return}const t=this.mediaSeekableEnd;if(!t)return;const s=pt(this.shadowRoot,"#preview-rail"),r=pt(this.shadowRoot,'[part~="preview-box"]'),n=kt(this,Bd,Am).call(this,Je(this,Fd));let a=(i.clientX-n.range.left)/n.range.width;a=Math.max(0,Math.min(1,a));const o=kt(this,Hd,Sm).call(this,n,a),l=kt(this,Gd,Im).call(this,n,a);s.style.transform=`translateX(${o})`,s.style.setProperty("--_range-width",`${n.range.width}`),r.style.setProperty("--_box-shift",`${l}`),r.style.setProperty("--_box-width",`${n.box.width}px`);const d=Math.round(Je(this,qa))-Math.round(a*t);Math.abs(d)<1&&a>.01&&a<.99||(si(this,qa,a*t),kt(this,co,Kd).call(this,Je(this,qa)))};co=new WeakSet;Kd=function(i){this.dispatchEvent(new k.CustomEvent(Q.MEDIA_PREVIEW_REQUEST,{composed:!0,bubbles:!0,detail:i}))};Ch=new WeakSet;ZE=function(){Je(this,xr).stop();const i=JE(this);this.dispatchEvent(new k.CustomEvent(Q.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:i}))};Ku.shadowRootOptions={mode:"open"};Ku.getContainerTemplateHTML=oI;k.customElements.get("media-time-range")||k.customElements.define("media-time-range",Ku);var lI=Ku;const dI=1,uI=i=>i.mediaMuted?0:i.mediaVolume,cI=i=>`${Math.round(i*100)}%`;let ey=class extends Or{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_VOLUME,_.MEDIA_MUTED,_.MEDIA_VOLUME_UNAVAILABLE]}constructor(){super(),this.range.addEventListener("input",()=>{const e=this.range.value,t=new k.CustomEvent(Q.MEDIA_VOLUME_REQUEST,{composed:!0,bubbles:!0,detail:e});this.dispatchEvent(t)})}connectedCallback(){super.connectedCallback(),this.range.setAttribute("aria-label",te("volume"))}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),(e===_.MEDIA_VOLUME||e===_.MEDIA_MUTED)&&(this.range.valueAsNumber=uI(this),this.range.setAttribute("aria-valuetext",cI(this.range.valueAsNumber)),this.updateBar())}get mediaVolume(){return Be(this,_.MEDIA_VOLUME,dI)}set mediaVolume(e){Xe(this,_.MEDIA_VOLUME,e)}get mediaMuted(){return ye(this,_.MEDIA_MUTED)}set mediaMuted(e){be(this,_.MEDIA_MUTED,e)}get mediaVolumeUnavailable(){return He(this,_.MEDIA_VOLUME_UNAVAILABLE)}set mediaVolumeUnavailable(e){Ge(this,_.MEDIA_VOLUME_UNAVAILABLE,e)}};k.customElements.get("media-volume-range")||k.customElements.define("media-volume-range",ey);var hI=ey;function fI(i){return`
|
|
1374
1374
|
<style>
|
|
1375
1375
|
:host {
|
|
1376
1376
|
min-width: 4ch;
|
|
@@ -1399,9 +1399,9 @@ import{j as N}from"./jsx-runtime-C5WNSv3b.js";import{R as ve,r as Se}from"./inde
|
|
|
1399
1399
|
<path d="m10 15.17 9.193-9.191 1.414 1.414-10.606 10.606-6.364-6.364 1.414-1.414 4.95 4.95Z"/>
|
|
1400
1400
|
</svg>
|
|
1401
1401
|
</div>
|
|
1402
|
-
`}function mI(){return te("Loop")}class Vu extends vt{constructor(){super(...arguments),this.container=null}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_LOOP]}connectedCallback(){var e;super.connectedCallback(),this.container=((e=this.shadowRoot)==null?void 0:e.querySelector("#icon"))||null,this.container&&(this.container.textContent=te("Loop"))}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_LOOP&&this.container&&this.setAttribute("aria-checked",this.mediaLoop?"true":"false")}get mediaLoop(){return ye(this,_.MEDIA_LOOP)}set mediaLoop(e){be(this,_.MEDIA_LOOP,e)}handleClick(){const e=!this.mediaLoop,t=new k.CustomEvent(z.MEDIA_LOOP_REQUEST,{composed:!0,bubbles:!0,detail:e});this.dispatchEvent(t)}}Vu.getSlotTemplateHTML=fI;Vu.getTooltipContentHTML=mI;k.customElements.get("media-loop-button")||k.customElements.define("media-loop-button",Vu);var pI=Vu;function Re(i){if(typeof i=="boolean")return i?"":void 0;if(typeof i=="function")return;const e=t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean";if(Array.isArray(i)&&i.every(e))return i.join(" ");if(!(typeof i=="object"&&i!==null))return i}Le({tagName:"media-gesture-receiver",elementClass:rh,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-container",elementClass:TA,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});const gI=Le({tagName:"media-controller",elementClass:TE,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-tooltip",elementClass:fh,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-chrome-button",elementClass:nS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-airplay-button",elementClass:lS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-captions-button",elementClass:fS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-cast-button",elementClass:ES,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-chrome-dialog",elementClass:TS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-chrome-range",elementClass:SS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});const vI=Le({tagName:"media-control-bar",elementClass:LS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-text-display",elementClass:CS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-duration-display",elementClass:OS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-error-dialog",elementClass:vm,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-keyboard-shortcuts-dialog",elementClass:qS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});const EI=Le({tagName:"media-fullscreen-button",elementClass:e1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-live-button",elementClass:n1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-loading-indicator",elementClass:l1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});const yI=Le({tagName:"media-mute-button",elementClass:f1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}}),bI=Le({tagName:"media-pip-button",elementClass:g1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}}),TI=Le({tagName:"media-playback-rate-button",elementClass:T1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}}),_I=Le({tagName:"media-play-button",elementClass:x1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-poster-image",elementClass:D1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-preview-chapter-display",elementClass:P1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-preview-thumbnail",elementClass:Lh,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-preview-time-display",elementClass:F1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});const AI=Le({tagName:"media-seek-backward-button",elementClass:V1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}}),SI=Le({tagName:"media-seek-forward-button",elementClass:z1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}}),II=Le({tagName:"media-time-display",elementClass:iI,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}}),xI=Le({tagName:"media-time-range",elementClass:lI,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}}),LI=Le({tagName:"media-volume-range",elementClass:hI,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-loop-button",elementClass:pI,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});var RI=Object.create,ty=Object.defineProperty,kI=Object.getOwnPropertyDescriptor,DI=Object.getOwnPropertyNames,CI=Object.getPrototypeOf,wI=Object.prototype.hasOwnProperty,iy=function(i,e){return function(){return i&&(e=i(i=0)),e}},$t=function(i,e){return function(){return e||i((e={exports:{}}).exports,e),e.exports}},MI=function(i,e,t,s){if(e&&typeof e=="object"||typeof e=="function")for(var r=DI(e),n=0,a=r.length,o;n<a;n++)o=r[n],!wI.call(i,o)&&o!==t&&ty(i,o,{get:(function(l){return e[l]}).bind(null,o),enumerable:!(s=kI(e,o))||s.enumerable});return i},Jt=function(i,e,t){return t=i!=null?RI(CI(i)):{},MI(!i||!i.__esModule?ty(t,"default",{value:i,enumerable:!0}):t,i)},Ii=$t(function(i,e){var t;typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"?t=self:t={},e.exports=t});function Nr(i,e){return e!=null&&typeof Symbol<"u"&&e[Symbol.hasInstance]?!!e[Symbol.hasInstance](i):Nr(i,e)}var Ur=iy(function(){Ur()});function sy(i){"@swc/helpers - typeof";return i&&typeof Symbol<"u"&&i.constructor===Symbol?"symbol":typeof i}var ry=iy(function(){}),ny=$t(function(i,e){var t=Array.prototype.slice;e.exports=s;function s(r,n){for(("length"in r)||(r=[r]),r=t.call(r);r.length;){var a=r.shift(),o=n(a);if(o)return o;a.childNodes&&a.childNodes.length&&(r=t.call(a.childNodes).concat(r))}}}),PI=$t(function(i,e){Ur(),e.exports=t;function t(s,r){if(!Nr(this,t))return new t(s,r);this.data=s,this.nodeValue=s,this.length=s.length,this.ownerDocument=r||null}t.prototype.nodeType=8,t.prototype.nodeName="#comment",t.prototype.toString=function(){return"[object Comment]"}}),OI=$t(function(i,e){Ur(),e.exports=t;function t(s,r){if(!Nr(this,t))return new t(s);this.data=s||"",this.length=this.data.length,this.ownerDocument=r||null}t.prototype.type="DOMTextNode",t.prototype.nodeType=3,t.prototype.nodeName="#text",t.prototype.toString=function(){return this.data},t.prototype.replaceData=function(s,r,n){var a=this.data,o=a.substring(0,s),l=a.substring(s+r,a.length);this.data=o+n+l,this.length=this.data.length}}),ay=$t(function(i,e){e.exports=t;function t(s){var r=this,n=s.type;s.target||(s.target=r),r.listeners||(r.listeners={});var a=r.listeners[n];if(a)return a.forEach(function(o){s.currentTarget=r,typeof o=="function"?o(s):o.handleEvent(s)});r.parentNode&&r.parentNode.dispatchEvent(s)}}),oy=$t(function(i,e){e.exports=t;function t(s,r){var n=this;n.listeners||(n.listeners={}),n.listeners[s]||(n.listeners[s]=[]),n.listeners[s].indexOf(r)===-1&&n.listeners[s].push(r)}}),ly=$t(function(i,e){e.exports=t;function t(s,r){var n=this;if(n.listeners&&n.listeners[s]){var a=n.listeners[s],o=a.indexOf(r);o!==-1&&a.splice(o,1)}}}),NI=$t(function(i,e){ry(),e.exports=s;var t=["area","base","br","col","embed","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr"];function s(h){switch(h.nodeType){case 3:return u(h.data);case 8:return"<!--"+h.data+"-->";default:return r(h)}}function r(h){var f=[],m=h.tagName;return h.namespaceURI==="http://www.w3.org/1999/xhtml"&&(m=m.toLowerCase()),f.push("<"+m+d(h)+o(h)),t.indexOf(m)>-1?f.push(" />"):(f.push(">"),h.childNodes.length?f.push.apply(f,h.childNodes.map(s)):h.textContent||h.innerText?f.push(u(h.textContent||h.innerText)):h.innerHTML&&f.push(h.innerHTML),f.push("</"+m+">")),f.join("")}function n(h,f){var m=sy(h[f]);return f==="style"&&Object.keys(h.style).length>0?!0:h.hasOwnProperty(f)&&(m==="string"||m==="boolean"||m==="number")&&f!=="nodeName"&&f!=="className"&&f!=="tagName"&&f!=="textContent"&&f!=="innerText"&&f!=="namespaceURI"&&f!=="innerHTML"}function a(h){if(typeof h=="string")return h;var f="";return Object.keys(h).forEach(function(m){var p=h[m];m=m.replace(/[A-Z]/g,function(g){return"-"+g.toLowerCase()}),f+=m+":"+p+";"}),f}function o(h){var f=h.dataset,m=[];for(var p in f)m.push({name:"data-"+p,value:f[p]});return m.length?l(m):""}function l(h){var f=[];return h.forEach(function(m){var p=m.name,g=m.value;p==="style"&&(g=a(g)),f.push(p+'="'+c(g)+'"')}),f.length?" "+f.join(" "):""}function d(h){var f=[];for(var m in h)n(h,m)&&f.push({name:m,value:h[m]});for(var p in h._attributes)for(var g in h._attributes[p]){var v=h._attributes[p][g],b=(v.prefix?v.prefix+":":"")+g;f.push({name:b,value:v.value})}return h.className&&f.push({name:"class",value:h.className}),f.length?l(f):""}function u(h){var f="";return typeof h=="string"?f=h:h&&(f=h.toString()),f.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function c(h){return u(h).replace(/"/g,""")}}),dy=$t(function(i,e){Ur();var t=ny(),s=ay(),r=oy(),n=ly(),a=NI(),o="http://www.w3.org/1999/xhtml";e.exports=l;function l(d,u,c){if(!Nr(this,l))return new l(d);var h=c===void 0?o:c||null;this.tagName=h===o?String(d).toUpperCase():d,this.nodeName=this.tagName,this.className="",this.dataset={},this.childNodes=[],this.parentNode=null,this.style={},this.ownerDocument=u||null,this.namespaceURI=h,this._attributes={},this.tagName==="INPUT"&&(this.type="text")}l.prototype.type="DOMElement",l.prototype.nodeType=1,l.prototype.appendChild=function(d){return d.parentNode&&d.parentNode.removeChild(d),this.childNodes.push(d),d.parentNode=this,d},l.prototype.replaceChild=function(d,u){d.parentNode&&d.parentNode.removeChild(d);var c=this.childNodes.indexOf(u);return u.parentNode=null,this.childNodes[c]=d,d.parentNode=this,u},l.prototype.removeChild=function(d){var u=this.childNodes.indexOf(d);return this.childNodes.splice(u,1),d.parentNode=null,d},l.prototype.insertBefore=function(d,u){d.parentNode&&d.parentNode.removeChild(d);var c=u==null?-1:this.childNodes.indexOf(u);return c>-1?this.childNodes.splice(c,0,d):this.childNodes.push(d),d.parentNode=this,d},l.prototype.setAttributeNS=function(d,u,c){var h=null,f=u,m=u.indexOf(":");if(m>-1&&(h=u.substr(0,m),f=u.substr(m+1)),this.tagName==="INPUT"&&u==="type")this.type=c;else{var p=this._attributes[d]||(this._attributes[d]={});p[f]={value:c,prefix:h}}},l.prototype.getAttributeNS=function(d,u){var c=this._attributes[d],h=c&&c[u]&&c[u].value;return this.tagName==="INPUT"&&u==="type"?this.type:typeof h!="string"?null:h},l.prototype.removeAttributeNS=function(d,u){var c=this._attributes[d];c&&delete c[u]},l.prototype.hasAttributeNS=function(d,u){var c=this._attributes[d];return!!c&&u in c},l.prototype.setAttribute=function(d,u){return this.setAttributeNS(null,d,u)},l.prototype.getAttribute=function(d){return this.getAttributeNS(null,d)},l.prototype.removeAttribute=function(d){return this.removeAttributeNS(null,d)},l.prototype.hasAttribute=function(d){return this.hasAttributeNS(null,d)},l.prototype.removeEventListener=n,l.prototype.addEventListener=r,l.prototype.dispatchEvent=s,l.prototype.focus=function(){},l.prototype.toString=function(){return a(this)},l.prototype.getElementsByClassName=function(d){var u=d.split(" "),c=[];return t(this,function(h){if(h.nodeType===1){var f=h.className||"",m=f.split(" ");u.every(function(p){return m.indexOf(p)!==-1})&&c.push(h)}}),c},l.prototype.getElementsByTagName=function(d){d=d.toLowerCase();var u=[];return t(this.childNodes,function(c){c.nodeType===1&&(d==="*"||c.tagName.toLowerCase()===d)&&u.push(c)}),u},l.prototype.contains=function(d){return t(this,function(u){return d===u})||!1}}),UI=$t(function(i,e){Ur();var t=dy();e.exports=s;function s(r){if(!Nr(this,s))return new s;this.childNodes=[],this.parentNode=null,this.ownerDocument=r||null}s.prototype.type="DocumentFragment",s.prototype.nodeType=11,s.prototype.nodeName="#document-fragment",s.prototype.appendChild=t.prototype.appendChild,s.prototype.replaceChild=t.prototype.replaceChild,s.prototype.removeChild=t.prototype.removeChild,s.prototype.toString=function(){return this.childNodes.map(function(r){return String(r)}).join("")}}),$I=$t(function(i,e){e.exports=t;function t(s){}t.prototype.initEvent=function(s,r,n){this.type=s,this.bubbles=r,this.cancelable=n},t.prototype.preventDefault=function(){}}),FI=$t(function(i,e){Ur();var t=ny(),s=PI(),r=OI(),n=dy(),a=UI(),o=$I(),l=ay(),d=oy(),u=ly();e.exports=c;function c(){if(!Nr(this,c))return new c;this.head=this.createElement("head"),this.body=this.createElement("body"),this.documentElement=this.createElement("html"),this.documentElement.appendChild(this.head),this.documentElement.appendChild(this.body),this.childNodes=[this.documentElement],this.nodeType=9}var h=c.prototype;h.createTextNode=function(f){return new r(f,this)},h.createElementNS=function(f,m){var p=f===null?null:String(f);return new n(m,this,p)},h.createElement=function(f){return new n(f,this)},h.createDocumentFragment=function(){return new a(this)},h.createEvent=function(f){return new o(f)},h.createComment=function(f){return new s(f,this)},h.getElementById=function(f){f=String(f);var m=t(this.childNodes,function(p){if(String(p.id)===f)return p});return m||null},h.getElementsByClassName=n.prototype.getElementsByClassName,h.getElementsByTagName=n.prototype.getElementsByTagName,h.contains=n.prototype.contains,h.removeEventListener=u,h.addEventListener=d,h.dispatchEvent=l}),BI=$t(function(i,e){var t=FI();e.exports=new t}),uy=$t(function(i,e){var t=typeof global<"u"?global:typeof window<"u"?window:{},s=BI(),r;typeof document<"u"?r=document:(r=t["__GLOBAL_DOCUMENT_CACHE@4"],r||(r=t["__GLOBAL_DOCUMENT_CACHE@4"]=s)),e.exports=r});function HI(i){if(Array.isArray(i))return i}function GI(i,e){var t=i==null?null:typeof Symbol<"u"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var s=[],r=!0,n=!1,a,o;try{for(t=t.call(i);!(r=(a=t.next()).done)&&(s.push(a.value),!(e&&s.length===e));r=!0);}catch(l){n=!0,o=l}finally{try{!r&&t.return!=null&&t.return()}finally{if(n)throw o}}return s}}function KI(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
1402
|
+
`}function mI(){return te("Loop")}class Vu extends vt{constructor(){super(...arguments),this.container=null}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_LOOP]}connectedCallback(){var e;super.connectedCallback(),this.container=((e=this.shadowRoot)==null?void 0:e.querySelector("#icon"))||null,this.container&&(this.container.textContent=te("Loop"))}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_LOOP&&this.container&&this.setAttribute("aria-checked",this.mediaLoop?"true":"false")}get mediaLoop(){return ye(this,_.MEDIA_LOOP)}set mediaLoop(e){be(this,_.MEDIA_LOOP,e)}handleClick(){const e=!this.mediaLoop,t=new k.CustomEvent(Q.MEDIA_LOOP_REQUEST,{composed:!0,bubbles:!0,detail:e});this.dispatchEvent(t)}}Vu.getSlotTemplateHTML=fI;Vu.getTooltipContentHTML=mI;k.customElements.get("media-loop-button")||k.customElements.define("media-loop-button",Vu);var pI=Vu;function Re(i){if(typeof i=="boolean")return i?"":void 0;if(typeof i=="function")return;const e=t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean";if(Array.isArray(i)&&i.every(e))return i.join(" ");if(!(typeof i=="object"&&i!==null))return i}Le({tagName:"media-gesture-receiver",elementClass:rh,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-container",elementClass:TA,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});const gI=Le({tagName:"media-controller",elementClass:TE,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-tooltip",elementClass:fh,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-chrome-button",elementClass:nS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-airplay-button",elementClass:lS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-captions-button",elementClass:fS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-cast-button",elementClass:ES,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-chrome-dialog",elementClass:TS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-chrome-range",elementClass:SS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});const vI=Le({tagName:"media-control-bar",elementClass:LS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-text-display",elementClass:CS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-duration-display",elementClass:OS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-error-dialog",elementClass:vm,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-keyboard-shortcuts-dialog",elementClass:qS,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});const EI=Le({tagName:"media-fullscreen-button",elementClass:e1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-live-button",elementClass:n1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-loading-indicator",elementClass:l1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});const yI=Le({tagName:"media-mute-button",elementClass:f1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}}),bI=Le({tagName:"media-pip-button",elementClass:g1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}}),TI=Le({tagName:"media-playback-rate-button",elementClass:T1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}}),_I=Le({tagName:"media-play-button",elementClass:x1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-poster-image",elementClass:D1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-preview-chapter-display",elementClass:P1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-preview-thumbnail",elementClass:Lh,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-preview-time-display",elementClass:F1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});const AI=Le({tagName:"media-seek-backward-button",elementClass:V1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}}),SI=Le({tagName:"media-seek-forward-button",elementClass:z1,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}}),II=Le({tagName:"media-time-display",elementClass:iI,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}}),xI=Le({tagName:"media-time-range",elementClass:lI,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}}),LI=Le({tagName:"media-volume-range",elementClass:hI,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});Le({tagName:"media-loop-button",elementClass:pI,react:ve,toAttributeValue:Re,defaultProps:{suppressHydrationWarning:!0}});var RI=Object.create,ty=Object.defineProperty,kI=Object.getOwnPropertyDescriptor,DI=Object.getOwnPropertyNames,CI=Object.getPrototypeOf,wI=Object.prototype.hasOwnProperty,iy=function(i,e){return function(){return i&&(e=i(i=0)),e}},$t=function(i,e){return function(){return e||i((e={exports:{}}).exports,e),e.exports}},MI=function(i,e,t,s){if(e&&typeof e=="object"||typeof e=="function")for(var r=DI(e),n=0,a=r.length,o;n<a;n++)o=r[n],!wI.call(i,o)&&o!==t&&ty(i,o,{get:(function(l){return e[l]}).bind(null,o),enumerable:!(s=kI(e,o))||s.enumerable});return i},Jt=function(i,e,t){return t=i!=null?RI(CI(i)):{},MI(!i||!i.__esModule?ty(t,"default",{value:i,enumerable:!0}):t,i)},Ii=$t(function(i,e){var t;typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"?t=self:t={},e.exports=t});function Nr(i,e){return e!=null&&typeof Symbol<"u"&&e[Symbol.hasInstance]?!!e[Symbol.hasInstance](i):Nr(i,e)}var Ur=iy(function(){Ur()});function sy(i){"@swc/helpers - typeof";return i&&typeof Symbol<"u"&&i.constructor===Symbol?"symbol":typeof i}var ry=iy(function(){}),ny=$t(function(i,e){var t=Array.prototype.slice;e.exports=s;function s(r,n){for(("length"in r)||(r=[r]),r=t.call(r);r.length;){var a=r.shift(),o=n(a);if(o)return o;a.childNodes&&a.childNodes.length&&(r=t.call(a.childNodes).concat(r))}}}),PI=$t(function(i,e){Ur(),e.exports=t;function t(s,r){if(!Nr(this,t))return new t(s,r);this.data=s,this.nodeValue=s,this.length=s.length,this.ownerDocument=r||null}t.prototype.nodeType=8,t.prototype.nodeName="#comment",t.prototype.toString=function(){return"[object Comment]"}}),OI=$t(function(i,e){Ur(),e.exports=t;function t(s,r){if(!Nr(this,t))return new t(s);this.data=s||"",this.length=this.data.length,this.ownerDocument=r||null}t.prototype.type="DOMTextNode",t.prototype.nodeType=3,t.prototype.nodeName="#text",t.prototype.toString=function(){return this.data},t.prototype.replaceData=function(s,r,n){var a=this.data,o=a.substring(0,s),l=a.substring(s+r,a.length);this.data=o+n+l,this.length=this.data.length}}),ay=$t(function(i,e){e.exports=t;function t(s){var r=this,n=s.type;s.target||(s.target=r),r.listeners||(r.listeners={});var a=r.listeners[n];if(a)return a.forEach(function(o){s.currentTarget=r,typeof o=="function"?o(s):o.handleEvent(s)});r.parentNode&&r.parentNode.dispatchEvent(s)}}),oy=$t(function(i,e){e.exports=t;function t(s,r){var n=this;n.listeners||(n.listeners={}),n.listeners[s]||(n.listeners[s]=[]),n.listeners[s].indexOf(r)===-1&&n.listeners[s].push(r)}}),ly=$t(function(i,e){e.exports=t;function t(s,r){var n=this;if(n.listeners&&n.listeners[s]){var a=n.listeners[s],o=a.indexOf(r);o!==-1&&a.splice(o,1)}}}),NI=$t(function(i,e){ry(),e.exports=s;var t=["area","base","br","col","embed","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr"];function s(h){switch(h.nodeType){case 3:return u(h.data);case 8:return"<!--"+h.data+"-->";default:return r(h)}}function r(h){var f=[],m=h.tagName;return h.namespaceURI==="http://www.w3.org/1999/xhtml"&&(m=m.toLowerCase()),f.push("<"+m+d(h)+o(h)),t.indexOf(m)>-1?f.push(" />"):(f.push(">"),h.childNodes.length?f.push.apply(f,h.childNodes.map(s)):h.textContent||h.innerText?f.push(u(h.textContent||h.innerText)):h.innerHTML&&f.push(h.innerHTML),f.push("</"+m+">")),f.join("")}function n(h,f){var m=sy(h[f]);return f==="style"&&Object.keys(h.style).length>0?!0:h.hasOwnProperty(f)&&(m==="string"||m==="boolean"||m==="number")&&f!=="nodeName"&&f!=="className"&&f!=="tagName"&&f!=="textContent"&&f!=="innerText"&&f!=="namespaceURI"&&f!=="innerHTML"}function a(h){if(typeof h=="string")return h;var f="";return Object.keys(h).forEach(function(m){var p=h[m];m=m.replace(/[A-Z]/g,function(g){return"-"+g.toLowerCase()}),f+=m+":"+p+";"}),f}function o(h){var f=h.dataset,m=[];for(var p in f)m.push({name:"data-"+p,value:f[p]});return m.length?l(m):""}function l(h){var f=[];return h.forEach(function(m){var p=m.name,g=m.value;p==="style"&&(g=a(g)),f.push(p+'="'+c(g)+'"')}),f.length?" "+f.join(" "):""}function d(h){var f=[];for(var m in h)n(h,m)&&f.push({name:m,value:h[m]});for(var p in h._attributes)for(var g in h._attributes[p]){var v=h._attributes[p][g],b=(v.prefix?v.prefix+":":"")+g;f.push({name:b,value:v.value})}return h.className&&f.push({name:"class",value:h.className}),f.length?l(f):""}function u(h){var f="";return typeof h=="string"?f=h:h&&(f=h.toString()),f.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function c(h){return u(h).replace(/"/g,""")}}),dy=$t(function(i,e){Ur();var t=ny(),s=ay(),r=oy(),n=ly(),a=NI(),o="http://www.w3.org/1999/xhtml";e.exports=l;function l(d,u,c){if(!Nr(this,l))return new l(d);var h=c===void 0?o:c||null;this.tagName=h===o?String(d).toUpperCase():d,this.nodeName=this.tagName,this.className="",this.dataset={},this.childNodes=[],this.parentNode=null,this.style={},this.ownerDocument=u||null,this.namespaceURI=h,this._attributes={},this.tagName==="INPUT"&&(this.type="text")}l.prototype.type="DOMElement",l.prototype.nodeType=1,l.prototype.appendChild=function(d){return d.parentNode&&d.parentNode.removeChild(d),this.childNodes.push(d),d.parentNode=this,d},l.prototype.replaceChild=function(d,u){d.parentNode&&d.parentNode.removeChild(d);var c=this.childNodes.indexOf(u);return u.parentNode=null,this.childNodes[c]=d,d.parentNode=this,u},l.prototype.removeChild=function(d){var u=this.childNodes.indexOf(d);return this.childNodes.splice(u,1),d.parentNode=null,d},l.prototype.insertBefore=function(d,u){d.parentNode&&d.parentNode.removeChild(d);var c=u==null?-1:this.childNodes.indexOf(u);return c>-1?this.childNodes.splice(c,0,d):this.childNodes.push(d),d.parentNode=this,d},l.prototype.setAttributeNS=function(d,u,c){var h=null,f=u,m=u.indexOf(":");if(m>-1&&(h=u.substr(0,m),f=u.substr(m+1)),this.tagName==="INPUT"&&u==="type")this.type=c;else{var p=this._attributes[d]||(this._attributes[d]={});p[f]={value:c,prefix:h}}},l.prototype.getAttributeNS=function(d,u){var c=this._attributes[d],h=c&&c[u]&&c[u].value;return this.tagName==="INPUT"&&u==="type"?this.type:typeof h!="string"?null:h},l.prototype.removeAttributeNS=function(d,u){var c=this._attributes[d];c&&delete c[u]},l.prototype.hasAttributeNS=function(d,u){var c=this._attributes[d];return!!c&&u in c},l.prototype.setAttribute=function(d,u){return this.setAttributeNS(null,d,u)},l.prototype.getAttribute=function(d){return this.getAttributeNS(null,d)},l.prototype.removeAttribute=function(d){return this.removeAttributeNS(null,d)},l.prototype.hasAttribute=function(d){return this.hasAttributeNS(null,d)},l.prototype.removeEventListener=n,l.prototype.addEventListener=r,l.prototype.dispatchEvent=s,l.prototype.focus=function(){},l.prototype.toString=function(){return a(this)},l.prototype.getElementsByClassName=function(d){var u=d.split(" "),c=[];return t(this,function(h){if(h.nodeType===1){var f=h.className||"",m=f.split(" ");u.every(function(p){return m.indexOf(p)!==-1})&&c.push(h)}}),c},l.prototype.getElementsByTagName=function(d){d=d.toLowerCase();var u=[];return t(this.childNodes,function(c){c.nodeType===1&&(d==="*"||c.tagName.toLowerCase()===d)&&u.push(c)}),u},l.prototype.contains=function(d){return t(this,function(u){return d===u})||!1}}),UI=$t(function(i,e){Ur();var t=dy();e.exports=s;function s(r){if(!Nr(this,s))return new s;this.childNodes=[],this.parentNode=null,this.ownerDocument=r||null}s.prototype.type="DocumentFragment",s.prototype.nodeType=11,s.prototype.nodeName="#document-fragment",s.prototype.appendChild=t.prototype.appendChild,s.prototype.replaceChild=t.prototype.replaceChild,s.prototype.removeChild=t.prototype.removeChild,s.prototype.toString=function(){return this.childNodes.map(function(r){return String(r)}).join("")}}),$I=$t(function(i,e){e.exports=t;function t(s){}t.prototype.initEvent=function(s,r,n){this.type=s,this.bubbles=r,this.cancelable=n},t.prototype.preventDefault=function(){}}),FI=$t(function(i,e){Ur();var t=ny(),s=PI(),r=OI(),n=dy(),a=UI(),o=$I(),l=ay(),d=oy(),u=ly();e.exports=c;function c(){if(!Nr(this,c))return new c;this.head=this.createElement("head"),this.body=this.createElement("body"),this.documentElement=this.createElement("html"),this.documentElement.appendChild(this.head),this.documentElement.appendChild(this.body),this.childNodes=[this.documentElement],this.nodeType=9}var h=c.prototype;h.createTextNode=function(f){return new r(f,this)},h.createElementNS=function(f,m){var p=f===null?null:String(f);return new n(m,this,p)},h.createElement=function(f){return new n(f,this)},h.createDocumentFragment=function(){return new a(this)},h.createEvent=function(f){return new o(f)},h.createComment=function(f){return new s(f,this)},h.getElementById=function(f){f=String(f);var m=t(this.childNodes,function(p){if(String(p.id)===f)return p});return m||null},h.getElementsByClassName=n.prototype.getElementsByClassName,h.getElementsByTagName=n.prototype.getElementsByTagName,h.contains=n.prototype.contains,h.removeEventListener=u,h.addEventListener=d,h.dispatchEvent=l}),BI=$t(function(i,e){var t=FI();e.exports=new t}),uy=$t(function(i,e){var t=typeof global<"u"?global:typeof window<"u"?window:{},s=BI(),r;typeof document<"u"?r=document:(r=t["__GLOBAL_DOCUMENT_CACHE@4"],r||(r=t["__GLOBAL_DOCUMENT_CACHE@4"]=s)),e.exports=r});function HI(i){if(Array.isArray(i))return i}function GI(i,e){var t=i==null?null:typeof Symbol<"u"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var s=[],r=!0,n=!1,a,o;try{for(t=t.call(i);!(r=(a=t.next()).done)&&(s.push(a.value),!(e&&s.length===e));r=!0);}catch(l){n=!0,o=l}finally{try{!r&&t.return!=null&&t.return()}finally{if(n)throw o}}return s}}function KI(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
1403
1403
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function wh(i,e){(e==null||e>i.length)&&(e=i.length);for(var t=0,s=new Array(e);t<e;t++)s[t]=i[t];return s}function cy(i,e){if(i){if(typeof i=="string")return wh(i,e);var t=Object.prototype.toString.call(i).slice(8,-1);if(t==="Object"&&i.constructor&&(t=i.constructor.name),t==="Map"||t==="Set")return Array.from(t);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return wh(i,e)}}function bs(i,e){return HI(i)||GI(i,e)||cy(i,e)||KI()}var Ya=Jt(Ii()),Eg=Jt(Ii()),VI=Jt(Ii()),WI={now:function(){var i=VI.default.performance,e=i&&i.timing,t=e&&e.navigationStart,s=typeof t=="number"&&typeof i.now=="function"?t+i.now():Date.now();return Math.round(s)}},dt=WI,ho=function(){var i,e,t;if(typeof((i=Eg.default.crypto)===null||i===void 0?void 0:i.getRandomValues)=="function"){t=new Uint8Array(32),Eg.default.crypto.getRandomValues(t);for(var s=0;s<32;s++)t[s]=t[s]%16}else{t=[];for(var r=0;r<32;r++)t[r]=Math.random()*16|0}var n=0;e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(l){var d=l==="x"?t[n]:t[n]&3|8;return n++,d.toString(16)});var a=dt.now(),o=a?.toString(16).substring(3);return o?e.substring(0,28)+o:e},hy=function(){return("000000"+(Math.random()*Math.pow(36,6)<<0).toString(36)).slice(-6)},pi=function(i){if(i&&typeof i.nodeName<"u")return i.muxId||(i.muxId=hy()),i.muxId;var e;try{e=document.querySelector(i)}catch{}return e&&!e.muxId&&(e.muxId=i),e?.muxId||i},Vd=function(i){var e;i&&typeof i.nodeName<"u"?(e=i,i=pi(e)):e=document.querySelector(i);var t=e&&e.nodeName?e.nodeName.toLowerCase():"";return[e,i,t]};function qI(i){if(Array.isArray(i))return wh(i)}function YI(i){if(typeof Symbol<"u"&&i[Symbol.iterator]!=null||i["@@iterator"]!=null)return Array.from(i)}function jI(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
1404
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function gi(i){return qI(i)||YI(i)||cy(i)||jI()}var gr={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4},zI=function(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:3,t,s,r,n,a,o=[console,i],l=(t=console.trace).bind.apply(t,gi(o)),d=(s=console.info).bind.apply(s,gi(o)),u=(r=console.debug).bind.apply(r,gi(o)),c=(n=console.warn).bind.apply(n,gi(o)),h=(a=console.error).bind.apply(a,gi(o)),f=e;return{trace:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>gr.TRACE))return l.apply(void 0,gi(p))},debug:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>gr.DEBUG))return u.apply(void 0,gi(p))},info:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>gr.INFO))return d.apply(void 0,gi(p))},warn:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>gr.WARN))return c.apply(void 0,gi(p))},error:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>gr.ERROR))return h.apply(void 0,gi(p))},get level(){return f},set level(m){m!==this.level&&(f=m??e)}}},Ne=zI("[mux]"),fc=Jt(Ii());function Mh(){var i=fc.default.doNotTrack||fc.default.navigator&&fc.default.navigator.doNotTrack;return i==="1"}function le(i){if(i===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return i}Ur();function Tt(i,e){if(!Nr(i,e))throw new TypeError("Cannot call a class as a function")}function QI(i,e){for(var t=0;t<e.length;t++){var s=e[t];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(i,s.key,s)}}function ns(i,e,t){return e&&QI(i.prototype,e),i}function
|
|
1404
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function gi(i){return qI(i)||YI(i)||cy(i)||jI()}var gr={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4},zI=function(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:3,t,s,r,n,a,o=[console,i],l=(t=console.trace).bind.apply(t,gi(o)),d=(s=console.info).bind.apply(s,gi(o)),u=(r=console.debug).bind.apply(r,gi(o)),c=(n=console.warn).bind.apply(n,gi(o)),h=(a=console.error).bind.apply(a,gi(o)),f=e;return{trace:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>gr.TRACE))return l.apply(void 0,gi(p))},debug:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>gr.DEBUG))return u.apply(void 0,gi(p))},info:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>gr.INFO))return d.apply(void 0,gi(p))},warn:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>gr.WARN))return c.apply(void 0,gi(p))},error:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>gr.ERROR))return h.apply(void 0,gi(p))},get level(){return f},set level(m){m!==this.level&&(f=m??e)}}},Ne=zI("[mux]"),fc=Jt(Ii());function Mh(){var i=fc.default.doNotTrack||fc.default.navigator&&fc.default.navigator.doNotTrack;return i==="1"}function le(i){if(i===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return i}Ur();function Tt(i,e){if(!Nr(i,e))throw new TypeError("Cannot call a class as a function")}function QI(i,e){for(var t=0;t<e.length;t++){var s=e[t];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(i,s.key,s)}}function ns(i,e,t){return e&&QI(i.prototype,e),i}function Y(i,e,t){return e in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function Qn(i){return Qn=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},Qn(i)}function XI(i,e){for(;!Object.prototype.hasOwnProperty.call(i,e)&&(i=Qn(i),i!==null););return i}function Bl(i,e,t){return typeof Reflect<"u"&&Reflect.get?Bl=Reflect.get:Bl=function(s,r,n){var a=XI(s,r);if(a){var o=Object.getOwnPropertyDescriptor(a,r);return o.get?o.get.call(n||s):o.value}},Bl(i,e,t||i)}function Ph(i,e){return Ph=Object.setPrototypeOf||function(t,s){return t.__proto__=s,t},Ph(i,e)}function ZI(i,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");i.prototype=Object.create(e&&e.prototype,{constructor:{value:i,writable:!0,configurable:!0}}),e&&Ph(i,e)}function JI(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}ry();function ex(i,e){return e&&(sy(e)==="object"||typeof e=="function")?e:le(i)}function tx(i){var e=JI();return function(){var t=Qn(i),s;if(e){var r=Qn(this).constructor;s=Reflect.construct(t,arguments,r)}else s=t.apply(this,arguments);return ex(this,s)}}var _i=function(i){return fo(i)[0]},fo=function(i){if(typeof i!="string"||i==="")return["localhost"];var e=/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,t=i.match(e)||[],s=t[4],r;return s&&(r=(s.match(/[^\.]+\.[^\.]+$/)||[])[0]),[s,r]},mc=Jt(Ii()),ix={exists:function(){var i=mc.default.performance,e=i&&i.timing;return e!==void 0},domContentLoadedEventEnd:function(){var i=mc.default.performance,e=i&&i.timing;return e&&e.domContentLoadedEventEnd},navigationStart:function(){var i=mc.default.performance,e=i&&i.timing;return e&&e.navigationStart}},Wd=ix;function ot(i,e,t){t=t===void 0?1:t,i[e]=i[e]||0,i[e]+=t}function qd(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{},s=Object.keys(t);typeof Object.getOwnPropertySymbols=="function"&&(s=s.concat(Object.getOwnPropertySymbols(t).filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable}))),s.forEach(function(r){Y(i,r,t[r])})}return i}function sx(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(i);t.push.apply(t,s)}return t}function xm(i,e){return e=e??{},Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(e)):sx(Object(e)).forEach(function(t){Object.defineProperty(i,t,Object.getOwnPropertyDescriptor(e,t))}),i}var rx=["x-cdn","content-type"],fy=["x-request-id","cf-ray","x-amz-cf-id","x-akamai-request-id"],nx=rx.concat(fy);function Lm(i){i=i||"";var e={},t=i.trim().split(/[\r\n]+/);return t.forEach(function(s){if(s){var r=s.split(": "),n=r.shift();n&&(nx.indexOf(n.toLowerCase())>=0||n.toLowerCase().indexOf("x-litix-")===0)&&(e[n]=r.join(": "))}}),e}function Yd(i){if(i){var e=fy.find(function(t){return i[t]!==void 0});return e?i[e]:void 0}}var ax=function(i){var e={};for(var t in i){var s=i[t],r=s["DATA-ID"].search("io.litix.data.");if(r!==-1){var n=s["DATA-ID"].replace("io.litix.data.","");e[n]=s.VALUE}}return e},my=ax,Wo=function(i){if(!i)return{};var e=Wd.navigationStart(),t=i.loading,s=t?t.start:i.trequest,r=t?t.first:i.tfirst,n=t?t.end:i.tload;return{bytesLoaded:i.total,requestStart:Math.round(e+s),responseStart:Math.round(e+r),responseEnd:Math.round(e+n)}},da=function(i){if(!(!i||typeof i.getAllResponseHeaders!="function"))return Lm(i.getAllResponseHeaders())},ox=function(i,e,t){var s=arguments.length>4?arguments[4]:void 0,r=i.log,n=i.utils.secondsToMs,a=function(g){var v=parseInt(s.version),b;return v===1&&g.programDateTime!==null&&(b=g.programDateTime),v===0&&g.pdt!==null&&(b=g.pdt),b};if(!Wd.exists()){r.warn("performance timing not supported. Not tracking HLS.js.");return}var o=function(g,v){return i.emit(e,g,v)},l=function(g,v){var b=v.levels,E=v.audioTracks,T=v.url,A=v.stats,x=v.networkDetails,S=v.sessionData,L={},R={};b.forEach(function(K,H){L[H]={width:K.width,height:K.height,bitrate:K.bitrate,attrs:K.attrs}}),E.forEach(function(K,H){R[H]={name:K.name,language:K.lang,bitrate:K.bitrate}});var I=Wo(A),M=I.bytesLoaded,B=I.requestStart,q=I.responseStart,z=I.responseEnd;o("requestcompleted",xm(qd({},my(S)),{request_event_type:g,request_bytes_loaded:M,request_start:B,request_response_start:q,request_response_end:z,request_type:"manifest",request_hostname:_i(T),request_response_headers:da(x),request_rendition_lists:{media:L,audio:R,video:{}}}))};t.on(s.Events.MANIFEST_LOADED,l);var d=function(g,v){var b=v.details,E=v.level,T=v.networkDetails,A=v.stats,x=Wo(A),S=x.bytesLoaded,L=x.requestStart,R=x.responseStart,I=x.responseEnd,M=b.fragments[b.fragments.length-1],B=a(M)+n(M.duration);o("requestcompleted",{request_event_type:g,request_bytes_loaded:S,request_start:L,request_response_start:R,request_response_end:I,request_current_level:E,request_type:"manifest",request_hostname:_i(b.url),request_response_headers:da(T),video_holdback:b.holdBack&&n(b.holdBack),video_part_holdback:b.partHoldBack&&n(b.partHoldBack),video_part_target_duration:b.partTarget&&n(b.partTarget),video_target_duration:b.targetduration&&n(b.targetduration),video_source_is_live:b.live,player_manifest_newest_program_time:isNaN(B)?void 0:B})};t.on(s.Events.LEVEL_LOADED,d);var u=function(g,v){var b=v.details,E=v.networkDetails,T=v.stats,A=Wo(T),x=A.bytesLoaded,S=A.requestStart,L=A.responseStart,R=A.responseEnd;o("requestcompleted",{request_event_type:g,request_bytes_loaded:x,request_start:S,request_response_start:L,request_response_end:R,request_type:"manifest",request_hostname:_i(b.url),request_response_headers:da(E)})};t.on(s.Events.AUDIO_TRACK_LOADED,u);var c=function(g,v){var b=v.stats,E=v.networkDetails,T=v.frag;b=b||T.stats;var A=Wo(b),x=A.bytesLoaded,S=A.requestStart,L=A.responseStart,R=A.responseEnd,I=E?da(E):void 0,M={request_event_type:g,request_bytes_loaded:x,request_start:S,request_response_start:L,request_response_end:R,request_hostname:E?_i(E.responseURL):void 0,request_id:I?Yd(I):void 0,request_response_headers:I,request_media_duration:T.duration,request_url:E?.responseURL};T.type==="main"?(M.request_type="media",M.request_current_level=T.level,M.request_video_width=(t.levels[T.level]||{}).width,M.request_video_height=(t.levels[T.level]||{}).height,M.request_labeled_bitrate=(t.levels[T.level]||{}).bitrate):M.request_type=T.type,o("requestcompleted",M)};t.on(s.Events.FRAG_LOADED,c);var h=function(g,v){var b=v.frag,E=b.start,T=a(b),A={currentFragmentPDT:T,currentFragmentStart:n(E)};o("fragmentchange",A)};t.on(s.Events.FRAG_CHANGED,h);var f=function(g,v){var b=v.type,E=v.details,T=v.response,A=v.fatal,x=v.frag,S=v.networkDetails,L=x?.url||v.url||"",R=S?da(S):void 0;if((E===s.ErrorDetails.MANIFEST_LOAD_ERROR||E===s.ErrorDetails.MANIFEST_LOAD_TIMEOUT||E===s.ErrorDetails.FRAG_LOAD_ERROR||E===s.ErrorDetails.FRAG_LOAD_TIMEOUT||E===s.ErrorDetails.LEVEL_LOAD_ERROR||E===s.ErrorDetails.LEVEL_LOAD_TIMEOUT||E===s.ErrorDetails.AUDIO_TRACK_LOAD_ERROR||E===s.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT||E===s.ErrorDetails.SUBTITLE_LOAD_ERROR||E===s.ErrorDetails.SUBTITLE_LOAD_TIMEOUT||E===s.ErrorDetails.KEY_LOAD_ERROR||E===s.ErrorDetails.KEY_LOAD_TIMEOUT)&&o("requestfailed",{request_error:E,request_url:L,request_hostname:_i(L),request_id:R?Yd(R):void 0,request_type:E===s.ErrorDetails.FRAG_LOAD_ERROR||E===s.ErrorDetails.FRAG_LOAD_TIMEOUT?"media":E===s.ErrorDetails.AUDIO_TRACK_LOAD_ERROR||E===s.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT?"audio":E===s.ErrorDetails.SUBTITLE_LOAD_ERROR||E===s.ErrorDetails.SUBTITLE_LOAD_TIMEOUT?"subtitle":E===s.ErrorDetails.KEY_LOAD_ERROR||E===s.ErrorDetails.KEY_LOAD_TIMEOUT?"encryption":"manifest",request_error_code:T?.code,request_error_text:T?.text}),A){var I,M="".concat(L?"url: ".concat(L,`
|
|
1405
1405
|
`):"")+"".concat(T&&(T.code||T.text)?"response: ".concat(T.code,", ").concat(T.text,`
|
|
1406
1406
|
`):"")+"".concat(v.reason?"failure reason: ".concat(v.reason,`
|
|
1407
1407
|
`):"")+"".concat(v.level?"level: ".concat(v.level,`
|
|
@@ -1410,53 +1410,53 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1410
1410
|
`):"")+"".concat(v.error?"error: ".concat(v.error,`
|
|
1411
1411
|
`):"")+"".concat(v.event?"event: ".concat(v.event,`
|
|
1412
1412
|
`):"")+"".concat(v.err?"error message: ".concat((I=v.err)===null||I===void 0?void 0:I.message,`
|
|
1413
|
-
`):"");o("error",{player_error_code:b,player_error_message:E,player_error_context:M})}};t.on(s.Events.ERROR,f);var m=function(g,v){var b=v.frag,E=b&&b._url||"";o("requestcanceled",{request_event_type:g,request_url:E,request_type:"media",request_hostname:_i(E)})};t.on(s.Events.FRAG_LOAD_EMERGENCY_ABORTED,m);var p=function(g,v){var b=v.level,E=t.levels[b];if(E&&E.attrs&&E.attrs.BANDWIDTH){var T=E.attrs.BANDWIDTH,A,x=parseFloat(E.attrs["FRAME-RATE"]);isNaN(x)||(A=x),T?o("renditionchange",{video_source_fps:A,video_source_bitrate:T,video_source_width:E.width,video_source_height:E.height,video_source_rendition_name:E.name,video_source_codec:E?.videoCodec}):r.warn("missing BANDWIDTH from HLS manifest parsed by HLS.js")}};t.on(s.Events.LEVEL_SWITCHED,p),t._stopMuxMonitor=function(){t.off(s.Events.MANIFEST_LOADED,l),t.off(s.Events.LEVEL_LOADED,d),t.off(s.Events.AUDIO_TRACK_LOADED,u),t.off(s.Events.FRAG_LOADED,c),t.off(s.Events.FRAG_CHANGED,h),t.off(s.Events.ERROR,f),t.off(s.Events.FRAG_LOAD_EMERGENCY_ABORTED,m),t.off(s.Events.LEVEL_SWITCHED,p),t.off(s.Events.DESTROYING,t._stopMuxMonitor),delete t._stopMuxMonitor},t.on(s.Events.DESTROYING,t._stopMuxMonitor)},lx=function(i){i&&typeof i._stopMuxMonitor=="function"&&i._stopMuxMonitor()},yg=function(i,e){if(!i||!i.requestEndDate)return{};var t=_i(i.url),s=i.url,r=i.bytesLoaded,n=new Date(i.requestStartDate).getTime(),a=new Date(i.firstByteDate).getTime(),o=new Date(i.requestEndDate).getTime(),l=isNaN(i.duration)?0:i.duration,d=typeof e.getMetricsFor=="function"?e.getMetricsFor(i.mediaType).HttpList:e.getDashMetrics().getHttpRequests(i.mediaType),u;d.length>0&&(u=Lm(d[d.length-1]._responseHeaders||""));var c=u?Yd(u):void 0;return{requestStart:n,requestResponseStart:a,requestResponseEnd:o,requestBytesLoaded:r,requestResponseHeaders:u,requestMediaDuration:l,requestHostname:t,requestUrl:s,requestId:c}},dx=function(i,e){var t=e.getQualityFor(i),s=e.getCurrentTrackFor(i).bitrateList;return s?{currentLevel:t,renditionWidth:s[t].width||null,renditionHeight:s[t].height||null,renditionBitrate:s[t].bandwidth}:{}},ux=function(i){var e;return(e=i.match(/.*codecs\*?="(.*)"/))===null||e===void 0?void 0:e[1]},cx=function(i){try{var e,t,s=(t=i.getVersion)===null||t===void 0||(e=t.call(i))===null||e===void 0?void 0:e.split(".").map(function(r){return parseInt(r)})[0];return s}catch{return!1}},hx=function(i,e,t){var s=i.log;if(!t||!t.on){s.warn("Invalid dash.js player reference. Monitoring blocked.");return}var r=cx(t),n=function(b,E){return i.emit(e,b,E)},a=function(b){var E=b.type,T=b.data,A=(T||{}).url;n("requestcompleted",{request_event_type:E,request_start:0,request_response_start:0,request_response_end:0,request_bytes_loaded:-1,request_type:"manifest",request_hostname:_i(A),request_url:A})};t.on("manifestLoaded",a);var o={},l=function(b){if(typeof b.getRequests!="function")return null;var E=b.getRequests({state:"executed"});return E.length===0?null:E[E.length-1]},d=function(b){var E=b.type,T=b.fragmentModel,A=b.chunk,x=l(T);u({type:E,request:x,chunk:A})},u=function(b){var E=b.type,T=b.chunk,A=b.request,x=(T||{}).mediaInfo,S=x||{},L=S.type,R=S.bitrateList;R=R||[];var I={};R.forEach(function(
|
|
1413
|
+
`):"");o("error",{player_error_code:b,player_error_message:E,player_error_context:M})}};t.on(s.Events.ERROR,f);var m=function(g,v){var b=v.frag,E=b&&b._url||"";o("requestcanceled",{request_event_type:g,request_url:E,request_type:"media",request_hostname:_i(E)})};t.on(s.Events.FRAG_LOAD_EMERGENCY_ABORTED,m);var p=function(g,v){var b=v.level,E=t.levels[b];if(E&&E.attrs&&E.attrs.BANDWIDTH){var T=E.attrs.BANDWIDTH,A,x=parseFloat(E.attrs["FRAME-RATE"]);isNaN(x)||(A=x),T?o("renditionchange",{video_source_fps:A,video_source_bitrate:T,video_source_width:E.width,video_source_height:E.height,video_source_rendition_name:E.name,video_source_codec:E?.videoCodec}):r.warn("missing BANDWIDTH from HLS manifest parsed by HLS.js")}};t.on(s.Events.LEVEL_SWITCHED,p),t._stopMuxMonitor=function(){t.off(s.Events.MANIFEST_LOADED,l),t.off(s.Events.LEVEL_LOADED,d),t.off(s.Events.AUDIO_TRACK_LOADED,u),t.off(s.Events.FRAG_LOADED,c),t.off(s.Events.FRAG_CHANGED,h),t.off(s.Events.ERROR,f),t.off(s.Events.FRAG_LOAD_EMERGENCY_ABORTED,m),t.off(s.Events.LEVEL_SWITCHED,p),t.off(s.Events.DESTROYING,t._stopMuxMonitor),delete t._stopMuxMonitor},t.on(s.Events.DESTROYING,t._stopMuxMonitor)},lx=function(i){i&&typeof i._stopMuxMonitor=="function"&&i._stopMuxMonitor()},yg=function(i,e){if(!i||!i.requestEndDate)return{};var t=_i(i.url),s=i.url,r=i.bytesLoaded,n=new Date(i.requestStartDate).getTime(),a=new Date(i.firstByteDate).getTime(),o=new Date(i.requestEndDate).getTime(),l=isNaN(i.duration)?0:i.duration,d=typeof e.getMetricsFor=="function"?e.getMetricsFor(i.mediaType).HttpList:e.getDashMetrics().getHttpRequests(i.mediaType),u;d.length>0&&(u=Lm(d[d.length-1]._responseHeaders||""));var c=u?Yd(u):void 0;return{requestStart:n,requestResponseStart:a,requestResponseEnd:o,requestBytesLoaded:r,requestResponseHeaders:u,requestMediaDuration:l,requestHostname:t,requestUrl:s,requestId:c}},dx=function(i,e){var t=e.getQualityFor(i),s=e.getCurrentTrackFor(i).bitrateList;return s?{currentLevel:t,renditionWidth:s[t].width||null,renditionHeight:s[t].height||null,renditionBitrate:s[t].bandwidth}:{}},ux=function(i){var e;return(e=i.match(/.*codecs\*?="(.*)"/))===null||e===void 0?void 0:e[1]},cx=function(i){try{var e,t,s=(t=i.getVersion)===null||t===void 0||(e=t.call(i))===null||e===void 0?void 0:e.split(".").map(function(r){return parseInt(r)})[0];return s}catch{return!1}},hx=function(i,e,t){var s=i.log;if(!t||!t.on){s.warn("Invalid dash.js player reference. Monitoring blocked.");return}var r=cx(t),n=function(b,E){return i.emit(e,b,E)},a=function(b){var E=b.type,T=b.data,A=(T||{}).url;n("requestcompleted",{request_event_type:E,request_start:0,request_response_start:0,request_response_end:0,request_bytes_loaded:-1,request_type:"manifest",request_hostname:_i(A),request_url:A})};t.on("manifestLoaded",a);var o={},l=function(b){if(typeof b.getRequests!="function")return null;var E=b.getRequests({state:"executed"});return E.length===0?null:E[E.length-1]},d=function(b){var E=b.type,T=b.fragmentModel,A=b.chunk,x=l(T);u({type:E,request:x,chunk:A})},u=function(b){var E=b.type,T=b.chunk,A=b.request,x=(T||{}).mediaInfo,S=x||{},L=S.type,R=S.bitrateList;R=R||[];var I={};R.forEach(function(W,U){I[U]={},I[U].width=W.width,I[U].height=W.height,I[U].bitrate=W.bandwidth,I[U].attrs={}}),L==="video"?o.video=I:L==="audio"?o.audio=I:o.media=I;var M=yg(A,t),B=M.requestStart,q=M.requestResponseStart,z=M.requestResponseEnd,K=M.requestResponseHeaders,H=M.requestMediaDuration,j=M.requestHostname,G=M.requestUrl,N=M.requestId;n("requestcompleted",{request_event_type:E,request_start:B,request_response_start:q,request_response_end:z,request_bytes_loaded:-1,request_type:L+"_init",request_response_headers:K,request_hostname:j,request_id:N,request_url:G,request_media_duration:H,request_rendition_lists:o})};r>=4?t.on("initFragmentLoaded",u):t.on("initFragmentLoaded",d);var c=function(b){var E=b.type,T=b.fragmentModel,A=b.chunk,x=l(T);h({type:E,request:x,chunk:A})},h=function(b){var E=b.type,T=b.chunk,A=b.request,x=T||{},S=x.mediaInfo,L=x.start,R=S||{},I=R.type,M=yg(A,t),B=M.requestStart,q=M.requestResponseStart,z=M.requestResponseEnd,K=M.requestBytesLoaded,H=M.requestResponseHeaders,j=M.requestMediaDuration,G=M.requestHostname,N=M.requestUrl,W=M.requestId,U=dx(I,t),$=U.currentLevel,re=U.renditionWidth,he=U.renditionHeight,ce=U.renditionBitrate;n("requestcompleted",{request_event_type:E,request_start:B,request_response_start:q,request_response_end:z,request_bytes_loaded:K,request_type:I,request_response_headers:H,request_hostname:G,request_id:W,request_url:N,request_media_start_time:L,request_media_duration:j,request_current_level:$,request_labeled_bitrate:ce,request_video_width:re,request_video_height:he})};r>=4?t.on("mediaFragmentLoaded",h):t.on("mediaFragmentLoaded",c);var f={video:void 0,audio:void 0,totalBitrate:void 0},m=function(){if(f.video&&typeof f.video.bitrate=="number"){if(!(f.video.width&&f.video.height)){s.warn("have bitrate info for video but missing width/height");return}var b=f.video.bitrate;if(f.audio&&typeof f.audio.bitrate=="number"&&(b+=f.audio.bitrate),b!==f.totalBitrate)return f.totalBitrate=b,{video_source_bitrate:b,video_source_height:f.video.height,video_source_width:f.video.width,video_source_codec:ux(f.video.codec)}}},p=function(b,E,T){if(typeof b.newQuality!="number"){s.warn("missing evt.newQuality in qualityChangeRendered event",b);return}var A=b.mediaType;if(A==="audio"||A==="video"){var x=t.getBitrateInfoListFor(A).find(function(L){var R=L.qualityIndex;return R===b.newQuality});if(!(x&&typeof x.bitrate=="number")){s.warn("missing bitrate info for ".concat(A));return}f[A]=xm(qd({},x),{codec:t.getCurrentTrackFor(A).codec});var S=m();S&&n("renditionchange",S)}};t.on("qualityChangeRendered",p);var g=function(b){var E=b.request,T=b.mediaType;E=E||{},n("requestcanceled",{request_event_type:E.type+"_"+E.action,request_url:E.url,request_type:T,request_hostname:_i(E.url)})};t.on("fragmentLoadingAbandoned",g);var v=function(b){var E=b.error,T,A,x=(E==null||(T=E.data)===null||T===void 0?void 0:T.request)||{},S=(E==null||(A=E.data)===null||A===void 0?void 0:A.response)||{};E?.code===27&&n("requestfailed",{request_error:x.type+"_"+x.action,request_url:x.url,request_hostname:_i(x.url),request_type:x.mediaType,request_error_code:S.status,request_error_text:S.statusText});var L="".concat(x!=null&&x.url?"url: ".concat(x.url,`
|
|
1414
1414
|
`):"")+"".concat(S!=null&&S.status||S!=null&&S.statusText?"response: ".concat(S?.status,", ").concat(S?.statusText,`
|
|
1415
|
-
`):"");n("error",{player_error_code:E?.code,player_error_message:E?.message,player_error_context:L})};t.on("error",v),t._stopMuxMonitor=function(){t.off("manifestLoaded",a),t.off("initFragmentLoaded",u),t.off("mediaFragmentLoaded",h),t.off("qualityChangeRendered",p),t.off("error",v),t.off("fragmentLoadingAbandoned",g),delete t._stopMuxMonitor}},fx=function(i){i&&typeof i._stopMuxMonitor=="function"&&i._stopMuxMonitor()},bg=0,mx=(function(){function i(){Tt(this,i),q(this,"_listeners",void 0)}return ns(i,[{key:"on",value:function(e,t,s){return t._eventEmitterGuid=t._eventEmitterGuid||++bg,this._listeners=this._listeners||{},this._listeners[e]=this._listeners[e]||[],s&&(t=t.bind(s)),this._listeners[e].push(t),t}},{key:"off",value:function(e,t){var s=this._listeners&&this._listeners[e];s&&s.forEach(function(r,n){r._eventEmitterGuid===t._eventEmitterGuid&&s.splice(n,1)})}},{key:"one",value:function(e,t,s){var r=this;t._eventEmitterGuid=t._eventEmitterGuid||++bg;var n=function(){r.off(e,n),t.apply(s||this,arguments)};n._eventEmitterGuid=t._eventEmitterGuid,this.on(e,n)}},{key:"emit",value:function(e,t){var s=this;if(this._listeners){t=t||{};var r=this._listeners["before*"]||[],n=this._listeners[e]||[],a=this._listeners["after"+e]||[],o=function(l,d){l=l.slice(),l.forEach(function(u){u.call(s,{type:e},d)})};o(r,t),o(n,t),o(a,t)}}}]),i})(),px=mx,pc=Jt(Ii()),gx=(function(){function i(e){var t=this;Tt(this,i),q(this,"_playbackHeartbeatInterval",void 0),q(this,"_playheadShouldBeProgressing",void 0),q(this,"pm",void 0),this.pm=e,this._playbackHeartbeatInterval=null,this._playheadShouldBeProgressing=!1,e.on("playing",function(){t._playheadShouldBeProgressing=!0}),e.on("play",this._startPlaybackHeartbeatInterval.bind(this)),e.on("playing",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adbreakstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adplay",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adplaying",this._startPlaybackHeartbeatInterval.bind(this)),e.on("devicewake",this._startPlaybackHeartbeatInterval.bind(this)),e.on("viewstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("rebufferstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("pause",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("ended",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("viewend",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("error",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("aderror",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adpause",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adended",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adbreakend",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("seeked",function(){e.data.player_is_paused?t._stopPlaybackHeartbeatInterval():t._startPlaybackHeartbeatInterval()}),e.on("timeupdate",function(){t._playbackHeartbeatInterval!==null&&e.emit("playbackheartbeat")}),e.on("devicesleep",function(s,r){t._playbackHeartbeatInterval!==null&&(pc.default.clearInterval(t._playbackHeartbeatInterval),e.emit("playbackheartbeatend",{viewer_time:r.viewer_time}),t._playbackHeartbeatInterval=null)})}return ns(i,[{key:"_startPlaybackHeartbeatInterval",value:function(){var e=this;this._playbackHeartbeatInterval===null&&(this.pm.emit("playbackheartbeat"),this._playbackHeartbeatInterval=pc.default.setInterval(function(){e.pm.emit("playbackheartbeat")},this.pm.playbackHeartbeatTime))}},{key:"_stopPlaybackHeartbeatInterval",value:function(){this._playheadShouldBeProgressing=!1,this._playbackHeartbeatInterval!==null&&(pc.default.clearInterval(this._playbackHeartbeatInterval),this.pm.emit("playbackheartbeatend"),this._playbackHeartbeatInterval=null)}}]),i})(),vx=gx,Ex=function i(e){var t=this;Tt(this,i),q(this,"viewErrored",void 0),e.on("viewinit",function(){t.viewErrored=!1}),e.on("error",function(s,r){try{var n=e.errorTranslator({player_error_code:r.player_error_code,player_error_message:r.player_error_message,player_error_context:r.player_error_context,player_error_severity:r.player_error_severity,player_error_business_exception:r.player_error_business_exception});n&&(e.data.player_error_code=n.player_error_code||r.player_error_code,e.data.player_error_message=n.player_error_message||r.player_error_message,e.data.player_error_context=n.player_error_context||r.player_error_context,e.data.player_error_severity=n.player_error_severity||r.player_error_severity,e.data.player_error_business_exception=n.player_error_business_exception||r.player_error_business_exception,t.viewErrored=!0)}catch(a){e.mux.log.warn("Exception in error translator callback.",a),t.viewErrored=!0}}),e.on("aftererror",function(){var s,r,n,a,o;(s=e.data)===null||s===void 0||delete s.player_error_code,(r=e.data)===null||r===void 0||delete r.player_error_message,(n=e.data)===null||n===void 0||delete n.player_error_context,(a=e.data)===null||a===void 0||delete a.player_error_severity,(o=e.data)===null||o===void 0||delete o.player_error_business_exception})},yx=Ex,bx=(function(){function i(e){Tt(this,i),q(this,"_watchTimeTrackerLastCheckedTime",void 0),q(this,"pm",void 0),this.pm=e,this._watchTimeTrackerLastCheckedTime=null,e.on("playbackheartbeat",this._updateWatchTime.bind(this)),e.on("playbackheartbeatend",this._clearWatchTimeState.bind(this))}return ns(i,[{key:"_updateWatchTime",value:function(e,t){var s=t.viewer_time;this._watchTimeTrackerLastCheckedTime===null&&(this._watchTimeTrackerLastCheckedTime=s),ot(this.pm.data,"view_watch_time",s-this._watchTimeTrackerLastCheckedTime),this._watchTimeTrackerLastCheckedTime=s}},{key:"_clearWatchTimeState",value:function(e,t){this._updateWatchTime(e,t),this._watchTimeTrackerLastCheckedTime=null}}]),i})(),Tx=bx,_x=(function(){function i(e){var t=this;Tt(this,i),q(this,"_playbackTimeTrackerLastPlayheadPosition",void 0),q(this,"_lastTime",void 0),q(this,"_isAdPlaying",void 0),q(this,"_callbackUpdatePlaybackTime",void 0),q(this,"pm",void 0),this.pm=e,this._playbackTimeTrackerLastPlayheadPosition=-1,this._lastTime=dt.now(),this._isAdPlaying=!1,this._callbackUpdatePlaybackTime=null;var s=this._startPlaybackTimeTracking.bind(this);e.on("playing",s),e.on("adplaying",s),e.on("seeked",s);var r=this._stopPlaybackTimeTracking.bind(this);e.on("playbackheartbeatend",r),e.on("seeking",r),e.on("adplaying",function(){t._isAdPlaying=!0}),e.on("adended",function(){t._isAdPlaying=!1}),e.on("adpause",function(){t._isAdPlaying=!1}),e.on("adbreakstart",function(){t._isAdPlaying=!1}),e.on("adbreakend",function(){t._isAdPlaying=!1}),e.on("adplay",function(){t._isAdPlaying=!1}),e.on("viewinit",function(){t._playbackTimeTrackerLastPlayheadPosition=-1,t._lastTime=dt.now(),t._isAdPlaying=!1,t._callbackUpdatePlaybackTime=null})}return ns(i,[{key:"_startPlaybackTimeTracking",value:function(){this._callbackUpdatePlaybackTime===null&&(this._callbackUpdatePlaybackTime=this._updatePlaybackTime.bind(this),this._playbackTimeTrackerLastPlayheadPosition=this.pm.data.player_playhead_time,this.pm.on("playbackheartbeat",this._callbackUpdatePlaybackTime))}},{key:"_stopPlaybackTimeTracking",value:function(){this._callbackUpdatePlaybackTime&&(this._updatePlaybackTime(),this.pm.off("playbackheartbeat",this._callbackUpdatePlaybackTime),this._callbackUpdatePlaybackTime=null,this._playbackTimeTrackerLastPlayheadPosition=-1)}},{key:"_updatePlaybackTime",value:function(){var e=this.pm.data.player_playhead_time,t=dt.now(),s=-1;this._playbackTimeTrackerLastPlayheadPosition>=0&&e>this._playbackTimeTrackerLastPlayheadPosition?s=e-this._playbackTimeTrackerLastPlayheadPosition:this._isAdPlaying&&(s=t-this._lastTime),s>0&&s<=1e3&&ot(this.pm.data,"view_content_playback_time",s),this._playbackTimeTrackerLastPlayheadPosition=e,this._lastTime=t}}]),i})(),Ax=_x,Sx=(function(){function i(e){Tt(this,i),q(this,"pm",void 0),this.pm=e;var t=this._updatePlayheadTime.bind(this);e.on("playbackheartbeat",t),e.on("playbackheartbeatend",t),e.on("timeupdate",t),e.on("destroy",function(){e.off("timeupdate",t)})}return ns(i,[{key:"_updateMaxPlayheadPosition",value:function(){this.pm.data.view_max_playhead_position=typeof this.pm.data.view_max_playhead_position>"u"?this.pm.data.player_playhead_time:Math.max(this.pm.data.view_max_playhead_position,this.pm.data.player_playhead_time)}},{key:"_updatePlayheadTime",value:function(e,t){var s=this,r=function(){s.pm.currentFragmentPDT&&s.pm.currentFragmentStart&&(s.pm.data.player_program_time=s.pm.currentFragmentPDT+s.pm.data.player_playhead_time-s.pm.currentFragmentStart)};if(t&&t.player_playhead_time)this.pm.data.player_playhead_time=t.player_playhead_time,r(),this._updateMaxPlayheadPosition();else if(this.pm.getPlayheadTime){var n=this.pm.getPlayheadTime();typeof n<"u"&&(this.pm.data.player_playhead_time=n,r(),this._updateMaxPlayheadPosition())}}}]),i})(),Ix=Sx,Tg=300*1e3,xx=function i(e){if(Tt(this,i),!e.disableRebufferTracking){var t,s=function(n,a){r(a),t=void 0},r=function(n){if(t){var a=n.viewer_time-t;ot(e.data,"view_rebuffer_duration",a),t=n.viewer_time,e.data.view_rebuffer_duration>Tg&&(e.emit("viewend"),e.send("viewend"),e.mux.log.warn("Ending view after rebuffering for longer than ".concat(Tg,"ms, future events will be ignored unless a programchange or videochange occurs.")))}e.data.view_watch_time>=0&&e.data.view_rebuffer_count>0&&(e.data.view_rebuffer_frequency=e.data.view_rebuffer_count/e.data.view_watch_time,e.data.view_rebuffer_percentage=e.data.view_rebuffer_duration/e.data.view_watch_time)};e.on("playbackheartbeat",function(n,a){return r(a)}),e.on("rebufferstart",function(n,a){t||(ot(e.data,"view_rebuffer_count",1),t=a.viewer_time,e.one("rebufferend",s))}),e.on("viewinit",function(){t=void 0,e.off("rebufferend",s)})}},Lx=xx,Rx=(function(){function i(e){var t=this;Tt(this,i),q(this,"_lastCheckedTime",void 0),q(this,"_lastPlayheadTime",void 0),q(this,"_lastPlayheadTimeUpdatedTime",void 0),q(this,"_rebuffering",void 0),q(this,"pm",void 0),this.pm=e,!(e.disableRebufferTracking||e.disablePlayheadRebufferTracking)&&(this._lastCheckedTime=null,this._lastPlayheadTime=null,this._lastPlayheadTimeUpdatedTime=null,e.on("playbackheartbeat",this._checkIfRebuffering.bind(this)),e.on("playbackheartbeatend",this._cleanupRebufferTracker.bind(this)),e.on("seeking",function(){t._cleanupRebufferTracker(null,{viewer_time:dt.now()})}))}return ns(i,[{key:"_checkIfRebuffering",value:function(e,t){if(this.pm.seekingTracker.isSeeking||this.pm.adTracker.isAdBreak||!this.pm.playbackHeartbeat._playheadShouldBeProgressing){this._cleanupRebufferTracker(e,t);return}if(this._lastCheckedTime===null){this._prepareRebufferTrackerState(t.viewer_time);return}if(this._lastPlayheadTime!==this.pm.data.player_playhead_time){this._cleanupRebufferTracker(e,t,!0);return}var s=t.viewer_time-this._lastPlayheadTimeUpdatedTime;typeof this.pm.sustainedRebufferThreshold=="number"&&s>=this.pm.sustainedRebufferThreshold&&(this._rebuffering||(this._rebuffering=!0,this.pm.emit("rebufferstart",{viewer_time:this._lastPlayheadTimeUpdatedTime}))),this._lastCheckedTime=t.viewer_time}},{key:"_clearRebufferTrackerState",value:function(){this._lastCheckedTime=null,this._lastPlayheadTime=null,this._lastPlayheadTimeUpdatedTime=null}},{key:"_prepareRebufferTrackerState",value:function(e){this._lastCheckedTime=e,this._lastPlayheadTime=this.pm.data.player_playhead_time,this._lastPlayheadTimeUpdatedTime=e}},{key:"_cleanupRebufferTracker",value:function(e,t){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;if(this._rebuffering)this._rebuffering=!1,this.pm.emit("rebufferend",{viewer_time:t.viewer_time});else{if(this._lastCheckedTime===null)return;var r=this.pm.data.player_playhead_time-this._lastPlayheadTime,n=t.viewer_time-this._lastPlayheadTimeUpdatedTime;typeof this.pm.minimumRebufferDuration=="number"&&r>0&&n-r>this.pm.minimumRebufferDuration&&(this._lastCheckedTime=null,this.pm.emit("rebufferstart",{viewer_time:this._lastPlayheadTimeUpdatedTime}),this.pm.emit("rebufferend",{viewer_time:this._lastPlayheadTimeUpdatedTime+n-r}))}s?this._prepareRebufferTrackerState(t.viewer_time):this._clearRebufferTrackerState()}}]),i})(),kx=Rx,Dx=(function(){function i(e){var t=this;Tt(this,i),q(this,"NAVIGATION_START",void 0),q(this,"pm",void 0),this.pm=e,e.on("viewinit",function(){var s=e.data,r=s.view_id;if(!s.view_program_changed){var n=function(a,o){var l=o.viewer_time;(a.type==="playing"&&typeof e.data.view_time_to_first_frame>"u"||a.type==="adplaying"&&(typeof e.data.view_time_to_first_frame>"u"||t._inPrerollPosition()))&&t.calculateTimeToFirstFrame(l||dt.now(),r)};e.one("playing",n),e.one("adplaying",n),e.one("viewend",function(){e.off("playing",n),e.off("adplaying",n)})}})}return ns(i,[{key:"_inPrerollPosition",value:function(){return typeof this.pm.data.view_content_playback_time>"u"||this.pm.data.view_content_playback_time<=1e3}},{key:"calculateTimeToFirstFrame",value:function(e,t){t===this.pm.data.view_id&&(this.pm.watchTimeTracker._updateWatchTime(null,{viewer_time:e}),this.pm.data.view_time_to_first_frame=this.pm.data.view_watch_time,(this.pm.data.player_autoplay_on||this.pm.data.video_is_autoplay)&&this.NAVIGATION_START&&(this.pm.data.view_aggregate_startup_time=this.pm.data.view_start+this.pm.data.view_watch_time-this.NAVIGATION_START))}}]),i})(),Cx=Dx,wx=function i(e){var t=this;Tt(this,i),q(this,"_lastPlayerHeight",void 0),q(this,"_lastPlayerWidth",void 0),q(this,"_lastPlayheadPosition",void 0),q(this,"_lastSourceHeight",void 0),q(this,"_lastSourceWidth",void 0),e.on("viewinit",function(){t._lastPlayheadPosition=-1});var s=["pause","rebufferstart","seeking","error","adbreakstart","hb","renditionchange","orientationchange","viewend"],r=["playing","hb","renditionchange","orientationchange"];s.forEach(function(n){e.on(n,function(){if(t._lastPlayheadPosition>=0&&e.data.player_playhead_time>=0&&t._lastPlayerWidth>=0&&t._lastSourceWidth>0&&t._lastPlayerHeight>=0&&t._lastSourceHeight>0){var a=e.data.player_playhead_time-t._lastPlayheadPosition;if(a<0){t._lastPlayheadPosition=-1;return}var o=Math.min(t._lastPlayerWidth/t._lastSourceWidth,t._lastPlayerHeight/t._lastSourceHeight),l=Math.max(0,o-1),d=Math.max(0,1-o);e.data.view_max_upscale_percentage=Math.max(e.data.view_max_upscale_percentage||0,l),e.data.view_max_downscale_percentage=Math.max(e.data.view_max_downscale_percentage||0,d),ot(e.data,"view_total_content_playback_time",a),ot(e.data,"view_total_upscaling",l*a),ot(e.data,"view_total_downscaling",d*a)}t._lastPlayheadPosition=-1})}),r.forEach(function(n){e.on(n,function(){t._lastPlayheadPosition=e.data.player_playhead_time,t._lastPlayerWidth=e.data.player_width,t._lastPlayerHeight=e.data.player_height,t._lastSourceWidth=e.data.video_source_width,t._lastSourceHeight=e.data.video_source_height})})},Mx=wx,Px=2e3,Ox=function i(e){var t=this;Tt(this,i),q(this,"isSeeking",void 0),this.isSeeking=!1;var s=-1,r=function(){var n=dt.now(),a=(e.data.viewer_time||n)-(s||n);ot(e.data,"view_seek_duration",a),e.data.view_max_seek_time=Math.max(e.data.view_max_seek_time||0,a),t.isSeeking=!1,s=-1};e.on("seeking",function(n,a){if(Object.assign(e.data,a),t.isSeeking&&a.viewer_time-s<=Px){s=a.viewer_time;return}t.isSeeking&&r(),t.isSeeking=!0,s=a.viewer_time,ot(e.data,"view_seek_count",1),e.send("seeking")}),e.on("seeked",function(){r()}),e.on("viewend",function(){t.isSeeking&&(r(),e.send("seeked")),t.isSeeking=!1,s=-1})},Nx=Ox,_g=function(i,e){i.push(e),i.sort(function(t,s){return t.viewer_time-s.viewer_time})},Ux=["adbreakstart","adrequest","adresponse","adplay","adplaying","adpause","adended","adbreakend","aderror","adclicked","adskipped"],$x=(function(){function i(e){var t=this;Tt(this,i),q(this,"_adHasPlayed",void 0),q(this,"_adRequests",void 0),q(this,"_adResponses",void 0),q(this,"_currentAdRequestNumber",void 0),q(this,"_currentAdResponseNumber",void 0),q(this,"_prerollPlayTime",void 0),q(this,"_wouldBeNewAdPlay",void 0),q(this,"isAdBreak",void 0),q(this,"pm",void 0),this.pm=e,e.on("viewinit",function(){t.isAdBreak=!1,t._currentAdRequestNumber=0,t._currentAdResponseNumber=0,t._adRequests=[],t._adResponses=[],t._adHasPlayed=!1,t._wouldBeNewAdPlay=!0,t._prerollPlayTime=void 0}),Ux.forEach(function(r){return e.on(r,t._updateAdData.bind(t))});var s=function(){t.isAdBreak=!1};e.on("adbreakstart",function(){t.isAdBreak=!0}),e.on("play",s),e.on("playing",s),e.on("viewend",s),e.on("adrequest",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdRequestNumber++},n),_g(t._adRequests,n),ot(e.data,"view_ad_request_count"),t.inPrerollPosition()&&(e.data.view_preroll_requested=!0,t._adHasPlayed||ot(e.data,"view_preroll_request_count"))}),e.on("adresponse",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdResponseNumber++},n),_g(t._adResponses,n);var a=t.findAdRequest(n.ad_request_id);a&&ot(e.data,"view_ad_request_time",Math.max(0,n.viewer_time-a.viewer_time))}),e.on("adplay",function(r,n){t._adHasPlayed=!0,t._wouldBeNewAdPlay&&(t._wouldBeNewAdPlay=!1,ot(e.data,"view_ad_played_count")),t.inPrerollPosition()&&!e.data.view_preroll_played&&(e.data.view_preroll_played=!0,t._adRequests.length>0&&(e.data.view_preroll_request_time=Math.max(0,n.viewer_time-t._adRequests[0].viewer_time)),e.data.view_start&&(e.data.view_startup_preroll_request_time=Math.max(0,n.viewer_time-e.data.view_start)),t._prerollPlayTime=n.viewer_time)}),e.on("adplaying",function(r,n){t.inPrerollPosition()&&typeof e.data.view_preroll_load_time>"u"&&typeof t._prerollPlayTime<"u"&&(e.data.view_preroll_load_time=n.viewer_time-t._prerollPlayTime,e.data.view_startup_preroll_load_time=n.viewer_time-t._prerollPlayTime)}),e.on("adclicked",function(r,n){t._wouldBeNewAdPlay||ot(e.data,"view_ad_clicked_count")}),e.on("adskipped",function(r,n){t._wouldBeNewAdPlay||ot(e.data,"view_ad_skipped_count")}),e.on("adended",function(){t._wouldBeNewAdPlay=!0}),e.on("aderror",function(){t._wouldBeNewAdPlay=!0})}return ns(i,[{key:"inPrerollPosition",value:function(){return typeof this.pm.data.view_content_playback_time>"u"||this.pm.data.view_content_playback_time<=1e3}},{key:"findAdRequest",value:function(e){for(var t=0;t<this._adRequests.length;t++)if(this._adRequests[t].ad_request_id===e)return this._adRequests[t]}},{key:"_updateAdData",value:function(e,t){if(this.inPrerollPosition()){if(!this.pm.data.view_preroll_ad_tag_hostname&&t.ad_tag_url){var s=bs(fo(t.ad_tag_url),2),r=s[0],n=s[1];this.pm.data.view_preroll_ad_tag_domain=n,this.pm.data.view_preroll_ad_tag_hostname=r}if(!this.pm.data.view_preroll_ad_asset_hostname&&t.ad_asset_url){var a=bs(fo(t.ad_asset_url),2),o=a[0],l=a[1];this.pm.data.view_preroll_ad_asset_domain=l,this.pm.data.view_preroll_ad_asset_hostname=o}}this.pm.data.ad_asset_url=t?.ad_asset_url,this.pm.data.ad_tag_url=t?.ad_tag_url,this.pm.data.ad_creative_id=t?.ad_creative_id,this.pm.data.ad_id=t?.ad_id,this.pm.data.ad_universal_id=t?.ad_universal_id}}]),i})(),Fx=$x,Ag=Jt(Ii()),Bx=function i(e){Tt(this,i);var t,s,r=function(){e.disableRebufferTracking||(ot(e.data,"view_waiting_rebuffer_count",1),t=dt.now(),s=Ag.default.setInterval(function(){if(t){var d=dt.now();ot(e.data,"view_waiting_rebuffer_duration",d-t),t=d}},250))},n=function(){e.disableRebufferTracking||t&&(ot(e.data,"view_waiting_rebuffer_duration",dt.now()-t),t=!1,Ag.default.clearInterval(s))},a=!1,o=function(){a=!0},l=function(){a=!1,n()};e.on("waiting",function(){a&&r()}),e.on("playing",function(){n(),o()}),e.on("pause",l),e.on("seeking",l)},Hx=Bx,Gx=function i(e){var t=this;Tt(this,i),q(this,"lastWallClockTime",void 0);var s=function(){t.lastWallClockTime=dt.now(),e.on("before*",r)},r=function(n){var a=dt.now(),o=t.lastWallClockTime;t.lastWallClockTime=a,a-o>3e4&&(e.emit("devicesleep",{viewer_time:o}),Object.assign(e.data,{viewer_time:o}),e.send("devicesleep"),e.emit("devicewake",{viewer_time:a}),Object.assign(e.data,{viewer_time:a}),e.send("devicewake"))};e.one("playbackheartbeat",s),e.on("playbackheartbeatend",function(){e.off("before*",r),e.one("playbackheartbeat",s)})},Kx=Gx,gc=Jt(Ii()),py=(function(i){return i()})(function(){var i=function(){for(var t=0,s={};t<arguments.length;t++){var r=arguments[t];for(var n in r)s[n]=r[n]}return s};function e(t){function s(r,n,a){var o;if(typeof document<"u"){if(arguments.length>1){if(a=i({path:"/"},s.defaults,a),typeof a.expires=="number"){var l=new Date;l.setMilliseconds(l.getMilliseconds()+a.expires*864e5),a.expires=l}try{o=JSON.stringify(n),/^[\{\[]/.test(o)&&(n=o)}catch{}return t.write?n=t.write(n,r):n=encodeURIComponent(String(n)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),r=encodeURIComponent(String(r)),r=r.replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent),r=r.replace(/[\(\)]/g,escape),document.cookie=[r,"=",n,a.expires?"; expires="+a.expires.toUTCString():"",a.path?"; path="+a.path:"",a.domain?"; domain="+a.domain:"",a.secure?"; secure":""].join("")}r||(o={});for(var d=document.cookie?document.cookie.split("; "):[],u=/(%[0-9A-Z]{2})+/g,c=0;c<d.length;c++){var h=d[c].split("="),f=h.slice(1).join("=");f.charAt(0)==='"'&&(f=f.slice(1,-1));try{var m=h[0].replace(u,decodeURIComponent);if(f=t.read?t.read(f,m):t(f,m)||f.replace(u,decodeURIComponent),this.json)try{f=JSON.parse(f)}catch{}if(r===m){o=f;break}r||(o[m]=f)}catch{}}return o}}return s.set=s,s.get=function(r){return s.call(s,r)},s.getJSON=function(){return s.apply({json:!0},[].slice.call(arguments))},s.defaults={},s.remove=function(r,n){s(r,"",i(n,{expires:-1}))},s.withConverter=e,s}return e(function(){})}),gy="muxData",Vx=function(i){return Object.entries(i).map(function(e){var t=bs(e,2),s=t[0],r=t[1];return"".concat(s,"=").concat(r)}).join("&")},Wx=function(i){return i.split("&").reduce(function(e,t){var s=bs(t.split("="),2),r=s[0],n=s[1],a=+n,o=n&&a==n?a:n;return e[r]=o,e},{})},vy=function(){var i;try{i=Wx(py.get(gy)||"")}catch{i={}}return i},Ey=function(i){try{py.set(gy,Vx(i),{expires:365})}catch{}},qx=function(){var i=vy();return i.mux_viewer_id=i.mux_viewer_id||ho(),i.msn=i.msn||Math.random(),Ey(i),{mux_viewer_id:i.mux_viewer_id,mux_sample_number:i.msn}},Yx=function(){var i=vy(),e=dt.now();return i.session_start&&(i.sst=i.session_start,delete i.session_start),i.session_id&&(i.sid=i.session_id,delete i.session_id),i.session_expires&&(i.sex=i.session_expires,delete i.session_expires),(!i.sex||i.sex<e)&&(i.sid=ho(),i.sst=e),i.sex=e+1500*1e3,Ey(i),{session_id:i.sid,session_start:i.sst,session_expires:i.sex}};function jx(i,e){var t=e.beaconCollectionDomain,s=e.beaconDomain;if(t)return"https://"+t;i=i||"inferred";var r=s||"litix.io";return i.match(/^[a-z0-9]+$/)?"https://"+i+"."+r:"https://img.litix.io/a.gif"}var zx=Jt(Ii()),yy=function(){var i;switch(by()){case"cellular":i="cellular";break;case"ethernet":i="wired";break;case"wifi":i="wifi";break;case void 0:break;default:i="other"}return i},by=function(){var i=zx.default.navigator,e=i&&(i.connection||i.mozConnection||i.webkitConnection);return e&&e.type};yy.getConnectionFromAPI=by;var Qx=yy,Xx={a:"env",b:"beacon",c:"custom",d:"ad",e:"event",f:"experiment",i:"internal",m:"mux",n:"response",p:"player",q:"request",r:"retry",s:"session",t:"timestamp",u:"viewer",v:"video",w:"page",x:"view",y:"sub"},Zx=Ty(Xx),Jx={ad:"ad",af:"affiliate",ag:"aggregate",ap:"api",al:"application",ao:"audio",ar:"architecture",as:"asset",au:"autoplay",av:"average",bi:"bitrate",bn:"brand",br:"break",bw:"browser",by:"bytes",bz:"business",ca:"cached",cb:"cancel",cc:"codec",cd:"code",cg:"category",ch:"changed",ci:"client",ck:"clicked",cl:"canceled",cn:"config",co:"count",ce:"counter",cp:"complete",cq:"creator",cr:"creative",cs:"captions",ct:"content",cu:"current",cx:"connection",cz:"context",dg:"downscaling",dm:"domain",dn:"cdn",do:"downscale",dr:"drm",dp:"dropped",du:"duration",dv:"device",dy:"dynamic",eb:"enabled",ec:"encoding",ed:"edge",en:"end",eg:"engine",em:"embed",er:"error",ep:"experiments",es:"errorcode",et:"errortext",ee:"event",ev:"events",ex:"expires",ez:"exception",fa:"failed",fi:"first",fm:"family",ft:"format",fp:"fps",fq:"frequency",fr:"frame",fs:"fullscreen",ha:"has",hb:"holdback",he:"headers",ho:"host",hn:"hostname",ht:"height",id:"id",ii:"init",in:"instance",ip:"ip",is:"is",ke:"key",la:"language",lb:"labeled",le:"level",li:"live",ld:"loaded",lo:"load",ls:"lists",lt:"latency",ma:"max",md:"media",me:"message",mf:"manifest",mi:"mime",ml:"midroll",mm:"min",mn:"manufacturer",mo:"model",mx:"mux",ne:"newest",nm:"name",no:"number",on:"on",or:"origin",os:"os",pa:"paused",pb:"playback",pd:"producer",pe:"percentage",pf:"played",pg:"program",ph:"playhead",pi:"plugin",pl:"preroll",pn:"playing",po:"poster",pp:"pip",pr:"preload",ps:"position",pt:"part",py:"property",px:"pop",pz:"plan",ra:"rate",rd:"requested",re:"rebuffer",rf:"rendition",rg:"range",rm:"remote",ro:"ratio",rp:"response",rq:"request",rs:"requests",sa:"sample",sd:"skipped",se:"session",sh:"shift",sk:"seek",sm:"stream",so:"source",sq:"sequence",sr:"series",ss:"status",st:"start",su:"startup",sv:"server",sw:"software",sy:"severity",ta:"tag",tc:"tech",te:"text",tg:"target",th:"throughput",ti:"time",tl:"total",to:"to",tt:"title",ty:"type",ug:"upscaling",un:"universal",up:"upscale",ur:"url",us:"user",va:"variant",vd:"viewed",vi:"video",ve:"version",vw:"view",vr:"viewer",wd:"width",wa:"watch",wt:"waiting"},Sg=Ty(Jx);function Ty(i){var e={};for(var t in i)i.hasOwnProperty(t)&&(e[i[t]]=t);return e}function Oh(i){var e={},t={};return Object.keys(i).forEach(function(s){var r=!1;if(i.hasOwnProperty(s)&&i[s]!==void 0){var n=s.split("_"),a=n[0],o=Zx[a];o||(Ne.info("Data key word `"+n[0]+"` not expected in "+s),o=a+"_"),n.splice(1).forEach(function(l){l==="url"&&(r=!0),Sg[l]?o+=Sg[l]:Number.isInteger(Number(l))?o+=l:(Ne.info("Data key word `"+l+"` not expected in "+s),o+="_"+l+"_")}),r?t[o]=i[s]:e[o]=i[s]}}),Object.assign(e,t)}var br=Jt(Ii()),eL=Jt(uy()),tL={maxBeaconSize:300,maxQueueLength:3600,baseTimeBetweenBeacons:1e4,maxPayloadKBSize:500},iL=56*1024,sL=["hb","requestcompleted","requestfailed","requestcanceled"],rL="https://img.litix.io",As=function(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this._beaconUrl=i||rL,this._eventQueue=[],this._postInFlight=!1,this._resendAfterPost=!1,this._failureCount=0,this._sendTimeout=!1,this._options=Object.assign({},tL,e)};As.prototype.queueEvent=function(i,e){var t=Object.assign({},e);return this._eventQueue.length<=this._options.maxQueueLength||i==="eventrateexceeded"?(this._eventQueue.push(t),this._sendTimeout||this._startBeaconSending(),this._eventQueue.length<=this._options.maxQueueLength):!1};As.prototype.flushEvents=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(i&&this._eventQueue.length===1){this._eventQueue.pop();return}this._eventQueue.length&&this._sendBeaconQueue(),this._startBeaconSending()};As.prototype.destroy=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;this.destroyed=!0,i?this._clearBeaconQueue():this.flushEvents(),br.default.clearTimeout(this._sendTimeout)};As.prototype._clearBeaconQueue=function(){var i=this._eventQueue.length>this._options.maxBeaconSize?this._eventQueue.length-this._options.maxBeaconSize:0,e=this._eventQueue.slice(i);i>0&&Object.assign(e[e.length-1],Oh({mux_view_message:"event queue truncated"}));var t=this._createPayload(e);_y(this._beaconUrl,t,!0,function(){})};As.prototype._sendBeaconQueue=function(){var i=this;if(this._postInFlight){this._resendAfterPost=!0;return}var e=this._eventQueue.slice(0,this._options.maxBeaconSize);this._eventQueue=this._eventQueue.slice(this._options.maxBeaconSize),this._postInFlight=!0;var t=this._createPayload(e),s=dt.now();_y(this._beaconUrl,t,!1,function(r,n){n?(i._eventQueue=e.concat(i._eventQueue),i._failureCount+=1,Ne.info("Error sending beacon: "+n)):i._failureCount=0,i._roundTripTime=dt.now()-s,i._postInFlight=!1,i._resendAfterPost&&(i._resendAfterPost=!1,i._eventQueue.length>0&&i._sendBeaconQueue())})};As.prototype._getNextBeaconTime=function(){if(!this._failureCount)return this._options.baseTimeBetweenBeacons;var i=Math.pow(2,this._failureCount-1);return i=i*Math.random(),(1+i)*this._options.baseTimeBetweenBeacons};As.prototype._startBeaconSending=function(){var i=this;br.default.clearTimeout(this._sendTimeout),!this.destroyed&&(this._sendTimeout=br.default.setTimeout(function(){i._eventQueue.length&&i._sendBeaconQueue(),i._startBeaconSending()},this._getNextBeaconTime()))};As.prototype._createPayload=function(i){var e=this,t={transmission_timestamp:Math.round(dt.now())};this._roundTripTime&&(t.rtt_ms=Math.round(this._roundTripTime));var s,r,n,a=function(){s=JSON.stringify({metadata:t,events:r||i}),n=s.length/1024},o=function(){return n<=e._options.maxPayloadKBSize};return a(),o()||(Ne.info("Payload size is too big ("+n+" kb). Removing unnecessary events."),r=i.filter(function(l){return sL.indexOf(l.e)===-1}),a()),o()||(Ne.info("Payload size still too big ("+n+" kb). Cropping fields.."),r.forEach(function(l){for(var d in l){var u=l[d],c=50*1024;typeof u=="string"&&u.length>c&&(l[d]=u.substring(0,c))}}),a()),s};var nL=typeof eL.default.exitPictureInPicture=="function"?function(i){return i.length<=iL}:function(i){return!1},_y=function(i,e,t,s){if(t&&navigator&&navigator.sendBeacon&&navigator.sendBeacon(i,e)){s();return}if(br.default.fetch){br.default.fetch(i,{method:"POST",body:e,headers:{"Content-Type":"text/plain"},keepalive:nL(e)}).then(function(n){return s(null,n.ok?null:"Error")}).catch(function(n){return s(null,n)});return}if(br.default.XMLHttpRequest){var r=new br.default.XMLHttpRequest;r.onreadystatechange=function(){if(r.readyState===4)return s(null,r.status!==200?"error":void 0)},r.open("POST",i),r.setRequestHeader("Content-Type","text/plain"),r.send(e);return}s()},aL=As,oL=["env_key","view_id","view_sequence_number","player_sequence_number","beacon_domain","player_playhead_time","viewer_time","mux_api_version","event","video_id","player_instance_id","player_error_code","player_error_message","player_error_context","player_error_severity","player_error_business_exception"],lL=["adplay","adplaying","adpause","adfirstquartile","admidpoint","adthirdquartile","adended","adresponse","adrequest"],dL=["ad_id","ad_creative_id","ad_universal_id"],uL=["viewstart","error","ended","viewend"],cL=600*1e3,hL=(function(){function i(e,t){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Tt(this,i);var r,n,a,o,l,d,u,c,h,f,m,p;q(this,"mux",void 0),q(this,"envKey",void 0),q(this,"options",void 0),q(this,"eventQueue",void 0),q(this,"sampleRate",void 0),q(this,"disableCookies",void 0),q(this,"respectDoNotTrack",void 0),q(this,"previousBeaconData",void 0),q(this,"lastEventTime",void 0),q(this,"rateLimited",void 0),q(this,"pageLevelData",void 0),q(this,"viewerData",void 0),this.mux=e,this.envKey=t,this.options=s,this.previousBeaconData=null,this.lastEventTime=0,this.rateLimited=!1,this.eventQueue=new aL(jx(this.envKey,this.options));var g;this.sampleRate=(g=this.options.sampleRate)!==null&&g!==void 0?g:1;var v;this.disableCookies=(v=this.options.disableCookies)!==null&&v!==void 0?v:!1;var b;this.respectDoNotTrack=(b=this.options.respectDoNotTrack)!==null&&b!==void 0?b:!1,this.previousBeaconData=null,this.lastEventTime=0,this.rateLimited=!1,this.pageLevelData={mux_api_version:this.mux.API_VERSION,mux_embed:this.mux.NAME,mux_embed_version:this.mux.VERSION,viewer_application_name:(r=this.options.platform)===null||r===void 0?void 0:r.name,viewer_application_version:(n=this.options.platform)===null||n===void 0?void 0:n.version,viewer_application_engine:(a=this.options.platform)===null||a===void 0?void 0:a.layout,viewer_device_name:(o=this.options.platform)===null||o===void 0?void 0:o.product,viewer_device_category:"",viewer_device_manufacturer:(l=this.options.platform)===null||l===void 0?void 0:l.manufacturer,viewer_os_family:(u=this.options.platform)===null||u===void 0||(d=u.os)===null||d===void 0?void 0:d.family,viewer_os_architecture:(h=this.options.platform)===null||h===void 0||(c=h.os)===null||c===void 0?void 0:c.architecture,viewer_os_version:(m=this.options.platform)===null||m===void 0||(f=m.os)===null||f===void 0?void 0:f.version,viewer_connection_type:Qx(),page_url:gc.default===null||gc.default===void 0||(p=gc.default.location)===null||p===void 0?void 0:p.href},this.viewerData=this.disableCookies?{}:qx()}return ns(i,[{key:"send",value:function(e,t){if(!(!e||!(t!=null&&t.view_id))){if(this.respectDoNotTrack&&Mh())return Ne.info("Not sending `"+e+"` because Do Not Track is enabled");if(!t||typeof t!="object")return Ne.error("A data object was expected in send() but was not provided");var s=this.disableCookies?{}:Yx(),r=xm(qd({},this.pageLevelData,t,s,this.viewerData),{event:e,env_key:this.envKey});r.user_id&&(r.viewer_user_id=r.user_id,delete r.user_id);var n,a=((n=r.mux_sample_number)!==null&&n!==void 0?n:0)>=this.sampleRate,o=this._deduplicateBeaconData(e,r),l=Oh(o);if(this.lastEventTime=this.mux.utils.now(),a)return Ne.info("Not sending event due to sample rate restriction",e,r,l);if(this.envKey||Ne.info("Missing environment key (envKey) - beacons will be dropped if the video source is not a valid mux video URL",e,r,l),!this.rateLimited){if(Ne.info("Sending event",e,r,l),this.rateLimited=!this.eventQueue.queueEvent(e,l),this.mux.WINDOW_UNLOADING&&e==="viewend")this.eventQueue.destroy(!0);else if(this.mux.WINDOW_HIDDEN&&e==="hb"?this.eventQueue.flushEvents(!0):uL.indexOf(e)>=0&&this.eventQueue.flushEvents(),this.rateLimited)return r.event="eventrateexceeded",l=Oh(r),this.eventQueue.queueEvent(r.event,l),Ne.error("Beaconing disabled due to rate limit.")}}}},{key:"destroy",value:function(){this.eventQueue.destroy(!1)}},{key:"_deduplicateBeaconData",value:function(e,t){var s=this,r={},n=t.view_id;if(n==="-1"||e==="viewstart"||e==="viewend"||!this.previousBeaconData||this.mux.utils.now()-this.lastEventTime>=cL)r=qd({},t),n&&(this.previousBeaconData=r),n&&e==="viewend"&&(this.previousBeaconData=null);else{var a=e.indexOf("request")===0;Object.entries(t).forEach(function(o){var l=bs(o,2),d=l[0],u=l[1];s.previousBeaconData&&(u!==s.previousBeaconData[d]||oL.indexOf(d)>-1||s.objectHasChanged(a,d,u,s.previousBeaconData[d])||s.eventRequiresKey(e,d))&&(r[d]=u,s.previousBeaconData[d]=u)})}return r}},{key:"objectHasChanged",value:function(e,t,s,r){return!e||t.indexOf("request_")!==0?!1:t==="request_response_headers"||typeof s!="object"||typeof r!="object"?!0:Object.keys(s||{}).length!==Object.keys(r||{}).length}},{key:"eventRequiresKey",value:function(e,t){return!!(e==="renditionchange"&&t.indexOf("video_source_")===0||dL.includes(t)&&lL.includes(e))}}]),i})(),fL=function i(e){Tt(this,i);var t=0,s=0,r=0,n=0,a=0,o=0,l=0,d=function(h,f){var m=f.request_start,p=f.request_response_start,g=f.request_response_end,v=f.request_bytes_loaded;n++;var b,E;if(p?(b=p-(m??0),E=(g??0)-p):E=(g??0)-(m??0),E>0&&v&&v>0){var T=v/E*8e3;a++,s+=v,r+=E,e.data.view_min_request_throughput=Math.min(e.data.view_min_request_throughput||1/0,T),e.data.view_average_request_throughput=s/r*8e3,e.data.view_request_count=n,b>0&&(t+=b,e.data.view_max_request_latency=Math.max(e.data.view_max_request_latency||0,b),e.data.view_average_request_latency=t/a)}},u=function(h,f){n++,o++,e.data.view_request_count=n,e.data.view_request_failed_count=o},c=function(h,f){n++,l++,e.data.view_request_count=n,e.data.view_request_canceled_count=l};e.on("requestcompleted",d),e.on("requestfailed",u),e.on("requestcanceled",c)},mL=fL,pL=3600*1e3,gL=function i(e){var t=this;Tt(this,i),q(this,"_lastEventTime",void 0),e.on("before*",function(s,r){var n=r.viewer_time,a=dt.now(),o=t._lastEventTime;if(t._lastEventTime=a,o&&a-o>pL){var l=Object.keys(e.data).reduce(function(u,c){return c.indexOf("video_")===0?Object.assign(u,q({},c,e.data[c])):u},{});e.mux.log.info("Received event after at least an hour inactivity, creating a new view");var d=e.playbackHeartbeat._playheadShouldBeProgressing;e._resetView(Object.assign({viewer_time:n},l)),e.playbackHeartbeat._playheadShouldBeProgressing=d,e.playbackHeartbeat._playheadShouldBeProgressing&&s.type!=="play"&&s.type!=="adbreakstart"&&(e.emit("play",{viewer_time:n}),s.type!=="playing"&&e.emit("playing",{viewer_time:n}))}})},vL=gL,EL=["viewstart","ended","loadstart","pause","play","playing","ratechange","waiting","adplay","adpause","adended","aderror","adplaying","adrequest","adresponse","adbreakstart","adbreakend","adfirstquartile","admidpoint","adthirdquartile","rebufferstart","rebufferend","seeked","error","hb","requestcompleted","requestfailed","requestcanceled","renditionchange"],yL=new Set(["requestcompleted","requestfailed","requestcanceled"]),bL=(function(i){ZI(t,i);var e=tx(t);function t(s,r,n){Tt(this,t);var a;a=e.call(this),q(le(a),"DOM_CONTENT_LOADED_EVENT_END",void 0),q(le(a),"NAVIGATION_START",void 0),q(le(a),"_destroyed",void 0),q(le(a),"_heartBeatTimeout",void 0),q(le(a),"adTracker",void 0),q(le(a),"dashjs",void 0),q(le(a),"data",void 0),q(le(a),"disablePlayheadRebufferTracking",void 0),q(le(a),"disableRebufferTracking",void 0),q(le(a),"errorTracker",void 0),q(le(a),"errorTranslator",void 0),q(le(a),"emitTranslator",void 0),q(le(a),"getAdData",void 0),q(le(a),"getPlayheadTime",void 0),q(le(a),"getStateData",void 0),q(le(a),"stateDataTranslator",void 0),q(le(a),"hlsjs",void 0),q(le(a),"id",void 0),q(le(a),"longResumeTracker",void 0),q(le(a),"minimumRebufferDuration",void 0),q(le(a),"mux",void 0),q(le(a),"playbackEventDispatcher",void 0),q(le(a),"playbackHeartbeat",void 0),q(le(a),"playbackHeartbeatTime",void 0),q(le(a),"playheadTime",void 0),q(le(a),"seekingTracker",void 0),q(le(a),"sustainedRebufferThreshold",void 0),q(le(a),"watchTimeTracker",void 0),q(le(a),"currentFragmentPDT",void 0),q(le(a),"currentFragmentStart",void 0),a.DOM_CONTENT_LOADED_EVENT_END=Wd.domContentLoadedEventEnd(),a.NAVIGATION_START=Wd.navigationStart();var o={debug:!1,minimumRebufferDuration:250,sustainedRebufferThreshold:1e3,playbackHeartbeatTime:25,beaconDomain:"litix.io",sampleRate:1,disableCookies:!1,respectDoNotTrack:!1,disableRebufferTracking:!1,disablePlayheadRebufferTracking:!1,errorTranslator:function(h){return h},emitTranslator:function(){for(var h=arguments.length,f=new Array(h),m=0;m<h;m++)f[m]=arguments[m];return f},stateDataTranslator:function(h){return h}};a.mux=s,a.id=r,n!=null&&n.beaconDomain&&a.mux.log.warn("The `beaconDomain` setting has been deprecated in favor of `beaconCollectionDomain`. Please change your integration to use `beaconCollectionDomain` instead of `beaconDomain`."),n=Object.assign(o,n),n.data=n.data||{},n.data.property_key&&(n.data.env_key=n.data.property_key,delete n.data.property_key),Ne.level=n.debug?gr.DEBUG:gr.WARN,a.getPlayheadTime=n.getPlayheadTime,a.getStateData=n.getStateData||function(){return{}},a.getAdData=n.getAdData||function(){},a.minimumRebufferDuration=n.minimumRebufferDuration,a.sustainedRebufferThreshold=n.sustainedRebufferThreshold,a.playbackHeartbeatTime=n.playbackHeartbeatTime,a.disableRebufferTracking=n.disableRebufferTracking,a.disableRebufferTracking&&a.mux.log.warn("Disabling rebuffer tracking. This should only be used in specific circumstances as a last resort when your player is known to unreliably track rebuffering."),a.disablePlayheadRebufferTracking=n.disablePlayheadRebufferTracking,a.errorTranslator=n.errorTranslator,a.emitTranslator=n.emitTranslator,a.stateDataTranslator=n.stateDataTranslator,a.playbackEventDispatcher=new hL(s,n.data.env_key,n),a.data={player_instance_id:ho(),mux_sample_rate:n.sampleRate,beacon_domain:n.beaconCollectionDomain||n.beaconDomain},a.data.view_sequence_number=1,a.data.player_sequence_number=1;var l=(function(){typeof this.data.view_start>"u"&&(this.data.view_start=this.mux.utils.now(),this.emit("viewstart"))}).bind(le(a));if(a.on("viewinit",function(h,f){this._resetVideoData(),this._resetViewData(),this._resetErrorData(),this._updateStateData(),Object.assign(this.data,f),this._initializeViewData(),this.one("play",l),this.one("adbreakstart",l)}),a.on("videochange",function(h,f){this._resetView(f)}),a.on("programchange",function(h,f){this.data.player_is_paused&&this.mux.log.warn("The `programchange` event is intended to be used when the content changes mid playback without the video source changing, however the video is not currently playing. If the video source is changing please use the videochange event otherwise you will lose startup time information."),this._resetView(Object.assign(f,{view_program_changed:!0})),l(),this.emit("play"),this.emit("playing")}),a.on("fragmentchange",function(h,f){this.currentFragmentPDT=f.currentFragmentPDT,this.currentFragmentStart=f.currentFragmentStart}),a.on("destroy",a.destroy),typeof window<"u"&&typeof window.addEventListener=="function"&&typeof window.removeEventListener=="function"){var d=function(){var h=typeof a.data.view_start<"u";a.mux.WINDOW_HIDDEN=document.visibilityState==="hidden",h&&a.mux.WINDOW_HIDDEN&&(a.data.player_is_paused||a.emit("hb"))};window.addEventListener("visibilitychange",d,!1);var u=function(h){h.persisted||a.destroy()};window.addEventListener("pagehide",u,!1),a.on("destroy",function(){window.removeEventListener("visibilitychange",d),window.removeEventListener("pagehide",u)})}a.on("playerready",function(h,f){Object.assign(this.data,f)}),EL.forEach(function(h){a.on(h,function(f,m){h.indexOf("ad")!==0&&this._updateStateData(),Object.assign(this.data,m),this._sanitizeData()}),a.on("after"+h,function(){(h!=="error"||this.errorTracker.viewErrored)&&this.send(h)})}),a.on("viewend",function(h,f){Object.assign(a.data,f)});var c=function(h){var f=this.mux.utils.now();this.data.player_init_time&&(this.data.player_startup_time=f-this.data.player_init_time),!this.mux.PLAYER_TRACKED&&this.NAVIGATION_START&&(this.mux.PLAYER_TRACKED=!0,(this.data.player_init_time||this.DOM_CONTENT_LOADED_EVENT_END)&&(this.data.page_load_time=Math.min(this.data.player_init_time||1/0,this.DOM_CONTENT_LOADED_EVENT_END||1/0)-this.NAVIGATION_START)),this.send("playerready"),delete this.data.player_startup_time,delete this.data.page_load_time};return a.one("playerready",c),a.longResumeTracker=new vL(le(a)),a.errorTracker=new yx(le(a)),new Kx(le(a)),a.seekingTracker=new Nx(le(a)),a.playheadTime=new Ix(le(a)),a.playbackHeartbeat=new vx(le(a)),new Mx(le(a)),a.watchTimeTracker=new Tx(le(a)),new Ax(le(a)),a.adTracker=new Fx(le(a)),new kx(le(a)),new Lx(le(a)),new Cx(le(a)),new Hx(le(a)),new mL(le(a)),n.hlsjs&&a.addHLSJS(n),n.dashjs&&a.addDashJS(n),a.emit("viewinit",n.data),a}return ns(t,[{key:"emit",value:function(s,r){var n,a=Object.assign({viewer_time:this.mux.utils.now()},r),o=[s,a];if(this.emitTranslator)try{o=this.emitTranslator(s,a)}catch(l){this.mux.log.warn("Exception in emit translator callback.",l)}o!=null&&o.length&&(n=Bl(Qn(t.prototype),"emit",this)).call.apply(n,[this].concat(gi(o)))}},{key:"destroy",value:function(){this._destroyed||(this._destroyed=!0,typeof this.data.view_start<"u"&&(this.emit("viewend"),this.send("viewend")),this.playbackEventDispatcher.destroy(),this.removeHLSJS(),this.removeDashJS(),window.clearTimeout(this._heartBeatTimeout))}},{key:"send",value:function(s){if(this.data.view_id){var r=Object.assign({},this.data),n=["player_program_time","player_manifest_newest_program_time","player_live_edge_program_time","player_program_time","video_holdback","video_part_holdback","video_target_duration","video_part_target_duration"];if(r.video_source_is_live===void 0&&(r.player_source_duration===1/0||r.video_source_duration===1/0?r.video_source_is_live=!0:(r.player_source_duration>0||r.video_source_duration>0)&&(r.video_source_is_live=!1)),r.video_source_is_live||n.forEach(function(d){r[d]=void 0}),r.video_source_url=r.video_source_url||r.player_source_url,r.video_source_url){var a=bs(fo(r.video_source_url),2),o=a[0],l=a[1];r.video_source_domain=l,r.video_source_hostname=o}delete r.ad_request_id,this.playbackEventDispatcher.send(s,r),this.data.view_sequence_number++,this.data.player_sequence_number++,yL.has(s)||this._restartHeartBeat(),s==="viewend"&&delete this.data.view_id}}},{key:"_resetView",value:function(s){this.emit("viewend"),this.send("viewend"),this.emit("viewinit",s)}},{key:"_updateStateData",value:function(){var s=this.getStateData();if(typeof this.stateDataTranslator=="function")try{s=this.stateDataTranslator(s)}catch(r){this.mux.log.warn("Exception in stateDataTranslator translator callback.",r)}Object.assign(this.data,s),this.playheadTime._updatePlayheadTime(),this._sanitizeData()}},{key:"_sanitizeData",value:function(){var s=this,r=["player_width","player_height","video_source_width","video_source_height","player_playhead_time","video_source_bitrate"];r.forEach(function(a){var o=parseInt(s.data[a],10);s.data[a]=isNaN(o)?void 0:o});var n=["player_source_url","video_source_url"];n.forEach(function(a){if(s.data[a]){var o=s.data[a].toLowerCase();(o.indexOf("data:")===0||o.indexOf("blob:")===0)&&(s.data[a]="MSE style URL")}})}},{key:"_resetVideoData",value:function(){var s=this;Object.keys(this.data).forEach(function(r){r.indexOf("video_")===0&&delete s.data[r]})}},{key:"_resetViewData",value:function(){var s=this;Object.keys(this.data).forEach(function(r){r.indexOf("view_")===0&&delete s.data[r]}),this.data.view_sequence_number=1}},{key:"_resetErrorData",value:function(){delete this.data.player_error_code,delete this.data.player_error_message,delete this.data.player_error_context,delete this.data.player_error_severity,delete this.data.player_error_business_exception}},{key:"_initializeViewData",value:function(){var s=this,r=this.data.view_id=ho(),n=function(){r===s.data.view_id&&ot(s.data,"player_view_count",1)};this.data.player_is_paused?this.one("play",n):n()}},{key:"_restartHeartBeat",value:function(){var s=this;window.clearTimeout(this._heartBeatTimeout),this._heartBeatTimeout=window.setTimeout(function(){s.data.player_is_paused||s.emit("hb")},1e4)}},{key:"addHLSJS",value:function(s){if(!s.hlsjs){this.mux.log.warn("You must pass a valid hlsjs instance in order to track it.");return}if(this.hlsjs){this.mux.log.warn("An instance of HLS.js is already being monitored for this player.");return}this.hlsjs=s.hlsjs,ox(this.mux,this.id,s.hlsjs,{},s.Hls||window.Hls)}},{key:"removeHLSJS",value:function(){this.hlsjs&&(lx(this.hlsjs),this.hlsjs=void 0)}},{key:"addDashJS",value:function(s){if(!s.dashjs){this.mux.log.warn("You must pass a valid dashjs instance in order to track it.");return}if(this.dashjs){this.mux.log.warn("An instance of Dash.js is already being monitored for this player.");return}this.dashjs=s.dashjs,hx(this.mux,this.id,s.dashjs)}},{key:"removeDashJS",value:function(){this.dashjs&&(fx(this.dashjs),this.dashjs=void 0)}}]),t})(px),TL=bL,ua=Jt(uy());function _L(){return ua.default&&!!(ua.default.fullscreenElement||ua.default.webkitFullscreenElement||ua.default.mozFullScreenElement||ua.default.msFullscreenElement)}var AL=["loadstart","pause","play","playing","seeking","seeked","timeupdate","ratechange","stalled","waiting","error","ended"],SL={1:"MEDIA_ERR_ABORTED",2:"MEDIA_ERR_NETWORK",3:"MEDIA_ERR_DECODE",4:"MEDIA_ERR_SRC_NOT_SUPPORTED"};function IL(i,e,t){var s=bs(Vd(e),3),r=s[0],n=s[1],a=s[2],o=i.log,l=i.utils.getComputedStyle,d=i.utils.secondsToMs,u={automaticErrorTracking:!0};if(r){if(a!=="video"&&a!=="audio")return o.error("The element of `"+n+"` was not a media element.")}else return o.error("No element was found with the `"+n+"` query selector.");r.mux&&(r.mux.destroy(),delete r.mux,o.warn("Already monitoring this video element, replacing existing event listeners"));var c={getPlayheadTime:function(){return d(r.currentTime)},getStateData:function(){var f,m,p,g=((f=(m=this).getPlayheadTime)===null||f===void 0?void 0:f.call(m))||d(r.currentTime),v=this.hlsjs&&this.hlsjs.url,b=this.dashjs&&typeof this.dashjs.getSource=="function"&&this.dashjs.getSource(),E={player_is_paused:r.paused,player_width:parseInt(l(r,"width")),player_height:parseInt(l(r,"height")),player_autoplay_on:r.autoplay,player_preload_on:r.preload,player_language_code:r.lang,player_is_fullscreen:_L(),video_poster_url:r.poster,video_source_url:v||b||r.currentSrc,video_source_duration:d(r.duration),video_source_height:r.videoHeight,video_source_width:r.videoWidth,view_dropped_frame_count:r==null||(p=r.getVideoPlaybackQuality)===null||p===void 0?void 0:p.call(r).droppedVideoFrames};if(r.getStartDate&&g>0){var T=r.getStartDate();if(T&&typeof T.getTime=="function"&&T.getTime()){var A=T.getTime();if(E.player_program_time=A+g,r.seekable.length>0){var x=A+r.seekable.end(r.seekable.length-1);E.player_live_edge_program_time=x}}}return E}};t=Object.assign(u,t,c),t.data=Object.assign({player_software:"HTML5 Video Element",player_mux_plugin_name:"VideoElementMonitor",player_mux_plugin_version:i.VERSION},t.data),r.mux=r.mux||{},r.mux.deleted=!1,r.mux.emit=function(f,m){i.emit(n,f,m)},r.mux.updateData=function(f){r.mux.emit("hb",f)};var h=function(){o.error("The monitor for this video element has already been destroyed.")};r.mux.destroy=function(){Object.keys(r.mux.listeners).forEach(function(f){r.removeEventListener(f,r.mux.listeners[f],!1)}),delete r.mux.listeners,r.mux.destroy=h,r.mux.swapElement=h,r.mux.emit=h,r.mux.addHLSJS=h,r.mux.addDashJS=h,r.mux.removeHLSJS=h,r.mux.removeDashJS=h,r.mux.updateData=h,r.mux.setEmitTranslator=h,r.mux.setStateDataTranslator=h,r.mux.setGetPlayheadTime=h,r.mux.deleted=!0,i.emit(n,"destroy")},r.mux.swapElement=function(f){var m=bs(Vd(f),3),p=m[0],g=m[1],v=m[2];if(p){if(v!=="video"&&v!=="audio")return i.log.error("The element of `"+g+"` was not a media element.")}else return i.log.error("No element was found with the `"+g+"` query selector.");p.muxId=r.muxId,delete r.muxId,p.mux=p.mux||{},p.mux.listeners=Object.assign({},r.mux.listeners),delete r.mux.listeners,Object.keys(p.mux.listeners).forEach(function(b){r.removeEventListener(b,p.mux.listeners[b],!1),p.addEventListener(b,p.mux.listeners[b],!1)}),p.mux.swapElement=r.mux.swapElement,p.mux.destroy=r.mux.destroy,delete r.mux,r=p},r.mux.addHLSJS=function(f){i.addHLSJS(n,f)},r.mux.addDashJS=function(f){i.addDashJS(n,f)},r.mux.removeHLSJS=function(){i.removeHLSJS(n)},r.mux.removeDashJS=function(){i.removeDashJS(n)},r.mux.setEmitTranslator=function(f){i.setEmitTranslator(n,f)},r.mux.setStateDataTranslator=function(f){i.setStateDataTranslator(n,f)},r.mux.setGetPlayheadTime=function(f){f||(f=t.getPlayheadTime),i.setGetPlayheadTime(n,f)},i.init(n,t),i.emit(n,"playerready"),r.paused||(i.emit(n,"play"),r.readyState>2&&i.emit(n,"playing")),r.mux.listeners={},AL.forEach(function(f){f==="error"&&!t.automaticErrorTracking||(r.mux.listeners[f]=function(){var m={};if(f==="error"){if(!r.error||r.error.code===1)return;m.player_error_code=r.error.code,m.player_error_message=SL[r.error.code]||r.error.message}i.emit(n,f,m)},r.addEventListener(f,r.mux.listeners[f],!1))})}function xL(i,e,t,s){var r=s;if(i&&typeof i[e]=="function")try{r=i[e].apply(i,t)}catch(n){Ne.info("safeCall error",n)}return r}var ja=Jt(Ii()),pn;ja.default&&ja.default.WeakMap&&(pn=new WeakMap);function LL(i,e){if(!i||!e||!ja.default||typeof ja.default.getComputedStyle!="function")return"";var t;return pn&&pn.has(i)&&(t=pn.get(i)),t||(t=ja.default.getComputedStyle(i,null),pn&&pn.set(i,t)),t.getPropertyValue(e)}function RL(i){return Math.floor(i*1e3)}var tr={TARGET_DURATION:"#EXT-X-TARGETDURATION",PART_INF:"#EXT-X-PART-INF",SERVER_CONTROL:"#EXT-X-SERVER-CONTROL",INF:"#EXTINF",PROGRAM_DATE_TIME:"#EXT-X-PROGRAM-DATE-TIME",VERSION:"#EXT-X-VERSION",SESSION_DATA:"#EXT-X-SESSION-DATA"},Wu=function(i){return this.buffer="",this.manifest={segments:[],serverControl:{},sessionData:{}},this.currentUri={},this.process(i),this.manifest};Wu.prototype.process=function(i){var e;for(this.buffer+=i,e=this.buffer.indexOf(`
|
|
1415
|
+
`):"");n("error",{player_error_code:E?.code,player_error_message:E?.message,player_error_context:L})};t.on("error",v),t._stopMuxMonitor=function(){t.off("manifestLoaded",a),t.off("initFragmentLoaded",u),t.off("mediaFragmentLoaded",h),t.off("qualityChangeRendered",p),t.off("error",v),t.off("fragmentLoadingAbandoned",g),delete t._stopMuxMonitor}},fx=function(i){i&&typeof i._stopMuxMonitor=="function"&&i._stopMuxMonitor()},bg=0,mx=(function(){function i(){Tt(this,i),Y(this,"_listeners",void 0)}return ns(i,[{key:"on",value:function(e,t,s){return t._eventEmitterGuid=t._eventEmitterGuid||++bg,this._listeners=this._listeners||{},this._listeners[e]=this._listeners[e]||[],s&&(t=t.bind(s)),this._listeners[e].push(t),t}},{key:"off",value:function(e,t){var s=this._listeners&&this._listeners[e];s&&s.forEach(function(r,n){r._eventEmitterGuid===t._eventEmitterGuid&&s.splice(n,1)})}},{key:"one",value:function(e,t,s){var r=this;t._eventEmitterGuid=t._eventEmitterGuid||++bg;var n=function(){r.off(e,n),t.apply(s||this,arguments)};n._eventEmitterGuid=t._eventEmitterGuid,this.on(e,n)}},{key:"emit",value:function(e,t){var s=this;if(this._listeners){t=t||{};var r=this._listeners["before*"]||[],n=this._listeners[e]||[],a=this._listeners["after"+e]||[],o=function(l,d){l=l.slice(),l.forEach(function(u){u.call(s,{type:e},d)})};o(r,t),o(n,t),o(a,t)}}}]),i})(),px=mx,pc=Jt(Ii()),gx=(function(){function i(e){var t=this;Tt(this,i),Y(this,"_playbackHeartbeatInterval",void 0),Y(this,"_playheadShouldBeProgressing",void 0),Y(this,"pm",void 0),this.pm=e,this._playbackHeartbeatInterval=null,this._playheadShouldBeProgressing=!1,e.on("playing",function(){t._playheadShouldBeProgressing=!0}),e.on("play",this._startPlaybackHeartbeatInterval.bind(this)),e.on("playing",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adbreakstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adplay",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adplaying",this._startPlaybackHeartbeatInterval.bind(this)),e.on("devicewake",this._startPlaybackHeartbeatInterval.bind(this)),e.on("viewstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("rebufferstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("pause",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("ended",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("viewend",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("error",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("aderror",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adpause",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adended",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adbreakend",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("seeked",function(){e.data.player_is_paused?t._stopPlaybackHeartbeatInterval():t._startPlaybackHeartbeatInterval()}),e.on("timeupdate",function(){t._playbackHeartbeatInterval!==null&&e.emit("playbackheartbeat")}),e.on("devicesleep",function(s,r){t._playbackHeartbeatInterval!==null&&(pc.default.clearInterval(t._playbackHeartbeatInterval),e.emit("playbackheartbeatend",{viewer_time:r.viewer_time}),t._playbackHeartbeatInterval=null)})}return ns(i,[{key:"_startPlaybackHeartbeatInterval",value:function(){var e=this;this._playbackHeartbeatInterval===null&&(this.pm.emit("playbackheartbeat"),this._playbackHeartbeatInterval=pc.default.setInterval(function(){e.pm.emit("playbackheartbeat")},this.pm.playbackHeartbeatTime))}},{key:"_stopPlaybackHeartbeatInterval",value:function(){this._playheadShouldBeProgressing=!1,this._playbackHeartbeatInterval!==null&&(pc.default.clearInterval(this._playbackHeartbeatInterval),this.pm.emit("playbackheartbeatend"),this._playbackHeartbeatInterval=null)}}]),i})(),vx=gx,Ex=function i(e){var t=this;Tt(this,i),Y(this,"viewErrored",void 0),e.on("viewinit",function(){t.viewErrored=!1}),e.on("error",function(s,r){try{var n=e.errorTranslator({player_error_code:r.player_error_code,player_error_message:r.player_error_message,player_error_context:r.player_error_context,player_error_severity:r.player_error_severity,player_error_business_exception:r.player_error_business_exception});n&&(e.data.player_error_code=n.player_error_code||r.player_error_code,e.data.player_error_message=n.player_error_message||r.player_error_message,e.data.player_error_context=n.player_error_context||r.player_error_context,e.data.player_error_severity=n.player_error_severity||r.player_error_severity,e.data.player_error_business_exception=n.player_error_business_exception||r.player_error_business_exception,t.viewErrored=!0)}catch(a){e.mux.log.warn("Exception in error translator callback.",a),t.viewErrored=!0}}),e.on("aftererror",function(){var s,r,n,a,o;(s=e.data)===null||s===void 0||delete s.player_error_code,(r=e.data)===null||r===void 0||delete r.player_error_message,(n=e.data)===null||n===void 0||delete n.player_error_context,(a=e.data)===null||a===void 0||delete a.player_error_severity,(o=e.data)===null||o===void 0||delete o.player_error_business_exception})},yx=Ex,bx=(function(){function i(e){Tt(this,i),Y(this,"_watchTimeTrackerLastCheckedTime",void 0),Y(this,"pm",void 0),this.pm=e,this._watchTimeTrackerLastCheckedTime=null,e.on("playbackheartbeat",this._updateWatchTime.bind(this)),e.on("playbackheartbeatend",this._clearWatchTimeState.bind(this))}return ns(i,[{key:"_updateWatchTime",value:function(e,t){var s=t.viewer_time;this._watchTimeTrackerLastCheckedTime===null&&(this._watchTimeTrackerLastCheckedTime=s),ot(this.pm.data,"view_watch_time",s-this._watchTimeTrackerLastCheckedTime),this._watchTimeTrackerLastCheckedTime=s}},{key:"_clearWatchTimeState",value:function(e,t){this._updateWatchTime(e,t),this._watchTimeTrackerLastCheckedTime=null}}]),i})(),Tx=bx,_x=(function(){function i(e){var t=this;Tt(this,i),Y(this,"_playbackTimeTrackerLastPlayheadPosition",void 0),Y(this,"_lastTime",void 0),Y(this,"_isAdPlaying",void 0),Y(this,"_callbackUpdatePlaybackTime",void 0),Y(this,"pm",void 0),this.pm=e,this._playbackTimeTrackerLastPlayheadPosition=-1,this._lastTime=dt.now(),this._isAdPlaying=!1,this._callbackUpdatePlaybackTime=null;var s=this._startPlaybackTimeTracking.bind(this);e.on("playing",s),e.on("adplaying",s),e.on("seeked",s);var r=this._stopPlaybackTimeTracking.bind(this);e.on("playbackheartbeatend",r),e.on("seeking",r),e.on("adplaying",function(){t._isAdPlaying=!0}),e.on("adended",function(){t._isAdPlaying=!1}),e.on("adpause",function(){t._isAdPlaying=!1}),e.on("adbreakstart",function(){t._isAdPlaying=!1}),e.on("adbreakend",function(){t._isAdPlaying=!1}),e.on("adplay",function(){t._isAdPlaying=!1}),e.on("viewinit",function(){t._playbackTimeTrackerLastPlayheadPosition=-1,t._lastTime=dt.now(),t._isAdPlaying=!1,t._callbackUpdatePlaybackTime=null})}return ns(i,[{key:"_startPlaybackTimeTracking",value:function(){this._callbackUpdatePlaybackTime===null&&(this._callbackUpdatePlaybackTime=this._updatePlaybackTime.bind(this),this._playbackTimeTrackerLastPlayheadPosition=this.pm.data.player_playhead_time,this.pm.on("playbackheartbeat",this._callbackUpdatePlaybackTime))}},{key:"_stopPlaybackTimeTracking",value:function(){this._callbackUpdatePlaybackTime&&(this._updatePlaybackTime(),this.pm.off("playbackheartbeat",this._callbackUpdatePlaybackTime),this._callbackUpdatePlaybackTime=null,this._playbackTimeTrackerLastPlayheadPosition=-1)}},{key:"_updatePlaybackTime",value:function(){var e=this.pm.data.player_playhead_time,t=dt.now(),s=-1;this._playbackTimeTrackerLastPlayheadPosition>=0&&e>this._playbackTimeTrackerLastPlayheadPosition?s=e-this._playbackTimeTrackerLastPlayheadPosition:this._isAdPlaying&&(s=t-this._lastTime),s>0&&s<=1e3&&ot(this.pm.data,"view_content_playback_time",s),this._playbackTimeTrackerLastPlayheadPosition=e,this._lastTime=t}}]),i})(),Ax=_x,Sx=(function(){function i(e){Tt(this,i),Y(this,"pm",void 0),this.pm=e;var t=this._updatePlayheadTime.bind(this);e.on("playbackheartbeat",t),e.on("playbackheartbeatend",t),e.on("timeupdate",t),e.on("destroy",function(){e.off("timeupdate",t)})}return ns(i,[{key:"_updateMaxPlayheadPosition",value:function(){this.pm.data.view_max_playhead_position=typeof this.pm.data.view_max_playhead_position>"u"?this.pm.data.player_playhead_time:Math.max(this.pm.data.view_max_playhead_position,this.pm.data.player_playhead_time)}},{key:"_updatePlayheadTime",value:function(e,t){var s=this,r=function(){s.pm.currentFragmentPDT&&s.pm.currentFragmentStart&&(s.pm.data.player_program_time=s.pm.currentFragmentPDT+s.pm.data.player_playhead_time-s.pm.currentFragmentStart)};if(t&&t.player_playhead_time)this.pm.data.player_playhead_time=t.player_playhead_time,r(),this._updateMaxPlayheadPosition();else if(this.pm.getPlayheadTime){var n=this.pm.getPlayheadTime();typeof n<"u"&&(this.pm.data.player_playhead_time=n,r(),this._updateMaxPlayheadPosition())}}}]),i})(),Ix=Sx,Tg=300*1e3,xx=function i(e){if(Tt(this,i),!e.disableRebufferTracking){var t,s=function(n,a){r(a),t=void 0},r=function(n){if(t){var a=n.viewer_time-t;ot(e.data,"view_rebuffer_duration",a),t=n.viewer_time,e.data.view_rebuffer_duration>Tg&&(e.emit("viewend"),e.send("viewend"),e.mux.log.warn("Ending view after rebuffering for longer than ".concat(Tg,"ms, future events will be ignored unless a programchange or videochange occurs.")))}e.data.view_watch_time>=0&&e.data.view_rebuffer_count>0&&(e.data.view_rebuffer_frequency=e.data.view_rebuffer_count/e.data.view_watch_time,e.data.view_rebuffer_percentage=e.data.view_rebuffer_duration/e.data.view_watch_time)};e.on("playbackheartbeat",function(n,a){return r(a)}),e.on("rebufferstart",function(n,a){t||(ot(e.data,"view_rebuffer_count",1),t=a.viewer_time,e.one("rebufferend",s))}),e.on("viewinit",function(){t=void 0,e.off("rebufferend",s)})}},Lx=xx,Rx=(function(){function i(e){var t=this;Tt(this,i),Y(this,"_lastCheckedTime",void 0),Y(this,"_lastPlayheadTime",void 0),Y(this,"_lastPlayheadTimeUpdatedTime",void 0),Y(this,"_rebuffering",void 0),Y(this,"pm",void 0),this.pm=e,!(e.disableRebufferTracking||e.disablePlayheadRebufferTracking)&&(this._lastCheckedTime=null,this._lastPlayheadTime=null,this._lastPlayheadTimeUpdatedTime=null,e.on("playbackheartbeat",this._checkIfRebuffering.bind(this)),e.on("playbackheartbeatend",this._cleanupRebufferTracker.bind(this)),e.on("seeking",function(){t._cleanupRebufferTracker(null,{viewer_time:dt.now()})}))}return ns(i,[{key:"_checkIfRebuffering",value:function(e,t){if(this.pm.seekingTracker.isSeeking||this.pm.adTracker.isAdBreak||!this.pm.playbackHeartbeat._playheadShouldBeProgressing){this._cleanupRebufferTracker(e,t);return}if(this._lastCheckedTime===null){this._prepareRebufferTrackerState(t.viewer_time);return}if(this._lastPlayheadTime!==this.pm.data.player_playhead_time){this._cleanupRebufferTracker(e,t,!0);return}var s=t.viewer_time-this._lastPlayheadTimeUpdatedTime;typeof this.pm.sustainedRebufferThreshold=="number"&&s>=this.pm.sustainedRebufferThreshold&&(this._rebuffering||(this._rebuffering=!0,this.pm.emit("rebufferstart",{viewer_time:this._lastPlayheadTimeUpdatedTime}))),this._lastCheckedTime=t.viewer_time}},{key:"_clearRebufferTrackerState",value:function(){this._lastCheckedTime=null,this._lastPlayheadTime=null,this._lastPlayheadTimeUpdatedTime=null}},{key:"_prepareRebufferTrackerState",value:function(e){this._lastCheckedTime=e,this._lastPlayheadTime=this.pm.data.player_playhead_time,this._lastPlayheadTimeUpdatedTime=e}},{key:"_cleanupRebufferTracker",value:function(e,t){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;if(this._rebuffering)this._rebuffering=!1,this.pm.emit("rebufferend",{viewer_time:t.viewer_time});else{if(this._lastCheckedTime===null)return;var r=this.pm.data.player_playhead_time-this._lastPlayheadTime,n=t.viewer_time-this._lastPlayheadTimeUpdatedTime;typeof this.pm.minimumRebufferDuration=="number"&&r>0&&n-r>this.pm.minimumRebufferDuration&&(this._lastCheckedTime=null,this.pm.emit("rebufferstart",{viewer_time:this._lastPlayheadTimeUpdatedTime}),this.pm.emit("rebufferend",{viewer_time:this._lastPlayheadTimeUpdatedTime+n-r}))}s?this._prepareRebufferTrackerState(t.viewer_time):this._clearRebufferTrackerState()}}]),i})(),kx=Rx,Dx=(function(){function i(e){var t=this;Tt(this,i),Y(this,"NAVIGATION_START",void 0),Y(this,"pm",void 0),this.pm=e,e.on("viewinit",function(){var s=e.data,r=s.view_id;if(!s.view_program_changed){var n=function(a,o){var l=o.viewer_time;(a.type==="playing"&&typeof e.data.view_time_to_first_frame>"u"||a.type==="adplaying"&&(typeof e.data.view_time_to_first_frame>"u"||t._inPrerollPosition()))&&t.calculateTimeToFirstFrame(l||dt.now(),r)};e.one("playing",n),e.one("adplaying",n),e.one("viewend",function(){e.off("playing",n),e.off("adplaying",n)})}})}return ns(i,[{key:"_inPrerollPosition",value:function(){return typeof this.pm.data.view_content_playback_time>"u"||this.pm.data.view_content_playback_time<=1e3}},{key:"calculateTimeToFirstFrame",value:function(e,t){t===this.pm.data.view_id&&(this.pm.watchTimeTracker._updateWatchTime(null,{viewer_time:e}),this.pm.data.view_time_to_first_frame=this.pm.data.view_watch_time,(this.pm.data.player_autoplay_on||this.pm.data.video_is_autoplay)&&this.NAVIGATION_START&&(this.pm.data.view_aggregate_startup_time=this.pm.data.view_start+this.pm.data.view_watch_time-this.NAVIGATION_START))}}]),i})(),Cx=Dx,wx=function i(e){var t=this;Tt(this,i),Y(this,"_lastPlayerHeight",void 0),Y(this,"_lastPlayerWidth",void 0),Y(this,"_lastPlayheadPosition",void 0),Y(this,"_lastSourceHeight",void 0),Y(this,"_lastSourceWidth",void 0),e.on("viewinit",function(){t._lastPlayheadPosition=-1});var s=["pause","rebufferstart","seeking","error","adbreakstart","hb","renditionchange","orientationchange","viewend"],r=["playing","hb","renditionchange","orientationchange"];s.forEach(function(n){e.on(n,function(){if(t._lastPlayheadPosition>=0&&e.data.player_playhead_time>=0&&t._lastPlayerWidth>=0&&t._lastSourceWidth>0&&t._lastPlayerHeight>=0&&t._lastSourceHeight>0){var a=e.data.player_playhead_time-t._lastPlayheadPosition;if(a<0){t._lastPlayheadPosition=-1;return}var o=Math.min(t._lastPlayerWidth/t._lastSourceWidth,t._lastPlayerHeight/t._lastSourceHeight),l=Math.max(0,o-1),d=Math.max(0,1-o);e.data.view_max_upscale_percentage=Math.max(e.data.view_max_upscale_percentage||0,l),e.data.view_max_downscale_percentage=Math.max(e.data.view_max_downscale_percentage||0,d),ot(e.data,"view_total_content_playback_time",a),ot(e.data,"view_total_upscaling",l*a),ot(e.data,"view_total_downscaling",d*a)}t._lastPlayheadPosition=-1})}),r.forEach(function(n){e.on(n,function(){t._lastPlayheadPosition=e.data.player_playhead_time,t._lastPlayerWidth=e.data.player_width,t._lastPlayerHeight=e.data.player_height,t._lastSourceWidth=e.data.video_source_width,t._lastSourceHeight=e.data.video_source_height})})},Mx=wx,Px=2e3,Ox=function i(e){var t=this;Tt(this,i),Y(this,"isSeeking",void 0),this.isSeeking=!1;var s=-1,r=function(){var n=dt.now(),a=(e.data.viewer_time||n)-(s||n);ot(e.data,"view_seek_duration",a),e.data.view_max_seek_time=Math.max(e.data.view_max_seek_time||0,a),t.isSeeking=!1,s=-1};e.on("seeking",function(n,a){if(Object.assign(e.data,a),t.isSeeking&&a.viewer_time-s<=Px){s=a.viewer_time;return}t.isSeeking&&r(),t.isSeeking=!0,s=a.viewer_time,ot(e.data,"view_seek_count",1),e.send("seeking")}),e.on("seeked",function(){r()}),e.on("viewend",function(){t.isSeeking&&(r(),e.send("seeked")),t.isSeeking=!1,s=-1})},Nx=Ox,_g=function(i,e){i.push(e),i.sort(function(t,s){return t.viewer_time-s.viewer_time})},Ux=["adbreakstart","adrequest","adresponse","adplay","adplaying","adpause","adended","adbreakend","aderror","adclicked","adskipped"],$x=(function(){function i(e){var t=this;Tt(this,i),Y(this,"_adHasPlayed",void 0),Y(this,"_adRequests",void 0),Y(this,"_adResponses",void 0),Y(this,"_currentAdRequestNumber",void 0),Y(this,"_currentAdResponseNumber",void 0),Y(this,"_prerollPlayTime",void 0),Y(this,"_wouldBeNewAdPlay",void 0),Y(this,"isAdBreak",void 0),Y(this,"pm",void 0),this.pm=e,e.on("viewinit",function(){t.isAdBreak=!1,t._currentAdRequestNumber=0,t._currentAdResponseNumber=0,t._adRequests=[],t._adResponses=[],t._adHasPlayed=!1,t._wouldBeNewAdPlay=!0,t._prerollPlayTime=void 0}),Ux.forEach(function(r){return e.on(r,t._updateAdData.bind(t))});var s=function(){t.isAdBreak=!1};e.on("adbreakstart",function(){t.isAdBreak=!0}),e.on("play",s),e.on("playing",s),e.on("viewend",s),e.on("adrequest",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdRequestNumber++},n),_g(t._adRequests,n),ot(e.data,"view_ad_request_count"),t.inPrerollPosition()&&(e.data.view_preroll_requested=!0,t._adHasPlayed||ot(e.data,"view_preroll_request_count"))}),e.on("adresponse",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdResponseNumber++},n),_g(t._adResponses,n);var a=t.findAdRequest(n.ad_request_id);a&&ot(e.data,"view_ad_request_time",Math.max(0,n.viewer_time-a.viewer_time))}),e.on("adplay",function(r,n){t._adHasPlayed=!0,t._wouldBeNewAdPlay&&(t._wouldBeNewAdPlay=!1,ot(e.data,"view_ad_played_count")),t.inPrerollPosition()&&!e.data.view_preroll_played&&(e.data.view_preroll_played=!0,t._adRequests.length>0&&(e.data.view_preroll_request_time=Math.max(0,n.viewer_time-t._adRequests[0].viewer_time)),e.data.view_start&&(e.data.view_startup_preroll_request_time=Math.max(0,n.viewer_time-e.data.view_start)),t._prerollPlayTime=n.viewer_time)}),e.on("adplaying",function(r,n){t.inPrerollPosition()&&typeof e.data.view_preroll_load_time>"u"&&typeof t._prerollPlayTime<"u"&&(e.data.view_preroll_load_time=n.viewer_time-t._prerollPlayTime,e.data.view_startup_preroll_load_time=n.viewer_time-t._prerollPlayTime)}),e.on("adclicked",function(r,n){t._wouldBeNewAdPlay||ot(e.data,"view_ad_clicked_count")}),e.on("adskipped",function(r,n){t._wouldBeNewAdPlay||ot(e.data,"view_ad_skipped_count")}),e.on("adended",function(){t._wouldBeNewAdPlay=!0}),e.on("aderror",function(){t._wouldBeNewAdPlay=!0})}return ns(i,[{key:"inPrerollPosition",value:function(){return typeof this.pm.data.view_content_playback_time>"u"||this.pm.data.view_content_playback_time<=1e3}},{key:"findAdRequest",value:function(e){for(var t=0;t<this._adRequests.length;t++)if(this._adRequests[t].ad_request_id===e)return this._adRequests[t]}},{key:"_updateAdData",value:function(e,t){if(this.inPrerollPosition()){if(!this.pm.data.view_preroll_ad_tag_hostname&&t.ad_tag_url){var s=bs(fo(t.ad_tag_url),2),r=s[0],n=s[1];this.pm.data.view_preroll_ad_tag_domain=n,this.pm.data.view_preroll_ad_tag_hostname=r}if(!this.pm.data.view_preroll_ad_asset_hostname&&t.ad_asset_url){var a=bs(fo(t.ad_asset_url),2),o=a[0],l=a[1];this.pm.data.view_preroll_ad_asset_domain=l,this.pm.data.view_preroll_ad_asset_hostname=o}}this.pm.data.ad_asset_url=t?.ad_asset_url,this.pm.data.ad_tag_url=t?.ad_tag_url,this.pm.data.ad_creative_id=t?.ad_creative_id,this.pm.data.ad_id=t?.ad_id,this.pm.data.ad_universal_id=t?.ad_universal_id}}]),i})(),Fx=$x,Ag=Jt(Ii()),Bx=function i(e){Tt(this,i);var t,s,r=function(){e.disableRebufferTracking||(ot(e.data,"view_waiting_rebuffer_count",1),t=dt.now(),s=Ag.default.setInterval(function(){if(t){var d=dt.now();ot(e.data,"view_waiting_rebuffer_duration",d-t),t=d}},250))},n=function(){e.disableRebufferTracking||t&&(ot(e.data,"view_waiting_rebuffer_duration",dt.now()-t),t=!1,Ag.default.clearInterval(s))},a=!1,o=function(){a=!0},l=function(){a=!1,n()};e.on("waiting",function(){a&&r()}),e.on("playing",function(){n(),o()}),e.on("pause",l),e.on("seeking",l)},Hx=Bx,Gx=function i(e){var t=this;Tt(this,i),Y(this,"lastWallClockTime",void 0);var s=function(){t.lastWallClockTime=dt.now(),e.on("before*",r)},r=function(n){var a=dt.now(),o=t.lastWallClockTime;t.lastWallClockTime=a,a-o>3e4&&(e.emit("devicesleep",{viewer_time:o}),Object.assign(e.data,{viewer_time:o}),e.send("devicesleep"),e.emit("devicewake",{viewer_time:a}),Object.assign(e.data,{viewer_time:a}),e.send("devicewake"))};e.one("playbackheartbeat",s),e.on("playbackheartbeatend",function(){e.off("before*",r),e.one("playbackheartbeat",s)})},Kx=Gx,gc=Jt(Ii()),py=(function(i){return i()})(function(){var i=function(){for(var t=0,s={};t<arguments.length;t++){var r=arguments[t];for(var n in r)s[n]=r[n]}return s};function e(t){function s(r,n,a){var o;if(typeof document<"u"){if(arguments.length>1){if(a=i({path:"/"},s.defaults,a),typeof a.expires=="number"){var l=new Date;l.setMilliseconds(l.getMilliseconds()+a.expires*864e5),a.expires=l}try{o=JSON.stringify(n),/^[\{\[]/.test(o)&&(n=o)}catch{}return t.write?n=t.write(n,r):n=encodeURIComponent(String(n)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),r=encodeURIComponent(String(r)),r=r.replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent),r=r.replace(/[\(\)]/g,escape),document.cookie=[r,"=",n,a.expires?"; expires="+a.expires.toUTCString():"",a.path?"; path="+a.path:"",a.domain?"; domain="+a.domain:"",a.secure?"; secure":""].join("")}r||(o={});for(var d=document.cookie?document.cookie.split("; "):[],u=/(%[0-9A-Z]{2})+/g,c=0;c<d.length;c++){var h=d[c].split("="),f=h.slice(1).join("=");f.charAt(0)==='"'&&(f=f.slice(1,-1));try{var m=h[0].replace(u,decodeURIComponent);if(f=t.read?t.read(f,m):t(f,m)||f.replace(u,decodeURIComponent),this.json)try{f=JSON.parse(f)}catch{}if(r===m){o=f;break}r||(o[m]=f)}catch{}}return o}}return s.set=s,s.get=function(r){return s.call(s,r)},s.getJSON=function(){return s.apply({json:!0},[].slice.call(arguments))},s.defaults={},s.remove=function(r,n){s(r,"",i(n,{expires:-1}))},s.withConverter=e,s}return e(function(){})}),gy="muxData",Vx=function(i){return Object.entries(i).map(function(e){var t=bs(e,2),s=t[0],r=t[1];return"".concat(s,"=").concat(r)}).join("&")},Wx=function(i){return i.split("&").reduce(function(e,t){var s=bs(t.split("="),2),r=s[0],n=s[1],a=+n,o=n&&a==n?a:n;return e[r]=o,e},{})},vy=function(){var i;try{i=Wx(py.get(gy)||"")}catch{i={}}return i},Ey=function(i){try{py.set(gy,Vx(i),{expires:365})}catch{}},qx=function(){var i=vy();return i.mux_viewer_id=i.mux_viewer_id||ho(),i.msn=i.msn||Math.random(),Ey(i),{mux_viewer_id:i.mux_viewer_id,mux_sample_number:i.msn}},Yx=function(){var i=vy(),e=dt.now();return i.session_start&&(i.sst=i.session_start,delete i.session_start),i.session_id&&(i.sid=i.session_id,delete i.session_id),i.session_expires&&(i.sex=i.session_expires,delete i.session_expires),(!i.sex||i.sex<e)&&(i.sid=ho(),i.sst=e),i.sex=e+1500*1e3,Ey(i),{session_id:i.sid,session_start:i.sst,session_expires:i.sex}};function jx(i,e){var t=e.beaconCollectionDomain,s=e.beaconDomain;if(t)return"https://"+t;i=i||"inferred";var r=s||"litix.io";return i.match(/^[a-z0-9]+$/)?"https://"+i+"."+r:"https://img.litix.io/a.gif"}var zx=Jt(Ii()),yy=function(){var i;switch(by()){case"cellular":i="cellular";break;case"ethernet":i="wired";break;case"wifi":i="wifi";break;case void 0:break;default:i="other"}return i},by=function(){var i=zx.default.navigator,e=i&&(i.connection||i.mozConnection||i.webkitConnection);return e&&e.type};yy.getConnectionFromAPI=by;var Qx=yy,Xx={a:"env",b:"beacon",c:"custom",d:"ad",e:"event",f:"experiment",i:"internal",m:"mux",n:"response",p:"player",q:"request",r:"retry",s:"session",t:"timestamp",u:"viewer",v:"video",w:"page",x:"view",y:"sub"},Zx=Ty(Xx),Jx={ad:"ad",af:"affiliate",ag:"aggregate",ap:"api",al:"application",ao:"audio",ar:"architecture",as:"asset",au:"autoplay",av:"average",bi:"bitrate",bn:"brand",br:"break",bw:"browser",by:"bytes",bz:"business",ca:"cached",cb:"cancel",cc:"codec",cd:"code",cg:"category",ch:"changed",ci:"client",ck:"clicked",cl:"canceled",cn:"config",co:"count",ce:"counter",cp:"complete",cq:"creator",cr:"creative",cs:"captions",ct:"content",cu:"current",cx:"connection",cz:"context",dg:"downscaling",dm:"domain",dn:"cdn",do:"downscale",dr:"drm",dp:"dropped",du:"duration",dv:"device",dy:"dynamic",eb:"enabled",ec:"encoding",ed:"edge",en:"end",eg:"engine",em:"embed",er:"error",ep:"experiments",es:"errorcode",et:"errortext",ee:"event",ev:"events",ex:"expires",ez:"exception",fa:"failed",fi:"first",fm:"family",ft:"format",fp:"fps",fq:"frequency",fr:"frame",fs:"fullscreen",ha:"has",hb:"holdback",he:"headers",ho:"host",hn:"hostname",ht:"height",id:"id",ii:"init",in:"instance",ip:"ip",is:"is",ke:"key",la:"language",lb:"labeled",le:"level",li:"live",ld:"loaded",lo:"load",ls:"lists",lt:"latency",ma:"max",md:"media",me:"message",mf:"manifest",mi:"mime",ml:"midroll",mm:"min",mn:"manufacturer",mo:"model",mx:"mux",ne:"newest",nm:"name",no:"number",on:"on",or:"origin",os:"os",pa:"paused",pb:"playback",pd:"producer",pe:"percentage",pf:"played",pg:"program",ph:"playhead",pi:"plugin",pl:"preroll",pn:"playing",po:"poster",pp:"pip",pr:"preload",ps:"position",pt:"part",py:"property",px:"pop",pz:"plan",ra:"rate",rd:"requested",re:"rebuffer",rf:"rendition",rg:"range",rm:"remote",ro:"ratio",rp:"response",rq:"request",rs:"requests",sa:"sample",sd:"skipped",se:"session",sh:"shift",sk:"seek",sm:"stream",so:"source",sq:"sequence",sr:"series",ss:"status",st:"start",su:"startup",sv:"server",sw:"software",sy:"severity",ta:"tag",tc:"tech",te:"text",tg:"target",th:"throughput",ti:"time",tl:"total",to:"to",tt:"title",ty:"type",ug:"upscaling",un:"universal",up:"upscale",ur:"url",us:"user",va:"variant",vd:"viewed",vi:"video",ve:"version",vw:"view",vr:"viewer",wd:"width",wa:"watch",wt:"waiting"},Sg=Ty(Jx);function Ty(i){var e={};for(var t in i)i.hasOwnProperty(t)&&(e[i[t]]=t);return e}function Oh(i){var e={},t={};return Object.keys(i).forEach(function(s){var r=!1;if(i.hasOwnProperty(s)&&i[s]!==void 0){var n=s.split("_"),a=n[0],o=Zx[a];o||(Ne.info("Data key word `"+n[0]+"` not expected in "+s),o=a+"_"),n.splice(1).forEach(function(l){l==="url"&&(r=!0),Sg[l]?o+=Sg[l]:Number.isInteger(Number(l))?o+=l:(Ne.info("Data key word `"+l+"` not expected in "+s),o+="_"+l+"_")}),r?t[o]=i[s]:e[o]=i[s]}}),Object.assign(e,t)}var br=Jt(Ii()),eL=Jt(uy()),tL={maxBeaconSize:300,maxQueueLength:3600,baseTimeBetweenBeacons:1e4,maxPayloadKBSize:500},iL=56*1024,sL=["hb","requestcompleted","requestfailed","requestcanceled"],rL="https://img.litix.io",As=function(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this._beaconUrl=i||rL,this._eventQueue=[],this._postInFlight=!1,this._resendAfterPost=!1,this._failureCount=0,this._sendTimeout=!1,this._options=Object.assign({},tL,e)};As.prototype.queueEvent=function(i,e){var t=Object.assign({},e);return this._eventQueue.length<=this._options.maxQueueLength||i==="eventrateexceeded"?(this._eventQueue.push(t),this._sendTimeout||this._startBeaconSending(),this._eventQueue.length<=this._options.maxQueueLength):!1};As.prototype.flushEvents=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(i&&this._eventQueue.length===1){this._eventQueue.pop();return}this._eventQueue.length&&this._sendBeaconQueue(),this._startBeaconSending()};As.prototype.destroy=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;this.destroyed=!0,i?this._clearBeaconQueue():this.flushEvents(),br.default.clearTimeout(this._sendTimeout)};As.prototype._clearBeaconQueue=function(){var i=this._eventQueue.length>this._options.maxBeaconSize?this._eventQueue.length-this._options.maxBeaconSize:0,e=this._eventQueue.slice(i);i>0&&Object.assign(e[e.length-1],Oh({mux_view_message:"event queue truncated"}));var t=this._createPayload(e);_y(this._beaconUrl,t,!0,function(){})};As.prototype._sendBeaconQueue=function(){var i=this;if(this._postInFlight){this._resendAfterPost=!0;return}var e=this._eventQueue.slice(0,this._options.maxBeaconSize);this._eventQueue=this._eventQueue.slice(this._options.maxBeaconSize),this._postInFlight=!0;var t=this._createPayload(e),s=dt.now();_y(this._beaconUrl,t,!1,function(r,n){n?(i._eventQueue=e.concat(i._eventQueue),i._failureCount+=1,Ne.info("Error sending beacon: "+n)):i._failureCount=0,i._roundTripTime=dt.now()-s,i._postInFlight=!1,i._resendAfterPost&&(i._resendAfterPost=!1,i._eventQueue.length>0&&i._sendBeaconQueue())})};As.prototype._getNextBeaconTime=function(){if(!this._failureCount)return this._options.baseTimeBetweenBeacons;var i=Math.pow(2,this._failureCount-1);return i=i*Math.random(),(1+i)*this._options.baseTimeBetweenBeacons};As.prototype._startBeaconSending=function(){var i=this;br.default.clearTimeout(this._sendTimeout),!this.destroyed&&(this._sendTimeout=br.default.setTimeout(function(){i._eventQueue.length&&i._sendBeaconQueue(),i._startBeaconSending()},this._getNextBeaconTime()))};As.prototype._createPayload=function(i){var e=this,t={transmission_timestamp:Math.round(dt.now())};this._roundTripTime&&(t.rtt_ms=Math.round(this._roundTripTime));var s,r,n,a=function(){s=JSON.stringify({metadata:t,events:r||i}),n=s.length/1024},o=function(){return n<=e._options.maxPayloadKBSize};return a(),o()||(Ne.info("Payload size is too big ("+n+" kb). Removing unnecessary events."),r=i.filter(function(l){return sL.indexOf(l.e)===-1}),a()),o()||(Ne.info("Payload size still too big ("+n+" kb). Cropping fields.."),r.forEach(function(l){for(var d in l){var u=l[d],c=50*1024;typeof u=="string"&&u.length>c&&(l[d]=u.substring(0,c))}}),a()),s};var nL=typeof eL.default.exitPictureInPicture=="function"?function(i){return i.length<=iL}:function(i){return!1},_y=function(i,e,t,s){if(t&&navigator&&navigator.sendBeacon&&navigator.sendBeacon(i,e)){s();return}if(br.default.fetch){br.default.fetch(i,{method:"POST",body:e,headers:{"Content-Type":"text/plain"},keepalive:nL(e)}).then(function(n){return s(null,n.ok?null:"Error")}).catch(function(n){return s(null,n)});return}if(br.default.XMLHttpRequest){var r=new br.default.XMLHttpRequest;r.onreadystatechange=function(){if(r.readyState===4)return s(null,r.status!==200?"error":void 0)},r.open("POST",i),r.setRequestHeader("Content-Type","text/plain"),r.send(e);return}s()},aL=As,oL=["env_key","view_id","view_sequence_number","player_sequence_number","beacon_domain","player_playhead_time","viewer_time","mux_api_version","event","video_id","player_instance_id","player_error_code","player_error_message","player_error_context","player_error_severity","player_error_business_exception"],lL=["adplay","adplaying","adpause","adfirstquartile","admidpoint","adthirdquartile","adended","adresponse","adrequest"],dL=["ad_id","ad_creative_id","ad_universal_id"],uL=["viewstart","error","ended","viewend"],cL=600*1e3,hL=(function(){function i(e,t){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Tt(this,i);var r,n,a,o,l,d,u,c,h,f,m,p;Y(this,"mux",void 0),Y(this,"envKey",void 0),Y(this,"options",void 0),Y(this,"eventQueue",void 0),Y(this,"sampleRate",void 0),Y(this,"disableCookies",void 0),Y(this,"respectDoNotTrack",void 0),Y(this,"previousBeaconData",void 0),Y(this,"lastEventTime",void 0),Y(this,"rateLimited",void 0),Y(this,"pageLevelData",void 0),Y(this,"viewerData",void 0),this.mux=e,this.envKey=t,this.options=s,this.previousBeaconData=null,this.lastEventTime=0,this.rateLimited=!1,this.eventQueue=new aL(jx(this.envKey,this.options));var g;this.sampleRate=(g=this.options.sampleRate)!==null&&g!==void 0?g:1;var v;this.disableCookies=(v=this.options.disableCookies)!==null&&v!==void 0?v:!1;var b;this.respectDoNotTrack=(b=this.options.respectDoNotTrack)!==null&&b!==void 0?b:!1,this.previousBeaconData=null,this.lastEventTime=0,this.rateLimited=!1,this.pageLevelData={mux_api_version:this.mux.API_VERSION,mux_embed:this.mux.NAME,mux_embed_version:this.mux.VERSION,viewer_application_name:(r=this.options.platform)===null||r===void 0?void 0:r.name,viewer_application_version:(n=this.options.platform)===null||n===void 0?void 0:n.version,viewer_application_engine:(a=this.options.platform)===null||a===void 0?void 0:a.layout,viewer_device_name:(o=this.options.platform)===null||o===void 0?void 0:o.product,viewer_device_category:"",viewer_device_manufacturer:(l=this.options.platform)===null||l===void 0?void 0:l.manufacturer,viewer_os_family:(u=this.options.platform)===null||u===void 0||(d=u.os)===null||d===void 0?void 0:d.family,viewer_os_architecture:(h=this.options.platform)===null||h===void 0||(c=h.os)===null||c===void 0?void 0:c.architecture,viewer_os_version:(m=this.options.platform)===null||m===void 0||(f=m.os)===null||f===void 0?void 0:f.version,viewer_connection_type:Qx(),page_url:gc.default===null||gc.default===void 0||(p=gc.default.location)===null||p===void 0?void 0:p.href},this.viewerData=this.disableCookies?{}:qx()}return ns(i,[{key:"send",value:function(e,t){if(!(!e||!(t!=null&&t.view_id))){if(this.respectDoNotTrack&&Mh())return Ne.info("Not sending `"+e+"` because Do Not Track is enabled");if(!t||typeof t!="object")return Ne.error("A data object was expected in send() but was not provided");var s=this.disableCookies?{}:Yx(),r=xm(qd({},this.pageLevelData,t,s,this.viewerData),{event:e,env_key:this.envKey});r.user_id&&(r.viewer_user_id=r.user_id,delete r.user_id);var n,a=((n=r.mux_sample_number)!==null&&n!==void 0?n:0)>=this.sampleRate,o=this._deduplicateBeaconData(e,r),l=Oh(o);if(this.lastEventTime=this.mux.utils.now(),a)return Ne.info("Not sending event due to sample rate restriction",e,r,l);if(this.envKey||Ne.info("Missing environment key (envKey) - beacons will be dropped if the video source is not a valid mux video URL",e,r,l),!this.rateLimited){if(Ne.info("Sending event",e,r,l),this.rateLimited=!this.eventQueue.queueEvent(e,l),this.mux.WINDOW_UNLOADING&&e==="viewend")this.eventQueue.destroy(!0);else if(this.mux.WINDOW_HIDDEN&&e==="hb"?this.eventQueue.flushEvents(!0):uL.indexOf(e)>=0&&this.eventQueue.flushEvents(),this.rateLimited)return r.event="eventrateexceeded",l=Oh(r),this.eventQueue.queueEvent(r.event,l),Ne.error("Beaconing disabled due to rate limit.")}}}},{key:"destroy",value:function(){this.eventQueue.destroy(!1)}},{key:"_deduplicateBeaconData",value:function(e,t){var s=this,r={},n=t.view_id;if(n==="-1"||e==="viewstart"||e==="viewend"||!this.previousBeaconData||this.mux.utils.now()-this.lastEventTime>=cL)r=qd({},t),n&&(this.previousBeaconData=r),n&&e==="viewend"&&(this.previousBeaconData=null);else{var a=e.indexOf("request")===0;Object.entries(t).forEach(function(o){var l=bs(o,2),d=l[0],u=l[1];s.previousBeaconData&&(u!==s.previousBeaconData[d]||oL.indexOf(d)>-1||s.objectHasChanged(a,d,u,s.previousBeaconData[d])||s.eventRequiresKey(e,d))&&(r[d]=u,s.previousBeaconData[d]=u)})}return r}},{key:"objectHasChanged",value:function(e,t,s,r){return!e||t.indexOf("request_")!==0?!1:t==="request_response_headers"||typeof s!="object"||typeof r!="object"?!0:Object.keys(s||{}).length!==Object.keys(r||{}).length}},{key:"eventRequiresKey",value:function(e,t){return!!(e==="renditionchange"&&t.indexOf("video_source_")===0||dL.includes(t)&&lL.includes(e))}}]),i})(),fL=function i(e){Tt(this,i);var t=0,s=0,r=0,n=0,a=0,o=0,l=0,d=function(h,f){var m=f.request_start,p=f.request_response_start,g=f.request_response_end,v=f.request_bytes_loaded;n++;var b,E;if(p?(b=p-(m??0),E=(g??0)-p):E=(g??0)-(m??0),E>0&&v&&v>0){var T=v/E*8e3;a++,s+=v,r+=E,e.data.view_min_request_throughput=Math.min(e.data.view_min_request_throughput||1/0,T),e.data.view_average_request_throughput=s/r*8e3,e.data.view_request_count=n,b>0&&(t+=b,e.data.view_max_request_latency=Math.max(e.data.view_max_request_latency||0,b),e.data.view_average_request_latency=t/a)}},u=function(h,f){n++,o++,e.data.view_request_count=n,e.data.view_request_failed_count=o},c=function(h,f){n++,l++,e.data.view_request_count=n,e.data.view_request_canceled_count=l};e.on("requestcompleted",d),e.on("requestfailed",u),e.on("requestcanceled",c)},mL=fL,pL=3600*1e3,gL=function i(e){var t=this;Tt(this,i),Y(this,"_lastEventTime",void 0),e.on("before*",function(s,r){var n=r.viewer_time,a=dt.now(),o=t._lastEventTime;if(t._lastEventTime=a,o&&a-o>pL){var l=Object.keys(e.data).reduce(function(u,c){return c.indexOf("video_")===0?Object.assign(u,Y({},c,e.data[c])):u},{});e.mux.log.info("Received event after at least an hour inactivity, creating a new view");var d=e.playbackHeartbeat._playheadShouldBeProgressing;e._resetView(Object.assign({viewer_time:n},l)),e.playbackHeartbeat._playheadShouldBeProgressing=d,e.playbackHeartbeat._playheadShouldBeProgressing&&s.type!=="play"&&s.type!=="adbreakstart"&&(e.emit("play",{viewer_time:n}),s.type!=="playing"&&e.emit("playing",{viewer_time:n}))}})},vL=gL,EL=["viewstart","ended","loadstart","pause","play","playing","ratechange","waiting","adplay","adpause","adended","aderror","adplaying","adrequest","adresponse","adbreakstart","adbreakend","adfirstquartile","admidpoint","adthirdquartile","rebufferstart","rebufferend","seeked","error","hb","requestcompleted","requestfailed","requestcanceled","renditionchange"],yL=new Set(["requestcompleted","requestfailed","requestcanceled"]),bL=(function(i){ZI(t,i);var e=tx(t);function t(s,r,n){Tt(this,t);var a;a=e.call(this),Y(le(a),"DOM_CONTENT_LOADED_EVENT_END",void 0),Y(le(a),"NAVIGATION_START",void 0),Y(le(a),"_destroyed",void 0),Y(le(a),"_heartBeatTimeout",void 0),Y(le(a),"adTracker",void 0),Y(le(a),"dashjs",void 0),Y(le(a),"data",void 0),Y(le(a),"disablePlayheadRebufferTracking",void 0),Y(le(a),"disableRebufferTracking",void 0),Y(le(a),"errorTracker",void 0),Y(le(a),"errorTranslator",void 0),Y(le(a),"emitTranslator",void 0),Y(le(a),"getAdData",void 0),Y(le(a),"getPlayheadTime",void 0),Y(le(a),"getStateData",void 0),Y(le(a),"stateDataTranslator",void 0),Y(le(a),"hlsjs",void 0),Y(le(a),"id",void 0),Y(le(a),"longResumeTracker",void 0),Y(le(a),"minimumRebufferDuration",void 0),Y(le(a),"mux",void 0),Y(le(a),"playbackEventDispatcher",void 0),Y(le(a),"playbackHeartbeat",void 0),Y(le(a),"playbackHeartbeatTime",void 0),Y(le(a),"playheadTime",void 0),Y(le(a),"seekingTracker",void 0),Y(le(a),"sustainedRebufferThreshold",void 0),Y(le(a),"watchTimeTracker",void 0),Y(le(a),"currentFragmentPDT",void 0),Y(le(a),"currentFragmentStart",void 0),a.DOM_CONTENT_LOADED_EVENT_END=Wd.domContentLoadedEventEnd(),a.NAVIGATION_START=Wd.navigationStart();var o={debug:!1,minimumRebufferDuration:250,sustainedRebufferThreshold:1e3,playbackHeartbeatTime:25,beaconDomain:"litix.io",sampleRate:1,disableCookies:!1,respectDoNotTrack:!1,disableRebufferTracking:!1,disablePlayheadRebufferTracking:!1,errorTranslator:function(h){return h},emitTranslator:function(){for(var h=arguments.length,f=new Array(h),m=0;m<h;m++)f[m]=arguments[m];return f},stateDataTranslator:function(h){return h}};a.mux=s,a.id=r,n!=null&&n.beaconDomain&&a.mux.log.warn("The `beaconDomain` setting has been deprecated in favor of `beaconCollectionDomain`. Please change your integration to use `beaconCollectionDomain` instead of `beaconDomain`."),n=Object.assign(o,n),n.data=n.data||{},n.data.property_key&&(n.data.env_key=n.data.property_key,delete n.data.property_key),Ne.level=n.debug?gr.DEBUG:gr.WARN,a.getPlayheadTime=n.getPlayheadTime,a.getStateData=n.getStateData||function(){return{}},a.getAdData=n.getAdData||function(){},a.minimumRebufferDuration=n.minimumRebufferDuration,a.sustainedRebufferThreshold=n.sustainedRebufferThreshold,a.playbackHeartbeatTime=n.playbackHeartbeatTime,a.disableRebufferTracking=n.disableRebufferTracking,a.disableRebufferTracking&&a.mux.log.warn("Disabling rebuffer tracking. This should only be used in specific circumstances as a last resort when your player is known to unreliably track rebuffering."),a.disablePlayheadRebufferTracking=n.disablePlayheadRebufferTracking,a.errorTranslator=n.errorTranslator,a.emitTranslator=n.emitTranslator,a.stateDataTranslator=n.stateDataTranslator,a.playbackEventDispatcher=new hL(s,n.data.env_key,n),a.data={player_instance_id:ho(),mux_sample_rate:n.sampleRate,beacon_domain:n.beaconCollectionDomain||n.beaconDomain},a.data.view_sequence_number=1,a.data.player_sequence_number=1;var l=(function(){typeof this.data.view_start>"u"&&(this.data.view_start=this.mux.utils.now(),this.emit("viewstart"))}).bind(le(a));if(a.on("viewinit",function(h,f){this._resetVideoData(),this._resetViewData(),this._resetErrorData(),this._updateStateData(),Object.assign(this.data,f),this._initializeViewData(),this.one("play",l),this.one("adbreakstart",l)}),a.on("videochange",function(h,f){this._resetView(f)}),a.on("programchange",function(h,f){this.data.player_is_paused&&this.mux.log.warn("The `programchange` event is intended to be used when the content changes mid playback without the video source changing, however the video is not currently playing. If the video source is changing please use the videochange event otherwise you will lose startup time information."),this._resetView(Object.assign(f,{view_program_changed:!0})),l(),this.emit("play"),this.emit("playing")}),a.on("fragmentchange",function(h,f){this.currentFragmentPDT=f.currentFragmentPDT,this.currentFragmentStart=f.currentFragmentStart}),a.on("destroy",a.destroy),typeof window<"u"&&typeof window.addEventListener=="function"&&typeof window.removeEventListener=="function"){var d=function(){var h=typeof a.data.view_start<"u";a.mux.WINDOW_HIDDEN=document.visibilityState==="hidden",h&&a.mux.WINDOW_HIDDEN&&(a.data.player_is_paused||a.emit("hb"))};window.addEventListener("visibilitychange",d,!1);var u=function(h){h.persisted||a.destroy()};window.addEventListener("pagehide",u,!1),a.on("destroy",function(){window.removeEventListener("visibilitychange",d),window.removeEventListener("pagehide",u)})}a.on("playerready",function(h,f){Object.assign(this.data,f)}),EL.forEach(function(h){a.on(h,function(f,m){h.indexOf("ad")!==0&&this._updateStateData(),Object.assign(this.data,m),this._sanitizeData()}),a.on("after"+h,function(){(h!=="error"||this.errorTracker.viewErrored)&&this.send(h)})}),a.on("viewend",function(h,f){Object.assign(a.data,f)});var c=function(h){var f=this.mux.utils.now();this.data.player_init_time&&(this.data.player_startup_time=f-this.data.player_init_time),!this.mux.PLAYER_TRACKED&&this.NAVIGATION_START&&(this.mux.PLAYER_TRACKED=!0,(this.data.player_init_time||this.DOM_CONTENT_LOADED_EVENT_END)&&(this.data.page_load_time=Math.min(this.data.player_init_time||1/0,this.DOM_CONTENT_LOADED_EVENT_END||1/0)-this.NAVIGATION_START)),this.send("playerready"),delete this.data.player_startup_time,delete this.data.page_load_time};return a.one("playerready",c),a.longResumeTracker=new vL(le(a)),a.errorTracker=new yx(le(a)),new Kx(le(a)),a.seekingTracker=new Nx(le(a)),a.playheadTime=new Ix(le(a)),a.playbackHeartbeat=new vx(le(a)),new Mx(le(a)),a.watchTimeTracker=new Tx(le(a)),new Ax(le(a)),a.adTracker=new Fx(le(a)),new kx(le(a)),new Lx(le(a)),new Cx(le(a)),new Hx(le(a)),new mL(le(a)),n.hlsjs&&a.addHLSJS(n),n.dashjs&&a.addDashJS(n),a.emit("viewinit",n.data),a}return ns(t,[{key:"emit",value:function(s,r){var n,a=Object.assign({viewer_time:this.mux.utils.now()},r),o=[s,a];if(this.emitTranslator)try{o=this.emitTranslator(s,a)}catch(l){this.mux.log.warn("Exception in emit translator callback.",l)}o!=null&&o.length&&(n=Bl(Qn(t.prototype),"emit",this)).call.apply(n,[this].concat(gi(o)))}},{key:"destroy",value:function(){this._destroyed||(this._destroyed=!0,typeof this.data.view_start<"u"&&(this.emit("viewend"),this.send("viewend")),this.playbackEventDispatcher.destroy(),this.removeHLSJS(),this.removeDashJS(),window.clearTimeout(this._heartBeatTimeout))}},{key:"send",value:function(s){if(this.data.view_id){var r=Object.assign({},this.data),n=["player_program_time","player_manifest_newest_program_time","player_live_edge_program_time","player_program_time","video_holdback","video_part_holdback","video_target_duration","video_part_target_duration"];if(r.video_source_is_live===void 0&&(r.player_source_duration===1/0||r.video_source_duration===1/0?r.video_source_is_live=!0:(r.player_source_duration>0||r.video_source_duration>0)&&(r.video_source_is_live=!1)),r.video_source_is_live||n.forEach(function(d){r[d]=void 0}),r.video_source_url=r.video_source_url||r.player_source_url,r.video_source_url){var a=bs(fo(r.video_source_url),2),o=a[0],l=a[1];r.video_source_domain=l,r.video_source_hostname=o}delete r.ad_request_id,this.playbackEventDispatcher.send(s,r),this.data.view_sequence_number++,this.data.player_sequence_number++,yL.has(s)||this._restartHeartBeat(),s==="viewend"&&delete this.data.view_id}}},{key:"_resetView",value:function(s){this.emit("viewend"),this.send("viewend"),this.emit("viewinit",s)}},{key:"_updateStateData",value:function(){var s=this.getStateData();if(typeof this.stateDataTranslator=="function")try{s=this.stateDataTranslator(s)}catch(r){this.mux.log.warn("Exception in stateDataTranslator translator callback.",r)}Object.assign(this.data,s),this.playheadTime._updatePlayheadTime(),this._sanitizeData()}},{key:"_sanitizeData",value:function(){var s=this,r=["player_width","player_height","video_source_width","video_source_height","player_playhead_time","video_source_bitrate"];r.forEach(function(a){var o=parseInt(s.data[a],10);s.data[a]=isNaN(o)?void 0:o});var n=["player_source_url","video_source_url"];n.forEach(function(a){if(s.data[a]){var o=s.data[a].toLowerCase();(o.indexOf("data:")===0||o.indexOf("blob:")===0)&&(s.data[a]="MSE style URL")}})}},{key:"_resetVideoData",value:function(){var s=this;Object.keys(this.data).forEach(function(r){r.indexOf("video_")===0&&delete s.data[r]})}},{key:"_resetViewData",value:function(){var s=this;Object.keys(this.data).forEach(function(r){r.indexOf("view_")===0&&delete s.data[r]}),this.data.view_sequence_number=1}},{key:"_resetErrorData",value:function(){delete this.data.player_error_code,delete this.data.player_error_message,delete this.data.player_error_context,delete this.data.player_error_severity,delete this.data.player_error_business_exception}},{key:"_initializeViewData",value:function(){var s=this,r=this.data.view_id=ho(),n=function(){r===s.data.view_id&&ot(s.data,"player_view_count",1)};this.data.player_is_paused?this.one("play",n):n()}},{key:"_restartHeartBeat",value:function(){var s=this;window.clearTimeout(this._heartBeatTimeout),this._heartBeatTimeout=window.setTimeout(function(){s.data.player_is_paused||s.emit("hb")},1e4)}},{key:"addHLSJS",value:function(s){if(!s.hlsjs){this.mux.log.warn("You must pass a valid hlsjs instance in order to track it.");return}if(this.hlsjs){this.mux.log.warn("An instance of HLS.js is already being monitored for this player.");return}this.hlsjs=s.hlsjs,ox(this.mux,this.id,s.hlsjs,{},s.Hls||window.Hls)}},{key:"removeHLSJS",value:function(){this.hlsjs&&(lx(this.hlsjs),this.hlsjs=void 0)}},{key:"addDashJS",value:function(s){if(!s.dashjs){this.mux.log.warn("You must pass a valid dashjs instance in order to track it.");return}if(this.dashjs){this.mux.log.warn("An instance of Dash.js is already being monitored for this player.");return}this.dashjs=s.dashjs,hx(this.mux,this.id,s.dashjs)}},{key:"removeDashJS",value:function(){this.dashjs&&(fx(this.dashjs),this.dashjs=void 0)}}]),t})(px),TL=bL,ua=Jt(uy());function _L(){return ua.default&&!!(ua.default.fullscreenElement||ua.default.webkitFullscreenElement||ua.default.mozFullScreenElement||ua.default.msFullscreenElement)}var AL=["loadstart","pause","play","playing","seeking","seeked","timeupdate","ratechange","stalled","waiting","error","ended"],SL={1:"MEDIA_ERR_ABORTED",2:"MEDIA_ERR_NETWORK",3:"MEDIA_ERR_DECODE",4:"MEDIA_ERR_SRC_NOT_SUPPORTED"};function IL(i,e,t){var s=bs(Vd(e),3),r=s[0],n=s[1],a=s[2],o=i.log,l=i.utils.getComputedStyle,d=i.utils.secondsToMs,u={automaticErrorTracking:!0};if(r){if(a!=="video"&&a!=="audio")return o.error("The element of `"+n+"` was not a media element.")}else return o.error("No element was found with the `"+n+"` query selector.");r.mux&&(r.mux.destroy(),delete r.mux,o.warn("Already monitoring this video element, replacing existing event listeners"));var c={getPlayheadTime:function(){return d(r.currentTime)},getStateData:function(){var f,m,p,g=((f=(m=this).getPlayheadTime)===null||f===void 0?void 0:f.call(m))||d(r.currentTime),v=this.hlsjs&&this.hlsjs.url,b=this.dashjs&&typeof this.dashjs.getSource=="function"&&this.dashjs.getSource(),E={player_is_paused:r.paused,player_width:parseInt(l(r,"width")),player_height:parseInt(l(r,"height")),player_autoplay_on:r.autoplay,player_preload_on:r.preload,player_language_code:r.lang,player_is_fullscreen:_L(),video_poster_url:r.poster,video_source_url:v||b||r.currentSrc,video_source_duration:d(r.duration),video_source_height:r.videoHeight,video_source_width:r.videoWidth,view_dropped_frame_count:r==null||(p=r.getVideoPlaybackQuality)===null||p===void 0?void 0:p.call(r).droppedVideoFrames};if(r.getStartDate&&g>0){var T=r.getStartDate();if(T&&typeof T.getTime=="function"&&T.getTime()){var A=T.getTime();if(E.player_program_time=A+g,r.seekable.length>0){var x=A+r.seekable.end(r.seekable.length-1);E.player_live_edge_program_time=x}}}return E}};t=Object.assign(u,t,c),t.data=Object.assign({player_software:"HTML5 Video Element",player_mux_plugin_name:"VideoElementMonitor",player_mux_plugin_version:i.VERSION},t.data),r.mux=r.mux||{},r.mux.deleted=!1,r.mux.emit=function(f,m){i.emit(n,f,m)},r.mux.updateData=function(f){r.mux.emit("hb",f)};var h=function(){o.error("The monitor for this video element has already been destroyed.")};r.mux.destroy=function(){Object.keys(r.mux.listeners).forEach(function(f){r.removeEventListener(f,r.mux.listeners[f],!1)}),delete r.mux.listeners,r.mux.destroy=h,r.mux.swapElement=h,r.mux.emit=h,r.mux.addHLSJS=h,r.mux.addDashJS=h,r.mux.removeHLSJS=h,r.mux.removeDashJS=h,r.mux.updateData=h,r.mux.setEmitTranslator=h,r.mux.setStateDataTranslator=h,r.mux.setGetPlayheadTime=h,r.mux.deleted=!0,i.emit(n,"destroy")},r.mux.swapElement=function(f){var m=bs(Vd(f),3),p=m[0],g=m[1],v=m[2];if(p){if(v!=="video"&&v!=="audio")return i.log.error("The element of `"+g+"` was not a media element.")}else return i.log.error("No element was found with the `"+g+"` query selector.");p.muxId=r.muxId,delete r.muxId,p.mux=p.mux||{},p.mux.listeners=Object.assign({},r.mux.listeners),delete r.mux.listeners,Object.keys(p.mux.listeners).forEach(function(b){r.removeEventListener(b,p.mux.listeners[b],!1),p.addEventListener(b,p.mux.listeners[b],!1)}),p.mux.swapElement=r.mux.swapElement,p.mux.destroy=r.mux.destroy,delete r.mux,r=p},r.mux.addHLSJS=function(f){i.addHLSJS(n,f)},r.mux.addDashJS=function(f){i.addDashJS(n,f)},r.mux.removeHLSJS=function(){i.removeHLSJS(n)},r.mux.removeDashJS=function(){i.removeDashJS(n)},r.mux.setEmitTranslator=function(f){i.setEmitTranslator(n,f)},r.mux.setStateDataTranslator=function(f){i.setStateDataTranslator(n,f)},r.mux.setGetPlayheadTime=function(f){f||(f=t.getPlayheadTime),i.setGetPlayheadTime(n,f)},i.init(n,t),i.emit(n,"playerready"),r.paused||(i.emit(n,"play"),r.readyState>2&&i.emit(n,"playing")),r.mux.listeners={},AL.forEach(function(f){f==="error"&&!t.automaticErrorTracking||(r.mux.listeners[f]=function(){var m={};if(f==="error"){if(!r.error||r.error.code===1)return;m.player_error_code=r.error.code,m.player_error_message=SL[r.error.code]||r.error.message}i.emit(n,f,m)},r.addEventListener(f,r.mux.listeners[f],!1))})}function xL(i,e,t,s){var r=s;if(i&&typeof i[e]=="function")try{r=i[e].apply(i,t)}catch(n){Ne.info("safeCall error",n)}return r}var ja=Jt(Ii()),pn;ja.default&&ja.default.WeakMap&&(pn=new WeakMap);function LL(i,e){if(!i||!e||!ja.default||typeof ja.default.getComputedStyle!="function")return"";var t;return pn&&pn.has(i)&&(t=pn.get(i)),t||(t=ja.default.getComputedStyle(i,null),pn&&pn.set(i,t)),t.getPropertyValue(e)}function RL(i){return Math.floor(i*1e3)}var tr={TARGET_DURATION:"#EXT-X-TARGETDURATION",PART_INF:"#EXT-X-PART-INF",SERVER_CONTROL:"#EXT-X-SERVER-CONTROL",INF:"#EXTINF",PROGRAM_DATE_TIME:"#EXT-X-PROGRAM-DATE-TIME",VERSION:"#EXT-X-VERSION",SESSION_DATA:"#EXT-X-SESSION-DATA"},Wu=function(i){return this.buffer="",this.manifest={segments:[],serverControl:{},sessionData:{}},this.currentUri={},this.process(i),this.manifest};Wu.prototype.process=function(i){var e;for(this.buffer+=i,e=this.buffer.indexOf(`
|
|
1416
1416
|
`);e>-1;e=this.buffer.indexOf(`
|
|
1417
|
-
`))this.processLine(this.buffer.substring(0,e)),this.buffer=this.buffer.substring(e+1)};Wu.prototype.processLine=function(i){var e=i.indexOf(":"),t=wL(i,e),s=t[0],r=t.length===2?Rm(t[1]):void 0;if(s[0]!=="#")this.currentUri.uri=s,this.manifest.segments.push(this.currentUri),this.manifest.targetDuration&&!("duration"in this.currentUri)&&(this.currentUri.duration=this.manifest.targetDuration),this.currentUri={};else switch(s){case tr.TARGET_DURATION:{if(!isFinite(r)||r<0)return;this.manifest.targetDuration=r,this.setHoldBack();break}case tr.PART_INF:{vc(this.manifest,t),this.manifest.partInf.partTarget&&(this.manifest.partTargetDuration=this.manifest.partInf.partTarget),this.setHoldBack();break}case tr.SERVER_CONTROL:{vc(this.manifest,t),this.setHoldBack();break}case tr.INF:{r===0?this.currentUri.duration=.01:r>0&&(this.currentUri.duration=r);break}case tr.PROGRAM_DATE_TIME:{var n=r,a=new Date(n);this.manifest.dateTimeString||(this.manifest.dateTimeString=n,this.manifest.dateTimeObject=a),this.currentUri.dateTimeString=n,this.currentUri.dateTimeObject=a;break}case tr.VERSION:{vc(this.manifest,t);break}case tr.SESSION_DATA:{var o=ML(t[1]),l=my(o);Object.assign(this.manifest.sessionData,l)}}};Wu.prototype.setHoldBack=function(){var i=this.manifest,e=i.serverControl,t=i.targetDuration,s=i.partTargetDuration;if(e){var r="holdBack",n="partHoldBack",a=t&&t*3,o=s&&s*2;t&&!e.hasOwnProperty(r)&&(e[r]=a),a&&e[r]<a&&(e[r]=a),s&&!e.hasOwnProperty(n)&&(e[n]=s*3),s&&e[n]<o&&(e[n]=o)}};var vc=function(i,e){var t=Ay(e[0].replace("#EXT-X-","")),s;CL(e[1])?(s={},s=Object.assign(DL(e[1]),s)):s=Rm(e[1]),i[t]=s},Ay=function(i){return i.toLowerCase().replace(/-(\w)/g,function(e){return e[1].toUpperCase()})},Rm=function(i){if(i.toLowerCase()==="yes"||i.toLowerCase()==="no")return i.toLowerCase()==="yes";var e=i.indexOf(":")!==-1?i:parseFloat(i);return isNaN(e)?i:e},kL=function(i){var e={},t=i.split("=");if(t.length>1){var s=Ay(t[0]);e[s]=Rm(t[1])}return e},DL=function(i){for(var e=i.split(","),t={},s=0;e.length>s;s++){var r=e[s],n=kL(r);t=Object.assign(n,t)}return t},CL=function(i){return i.indexOf("=")>-1},wL=function(i,e){return e===-1?[i]:[i.substring(0,e),i.substring(e+1)]},ML=function(i){var e={};if(i){var t=i.search(","),s=i.slice(0,t),r=i.slice(t+1),n=[s,r];return n.forEach(function(a,o){for(var l=a.replace(/['"]+/g,"").split("="),d=0;d<l.length;d++)l[d]==="DATA-ID"&&(e["DATA-ID"]=l[1-d]),l[d]==="VALUE"&&(e.VALUE=l[1-d])}),{data:e}}},PL=Wu,OL={safeCall:xL,safeIncrement:ot,getComputedStyle:LL,secondsToMs:RL,assign:Object.assign,headersStringToObject:Lm,cdnHeadersToRequestId:Yd,extractHostnameAndDomain:fo,extractHostname:_i,manifestParser:PL,generateShortID:hy,generateUUID:ho,now:dt.now,findMediaElement:Vd},NL=OL,UL={PLAYER_READY:"playerready",VIEW_INIT:"viewinit",VIDEO_CHANGE:"videochange",PLAY:"play",PAUSE:"pause",PLAYING:"playing",TIME_UPDATE:"timeupdate",SEEKING:"seeking",SEEKED:"seeked",REBUFFER_START:"rebufferstart",REBUFFER_END:"rebufferend",ERROR:"error",ENDED:"ended",RENDITION_CHANGE:"renditionchange",ORIENTATION_CHANGE:"orientationchange",AD_REQUEST:"adrequest",AD_RESPONSE:"adresponse",AD_BREAK_START:"adbreakstart",AD_PLAY:"adplay",AD_PLAYING:"adplaying",AD_PAUSE:"adpause",AD_FIRST_QUARTILE:"adfirstquartile",AD_MID_POINT:"admidpoint",AD_THIRD_QUARTILE:"adthirdquartile",AD_ENDED:"adended",AD_BREAK_END:"adbreakend",AD_ERROR:"aderror",REQUEST_COMPLETED:"requestcompleted",REQUEST_FAILED:"requestfailed",REQUEST_CANCELLED:"requestcanceled",HEARTBEAT:"hb",DESTROY:"destroy"},$L=UL,FL="mux-embed",BL="5.9.0",HL="2.1",st={},Ys=function(i){var e=arguments;typeof i=="string"?Ys.hasOwnProperty(i)?Ya.default.setTimeout(function(){e=Array.prototype.splice.call(e,1),Ys[i].apply(null,e)},0):Ne.warn("`"+i+"` is an unknown task"):typeof i=="function"?Ya.default.setTimeout(function(){i(Ys)},0):Ne.warn("`"+i+"` is invalid.")},GL={loaded:dt.now(),NAME:FL,VERSION:BL,API_VERSION:HL,PLAYER_TRACKED:!1,monitor:function(i,e){return IL(Ys,i,e)},destroyMonitor:function(i){var e=bs(Vd(i),1),t=e[0];t&&t.mux&&typeof t.mux.destroy=="function"?t.mux.destroy():Ne.error("A video element monitor for `"+i+"` has not been initialized via `mux.monitor`.")},addHLSJS:function(i,e){var t=pi(i);st[t]?st[t].addHLSJS(e):Ne.error("A monitor for `"+t+"` has not been initialized.")},addDashJS:function(i,e){var t=pi(i);st[t]?st[t].addDashJS(e):Ne.error("A monitor for `"+t+"` has not been initialized.")},removeHLSJS:function(i){var e=pi(i);st[e]?st[e].removeHLSJS():Ne.error("A monitor for `"+e+"` has not been initialized.")},removeDashJS:function(i){var e=pi(i);st[e]?st[e].removeDashJS():Ne.error("A monitor for `"+e+"` has not been initialized.")},init:function(i,e){Mh()&&e&&e.respectDoNotTrack&&Ne.info("The browser's Do Not Track flag is enabled - Mux beaconing is disabled.");var t=pi(i);st[t]=new TL(Ys,t,e)},emit:function(i,e,t){var s=pi(i);st[s]?(st[s].emit(e,t),e==="destroy"&&delete st[s]):Ne.error("A monitor for `"+s+"` has not been initialized.")},updateData:function(i,e){var t=pi(i);st[t]?st[t].emit("hb",e):Ne.error("A monitor for `"+t+"` has not been initialized.")},setEmitTranslator:function(i,e){var t=pi(i);st[t]?st[t].emitTranslator=e:Ne.error("A monitor for `"+t+"` has not been initialized.")},setStateDataTranslator:function(i,e){var t=pi(i);st[t]?st[t].stateDataTranslator=e:Ne.error("A monitor for `"+t+"` has not been initialized.")},setGetPlayheadTime:function(i,e){var t=pi(i);st[t]?st[t].getPlayheadTime=e:Ne.error("A monitor for `"+t+"` has not been initialized.")},checkDoNotTrack:Mh,log:Ne,utils:NL,events:$L,WINDOW_HIDDEN:!1,WINDOW_UNLOADING:!1};Object.assign(Ys,GL);typeof Ya.default<"u"&&typeof Ya.default.addEventListener=="function"&&Ya.default.addEventListener("pagehide",function(i){i.persisted||(Ys.WINDOW_UNLOADING=!0)},!1);var km=Ys;const Q=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},KL=Number.isSafeInteger||function(i){return typeof i=="number"&&Math.abs(i)<=VL},VL=Number.MAX_SAFE_INTEGER||9007199254740991;let ie=(function(i){return i.NETWORK_ERROR="networkError",i.MEDIA_ERROR="mediaError",i.KEY_SYSTEM_ERROR="keySystemError",i.MUX_ERROR="muxError",i.OTHER_ERROR="otherError",i})({}),w=(function(i){return i.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",i.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",i.KEY_SYSTEM_NO_SESSION="keySystemNoSession",i.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",i.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",i.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",i.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",i.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",i.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",i.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",i.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",i.MANIFEST_LOAD_ERROR="manifestLoadError",i.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",i.MANIFEST_PARSING_ERROR="manifestParsingError",i.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",i.LEVEL_EMPTY_ERROR="levelEmptyError",i.LEVEL_LOAD_ERROR="levelLoadError",i.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",i.LEVEL_PARSING_ERROR="levelParsingError",i.LEVEL_SWITCH_ERROR="levelSwitchError",i.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",i.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",i.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",i.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",i.FRAG_LOAD_ERROR="fragLoadError",i.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",i.FRAG_DECRYPT_ERROR="fragDecryptError",i.FRAG_PARSING_ERROR="fragParsingError",i.FRAG_GAP="fragGap",i.REMUX_ALLOC_ERROR="remuxAllocError",i.KEY_LOAD_ERROR="keyLoadError",i.KEY_LOAD_TIMEOUT="keyLoadTimeOut",i.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",i.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",i.BUFFER_APPEND_ERROR="bufferAppendError",i.BUFFER_APPENDING_ERROR="bufferAppendingError",i.BUFFER_STALLED_ERROR="bufferStalledError",i.BUFFER_FULL_ERROR="bufferFullError",i.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",i.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",i.ASSET_LIST_LOAD_ERROR="assetListLoadError",i.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",i.ASSET_LIST_PARSING_ERROR="assetListParsingError",i.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",i.INTERNAL_EXCEPTION="internalException",i.INTERNAL_ABORTED="aborted",i.ATTACH_MEDIA_ERROR="attachMediaError",i.UNKNOWN="unknown",i})({}),y=(function(i){return i.MEDIA_ATTACHING="hlsMediaAttaching",i.MEDIA_ATTACHED="hlsMediaAttached",i.MEDIA_DETACHING="hlsMediaDetaching",i.MEDIA_DETACHED="hlsMediaDetached",i.MEDIA_ENDED="hlsMediaEnded",i.STALL_RESOLVED="hlsStallResolved",i.BUFFER_RESET="hlsBufferReset",i.BUFFER_CODECS="hlsBufferCodecs",i.BUFFER_CREATED="hlsBufferCreated",i.BUFFER_APPENDING="hlsBufferAppending",i.BUFFER_APPENDED="hlsBufferAppended",i.BUFFER_EOS="hlsBufferEos",i.BUFFERED_TO_END="hlsBufferedToEnd",i.BUFFER_FLUSHING="hlsBufferFlushing",i.BUFFER_FLUSHED="hlsBufferFlushed",i.MANIFEST_LOADING="hlsManifestLoading",i.MANIFEST_LOADED="hlsManifestLoaded",i.MANIFEST_PARSED="hlsManifestParsed",i.LEVEL_SWITCHING="hlsLevelSwitching",i.LEVEL_SWITCHED="hlsLevelSwitched",i.LEVEL_LOADING="hlsLevelLoading",i.LEVEL_LOADED="hlsLevelLoaded",i.LEVEL_UPDATED="hlsLevelUpdated",i.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",i.LEVELS_UPDATED="hlsLevelsUpdated",i.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",i.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",i.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",i.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",i.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",i.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",i.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",i.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",i.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",i.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",i.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",i.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",i.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",i.CUES_PARSED="hlsCuesParsed",i.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",i.INIT_PTS_FOUND="hlsInitPtsFound",i.FRAG_LOADING="hlsFragLoading",i.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",i.FRAG_LOADED="hlsFragLoaded",i.FRAG_DECRYPTED="hlsFragDecrypted",i.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",i.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",i.FRAG_PARSING_METADATA="hlsFragParsingMetadata",i.FRAG_PARSED="hlsFragParsed",i.FRAG_BUFFERED="hlsFragBuffered",i.FRAG_CHANGED="hlsFragChanged",i.FPS_DROP="hlsFpsDrop",i.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",i.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",i.ERROR="hlsError",i.DESTROYING="hlsDestroying",i.KEY_LOADING="hlsKeyLoading",i.KEY_LOADED="hlsKeyLoaded",i.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",i.BACK_BUFFER_REACHED="hlsBackBufferReached",i.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",i.ASSET_LIST_LOADING="hlsAssetListLoading",i.ASSET_LIST_LOADED="hlsAssetListLoaded",i.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",i.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",i.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",i.INTERSTITIAL_STARTED="hlsInterstitialStarted",i.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",i.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",i.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",i.INTERSTITIAL_ENDED="hlsInterstitialEnded",i.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",i.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",i.EVENT_CUE_ENTER="hlsEventCueEnter",i})({});var pe={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},J={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class qr{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 WL{constructor(e,t,s,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new qr(e),this.fast_=new qr(t),this.defaultTTFB_=r,this.ttfb_=new qr(e)}update(e,t){const{slow_:s,fast_:r,ttfb_:n}=this;s.halfLife!==e&&(this.slow_=new qr(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.fast_=new qr(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new qr(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,r=e/1e3,n=s/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function qL(i,e,t){return(e=jL(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function Oe(){return Oe=Object.assign?Object.assign.bind():function(i){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(i[s]=t[s])}return i},Oe.apply(null,arguments)}function Ig(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(i);e&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(i,r).enumerable})),t.push.apply(t,s)}return t}function Ce(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Ig(Object(t),!0).forEach(function(s){qL(i,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):Ig(Object(t)).forEach(function(s){Object.defineProperty(i,s,Object.getOwnPropertyDescriptor(t,s))})}return i}function YL(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var s=t.call(i,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function jL(i){var e=YL(i,"string");return typeof e=="symbol"?e:e+""}class di{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=Fs,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 Fs=function(){},zL={trace:Fs,debug:Fs,log:Fs,warn:Fs,info:Fs,error:Fs};function Nh(){return Oe({},zL)}function QL(i,e){const t=self.console[i];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${i}] >`):Fs}function xg(i,e,t){return e[i]?e[i].bind(e):QL(i,t)}const Uh=Nh();function XL(i,e,t){const s=Nh();if(typeof console=="object"&&i===!0||typeof i=="object"){const r=["debug","log","info","warn","error"];r.forEach(n=>{s[n]=xg(n,i,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return Nh()}r.forEach(n=>{Uh[n]=xg(n,i)})}else Oe(Uh,s);return s}const we=Uh;function zs(i=!0){return typeof self>"u"?void 0:(i||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ZL(i){return typeof self<"u"&&i===self.ManagedMediaSource}function Sy(i,e){const t=Object.keys(i),s=Object.keys(e),r=t.length,n=s.length;return!r||!n||r===n&&!t.some(a=>s.indexOf(a)===-1)}function Xt(i,e=!1){if(typeof TextDecoder<"u"){const d=new TextDecoder("utf-8").decode(i);if(e){const u=d.indexOf("\0");return u!==-1?d.substring(0,u):d}return d.replace(/\0/g,"")}const t=i.length;let s,r,n,a="",o=0;for(;o<t;){if(s=i[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:r=i[o++],a+=String.fromCharCode((s&31)<<6|r&63);break;case 14:r=i[o++],n=i[o++],a+=String.fromCharCode((s&15)<<12|(r&63)<<6|(n&63)<<0);break}}return a}function It(i){let e="";for(let t=0;t<i.length;t++){let s=i[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function Iy(i){return Uint8Array.from(i.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function JL(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Ec={exports:{}},Lg;function eR(){return Lg||(Lg=1,(function(i,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,d,u){if(u=u||{},l=l.trim(),d=d.trim(),!d){if(!u.alwaysNormalize)return l;var c=o.parseURL(l);if(!c)throw new Error("Error trying to parse base URL.");return c.path=o.normalizePath(c.path),o.buildURLFromParts(c)}var h=o.parseURL(d);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return u.alwaysNormalize?(h.path=o.normalizePath(h.path),o.buildURLFromParts(h)):d;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var m=r.exec(f.path);f.netLoc=m[1],f.path=m[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(p.netLoc=f.netLoc,h.path[0]!=="/"))if(!h.path)p.path=f.path,h.params||(p.params=f.params,h.query||(p.query=f.query));else{var g=f.path,v=g.substring(0,g.lastIndexOf("/")+1)+h.path;p.path=o.normalizePath(v)}return p.path===null&&(p.path=u.alwaysNormalize?o.normalizePath(h.path):h.path),o.buildURLFromParts(p)},parseURL:function(l){var d=s.exec(l);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};i.exports=o})()})(Ec)),Ec.exports}var Dm=eR();class Cm{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 Ue={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class xy{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,iR(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let r;s.length===1?r=t?.byteRangeEndOffset||0:r=parseInt(s[1]),this._byteRange=[r,parseInt(s[0])+r]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[Ue.AUDIO]:null,[Ue.VIDEO]:null,[Ue.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 Cm),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Dm.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Ue.AUDIO]=null,e[Ue.VIDEO]=null,e[Ue.AUDIOVIDEO]=null}}function et(i){return i.sn!=="initSegment"}class yc extends xy{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(Q(e)&&Q(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const s=Object.keys(t);if(s.length===1){const r=this._decryptdata=t[s[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=Q(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),r=s.length;if(r>1||r===1&&(t=this.levelkeys[s[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!Q(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return et(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const r=t[e];r&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,r,n,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:s,startDTS:r,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,s),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,n)}}let tR=class extends xy{constructor(e,t,s,r,n){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}};function Ly(i,e){const t=Object.getPrototypeOf(i);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||Ly(t,e)}}function iR(i,e){const t=Ly(i,e);t&&(t.enumerable=!0,Object.defineProperty(i,e,t))}const Rg=Math.pow(2,32)-1,sR=[].push,Ry={video:1,audio:2,id3:3,text:4};function mt(i){return String.fromCharCode.apply(null,i)}function ky(i,e){const t=i[e]<<8|i[e+1];return t<0?65536+t:t}function de(i,e){const t=Dy(i,e);return t<0?4294967296+t:t}function kg(i,e){let t=de(i,e);return t*=Math.pow(2,32),t+=de(i,e+4),t}function Dy(i,e){return i[e]<<24|i[e+1]<<16|i[e+2]<<8|i[e+3]}function rR(i){const e=i.byteLength;for(let t=0;t<e;){const s=de(i,t);if(s>8&&i[t+4]===109&&i[t+5]===111&&i[t+6]===111&&i[t+7]===102)return!0;t=s>1?t+s:e}return!1}function fe(i,e){const t=[];if(!e.length)return t;const s=i.byteLength;for(let r=0;r<s;){const n=de(i,r),a=mt(i.subarray(r+4,r+8)),o=n>1?r+n:s;if(a===e[0])if(e.length===1)t.push(i.subarray(r+8,o));else{const l=fe(i.subarray(r+8,o),e.slice(1));l.length&&sR.apply(t,l)}r=o}return t}function nR(i){const e=[],t=i[0];let s=8;const r=de(i,s);s+=4;let n=0,a=0;t===0?(n=de(i,s),a=de(i,s+4),s+=8):(n=kg(i,s),a=kg(i,s+8),s+=16),s+=2;let o=i.length+a;const l=ky(i,s);s+=2;for(let d=0;d<l;d++){let u=s;const c=de(i,u);u+=4;const h=c&2147483647;if((c&2147483648)>>>31===1)return we.warn("SIDX has hierarchical references (not supported)"),null;const m=de(i,u);u+=4,e.push({referenceSize:h,subsegmentDuration:m,info:{duration:m/r,start:o,end:o+h-1}}),o+=h,u+=4,s=u}return{earliestPresentationTime:n,timescale:r,version:t,referencesCount:l,references:e}}function Cy(i){const e=[],t=fe(i,["moov","trak"]);for(let r=0;r<t.length;r++){const n=t[r],a=fe(n,["tkhd"])[0];if(a){let o=a[0];const l=de(a,o===0?12:20),d=fe(n,["mdia","mdhd"])[0];if(d){o=d[0];const u=de(d,o===0?12:20),c=fe(n,["mdia","hdlr"])[0];if(c){const h=mt(c.subarray(8,12)),f={soun:Ue.AUDIO,vide:Ue.VIDEO}[h],m=fe(n,["mdia","minf","stbl","stsd"])[0],p=aR(m);f?(e[l]={timescale:u,type:f,stsd:p},e[f]=Ce({timescale:u,id:l},p)):e[l]={timescale:u,type:h,stsd:p}}}}}return fe(i,["moov","mvex","trex"]).forEach(r=>{const n=de(r,4),a=e[n];a&&(a.default={duration:de(r,12),flags:de(r,20)})}),e}function aR(i){const e=i.subarray(8),t=e.subarray(86),s=mt(e.subarray(4,8));let r=s,n;const a=s==="enca"||s==="encv";if(a){const d=fe(e,[s])[0].subarray(s==="enca"?28:78);fe(d,["sinf"]).forEach(c=>{const h=fe(c,["schm"])[0];if(h){const f=mt(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){const m=fe(c,["frma"])[0];m&&(r=mt(m))}}})}const o=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const l=fe(t,["avcC"])[0];l&&l.length>3&&(r+="."+Yo(l[1])+Yo(l[2])+Yo(l[3]),n=qo(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const l=fe(e,[s])[0],d=fe(l.subarray(28),["esds"])[0];if(d&&d.length>7){let u=4;if(d[u++]!==3)break;u=bc(d,u),u+=2;const c=d[u++];if(c&128&&(u+=2),c&64&&(u+=d[u++]),d[u++]!==4)break;u=bc(d,u);const h=d[u++];if(h===64)r+="."+Yo(h);else break;if(u+=12,d[u++]!==5)break;u=bc(d,u);const f=d[u++];let m=(f&248)>>3;m===31&&(m+=1+((f&7)<<3)+((d[u]&224)>>5)),r+="."+m}break}case"hvc1":case"hev1":{const l=fe(t,["hvcC"])[0];if(l&&l.length>12){const d=l[1],u=["","A","B","C"][d>>6],c=d&31,h=de(l,2),f=(d&32)>>5?"H":"L",m=l[12],p=l.subarray(6,12);r+="."+u+c,r+="."+oR(h).toString(16).toUpperCase(),r+="."+f+m;let g="";for(let v=p.length;v--;){const b=p[v];(b||g)&&(g="."+b.toString(16).toUpperCase()+g)}r+=g}n=qo(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{r=qo(r,t)||r;break}case"vp09":{const l=fe(t,["vpcC"])[0];if(l&&l.length>6){const d=l[4],u=l[5],c=l[6]>>4&15;r+="."+Vi(d)+"."+Vi(u)+"."+Vi(c)}break}case"av01":{const l=fe(t,["av1C"])[0];if(l&&l.length>2){const d=l[1]>>>5,u=l[1]&31,c=l[2]>>>7?"H":"M",h=(l[2]&64)>>6,f=(l[2]&32)>>5,m=d===2&&h?f?12:10:h?10:8,p=(l[2]&16)>>4,g=(l[2]&8)>>3,v=(l[2]&4)>>2,b=l[2]&3;r+="."+d+"."+Vi(u)+c+"."+Vi(m)+"."+p+"."+g+v+b+"."+Vi(1)+"."+Vi(1)+"."+Vi(1)+"."+0,n=qo("dav1",t)}break}}return{codec:r,encrypted:a,supplemental:n}}function qo(i,e){const t=fe(e,["dvvC"]),s=t.length?t[0]:fe(e,["dvcC"])[0];if(s){const r=s[2]>>1&127,n=s[2]<<5&32|s[3]>>3&31;return i+"."+Vi(r)+"."+Vi(n)}}function oR(i){let e=0;for(let t=0;t<32;t++)e|=(i>>t&1)<<31-t;return e>>>0}function bc(i,e){const t=e+5;for(;i[e++]&128&&e<t;);return e}function Yo(i){return("0"+i.toString(16).toUpperCase()).slice(-2)}function Vi(i){return(i<10?"0":"")+i}function lR(i,e){if(!i||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&wy(i,(s,r)=>{const n=s.subarray(8,24);n.some(a=>a!==0)||(we.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${It(n)} -> ${It(t)}`),s.set(t,8))})}function dR(i){const e=[];return wy(i,t=>e.push(t.subarray(8,24))),e}function wy(i,e){fe(i,["moov","trak"]).forEach(s=>{const r=fe(s,["mdia","minf","stbl","stsd"])[0];if(!r)return;const n=r.subarray(8);let a=fe(n,["enca"]);const o=a.length>0;o||(a=fe(n,["encv"])),a.forEach(l=>{const d=o?l.subarray(28):l.subarray(78);fe(d,["sinf"]).forEach(c=>{const h=My(c);h&&e(h,o)})})})}function My(i){const e=fe(i,["schm"])[0];if(e){const t=mt(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=fe(i,["schi","tenc"])[0];if(s)return s}}}function uR(i,e,t){const s={},r=fe(i,["moof","traf"]);for(let n=0;n<r.length;n++){const a=r[n],o=fe(a,["tfhd"])[0],l=de(o,4),d=e[l];if(!d)continue;s[l]||(s[l]={start:NaN,duration:0,sampleCount:0,timescale:d.timescale,type:d.type});const u=s[l],c=fe(a,["tfdt"])[0];if(c){const E=c[0];let T=de(c,4);E===1&&(T===Rg?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(T*=Rg+1,T+=de(c,8))),Q(T)&&(!Q(u.start)||T<u.start)&&(u.start=T)}const h=d.default,f=de(o,0)|h?.flags;let m=h?.duration||0;f&8&&(f&2?m=de(o,12):m=de(o,8));const p=fe(a,["trun"]);let g=u.start||0,v=0,b=m;for(let E=0;E<p.length;E++){const T=p[E],A=de(T,4),x=u.sampleCount;u.sampleCount+=A;const S=T[3]&1,L=T[3]&4,R=T[2]&1,I=T[2]&2,M=T[2]&4,B=T[2]&8;let W=8,j=A;for(S&&(W+=4),L&&A&&(!(T[W+1]&1)&&u.keyFrameIndex===void 0&&(u.keyFrameIndex=x),W+=4,R?(b=de(T,W),W+=4):b=m,I&&(W+=4),B&&(W+=4),g+=b,v+=b,j--);j--;)R?(b=de(T,W),W+=4):b=m,I&&(W+=4),M&&(T[W+1]&1||u.keyFrameIndex===void 0&&(u.keyFrameIndex=u.sampleCount-(j+1),u.keyFrameStart=g),W+=4),B&&(W+=4),g+=b,v+=b;!v&&m&&(v+=m*A)}u.duration+=v}if(!Object.keys(s).some(n=>s[n].duration)){let n=1/0,a=0;const o=fe(i,["sidx"]);for(let l=0;l<o.length;l++){const d=nR(o[l]);if(d!=null&&d.references){n=Math.min(n,d.earliestPresentationTime/d.timescale);const u=d.references.reduce((c,h)=>c+h.info.duration||0,0);a=Math.max(a,u+d.earliestPresentationTime/d.timescale)}}a&&Q(a)&&Object.keys(s).forEach(l=>{s[l].duration||(s[l].duration=a*s[l].timescale-s[l].start)})}return s}function cR(i){const e={valid:null,remainder:null},t=fe(i,["moof"]);if(t.length<2)return e.remainder=i,e;const s=t[t.length-1];return e.valid=i.slice(0,s.byteOffset-8),e.remainder=i.slice(s.byteOffset-8),e}function li(i,e){const t=new Uint8Array(i.length+e.length);return t.set(i),t.set(e,i.length),t}function Dg(i,e){const t=[],s=e.samples,r=e.timescale,n=e.id;let a=!1;return fe(s,["moof"]).map(l=>{const d=l.byteOffset-8;fe(l,["traf"]).map(c=>{const h=fe(c,["tfdt"]).map(f=>{const m=f[0];let p=de(f,4);return m===1&&(p*=Math.pow(2,32),p+=de(f,8)),p/r})[0];return h!==void 0&&(i=h),fe(c,["tfhd"]).map(f=>{const m=de(f,4),p=de(f,0)&16777215,g=(p&1)!==0,v=(p&2)!==0,b=(p&8)!==0;let E=0;const T=(p&16)!==0;let A=0;const x=(p&32)!==0;let S=8;m===n&&(g&&(S+=8),v&&(S+=4),b&&(E=de(f,S),S+=4),T&&(A=de(f,S),S+=4),x&&(S+=4),e.type==="video"&&(a=qu(e.codec)),fe(c,["trun"]).map(L=>{const R=L[0],I=de(L,0)&16777215,M=(I&1)!==0;let B=0;const W=(I&4)!==0,j=(I&256)!==0;let K=0;const F=(I&512)!==0;let Y=0;const P=(I&1024)!==0,G=(I&2048)!==0;let Z=0;const $=de(L,4);let H=8;M&&(B=de(L,H),H+=4),W&&(H+=4);let se=B+d;for(let ge=0;ge<$;ge++){if(j?(K=de(L,H),H+=4):K=E,F?(Y=de(L,H),H+=4):Y=A,P&&(H+=4),G&&(R===0?Z=de(L,H):Z=Dy(L,H),H+=4),e.type===Ue.VIDEO){let ce=0;for(;ce<Y;){const me=de(s,se);if(se+=4,hR(a,s[se])){const ut=s.subarray(se,se+me);wm(ut,a?2:1,i+Z/r,t)}se+=me,ce+=me+4}}i+=K/r}}))})})}),t}function qu(i){if(!i)return!1;const e=i.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function hR(i,e){if(i){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function wm(i,e,t,s){const r=Py(i);let n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(l===255);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(l===255);const d=r.length-n;let u=n;if(o<d)n+=o;else if(o>d){we.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(a===4){if(r[u++]===181){const h=ky(r,u);if(u+=2,h===49){const f=de(r,u);if(u+=4,f===1195456820){const m=r[u++];if(m===3){const p=r[u++],g=31&p,v=64&p,b=v?2+g*3:0,E=new Uint8Array(b);if(v){E[0]=p;for(let T=1;T<b;T++)E[T]=r[u++]}s.push({type:m,payloadType:a,pts:t,bytes:E})}}}}}else if(a===5&&o>16){const c=[];for(let m=0;m<16;m++){const p=r[u++].toString(16);c.push(p.length==1?"0"+p:p),(m===3||m===5||m===7||m===9)&&c.push("-")}const h=o-16,f=new Uint8Array(h);for(let m=0;m<h;m++)f[m]=r[u++];s.push({payloadType:a,pts:t,uuid:c.join(""),userData:Xt(f),userDataBytes:f})}}}function Py(i){const e=i.byteLength,t=[];let s=1;for(;s<e-2;)i[s]===0&&i[s+1]===0&&i[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return i;const r=e-t.length,n=new Uint8Array(r);let a=0;for(s=0;s<r;a++,s++)a===t[0]&&(a++,t.shift()),n[s]=i[a];return n}function fR(i){const e=i[0];let t="",s="",r=0,n=0,a=0,o=0,l=0,d=0;if(e===0){for(;mt(i.subarray(d,d+1))!=="\0";)t+=mt(i.subarray(d,d+1)),d+=1;for(t+=mt(i.subarray(d,d+1)),d+=1;mt(i.subarray(d,d+1))!=="\0";)s+=mt(i.subarray(d,d+1)),d+=1;s+=mt(i.subarray(d,d+1)),d+=1,r=de(i,12),n=de(i,16),o=de(i,20),l=de(i,24),d=28}else if(e===1){d+=4,r=de(i,d),d+=4;const c=de(i,d);d+=4;const h=de(i,d);for(d+=4,a=2**32*c+h,KL(a)||(a=Number.MAX_SAFE_INTEGER,we.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=de(i,d),d+=4,l=de(i,d),d+=4;mt(i.subarray(d,d+1))!=="\0";)t+=mt(i.subarray(d,d+1)),d+=1;for(t+=mt(i.subarray(d,d+1)),d+=1;mt(i.subarray(d,d+1))!=="\0";)s+=mt(i.subarray(d,d+1)),d+=1;s+=mt(i.subarray(d,d+1)),d+=1}const u=i.subarray(d,i.byteLength);return{schemeIdUri:t,value:s,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:u}}function mR(i,...e){const t=e.length;let s=8,r=t;for(;r--;)s+=e[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(i,4),r=0,s=8;r<t;r++)n.set(e[r],s),s+=e[r].byteLength;return n}function pR(i,e,t){if(i.byteLength!==16)throw new RangeError("Invalid system id");let s,r;s=0,r=new Uint8Array;let n;s>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),mR([112,115,115,104],new Uint8Array([s,0,0,0]),i,n,r,a,t)}function gR(i){const e=[];if(i instanceof ArrayBuffer){const t=i.byteLength;let s=0;for(;s+32<t;){const r=new DataView(i,s),n=vR(r);e.push(n),s+=n.size}}return e}function vR(i){const e=i.getUint32(0),t=i.byteOffset,s=i.byteLength;if(s<e)return{offset:t,size:s};if(i.getUint32(4)!==1886614376)return{offset:t,size:e};const n=i.getUint32(8)>>>24;if(n!==0&&n!==1)return{offset:t,size:e};const a=i.buffer,o=It(new Uint8Array(a,t+12,16));let l=null,d=null,u=0;if(n===0)u=28;else{const h=i.getUint32(28);if(!h||s<32+h*16)return{offset:t,size:e};l=[];for(let f=0;f<h;f++)l.push(new Uint8Array(a,t+32+f*16,16));u=32+h*16}if(!u)return{offset:t,size:e};const c=i.getUint32(u);return e-32<c?{offset:t,size:e}:(d=new Uint8Array(a,t+u+4,c),{version:n,systemId:o,kids:l,data:d,offset:t,size:e})}const Oy=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Xn={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 Mm(i,e){const t=Xn[e];return!!t&&!!t[i.slice(0,4)]}function mo(i,e,t=!0){return!i.split(",").some(s=>!Pm(s,e,t))}function Pm(i,e,t=!0){var s;const r=zs(t);return(s=r?.isTypeSupported(po(i,e)))!=null?s:!1}function po(i,e){return`${e}/mp4;codecs=${i}`}function Cg(i){if(i){const e=i.substring(0,4);return Xn.video[e]}return 2}function jd(i){const e=Oy();return i.split(",").reduce((t,s)=>{const n=e&&qu(s)?9:Xn.video[s];return n?(n*2+t)/(t?3:2):(Xn.audio[s]+t)/(t?2:1)},0)}const Tc={};function ER(i,e=!0){if(Tc[i])return Tc[i];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[i];for(let r=0;r<t.length;r++){var s;if(Pm(t[r],"audio",e))return Tc[i]=t[r],t[r];if(t[r]==="mp3"&&(s=zs(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return i}const yR=/flac|opus|mp4a\.40\.34/i;function zd(i,e=!0){return i.replace(yR,t=>ER(t.toLowerCase(),e))}function bR(i,e){const t=[];if(i){const s=i.split(",");for(let r=0;r<s.length;r++)Mm(s[r],"video")||t.push(s[r])}return e&&t.push(e),t.join(",")}function Hl(i,e){if(i&&(i.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(i)!==-1)&&(wg(i,"audio")||wg(i,"video")))return i;if(e){const t=e.split(",");if(t.length>1){if(i){for(let s=t.length;s--;)if(t[s].substring(0,4)===i.substring(0,4))return t[s]}return t[0]}}return e||i}function wg(i,e){return Mm(i,e)&&Pm(i,e)}function TR(i){const e=i.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function _R(i){if(i.startsWith("av01.")){const e=i.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 i}function Mg(i){const e=zs(i)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function $h(i){return i.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const AR={supported:!0,powerEfficient:!0,smooth:!0},SR={supported:!1,smooth:!1,powerEfficient:!1},Ny={supported:!0,configurations:[],decodingInfoResults:[AR]};function Uy(i,e){return{supported:!1,configurations:e,decodingInfoResults:[SR],error:i}}function IR(i,e,t,s,r,n){const a=i.videoCodec,o=i.audioCodec?i.audioGroups:null,l=n?.audioCodec,d=n?.channels,u=d?parseInt(d):l?1/0:2;let c=null;if(o!=null&&o.length)try{o.length===1&&o[0]?c=e.groups[o[0]].channels:c=o.reduce((h,f)=>{if(f){const m=e.groups[f];if(!m)throw new Error(`Audio track group ${f} not found`);Object.keys(m.channels).forEach(p=>{h[p]=(h[p]||0)+m.channels[p]})}return h},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(h=>qu(h))||i.width>1920&&i.height>1088||i.height>1920&&i.width>1088||i.frameRate>Math.max(s,30)||i.videoRange!=="SDR"&&i.videoRange!==t||i.bitrate>Math.max(r,8e6))||!!c&&Q(u)&&Object.keys(c).some(h=>parseInt(h)>u)}function $y(i,e,t,s={}){const r=i.videoCodec;if(!r&&!i.audioCodec||!t)return Promise.resolve(Ny);const n=[],a=xR(i),o=a.length,l=LR(i,e,o>0),d=l.length;for(let u=o||1*d||1;u--;){const c={type:"media-source"};if(o&&(c.video=a[u%o]),d){c.audio=l[u%d];const h=c.audio.bitrate;c.video&&h&&(c.video.bitrate-=h)}n.push(c)}if(r){const u=navigator.userAgent;if(r.split(",").some(c=>qu(c))&&Oy())return Promise.resolve(Uy(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),n))}return Promise.all(n.map(u=>{const c=kR(u);return s[c]||(s[c]=t.decodingInfo(u))})).then(u=>({supported:!u.some(c=>!c.supported),configurations:n,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:n,decodingInfoResults:[],error:u}))}function xR(i){var e;const t=(e=i.videoCodec)==null?void 0:e.split(","),s=Fy(i),r=i.width||640,n=i.height||480,a=i.frameRate||30,o=i.videoRange.toLowerCase();return t?t.map(l=>{const d={contentType:po(_R(l),"video"),width:r,height:n,bitrate:s,framerate:a};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function LR(i,e,t){var s;const r=(s=i.audioCodec)==null?void 0:s.split(","),n=Fy(i);return r&&i.audioGroups?i.audioGroups.reduce((a,o)=>{var l;const d=o?(l=e.groups[o])==null?void 0:l.tracks:null;return d?d.reduce((u,c)=>{if(c.groupId===o){const h=parseFloat(c.channels||"");r.forEach(f=>{const m={contentType:po(f,"audio"),bitrate:t?RR(f,n):n};h&&(m.channels=""+h),u.push(m)})}return u},a):a},[]):[]}function RR(i,e){if(e<=1)return 1;let t=128e3;return i==="ec-3"?t=768e3:i==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Fy(i){return Math.ceil(Math.max(i.bitrate*.9,i.averageBitrate)/1e3)*1e3||1}function kR(i){let e="";const{audio:t,video:s}=i;if(s){const r=$h(s.contentType);e+=`${r}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){const r=$h(t.contentType);e+=`${s?"_":""}${r}_c${t.channels}`}return e}const Fh=["NONE","TYPE-0","TYPE-1",null];function DR(i){return Fh.indexOf(i)>-1}const Qd=["SDR","PQ","HLG"];function CR(i){return!!i&&Qd.indexOf(i)>-1}var Gl={No:"",Yes:"YES",v2:"v2"};function Pg(i){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=i,r=s<e/2;return e&&r?t?Gl.v2:Gl.Yes:Gl.No}class Og{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 go{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 Ng(this._audioGroups,e)}hasSubtitleGroup(e){return Ng(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 Ng(i,e){return!e||!i?!1:i.indexOf(e)!==-1}function wR(){if(typeof matchMedia=="function"){const i=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(i.media!==e.media)return i.matches===!0}return!1}function MR(i,e){let t=!1,s=[];if(i&&(t=i!=="SDR",s=[i]),e){s=e.allowedVideoRanges||Qd.slice(0);const r=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:r&&wR(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const PR=i=>{const e=new WeakSet;return(t,s)=>{if(i&&(s=i(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},$e=(i,e)=>JSON.stringify(i,PR(e));function OR(i,e,t,s,r){const n=Object.keys(i),a=s?.channels,o=s?.audioCodec,l=r?.videoCodec,d=a&&parseInt(a)===2;let u=!1,c=!1,h=1/0,f=1/0,m=1/0,p=1/0,g=0,v=[];const{preferHDR:b,allowedVideoRanges:E}=MR(e,r);for(let L=n.length;L--;){const R=i[n[L]];u||(u=R.channels[2]>0),h=Math.min(h,R.minHeight),f=Math.min(f,R.minFramerate),m=Math.min(m,R.minBitrate),E.filter(M=>R.videoRanges[M]>0).length>0&&(c=!0)}h=Q(h)?h:0,f=Q(f)?f:0;const T=Math.max(1080,h),A=Math.max(30,f);m=Q(m)?m:t,t=Math.max(m,t),c||(e=void 0);const x=n.length>1;return{codecSet:n.reduce((L,R)=>{const I=i[R];if(R===L)return L;if(v=c?E.filter(M=>I.videoRanges[M]>0):[],x){if(I.minBitrate>t)return ki(R,`min bitrate of ${I.minBitrate} > current estimate of ${t}`),L;if(!I.hasDefaultAudio)return ki(R,"no renditions with default or auto-select sound found"),L;if(o&&R.indexOf(o.substring(0,4))%5!==0)return ki(R,`audio codec preference "${o}" not found`),L;if(a&&!d){if(!I.channels[a])return ki(R,`no renditions with ${a} channel sound found (channels options: ${Object.keys(I.channels)})`),L}else if((!o||d)&&u&&I.channels[2]===0)return ki(R,"no renditions with stereo sound found"),L;if(I.minHeight>T)return ki(R,`min resolution of ${I.minHeight} > maximum of ${T}`),L;if(I.minFramerate>A)return ki(R,`min framerate of ${I.minFramerate} > maximum of ${A}`),L;if(!v.some(M=>I.videoRanges[M]>0))return ki(R,`no variants with VIDEO-RANGE of ${$e(v)} found`),L;if(l&&R.indexOf(l.substring(0,4))%5!==0)return ki(R,`video codec preference "${l}" not found`),L;if(I.maxScore<g)return ki(R,`max score of ${I.maxScore} < selected max of ${g}`),L}return L&&(jd(R)>=jd(L)||I.fragmentError>i[L].fragmentError)?L:(p=I.minIndex,g=I.maxScore,R)},void 0),videoRanges:v,preferHDR:b,minFramerate:f,minBitrate:m,minIndex:p}}function ki(i,e){we.log(`[abr] start candidates with "${i}" ignored because ${e}`)}function By(i){return i.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 r=t.channels||"2";return s.channels[r]=(s.channels[r]||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 NR(i,e,t,s){return i.slice(t,s+1).reduce((r,n,a)=>{if(!n.codecSet)return r;const o=n.audioGroups;let l=r[n.codecSet];l||(r[n.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,n.bitrate);const d=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,d),l.minFramerate=Math.min(l.minFramerate,n.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,n.score),l.fragmentError+=n.fragmentError,l.videoRanges[n.videoRange]=(l.videoRanges[n.videoRange]||0)+1,o&&o.forEach(u=>{if(!u)return;const c=e.groups[u];c&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?c.hasDefault:c.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(c.channels).forEach(h=>{l.channels[h]=(l.channels[h]||0)+c.channels[h]}))}),r},{})}function Ug(i){if(!i)return i;const{lang:e,assocLang:t,characteristics:s,channels:r,audioCodec:n}=i;return{lang:e,assocLang:t,characteristics:s,channels:r,audioCodec:n}}function Qi(i,e,t){if("attrs"in i){const s=e.indexOf(i);if(s!==-1)return s}for(let s=0;s<e.length;s++){const r=e[s];if(Lr(i,r,t))return s}return-1}function Lr(i,e,t){const{groupId:s,name:r,lang:n,assocLang:a,default:o}=i,l=i.forced;return(s===void 0||e.groupId===s)&&(r===void 0||e.name===r)&&(n===void 0||UR(n,e.lang))&&(n===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in i)||$R(i.characteristics||"",e.characteristics))&&(t===void 0||t(i,e))}function UR(i,e="--"){return i.length===e.length?i===e:i.startsWith(e)||e.startsWith(i)}function $R(i,e=""){const t=i.split(","),s=e.split(",");return t.length===s.length&&!t.some(r=>s.indexOf(r)===-1)}function ur(i,e){const{audioCodec:t,channels:s}=i;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function FR(i,e,t,s,r){const n=e[s],o=e.reduce((h,f,m)=>{const p=f.uri;return(h[p]||(h[p]=[])).push(m),h},{})[n.uri];o.length>1&&(s=Math.max.apply(Math,o));const l=n.videoRange,d=n.frameRate,u=n.codecSet.substring(0,4),c=$g(e,s,h=>{if(h.videoRange!==l||h.frameRate!==d||h.codecSet.substring(0,4)!==u)return!1;const f=h.audioGroups,m=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return Qi(i,m,r)>-1});return c>-1?c:$g(e,s,h=>{const f=h.audioGroups,m=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return Qi(i,m,r)>-1})}function $g(i,e,t){for(let s=e;s>-1;s--)if(t(i[s]))return s;for(let s=e+1;s<i.length;s++)if(t(i[s]))return s;return-1}function Xd(i,e){var t;return!!i&&i!==((t=e.loadLevelObj)==null?void 0:t.uri)}class BR extends di{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:r,partCurrent:n,hls:a}=this,{autoLevelEnabled:o,media:l}=a;if(!r||!l)return;const d=performance.now(),u=n?n.stats:r.stats,c=n?n.duration:r.duration,h=d-u.loading.start,f=a.minAutoLevel,m=r.level,p=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||m<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const g=p>-1&&p!==m,v=!!t||g;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;const b=a.mainForwardBufferInfo;if(!v&&b===null)return;const E=this.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(h<=Math.max(E,1e3*(c/(T*2))))return;const A=b?b.len/T:0,x=u.loading.first?u.loading.first-u.loading.start:-1,S=u.loaded&&x>-1,L=this.getBwEstimate(),R=a.levels,I=R[m],M=Math.max(u.loaded,Math.round(c*(r.bitrate||I.averageBitrate)/8));let B=S?h-x:h;B<1&&S&&(B=Math.min(h,u.loaded*8/L));const W=S?u.loaded*1e3/B:0,j=E/1e3,K=W?(M-u.loaded)/W:M*8/L+j;if(K<=A)return;const F=W?W*8:L,Y=((s=t?.details||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,P=this.hls.config.abrBandWidthUpFactor;let G=Number.POSITIVE_INFINITY,Z;for(Z=m-1;Z>f;Z--){const ge=R[Z].maxBitrate,ce=!R[Z].details||Y;if(G=this.getTimeToLoadFrag(j,F,c*ge,ce),G<Math.min(A,c+j))break}if(G>=K||G>c*10)return;S?this.bwEstimator.sample(h-Math.min(E,x),u.loaded):this.bwEstimator.sampleTTFB(h);const $=R[Z].maxBitrate;this.getBwEstimate()*P>$&&this.resetEstimator($);const H=this.findBestLevel($,f,Z,0,A,1,1);H>-1&&(Z=H),this.warn(`Fragment ${r.sn}${n?" part "+n.index:""} of level ${m} is loading too slowly;
|
|
1417
|
+
`))this.processLine(this.buffer.substring(0,e)),this.buffer=this.buffer.substring(e+1)};Wu.prototype.processLine=function(i){var e=i.indexOf(":"),t=wL(i,e),s=t[0],r=t.length===2?Rm(t[1]):void 0;if(s[0]!=="#")this.currentUri.uri=s,this.manifest.segments.push(this.currentUri),this.manifest.targetDuration&&!("duration"in this.currentUri)&&(this.currentUri.duration=this.manifest.targetDuration),this.currentUri={};else switch(s){case tr.TARGET_DURATION:{if(!isFinite(r)||r<0)return;this.manifest.targetDuration=r,this.setHoldBack();break}case tr.PART_INF:{vc(this.manifest,t),this.manifest.partInf.partTarget&&(this.manifest.partTargetDuration=this.manifest.partInf.partTarget),this.setHoldBack();break}case tr.SERVER_CONTROL:{vc(this.manifest,t),this.setHoldBack();break}case tr.INF:{r===0?this.currentUri.duration=.01:r>0&&(this.currentUri.duration=r);break}case tr.PROGRAM_DATE_TIME:{var n=r,a=new Date(n);this.manifest.dateTimeString||(this.manifest.dateTimeString=n,this.manifest.dateTimeObject=a),this.currentUri.dateTimeString=n,this.currentUri.dateTimeObject=a;break}case tr.VERSION:{vc(this.manifest,t);break}case tr.SESSION_DATA:{var o=ML(t[1]),l=my(o);Object.assign(this.manifest.sessionData,l)}}};Wu.prototype.setHoldBack=function(){var i=this.manifest,e=i.serverControl,t=i.targetDuration,s=i.partTargetDuration;if(e){var r="holdBack",n="partHoldBack",a=t&&t*3,o=s&&s*2;t&&!e.hasOwnProperty(r)&&(e[r]=a),a&&e[r]<a&&(e[r]=a),s&&!e.hasOwnProperty(n)&&(e[n]=s*3),s&&e[n]<o&&(e[n]=o)}};var vc=function(i,e){var t=Ay(e[0].replace("#EXT-X-","")),s;CL(e[1])?(s={},s=Object.assign(DL(e[1]),s)):s=Rm(e[1]),i[t]=s},Ay=function(i){return i.toLowerCase().replace(/-(\w)/g,function(e){return e[1].toUpperCase()})},Rm=function(i){if(i.toLowerCase()==="yes"||i.toLowerCase()==="no")return i.toLowerCase()==="yes";var e=i.indexOf(":")!==-1?i:parseFloat(i);return isNaN(e)?i:e},kL=function(i){var e={},t=i.split("=");if(t.length>1){var s=Ay(t[0]);e[s]=Rm(t[1])}return e},DL=function(i){for(var e=i.split(","),t={},s=0;e.length>s;s++){var r=e[s],n=kL(r);t=Object.assign(n,t)}return t},CL=function(i){return i.indexOf("=")>-1},wL=function(i,e){return e===-1?[i]:[i.substring(0,e),i.substring(e+1)]},ML=function(i){var e={};if(i){var t=i.search(","),s=i.slice(0,t),r=i.slice(t+1),n=[s,r];return n.forEach(function(a,o){for(var l=a.replace(/['"]+/g,"").split("="),d=0;d<l.length;d++)l[d]==="DATA-ID"&&(e["DATA-ID"]=l[1-d]),l[d]==="VALUE"&&(e.VALUE=l[1-d])}),{data:e}}},PL=Wu,OL={safeCall:xL,safeIncrement:ot,getComputedStyle:LL,secondsToMs:RL,assign:Object.assign,headersStringToObject:Lm,cdnHeadersToRequestId:Yd,extractHostnameAndDomain:fo,extractHostname:_i,manifestParser:PL,generateShortID:hy,generateUUID:ho,now:dt.now,findMediaElement:Vd},NL=OL,UL={PLAYER_READY:"playerready",VIEW_INIT:"viewinit",VIDEO_CHANGE:"videochange",PLAY:"play",PAUSE:"pause",PLAYING:"playing",TIME_UPDATE:"timeupdate",SEEKING:"seeking",SEEKED:"seeked",REBUFFER_START:"rebufferstart",REBUFFER_END:"rebufferend",ERROR:"error",ENDED:"ended",RENDITION_CHANGE:"renditionchange",ORIENTATION_CHANGE:"orientationchange",AD_REQUEST:"adrequest",AD_RESPONSE:"adresponse",AD_BREAK_START:"adbreakstart",AD_PLAY:"adplay",AD_PLAYING:"adplaying",AD_PAUSE:"adpause",AD_FIRST_QUARTILE:"adfirstquartile",AD_MID_POINT:"admidpoint",AD_THIRD_QUARTILE:"adthirdquartile",AD_ENDED:"adended",AD_BREAK_END:"adbreakend",AD_ERROR:"aderror",REQUEST_COMPLETED:"requestcompleted",REQUEST_FAILED:"requestfailed",REQUEST_CANCELLED:"requestcanceled",HEARTBEAT:"hb",DESTROY:"destroy"},$L=UL,FL="mux-embed",BL="5.9.0",HL="2.1",st={},Ys=function(i){var e=arguments;typeof i=="string"?Ys.hasOwnProperty(i)?Ya.default.setTimeout(function(){e=Array.prototype.splice.call(e,1),Ys[i].apply(null,e)},0):Ne.warn("`"+i+"` is an unknown task"):typeof i=="function"?Ya.default.setTimeout(function(){i(Ys)},0):Ne.warn("`"+i+"` is invalid.")},GL={loaded:dt.now(),NAME:FL,VERSION:BL,API_VERSION:HL,PLAYER_TRACKED:!1,monitor:function(i,e){return IL(Ys,i,e)},destroyMonitor:function(i){var e=bs(Vd(i),1),t=e[0];t&&t.mux&&typeof t.mux.destroy=="function"?t.mux.destroy():Ne.error("A video element monitor for `"+i+"` has not been initialized via `mux.monitor`.")},addHLSJS:function(i,e){var t=pi(i);st[t]?st[t].addHLSJS(e):Ne.error("A monitor for `"+t+"` has not been initialized.")},addDashJS:function(i,e){var t=pi(i);st[t]?st[t].addDashJS(e):Ne.error("A monitor for `"+t+"` has not been initialized.")},removeHLSJS:function(i){var e=pi(i);st[e]?st[e].removeHLSJS():Ne.error("A monitor for `"+e+"` has not been initialized.")},removeDashJS:function(i){var e=pi(i);st[e]?st[e].removeDashJS():Ne.error("A monitor for `"+e+"` has not been initialized.")},init:function(i,e){Mh()&&e&&e.respectDoNotTrack&&Ne.info("The browser's Do Not Track flag is enabled - Mux beaconing is disabled.");var t=pi(i);st[t]=new TL(Ys,t,e)},emit:function(i,e,t){var s=pi(i);st[s]?(st[s].emit(e,t),e==="destroy"&&delete st[s]):Ne.error("A monitor for `"+s+"` has not been initialized.")},updateData:function(i,e){var t=pi(i);st[t]?st[t].emit("hb",e):Ne.error("A monitor for `"+t+"` has not been initialized.")},setEmitTranslator:function(i,e){var t=pi(i);st[t]?st[t].emitTranslator=e:Ne.error("A monitor for `"+t+"` has not been initialized.")},setStateDataTranslator:function(i,e){var t=pi(i);st[t]?st[t].stateDataTranslator=e:Ne.error("A monitor for `"+t+"` has not been initialized.")},setGetPlayheadTime:function(i,e){var t=pi(i);st[t]?st[t].getPlayheadTime=e:Ne.error("A monitor for `"+t+"` has not been initialized.")},checkDoNotTrack:Mh,log:Ne,utils:NL,events:$L,WINDOW_HIDDEN:!1,WINDOW_UNLOADING:!1};Object.assign(Ys,GL);typeof Ya.default<"u"&&typeof Ya.default.addEventListener=="function"&&Ya.default.addEventListener("pagehide",function(i){i.persisted||(Ys.WINDOW_UNLOADING=!0)},!1);var km=Ys;const X=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},KL=Number.isSafeInteger||function(i){return typeof i=="number"&&Math.abs(i)<=VL},VL=Number.MAX_SAFE_INTEGER||9007199254740991;let ie=(function(i){return i.NETWORK_ERROR="networkError",i.MEDIA_ERROR="mediaError",i.KEY_SYSTEM_ERROR="keySystemError",i.MUX_ERROR="muxError",i.OTHER_ERROR="otherError",i})({}),w=(function(i){return i.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",i.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",i.KEY_SYSTEM_NO_SESSION="keySystemNoSession",i.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",i.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",i.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",i.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",i.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",i.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",i.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",i.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",i.MANIFEST_LOAD_ERROR="manifestLoadError",i.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",i.MANIFEST_PARSING_ERROR="manifestParsingError",i.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",i.LEVEL_EMPTY_ERROR="levelEmptyError",i.LEVEL_LOAD_ERROR="levelLoadError",i.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",i.LEVEL_PARSING_ERROR="levelParsingError",i.LEVEL_SWITCH_ERROR="levelSwitchError",i.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",i.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",i.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",i.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",i.FRAG_LOAD_ERROR="fragLoadError",i.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",i.FRAG_DECRYPT_ERROR="fragDecryptError",i.FRAG_PARSING_ERROR="fragParsingError",i.FRAG_GAP="fragGap",i.REMUX_ALLOC_ERROR="remuxAllocError",i.KEY_LOAD_ERROR="keyLoadError",i.KEY_LOAD_TIMEOUT="keyLoadTimeOut",i.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",i.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",i.BUFFER_APPEND_ERROR="bufferAppendError",i.BUFFER_APPENDING_ERROR="bufferAppendingError",i.BUFFER_STALLED_ERROR="bufferStalledError",i.BUFFER_FULL_ERROR="bufferFullError",i.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",i.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",i.ASSET_LIST_LOAD_ERROR="assetListLoadError",i.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",i.ASSET_LIST_PARSING_ERROR="assetListParsingError",i.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",i.INTERNAL_EXCEPTION="internalException",i.INTERNAL_ABORTED="aborted",i.ATTACH_MEDIA_ERROR="attachMediaError",i.UNKNOWN="unknown",i})({}),y=(function(i){return i.MEDIA_ATTACHING="hlsMediaAttaching",i.MEDIA_ATTACHED="hlsMediaAttached",i.MEDIA_DETACHING="hlsMediaDetaching",i.MEDIA_DETACHED="hlsMediaDetached",i.MEDIA_ENDED="hlsMediaEnded",i.STALL_RESOLVED="hlsStallResolved",i.BUFFER_RESET="hlsBufferReset",i.BUFFER_CODECS="hlsBufferCodecs",i.BUFFER_CREATED="hlsBufferCreated",i.BUFFER_APPENDING="hlsBufferAppending",i.BUFFER_APPENDED="hlsBufferAppended",i.BUFFER_EOS="hlsBufferEos",i.BUFFERED_TO_END="hlsBufferedToEnd",i.BUFFER_FLUSHING="hlsBufferFlushing",i.BUFFER_FLUSHED="hlsBufferFlushed",i.MANIFEST_LOADING="hlsManifestLoading",i.MANIFEST_LOADED="hlsManifestLoaded",i.MANIFEST_PARSED="hlsManifestParsed",i.LEVEL_SWITCHING="hlsLevelSwitching",i.LEVEL_SWITCHED="hlsLevelSwitched",i.LEVEL_LOADING="hlsLevelLoading",i.LEVEL_LOADED="hlsLevelLoaded",i.LEVEL_UPDATED="hlsLevelUpdated",i.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",i.LEVELS_UPDATED="hlsLevelsUpdated",i.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",i.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",i.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",i.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",i.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",i.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",i.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",i.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",i.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",i.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",i.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",i.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",i.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",i.CUES_PARSED="hlsCuesParsed",i.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",i.INIT_PTS_FOUND="hlsInitPtsFound",i.FRAG_LOADING="hlsFragLoading",i.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",i.FRAG_LOADED="hlsFragLoaded",i.FRAG_DECRYPTED="hlsFragDecrypted",i.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",i.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",i.FRAG_PARSING_METADATA="hlsFragParsingMetadata",i.FRAG_PARSED="hlsFragParsed",i.FRAG_BUFFERED="hlsFragBuffered",i.FRAG_CHANGED="hlsFragChanged",i.FPS_DROP="hlsFpsDrop",i.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",i.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",i.ERROR="hlsError",i.DESTROYING="hlsDestroying",i.KEY_LOADING="hlsKeyLoading",i.KEY_LOADED="hlsKeyLoaded",i.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",i.BACK_BUFFER_REACHED="hlsBackBufferReached",i.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",i.ASSET_LIST_LOADING="hlsAssetListLoading",i.ASSET_LIST_LOADED="hlsAssetListLoaded",i.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",i.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",i.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",i.INTERSTITIAL_STARTED="hlsInterstitialStarted",i.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",i.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",i.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",i.INTERSTITIAL_ENDED="hlsInterstitialEnded",i.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",i.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",i.EVENT_CUE_ENTER="hlsEventCueEnter",i})({});var ge={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},J={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class qr{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 WL{constructor(e,t,s,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new qr(e),this.fast_=new qr(t),this.defaultTTFB_=r,this.ttfb_=new qr(e)}update(e,t){const{slow_:s,fast_:r,ttfb_:n}=this;s.halfLife!==e&&(this.slow_=new qr(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.fast_=new qr(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new qr(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,r=e/1e3,n=s/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function qL(i,e,t){return(e=jL(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function Oe(){return Oe=Object.assign?Object.assign.bind():function(i){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(i[s]=t[s])}return i},Oe.apply(null,arguments)}function Ig(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(i);e&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(i,r).enumerable})),t.push.apply(t,s)}return t}function Ce(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Ig(Object(t),!0).forEach(function(s){qL(i,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):Ig(Object(t)).forEach(function(s){Object.defineProperty(i,s,Object.getOwnPropertyDescriptor(t,s))})}return i}function YL(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var s=t.call(i,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function jL(i){var e=YL(i,"string");return typeof e=="symbol"?e:e+""}class di{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=Fs,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 Fs=function(){},zL={trace:Fs,debug:Fs,log:Fs,warn:Fs,info:Fs,error:Fs};function Nh(){return Oe({},zL)}function QL(i,e){const t=self.console[i];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${i}] >`):Fs}function xg(i,e,t){return e[i]?e[i].bind(e):QL(i,t)}const Uh=Nh();function XL(i,e,t){const s=Nh();if(typeof console=="object"&&i===!0||typeof i=="object"){const r=["debug","log","info","warn","error"];r.forEach(n=>{s[n]=xg(n,i,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return Nh()}r.forEach(n=>{Uh[n]=xg(n,i)})}else Oe(Uh,s);return s}const we=Uh;function zs(i=!0){return typeof self>"u"?void 0:(i||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ZL(i){return typeof self<"u"&&i===self.ManagedMediaSource}function Sy(i,e){const t=Object.keys(i),s=Object.keys(e),r=t.length,n=s.length;return!r||!n||r===n&&!t.some(a=>s.indexOf(a)===-1)}function Xt(i,e=!1){if(typeof TextDecoder<"u"){const d=new TextDecoder("utf-8").decode(i);if(e){const u=d.indexOf("\0");return u!==-1?d.substring(0,u):d}return d.replace(/\0/g,"")}const t=i.length;let s,r,n,a="",o=0;for(;o<t;){if(s=i[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:r=i[o++],a+=String.fromCharCode((s&31)<<6|r&63);break;case 14:r=i[o++],n=i[o++],a+=String.fromCharCode((s&15)<<12|(r&63)<<6|(n&63)<<0);break}}return a}function It(i){let e="";for(let t=0;t<i.length;t++){let s=i[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function Iy(i){return Uint8Array.from(i.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function JL(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Ec={exports:{}},Lg;function eR(){return Lg||(Lg=1,(function(i,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,d,u){if(u=u||{},l=l.trim(),d=d.trim(),!d){if(!u.alwaysNormalize)return l;var c=o.parseURL(l);if(!c)throw new Error("Error trying to parse base URL.");return c.path=o.normalizePath(c.path),o.buildURLFromParts(c)}var h=o.parseURL(d);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return u.alwaysNormalize?(h.path=o.normalizePath(h.path),o.buildURLFromParts(h)):d;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var m=r.exec(f.path);f.netLoc=m[1],f.path=m[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(p.netLoc=f.netLoc,h.path[0]!=="/"))if(!h.path)p.path=f.path,h.params||(p.params=f.params,h.query||(p.query=f.query));else{var g=f.path,v=g.substring(0,g.lastIndexOf("/")+1)+h.path;p.path=o.normalizePath(v)}return p.path===null&&(p.path=u.alwaysNormalize?o.normalizePath(h.path):h.path),o.buildURLFromParts(p)},parseURL:function(l){var d=s.exec(l);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};i.exports=o})()})(Ec)),Ec.exports}var Dm=eR();class Cm{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 Ue={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class xy{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,iR(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let r;s.length===1?r=t?.byteRangeEndOffset||0:r=parseInt(s[1]),this._byteRange=[r,parseInt(s[0])+r]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[Ue.AUDIO]:null,[Ue.VIDEO]:null,[Ue.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 Cm),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Dm.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Ue.AUDIO]=null,e[Ue.VIDEO]=null,e[Ue.AUDIOVIDEO]=null}}function et(i){return i.sn!=="initSegment"}class yc extends xy{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(X(e)&&X(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const s=Object.keys(t);if(s.length===1){const r=this._decryptdata=t[s[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=X(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),r=s.length;if(r>1||r===1&&(t=this.levelkeys[s[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!X(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return et(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const r=t[e];r&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,r,n,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:s,startDTS:r,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,s),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,n)}}let tR=class extends xy{constructor(e,t,s,r,n){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}};function Ly(i,e){const t=Object.getPrototypeOf(i);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||Ly(t,e)}}function iR(i,e){const t=Ly(i,e);t&&(t.enumerable=!0,Object.defineProperty(i,e,t))}const Rg=Math.pow(2,32)-1,sR=[].push,Ry={video:1,audio:2,id3:3,text:4};function mt(i){return String.fromCharCode.apply(null,i)}function ky(i,e){const t=i[e]<<8|i[e+1];return t<0?65536+t:t}function de(i,e){const t=Dy(i,e);return t<0?4294967296+t:t}function kg(i,e){let t=de(i,e);return t*=Math.pow(2,32),t+=de(i,e+4),t}function Dy(i,e){return i[e]<<24|i[e+1]<<16|i[e+2]<<8|i[e+3]}function rR(i){const e=i.byteLength;for(let t=0;t<e;){const s=de(i,t);if(s>8&&i[t+4]===109&&i[t+5]===111&&i[t+6]===111&&i[t+7]===102)return!0;t=s>1?t+s:e}return!1}function me(i,e){const t=[];if(!e.length)return t;const s=i.byteLength;for(let r=0;r<s;){const n=de(i,r),a=mt(i.subarray(r+4,r+8)),o=n>1?r+n:s;if(a===e[0])if(e.length===1)t.push(i.subarray(r+8,o));else{const l=me(i.subarray(r+8,o),e.slice(1));l.length&&sR.apply(t,l)}r=o}return t}function nR(i){const e=[],t=i[0];let s=8;const r=de(i,s);s+=4;let n=0,a=0;t===0?(n=de(i,s),a=de(i,s+4),s+=8):(n=kg(i,s),a=kg(i,s+8),s+=16),s+=2;let o=i.length+a;const l=ky(i,s);s+=2;for(let d=0;d<l;d++){let u=s;const c=de(i,u);u+=4;const h=c&2147483647;if((c&2147483648)>>>31===1)return we.warn("SIDX has hierarchical references (not supported)"),null;const m=de(i,u);u+=4,e.push({referenceSize:h,subsegmentDuration:m,info:{duration:m/r,start:o,end:o+h-1}}),o+=h,u+=4,s=u}return{earliestPresentationTime:n,timescale:r,version:t,referencesCount:l,references:e}}function Cy(i){const e=[],t=me(i,["moov","trak"]);for(let r=0;r<t.length;r++){const n=t[r],a=me(n,["tkhd"])[0];if(a){let o=a[0];const l=de(a,o===0?12:20),d=me(n,["mdia","mdhd"])[0];if(d){o=d[0];const u=de(d,o===0?12:20),c=me(n,["mdia","hdlr"])[0];if(c){const h=mt(c.subarray(8,12)),f={soun:Ue.AUDIO,vide:Ue.VIDEO}[h],m=me(n,["mdia","minf","stbl","stsd"])[0],p=aR(m);f?(e[l]={timescale:u,type:f,stsd:p},e[f]=Ce({timescale:u,id:l},p)):e[l]={timescale:u,type:h,stsd:p}}}}}return me(i,["moov","mvex","trex"]).forEach(r=>{const n=de(r,4),a=e[n];a&&(a.default={duration:de(r,12),flags:de(r,20)})}),e}function aR(i){const e=i.subarray(8),t=e.subarray(86),s=mt(e.subarray(4,8));let r=s,n;const a=s==="enca"||s==="encv";if(a){const d=me(e,[s])[0].subarray(s==="enca"?28:78);me(d,["sinf"]).forEach(c=>{const h=me(c,["schm"])[0];if(h){const f=mt(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){const m=me(c,["frma"])[0];m&&(r=mt(m))}}})}const o=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const l=me(t,["avcC"])[0];l&&l.length>3&&(r+="."+Yo(l[1])+Yo(l[2])+Yo(l[3]),n=qo(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const l=me(e,[s])[0],d=me(l.subarray(28),["esds"])[0];if(d&&d.length>7){let u=4;if(d[u++]!==3)break;u=bc(d,u),u+=2;const c=d[u++];if(c&128&&(u+=2),c&64&&(u+=d[u++]),d[u++]!==4)break;u=bc(d,u);const h=d[u++];if(h===64)r+="."+Yo(h);else break;if(u+=12,d[u++]!==5)break;u=bc(d,u);const f=d[u++];let m=(f&248)>>3;m===31&&(m+=1+((f&7)<<3)+((d[u]&224)>>5)),r+="."+m}break}case"hvc1":case"hev1":{const l=me(t,["hvcC"])[0];if(l&&l.length>12){const d=l[1],u=["","A","B","C"][d>>6],c=d&31,h=de(l,2),f=(d&32)>>5?"H":"L",m=l[12],p=l.subarray(6,12);r+="."+u+c,r+="."+oR(h).toString(16).toUpperCase(),r+="."+f+m;let g="";for(let v=p.length;v--;){const b=p[v];(b||g)&&(g="."+b.toString(16).toUpperCase()+g)}r+=g}n=qo(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{r=qo(r,t)||r;break}case"vp09":{const l=me(t,["vpcC"])[0];if(l&&l.length>6){const d=l[4],u=l[5],c=l[6]>>4&15;r+="."+Vi(d)+"."+Vi(u)+"."+Vi(c)}break}case"av01":{const l=me(t,["av1C"])[0];if(l&&l.length>2){const d=l[1]>>>5,u=l[1]&31,c=l[2]>>>7?"H":"M",h=(l[2]&64)>>6,f=(l[2]&32)>>5,m=d===2&&h?f?12:10:h?10:8,p=(l[2]&16)>>4,g=(l[2]&8)>>3,v=(l[2]&4)>>2,b=l[2]&3;r+="."+d+"."+Vi(u)+c+"."+Vi(m)+"."+p+"."+g+v+b+"."+Vi(1)+"."+Vi(1)+"."+Vi(1)+"."+0,n=qo("dav1",t)}break}}return{codec:r,encrypted:a,supplemental:n}}function qo(i,e){const t=me(e,["dvvC"]),s=t.length?t[0]:me(e,["dvcC"])[0];if(s){const r=s[2]>>1&127,n=s[2]<<5&32|s[3]>>3&31;return i+"."+Vi(r)+"."+Vi(n)}}function oR(i){let e=0;for(let t=0;t<32;t++)e|=(i>>t&1)<<31-t;return e>>>0}function bc(i,e){const t=e+5;for(;i[e++]&128&&e<t;);return e}function Yo(i){return("0"+i.toString(16).toUpperCase()).slice(-2)}function Vi(i){return(i<10?"0":"")+i}function lR(i,e){if(!i||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&wy(i,(s,r)=>{const n=s.subarray(8,24);n.some(a=>a!==0)||(we.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${It(n)} -> ${It(t)}`),s.set(t,8))})}function dR(i){const e=[];return wy(i,t=>e.push(t.subarray(8,24))),e}function wy(i,e){me(i,["moov","trak"]).forEach(s=>{const r=me(s,["mdia","minf","stbl","stsd"])[0];if(!r)return;const n=r.subarray(8);let a=me(n,["enca"]);const o=a.length>0;o||(a=me(n,["encv"])),a.forEach(l=>{const d=o?l.subarray(28):l.subarray(78);me(d,["sinf"]).forEach(c=>{const h=My(c);h&&e(h,o)})})})}function My(i){const e=me(i,["schm"])[0];if(e){const t=mt(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=me(i,["schi","tenc"])[0];if(s)return s}}}function uR(i,e,t){const s={},r=me(i,["moof","traf"]);for(let n=0;n<r.length;n++){const a=r[n],o=me(a,["tfhd"])[0],l=de(o,4),d=e[l];if(!d)continue;s[l]||(s[l]={start:NaN,duration:0,sampleCount:0,timescale:d.timescale,type:d.type});const u=s[l],c=me(a,["tfdt"])[0];if(c){const E=c[0];let T=de(c,4);E===1&&(T===Rg?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(T*=Rg+1,T+=de(c,8))),X(T)&&(!X(u.start)||T<u.start)&&(u.start=T)}const h=d.default,f=de(o,0)|h?.flags;let m=h?.duration||0;f&8&&(f&2?m=de(o,12):m=de(o,8));const p=me(a,["trun"]);let g=u.start||0,v=0,b=m;for(let E=0;E<p.length;E++){const T=p[E],A=de(T,4),x=u.sampleCount;u.sampleCount+=A;const S=T[3]&1,L=T[3]&4,R=T[2]&1,I=T[2]&2,M=T[2]&4,B=T[2]&8;let q=8,z=A;for(S&&(q+=4),L&&A&&(!(T[q+1]&1)&&u.keyFrameIndex===void 0&&(u.keyFrameIndex=x),q+=4,R?(b=de(T,q),q+=4):b=m,I&&(q+=4),B&&(q+=4),g+=b,v+=b,z--);z--;)R?(b=de(T,q),q+=4):b=m,I&&(q+=4),M&&(T[q+1]&1||u.keyFrameIndex===void 0&&(u.keyFrameIndex=u.sampleCount-(z+1),u.keyFrameStart=g),q+=4),B&&(q+=4),g+=b,v+=b;!v&&m&&(v+=m*A)}u.duration+=v}if(!Object.keys(s).some(n=>s[n].duration)){let n=1/0,a=0;const o=me(i,["sidx"]);for(let l=0;l<o.length;l++){const d=nR(o[l]);if(d!=null&&d.references){n=Math.min(n,d.earliestPresentationTime/d.timescale);const u=d.references.reduce((c,h)=>c+h.info.duration||0,0);a=Math.max(a,u+d.earliestPresentationTime/d.timescale)}}a&&X(a)&&Object.keys(s).forEach(l=>{s[l].duration||(s[l].duration=a*s[l].timescale-s[l].start)})}return s}function cR(i){const e={valid:null,remainder:null},t=me(i,["moof"]);if(t.length<2)return e.remainder=i,e;const s=t[t.length-1];return e.valid=i.slice(0,s.byteOffset-8),e.remainder=i.slice(s.byteOffset-8),e}function li(i,e){const t=new Uint8Array(i.length+e.length);return t.set(i),t.set(e,i.length),t}function Dg(i,e){const t=[],s=e.samples,r=e.timescale,n=e.id;let a=!1;return me(s,["moof"]).map(l=>{const d=l.byteOffset-8;me(l,["traf"]).map(c=>{const h=me(c,["tfdt"]).map(f=>{const m=f[0];let p=de(f,4);return m===1&&(p*=Math.pow(2,32),p+=de(f,8)),p/r})[0];return h!==void 0&&(i=h),me(c,["tfhd"]).map(f=>{const m=de(f,4),p=de(f,0)&16777215,g=(p&1)!==0,v=(p&2)!==0,b=(p&8)!==0;let E=0;const T=(p&16)!==0;let A=0;const x=(p&32)!==0;let S=8;m===n&&(g&&(S+=8),v&&(S+=4),b&&(E=de(f,S),S+=4),T&&(A=de(f,S),S+=4),x&&(S+=4),e.type==="video"&&(a=qu(e.codec)),me(c,["trun"]).map(L=>{const R=L[0],I=de(L,0)&16777215,M=(I&1)!==0;let B=0;const q=(I&4)!==0,z=(I&256)!==0;let K=0;const H=(I&512)!==0;let j=0;const G=(I&1024)!==0,N=(I&2048)!==0;let W=0;const U=de(L,4);let $=8;M&&(B=de(L,$),$+=4),q&&($+=4);let re=B+d;for(let he=0;he<U;he++){if(z?(K=de(L,$),$+=4):K=E,H?(j=de(L,$),$+=4):j=A,G&&($+=4),N&&(R===0?W=de(L,$):W=Dy(L,$),$+=4),e.type===Ue.VIDEO){let ce=0;for(;ce<j;){const pe=de(s,re);if(re+=4,hR(a,s[re])){const ut=s.subarray(re,re+pe);wm(ut,a?2:1,i+W/r,t)}re+=pe,ce+=pe+4}}i+=K/r}}))})})}),t}function qu(i){if(!i)return!1;const e=i.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function hR(i,e){if(i){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function wm(i,e,t,s){const r=Py(i);let n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(l===255);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(l===255);const d=r.length-n;let u=n;if(o<d)n+=o;else if(o>d){we.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(a===4){if(r[u++]===181){const h=ky(r,u);if(u+=2,h===49){const f=de(r,u);if(u+=4,f===1195456820){const m=r[u++];if(m===3){const p=r[u++],g=31&p,v=64&p,b=v?2+g*3:0,E=new Uint8Array(b);if(v){E[0]=p;for(let T=1;T<b;T++)E[T]=r[u++]}s.push({type:m,payloadType:a,pts:t,bytes:E})}}}}}else if(a===5&&o>16){const c=[];for(let m=0;m<16;m++){const p=r[u++].toString(16);c.push(p.length==1?"0"+p:p),(m===3||m===5||m===7||m===9)&&c.push("-")}const h=o-16,f=new Uint8Array(h);for(let m=0;m<h;m++)f[m]=r[u++];s.push({payloadType:a,pts:t,uuid:c.join(""),userData:Xt(f),userDataBytes:f})}}}function Py(i){const e=i.byteLength,t=[];let s=1;for(;s<e-2;)i[s]===0&&i[s+1]===0&&i[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return i;const r=e-t.length,n=new Uint8Array(r);let a=0;for(s=0;s<r;a++,s++)a===t[0]&&(a++,t.shift()),n[s]=i[a];return n}function fR(i){const e=i[0];let t="",s="",r=0,n=0,a=0,o=0,l=0,d=0;if(e===0){for(;mt(i.subarray(d,d+1))!=="\0";)t+=mt(i.subarray(d,d+1)),d+=1;for(t+=mt(i.subarray(d,d+1)),d+=1;mt(i.subarray(d,d+1))!=="\0";)s+=mt(i.subarray(d,d+1)),d+=1;s+=mt(i.subarray(d,d+1)),d+=1,r=de(i,12),n=de(i,16),o=de(i,20),l=de(i,24),d=28}else if(e===1){d+=4,r=de(i,d),d+=4;const c=de(i,d);d+=4;const h=de(i,d);for(d+=4,a=2**32*c+h,KL(a)||(a=Number.MAX_SAFE_INTEGER,we.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=de(i,d),d+=4,l=de(i,d),d+=4;mt(i.subarray(d,d+1))!=="\0";)t+=mt(i.subarray(d,d+1)),d+=1;for(t+=mt(i.subarray(d,d+1)),d+=1;mt(i.subarray(d,d+1))!=="\0";)s+=mt(i.subarray(d,d+1)),d+=1;s+=mt(i.subarray(d,d+1)),d+=1}const u=i.subarray(d,i.byteLength);return{schemeIdUri:t,value:s,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:u}}function mR(i,...e){const t=e.length;let s=8,r=t;for(;r--;)s+=e[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(i,4),r=0,s=8;r<t;r++)n.set(e[r],s),s+=e[r].byteLength;return n}function pR(i,e,t){if(i.byteLength!==16)throw new RangeError("Invalid system id");let s,r;s=0,r=new Uint8Array;let n;s>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),mR([112,115,115,104],new Uint8Array([s,0,0,0]),i,n,r,a,t)}function gR(i){const e=[];if(i instanceof ArrayBuffer){const t=i.byteLength;let s=0;for(;s+32<t;){const r=new DataView(i,s),n=vR(r);e.push(n),s+=n.size}}return e}function vR(i){const e=i.getUint32(0),t=i.byteOffset,s=i.byteLength;if(s<e)return{offset:t,size:s};if(i.getUint32(4)!==1886614376)return{offset:t,size:e};const n=i.getUint32(8)>>>24;if(n!==0&&n!==1)return{offset:t,size:e};const a=i.buffer,o=It(new Uint8Array(a,t+12,16));let l=null,d=null,u=0;if(n===0)u=28;else{const h=i.getUint32(28);if(!h||s<32+h*16)return{offset:t,size:e};l=[];for(let f=0;f<h;f++)l.push(new Uint8Array(a,t+32+f*16,16));u=32+h*16}if(!u)return{offset:t,size:e};const c=i.getUint32(u);return e-32<c?{offset:t,size:e}:(d=new Uint8Array(a,t+u+4,c),{version:n,systemId:o,kids:l,data:d,offset:t,size:e})}const Oy=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Xn={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 Mm(i,e){const t=Xn[e];return!!t&&!!t[i.slice(0,4)]}function mo(i,e,t=!0){return!i.split(",").some(s=>!Pm(s,e,t))}function Pm(i,e,t=!0){var s;const r=zs(t);return(s=r?.isTypeSupported(po(i,e)))!=null?s:!1}function po(i,e){return`${e}/mp4;codecs=${i}`}function Cg(i){if(i){const e=i.substring(0,4);return Xn.video[e]}return 2}function jd(i){const e=Oy();return i.split(",").reduce((t,s)=>{const n=e&&qu(s)?9:Xn.video[s];return n?(n*2+t)/(t?3:2):(Xn.audio[s]+t)/(t?2:1)},0)}const Tc={};function ER(i,e=!0){if(Tc[i])return Tc[i];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[i];for(let r=0;r<t.length;r++){var s;if(Pm(t[r],"audio",e))return Tc[i]=t[r],t[r];if(t[r]==="mp3"&&(s=zs(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return i}const yR=/flac|opus|mp4a\.40\.34/i;function zd(i,e=!0){return i.replace(yR,t=>ER(t.toLowerCase(),e))}function bR(i,e){const t=[];if(i){const s=i.split(",");for(let r=0;r<s.length;r++)Mm(s[r],"video")||t.push(s[r])}return e&&t.push(e),t.join(",")}function Hl(i,e){if(i&&(i.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(i)!==-1)&&(wg(i,"audio")||wg(i,"video")))return i;if(e){const t=e.split(",");if(t.length>1){if(i){for(let s=t.length;s--;)if(t[s].substring(0,4)===i.substring(0,4))return t[s]}return t[0]}}return e||i}function wg(i,e){return Mm(i,e)&&Pm(i,e)}function TR(i){const e=i.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function _R(i){if(i.startsWith("av01.")){const e=i.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 i}function Mg(i){const e=zs(i)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function $h(i){return i.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const AR={supported:!0,powerEfficient:!0,smooth:!0},SR={supported:!1,smooth:!1,powerEfficient:!1},Ny={supported:!0,configurations:[],decodingInfoResults:[AR]};function Uy(i,e){return{supported:!1,configurations:e,decodingInfoResults:[SR],error:i}}function IR(i,e,t,s,r,n){const a=i.videoCodec,o=i.audioCodec?i.audioGroups:null,l=n?.audioCodec,d=n?.channels,u=d?parseInt(d):l?1/0:2;let c=null;if(o!=null&&o.length)try{o.length===1&&o[0]?c=e.groups[o[0]].channels:c=o.reduce((h,f)=>{if(f){const m=e.groups[f];if(!m)throw new Error(`Audio track group ${f} not found`);Object.keys(m.channels).forEach(p=>{h[p]=(h[p]||0)+m.channels[p]})}return h},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(h=>qu(h))||i.width>1920&&i.height>1088||i.height>1920&&i.width>1088||i.frameRate>Math.max(s,30)||i.videoRange!=="SDR"&&i.videoRange!==t||i.bitrate>Math.max(r,8e6))||!!c&&X(u)&&Object.keys(c).some(h=>parseInt(h)>u)}function $y(i,e,t,s={}){const r=i.videoCodec;if(!r&&!i.audioCodec||!t)return Promise.resolve(Ny);const n=[],a=xR(i),o=a.length,l=LR(i,e,o>0),d=l.length;for(let u=o||1*d||1;u--;){const c={type:"media-source"};if(o&&(c.video=a[u%o]),d){c.audio=l[u%d];const h=c.audio.bitrate;c.video&&h&&(c.video.bitrate-=h)}n.push(c)}if(r){const u=navigator.userAgent;if(r.split(",").some(c=>qu(c))&&Oy())return Promise.resolve(Uy(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),n))}return Promise.all(n.map(u=>{const c=kR(u);return s[c]||(s[c]=t.decodingInfo(u))})).then(u=>({supported:!u.some(c=>!c.supported),configurations:n,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:n,decodingInfoResults:[],error:u}))}function xR(i){var e;const t=(e=i.videoCodec)==null?void 0:e.split(","),s=Fy(i),r=i.width||640,n=i.height||480,a=i.frameRate||30,o=i.videoRange.toLowerCase();return t?t.map(l=>{const d={contentType:po(_R(l),"video"),width:r,height:n,bitrate:s,framerate:a};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function LR(i,e,t){var s;const r=(s=i.audioCodec)==null?void 0:s.split(","),n=Fy(i);return r&&i.audioGroups?i.audioGroups.reduce((a,o)=>{var l;const d=o?(l=e.groups[o])==null?void 0:l.tracks:null;return d?d.reduce((u,c)=>{if(c.groupId===o){const h=parseFloat(c.channels||"");r.forEach(f=>{const m={contentType:po(f,"audio"),bitrate:t?RR(f,n):n};h&&(m.channels=""+h),u.push(m)})}return u},a):a},[]):[]}function RR(i,e){if(e<=1)return 1;let t=128e3;return i==="ec-3"?t=768e3:i==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Fy(i){return Math.ceil(Math.max(i.bitrate*.9,i.averageBitrate)/1e3)*1e3||1}function kR(i){let e="";const{audio:t,video:s}=i;if(s){const r=$h(s.contentType);e+=`${r}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){const r=$h(t.contentType);e+=`${s?"_":""}${r}_c${t.channels}`}return e}const Fh=["NONE","TYPE-0","TYPE-1",null];function DR(i){return Fh.indexOf(i)>-1}const Qd=["SDR","PQ","HLG"];function CR(i){return!!i&&Qd.indexOf(i)>-1}var Gl={No:"",Yes:"YES",v2:"v2"};function Pg(i){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=i,r=s<e/2;return e&&r?t?Gl.v2:Gl.Yes:Gl.No}class Og{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 go{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 Ng(this._audioGroups,e)}hasSubtitleGroup(e){return Ng(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 Ng(i,e){return!e||!i?!1:i.indexOf(e)!==-1}function wR(){if(typeof matchMedia=="function"){const i=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(i.media!==e.media)return i.matches===!0}return!1}function MR(i,e){let t=!1,s=[];if(i&&(t=i!=="SDR",s=[i]),e){s=e.allowedVideoRanges||Qd.slice(0);const r=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:r&&wR(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const PR=i=>{const e=new WeakSet;return(t,s)=>{if(i&&(s=i(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},$e=(i,e)=>JSON.stringify(i,PR(e));function OR(i,e,t,s,r){const n=Object.keys(i),a=s?.channels,o=s?.audioCodec,l=r?.videoCodec,d=a&&parseInt(a)===2;let u=!1,c=!1,h=1/0,f=1/0,m=1/0,p=1/0,g=0,v=[];const{preferHDR:b,allowedVideoRanges:E}=MR(e,r);for(let L=n.length;L--;){const R=i[n[L]];u||(u=R.channels[2]>0),h=Math.min(h,R.minHeight),f=Math.min(f,R.minFramerate),m=Math.min(m,R.minBitrate),E.filter(M=>R.videoRanges[M]>0).length>0&&(c=!0)}h=X(h)?h:0,f=X(f)?f:0;const T=Math.max(1080,h),A=Math.max(30,f);m=X(m)?m:t,t=Math.max(m,t),c||(e=void 0);const x=n.length>1;return{codecSet:n.reduce((L,R)=>{const I=i[R];if(R===L)return L;if(v=c?E.filter(M=>I.videoRanges[M]>0):[],x){if(I.minBitrate>t)return ki(R,`min bitrate of ${I.minBitrate} > current estimate of ${t}`),L;if(!I.hasDefaultAudio)return ki(R,"no renditions with default or auto-select sound found"),L;if(o&&R.indexOf(o.substring(0,4))%5!==0)return ki(R,`audio codec preference "${o}" not found`),L;if(a&&!d){if(!I.channels[a])return ki(R,`no renditions with ${a} channel sound found (channels options: ${Object.keys(I.channels)})`),L}else if((!o||d)&&u&&I.channels[2]===0)return ki(R,"no renditions with stereo sound found"),L;if(I.minHeight>T)return ki(R,`min resolution of ${I.minHeight} > maximum of ${T}`),L;if(I.minFramerate>A)return ki(R,`min framerate of ${I.minFramerate} > maximum of ${A}`),L;if(!v.some(M=>I.videoRanges[M]>0))return ki(R,`no variants with VIDEO-RANGE of ${$e(v)} found`),L;if(l&&R.indexOf(l.substring(0,4))%5!==0)return ki(R,`video codec preference "${l}" not found`),L;if(I.maxScore<g)return ki(R,`max score of ${I.maxScore} < selected max of ${g}`),L}return L&&(jd(R)>=jd(L)||I.fragmentError>i[L].fragmentError)?L:(p=I.minIndex,g=I.maxScore,R)},void 0),videoRanges:v,preferHDR:b,minFramerate:f,minBitrate:m,minIndex:p}}function ki(i,e){we.log(`[abr] start candidates with "${i}" ignored because ${e}`)}function By(i){return i.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 r=t.channels||"2";return s.channels[r]=(s.channels[r]||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 NR(i,e,t,s){return i.slice(t,s+1).reduce((r,n,a)=>{if(!n.codecSet)return r;const o=n.audioGroups;let l=r[n.codecSet];l||(r[n.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,n.bitrate);const d=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,d),l.minFramerate=Math.min(l.minFramerate,n.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,n.score),l.fragmentError+=n.fragmentError,l.videoRanges[n.videoRange]=(l.videoRanges[n.videoRange]||0)+1,o&&o.forEach(u=>{if(!u)return;const c=e.groups[u];c&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?c.hasDefault:c.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(c.channels).forEach(h=>{l.channels[h]=(l.channels[h]||0)+c.channels[h]}))}),r},{})}function Ug(i){if(!i)return i;const{lang:e,assocLang:t,characteristics:s,channels:r,audioCodec:n}=i;return{lang:e,assocLang:t,characteristics:s,channels:r,audioCodec:n}}function Qi(i,e,t){if("attrs"in i){const s=e.indexOf(i);if(s!==-1)return s}for(let s=0;s<e.length;s++){const r=e[s];if(Lr(i,r,t))return s}return-1}function Lr(i,e,t){const{groupId:s,name:r,lang:n,assocLang:a,default:o}=i,l=i.forced;return(s===void 0||e.groupId===s)&&(r===void 0||e.name===r)&&(n===void 0||UR(n,e.lang))&&(n===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in i)||$R(i.characteristics||"",e.characteristics))&&(t===void 0||t(i,e))}function UR(i,e="--"){return i.length===e.length?i===e:i.startsWith(e)||e.startsWith(i)}function $R(i,e=""){const t=i.split(","),s=e.split(",");return t.length===s.length&&!t.some(r=>s.indexOf(r)===-1)}function ur(i,e){const{audioCodec:t,channels:s}=i;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function FR(i,e,t,s,r){const n=e[s],o=e.reduce((h,f,m)=>{const p=f.uri;return(h[p]||(h[p]=[])).push(m),h},{})[n.uri];o.length>1&&(s=Math.max.apply(Math,o));const l=n.videoRange,d=n.frameRate,u=n.codecSet.substring(0,4),c=$g(e,s,h=>{if(h.videoRange!==l||h.frameRate!==d||h.codecSet.substring(0,4)!==u)return!1;const f=h.audioGroups,m=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return Qi(i,m,r)>-1});return c>-1?c:$g(e,s,h=>{const f=h.audioGroups,m=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return Qi(i,m,r)>-1})}function $g(i,e,t){for(let s=e;s>-1;s--)if(t(i[s]))return s;for(let s=e+1;s<i.length;s++)if(t(i[s]))return s;return-1}function Xd(i,e){var t;return!!i&&i!==((t=e.loadLevelObj)==null?void 0:t.uri)}class BR extends di{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:r,partCurrent:n,hls:a}=this,{autoLevelEnabled:o,media:l}=a;if(!r||!l)return;const d=performance.now(),u=n?n.stats:r.stats,c=n?n.duration:r.duration,h=d-u.loading.start,f=a.minAutoLevel,m=r.level,p=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||m<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const g=p>-1&&p!==m,v=!!t||g;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;const b=a.mainForwardBufferInfo;if(!v&&b===null)return;const E=this.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(h<=Math.max(E,1e3*(c/(T*2))))return;const A=b?b.len/T:0,x=u.loading.first?u.loading.first-u.loading.start:-1,S=u.loaded&&x>-1,L=this.getBwEstimate(),R=a.levels,I=R[m],M=Math.max(u.loaded,Math.round(c*(r.bitrate||I.averageBitrate)/8));let B=S?h-x:h;B<1&&S&&(B=Math.min(h,u.loaded*8/L));const q=S?u.loaded*1e3/B:0,z=E/1e3,K=q?(M-u.loaded)/q:M*8/L+z;if(K<=A)return;const H=q?q*8:L,j=((s=t?.details||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,G=this.hls.config.abrBandWidthUpFactor;let N=Number.POSITIVE_INFINITY,W;for(W=m-1;W>f;W--){const he=R[W].maxBitrate,ce=!R[W].details||j;if(N=this.getTimeToLoadFrag(z,H,c*he,ce),N<Math.min(A,c+z))break}if(N>=K||N>c*10)return;S?this.bwEstimator.sample(h-Math.min(E,x),u.loaded):this.bwEstimator.sampleTTFB(h);const U=R[W].maxBitrate;this.getBwEstimate()*G>U&&this.resetEstimator(U);const $=this.findBestLevel(U,f,W,0,A,1,1);$>-1&&(W=$),this.warn(`Fragment ${r.sn}${n?" part "+n.index:""} of level ${m} is loading too slowly;
|
|
1418
1418
|
Fragment duration: ${r.duration.toFixed(3)}
|
|
1419
1419
|
Time to underbuffer: ${A.toFixed(3)} s
|
|
1420
1420
|
Estimated load time for current fragment: ${K.toFixed(3)} s
|
|
1421
|
-
Estimated load time for down switch fragment: ${
|
|
1421
|
+
Estimated load time for down switch fragment: ${N.toFixed(3)} s
|
|
1422
1422
|
TTFB estimate: ${x|0} ms
|
|
1423
|
-
Current BW estimate: ${
|
|
1423
|
+
Current BW estimate: ${X(L)?L|0:"Unknown"} bps
|
|
1424
1424
|
New BW estimate: ${this.getBwEstimate()|0} bps
|
|
1425
|
-
Switching to level ${
|
|
1425
|
+
Switching to level ${W} @ ${U|0} bps`),a.nextLoadLevel=a.nextAutoLevel=W,this.clearTimer();const re=()=>{if(this.clearTimer(),this.fragCurrent===r&&this.hls.loadLevel===W&&W>0){const he=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${W>0?"and switching down":""}
|
|
1426
1426
|
Fragment duration: ${r.duration.toFixed(3)} s
|
|
1427
|
-
Time to underbuffer: ${ge.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,Z>f){let ce=this.findBestLevel(this.hls.levels[f].bitrate,f,Z,0,ge,1,1);ce===-1&&(ce=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=ce,this.resetEstimator(this.hls.levels[ce].bitrate)}}};g||K>G*2?se():this.timer=self.setInterval(se,G*1e3),a.trigger(y.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:n,stats:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new WL(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(y.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var r;this.fragCurrent=s,this.partCurrent=(r=t.part)!=null?r:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case w.BUFFER_ADD_CODEC_ERROR:case w.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case w.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:r,partCurrent:n}=this;if(s&&r&&s.sn===r.sn&&s.level===r.level){const a=performance.now(),o=n?n.stats:s.stats,l=a-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){const c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(c,d),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,s,r){const n=e+s/t,a=r?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){const s=this.hls.config,{loading:r}=t.stats,n=r.end-r.first;Q(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const r=s?s.stats:t.stats;if(t.type===J.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const n=s?s.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+r.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){const n={stats:r,frag:t,part:s,id:t.type};this.onFragBuffered(y.FRAG_BUFFERED,n),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:r}=t,n=r!=null&&r.stats.loaded?r.stats:s.stats;if(n.aborted||this.ignoreFragment(s))return;const a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==J.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,n=this.findBestLevel(s,t,e,0,r,1,1);if(n>-1)return n;const a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return 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(),r=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const n=s&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,n)&&a[e].loadError<=a[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:r,config:n,minAutoLevel:a}=s,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),d=this.getStarvationDelay();let u=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(d){const g=this.findBestLevel(l,a,r,d,0,u,c);if(g>=0)return this.rebufferNotice=-1,g}let h=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!d){const g=this.bitrateTestDelay;g&&(h=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-g,this.info(`bitrate test took ${Math.round(1e3*g)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),u=c=1)}const f=this.findBestLevel(l,a,r,d,h,u,c);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const m=s.levels[a],p=s.loadLevelObj;return p&&m?.bitrate<p.bitrate?a:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,r,n,a,o){var l;const d=r+n,u=this.lastLoadedFragLevel,c=u===-1?this.hls.firstLevel:u,{fragCurrent:h,partCurrent:f}=this,{levels:m,allAudioTracks:p,loadLevel:g,config:v}=this.hls;if(m.length===1)return 0;const b=m[c],E=!!((l=this.hls.latestLevelDetails)!=null&&l.live),T=g===-1||u===-1;let A,x="SDR",S=b?.frameRate||0;const{audioPreference:L,videoPreference:R}=v,I=this.audioTracksByGroup||(this.audioTracksByGroup=By(p));let M=-1;if(T){if(this.firstSelection!==-1)return this.firstSelection;const F=this.codecTiers||(this.codecTiers=NR(m,I,t,s)),Y=OR(F,x,e,L,R),{codecSet:P,videoRanges:G,minFramerate:Z,minBitrate:$,minIndex:H,preferHDR:se}=Y;M=H,A=P,x=se?G[G.length-1]:G[0],S=Z,e=Math.max(e,$),this.log(`picked start tier ${$e(Y)}`)}else A=b?.codecSet,x=b?.videoRange;const B=f?f.duration:h?h.duration:0,W=this.bwEstimator.getEstimateTTFB()/1e3,j=[];for(let F=s;F>=t;F--){var K;const Y=m[F],P=F>c;if(!Y)continue;if(v.useMediaCapabilities&&!Y.supportedResult&&!Y.supportedPromise){const ce=navigator.mediaCapabilities;typeof ce?.decodingInfo=="function"&&IR(Y,I,x,S,e,L)?(Y.supportedPromise=$y(Y,I,ce,this.supportedCache),Y.supportedPromise.then(me=>{if(!this.hls)return;Y.supportedResult=me;const ut=this.hls.levels,tt=ut.indexOf(Y);me.error?this.warn(`MediaCapabilities decodingInfo error: "${me.error}" for level ${tt} ${$e(me)}`):me.supported?me.decodingInfoResults.some(Dt=>Dt.smooth===!1||Dt.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${tt} not smooth or powerEfficient: ${$e(me)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${tt} ${$e(me)}`),tt>-1&&ut.length>1&&(this.log(`Removing unsupported level ${tt}`),this.hls.removeLevel(tt),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(me=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${me}`)})):Y.supportedResult=Ny}if((A&&Y.codecSet!==A||x&&Y.videoRange!==x||P&&S>Y.frameRate||!P&&S>0&&S<Y.frameRate||(K=Y.supportedResult)!=null&&(K=K.decodingInfoResults)!=null&&K.some(ce=>ce.smooth===!1))&&(!T||F!==M)){j.push(F);continue}const G=Y.details,Z=(f?G?.partTarget:G?.averagetargetduration)||B;let $;P?$=o*e:$=a*e;const H=B&&r>=B*2&&n===0?Y.averageBitrate:Y.maxBitrate,se=this.getTimeToLoadFrag(W,$,H*Z,G===void 0);if($>=H&&(F===u||Y.loadError===0&&Y.fragmentError===0)&&(se<=W||!Q(se)||E&&!this.bitrateTestDelay||se<d)){const ce=this.forcedAutoLevel;return F!==g&&(ce===-1||ce!==g)&&(j.length&&this.trace(`Skipped level(s) ${j.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${m[j[0]].codecs}" ${m[j[0]].videoRange}; not compatible with "${A}" ${x}`),this.info(`switch candidate:${c}->${F} adjustedbw(${Math.round($)})-bitrate=${Math.round($-H)} ttfb:${W.toFixed(1)} avgDuration:${Z.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${se.toFixed(1)} firstSelection:${T} codecSet:${Y.codecSet} videoRange:${Y.videoRange} hls.loadLevel:${g}`)),T&&(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 Hy={search:function(i,e){let t=0,s=i.length-1,r=null,n=null;for(;t<=s;){r=(t+s)/2|0,n=i[r];const a=e(n);if(a>0)t=r+1;else if(a<0)s=r-1;else return n}return null}};function HR(i,e,t){if(e===null||!Array.isArray(i)||!i.length||!Q(e))return null;const s=i[0].programDateTime;if(e<(s||0))return null;const r=i[i.length-1].endProgramDateTime;if(e>=(r||0))return null;for(let n=0;n<i.length;++n){const a=i[n];if(KR(e,t,a))return a}return null}function Mr(i,e,t=0,s=0,r=.005){let n=null;if(i){n=e[1+i.sn-e[0].sn]||null;const o=i.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&i.level!==n.level&&n.end<=i.end&&(n=e[2+i.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!i||i.level===n.level)&&Fg(t,s,n)===0||GR(n,i,Math.min(r,s))))return n;const a=Hy.search(e,Fg.bind(null,t,s));return a&&(a!==i||!n)?a:n}function GR(i,e,t){if(e&&e.start===0&&e.level<i.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((r,n)=>(n[0]==="INF"&&(r+=parseFloat(n[1])),r),t);return i.start<=s}return!1}function Fg(i=0,e=0,t){if(t.start<=i&&t.start+t.duration>i)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=i?1:t.start-s>i&&t.start?-1:0}function KR(i,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>i}function Gy(i,e,t){if(i&&i.startCC<=e&&i.endCC>=e){let s=i.fragments;const{fragmentHint:r}=i;r&&(s=s.concat(r));let n;return Hy.search(s,a=>a.cc<e?1:a.cc>e?-1:(n=a,a.end<=t?1:a.start>t?-1:0)),n||null}return null}function Zd(i){switch(i.details){case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_TIMEOUT:case w.LEVEL_LOAD_TIMEOUT:case w.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Ky(i){return i.details.startsWith("key")}function Vy(i){return Ky(i)&&!!i.frag&&!i.frag.decryptdata}function Bg(i,e){const t=Zd(e);return i.default[`${t?"timeout":"error"}Retry`]}function Om(i,e){const t=i.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*i.retryDelayMs,i.maxRetryDelayMs)}function Hg(i){return Ce(Ce({},i),{errorRetry:null,timeoutRetry:null})}function Jd(i,e,t,s){if(!i)return!1;const r=s?.code,n=e<i.maxNumRetry&&(VR(r)||!!t);return i.shouldRetry?i.shouldRetry(i,e,t,s,n):n}function VR(i){return Bh(i)||!!i&&(i<400||i>499)}function Bh(i){return i===0&&navigator.onLine===!1}var St={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Wt={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class WR extends di{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(y.ERROR,this.onError,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(y.ERROR,this.onError,this),e.off(y.ERROR,this.onErrorOut,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===J.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;const r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(a=>r.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const r=this.hls,n=t.context;switch(t.details){case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case w.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=Nn();return}case w.FRAG_GAP:case w.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=St.SendAlternateToPenaltyBox;return}case w.LEVEL_EMPTY_ERROR:case w.LEVEL_PARSING_ERROR:{var a;const l=t.parent===J.MAIN?t.level:r.loadLevel;t.details===w.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l))}return;case w.LEVEL_LOAD_ERROR:case w.LEVEL_LOAD_TIMEOUT:typeof n?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case w.AUDIO_TRACK_LOAD_ERROR:case w.AUDIO_TRACK_LOAD_TIMEOUT:case w.SUBTITLE_LOAD_ERROR:case w.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const l=r.loadLevelObj;if(l&&(n.type===pe.AUDIO_TRACK&&l.hasAudioGroup(n.groupId)||n.type===pe.SUBTITLE_TRACK&&l.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=St.SendAlternateToPenaltyBox,t.errorAction.flags=Wt.MoveAllAlternatesMatchingHost;return}}return;case w.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:St.SendAlternateToPenaltyBox,flags:Wt.MoveAllAlternatesMatchingHDCP};return;case w.KEY_SYSTEM_SESSION_UPDATE_FAILED:case w.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case w.KEY_SYSTEM_NO_SESSION:t.errorAction={action:St.SendAlternateToPenaltyBox,flags:Wt.MoveAllAlternatesMatchingKey};return;case w.BUFFER_ADD_CODEC_ERROR:case w.REMUX_ALLOC_ERROR:case w.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:r.loadLevel)}return;case w.INTERNAL_EXCEPTION:case w.BUFFER_APPENDING_ERROR:case w.BUFFER_FULL_ERROR:case w.LEVEL_SWITCH_ERROR:case w.BUFFER_STALLED_ERROR:case w.BUFFER_SEEK_OVER_HOLE:case w.BUFFER_NUDGE_ON_STALL:t.errorAction=Nn();return}t.type===ie.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Nn())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,r=Bg(s.config.playlistLoadPolicy,e),n=this.playlistError++;if(Jd(r,n,Zd(e),e.response))return{action:St.RetryRequest,flags:Wt.None,retryConfig:r,retryCount:n};const o=this.getLevelSwitchAction(e,t);return r&&(o.retryConfig=r,o.retryCount=n),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),r=t.levels[s],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=Bg(Ky(e)?a:n,e),l=t.levels.reduce((u,c)=>u+c.fragmentError,0);if(r&&(e.details!==w.FRAG_GAP&&r.fragmentError++,!Vy(e)&&Jd(o,l,Zd(e),e.response)))return{action:St.RetryRequest,flags:Wt.None,retryConfig:o,retryCount:l};const d=this.getLevelSwitchAction(e,s);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const r=this.hls.levels[t];if(r){var n,a;const d=e.details;r.loadError++,d===w.BUFFER_APPEND_ERROR&&r.fragmentError++;let u=-1;const{levels:c,loadLevel:h,minAutoLevel:f,maxAutoLevel:m}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const p=(n=e.frag)==null?void 0:n.type,v=(p===J.AUDIO&&d===w.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===w.BUFFER_ADD_CODEC_ERROR||d===w.BUFFER_APPEND_ERROR))&&c.some(({audioCodec:x})=>r.audioCodec!==x),E=e.sourceBufferName==="video"&&(d===w.BUFFER_ADD_CODEC_ERROR||d===w.BUFFER_APPEND_ERROR)&&c.some(({codecSet:x,audioCodec:S})=>r.codecSet!==x&&r.audioCodec===S),{type:T,groupId:A}=(a=e.context)!=null?a:{};for(let x=c.length;x--;){const S=(x+h)%c.length;if(S!==h&&S>=f&&S<=m&&c[S].loadError===0){var o,l;const L=c[S];if(d===w.FRAG_GAP&&p===J.MAIN&&e.frag){const R=c[S].details;if(R){const I=Mr(e.frag,R.fragments,e.frag.start);if(I!=null&&I.gap)continue}}else{if(T===pe.AUDIO_TRACK&&L.hasAudioGroup(A)||T===pe.SUBTITLE_TRACK&&L.hasSubtitleGroup(A))continue;if(p===J.AUDIO&&(o=r.audioGroups)!=null&&o.some(R=>L.hasAudioGroup(R))||p===J.SUBTITLE&&(l=r.subtitleGroups)!=null&&l.some(R=>L.hasSubtitleGroup(R))||v&&r.audioCodec===L.audioCodec||E&&r.codecSet===L.codecSet||!v&&r.codecSet!==L.codecSet)continue}u=S;break}}if(u>-1&&s.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:St.SendAlternateToPenaltyBox,flags:Wt.None,nextAutoLevel:u}}return{action:St.SendAlternateToPenaltyBox,flags:Wt.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case St.DoNothing:break;case St.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==w.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:r}=s,n=s.nextAutoLevel;switch(r){case Wt.None:this.switchLevel(e,n);break;case Wt.MoveAllAlternatesMatchingHDCP:{const l=this.getVariantLevelIndex(e.frag),d=t.levels[l],u=d?.attrs["HDCP-LEVEL"];if(s.hdcpLevel=u,u==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(u){t.maxHdcpLevel=Fh[Fh.indexOf(u)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Wt.MoveAllAlternatesMatchingKey:{const l=e.decryptdata;if(l){const d=this.hls.levels,u=d.length;for(let h=u;h--;)if(this.variantHasKey(d[h],l)){var a,o;this.log(`Banned key found in level ${h} (${d[h].bitrate}bps) or audio group "${(a=d[h].audioGroups)==null?void 0:a.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${It(l.keyId||[])}`),d[h].fragmentError++,d[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h)}const c=e.frag;if(this.hls.levels.length<u)s.resolved=!0;else if(c&&c.type!==J.MAIN){const h=c.decryptdata;h&&!l.matches(h)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,n)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===w.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=$h(e.mimeType),r=this.hls.levels;for(let n=r.length;n--;)r[n][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${n} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(n))}}}function Nn(i){const e={action:St.DoNothing,flags:Wt.None};return i&&(e.resolved=!0),e}var gt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class qR{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let r=s.length;r--;){const n=s[r];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:r}=this,n=Object.keys(r);for(let a=n.length;a--;){const o=r[n[a]];if(o?.body.type===t&&(!s||o.buffered)){const l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,s,r,n){this.timeRanges&&(this.timeRanges[e]=t);const a=r?.fragment.sn||-1;Object.keys(this.fragments).forEach(o=>{const l=this.fragments[o];if(!l||a>=l.body.sn)return;if(!l.buffered&&(!l.loaded||n)){l.body.type===s&&this.removeFragment(l.body);return}const d=l.range[e];if(d){if(d.time.length===0){this.removeFragment(l.body);return}d.time.some(u=>{const c=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return c&&this.removeFragment(l.body),c})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,r=Yr(s),n=this.fragments[r];if(!n||n.buffered&&s.gap)return;const a=!s.relurl;Object.keys(t).forEach(o=>{const l=s.elementaryStreams[o];if(!l)return;const d=t[o],u=a||l.partial===!0;n.range[o]=this.getBufferedTimes(s,e.part,u,d)}),n.loaded=null,Object.keys(n.range).length?(this.bufferedEnd(n,s),jo(n)||this.removeParts(s.sn-1,s.type)):this.removeFragment(n.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Gg(s,r=>r.fragment.sn>=e))}fragBuffered(e,t){const s=Yr(e);let r=this.fragments[s];!r&&t&&(r=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e))}getBufferedTimes(e,t,s,r){const n={time:[],partial:s},a=e.start,o=e.end,l=e.minEndPTS||o,d=e.maxStartPTS||a;for(let u=0;u<r.length;u++){const c=r.start(u)-this.bufferPadding,h=r.end(u)+this.bufferPadding;if(d>=c&&l<=h){n.time.push({startPTS:Math.max(a,r.start(u)),endPTS:Math.min(o,r.end(u))});break}else if(a<h&&o>c){const f=Math.max(a,r.start(u)),m=Math.min(o,r.end(u));m>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:m}))}else if(o<=c)break}return n}getPartialFragment(e){let t=null,s,r,n,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(d=>{const u=l[d];u&&jo(u)&&(r=u.body.start-o,n=u.body.end+o,e>=r&&e<=n&&(s=Math.min(e-r,n-e),a<=s&&(t=u.body,a=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||jo(t))}getState(e){const t=Yr(e),s=this.fragments[t];return s?s.buffered?jo(s)?gt.PARTIAL:gt.OK:gt.APPENDING:gt.NOT_LOADED}isTimeBuffered(e,t,s){let r,n;for(let a=0;a<s.length;a++){if(r=s.start(a)-this.bufferPadding,n=s.end(a)+this.bufferPadding,e>=r&&t<=n)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const s=t.frag,r=t.part?null:t,n=Yr(s);this.fragments[n]={body:s,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:r,timeRanges:n,type:a}=t;if(s.sn==="initSegment")return;const o=s.type;if(r){let d=this.activePartLists[o];d||(this.activePartLists[o]=d=[]),d.push(r)}this.timeRanges=n;const l=n[a];this.detectEvictedFragments(a,l,o,r)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Yr(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let r=s.length;r--;){const n=t[s[r]];if(n?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,r,n){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==s||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(e){const t=Yr(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const r=e.sn;this.activePartLists[e.type]=Gg(s,n=>n.fragment.sn!==r)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(s=>s.clearElementaryStreamInfo())}}function jo(i){var e,t,s;return i.buffered&&!!(i.body.gap||(e=i.range.video)!=null&&e.partial||(t=i.range.audio)!=null&&t.partial||(s=i.range.audiovideo)!=null&&s.partial)}function Yr(i){return`${i.type}_${i.level}_${i.sn}`}function Gg(i,e){return i.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var Qs={cbc:0,ctr:1};class YR{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 Qs.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Qs.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 jR(i){const e=i.byteLength,t=e&&new DataView(i.buffer).getUint8(e-1);return t?i.slice(0,e-t):i}class zR{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 r=0;r<4;r++)s[r]=t.getUint32(r*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,r=s[0],n=s[1],a=s[2],o=s[3],l=this.invSubMix,d=l[0],u=l[1],c=l[2],h=l[3],f=new Uint32Array(256);let m=0,p=0,g=0;for(g=0;g<256;g++)g<128?f[g]=g<<1:f[g]=g<<1^283;for(g=0;g<256;g++){let v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^v&255^99,e[m]=v,t[v]=m;const b=f[m],E=f[b],T=f[E];let A=f[v]*257^v*16843008;r[m]=A<<24|A>>>8,n[m]=A<<16|A>>>16,a[m]=A<<8|A>>>24,o[m]=A,A=T*16843009^E*65537^b*257^m*16843008,d[v]=A<<24|A>>>8,u[v]=A<<16|A>>>16,c[v]=A<<8|A>>>24,h[v]=A,m?(m=b^f[f[f[T^b]]],p^=f[f[p]]):m=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,r=0;for(;r<t.length&&s;)s=t[r]===this.key[r],r++;if(s)return;this.key=t;const n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);const a=this.ksRows=(n+6+1)*4;let o,l;const d=this.keySchedule=new Uint32Array(a),u=this.invKeySchedule=new Uint32Array(a),c=this.sBox,h=this.rcon,f=this.invSubMix,m=f[0],p=f[1],g=f[2],v=f[3];let b,E;for(o=0;o<a;o++){if(o<n){b=d[o]=t[o];continue}E=b,o%n===0?(E=E<<8|E>>>24,E=c[E>>>24]<<24|c[E>>>16&255]<<16|c[E>>>8&255]<<8|c[E&255],E^=h[o/n|0]<<24):n>6&&o%n===4&&(E=c[E>>>24]<<24|c[E>>>16&255]<<16|c[E>>>8&255]<<8|c[E&255]),d[o]=b=(d[o-n]^E)>>>0}for(l=0;l<a;l++)o=a-l,l&3?E=d[o]:E=d[o-4],l<4||o<=4?u[l]=E:u[l]=m[c[E>>>24]]^p[c[E>>>16&255]]^g[c[E>>>8&255]]^v[c[E&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const r=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],d=o[1],u=o[2],c=o[3],h=this.uint8ArrayToUint32Array_(s);let f=h[0],m=h[1],p=h[2],g=h[3];const v=new Int32Array(e),b=new Int32Array(v.length);let E,T,A,x,S,L,R,I,M,B,W,j,K,F;const Y=this.networkToHostOrderSwap;for(;t<v.length;){for(M=Y(v[t]),B=Y(v[t+1]),W=Y(v[t+2]),j=Y(v[t+3]),S=M^n[0],L=j^n[1],R=W^n[2],I=B^n[3],K=4,F=1;F<r;F++)E=l[S>>>24]^d[L>>16&255]^u[R>>8&255]^c[I&255]^n[K],T=l[L>>>24]^d[R>>16&255]^u[I>>8&255]^c[S&255]^n[K+1],A=l[R>>>24]^d[I>>16&255]^u[S>>8&255]^c[L&255]^n[K+2],x=l[I>>>24]^d[S>>16&255]^u[L>>8&255]^c[R&255]^n[K+3],S=E,L=T,R=A,I=x,K=K+4;E=a[S>>>24]<<24^a[L>>16&255]<<16^a[R>>8&255]<<8^a[I&255]^n[K],T=a[L>>>24]<<24^a[R>>16&255]<<16^a[I>>8&255]<<8^a[S&255]^n[K+1],A=a[R>>>24]<<24^a[I>>16&255]<<16^a[S>>8&255]<<8^a[L&255]^n[K+2],x=a[I>>>24]<<24^a[S>>16&255]<<16^a[L>>8&255]<<8^a[R&255]^n[K+3],b[t]=Y(E^f),b[t+1]=Y(x^m),b[t+2]=Y(A^p),b[t+3]=Y(T^g),f=M,m=B,p=W,g=j,t=t+4}return b.buffer}}class QR{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=XR(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function XR(i){switch(i){case Qs.cbc:return"AES-CBC";case Qs.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${i}`)}}const ZR=16;class Nm{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?jR(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,r){return this.useSoftware?new Promise((n,a)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,r);const l=this.flush();l?n(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,r)}softwareDecrypt(e,t,s,r){const{currentIV:n,currentResult:a,remainderData:o}=this;if(r!==Qs.cbc||t.byteLength!==16)return we.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=li(o,e),this.remainderData=null);const l=this.getValidChunk(e);if(!l.length)return null;n&&(s=n);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new zR),d.expandKey(t);const u=a;return this.currentResult=d.decrypt(l.buffer,0,s),this.currentIV=l.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,s,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,r));this.key=t,this.fastAesKey=new QR(this.subtle,t,r)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new YR(this.subtle,new Uint8Array(s),r).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(we.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,s,r)))}onWebCryptoError(e,t,s,r){const n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,r);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%ZR;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(we.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Kg=Math.pow(2,17);class JR{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 fs({type:ie.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(m=>m[0]==="GAP")){l(Wg(e));return}else e.gap=!1;const d=this.loader=n?new n(r):new a(r),u=Vg(e);e.loader=d;const c=Hg(r.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Kg};e.stats=d.stats;const f={onSuccess:(m,p,g,v)=>{this.resetLoader(e,d);let b=m.data;g.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(b.slice(0,16)),b=b.slice(16)),o({frag:e,part:null,payload:b,networkDetails:v})},onError:(m,p,g,v)=>{this.resetLoader(e,d),l(new fs({type:ie.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Ce({url:s,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:g,stats:v}))},onAbort:(m,p,g)=>{this.resetLoader(e,d),l(new fs({type:ie.NETWORK_ERROR,details:w.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:g,stats:m}))},onTimeout:(m,p,g)=>{this.resetLoader(e,d),l(new fs({type:ie.NETWORK_ERROR,details:w.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:m}))}};t&&(f.onProgress=(m,p,g,v)=>t({frag:e,part:null,payload:g,networkDetails:v})),d.load(u,h,f)})}loadPart(e,t,s){this.abort();const r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Wg(e,t));return}const d=this.loader=n?new n(r):new a(r),u=Vg(e,t);e.loader=d;const c=Hg(r.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Kg};t.stats=d.stats,d.load(u,h,{onSuccess:(f,m,p,g)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:f.data,networkDetails:g};s(v),o(v)},onError:(f,m,p,g)=>{this.resetLoader(e,d),l(new fs({type:ie.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Ce({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:g}))},onAbort:(f,m,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),l(new fs({type:ie.NETWORK_ERROR,details:w.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,m,p)=>{this.resetLoader(e,d),l(new fs({type:ie.NETWORK_ERROR,details:w.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(e,t){const s=e.stats,r=t.stats,n=r.total;if(s.loaded+=r.loaded,n){const l=Math.round(e.duration/t.duration),d=Math.min(Math.round(s.loaded/n),l),c=(l-d)*Math.round(s.loaded/d);s.total=s.loaded+c}else s.total=Math.max(s.loaded,s.total);const a=s.loading,o=r.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Vg(i,e=null){const t=e||i,s={frag:i,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},r=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(Q(r)&&Q(n)){var a;let o=r,l=n;if(i.sn==="initSegment"&&ek((a=i.decryptdata)==null?void 0:a.method)){const d=n-r;d%16&&(l=n+(16-d%16)),r!==0&&(s.resetIV=!0,o=r-16)}s.rangeStart=o,s.rangeEnd=l}return s}function Wg(i,e){const t=new Error(`GAP ${i.gap?"tag":"attribute"} found`),s={type:ie.MEDIA_ERROR,details:w.FRAG_GAP,fatal:!1,frag:i,error:t,networkDetails:null};return e&&(s.part=e),(e||i).stats.aborted=!0,new fs(s)}function ek(i){return i==="AES-128"||i==="AES-256"}class fs extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Wy extends di{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 Um{constructor(e,t,s,r=0,n=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=zo(),this.buffering={audio:zo(),video:zo(),audiovideo:zo()},this.level=e,this.sn=t,this.id=s,this.size=r,this.part=n,this.partial=a}}function zo(){return{start:0,executeStart:0,executeEnd:0,end:0}}const qg={length:0,start:()=>0,end:()=>0};class ue{static isBuffered(e,t){if(e){const s=ue.getBuffered(e);for(let r=s.length;r--;)if(t>=s.start(r)&&t<=s.end(r))return!0}return!1}static bufferedRanges(e){if(e){const t=ue.getBuffered(e);return ue.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 r=ue.bufferedRanges(e);if(r.length)return ue.bufferedInfo(r,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,c)=>u.start-c.start||c.end-u.end);let r=-1,n=[];if(s)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(r=u);const c=n.length;if(c){const h=n[c-1].end;e[u].start-h<s?e[u].end>h&&(n[c-1].end=e[u].end):n.push(e[u])}else n.push(e[u])}else n=e;let a=0,o,l=t,d=t;for(let u=0;u<n.length;u++){const c=n[u].start,h=n[u].end;if(r===-1&&t>=c&&t<=h&&(r=u),t+s>=c&&t<h)l=c,d=h,a=d-t;else if(t+s<c){o=c;break}}return{len:a,start:l||0,end:d||0,nextStart:o,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||qg}catch(t){return we.log("failed to get media.buffered",t),qg}}}const qy=/\{\$([a-zA-Z0-9-_]+)\}/g;function Yg(i){return qy.test(i)}function Hh(i,e){if(i.variableList!==null||i.hasVariableRefs){const t=i.variableList;return e.replace(qy,s=>{const r=s.substring(2,s.length-1),n=t?.[r];return n===void 0?(i.playlistParsingError||(i.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),s):n})}return e}function jg(i,e,t){let s=i.variableList;s||(i.variableList=s={});let r,n;if("QUERYPARAM"in e){r=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(r))n=a.get(r);else throw new Error(`"${r}" does not match any query parameter in URI: "${t}"`)}catch(a){i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else r=e.NAME,n=e.VALUE;r in s?i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):s[r]=n||""}function tk(i,e,t){const s=e.IMPORT;if(t&&s in t){let r=i.variableList;r||(i.variableList=r={}),r[s]=t[s]}else i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const ik=/^(\d+)x(\d+)$/,zg=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Ye{constructor(e,t){typeof e=="string"&&(e=Ye.parseAttrList(e,t)),Oe(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const s=new Uint8Array(t.length/2);for(let r=0;r<t.length/2;r++)s[r]=parseInt(t.slice(r*2,r*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((r,n)=>(r[n.toLowerCase()]=!0,r),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=ik.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const r={};for(zg.lastIndex=0;(s=zg.exec(e))!==null;){const a=s[1].trim();let o=s[2];const l=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1;let d=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(l||d))o=Hh(t,o);else if(!d&&!l)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":we.warn(`${e}: attribute ${a} is missing quotes`)}r[a]=o}return r}}const sk="com.apple.hls.interstitial";function rk(i){return i!=="ID"&&i!=="CLASS"&&i!=="CUE"&&i!=="START-DATE"&&i!=="DURATION"&&i!=="END-DATE"&&i!=="END-ON-NEXT"}function nk(i){return i==="SCTE35-OUT"||i==="SCTE35-IN"||i==="SCTE35-CMD"}class Yy{constructor(e,t,s=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(r=t?.tagOrder)!=null?r:s,t){const n=t.attr;for(const a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){we.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=Oe(new Ye({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const n=t?.endDate||new Date(this.attr["END-DATE"]);Q(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(we.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(Q(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===sk}get isValid(){return!!this.id&&!this._badValueForSameId&&Q(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 ak=10;class ok{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?Q(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||ak}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function eu(i,e){return i.length===e.length?!i.some((t,s)=>t!==e[s]):!1}function Qg(i,e){return!i&&!e?!0:!i||!e?!1:eu(i,e)}function Un(i){return i==="AES-128"||i==="AES-256"||i==="AES-256-CTR"}function $m(i){switch(i){case"AES-128":case"AES-256":return Qs.cbc;case"AES-256-CTR":return Qs.ctr;default:throw new Error(`invalid full segment method ${i}`)}}function Fm(i){return Uint8Array.from(atob(i),e=>e.charCodeAt(0))}function Gh(i){return Uint8Array.from(unescape(encodeURIComponent(i)),e=>e.charCodeAt(0))}function lk(i){const e=Gh(i).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function jy(i){const e=function(s,r,n){const a=s[r];s[r]=s[n],s[n]=a};e(i,0,3),e(i,1,2),e(i,4,5),e(i,6,7)}function zy(i){const e=i.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),r=s[s.length-1].split(",");if(r.length===2){const n=r[0]==="base64",a=r[1];n?(s.splice(-1,1),t=Fm(a)):t=lk(a)}}return t}const tu=typeof self<"u"?self:void 0;var je={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},xt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Kl(i){switch(i){case xt.FAIRPLAY:return je.FAIRPLAY;case xt.PLAYREADY:return je.PLAYREADY;case xt.WIDEVINE:return je.WIDEVINE;case xt.CLEARKEY:return je.CLEARKEY}}function _c(i){switch(i){case je.FAIRPLAY:return xt.FAIRPLAY;case je.PLAYREADY:return xt.PLAYREADY;case je.WIDEVINE:return xt.WIDEVINE;case je.CLEARKEY:return xt.CLEARKEY}}function ka(i){const{drmSystems:e,widevineLicenseUrl:t}=i,s=e?[je.FAIRPLAY,je.WIDEVINE,je.PLAYREADY,je.CLEARKEY].filter(r=>!!e[r]):[];return!s[je.WIDEVINE]&&t&&s.push(je.WIDEVINE),s}const Qy=(function(i){return tu!=null&&(i=tu.navigator)!=null&&i.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function dk(i,e,t,s){let r;switch(i){case je.FAIRPLAY:r=["cenc","sinf"];break;case je.WIDEVINE:case je.PLAYREADY:r=["cenc"];break;case je.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${i}`)}return uk(r,e,t,s)}function uk(i,e,t,s){return[{initDataTypes:i,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function ck(i){var e;return!!i&&(i.sessionType==="persistent-license"||!!((e=i.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Xy(i){const e=new Uint16Array(i.buffer,i.byteOffset,i.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 l=Fm(o).subarray(0,16);return jy(l),l}}return null}let jr={};class js{static clearKeyUriToKeyIdMap(){jr={}}static setKeyIdForUri(e,t){jr[e]=t}static addKeyIdForUri(e){const t=Object.keys(jr).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),jr[e]=s,s}constructor(e,t,s,r=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=r,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Un(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Iy(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&eu(e.keyFormatVersions,this.keyFormatVersions)&&Qg(e.iv,this.iv)&&Qg(e.keyId,this.keyId)}isSupported(){if(this.method){if(Un(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case xt.FAIRPLAY:case xt.WIDEVINE:case xt.PLAYREADY:case xt.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(Un(this.method)){let n=this.iv;return n||(typeof e!="number"&&(we.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),n=fk(e)),new js(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){const n=jr[this.uri];if(n&&!eu(this.keyId,n)&&js.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=zy(this.uri);if(s)switch(this.keyFormat){case xt.WIDEVINE:if(this.pssh=s,!this.keyId){const n=gR(s.buffer);if(n.length){var r;const a=n[0];this.keyId=(r=a.kids)!=null&&r.length?a.kids[0]:null}}this.keyId||(this.keyId=Xg(t));break;case xt.PLAYREADY:{const n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=pR(n,null,s),this.keyId=Xy(s);break}default:{let n=s.subarray(0,16);if(n.length!==16){const a=new Uint8Array(16);a.set(n,16-n.length),n=a}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n;n=hk(t),n||(n=Xg(t),n||(n=jr[this.uri])),n&&(this.keyId=n,js.setKeyIdForUri(this.uri,n))}return this}}function hk(i){const e=i?.[xt.WIDEVINE];return e?e.keyId:null}function Xg(i){const e=i?.[xt.PLAYREADY];if(e){const t=zy(e.uri);if(t)return Xy(t)}return null}function fk(i){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=i>>8*(15-t)&255;return e}const Zg=/#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,Jg=/#EXT-X-MEDIA:(.*)/g,mk=/^#EXT(?:INF|-X-TARGETDURATION):/m,Ac=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),pk=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 Xi{static findGroup(e,t){for(let s=0;s<e.length;s++){const r=e[s];if(r.id===t)return r}}static resolve(e,t){return Dm.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return mk.test(e)}static parseMasterPlaylist(e,t){const s=Yg(e),r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},n=[];if(Zg.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let a;for(;(a=Zg.exec(e))!=null;)if(a[1]){var o;const d=new Ye(a[1],r),u=Hh(r,a[2]),c={attrs:d,bitrate:d.decimalInteger("BANDWIDTH")||d.decimalInteger("AVERAGE-BANDWIDTH"),name:d.NAME,url:Xi.resolve(u,t)},h=d.decimalResolution("RESOLUTION");h&&(c.width=h.width,c.height=h.height),i0(d.CODECS,c);const f=d["SUPPLEMENTAL-CODECS"];f&&(c.supplemental={},i0(f,c.supplemental)),(o=c.unknownCodecs)!=null&&o.length||n.push(c),r.levels.push(c)}else if(a[3]){const d=a[3],u=a[4];switch(d){case"SESSION-DATA":{const c=new Ye(u,r),h=c["DATA-ID"];h&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[h]=c);break}case"SESSION-KEY":{const c=e0(u,t,r);c.encrypted&&c.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(c)):we.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const c=new Ye(u,r);jg(r,c,t)}break}case"CONTENT-STEERING":{const c=new Ye(u,r);r.contentSteering={uri:Xi.resolve(c["SERVER-URI"],t),pathwayId:c["PATHWAY-ID"]||"."};break}case"START":{r.startTimeOffset=t0(u);break}}}const l=n.length>0&&n.length<r.levels.length;return r.levels=l?n:r.levels,r.levels.length===0&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,s){let r;const n={},a=s.levels,o={AUDIO:a.map(d=>({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:a.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Jg.lastIndex=0;(r=Jg.exec(e))!==null;){const d=new Ye(r[1],s),u=d.TYPE;if(u){const c=o[u],h=n[u]||[];n[u]=h;const f=d.LANGUAGE,m=d["ASSOC-LANGUAGE"],p=d.CHANNELS,g=d.CHARACTERISTICS,v=d["INSTREAM-ID"],b={attrs:d,bitrate:0,id:l++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:u,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?Xi.resolve(d.URI,t):""};if(m&&(b.assocLang=m),p&&(b.channels=p),g&&(b.characteristics=g),v&&(b.instreamId=v),c!=null&&c.length){const E=Xi.findGroup(c,b.groupId)||c[0];s0(b,E,"audioCodec"),s0(b,E,"textCodec")}h.push(b)}}return n}static parseLevelPlaylist(e,t,s,r,n,a){var o;const l={url:t},d=new ok(t),u=d.fragments,c=[];let h=null,f=0,m=0,p=0,g=0,v=0,b=null,E=new yc(r,l),T,A,x,S=-1,L=!1,R=null,I;if(Ac.lastIndex=0,d.m3u8=e,d.hasVariableRefs=Yg(e),((o=Ac.exec(e))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(T=Ac.exec(e))!==null;){L&&(L=!1,E=new yc(r,l),E.playlistOffset=p,E.setStart(p),E.sn=f,E.cc=g,v&&(E.bitrate=v),E.level=s,h&&(E.initSegment=h,h.rawProgramDateTime&&(E.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),R&&(E.setByteRange(R),R=null)));const j=T[1];if(j){E.duration=parseFloat(j);const K=(" "+T[2]).slice(1);E.title=K||null,E.tagList.push(K?["INF",j,K]:["INF",j])}else if(T[3]){if(Q(E.duration)){E.playlistOffset=p,E.setStart(p),x&&n0(E,x,d),E.sn=f,E.level=s,E.cc=g,u.push(E);const K=(" "+T[3]).slice(1);E.relurl=Hh(d,K),Kh(E,b,c),b=E,p+=E.duration,f++,m=0,L=!0}}else{if(T=T[0].match(pk),!T){we.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A<T.length&&T[A]===void 0;A++);const K=(" "+T[A]).slice(1),F=(" "+T[A+1]).slice(1),Y=T[A+2]?(" "+T[A+2]).slice(1):null;switch(K){case"BYTERANGE":b?E.setByteRange(F,b):E.setByteRange(F);break;case"PROGRAM-DATE-TIME":E.rawProgramDateTime=F,E.tagList.push(["PROGRAM-DATE-TIME",F]),S===-1&&(S=u.length);break;case"PLAYLIST-TYPE":d.type&&os(d,K,T),d.type=F.toUpperCase();break;case"MEDIA-SEQUENCE":d.startSN!==0?os(d,K,T):u.length>0&&a0(d,K,T),f=d.startSN=parseInt(F);break;case"SKIP":{d.skippedSegments&&os(d,K,T);const P=new Ye(F,d),G=P.decimalInteger("SKIPPED-SEGMENTS");if(Q(G)){d.skippedSegments+=G;for(let $=G;$--;)u.push(null);f+=G}const Z=P.enumeratedString("RECENTLY-REMOVED-DATERANGES");Z&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(Z.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&os(d,K,T),d.targetduration=Math.max(parseInt(F),1);break;case"VERSION":d.version!==null&&os(d,K,T),d.version=parseInt(F);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||os(d,K,T),d.live=!1;break;case"#":(F||Y)&&E.tagList.push(Y?[F,Y]:[F]);break;case"DISCONTINUITY":g++,E.tagList.push(["DIS"]);break;case"GAP":E.gap=!0,E.tagList.push([K]);break;case"BITRATE":E.tagList.push([K,F]),v=parseInt(F)*1e3,Q(v)?E.bitrate=v:v=0;break;case"DATERANGE":{const P=new Ye(F,d),G=new Yy(P,d.dateRanges[P.ID],d.dateRangeTagCount);d.dateRangeTagCount++,G.isValid||d.skippedSegments?d.dateRanges[G.id]=G:we.warn(`Ignoring invalid DATERANGE tag: "${F}"`),E.tagList.push(["EXT-X-DATERANGE",F]);break}case"DEFINE":{{const P=new Ye(F,d);"IMPORT"in P?tk(d,P,a):jg(d,P,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?os(d,K,T):u.length>0&&a0(d,K,T),d.startCC=g=parseInt(F);break;case"KEY":{const P=e0(F,t,d);if(P.isSupported()){if(P.method==="NONE"){x=void 0;break}x||(x={});const G=x[P.keyFormat];G!=null&&G.matches(P)||(G&&(x=Oe({},x)),x[P.keyFormat]=P)}else we.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${F}"`);break}case"START":d.startTimeOffset=t0(F);break;case"MAP":{const P=new Ye(F,d);if(E.duration){const G=new yc(r,l);r0(G,P,s,x),h=G,E.initSegment=h,h.rawProgramDateTime&&!E.rawProgramDateTime&&(E.rawProgramDateTime=h.rawProgramDateTime)}else{const G=E.byteRangeEndOffset;if(G){const Z=E.byteRangeStartOffset;R=`${G-Z}@${Z}`}else R=null;r0(E,P,s,x),h=E,L=!0}h.cc=g;break}case"SERVER-CONTROL":{I&&os(d,K,T),I=new Ye(F),d.canBlockReload=I.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=I.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&I.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=I.optionalFloat("PART-HOLD-BACK",0),d.holdBack=I.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&os(d,K,T);const P=new Ye(F);d.partTarget=P.decimalFloatingPoint("PART-TARGET");break}case"PART":{let P=d.partList;P||(P=d.partList=[]);const G=m>0?P[P.length-1]:void 0,Z=m++,$=new Ye(F,d),H=new tR($,E,l,Z,G);P.push(H),E.duration+=H.duration;break}case"PRELOAD-HINT":{const P=new Ye(F,d);d.preloadHint=P;break}case"RENDITION-REPORT":{const P=new Ye(F,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(P);break}default:we.warn(`line parsed but not handled: ${T}`);break}}}b&&!b.relurl?(u.pop(),p-=b.duration,d.partList&&(d.fragmentHint=b)):d.partList&&(Kh(E,b,c),E.cc=g,d.fragmentHint=E,x&&n0(E,x,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const M=u.length,B=u[0],W=u[M-1];if(p+=d.skippedSegments*d.targetduration,p>0&&M&&W){d.averagetargetduration=p/M;const j=W.sn;d.endSN=j!=="initSegment"?j:0,d.live||(W.endList=!0),S>0&&(vk(u,S),B&&c.unshift(B))}return d.fragmentHint&&(p+=d.fragmentHint.duration),d.totalduration=p,c.length&&d.dateRangeTagCount&&B&&Zy(c,d),d.endCC=g,d}}function Zy(i,e){let t=i.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];i.push(o),t++}else return;const s=i[t-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=s.ref;for(let u=t;u--;){var a;if(((a=i[u])==null?void 0:a.sn)<e.startSN)break;const c=gk(e,d,i,u,r);if(c!==-1){l.tagAnchor=e.fragments[c].ref;break}}}}function gk(i,e,t,s,r){const n=t[s];if(n){const o=n.programDateTime;if(e>=o||s===0){var a;const l=(((a=t[s+1])==null?void 0:a.start)||r)-n.start;if(e<=o+l*1e3){const d=t[s].sn-i.startSN;if(d<0)return-1;const u=i.fragments;if(u.length>t.length){const h=(t[s+1]||u[u.length-1]).sn-i.startSN;for(let f=h;f>d;f--){const m=u[f].programDateTime;if(e>=m&&e<m+u[f].duration*1e3)return f}}return d}}}return-1}function e0(i,e,t){var s,r;const n=new Ye(i,t),a=(s=n.METHOD)!=null?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,u=(r=n.KEYFORMAT)!=null?r:"identity";o&&n.IV&&!l&&we.error(`Invalid IV: ${n.IV}`);const c=o?Xi.resolve(o,e):"",h=(d||"1").split("/").map(Number).filter(Number.isFinite);return new js(a,c,u,h,l,n.KEYID)}function t0(i){const t=new Ye(i).decimalFloatingPoint("TIME-OFFSET");return Q(t)?t:null}function i0(i,e){let t=(i||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const r=t.filter(n=>Mm(n,s));r.length&&(e[`${s}Codec`]=r.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>r.indexOf(n)===-1))}),e.unknownCodecs=t}function s0(i,e,t){const s=e[t];s&&(i[t]=s)}function vk(i,e){let t=i[e];for(let s=e;s--;){const r=i[s];if(!r)return;r.programDateTime=t.programDateTime-r.duration*1e3,t=r}}function Kh(i,e,t){i.rawProgramDateTime?t.push(i):e!=null&&e.programDateTime&&(i.programDateTime=e.endProgramDateTime)}function r0(i,e,t,s){i.relurl=e.URI,e.BYTERANGE&&i.setByteRange(e.BYTERANGE),i.level=t,i.sn="initSegment",s&&(i.levelkeys=s),i.initSegment=null}function n0(i,e,t){i.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(r=>e[r].isCommonEncryption)&&s.push(i)}function os(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function a0(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Sc(i,e){const t=e.startPTS;if(Q(t)){let s=0,r;e.sn>i.sn?(s=t-i.start,r=i):(s=i.start-t,r=e),r.duration!==s&&r.setDuration(s)}else e.sn>i.sn?i.cc===e.cc&&i.minEndPTS?e.setStart(i.start+(i.minEndPTS-i.start)):e.setStart(i.start+i.duration):e.setStart(Math.max(i.start-e.duration,0))}function Jy(i,e,t,s,r,n,a){s-t<=0&&(a.warn("Fragment should have a positive duration",e),s=t+e.duration,n=r+e.duration);let l=t,d=s;const u=e.startPTS,c=e.endPTS;if(Q(u)){const v=Math.abs(u-t);i&&v>i.totalduration?a.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${i.url}`):Q(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,l=Math.max(t,u),t=Math.min(t,u),r=e.startDTS!==void 0?Math.min(r,e.startDTS):r,d=Math.min(s,c),s=Math.max(s,c),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n}const h=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=l,e.startDTS=r,e.endPTS=s,e.minEndPTS=d,e.endDTS=n;const f=e.sn;if(!i||f<i.startSN||f>i.endSN)return 0;let m;const p=f-i.startSN,g=i.fragments;for(g[p]=e,m=p;m>0;m--)Sc(g[m],g[m-1]);for(m=p;m<g.length-1;m++)Sc(g[m],g[m+1]);return i.fragmentHint&&Sc(g[g.length-1],i.fragmentHint),i.PTSKnown=i.alignedSliding=!0,h}function Ek(i,e,t){if(i===e)return;let s=null;const r=i.fragments;for(let u=r.length-1;u>=0;u--){const c=r[u].initSegment;if(c){s=c;break}}i.fragmentHint&&delete i.fragmentHint.endPTS;let n;Tk(i,e,(u,c,h,f)=>{if((!e.startCC||e.skippedSegments)&&c.cc!==u.cc){const m=u.cc-c.cc;for(let p=h;p<f.length;p++)f[p].cc+=m;e.endCC=f[f.length-1].cc}Q(u.startPTS)&&Q(u.endPTS)&&(c.setStart(c.startPTS=u.startPTS),c.startDTS=u.startDTS,c.maxStartPTS=u.maxStartPTS,c.endPTS=u.endPTS,c.endDTS=u.endDTS,c.minEndPTS=u.minEndPTS,c.setDuration(u.endPTS-u.startPTS),c.duration&&(n=c),e.PTSKnown=e.alignedSliding=!0),u.hasStreams&&(c.elementaryStreams=u.elementaryStreams),c.loader=u.loader,u.hasStats&&(c.stats=u.stats),u.initSegment&&(c.initSegment=u.initSegment,s=u.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(s&&o.forEach(u=>{var c;u&&(!u.initSegment||u.initSegment.relurl===((c=s)==null?void 0:c.relurl))&&(u.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(u=>!u),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=e.skippedSegments;u--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=yk(i.dateRanges,e,t));const u=i.fragments.filter(c=>c.rawProgramDateTime);if(i.hasProgramDateTime&&!e.hasProgramDateTime)for(let c=1;c<o.length;c++)o[c].programDateTime===null&&Kh(o[c],o[c-1],u);Zy(u,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const u=ib(i,e.startSN-1);e.startCC=(l=u?.cc)!=null?l:a[0].cc}bk(i.partList,e.partList,(u,c)=>{c.elementaryStreams=u.elementaryStreams,c.stats=u.stats}),n?Jy(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,t):eb(i,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=i.driftStartTime,e.driftStart=i.driftStart;const d=e.advancedDateTime;if(e.advanced&&d){const u=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=u),e.driftEndTime=d,e.driftEnd=u}else e.driftEndTime=i.driftEndTime,e.driftEnd=i.driftEnd,e.advancedDateTime=i.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=i.requestScheduled)}function yk(i,e,t){const{dateRanges:s,recentlyRemovedDateranges:r}=e,n=Oe({},i);r&&r.forEach(l=>{delete n[l]});const o=Object.keys(n).length;return o?(Object.keys(s).forEach(l=>{const d=n[l],u=new Yy(s[l].attr,d);u.isValid?(n[l]=u,d||(u.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${$e(s[l].attr)}"`)}),n):s}function bk(i,e,t){if(i&&e){let s=0;for(let r=0,n=i.length;r<=n;r++){const a=i[r],o=e[r+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):s--}}}function Tk(i,e,t){const s=e.skippedSegments,r=Math.max(i.startSN,e.startSN)-e.startSN,n=(i.fragmentHint?1:0)+(s?e.endSN:Math.min(i.endSN,e.endSN))-e.startSN,a=e.startSN-i.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=i.fragmentHint?i.fragments.concat(i.fragmentHint):i.fragments;for(let d=r;d<=n;d++){const u=l[a+d];let c=o[d];if(s&&!c&&u&&(c=e.fragments[d]=u),u&&c){t(u,c,d,o);const h=u.relurl,f=c.relurl;if(h&&_k(h,f)){e.playlistParsingError=o0(`media sequence mismatch ${c.sn}:`,i,e,u,c);return}else if(u.cc!==c.cc){e.playlistParsingError=o0(`discontinuity sequence mismatch (${u.cc}!=${c.cc})`,i,e,u,c);return}}}}function o0(i,e,t,s,r){return new Error(`${i} ${r.url}
|
|
1427
|
+
Time to underbuffer: ${he.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,W>f){let ce=this.findBestLevel(this.hls.levels[f].bitrate,f,W,0,he,1,1);ce===-1&&(ce=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=ce,this.resetEstimator(this.hls.levels[ce].bitrate)}}};g||K>N*2?re():this.timer=self.setInterval(re,N*1e3),a.trigger(y.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:n,stats:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new WL(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(y.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var r;this.fragCurrent=s,this.partCurrent=(r=t.part)!=null?r:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case w.BUFFER_ADD_CODEC_ERROR:case w.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case w.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:r,partCurrent:n}=this;if(s&&r&&s.sn===r.sn&&s.level===r.level){const a=performance.now(),o=n?n.stats:s.stats,l=a-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){const c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(c,d),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,s,r){const n=e+s/t,a=r?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){const s=this.hls.config,{loading:r}=t.stats,n=r.end-r.first;X(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const r=s?s.stats:t.stats;if(t.type===J.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const n=s?s.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+r.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){const n={stats:r,frag:t,part:s,id:t.type};this.onFragBuffered(y.FRAG_BUFFERED,n),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:r}=t,n=r!=null&&r.stats.loaded?r.stats:s.stats;if(n.aborted||this.ignoreFragment(s))return;const a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==J.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,n=this.findBestLevel(s,t,e,0,r,1,1);if(n>-1)return n;const a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return 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(),r=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const n=s&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,n)&&a[e].loadError<=a[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:r,config:n,minAutoLevel:a}=s,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),d=this.getStarvationDelay();let u=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(d){const g=this.findBestLevel(l,a,r,d,0,u,c);if(g>=0)return this.rebufferNotice=-1,g}let h=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!d){const g=this.bitrateTestDelay;g&&(h=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-g,this.info(`bitrate test took ${Math.round(1e3*g)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),u=c=1)}const f=this.findBestLevel(l,a,r,d,h,u,c);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const m=s.levels[a],p=s.loadLevelObj;return p&&m?.bitrate<p.bitrate?a:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,r,n,a,o){var l;const d=r+n,u=this.lastLoadedFragLevel,c=u===-1?this.hls.firstLevel:u,{fragCurrent:h,partCurrent:f}=this,{levels:m,allAudioTracks:p,loadLevel:g,config:v}=this.hls;if(m.length===1)return 0;const b=m[c],E=!!((l=this.hls.latestLevelDetails)!=null&&l.live),T=g===-1||u===-1;let A,x="SDR",S=b?.frameRate||0;const{audioPreference:L,videoPreference:R}=v,I=this.audioTracksByGroup||(this.audioTracksByGroup=By(p));let M=-1;if(T){if(this.firstSelection!==-1)return this.firstSelection;const H=this.codecTiers||(this.codecTiers=NR(m,I,t,s)),j=OR(H,x,e,L,R),{codecSet:G,videoRanges:N,minFramerate:W,minBitrate:U,minIndex:$,preferHDR:re}=j;M=$,A=G,x=re?N[N.length-1]:N[0],S=W,e=Math.max(e,U),this.log(`picked start tier ${$e(j)}`)}else A=b?.codecSet,x=b?.videoRange;const B=f?f.duration:h?h.duration:0,q=this.bwEstimator.getEstimateTTFB()/1e3,z=[];for(let H=s;H>=t;H--){var K;const j=m[H],G=H>c;if(!j)continue;if(v.useMediaCapabilities&&!j.supportedResult&&!j.supportedPromise){const ce=navigator.mediaCapabilities;typeof ce?.decodingInfo=="function"&&IR(j,I,x,S,e,L)?(j.supportedPromise=$y(j,I,ce,this.supportedCache),j.supportedPromise.then(pe=>{if(!this.hls)return;j.supportedResult=pe;const ut=this.hls.levels,tt=ut.indexOf(j);pe.error?this.warn(`MediaCapabilities decodingInfo error: "${pe.error}" for level ${tt} ${$e(pe)}`):pe.supported?pe.decodingInfoResults.some(Dt=>Dt.smooth===!1||Dt.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${tt} not smooth or powerEfficient: ${$e(pe)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${tt} ${$e(pe)}`),tt>-1&&ut.length>1&&(this.log(`Removing unsupported level ${tt}`),this.hls.removeLevel(tt),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(pe=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${pe}`)})):j.supportedResult=Ny}if((A&&j.codecSet!==A||x&&j.videoRange!==x||G&&S>j.frameRate||!G&&S>0&&S<j.frameRate||(K=j.supportedResult)!=null&&(K=K.decodingInfoResults)!=null&&K.some(ce=>ce.smooth===!1))&&(!T||H!==M)){z.push(H);continue}const N=j.details,W=(f?N?.partTarget:N?.averagetargetduration)||B;let U;G?U=o*e:U=a*e;const $=B&&r>=B*2&&n===0?j.averageBitrate:j.maxBitrate,re=this.getTimeToLoadFrag(q,U,$*W,N===void 0);if(U>=$&&(H===u||j.loadError===0&&j.fragmentError===0)&&(re<=q||!X(re)||E&&!this.bitrateTestDelay||re<d)){const ce=this.forcedAutoLevel;return H!==g&&(ce===-1||ce!==g)&&(z.length&&this.trace(`Skipped level(s) ${z.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${m[z[0]].codecs}" ${m[z[0]].videoRange}; not compatible with "${A}" ${x}`),this.info(`switch candidate:${c}->${H} adjustedbw(${Math.round(U)})-bitrate=${Math.round(U-$)} ttfb:${q.toFixed(1)} avgDuration:${W.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${re.toFixed(1)} firstSelection:${T} codecSet:${j.codecSet} videoRange:${j.videoRange} hls.loadLevel:${g}`)),T&&(this.firstSelection=H),H}}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 Hy={search:function(i,e){let t=0,s=i.length-1,r=null,n=null;for(;t<=s;){r=(t+s)/2|0,n=i[r];const a=e(n);if(a>0)t=r+1;else if(a<0)s=r-1;else return n}return null}};function HR(i,e,t){if(e===null||!Array.isArray(i)||!i.length||!X(e))return null;const s=i[0].programDateTime;if(e<(s||0))return null;const r=i[i.length-1].endProgramDateTime;if(e>=(r||0))return null;for(let n=0;n<i.length;++n){const a=i[n];if(KR(e,t,a))return a}return null}function Mr(i,e,t=0,s=0,r=.005){let n=null;if(i){n=e[1+i.sn-e[0].sn]||null;const o=i.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&i.level!==n.level&&n.end<=i.end&&(n=e[2+i.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!i||i.level===n.level)&&Fg(t,s,n)===0||GR(n,i,Math.min(r,s))))return n;const a=Hy.search(e,Fg.bind(null,t,s));return a&&(a!==i||!n)?a:n}function GR(i,e,t){if(e&&e.start===0&&e.level<i.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((r,n)=>(n[0]==="INF"&&(r+=parseFloat(n[1])),r),t);return i.start<=s}return!1}function Fg(i=0,e=0,t){if(t.start<=i&&t.start+t.duration>i)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=i?1:t.start-s>i&&t.start?-1:0}function KR(i,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>i}function Gy(i,e,t){if(i&&i.startCC<=e&&i.endCC>=e){let s=i.fragments;const{fragmentHint:r}=i;r&&(s=s.concat(r));let n;return Hy.search(s,a=>a.cc<e?1:a.cc>e?-1:(n=a,a.end<=t?1:a.start>t?-1:0)),n||null}return null}function Zd(i){switch(i.details){case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_TIMEOUT:case w.LEVEL_LOAD_TIMEOUT:case w.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Ky(i){return i.details.startsWith("key")}function Vy(i){return Ky(i)&&!!i.frag&&!i.frag.decryptdata}function Bg(i,e){const t=Zd(e);return i.default[`${t?"timeout":"error"}Retry`]}function Om(i,e){const t=i.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*i.retryDelayMs,i.maxRetryDelayMs)}function Hg(i){return Ce(Ce({},i),{errorRetry:null,timeoutRetry:null})}function Jd(i,e,t,s){if(!i)return!1;const r=s?.code,n=e<i.maxNumRetry&&(VR(r)||!!t);return i.shouldRetry?i.shouldRetry(i,e,t,s,n):n}function VR(i){return Bh(i)||!!i&&(i<400||i>499)}function Bh(i){return i===0&&navigator.onLine===!1}var St={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Wt={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class WR extends di{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(y.ERROR,this.onError,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(y.ERROR,this.onError,this),e.off(y.ERROR,this.onErrorOut,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===J.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;const r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(a=>r.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const r=this.hls,n=t.context;switch(t.details){case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case w.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=Nn();return}case w.FRAG_GAP:case w.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=St.SendAlternateToPenaltyBox;return}case w.LEVEL_EMPTY_ERROR:case w.LEVEL_PARSING_ERROR:{var a;const l=t.parent===J.MAIN?t.level:r.loadLevel;t.details===w.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l))}return;case w.LEVEL_LOAD_ERROR:case w.LEVEL_LOAD_TIMEOUT:typeof n?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case w.AUDIO_TRACK_LOAD_ERROR:case w.AUDIO_TRACK_LOAD_TIMEOUT:case w.SUBTITLE_LOAD_ERROR:case w.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const l=r.loadLevelObj;if(l&&(n.type===ge.AUDIO_TRACK&&l.hasAudioGroup(n.groupId)||n.type===ge.SUBTITLE_TRACK&&l.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=St.SendAlternateToPenaltyBox,t.errorAction.flags=Wt.MoveAllAlternatesMatchingHost;return}}return;case w.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:St.SendAlternateToPenaltyBox,flags:Wt.MoveAllAlternatesMatchingHDCP};return;case w.KEY_SYSTEM_SESSION_UPDATE_FAILED:case w.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case w.KEY_SYSTEM_NO_SESSION:t.errorAction={action:St.SendAlternateToPenaltyBox,flags:Wt.MoveAllAlternatesMatchingKey};return;case w.BUFFER_ADD_CODEC_ERROR:case w.REMUX_ALLOC_ERROR:case w.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:r.loadLevel)}return;case w.INTERNAL_EXCEPTION:case w.BUFFER_APPENDING_ERROR:case w.BUFFER_FULL_ERROR:case w.LEVEL_SWITCH_ERROR:case w.BUFFER_STALLED_ERROR:case w.BUFFER_SEEK_OVER_HOLE:case w.BUFFER_NUDGE_ON_STALL:t.errorAction=Nn();return}t.type===ie.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Nn())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,r=Bg(s.config.playlistLoadPolicy,e),n=this.playlistError++;if(Jd(r,n,Zd(e),e.response))return{action:St.RetryRequest,flags:Wt.None,retryConfig:r,retryCount:n};const o=this.getLevelSwitchAction(e,t);return r&&(o.retryConfig=r,o.retryCount=n),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),r=t.levels[s],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=Bg(Ky(e)?a:n,e),l=t.levels.reduce((u,c)=>u+c.fragmentError,0);if(r&&(e.details!==w.FRAG_GAP&&r.fragmentError++,!Vy(e)&&Jd(o,l,Zd(e),e.response)))return{action:St.RetryRequest,flags:Wt.None,retryConfig:o,retryCount:l};const d=this.getLevelSwitchAction(e,s);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const r=this.hls.levels[t];if(r){var n,a;const d=e.details;r.loadError++,d===w.BUFFER_APPEND_ERROR&&r.fragmentError++;let u=-1;const{levels:c,loadLevel:h,minAutoLevel:f,maxAutoLevel:m}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const p=(n=e.frag)==null?void 0:n.type,v=(p===J.AUDIO&&d===w.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===w.BUFFER_ADD_CODEC_ERROR||d===w.BUFFER_APPEND_ERROR))&&c.some(({audioCodec:x})=>r.audioCodec!==x),E=e.sourceBufferName==="video"&&(d===w.BUFFER_ADD_CODEC_ERROR||d===w.BUFFER_APPEND_ERROR)&&c.some(({codecSet:x,audioCodec:S})=>r.codecSet!==x&&r.audioCodec===S),{type:T,groupId:A}=(a=e.context)!=null?a:{};for(let x=c.length;x--;){const S=(x+h)%c.length;if(S!==h&&S>=f&&S<=m&&c[S].loadError===0){var o,l;const L=c[S];if(d===w.FRAG_GAP&&p===J.MAIN&&e.frag){const R=c[S].details;if(R){const I=Mr(e.frag,R.fragments,e.frag.start);if(I!=null&&I.gap)continue}}else{if(T===ge.AUDIO_TRACK&&L.hasAudioGroup(A)||T===ge.SUBTITLE_TRACK&&L.hasSubtitleGroup(A))continue;if(p===J.AUDIO&&(o=r.audioGroups)!=null&&o.some(R=>L.hasAudioGroup(R))||p===J.SUBTITLE&&(l=r.subtitleGroups)!=null&&l.some(R=>L.hasSubtitleGroup(R))||v&&r.audioCodec===L.audioCodec||E&&r.codecSet===L.codecSet||!v&&r.codecSet!==L.codecSet)continue}u=S;break}}if(u>-1&&s.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:St.SendAlternateToPenaltyBox,flags:Wt.None,nextAutoLevel:u}}return{action:St.SendAlternateToPenaltyBox,flags:Wt.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case St.DoNothing:break;case St.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==w.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:r}=s,n=s.nextAutoLevel;switch(r){case Wt.None:this.switchLevel(e,n);break;case Wt.MoveAllAlternatesMatchingHDCP:{const l=this.getVariantLevelIndex(e.frag),d=t.levels[l],u=d?.attrs["HDCP-LEVEL"];if(s.hdcpLevel=u,u==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(u){t.maxHdcpLevel=Fh[Fh.indexOf(u)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Wt.MoveAllAlternatesMatchingKey:{const l=e.decryptdata;if(l){const d=this.hls.levels,u=d.length;for(let h=u;h--;)if(this.variantHasKey(d[h],l)){var a,o;this.log(`Banned key found in level ${h} (${d[h].bitrate}bps) or audio group "${(a=d[h].audioGroups)==null?void 0:a.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${It(l.keyId||[])}`),d[h].fragmentError++,d[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h)}const c=e.frag;if(this.hls.levels.length<u)s.resolved=!0;else if(c&&c.type!==J.MAIN){const h=c.decryptdata;h&&!l.matches(h)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,n)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===w.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=$h(e.mimeType),r=this.hls.levels;for(let n=r.length;n--;)r[n][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${n} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(n))}}}function Nn(i){const e={action:St.DoNothing,flags:Wt.None};return i&&(e.resolved=!0),e}var gt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class qR{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let r=s.length;r--;){const n=s[r];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:r}=this,n=Object.keys(r);for(let a=n.length;a--;){const o=r[n[a]];if(o?.body.type===t&&(!s||o.buffered)){const l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,s,r,n){this.timeRanges&&(this.timeRanges[e]=t);const a=r?.fragment.sn||-1;Object.keys(this.fragments).forEach(o=>{const l=this.fragments[o];if(!l||a>=l.body.sn)return;if(!l.buffered&&(!l.loaded||n)){l.body.type===s&&this.removeFragment(l.body);return}const d=l.range[e];if(d){if(d.time.length===0){this.removeFragment(l.body);return}d.time.some(u=>{const c=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return c&&this.removeFragment(l.body),c})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,r=Yr(s),n=this.fragments[r];if(!n||n.buffered&&s.gap)return;const a=!s.relurl;Object.keys(t).forEach(o=>{const l=s.elementaryStreams[o];if(!l)return;const d=t[o],u=a||l.partial===!0;n.range[o]=this.getBufferedTimes(s,e.part,u,d)}),n.loaded=null,Object.keys(n.range).length?(this.bufferedEnd(n,s),jo(n)||this.removeParts(s.sn-1,s.type)):this.removeFragment(n.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Gg(s,r=>r.fragment.sn>=e))}fragBuffered(e,t){const s=Yr(e);let r=this.fragments[s];!r&&t&&(r=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e))}getBufferedTimes(e,t,s,r){const n={time:[],partial:s},a=e.start,o=e.end,l=e.minEndPTS||o,d=e.maxStartPTS||a;for(let u=0;u<r.length;u++){const c=r.start(u)-this.bufferPadding,h=r.end(u)+this.bufferPadding;if(d>=c&&l<=h){n.time.push({startPTS:Math.max(a,r.start(u)),endPTS:Math.min(o,r.end(u))});break}else if(a<h&&o>c){const f=Math.max(a,r.start(u)),m=Math.min(o,r.end(u));m>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:m}))}else if(o<=c)break}return n}getPartialFragment(e){let t=null,s,r,n,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(d=>{const u=l[d];u&&jo(u)&&(r=u.body.start-o,n=u.body.end+o,e>=r&&e<=n&&(s=Math.min(e-r,n-e),a<=s&&(t=u.body,a=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||jo(t))}getState(e){const t=Yr(e),s=this.fragments[t];return s?s.buffered?jo(s)?gt.PARTIAL:gt.OK:gt.APPENDING:gt.NOT_LOADED}isTimeBuffered(e,t,s){let r,n;for(let a=0;a<s.length;a++){if(r=s.start(a)-this.bufferPadding,n=s.end(a)+this.bufferPadding,e>=r&&t<=n)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const s=t.frag,r=t.part?null:t,n=Yr(s);this.fragments[n]={body:s,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:r,timeRanges:n,type:a}=t;if(s.sn==="initSegment")return;const o=s.type;if(r){let d=this.activePartLists[o];d||(this.activePartLists[o]=d=[]),d.push(r)}this.timeRanges=n;const l=n[a];this.detectEvictedFragments(a,l,o,r)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Yr(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let r=s.length;r--;){const n=t[s[r]];if(n?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,r,n){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==s||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(e){const t=Yr(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const r=e.sn;this.activePartLists[e.type]=Gg(s,n=>n.fragment.sn!==r)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(s=>s.clearElementaryStreamInfo())}}function jo(i){var e,t,s;return i.buffered&&!!(i.body.gap||(e=i.range.video)!=null&&e.partial||(t=i.range.audio)!=null&&t.partial||(s=i.range.audiovideo)!=null&&s.partial)}function Yr(i){return`${i.type}_${i.level}_${i.sn}`}function Gg(i,e){return i.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var Qs={cbc:0,ctr:1};class YR{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 Qs.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Qs.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 jR(i){const e=i.byteLength,t=e&&new DataView(i.buffer).getUint8(e-1);return t?i.slice(0,e-t):i}class zR{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 r=0;r<4;r++)s[r]=t.getUint32(r*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,r=s[0],n=s[1],a=s[2],o=s[3],l=this.invSubMix,d=l[0],u=l[1],c=l[2],h=l[3],f=new Uint32Array(256);let m=0,p=0,g=0;for(g=0;g<256;g++)g<128?f[g]=g<<1:f[g]=g<<1^283;for(g=0;g<256;g++){let v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^v&255^99,e[m]=v,t[v]=m;const b=f[m],E=f[b],T=f[E];let A=f[v]*257^v*16843008;r[m]=A<<24|A>>>8,n[m]=A<<16|A>>>16,a[m]=A<<8|A>>>24,o[m]=A,A=T*16843009^E*65537^b*257^m*16843008,d[v]=A<<24|A>>>8,u[v]=A<<16|A>>>16,c[v]=A<<8|A>>>24,h[v]=A,m?(m=b^f[f[f[T^b]]],p^=f[f[p]]):m=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,r=0;for(;r<t.length&&s;)s=t[r]===this.key[r],r++;if(s)return;this.key=t;const n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);const a=this.ksRows=(n+6+1)*4;let o,l;const d=this.keySchedule=new Uint32Array(a),u=this.invKeySchedule=new Uint32Array(a),c=this.sBox,h=this.rcon,f=this.invSubMix,m=f[0],p=f[1],g=f[2],v=f[3];let b,E;for(o=0;o<a;o++){if(o<n){b=d[o]=t[o];continue}E=b,o%n===0?(E=E<<8|E>>>24,E=c[E>>>24]<<24|c[E>>>16&255]<<16|c[E>>>8&255]<<8|c[E&255],E^=h[o/n|0]<<24):n>6&&o%n===4&&(E=c[E>>>24]<<24|c[E>>>16&255]<<16|c[E>>>8&255]<<8|c[E&255]),d[o]=b=(d[o-n]^E)>>>0}for(l=0;l<a;l++)o=a-l,l&3?E=d[o]:E=d[o-4],l<4||o<=4?u[l]=E:u[l]=m[c[E>>>24]]^p[c[E>>>16&255]]^g[c[E>>>8&255]]^v[c[E&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const r=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],d=o[1],u=o[2],c=o[3],h=this.uint8ArrayToUint32Array_(s);let f=h[0],m=h[1],p=h[2],g=h[3];const v=new Int32Array(e),b=new Int32Array(v.length);let E,T,A,x,S,L,R,I,M,B,q,z,K,H;const j=this.networkToHostOrderSwap;for(;t<v.length;){for(M=j(v[t]),B=j(v[t+1]),q=j(v[t+2]),z=j(v[t+3]),S=M^n[0],L=z^n[1],R=q^n[2],I=B^n[3],K=4,H=1;H<r;H++)E=l[S>>>24]^d[L>>16&255]^u[R>>8&255]^c[I&255]^n[K],T=l[L>>>24]^d[R>>16&255]^u[I>>8&255]^c[S&255]^n[K+1],A=l[R>>>24]^d[I>>16&255]^u[S>>8&255]^c[L&255]^n[K+2],x=l[I>>>24]^d[S>>16&255]^u[L>>8&255]^c[R&255]^n[K+3],S=E,L=T,R=A,I=x,K=K+4;E=a[S>>>24]<<24^a[L>>16&255]<<16^a[R>>8&255]<<8^a[I&255]^n[K],T=a[L>>>24]<<24^a[R>>16&255]<<16^a[I>>8&255]<<8^a[S&255]^n[K+1],A=a[R>>>24]<<24^a[I>>16&255]<<16^a[S>>8&255]<<8^a[L&255]^n[K+2],x=a[I>>>24]<<24^a[S>>16&255]<<16^a[L>>8&255]<<8^a[R&255]^n[K+3],b[t]=j(E^f),b[t+1]=j(x^m),b[t+2]=j(A^p),b[t+3]=j(T^g),f=M,m=B,p=q,g=z,t=t+4}return b.buffer}}class QR{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=XR(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function XR(i){switch(i){case Qs.cbc:return"AES-CBC";case Qs.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${i}`)}}const ZR=16;class Nm{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?jR(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,r){return this.useSoftware?new Promise((n,a)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,r);const l=this.flush();l?n(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,r)}softwareDecrypt(e,t,s,r){const{currentIV:n,currentResult:a,remainderData:o}=this;if(r!==Qs.cbc||t.byteLength!==16)return we.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=li(o,e),this.remainderData=null);const l=this.getValidChunk(e);if(!l.length)return null;n&&(s=n);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new zR),d.expandKey(t);const u=a;return this.currentResult=d.decrypt(l.buffer,0,s),this.currentIV=l.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,s,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,r));this.key=t,this.fastAesKey=new QR(this.subtle,t,r)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new YR(this.subtle,new Uint8Array(s),r).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(we.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,s,r)))}onWebCryptoError(e,t,s,r){const n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,r);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%ZR;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(we.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Kg=Math.pow(2,17);class JR{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 fs({type:ie.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(m=>m[0]==="GAP")){l(Wg(e));return}else e.gap=!1;const d=this.loader=n?new n(r):new a(r),u=Vg(e);e.loader=d;const c=Hg(r.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Kg};e.stats=d.stats;const f={onSuccess:(m,p,g,v)=>{this.resetLoader(e,d);let b=m.data;g.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(b.slice(0,16)),b=b.slice(16)),o({frag:e,part:null,payload:b,networkDetails:v})},onError:(m,p,g,v)=>{this.resetLoader(e,d),l(new fs({type:ie.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Ce({url:s,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:g,stats:v}))},onAbort:(m,p,g)=>{this.resetLoader(e,d),l(new fs({type:ie.NETWORK_ERROR,details:w.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:g,stats:m}))},onTimeout:(m,p,g)=>{this.resetLoader(e,d),l(new fs({type:ie.NETWORK_ERROR,details:w.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:m}))}};t&&(f.onProgress=(m,p,g,v)=>t({frag:e,part:null,payload:g,networkDetails:v})),d.load(u,h,f)})}loadPart(e,t,s){this.abort();const r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Wg(e,t));return}const d=this.loader=n?new n(r):new a(r),u=Vg(e,t);e.loader=d;const c=Hg(r.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Kg};t.stats=d.stats,d.load(u,h,{onSuccess:(f,m,p,g)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:f.data,networkDetails:g};s(v),o(v)},onError:(f,m,p,g)=>{this.resetLoader(e,d),l(new fs({type:ie.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Ce({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:g}))},onAbort:(f,m,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),l(new fs({type:ie.NETWORK_ERROR,details:w.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,m,p)=>{this.resetLoader(e,d),l(new fs({type:ie.NETWORK_ERROR,details:w.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(e,t){const s=e.stats,r=t.stats,n=r.total;if(s.loaded+=r.loaded,n){const l=Math.round(e.duration/t.duration),d=Math.min(Math.round(s.loaded/n),l),c=(l-d)*Math.round(s.loaded/d);s.total=s.loaded+c}else s.total=Math.max(s.loaded,s.total);const a=s.loading,o=r.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Vg(i,e=null){const t=e||i,s={frag:i,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},r=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(X(r)&&X(n)){var a;let o=r,l=n;if(i.sn==="initSegment"&&ek((a=i.decryptdata)==null?void 0:a.method)){const d=n-r;d%16&&(l=n+(16-d%16)),r!==0&&(s.resetIV=!0,o=r-16)}s.rangeStart=o,s.rangeEnd=l}return s}function Wg(i,e){const t=new Error(`GAP ${i.gap?"tag":"attribute"} found`),s={type:ie.MEDIA_ERROR,details:w.FRAG_GAP,fatal:!1,frag:i,error:t,networkDetails:null};return e&&(s.part=e),(e||i).stats.aborted=!0,new fs(s)}function ek(i){return i==="AES-128"||i==="AES-256"}class fs extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Wy extends di{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 Um{constructor(e,t,s,r=0,n=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=zo(),this.buffering={audio:zo(),video:zo(),audiovideo:zo()},this.level=e,this.sn=t,this.id=s,this.size=r,this.part=n,this.partial=a}}function zo(){return{start:0,executeStart:0,executeEnd:0,end:0}}const qg={length:0,start:()=>0,end:()=>0};class ue{static isBuffered(e,t){if(e){const s=ue.getBuffered(e);for(let r=s.length;r--;)if(t>=s.start(r)&&t<=s.end(r))return!0}return!1}static bufferedRanges(e){if(e){const t=ue.getBuffered(e);return ue.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 r=ue.bufferedRanges(e);if(r.length)return ue.bufferedInfo(r,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,c)=>u.start-c.start||c.end-u.end);let r=-1,n=[];if(s)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(r=u);const c=n.length;if(c){const h=n[c-1].end;e[u].start-h<s?e[u].end>h&&(n[c-1].end=e[u].end):n.push(e[u])}else n.push(e[u])}else n=e;let a=0,o,l=t,d=t;for(let u=0;u<n.length;u++){const c=n[u].start,h=n[u].end;if(r===-1&&t>=c&&t<=h&&(r=u),t+s>=c&&t<h)l=c,d=h,a=d-t;else if(t+s<c){o=c;break}}return{len:a,start:l||0,end:d||0,nextStart:o,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||qg}catch(t){return we.log("failed to get media.buffered",t),qg}}}const qy=/\{\$([a-zA-Z0-9-_]+)\}/g;function Yg(i){return qy.test(i)}function Hh(i,e){if(i.variableList!==null||i.hasVariableRefs){const t=i.variableList;return e.replace(qy,s=>{const r=s.substring(2,s.length-1),n=t?.[r];return n===void 0?(i.playlistParsingError||(i.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),s):n})}return e}function jg(i,e,t){let s=i.variableList;s||(i.variableList=s={});let r,n;if("QUERYPARAM"in e){r=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(r))n=a.get(r);else throw new Error(`"${r}" does not match any query parameter in URI: "${t}"`)}catch(a){i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else r=e.NAME,n=e.VALUE;r in s?i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):s[r]=n||""}function tk(i,e,t){const s=e.IMPORT;if(t&&s in t){let r=i.variableList;r||(i.variableList=r={}),r[s]=t[s]}else i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const ik=/^(\d+)x(\d+)$/,zg=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Ye{constructor(e,t){typeof e=="string"&&(e=Ye.parseAttrList(e,t)),Oe(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const s=new Uint8Array(t.length/2);for(let r=0;r<t.length/2;r++)s[r]=parseInt(t.slice(r*2,r*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((r,n)=>(r[n.toLowerCase()]=!0,r),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=ik.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const r={};for(zg.lastIndex=0;(s=zg.exec(e))!==null;){const a=s[1].trim();let o=s[2];const l=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1;let d=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(l||d))o=Hh(t,o);else if(!d&&!l)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":we.warn(`${e}: attribute ${a} is missing quotes`)}r[a]=o}return r}}const sk="com.apple.hls.interstitial";function rk(i){return i!=="ID"&&i!=="CLASS"&&i!=="CUE"&&i!=="START-DATE"&&i!=="DURATION"&&i!=="END-DATE"&&i!=="END-ON-NEXT"}function nk(i){return i==="SCTE35-OUT"||i==="SCTE35-IN"||i==="SCTE35-CMD"}class Yy{constructor(e,t,s=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(r=t?.tagOrder)!=null?r:s,t){const n=t.attr;for(const a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){we.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=Oe(new Ye({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const n=t?.endDate||new Date(this.attr["END-DATE"]);X(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(we.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(X(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===sk}get isValid(){return!!this.id&&!this._badValueForSameId&&X(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 ak=10;class ok{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?X(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||ak}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function eu(i,e){return i.length===e.length?!i.some((t,s)=>t!==e[s]):!1}function Qg(i,e){return!i&&!e?!0:!i||!e?!1:eu(i,e)}function Un(i){return i==="AES-128"||i==="AES-256"||i==="AES-256-CTR"}function $m(i){switch(i){case"AES-128":case"AES-256":return Qs.cbc;case"AES-256-CTR":return Qs.ctr;default:throw new Error(`invalid full segment method ${i}`)}}function Fm(i){return Uint8Array.from(atob(i),e=>e.charCodeAt(0))}function Gh(i){return Uint8Array.from(unescape(encodeURIComponent(i)),e=>e.charCodeAt(0))}function lk(i){const e=Gh(i).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function jy(i){const e=function(s,r,n){const a=s[r];s[r]=s[n],s[n]=a};e(i,0,3),e(i,1,2),e(i,4,5),e(i,6,7)}function zy(i){const e=i.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),r=s[s.length-1].split(",");if(r.length===2){const n=r[0]==="base64",a=r[1];n?(s.splice(-1,1),t=Fm(a)):t=lk(a)}}return t}const tu=typeof self<"u"?self:void 0;var je={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},xt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Kl(i){switch(i){case xt.FAIRPLAY:return je.FAIRPLAY;case xt.PLAYREADY:return je.PLAYREADY;case xt.WIDEVINE:return je.WIDEVINE;case xt.CLEARKEY:return je.CLEARKEY}}function _c(i){switch(i){case je.FAIRPLAY:return xt.FAIRPLAY;case je.PLAYREADY:return xt.PLAYREADY;case je.WIDEVINE:return xt.WIDEVINE;case je.CLEARKEY:return xt.CLEARKEY}}function ka(i){const{drmSystems:e,widevineLicenseUrl:t}=i,s=e?[je.FAIRPLAY,je.WIDEVINE,je.PLAYREADY,je.CLEARKEY].filter(r=>!!e[r]):[];return!s[je.WIDEVINE]&&t&&s.push(je.WIDEVINE),s}const Qy=(function(i){return tu!=null&&(i=tu.navigator)!=null&&i.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function dk(i,e,t,s){let r;switch(i){case je.FAIRPLAY:r=["cenc","sinf"];break;case je.WIDEVINE:case je.PLAYREADY:r=["cenc"];break;case je.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${i}`)}return uk(r,e,t,s)}function uk(i,e,t,s){return[{initDataTypes:i,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function ck(i){var e;return!!i&&(i.sessionType==="persistent-license"||!!((e=i.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Xy(i){const e=new Uint16Array(i.buffer,i.byteOffset,i.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 l=Fm(o).subarray(0,16);return jy(l),l}}return null}let jr={};class js{static clearKeyUriToKeyIdMap(){jr={}}static setKeyIdForUri(e,t){jr[e]=t}static addKeyIdForUri(e){const t=Object.keys(jr).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),jr[e]=s,s}constructor(e,t,s,r=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=r,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Un(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Iy(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&eu(e.keyFormatVersions,this.keyFormatVersions)&&Qg(e.iv,this.iv)&&Qg(e.keyId,this.keyId)}isSupported(){if(this.method){if(Un(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case xt.FAIRPLAY:case xt.WIDEVINE:case xt.PLAYREADY:case xt.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(Un(this.method)){let n=this.iv;return n||(typeof e!="number"&&(we.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),n=fk(e)),new js(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){const n=jr[this.uri];if(n&&!eu(this.keyId,n)&&js.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=zy(this.uri);if(s)switch(this.keyFormat){case xt.WIDEVINE:if(this.pssh=s,!this.keyId){const n=gR(s.buffer);if(n.length){var r;const a=n[0];this.keyId=(r=a.kids)!=null&&r.length?a.kids[0]:null}}this.keyId||(this.keyId=Xg(t));break;case xt.PLAYREADY:{const n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=pR(n,null,s),this.keyId=Xy(s);break}default:{let n=s.subarray(0,16);if(n.length!==16){const a=new Uint8Array(16);a.set(n,16-n.length),n=a}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n;n=hk(t),n||(n=Xg(t),n||(n=jr[this.uri])),n&&(this.keyId=n,js.setKeyIdForUri(this.uri,n))}return this}}function hk(i){const e=i?.[xt.WIDEVINE];return e?e.keyId:null}function Xg(i){const e=i?.[xt.PLAYREADY];if(e){const t=zy(e.uri);if(t)return Xy(t)}return null}function fk(i){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=i>>8*(15-t)&255;return e}const Zg=/#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,Jg=/#EXT-X-MEDIA:(.*)/g,mk=/^#EXT(?:INF|-X-TARGETDURATION):/m,Ac=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),pk=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 Xi{static findGroup(e,t){for(let s=0;s<e.length;s++){const r=e[s];if(r.id===t)return r}}static resolve(e,t){return Dm.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return mk.test(e)}static parseMasterPlaylist(e,t){const s=Yg(e),r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},n=[];if(Zg.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let a;for(;(a=Zg.exec(e))!=null;)if(a[1]){var o;const d=new Ye(a[1],r),u=Hh(r,a[2]),c={attrs:d,bitrate:d.decimalInteger("BANDWIDTH")||d.decimalInteger("AVERAGE-BANDWIDTH"),name:d.NAME,url:Xi.resolve(u,t)},h=d.decimalResolution("RESOLUTION");h&&(c.width=h.width,c.height=h.height),i0(d.CODECS,c);const f=d["SUPPLEMENTAL-CODECS"];f&&(c.supplemental={},i0(f,c.supplemental)),(o=c.unknownCodecs)!=null&&o.length||n.push(c),r.levels.push(c)}else if(a[3]){const d=a[3],u=a[4];switch(d){case"SESSION-DATA":{const c=new Ye(u,r),h=c["DATA-ID"];h&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[h]=c);break}case"SESSION-KEY":{const c=e0(u,t,r);c.encrypted&&c.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(c)):we.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const c=new Ye(u,r);jg(r,c,t)}break}case"CONTENT-STEERING":{const c=new Ye(u,r);r.contentSteering={uri:Xi.resolve(c["SERVER-URI"],t),pathwayId:c["PATHWAY-ID"]||"."};break}case"START":{r.startTimeOffset=t0(u);break}}}const l=n.length>0&&n.length<r.levels.length;return r.levels=l?n:r.levels,r.levels.length===0&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,s){let r;const n={},a=s.levels,o={AUDIO:a.map(d=>({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:a.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Jg.lastIndex=0;(r=Jg.exec(e))!==null;){const d=new Ye(r[1],s),u=d.TYPE;if(u){const c=o[u],h=n[u]||[];n[u]=h;const f=d.LANGUAGE,m=d["ASSOC-LANGUAGE"],p=d.CHANNELS,g=d.CHARACTERISTICS,v=d["INSTREAM-ID"],b={attrs:d,bitrate:0,id:l++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:u,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?Xi.resolve(d.URI,t):""};if(m&&(b.assocLang=m),p&&(b.channels=p),g&&(b.characteristics=g),v&&(b.instreamId=v),c!=null&&c.length){const E=Xi.findGroup(c,b.groupId)||c[0];s0(b,E,"audioCodec"),s0(b,E,"textCodec")}h.push(b)}}return n}static parseLevelPlaylist(e,t,s,r,n,a){var o;const l={url:t},d=new ok(t),u=d.fragments,c=[];let h=null,f=0,m=0,p=0,g=0,v=0,b=null,E=new yc(r,l),T,A,x,S=-1,L=!1,R=null,I;if(Ac.lastIndex=0,d.m3u8=e,d.hasVariableRefs=Yg(e),((o=Ac.exec(e))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(T=Ac.exec(e))!==null;){L&&(L=!1,E=new yc(r,l),E.playlistOffset=p,E.setStart(p),E.sn=f,E.cc=g,v&&(E.bitrate=v),E.level=s,h&&(E.initSegment=h,h.rawProgramDateTime&&(E.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),R&&(E.setByteRange(R),R=null)));const z=T[1];if(z){E.duration=parseFloat(z);const K=(" "+T[2]).slice(1);E.title=K||null,E.tagList.push(K?["INF",z,K]:["INF",z])}else if(T[3]){if(X(E.duration)){E.playlistOffset=p,E.setStart(p),x&&n0(E,x,d),E.sn=f,E.level=s,E.cc=g,u.push(E);const K=(" "+T[3]).slice(1);E.relurl=Hh(d,K),Kh(E,b,c),b=E,p+=E.duration,f++,m=0,L=!0}}else{if(T=T[0].match(pk),!T){we.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A<T.length&&T[A]===void 0;A++);const K=(" "+T[A]).slice(1),H=(" "+T[A+1]).slice(1),j=T[A+2]?(" "+T[A+2]).slice(1):null;switch(K){case"BYTERANGE":b?E.setByteRange(H,b):E.setByteRange(H);break;case"PROGRAM-DATE-TIME":E.rawProgramDateTime=H,E.tagList.push(["PROGRAM-DATE-TIME",H]),S===-1&&(S=u.length);break;case"PLAYLIST-TYPE":d.type&&os(d,K,T),d.type=H.toUpperCase();break;case"MEDIA-SEQUENCE":d.startSN!==0?os(d,K,T):u.length>0&&a0(d,K,T),f=d.startSN=parseInt(H);break;case"SKIP":{d.skippedSegments&&os(d,K,T);const G=new Ye(H,d),N=G.decimalInteger("SKIPPED-SEGMENTS");if(X(N)){d.skippedSegments+=N;for(let U=N;U--;)u.push(null);f+=N}const W=G.enumeratedString("RECENTLY-REMOVED-DATERANGES");W&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(W.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&os(d,K,T),d.targetduration=Math.max(parseInt(H),1);break;case"VERSION":d.version!==null&&os(d,K,T),d.version=parseInt(H);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||os(d,K,T),d.live=!1;break;case"#":(H||j)&&E.tagList.push(j?[H,j]:[H]);break;case"DISCONTINUITY":g++,E.tagList.push(["DIS"]);break;case"GAP":E.gap=!0,E.tagList.push([K]);break;case"BITRATE":E.tagList.push([K,H]),v=parseInt(H)*1e3,X(v)?E.bitrate=v:v=0;break;case"DATERANGE":{const G=new Ye(H,d),N=new Yy(G,d.dateRanges[G.ID],d.dateRangeTagCount);d.dateRangeTagCount++,N.isValid||d.skippedSegments?d.dateRanges[N.id]=N:we.warn(`Ignoring invalid DATERANGE tag: "${H}"`),E.tagList.push(["EXT-X-DATERANGE",H]);break}case"DEFINE":{{const G=new Ye(H,d);"IMPORT"in G?tk(d,G,a):jg(d,G,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?os(d,K,T):u.length>0&&a0(d,K,T),d.startCC=g=parseInt(H);break;case"KEY":{const G=e0(H,t,d);if(G.isSupported()){if(G.method==="NONE"){x=void 0;break}x||(x={});const N=x[G.keyFormat];N!=null&&N.matches(G)||(N&&(x=Oe({},x)),x[G.keyFormat]=G)}else we.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${H}"`);break}case"START":d.startTimeOffset=t0(H);break;case"MAP":{const G=new Ye(H,d);if(E.duration){const N=new yc(r,l);r0(N,G,s,x),h=N,E.initSegment=h,h.rawProgramDateTime&&!E.rawProgramDateTime&&(E.rawProgramDateTime=h.rawProgramDateTime)}else{const N=E.byteRangeEndOffset;if(N){const W=E.byteRangeStartOffset;R=`${N-W}@${W}`}else R=null;r0(E,G,s,x),h=E,L=!0}h.cc=g;break}case"SERVER-CONTROL":{I&&os(d,K,T),I=new Ye(H),d.canBlockReload=I.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=I.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&I.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=I.optionalFloat("PART-HOLD-BACK",0),d.holdBack=I.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&os(d,K,T);const G=new Ye(H);d.partTarget=G.decimalFloatingPoint("PART-TARGET");break}case"PART":{let G=d.partList;G||(G=d.partList=[]);const N=m>0?G[G.length-1]:void 0,W=m++,U=new Ye(H,d),$=new tR(U,E,l,W,N);G.push($),E.duration+=$.duration;break}case"PRELOAD-HINT":{const G=new Ye(H,d);d.preloadHint=G;break}case"RENDITION-REPORT":{const G=new Ye(H,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(G);break}default:we.warn(`line parsed but not handled: ${T}`);break}}}b&&!b.relurl?(u.pop(),p-=b.duration,d.partList&&(d.fragmentHint=b)):d.partList&&(Kh(E,b,c),E.cc=g,d.fragmentHint=E,x&&n0(E,x,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const M=u.length,B=u[0],q=u[M-1];if(p+=d.skippedSegments*d.targetduration,p>0&&M&&q){d.averagetargetduration=p/M;const z=q.sn;d.endSN=z!=="initSegment"?z:0,d.live||(q.endList=!0),S>0&&(vk(u,S),B&&c.unshift(B))}return d.fragmentHint&&(p+=d.fragmentHint.duration),d.totalduration=p,c.length&&d.dateRangeTagCount&&B&&Zy(c,d),d.endCC=g,d}}function Zy(i,e){let t=i.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];i.push(o),t++}else return;const s=i[t-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=s.ref;for(let u=t;u--;){var a;if(((a=i[u])==null?void 0:a.sn)<e.startSN)break;const c=gk(e,d,i,u,r);if(c!==-1){l.tagAnchor=e.fragments[c].ref;break}}}}function gk(i,e,t,s,r){const n=t[s];if(n){const o=n.programDateTime;if(e>=o||s===0){var a;const l=(((a=t[s+1])==null?void 0:a.start)||r)-n.start;if(e<=o+l*1e3){const d=t[s].sn-i.startSN;if(d<0)return-1;const u=i.fragments;if(u.length>t.length){const h=(t[s+1]||u[u.length-1]).sn-i.startSN;for(let f=h;f>d;f--){const m=u[f].programDateTime;if(e>=m&&e<m+u[f].duration*1e3)return f}}return d}}}return-1}function e0(i,e,t){var s,r;const n=new Ye(i,t),a=(s=n.METHOD)!=null?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,u=(r=n.KEYFORMAT)!=null?r:"identity";o&&n.IV&&!l&&we.error(`Invalid IV: ${n.IV}`);const c=o?Xi.resolve(o,e):"",h=(d||"1").split("/").map(Number).filter(Number.isFinite);return new js(a,c,u,h,l,n.KEYID)}function t0(i){const t=new Ye(i).decimalFloatingPoint("TIME-OFFSET");return X(t)?t:null}function i0(i,e){let t=(i||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const r=t.filter(n=>Mm(n,s));r.length&&(e[`${s}Codec`]=r.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>r.indexOf(n)===-1))}),e.unknownCodecs=t}function s0(i,e,t){const s=e[t];s&&(i[t]=s)}function vk(i,e){let t=i[e];for(let s=e;s--;){const r=i[s];if(!r)return;r.programDateTime=t.programDateTime-r.duration*1e3,t=r}}function Kh(i,e,t){i.rawProgramDateTime?t.push(i):e!=null&&e.programDateTime&&(i.programDateTime=e.endProgramDateTime)}function r0(i,e,t,s){i.relurl=e.URI,e.BYTERANGE&&i.setByteRange(e.BYTERANGE),i.level=t,i.sn="initSegment",s&&(i.levelkeys=s),i.initSegment=null}function n0(i,e,t){i.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(r=>e[r].isCommonEncryption)&&s.push(i)}function os(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function a0(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Sc(i,e){const t=e.startPTS;if(X(t)){let s=0,r;e.sn>i.sn?(s=t-i.start,r=i):(s=i.start-t,r=e),r.duration!==s&&r.setDuration(s)}else e.sn>i.sn?i.cc===e.cc&&i.minEndPTS?e.setStart(i.start+(i.minEndPTS-i.start)):e.setStart(i.start+i.duration):e.setStart(Math.max(i.start-e.duration,0))}function Jy(i,e,t,s,r,n,a){s-t<=0&&(a.warn("Fragment should have a positive duration",e),s=t+e.duration,n=r+e.duration);let l=t,d=s;const u=e.startPTS,c=e.endPTS;if(X(u)){const v=Math.abs(u-t);i&&v>i.totalduration?a.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${i.url}`):X(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,l=Math.max(t,u),t=Math.min(t,u),r=e.startDTS!==void 0?Math.min(r,e.startDTS):r,d=Math.min(s,c),s=Math.max(s,c),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n}const h=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=l,e.startDTS=r,e.endPTS=s,e.minEndPTS=d,e.endDTS=n;const f=e.sn;if(!i||f<i.startSN||f>i.endSN)return 0;let m;const p=f-i.startSN,g=i.fragments;for(g[p]=e,m=p;m>0;m--)Sc(g[m],g[m-1]);for(m=p;m<g.length-1;m++)Sc(g[m],g[m+1]);return i.fragmentHint&&Sc(g[g.length-1],i.fragmentHint),i.PTSKnown=i.alignedSliding=!0,h}function Ek(i,e,t){if(i===e)return;let s=null;const r=i.fragments;for(let u=r.length-1;u>=0;u--){const c=r[u].initSegment;if(c){s=c;break}}i.fragmentHint&&delete i.fragmentHint.endPTS;let n;Tk(i,e,(u,c,h,f)=>{if((!e.startCC||e.skippedSegments)&&c.cc!==u.cc){const m=u.cc-c.cc;for(let p=h;p<f.length;p++)f[p].cc+=m;e.endCC=f[f.length-1].cc}X(u.startPTS)&&X(u.endPTS)&&(c.setStart(c.startPTS=u.startPTS),c.startDTS=u.startDTS,c.maxStartPTS=u.maxStartPTS,c.endPTS=u.endPTS,c.endDTS=u.endDTS,c.minEndPTS=u.minEndPTS,c.setDuration(u.endPTS-u.startPTS),c.duration&&(n=c),e.PTSKnown=e.alignedSliding=!0),u.hasStreams&&(c.elementaryStreams=u.elementaryStreams),c.loader=u.loader,u.hasStats&&(c.stats=u.stats),u.initSegment&&(c.initSegment=u.initSegment,s=u.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(s&&o.forEach(u=>{var c;u&&(!u.initSegment||u.initSegment.relurl===((c=s)==null?void 0:c.relurl))&&(u.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(u=>!u),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=e.skippedSegments;u--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=yk(i.dateRanges,e,t));const u=i.fragments.filter(c=>c.rawProgramDateTime);if(i.hasProgramDateTime&&!e.hasProgramDateTime)for(let c=1;c<o.length;c++)o[c].programDateTime===null&&Kh(o[c],o[c-1],u);Zy(u,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const u=ib(i,e.startSN-1);e.startCC=(l=u?.cc)!=null?l:a[0].cc}bk(i.partList,e.partList,(u,c)=>{c.elementaryStreams=u.elementaryStreams,c.stats=u.stats}),n?Jy(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,t):eb(i,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=i.driftStartTime,e.driftStart=i.driftStart;const d=e.advancedDateTime;if(e.advanced&&d){const u=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=u),e.driftEndTime=d,e.driftEnd=u}else e.driftEndTime=i.driftEndTime,e.driftEnd=i.driftEnd,e.advancedDateTime=i.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=i.requestScheduled)}function yk(i,e,t){const{dateRanges:s,recentlyRemovedDateranges:r}=e,n=Oe({},i);r&&r.forEach(l=>{delete n[l]});const o=Object.keys(n).length;return o?(Object.keys(s).forEach(l=>{const d=n[l],u=new Yy(s[l].attr,d);u.isValid?(n[l]=u,d||(u.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${$e(s[l].attr)}"`)}),n):s}function bk(i,e,t){if(i&&e){let s=0;for(let r=0,n=i.length;r<=n;r++){const a=i[r],o=e[r+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):s--}}}function Tk(i,e,t){const s=e.skippedSegments,r=Math.max(i.startSN,e.startSN)-e.startSN,n=(i.fragmentHint?1:0)+(s?e.endSN:Math.min(i.endSN,e.endSN))-e.startSN,a=e.startSN-i.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=i.fragmentHint?i.fragments.concat(i.fragmentHint):i.fragments;for(let d=r;d<=n;d++){const u=l[a+d];let c=o[d];if(s&&!c&&u&&(c=e.fragments[d]=u),u&&c){t(u,c,d,o);const h=u.relurl,f=c.relurl;if(h&&_k(h,f)){e.playlistParsingError=o0(`media sequence mismatch ${c.sn}:`,i,e,u,c);return}else if(u.cc!==c.cc){e.playlistParsingError=o0(`discontinuity sequence mismatch (${u.cc}!=${c.cc})`,i,e,u,c);return}}}}function o0(i,e,t,s,r){return new Error(`${i} ${r.url}
|
|
1428
1428
|
Playlist starting @${e.startSN}
|
|
1429
1429
|
${e.m3u8}
|
|
1430
1430
|
|
|
1431
1431
|
Playlist starting @${t.startSN}
|
|
1432
|
-
${t.m3u8}`)}function eb(i,e,t=!0){const s=e.startSN+e.skippedSegments-i.startSN,r=i.fragments,n=s>=0;let a=0;if(n&&s<r.length)a=r[s].start;else if(n&&e.startSN===i.endSN+1)a=i.fragmentEnd;else if(n&&t)a=i.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=i.fragmentStart;else return;Vh(e,a)}function Vh(i,e){if(e){const t=i.fragments;for(let s=i.skippedSegments;s<t.length;s++)t[s].addStart(e);i.fragmentHint&&i.fragmentHint.addStart(e)}}function tb(i,e=1/0){let t=1e3*i.targetduration;if(i.updated){const s=i.fragments;if(s.length&&t*4>e){const n=s[s.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function ib(i,e,t){if(!i)return null;let s=i.fragments[e-i.startSN];return s||(s=i.fragmentHint,s&&s.sn===e)?s:e<i.startSN&&t&&t.sn===e?t:null}function l0(i,e,t){return i?sb(i.partList,e,t):null}function sb(i,e,t){if(i)for(let s=i.length;s--;){const r=i[s];if(r.index===t&&r.fragment.sn===e)return r}return null}function rb(i){i.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(r=>{r.level=t,r.initSegment&&(r.initSegment.level=t)})})}function _k(i,e){return i!==e&&e?d0(i)!==d0(e):!1}function d0(i){return i.replace(/\?[^?]*$/,"")}function za(i,e){for(let s=0,r=i.length;s<r;s++){var t;if(((t=i[s])==null?void 0:t.cc)===e)return i[s]}return null}function Ak(i,e){return!!(i&&e.startCC<i.endCC&&e.endCC>i.startCC)}function u0(i,e){const t=i.start+e;i.startPTS=t,i.setStart(t),i.endPTS=t+i.duration}function nb(i,e){const t=e.fragments;for(let s=0,r=t.length;s<r;s++)u0(t[s],i);e.fragmentHint&&u0(e.fragmentHint,i),e.alignedSliding=!0}function Sk(i,e){i&&(ab(e,i),e.alignedSliding||iu(e,i),!e.alignedSliding&&!e.skippedSegments&&eb(i,e,!1))}function ab(i,e){if(!Ak(e,i))return;const t=Math.min(e.endCC,i.endCC),s=za(e.fragments,t),r=za(i.fragments,t);if(!s||!r)return;we.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const n=s.start-r.start;nb(n,i)}function iu(i,e){if(!i.hasProgramDateTime||!e.hasProgramDateTime)return;const t=i.fragments,s=e.fragments;if(!t.length||!s.length)return;let r,n;const a=Math.min(e.endCC,i.endCC);e.startCC<a&&i.startCC<a&&(r=za(s,a),n=za(t,a)),(!r||!n)&&(r=s[Math.floor(s.length/2)],n=za(t,r.cc)||t[Math.floor(t.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;const d=(l-o)/1e3-(n.start-r.start);nb(d,i)}function wt(i,e,t){Nt(i,e,t),i.addEventListener(e,t)}function Nt(i,e,t){i.removeEventListener(e,t)}const Ik={toString:function(i){let e="";const t=i.length;for(let s=0;s<t;s++)e+=`[${i.start(s).toFixed(3)}-${i.end(s).toFixed(3)}]`;return e}},O={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 Bm extends Wy{constructor(e,t,s,r,n){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=O.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:l,mediaBuffer:d,state:u}=this,c=l?l.currentTime:0,h=ue.bufferInfo(d||l,c,a.maxBufferHole),f=!h.len;if(this.log(`Media seeking to ${Q(c)?c.toFixed(3):c}, state: ${u}, ${f?"out of":"in"} buffer`),this.state===O.ENDED)this.resetLoadingState();else if(o){const m=a.maxFragLookUpTolerance,p=o.start-m,g=o.start+o.duration+m;if(f||g<h.start||p>h.end){const v=c>g;(c<p||v)&&(v&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0);const m=this.lastCurrentTime;if(c>m&&(this.lastCurrentTime=c),!this.loadingParts){const p=Math.max(h.end,c),g=this.shouldLoadParts(this.getLevelDetails(),p);g&&(this.log(`LL-Part loading ON after seeking to ${c.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=g)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${c} for seek without enough to start`),this.nextLoadPosition=c,f&&(this.startPosition=c)),f&&this.state===O.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=e,this.fragmentLoader=new JR(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Nm(e.config)}registerListeners(){const{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===O.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=O.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,r=this.config.timelineOffset||0;if(s<=r)return!1;const n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=ue.bufferedInfo(n,e.start,0));const a=e.nextStart;if(a&&a>r&&a<t.edge||this.media.currentTime<e.start)return!1;const l=t.partList;if(l!=null&&l.length){const u=l[l.length-1];return ue.isBuffered(this.media,u.start+u.duration/2)}const d=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(d)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;wt(s,"seeking",this.onMediaSeeking),wt(s,"ended",this.onMediaEnded);const r=this.config;this.levels&&r.autoStartLoad&&this.state===O.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,r=this.media;if(r!==null){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Nt(r,"seeking",this.onMediaSeeking),Nt(r,"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=O.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 r=n=>{const a=n.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,!1,n.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,s,r).then(n=>{if(!n)return;const a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===O.FRAG_LOADING||!this.fragCurrent&&a===O.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=O.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(y.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===O.STOPPED||this.state===O.ERROR||(this.warn(`Frag error: ${n?.message||n}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===gt.APPENDING){const n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.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)===gt.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const r={startOffset:e,endOffset:t,type:s};this.hls.trigger(y.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const r=s?.frag;if(!r||this.fragContextChanged(r)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:r}=this,{frag:n,payload:a}=s,o=n.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&Un(o.method)){const l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,$m(o.method)).catch(d=>{throw r.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:n}),d}).then(d=>{const u=self.performance.now();return r.trigger(y.FRAG_DECRYPTED,{frag:n,payload:d,stats:{tstart:l,tdecrypt:u}}),s.payload=d,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===O.STOPPED||this.state===O.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!==O.STOPPED&&(this.state=O.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,r;const n=e.tracks;if(n&&!t.encrypted&&((s=n.audio)!=null&&s.encrypted||(r=n.video)!=null&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(y.ERROR,{type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?Ik.toString(ue.getBuffered(s)):"(detached)"})`),et(e)){var r;if(e.type!==J.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=O.IDLE;return}}const n=(r=this.levels)==null?void 0:r[e.level];n!=null&&n.fragmentError&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0)}this.state=O.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:r,partsLoaded:n}=e,a=!n||n.length===0||n.some(l=>!l),o=new Um(s.level,s.sn,s.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,r){var n;this.fragCurrent=e;const a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((n=e.decryptdata)!=null&&n.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=O.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(y.KEY_LOADED,h),this.state===O.KEY_LOADING&&(this.state=O.IDLE),h}),this.hls.trigger(y.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const l=this.fragPrevious;if(et(e)&&(!l||e.sn!==l.sn)){const h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${l?.sn}->${e.sn}`),this.loadingParts=h)}if(s=Math.max(e.start,s||0),this.loadingParts&&et(e)){const h=a.partList;if(h&&r){s>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const f=this.getNextPart(h,e,s);if(f>-1){const m=h[f];e=this.fragCurrent=m.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${f}/${h.length-1}) of ${this.fragInfo(e,!1,m)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=m.start+m.duration,this.state=O.FRAG_LOADING;let p;return o?p=o.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,m,t,r)).catch(g=>this.handleFragLoadError(g)):p=this.doFragPartsLoad(e,m,t,r).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(y.FRAG_LOADING,{frag:e,part:m,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(h,s))return Promise.resolve(null)}}if(et(e)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(d=a.partList)==null?void 0:d.filter(h=>h.loaded).map(h=>`[${h.start}-${h.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),Q(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=O.FRAG_LOADING;const u=this.config.progressive&&e.type!==J.SUBTITLE;let c;return u&&o?c=o.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,r)).catch(h=>this.handleFragLoadError(h)):c=Promise.all([this.fragmentLoader.load(e,u?r:void 0),o]).then(([h])=>(!u&&r&&r(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(y.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,s,r){return new Promise((n,a)=>{var o;const l=[],d=(o=s.details)==null?void 0:o.partList,u=c=>{this.fragmentLoader.loadPart(e,c,r).then(h=>{l[c.index]=h;const f=h.part;this.hls.trigger(y.FRAG_LOADED,h);const m=l0(s.details,e.sn,c.index+1)||sb(d,e.sn,c.index+1);if(m)u(m);else return n({frag:e,part:f,partsLoaded:l})}).catch(a)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===w.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===ie.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(y.ERROR,t)}else this.hls.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==O.PARSING){!this.fragCurrent&&this.state!==O.STOPPED&&this.state!==O.ERROR&&(this.state=O.IDLE);return}const{frag:s,part:r,level:n}=t,a=self.performance.now();s.stats.parsing.end=a,r&&(r.stats.parsing.end=a);const o=this.getLevelDetails(),d=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(s,r,n,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const n=e.partList[0];if(n.fragment.type===J.SUBTITLE)return!1;const a=n.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=a){var r;if((this.hls.hasEnoughToStart?((r=this.media)==null?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:r,sn:n,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;const o=t[r],l=o.details,d=a>-1?l0(l,n,a):null,u=d?d.fragment:ib(l,n,s);return u?(s&&s!==u&&(u.stats=s.stats),{frag:u,part:d,level:o}):null}bufferFragmentData(e,t,s,r,n){if(this.state!==O.PARSING)return;const{data1:a,data2:o}=e;let l=a;if(o&&(l=li(a,o)),!l.length)return;const d=this.initPTS[t.cc],u=d?-d.baseTime/d.timescale:void 0,c={type:e.type,frag:t,part:s,chunkMeta:r,offset:u,parent:t.type,data:l};if(this.hls.trigger(y.BUFFER_APPENDING,c),e.dropped&&e.independent&&!s){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!ue.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,r=ue.bufferInfo(t,s,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,r.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;const r=this.getLoadPosition();if(!Q(r))return null;const a=this.lastCurrentTime>r||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,a)}getFwdBufferInfoAtPos(e,t,s,r){const n=ue.bufferInfo(e,t,r);if(n.len===0&&n.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&(n.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(n.nextStart,a.end)-t,r);return ue.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,r=Math.max(Math.min(e-t,s.maxBufferLength),t),n=Math.max(e-t*3,s.maxMaxBufferLength/2,r);return n>=r?(s.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(e,t=J.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,r=s.length;if(!r)return null;const{config:n}=this,a=s[0].start,o=n.lowLatencyMode&&!!t.partList;let l=null;if(t.live){const c=n.initialLiveManifestSize;if(r<c)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${c})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var d;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(t);const h=this.hls.startPosition,f=this.hls.liveSyncPosition,m=l?(h!==-1&&h>=a?h:f)||l.start:e;this.log(`Setting startPosition to ${m} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${f} frag.start: ${(d=l)==null?void 0:d.start}`),this.startPosition=this.nextLoadPosition=m}}else e<=a&&(l=s[0]);if(!l){const c=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,c,t)}let u=this.filterReplacedPrimary(l,t);if(!u&&l){const c=l.sn-t.startSN;u=this.filterReplacedPrimary(s[c+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===gt.OK||s===gt.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,r,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,r,0);if(o!==null&&s.len+o.len>=n){const l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(c0(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(c0(this.config)&&e.type!==J.SUBTITLE){const s=this.hls.interstitialsManager,r=s?.bufferingItem;if(r){const a=r.event;if(a){if(a.appendInPlace||Math.abs(e.start-r.start)>1||r.start===0)return null}else if(e.end<=r.start&&t?.live===!1||e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}const n=s?.playerQueue;if(n)for(let a=n.length;a--;){const o=n[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let r=-1,n=!1,a=!0;for(let o=0,l=e.length;o<l;o++){const d=e[o];if(a=a&&!d.independent,r>-1&&s<d.start)break;const u=d.loaded;u?r=-1:(n||(d.independent||a)&&d.fragment===t)&&(d.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${d.start}`),r=o),n=u}return r}loadedEndOfParts(e,t){let s;for(let r=e.length;r--;){if(s=e[r],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let r=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),r=HR(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const n=s.sn+1;if(n>=e.startSN&&n<=e.endSN){const a=t[n-e.startSN];s.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=Gy(e,s.cc,s.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const n=this.hls.liveSyncPosition;n!==null&&(r=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,s){const{config:r}=this;let{fragPrevious:n}=this,{fragments:a,endSN:o}=s;const{fragmentHint:l}=s,{maxFragLookUpTolerance:d}=r,u=s.partList,c=!!(this.loadingParts&&u!=null&&u.length&&l);c&&!this.bitrateTest&&u[u.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn);let h;if(e<t){var f;const p=e<this.lastCurrentTime||e>t-d||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:d;h=Mr(n,a,e,p)}else h=a[a.length-1];if(h){const m=h.sn-s.startSN,p=this.fragmentTracker.getState(h);if((p===gt.OK||p===gt.PARTIAL&&h.gap)&&(n=h),n&&h.sn===n.sn&&(!c||u[0].fragment.sn>h.sn||!s.live)&&h.level===n.level){const v=a[m+1];h.sn<o&&this.fragmentTracker.getState(v)!==gt.OK?h=v:h=null}}return h}alignPlaylists(e,t,s){const r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const n=e.fragmentStart,a=!t,o=e.alignedSliding&&Q(n);if(a||!o&&!n){Sk(s,e);const l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${r}`),l}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const r=this.timelineOffset;if(s===-1){const n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;a!==null&&Q(a)?(s=t+a,a<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+r}this.nextLoadPosition=s+r}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&&et(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==O.FRAG_LOADING_WAITING_RETRY)&&(this.state=O.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const v=this.getCurrentContext(t.chunkMeta);v&&(t.frag=v.frag)}const r=t.frag;if(!r||r.type!==e||!this.levels)return;if(this.fragContextChanged(r)){var n;this.warn(`Frag load error must match current frag to retry ${r.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}const a=t.details===w.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(r,!0);const o=t.errorAction;if(!o){this.state=O.ERROR;return}const{action:l,flags:d,retryCount:u=0,retryConfig:c}=o,h=!!c,f=h&&l===St.RetryRequest,m=h&&!o.resolved&&d===Wt.MoveAllAlternatesMatchingHost,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!f&&m&&et(r)&&!r.endList&&p&&!Vy(t))this.resetFragmentErrors(e),this.treatAsGap(r),o.resolved=!0;else if((f||m)&&u<c.maxNumRetry){var g;const v=Bh((g=t.response)==null?void 0:g.code),b=Om(c,u);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+b,this.state=O.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,v){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${u+1}/${c.maxNumRetry} in ${b}ms`)}else if(c)if(this.resetFragmentErrors(e),u<c.maxNumRetry)!a&&l!==St.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${u})`);return}else l===St.SendAlternateToPenaltyBox?this.state=O.WAITING_LEVEL:this.state=O.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Bh(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=O.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===O.PARSING||this.state===O.PARSED){const t=e.frag,s=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,s),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.len,t?.duration||10);const a=!n;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===J.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==O.STOPPED&&(this.state=O.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const r=ue.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,s),this.state===O.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==O.STOPPED&&(this.state=O.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,r){const n=s.details;if(!n){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,d)=>{const u=e.elementaryStreams[d];if(u){const c=u.endPTS-u.startPTS;if(c<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${c})`),l||!1;const h=r?0:Jy(n,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(y.LEVEL_PTS_UPDATED,{details:n,level:s,drift:h,type:d,frag:e,start:u.startPTS,end:u.endPTS}),!0}return l},!1)){var o;const l=((o=this.transmuxer)==null?void 0:o.error)===null;if((s.fragmentError===0||l&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),l){const d=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(d.message),this.hls.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,error:d,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=O.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(y.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===J.MAIN?"level":"track"}fragInfo(e,t=!0,s){var r,n;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((r=t&&!s?e.startPTS:(s||e).start)!=null?r:NaN).toFixed(3)}-${((n=t&&!s?e.endPTS:(s||e).end)!=null?n:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function c0(i){return!!i.interstitialsController&&i.enableInterstitialPlayback!==!1}class ob{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=xk(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function xk(i,e){const t=new Uint8Array(e);let s=0;for(let r=0;r<i.length;r++){const n=i[r];t.set(n,s),s+=n.length}return t}var Ic={exports:{}},h0;function Lk(){return h0||(h0=1,(function(i){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function r(l,d,u){this.fn=l,this.context=d,this.once=u||!1}function n(l,d,u,c,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new r(u,c||l,h),m=t?t+d:d;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],f]:l._events[m].push(f):(l._events[m]=f,l._eventsCount++),l}function a(l,d){--l._eventsCount===0?l._events=new s:delete l._events[d]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],u,c;if(this._eventsCount===0)return d;for(c in u=this._events)e.call(u,c)&&d.push(t?c.slice(1):c);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(u)):d},o.prototype.listeners=function(d){var u=t?t+d:d,c=this._events[u];if(!c)return[];if(c.fn)return[c.fn];for(var h=0,f=c.length,m=new Array(f);h<f;h++)m[h]=c[h].fn;return m},o.prototype.listenerCount=function(d){var u=t?t+d:d,c=this._events[u];return c?c.fn?1:c.length:0},o.prototype.emit=function(d,u,c,h,f,m){var p=t?t+d:d;if(!this._events[p])return!1;var g=this._events[p],v=arguments.length,b,E;if(g.fn){switch(g.once&&this.removeListener(d,g.fn,void 0,!0),v){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,u),!0;case 3:return g.fn.call(g.context,u,c),!0;case 4:return g.fn.call(g.context,u,c,h),!0;case 5:return g.fn.call(g.context,u,c,h,f),!0;case 6:return g.fn.call(g.context,u,c,h,f,m),!0}for(E=1,b=new Array(v-1);E<v;E++)b[E-1]=arguments[E];g.fn.apply(g.context,b)}else{var T=g.length,A;for(E=0;E<T;E++)switch(g[E].once&&this.removeListener(d,g[E].fn,void 0,!0),v){case 1:g[E].fn.call(g[E].context);break;case 2:g[E].fn.call(g[E].context,u);break;case 3:g[E].fn.call(g[E].context,u,c);break;case 4:g[E].fn.call(g[E].context,u,c,h);break;default:if(!b)for(A=1,b=new Array(v-1);A<v;A++)b[A-1]=arguments[A];g[E].fn.apply(g[E].context,b)}}return!0},o.prototype.on=function(d,u,c){return n(this,d,u,c,!1)},o.prototype.once=function(d,u,c){return n(this,d,u,c,!0)},o.prototype.removeListener=function(d,u,c,h){var f=t?t+d:d;if(!this._events[f])return this;if(!u)return a(this,f),this;var m=this._events[f];if(m.fn)m.fn===u&&(!h||m.once)&&(!c||m.context===c)&&a(this,f);else{for(var p=0,g=[],v=m.length;p<v;p++)(m[p].fn!==u||h&&!m[p].once||c&&m[p].context!==c)&&g.push(m[p]);g.length?this._events[f]=g.length===1?g[0]:g:a(this,f)}return this},o.prototype.removeAllListeners=function(d){var u;return d?(u=t?t+d:d,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,i.exports=o})(Ic)),Ic.exports}var Rk=Lk(),Hm=JL(Rk);const vo="1.6.15",Zn={};function kk(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Dk(){const i=Zn[vo];if(i)return i.clientCount++,i;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),r={worker:new self.Worker(t),objectURL:t,clientCount:1};return Zn[vo]=r,r}function Ck(i){const e=Zn[i];if(e)return e.clientCount++,e;const t=new self.URL(i,self.location.href).href,r={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Zn[i]=r,r}function wk(i){const e=Zn[i||vo];if(e&&e.clientCount--===1){const{worker:s,objectURL:r}=e;delete Zn[i||vo],r&&self.URL.revokeObjectURL(r),s.terminate()}}function lb(i,e){return e+10<=i.length&&i[e]===51&&i[e+1]===68&&i[e+2]===73&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function Gm(i,e){return e+10<=i.length&&i[e]===73&&i[e+1]===68&&i[e+2]===51&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function Yu(i,e){let t=0;return t=(i[e]&127)<<21,t|=(i[e+1]&127)<<14,t|=(i[e+2]&127)<<7,t|=i[e+3]&127,t}function Eo(i,e){const t=e;let s=0;for(;Gm(i,e);){s+=10;const r=Yu(i,e+6);s+=r,lb(i,e+10)&&(s+=10),e+=s}if(s>0)return i.subarray(t,t+s)}function Mk(i,e,t,s){const r=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[t+2],a=n>>2&15;if(a>12){const f=new Error(`invalid ADTS sampling index:${a}`);i.emit(y.ERROR,y.ERROR,{type:ie.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(n>>6&3)+1,l=e[t+3]>>6&3|(n&1)<<2,d="mp4a.40."+o,u=r[a];let c=a;(o===5||o===29)&&(c-=3);const h=[o<<3|(c&14)>>1,(c&1)<<7|l<<3];return we.log(`manifest codec:${s}, parsed codec:${d}, channels:${l}, rate:${u} (ADTS object type:${o} sampling index:${a})`),{config:h,samplerate:u,channelCount:l,codec:d,parsedCodec:d,manifestCodec:s}}function db(i,e){return i[e]===255&&(i[e+1]&246)===240}function ub(i,e){return i[e+1]&1?7:9}function Km(i,e){return(i[e+3]&3)<<11|i[e+4]<<3|(i[e+5]&224)>>>5}function Pk(i,e){return e+5<i.length}function su(i,e){return e+1<i.length&&db(i,e)}function Ok(i,e){return Pk(i,e)&&db(i,e)&&Km(i,e)<=i.length-e}function Nk(i,e){if(su(i,e)){const t=ub(i,e);if(e+t>=i.length)return!1;const s=Km(i,e);if(s<=t)return!1;const r=e+s;return r===i.length||su(i,r)}return!1}function cb(i,e,t,s,r){if(!i.samplerate){const n=Mk(e,t,s,r);if(!n)return;Oe(i,n)}}function hb(i){return 1024*9e4/i}function Uk(i,e){const t=ub(i,e);if(e+t<=i.length){const s=Km(i,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function fb(i,e,t,s,r){const n=hb(i.samplerate),a=s+r*n,o=Uk(e,t);let l;if(o){const{frameLength:c,headerLength:h}=o,f=h+c,m=Math.max(0,t+f-e.length);m?(l=new Uint8Array(f-h),l.set(e.subarray(t+h,e.length),0)):l=e.subarray(t+h,t+f);const p={unit:l,pts:a};return m||i.samples.push(p),{sample:p,length:f,missing:m}}const d=e.length-t;return l=new Uint8Array(d),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:d,missing:-1}}function $k(i,e){return Gm(i,e)&&Yu(i,e+6)+10<=i.length-e}function Fk(i){return i instanceof ArrayBuffer?i:i.byteOffset==0&&i.byteLength==i.buffer.byteLength?i.buffer:new Uint8Array(i).buffer}function xc(i,e=0,t=1/0){return Bk(i,e,t,Uint8Array)}function Bk(i,e,t,s){const r=Hk(i);let n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);const a=Gk(i)?i.byteOffset:0,o=(a+i.byteLength)/n,l=(a+e)/n,d=Math.floor(Math.max(0,Math.min(l,o))),u=Math.floor(Math.min(d+Math.max(t,0),o));return new s(r,d,u-d)}function Hk(i){return i instanceof ArrayBuffer?i:i.buffer}function Gk(i){return i&&i.buffer instanceof ArrayBuffer&&i.byteLength!==void 0&&i.byteOffset!==void 0}function Kk(i){const e={key:i.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(i.size<2)return;if(i.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const s=i.data.subarray(1).indexOf(0);if(s===-1)return;const r=Xt(xc(i.data,1,s)),n=i.data[2+s],a=i.data.subarray(3+s).indexOf(0);if(a===-1)return;const o=Xt(xc(i.data,3+s,a));let l;return r==="-->"?l=Xt(xc(i.data,4+s+a)):l=Fk(i.data.subarray(4+s+a)),e.mimeType=r,e.pictureType=n,e.description=o,e.data=l,e}function Vk(i){if(i.size<2)return;const e=Xt(i.data,!0),t=new Uint8Array(i.data.subarray(e.length+1));return{key:i.type,info:e,data:t.buffer}}function Wk(i){if(i.size<2)return;if(i.type==="TXXX"){let t=1;const s=Xt(i.data.subarray(t),!0);t+=s.length+1;const r=Xt(i.data.subarray(t));return{key:i.type,info:s,data:r}}const e=Xt(i.data.subarray(1));return{key:i.type,info:"",data:e}}function qk(i){if(i.type==="WXXX"){if(i.size<2)return;let t=1;const s=Xt(i.data.subarray(t),!0);t+=s.length+1;const r=Xt(i.data.subarray(t));return{key:i.type,info:s,data:r}}const e=Xt(i.data);return{key:i.type,info:"",data:e}}function Yk(i){return i.type==="PRIV"?Vk(i):i.type[0]==="W"?qk(i):i.type==="APIC"?Kk(i):Wk(i)}function jk(i){const e=String.fromCharCode(i[0],i[1],i[2],i[3]),t=Yu(i,4),s=10;return{type:e,size:t,data:i.subarray(s,s+t)}}const Qo=10,zk=10;function mb(i){let e=0;const t=[];for(;Gm(i,e);){const s=Yu(i,e+6);i[e+5]>>6&1&&(e+=Qo),e+=Qo;const r=e+s;for(;e+zk<r;){const n=jk(i.subarray(e)),a=Yk(n);a&&t.push(a),e+=n.size+Qo}lb(i,e)&&(e+=Qo)}return t}function pb(i){return i&&i.key==="PRIV"&&i.info==="com.apple.streaming.transportStreamTimestamp"}function Qk(i){if(i.data.byteLength===8){const e=new Uint8Array(i.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 Vm(i){const e=mb(i);for(let t=0;t<e.length;t++){const s=e[t];if(pb(s))return Qk(s)}}let zt=(function(i){return i.audioId3="org.id3",i.dateRange="com.apple.quicktime.HLS",i.emsg="https://aomedia.org/emsg/ID3",i.misbklv="urn:misb:KLV:bin:1910.1",i})({});function Yi(i="",e=9e4){return{type:i,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Wm{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,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=li(this.cachedData,e),this.cachedData=null);let s=Eo(e,0),r=s?s.length:0,n;const a=this._audioTrack,o=this._id3Track,l=s?Vm(s):void 0,d=e.length;for((this.basePTS===null||this.frameIndex===0&&Q(l))&&(this.basePTS=Xk(l,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:zt.audioId3,duration:Number.POSITIVE_INFINITY});r<d;){if(this.canParse(e,r)){const u=this.appendFrame(a,e,r);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r+=u.length,n=r):r=d}else $k(e,r)?(s=Eo(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:zt.audioId3,duration:Number.POSITIVE_INFINITY}),r+=s.length,n=r):r++;if(r===d&&n!==d){const u=e.slice(n);this.cachedData?this.cachedData=li(this.cachedData,u):this.cachedData=u}}return{audioTrack:a,videoTrack:Yi(),id3Track:o,textTrack:Yi()}}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:Yi(),id3Track:this._id3Track,textTrack:Yi()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Xk=(i,e,t)=>{if(Q(i))return i*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let Xo=null;const Zk=[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],Jk=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],eD=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],tD=[0,1,1,4];function gb(i,e,t,s,r){if(t+24>e.length)return;const n=vb(e,t);if(n&&t+n.frameLength<=e.length){const a=n.samplesPerFrame*9e4/n.sampleRate,o=s+r*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return i.config=[],i.channelCount=n.channelCount,i.samplerate=n.sampleRate,i.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function vb(i,e){const t=i[e+1]>>3&3,s=i[e+1]>>1&3,r=i[e+2]>>4&15,n=i[e+2]>>2&3;if(t!==1&&r!==0&&r!==15&&n!==3){const a=i[e+2]>>1&1,o=i[e+3]>>6,l=t===3?3-s:s===3?3:4,d=Zk[l*14+r-1]*1e3,c=Jk[(t===3?0:t===2?1:2)*3+n],h=o===3?1:2,f=eD[t][s],m=tD[s],p=f*8*m,g=Math.floor(f*d/c+a)*m;if(Xo===null){const E=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Xo=E?parseInt(E[1]):0}return!!Xo&&Xo<=87&&s===2&&d>=224e3&&o===0&&(i[e+3]=i[e+3]|128),{sampleRate:c,channelCount:h,frameLength:g,samplesPerFrame:p}}}function qm(i,e){return i[e]===255&&(i[e+1]&224)===224&&(i[e+1]&6)!==0}function Eb(i,e){return e+1<i.length&&qm(i,e)}function iD(i,e){return qm(i,e)&&4<=i.length-e}function yb(i,e){if(e+1<i.length&&qm(i,e)){const s=vb(i,e);let r=4;s!=null&&s.frameLength&&(r=s.frameLength);const n=e+r;return n===i.length||Eb(i,n)}return!1}class sD extends Wm{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=Eo(e,0);let r=s?.length||0;if(yb(e,r))return!1;for(let n=e.length;r<n;r++)if(Nk(e,r))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Ok(e,t)}appendFrame(e,t,s){cb(e,this.observer,t,s,e.manifestCodec);const r=fb(e,t,s,this.basePTS,this.frameIndex);if(r&&r.missing===0)return r}}const bb=(i,e)=>{let t=0,s=5;e+=s;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=i[e];const o=Math.min(s,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,t=t?t<<o|r[0]:r[0],e+=1,s-=o}return t};class rD extends Wm{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const r=Tb(e,t,s,this.basePTS,this.frameIndex);if(r!==-1)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;const t=Eo(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&Vm(t)!==void 0&&bb(e,s)<16}}function Tb(i,e,t,s,r){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const n=e[t+4]>>6;if(n>=3)return-1;const o=[48e3,44100,32e3][n],l=e[t+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+n]*2;if(t+u>e.length)return-1;const c=e[t+6]>>5;let h=0;c===2?h+=2:(c&1&&c!==1&&(h+=2),c&4&&(h+=2));const f=(e[t+6]<<8|e[t+7])>>12-h&1,p=[2,1,2,3,3,4,4,5][c]+f,g=e[t+5]>>3,v=e[t+5]&7,b=new Uint8Array([n<<6|g<<1|v>>2,(v&3)<<6|c<<3|f<<2|l>>4,l<<4&224]),E=1536/o*9e4,T=s+r*E,A=e.subarray(t,t+u);return i.config=b,i.channelCount=p,i.samplerate=o,i.samples.push({unit:A,pts:T}),u}class nD extends Wm{resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Eo(e,0);let s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&Vm(t)!==void 0&&bb(e,s)<=16)return!1;for(let r=e.length;s<r;s++)if(yb(e,s))return we.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return iD(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return gb(e,t,s,this.basePTS,this.frameIndex)}}const aD=/\/emsg[-/]ID3/i;class oD{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,r){const n=this.videoTrack=Yi("video",1),a=this.audioTrack=Yi("audio",1),o=this.txtTrack=Yi("text",1);if(this.id3Track=Yi("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=Cy(e);if(l.video){const{id:d,timescale:u,codec:c,supplemental:h}=l.video;n.id=d,n.timescale=o.timescale=u,n.codec=c,n.supplemental=h}if(l.audio){const{id:d,timescale:u,codec:c}=l.audio;a.id=d,a.timescale=u,a.codec=c}o.id=Ry.text,n.sampleDuration=0,n.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return rR(e)}demux(e,t){this.timeOffset=t;let s=e;const r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=li(this.remainderData,e));const o=cR(s);this.remainderData=o.remainder,r.samples=o.valid||new Uint8Array}else r.samples=s;const a=this.extractID3Track(r,t);return n.samples=Dg(t,r),{videoTrack:r,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 r=this.extractID3Track(t,this.timeOffset);return s.samples=Dg(e,t),{videoTrack:t,audioTrack:Yi(),id3Track:r,textTrack:Yi()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const r=fe(e.samples,["emsg"]);r&&r.forEach(n=>{const a=fR(n);if(aD.test(a.schemeIdUri)){const o=f0(a,t);let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const d=a.payload;s.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:zt.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=f0(a,t);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:zt.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 f0(i,e){return Q(i.presentationTime)?i.presentationTime/i.timeScale:e+i.presentationTimeDelta/i.timeScale}class lD{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Nm(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Qs.cbc)}decryptAacSample(e,t,s){const r=e[t].unit;if(r.length<=16)return;const n=r.subarray(16,r.length-r.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);r.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let r=0;for(let n=32;n<e.length-16;n+=160,r+=16)s.set(e.subarray(n,n+16),r);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let r=0;for(let n=32;n<e.length-16;n+=160,r+=16)e.set(s.subarray(r,r+16),n);return e}decryptAvcSample(e,t,s,r,n){const a=Py(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,r)}).catch(r)}decryptAvcSamples(e,t,s,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){r();return}const n=e[t].units;for(;!(s>=n.length);s++){const a=n[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,s,r,a),!this.decrypter.isSync()))return}}}}class _b{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,r;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const n=s.units;r=n[n.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,r=s.length;if(r){const n=s[r-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const r=t.byteLength;let n=e.naluState||0;const a=n,o=[];let l=0,d,u,c,h=-1,f=0;for(n===-1&&(h=0,f=this.getNALuType(t,0),n=0,l=1);l<r;){if(d=t[l++],!n){n=d?0:1;continue}if(n===1){n=d?0:2;continue}if(!d)n=3;else if(d===1){if(u=l-n-1,h>=0){const m={data:t.subarray(h,u),type:f};o.push(m)}else{const m=this.getLastNalUnit(e.samples);m&&(a&&l<=4-a&&m.state&&(m.data=m.data.subarray(0,m.data.byteLength-a)),u>0&&(m.data=li(m.data,t.subarray(0,u)),m.state=0))}l<r?(c=this.getNALuType(t,l),h=l,f=c,n=0):n=-1}else n=0}if(h>=0&&n>=0){const m={data:t.subarray(h,r),type:f,state:n};o.push(m)}if(o.length===0){const m=this.getLastNalUnit(e.samples);m&&(m.data=li(m.data,t))}return e.naluState=n,o}}class Qa{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,r=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");r.set(e.subarray(s,s+n)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&we.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 dD extends _b{parsePES(e,t,s,r){const n=this.parseNALu(e,s.data,r);let a=this.VideoSample,o,l=!1;s.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach(d=>{var u,c;switch(d.type){case 1:{let p=!1;o=!0;const g=d.data;if(l&&g.length>4){const v=this.readSliceType(g);(v===2||v===4||v===7||v===9)&&(p=!0)}if(p){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=p;break}case 5:o=!0,(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,wm(d.data,1,s.pts,t.samples);break}case 7:{var f,m;o=!0,l=!0;const p=d.data,g=this.readSPS(p);if(!e.sps||e.width!==g.width||e.height!==g.height||((f=e.pixelRatio)==null?void 0:f[0])!==g.pixelRatio[0]||((m=e.pixelRatio)==null?void 0:m[1])!==g.pixelRatio[1]){e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.sps=[p];const v=p.subarray(1,4);let b="avc1.";for(let E=0;E<3;E++){let T=v[E].toString(16);T.length<2&&(T="0"+T),b+=T}e.codec=b}break}case 8:o=!0,e.pps=[d.data];break;case 9:o=!0,e.audFound=!0,(c=a)!=null&&c.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(d)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Qa(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,r=8,n;for(let a=0;a<e;a++)r!==0&&(n=t.readEG(),r=(s+n+256)%256),s=r===0?s:r}readSPS(e){const t=new Qa(e);let s=0,r=0,n=0,a=0,o,l,d;const u=t.readUByte.bind(t),c=t.readBits.bind(t),h=t.readUEG.bind(t),f=t.readBoolean.bind(t),m=t.skipBits.bind(t),p=t.skipEG.bind(t),g=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);u();const b=u();if(c(5),m(3),u(),g(),b===100||b===110||b===122||b===244||b===44||b===83||b===86||b===118||b===128){const L=h();if(L===3&&m(1),g(),g(),m(1),f())for(l=L!==3?8:12,d=0;d<l;d++)f()&&(d<6?v(16,t):v(64,t))}g();const E=h();if(E===0)h();else if(E===1)for(m(1),p(),p(),o=h(),d=0;d<o;d++)p();g(),m(1);const T=h(),A=h(),x=c(1);x===0&&m(1),m(1),f()&&(s=h(),r=h(),n=h(),a=h());let S=[1,1];if(f()&&f())switch(u()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:{S=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((T+1)*16-s*2-r*2),height:(2-x)*(A+1)*16-(x?2:4)*(n+a),pixelRatio:S}}}class uD extends _b{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,r){const n=this.parseNALu(e,s.data,r);let a=this.VideoSample,o,l=!1;s.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach(d=>{var u,c;switch(d.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,l){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 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,wm(d.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Oe(e.params,this.readVPS(d.data)),this.initVPS=d.data),e.vps=[d.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],d.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const f=this.readSPS(d.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 m in f.params)e.params[m]=f.params[m]}this.pushParameterSet(e.sps,d.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(d.data);for(const m in f)e.params[m]=f[m]}this.pushParameterSet(e.pps,d.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(c=a)!=null&&c.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(d)}),r&&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 r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[s]=e[r],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 Qa(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),r=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:r}}readSPS(e){const t=new Qa(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const r=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),u=t.readUByte(),c=t.readUByte(),h=t.readUByte(),f=t.readUByte(),m=t.readUByte(),p=t.readUByte(),g=t.readUByte(),v=t.readUByte(),b=[],E=[];for(let Te=0;Te<s;Te++)b.push(t.readBoolean()),E.push(t.readBoolean());if(s>0)for(let Te=s;Te<8;Te++)t.readBits(2);for(let Te=0;Te<s;Te++)b[Te]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),E[Te]&&t.readUByte();t.readUEG();const T=t.readUEG();T==3&&t.skipBits(1);const A=t.readUEG(),x=t.readUEG(),S=t.readBoolean();let L=0,R=0,I=0,M=0;S&&(L+=t.readUEG(),R+=t.readUEG(),I+=t.readUEG(),M+=t.readUEG());const B=t.readUEG(),W=t.readUEG(),j=t.readUEG(),K=t.readBoolean();for(let Te=K?0:s;Te<=s;Te++)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 ct=0;ct<4;ct++)for(let Ct=0;Ct<(ct===3?2:6);Ct++)if(!t.readBoolean())t.readUEG();else{const ei=Math.min(64,1<<4+(ct<<1));ct>1&&t.readEG();for(let _e=0;_e<ei;_e++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const P=t.readUEG();let G=0;for(let Te=0;Te<P;Te++){let ct=!1;if(Te!==0&&(ct=t.readBoolean()),ct){Te===P&&t.readUEG(),t.readBoolean(),t.readUEG();let Ct=0;for(let xi=0;xi<=G;xi++){const ei=t.readBoolean();let _e=!1;ei||(_e=t.readBoolean()),(ei||_e)&&Ct++}G=Ct}else{const Ct=t.readUEG(),xi=t.readUEG();G=Ct+xi;for(let ei=0;ei<Ct;ei++)t.readUEG(),t.readBoolean();for(let ei=0;ei<xi;ei++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const Te=t.readUEG();for(let ct=0;ct<Te;ct++){for(let Ct=0;Ct<j+4;Ct++)t.readBits(1);t.readBits(1)}}let $=0,H=1,se=1,ge=!0,ce=1,me=0;t.readBoolean(),t.readBoolean();let ut=!1;if(t.readBoolean()){if(t.readBoolean()){const Bt=t.readUByte(),Ro=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Br=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Bt>0&&Bt<16?(H=Ro[Bt-1],se=Br[Bt-1]):Bt===255&&(H=t.readBits(16),se=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(),ut=t.readBoolean(),ut&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ce=t.readBits(32),me=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Br=t.readBoolean(),ko=t.readBoolean();let Js=!1;(Br||ko)&&(Js=t.readBoolean(),Js&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Js&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Do=0;Do<=s;Do++){ge=t.readBoolean();const ac=ge||t.readBoolean();let Co=!1;ac?t.readEG():Co=t.readBoolean();const Lt=Co?1:t.readUEG()+1;if(Br)for(let Ve=0;Ve<Lt;Ve++)t.readUEG(),t.readUEG(),Js&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(ko)for(let Ve=0;Ve<Lt;Ve++)t.readUEG(),t.readUEG(),Js&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),$=t.readUEG())}let Dt=A,Ft=x;if(S){let Te=1,ct=1;T===1?Te=ct=2:T==2&&(Te=2),Dt=A-Te*R-Te*L,Ft=x-ct*M-ct*I}const ci=r?["A","B","C"][r]:"",Ss=o<<24|l<<16|d<<8|u;let $r=0;for(let Te=0;Te<32;Te++)$r=($r|(Ss>>Te&1)<<31-Te)>>>0;let Fr=$r.toString(16);return a===1&&Fr==="2"&&(Fr="6"),{codecString:`hvc1.${ci}${a}.${Fr}.${n?"H":"L"}${v}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[o,l,d,u],general_constraint_indicator_flags:[c,h,f,m,p,g],general_level_idc:v,bit_depth:B+8,bit_depth_luma_minus8:B,bit_depth_chroma_minus8:W,min_spatial_segmentation_idc:$,chroma_format_idc:T,frame_rate:{fixed:ge,fps:me/ce}},width:Dt,height:Ft,pixelRatio:[H,se]}}readPPS(e){const t=new Qa(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 r=t.readBoolean(),n=t.readBoolean();let a=1;return n&&r?a=0:n?a=3:r&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Et=188;class Bs{constructor(e,t,s,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=r,this.videoParser=null}static probe(e,t){const s=Bs.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(Et*5,t-Et)+1,r=0;for(;r<s;){let n=!1,a=-1,o=0;for(let l=r;l<t;l+=Et)if(e[l]===71&&(t-l===Et||e[l+Et]===71)){if(o++,a===-1&&(a=l,a!==0&&(s=Math.min(a+Et*99,e.length-Et)+1)),n||(n=Wh(e,l)===0),n&&o>1&&(a===0&&o>2||l+Et>s))return a}else{if(o)return-1;break}r++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Ry[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Bs.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=Bs.createTrack("audio",r),this._id3Track=Bs.createTrack("id3"),this._txtTrack=Bs.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,r=!1){s||(this.sampleAes=null);let n;const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,d=this._txtTrack;let u=a.pid,c=a.pesData,h=o.pid,f=l.pid,m=o.pesData,p=l.pesData,g=null,v=this.pmtParsed,b=this._pmtId,E=e.length;if(this.remainderData&&(e=li(this.remainderData,e),E=e.length,this.remainderData=null),E<Et&&!r)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};const T=Math.max(0,Bs.syncOffset(e));E-=(E-T)%Et,E<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,E,e.buffer.byteLength-E));let A=0;for(let S=T;S<E;S+=Et)if(e[S]===71){const L=!!(e[S+1]&64),R=Wh(e,S),I=(e[S+3]&48)>>4;let M;if(I>1){if(M=S+5+e[S+4],M===S+Et)continue}else M=S+4;switch(R){case u:L&&(c&&(n=zr(c,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,d,n,!1)),c={data:[],size:0}),c&&(c.data.push(e.subarray(M,S+Et)),c.size+=S+Et-M);break;case h:if(L){if(m&&(n=zr(m,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n);break}m={data:[],size:0}}m&&(m.data.push(e.subarray(M,S+Et)),m.size+=S+Et-M);break;case f:L&&(p&&(n=zr(p,this.logger))&&this.parseID3PES(l,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(M,S+Et)),p.size+=S+Et-M);break;case 0:L&&(M+=e[M]+1),b=this._pmtId=cD(e,M);break;case b:{L&&(M+=e[M]+1);const B=hD(e,M,this.typeSupported,s,this.observer,this.logger);u=B.videoPid,u>0&&(a.pid=u,a.segmentCodec=B.segmentVideoCodec),h=B.audioPid,h>0&&(o.pid=h,o.segmentCodec=B.segmentAudioCodec),f=B.id3Pid,f>0&&(l.pid=f),g!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${S} after unknown PID '${g}'. Backtracking to sync byte @${T} to parse all TS packets.`),g=null,S=T-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=R;break}}else A++;A>0&&qh(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=c,o.pesData=m,l.pesData=p;const x={audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};return r&&this.extractRemainingSamples(x),x}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:r,textTrack:n}=e,a=s.pesData,o=t.pesData,l=r.pesData;let d;if(a&&(d=zr(a,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,n,d,!0),s.pesData=null)):s.pesData=a,o&&(d=zr(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,d);break;case"mp3":this.parseMPEGPES(t,d);break;case"ac3":this.parseAC3PES(t,d);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(d=zr(l,this.logger))?(this.parseID3PES(r,d),r.pesData=null):r.pesData=l}demuxSampleAes(e,t,s){const r=this.demux(e,s,!0,!this.config.progressive),n=this.sampleAes=new lD(this.observer,this.config,t);return this.decrypt(r,n)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new dD:e==="hevc"&&(this.videoParser=new uD))}decrypt(e,t){return new Promise(s=>{const{audioTrack:r,videoTrack:n}=e;r.samples&&r.segmentCodec==="aac"?t.decryptAacSamples(r.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{s(e)}):s(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const r=this.aacOverFlow;let n=t.data;if(r){this.aacOverFlow=null;const c=r.missing,h=r.sample.unit.byteLength;if(c===-1)n=li(r.sample.unit,n);else{const f=h-c;r.sample.unit.set(n.subarray(0,c),f),e.samples.push(r.sample),s=r.missing}}let a,o;for(a=s,o=n.length;a<o-1&&!su(n,a);a++);if(a!==s){let c;const h=a<o-1;if(h?c=`AAC PES did not start with ADTS header,offset:${a}`:c="No ADTS header found in AAC PES",qh(this.observer,new Error(c),h,this.logger),!h)return}cb(e,this.observer,n,a,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(r){const c=hb(e.samplerate);l=r.sample.pts+c}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let d=0,u;for(;a<o;)if(u=fb(e,n,a,l,d),a+=u.length,u.missing){this.aacOverFlow=u;break}else for(d++;a<o-1&&!su(n,a);a++);}parseMPEGPES(e,t){const s=t.data,r=s.length;let n=0,a=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<r;)if(Eb(s,a)){const l=gb(e,s,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(e,t){{const s=t.data,r=t.pts;if(r===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const n=s.length;let a=0,o=0,l;for(;o<n&&(l=Tb(e,s,o,r,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=Oe({},t,{type:this._videoTrack?zt.emsg:zt.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Wh(i,e){return((i[e+1]&31)<<8)+i[e+2]}function cD(i,e){return(i[e+10]&31)<<8|i[e+11]}function hD(i,e,t,s,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(i[e+1]&15)<<8|i[e+2],l=e+3+o-4,d=(i[e+10]&15)<<8|i[e+11];for(e+=12+d;e<l;){const u=Wh(i,e),c=(i[e+3]&15)<<8|i[e+4];switch(i[e]){case 207:if(!s){Lc("ADTS AAC",n);break}case 15:a.audioPid===-1&&(a.audioPid=u);break;case 21:a.id3Pid===-1&&(a.id3Pid=u);break;case 219:if(!s){Lc("H.264",n);break}case 27:a.videoPid===-1&&(a.videoPid=u);break;case 3:case 4:!t.mpeg&&!t.mp3?n.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=u,a.segmentAudioCodec="mp3");break;case 193:if(!s){Lc("AC-3",n);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=u,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&c>0){let h=e+5,f=c;for(;f>2;){switch(i[h]){case 106:t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=u,a.segmentAudioCodec="ac3");break}const p=i[h+1]+2;h+=p,f-=p}}break;case 194:case 135:return qh(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:a.videoPid===-1&&(a.videoPid=u,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}e+=c+5}return a}function qh(i,e,t,s){s.warn(`parsing error: ${e.message}`),i.emit(y.ERROR,y.ERROR,{type:ie.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Lc(i,e){e.log(`${i} with AES-128-CBC encryption found in unencrypted stream`)}function zr(i,e){let t=0,s,r,n,a,o;const l=i.data;if(!i||i.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=li(l[0],l[1]),l.splice(1,1);if(s=l[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(r=(s[4]<<8)+s[5],r&&r>i.size-6)return null;const u=s[7];u&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,u&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=s[8];let c=n+9;if(i.size<=c)return null;i.size-=c;const h=new Uint8Array(i.size);for(let f=0,m=l.length;f<m;f++){s=l[f];let p=s.byteLength;if(c)if(c>p){c-=p;continue}else s=s.subarray(c),p-=c,c=0;h.set(s,t),t+=p}return r&&(r-=n+3),{data:h,pts:a,dts:o,len:r}}return null}class fD{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 Rs=Math.pow(2,32)-1;class D{static init(){D.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 D.types)D.types.hasOwnProperty(e)&&(D.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]);D.HDLR_TYPES={video:t,audio:s};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);D.STTS=D.STSC=D.STCO=n,D.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),D.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),D.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),D.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);D.FTYP=D.box(D.types.ftyp,a,l,a,o),D.DINF=D.box(D.types.dinf,D.box(D.types.dref,r))}static box(e,...t){let s=8,r=t.length;const n=r;for(;r--;)s+=t[r].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),r=0,s=8;r<n;r++)a.set(t[r],s),s+=t[r].byteLength;return a}static hdlr(e){return D.box(D.types.hdlr,D.HDLR_TYPES[e])}static mdat(e){return D.box(D.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(Rs+1)),r=Math.floor(t%(Rs+1));return D.box(D.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,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(e){return D.box(D.types.mdia,D.mdhd(e.timescale||0,e.duration||0),D.hdlr(e.type),D.minf(e))}static mfhd(e){return D.box(D.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"?D.box(D.types.minf,D.box(D.types.smhd,D.SMHD),D.DINF,D.stbl(e)):D.box(D.types.minf,D.box(D.types.vmhd,D.VMHD),D.DINF,D.stbl(e))}static moof(e,t,s){return D.box(D.types.moof,D.mfhd(e),D.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=D.trak(e[t]);return D.box.apply(null,[D.types.moov,D.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(D.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=D.trex(e[t]);return D.box.apply(null,[D.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(Rs+1)),r=Math.floor(t%(Rs+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,r>>24,r>>16&255,r>>8&255,r&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return D.box(D.types.mvhd,n)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let r,n;for(r=0;r<t.length;r++)n=t[r].flags,s[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return D.box(D.types.sdtp,s)}static stbl(e){return D.box(D.types.stbl,D.stsd(e),D.box(D.types.stts,D.STTS),D.box(D.types.stsc,D.STSC),D.box(D.types.stsz,D.STSZ),D.box(D.types.stco,D.STCO))}static avc1(e){let t=[],s=[],r,n,a;for(r=0;r<e.sps.length;r++)n=e.sps[r],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(r=0;r<e.pps.length;r++)n=e.pps[r],a=n.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(n));const o=D.box(D.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),l=e.width,d=e.height,u=e.pixelRatio[0],c=e.pixelRatio[1];return D.box(D.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,D.box(D.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),D.box(D.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,c>>24,c>>16&255,c>>8&255,c&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 D.box(D.types.mp4a,D.audioStsd(e),D.box(D.types.esds,D.esds(e)))}static mp3(e){return D.box(D.types[".mp3"],D.audioStsd(e))}static ac3(e){return D.box(D.types["ac-3"],D.audioStsd(e),D.box(D.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return D.box(D.types.stsd,D.STSD,D.mp4a(e));if(t==="ac3"&&e.config)return D.box(D.types.stsd,D.STSD,D.ac3(e));if(t==="mp3"&&e.codec==="mp3")return D.box(D.types.stsd,D.STSD,D.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return D.box(D.types.stsd,D.STSD,D.avc1(e));if(t==="hevc"&&e.vps)return D.box(D.types.stsd,D.STSD,D.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),r=e.width||0,n=e.height||0,a=Math.floor(s/(Rs+1)),o=Math.floor(s%(Rs+1));return D.box(D.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,r&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){const s=D.sdtp(e),r=e.id,n=Math.floor(t/(Rs+1)),a=Math.floor(t%(Rs+1));return D.box(D.types.traf,D.box(D.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),D.box(D.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),D.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,D.box(D.types.trak,D.tkhd(e),D.mdia(e))}static trex(e){const t=e.id;return D.box(D.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||[],r=s.length,n=12+16*r,a=new Uint8Array(n);let o,l,d,u,c,h;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<r;o++)l=s[o],d=l.duration,u=l.size,c=l.flags,h=l.cts,a.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,c.degradPrio&61440,c.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*o);return D.box(D.types.trun,a)}static initSegment(e){D.types||D.init();const t=D.moov(e);return li(D.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],r=4,n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),r-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let a=n.length;for(let m=0;m<s.length;m+=1){a+=3;for(let p=0;p<s[m].length;p+=1)a+=2+s[m][p].length}const o=new Uint8Array(a);o.set(n,0),a=n.length;const l=s.length-1;for(let m=0;m<s.length;m+=1){o.set(new Uint8Array([32+m|(m===l?128:0),0,s[m].length]),a),a+=3;for(let p=0;p<s[m].length;p+=1)o.set(new Uint8Array([s[m][p].length>>8,s[m][p].length&255]),a),a+=2,o.set(s[m][p],a),a+=s[m][p].length}const d=D.box(D.types.hvcC,o),u=e.width,c=e.height,h=e.pixelRatio[0],f=e.pixelRatio[1];return D.box(D.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,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,D.box(D.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),D.box(D.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}}D.types=void 0;D.HDLR_TYPES=void 0;D.STTS=void 0;D.STSC=void 0;D.STCO=void 0;D.STSZ=void 0;D.VMHD=void 0;D.SMHD=void 0;D.STSD=void 0;D.FTYP=void 0;D.DINF=void 0;const Ab=9e4;function Ym(i,e,t=1,s=!1){const r=i*e*t;return s?Math.round(r):r}function mD(i,e,t=1,s=!1){return Ym(i,e,1/t,s)}function ca(i,e=!1){return Ym(i,1e3,1/Ab,e)}function pD(i,e=1){return Ym(i,Ab,1/e)}function m0(i){const{baseTime:e,timescale:t,trackId:s}=i;return`${e/t} (${e}/${t}) trackId: ${s}`}const gD=10*1e3,vD=1024,ED=1152,yD=1536;let Qr=null,Rc=null;function p0(i,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:i?2:1,isNonSync:i?0:1}}}class Vl extends di{constructor(e,t,s,r){if(super("mp4-remuxer",r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,Qr===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Qr=a?parseInt(a[1]):0}if(Rc===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);Rc=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&m0(t)} > ${e&&m0(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,r=e.reduce((n,a)=>{let o=a.pts,l=o-n;return l<-4294967296&&(t=!0,o=jt(o,s),l=o-n),l>0?n:o},s);return t&&this.debug("PTS rollover detected"),r}remux(e,t,s,r,n,a,o,l){let d,u,c,h,f,m,p=n,g=n;const v=e.pid>-1,b=t.pid>-1,E=t.samples.length,T=e.samples.length>0,A=o&&E>0||E>1;if((!v||T)&&(!b||A)||this.ISGenerated||o){if(this.ISGenerated){var S,L,R,I;const j=this.videoTrackConfig;(j&&(t.width!==j.width||t.height!==j.height||((S=t.pixelRatio)==null?void 0:S[0])!==((L=j.pixelRatio)==null?void 0:L[0])||((R=t.pixelRatio)==null?void 0:R[1])!==((I=j.pixelRatio)==null?void 0:I[1]))||!j&&A||this.nextAudioTs===null&&T)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,n,a));const M=this.isVideoContiguous;let B=-1,W;if(A&&(B=bD(t.samples),!M&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,B>0){this.warn(`Dropped ${B} out of ${E} video samples due to a missing keyframe`);const j=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(B),t.dropped+=B,g+=(t.samples[0].pts-j)/t.inputTimeScale,W=g}else B===-1&&(this.warn(`No keyframe found out of ${E} video samples`),m=!1);if(this.ISGenerated){if(T&&A){const j=this.getVideoStartPts(t.samples),F=(jt(e.samples[0].pts,j)-j)/t.inputTimeScale;p+=Math.max(0,F),g+=Math.max(0,-F)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,n,a)),u=this.remuxAudio(e,p,this.isAudioContiguous,a,b||A||l===J.AUDIO?g:void 0),A){const j=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,n,a)),d=this.remuxVideo(t,g,M,j)}}else A&&(d=this.remuxVideo(t,g,M,0));d&&(d.firstKeyFrame=B,d.independent=B!==-1,d.firstKeyFramePTS=W)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=Sb(s,n,this._initPTS,this._initDTS)),r.samples.length&&(h=Ib(r,n,this._initPTS))),{audio:u,video:d,initSegment:c,independent:m,text:h,id3:f}}computeInitPts(e,t,s,r){const n=Math.round(s*t);let a=jt(e,n);if(a<n+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${r}`);a<n+t;)a+=8589934592;return a-n}generateIS(e,t,s,r){const n=e.samples,a=t.samples,o=this.typeSupported,l={},d=this._initPTS;let u=!d||r,c="audio/mp4",h,f,m,p=-1;if(u&&(h=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(c="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:c,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):D.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(p=e.id,m=e.inputTimeScale,!d||m!==d.timescale?h=f=this.computeInitPts(n[0].pts,m,s,"audio"):u=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:D.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(p=t.id,m=t.inputTimeScale,!d||m!==d.timescale){const g=this.getVideoStartPts(a),v=jt(a[0].dts,g),b=this.computeInitPts(v,m,s,"video"),E=this.computeInitPts(g,m,s,"video");f=Math.min(f,b),h=Math.min(h,E)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u?(d&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${s} ${h/m} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${h/m} (${h}/${m}) trackId: ${p}`),this._initPTS={baseTime:h,timescale:m,trackId:p},this._initDTS={baseTime:f,timescale:m,trackId:p}):h=m=void 0,{tracks:l,initPTS:h,timescale:m,trackId:p}}remuxVideo(e,t,s,r){const n=e.inputTimeScale,a=e.samples,o=[],l=a.length,d=this._initPTS,u=d.baseTime*n/d.timescale;let c=this.nextVideoTs,h=8,f=this.videoSampleDuration,m,p,g=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,b=!1;if(!s||c===null){const $=u+t*n,H=a[0].pts-jt(a[0].dts,a[0].pts);Qr&&c!==null&&Math.abs($-H-(c+u))<15e3?s=!0:c=$-H-u}const E=c+u;for(let $=0;$<l;$++){const H=a[$];H.pts=jt(H.pts,E),H.dts=jt(H.dts,E),H.dts<a[$>0?$-1:$].dts&&(b=!0)}b&&a.sort(function($,H){const se=$.dts-H.dts,ge=$.pts-H.pts;return se||ge}),m=a[0].dts,p=a[a.length-1].dts;const T=p-m,A=T?Math.round(T/(l-1)):f||e.inputTimeScale/30;if(s){const $=m-E,H=$>A,se=$<-1;if((H||se)&&(H?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ca($,!0)} ms (${$}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ca(-$,!0)} ms (${$}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!se||E>=a[0].pts||Qr)){m=E;const ge=a[0].pts-$;if(H)a[0].dts=m,a[0].pts=ge;else{let ce=!0;for(let me=0;me<a.length&&!(a[me].dts>ge&&ce);me++){const ut=a[me].pts;if(a[me].dts-=$,a[me].pts-=$,me<a.length-1){const tt=a[me+1].pts,Dt=a[me].pts,Ft=tt<=Dt,ci=tt<=ut;ce=Ft==ci}}}this.log(`Video: Initial PTS/DTS adjusted: ${ca(ge,!0)}/${ca(m,!0)}, delta: ${ca($,!0)} ms`)}}m=Math.max(0,m);let x=0,S=0,L=m;for(let $=0;$<l;$++){const H=a[$],se=H.units,ge=se.length;let ce=0;for(let me=0;me<ge;me++)ce+=se[me].data.length;S+=ce,x+=ge,H.length=ce,H.dts<L?(H.dts=L,L+=A/4|0||1):L=H.dts,g=Math.min(H.pts,g),v=Math.max(H.pts,v)}p=a[l-1].dts;const R=S+4*x+8;let I;try{I=new Uint8Array(R)}catch($){this.observer.emit(y.ERROR,y.ERROR,{type:ie.MUX_ERROR,details:w.REMUX_ALLOC_ERROR,fatal:!1,error:$,bytes:R,reason:`fail allocating video mdat ${R}`});return}const M=new DataView(I.buffer);M.setUint32(0,R),I.set(D.types.mdat,4);let B=!1,W=Number.POSITIVE_INFINITY,j=Number.POSITIVE_INFINITY,K=Number.NEGATIVE_INFINITY,F=Number.NEGATIVE_INFINITY;for(let $=0;$<l;$++){const H=a[$],se=H.units;let ge=0;for(let ut=0,tt=se.length;ut<tt;ut++){const Dt=se[ut],Ft=Dt.data,ci=Dt.data.byteLength;M.setUint32(h,ci),h+=4,I.set(Ft,h),h+=ci,ge+=4+ci}let ce;if($<l-1)f=a[$+1].dts-H.dts,ce=a[$+1].pts-H.pts;else{const ut=this.config,tt=$>0?H.dts-a[$-1].dts:A;if(ce=$>0?H.pts-a[$-1].pts:A,ut.stretchShortVideoTrack&&this.nextAudioTs!==null){const Dt=Math.floor(ut.maxBufferHole*n),Ft=(r?g+r*n:this.nextAudioTs+u)-H.pts;Ft>Dt?(f=Ft-tt,f<0?f=tt:B=!0,this.log(`It is approximately ${Ft/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=tt}else f=tt}const me=Math.round(H.pts-H.dts);W=Math.min(W,f),K=Math.max(K,f),j=Math.min(j,ce),F=Math.max(F,ce),o.push(p0(H.key,f,ge,me))}if(o.length){if(Qr){if(Qr<70){const $=o[0].flags;$.dependsOn=2,$.isNonSync=0}}else if(Rc&&F-j<K-W&&A/K<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let $=m;for(let H=0,se=o.length;H<se;H++){const ge=$+o[H].duration,ce=$+o[H].cts;if(H<se-1){const me=ge+o[H+1].cts;o[H].duration=me-ce}else o[H].duration=H?o[H-1].duration:A;o[H].cts=0,$=ge}}}f=B||!f?A:f;const Y=p+f;this.nextVideoTs=c=Y-u,this.videoSampleDuration=f,this.isVideoContiguous=!0;const Z={data1:D.moof(e.sequenceNumber++,m,Oe(e,{samples:o})),data2:I,startPTS:(g-u)/n,endPTS:(v+f-u)/n,startDTS:(m-u)/n,endDTS:c/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Z}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return ED;case"ac3":return yD;default:return vD}}remuxAudio(e,t,s,r,n){const a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,l=a/o,d=this.getSamplesPerFrame(e),u=d*l,c=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],m=n!==void 0;let p=e.samples,g=h?0:8,v=this.nextAudioTs||-1;const b=c.baseTime*a/c.timescale,E=b+t*a;if(this.isAudioContiguous=s=s||p.length&&v>0&&(r&&Math.abs(E-(v+b))<9e3||Math.abs(jt(p[0].pts,E)-(v+b))<20*u),p.forEach(function(F){F.pts=jt(F.pts,E)}),!s||v<0){const F=p.length;if(p=p.filter(Y=>Y.pts>=0),F!==p.length&&this.warn(`Removed ${p.length-F} of ${F} samples (initPTS ${b} / ${a})`),!p.length)return;n===0?v=0:r&&!m?v=Math.max(0,E-b):v=p[0].pts-b}if(e.segmentCodec==="aac"){const F=this.config.maxAudioFramesDrift;for(let Y=0,P=v+b;Y<p.length;Y++){const G=p[Y],Z=G.pts,$=Z-P,H=Math.abs(1e3*$/a);if($<=-F*u&&m)Y===0&&(this.warn(`Audio frame @ ${(Z/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*$/a)} ms.`),this.nextAudioTs=v=Z-b,P=Z);else if($>=F*u&&H<gD&&m){let se=Math.round($/u);for(P=Z-se*u;P<0&&se&&u;)se--,P+=u;Y===0&&(this.nextAudioTs=v=P-b),this.warn(`Injecting ${se} audio frames @ ${((P-b)/a).toFixed(3)}s due to ${Math.round(1e3*$/a)} ms gap.`);for(let ge=0;ge<se;ge++){let ce=fD.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);ce||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),ce=G.unit.subarray()),p.splice(Y,0,{unit:ce,pts:P}),P+=u,Y++}}G.pts=P,P+=u}}let T=null,A=null,x,S=0,L=p.length;for(;L--;)S+=p[L].unit.byteLength;for(let F=0,Y=p.length;F<Y;F++){const P=p[F],G=P.unit;let Z=P.pts;if(A!==null){const H=f[F-1];H.duration=Math.round((Z-A)/l)}else if(s&&e.segmentCodec==="aac"&&(Z=v+b),T=Z,S>0){S+=g;try{x=new Uint8Array(S)}catch(H){this.observer.emit(y.ERROR,y.ERROR,{type:ie.MUX_ERROR,details:w.REMUX_ALLOC_ERROR,fatal:!1,error:H,bytes:S,reason:`fail allocating audio mdat ${S}`});return}h||(new DataView(x.buffer).setUint32(0,S),x.set(D.types.mdat,4))}else return;x.set(G,g);const $=G.byteLength;g+=$,f.push(p0(!0,d,$,0)),A=Z}const R=f.length;if(!R)return;const I=f[f.length-1];v=A-b,this.nextAudioTs=v+l*I.duration;const M=h?new Uint8Array(0):D.moof(e.sequenceNumber++,T/l,Oe({},e,{samples:f}));e.samples=[];const B=(T-b)/a,W=this.nextAudioTs/a,K={data1:M,data2:x,startPTS:B,endPTS:W,startDTS:B,endDTS:W,type:"audio",hasAudio:!0,hasVideo:!1,nb:R};return this.isAudioContiguous=!0,K}}function jt(i,e){let t;if(e===null)return i;for(e<i?t=-8589934592:t=8589934592;Math.abs(i-e)>4294967296;)i+=t;return i}function bD(i){for(let e=0;e<i.length;e++)if(i[e].key)return e;return-1}function Sb(i,e,t,s){const r=i.samples.length;if(!r)return;const n=i.inputTimeScale;for(let o=0;o<r;o++){const l=i.samples[o];l.pts=jt(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=jt(l.dts-s.baseTime*n/s.timescale,e*n)/n}const a=i.samples;return i.samples=[],{samples:a}}function Ib(i,e,t){const s=i.samples.length;if(!s)return;const r=i.inputTimeScale;for(let a=0;a<s;a++){const o=i.samples[a];o.pts=jt(o.pts-t.baseTime*r/t.timescale,e*r)/r}i.samples.sort((a,o)=>a.pts-o.pts);const n=i.samples;return i.samples=[],{samples:n}}class TD extends di{constructor(e,t,s,r){super("passthrough-remuxer",r),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,r){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,r),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:n,video:a}=this.initData=Cy(e);if(t)lR(e,t);else{const l=n||a;l!=null&&l.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${l.codec}")!`)}n&&(s=g0(n,Ue.AUDIO,this)),a&&(r=g0(a,Ue.VIDEO,this));const o={};n&&a?o.audiovideo={container:"video/mp4",codec:s+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:n?o.audio={container:"audio/mp4",codec:s,encrypted:n.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,r,n,a){var o,l;let{initPTS:d,lastEndTime:u}=this;const c={audio:void 0,video:void 0,text:r,id3:s,initSegment:void 0};Q(u)||(u=this.lastEndTime=n||0);const h=t.samples;if(!h.length)return c;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let m=this.initData;if((o=m)!=null&&o.length||(this.generateInitSegment(h),m=this.initData),!((l=m)!=null&&l.length))return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const p=uR(h,m,this),g=m.audio?p[m.audio.id]:null,v=m.video?p[m.video.id]:null,b=Zo(v,1/0),E=Zo(g,1/0),T=Zo(v,0,!0),A=Zo(g,0,!0);let x=n,S=0;const L=g&&(!v||!d&&E<b||d&&d.trackId===m.audio.id),R=L?g:v;if(R){const P=R.timescale,G=R.start-n*P,Z=L?m.audio.id:m.video.id;x=R.start/P,S=L?A-E:T-b,(a||!d)&&(_D(d,x,n,S)||P!==d.timescale)&&(d&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${G/P} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${x-n} (${G}/${P}) trackId: ${Z}`),d=null,f.initPTS=G,f.timescale=P,f.trackId=Z)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);d?(f.initPTS=d.baseTime,f.timescale=d.timescale,f.trackId=d.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=x,f.timescale=1,f.trackId=-1),this.initPTS=d={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const I=x-d.baseTime/d.timescale,M=I+S;S>0?this.lastEndTime=M:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const B=!!m.audio,W=!!m.video;let j="";B&&(j+="audio"),W&&(j+="video");const K=(m.audio?m.audio.encrypted:!1)||(m.video?m.video.encrypted:!1),F={data1:h,startPTS:I,startDTS:I,endPTS:M,endDTS:M,type:j,hasAudio:B,hasVideo:W,nb:1,dropped:0,encrypted:K};c.audio=B&&!W?F:void 0,c.video=W?F:void 0;const Y=v?.sampleCount;if(Y){const P=v.keyFrameIndex,G=P!==-1;F.nb=Y,F.dropped=P===0||this.isVideoContiguous?0:G?P:Y,F.independent=G,F.firstKeyFrame=P,G&&v.keyFrameStart&&(F.firstKeyFramePTS=(v.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(c.independent=G),this.isVideoContiguous||(this.isVideoContiguous=G),F.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${P}/${Y} dropped: ${F.dropped} start: ${F.firstKeyFramePTS||"NA"}`)}return c.initSegment=f,c.id3=Sb(s,n,d,d),r.samples.length&&(c.text=Ib(r,n,d)),c}}function Zo(i,e,t=!1){return i?.start!==void 0?(i.start+(t?i.duration:0))/i.timescale:e}function _D(i,e,t,s){if(i===null)return!0;const r=Math.max(s,1),n=e-i.baseTime/i.timescale;return Math.abs(n-t)>r}function g0(i,e,t){const s=i.codec;return s&&s.length>4?s:e===Ue.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?zd(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let ms;try{ms=self.performance.now.bind(self.performance)}catch{ms=Date.now}const Wl=[{demux:oD,remux:TD},{demux:Bs,remux:Vl},{demux:sD,remux:Vl},{demux:nD,remux:Vl}];Wl.splice(2,0,{demux:rD,remux:Vl});class v0{constructor(e,t,s,r,n,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,r){const n=s.transmuxing;n.executeStart=ms();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;r&&(this.currentTransmuxState=r);const{contiguous:d,discontinuity:u,trackSwitch:c,accurateTimeOffset:h,timeOffset:f,initSegmentChange:m}=r||o,{audioCodec:p,videoCodec:g,defaultInitPts:v,duration:b,initSegmentData:E}=l,T=AD(a,t);if(T&&Un(T.method)){const L=this.getDecrypter(),R=$m(T.method);if(L.isSync()){let I=L.softwareDecrypt(a,T.key.buffer,T.iv.buffer,R);if(s.part>-1){const B=L.flush();I=B&&B.buffer}if(!I)return n.executeEnd=ms(),kc(s);a=new Uint8Array(I)}else return this.asyncResult=!0,this.decryptionPromise=L.webCryptoDecrypt(a,T.key.buffer,T.iv.buffer,R).then(I=>{const M=this.push(I,null,s);return this.decryptionPromise=null,M}),this.decryptionPromise}const A=this.needsProbing(u,c);if(A){const L=this.configureTransmuxer(a);if(L)return this.logger.warn(`[transmuxer] ${L.message}`),this.observer.emit(y.ERROR,y.ERROR,{type:ie.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,error:L,reason:L.message}),n.executeEnd=ms(),kc(s)}(u||c||m||A)&&this.resetInitSegment(E,p,g,b,t),(u||m||A)&&this.resetInitialTimestamp(v),d||this.resetContiguity();const x=this.transmux(a,T,f,h,s);this.asyncResult=yo(x);const S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,n.executeEnd=ms(),x}flush(e){const t=e.transmuxing;t.executeStart=ms();const{decrypter:s,currentTransmuxState:r,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));const a=[],{timeOffset:o}=r;if(s){const c=s.flush();c&&a.push(this.push(c.buffer,null,e))}const{demuxer:l,remuxer:d}=this;if(!l||!d){t.executeEnd=ms();const c=[kc(e)];return this.asyncResult?Promise.resolve(c):c}const u=l.flush(o);return yo(u)?(this.asyncResult=!0,u.then(c=>(this.flushRemux(a,c,e),a))):(this.flushRemux(a,u,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,s){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===J.MAIN?"level":"track"} ${s.level}`);const u=this.remuxer.remux(r,n,a,o,d,l,!0,this.id);e.push({remuxResult:u,chunkMeta:s}),s.transmuxing.executeEnd=ms()}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,r,n){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,s,r),o.resetInitSegment(e,t,s,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,r,n){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,s,r,n):a=this.transmuxUnencrypted(e,s,r,n),a}transmuxUnencrypted(e,t,s,r){const{audioTrack:n,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,a,o,l,t,s,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,s,r,n){return this.demuxer.demuxSampleAes(e,t,s).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,r,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:r}=this;let n;for(let c=0,h=Wl.length;c<h;c++){var a;if((a=Wl[c].demux)!=null&&a.probe(e,this.logger)){n=Wl[c];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,d=n.remux,u=n.demux;(!l||!(l instanceof d))&&(this.remuxer=new d(s,t,r,this.logger)),(!o||!(o instanceof u))&&(this.demuxer=new u(s,t,r,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 Nm(this.config)),e}}function AD(i,e){let t=null;return i.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const kc=i=>({remuxResult:{},chunkMeta:i});function yo(i){return"then"in i&&i.then instanceof Function}class SD{constructor(e,t,s,r,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=r,this.defaultInitPts=n||null}}class ID{constructor(e,t,s,r,n,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=r,this.timeOffset=n,this.initSegmentChange=a}}let E0=0;class xb{constructor(e,t,s,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=E0++,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=l=>{const d=l.data,u=this.hls;if(!(!u||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var c;const h=(c=this.workerContext)==null?void 0:c.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{u.logger[d.data.logType]&&u.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,u.trigger(d.event,d.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const d=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};const n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=s,this.onFlush=r;const a=(l,d)=>{d=d||{},d.frag=this.frag||void 0,l===y.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(l,d)};this.observer=new Hm,this.observer.on(y.FRAG_DECRYPTED,a),this.observer.on(y.ERROR,a);const o=Mg(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(n.workerPath||kk()){try{n.workerPath?(l.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=Ck(n.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=Dk());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:$e(n)})}catch(u){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new v0(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new v0(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=E0++;const t=this.hls.config,s=Mg(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:$e(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),wk(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,r,n,a,o,l,d,u){var c,h;d.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:m}=this,p=a?a.start:n.start,g=n.decryptdata,v=this.frag,b=!(v&&n.cc===v.cc),E=!(v&&d.level===v.level),T=v?d.sn-v.sn:-1,A=this.part?d.part-this.part.index:-1,x=T===0&&d.id>1&&d.id===v?.stats.chunkCount,S=!E&&(T===1||T===0&&(A===1||x&&A<=0)),L=self.performance.now();(E||T||n.stats.parsing.start===0)&&(n.stats.parsing.start=L),a&&(A||!S)&&(a.stats.parsing.start=L);const R=!(v&&((c=n.initSegment)==null?void 0:c.url)===((h=v.initSegment)==null?void 0:h.url)),I=new ID(b,S,l,E,p,R);if(!S||b||R){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===J.MAIN?"level":"track"}: ${d.level} id: ${d.id}
|
|
1432
|
+
${t.m3u8}`)}function eb(i,e,t=!0){const s=e.startSN+e.skippedSegments-i.startSN,r=i.fragments,n=s>=0;let a=0;if(n&&s<r.length)a=r[s].start;else if(n&&e.startSN===i.endSN+1)a=i.fragmentEnd;else if(n&&t)a=i.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=i.fragmentStart;else return;Vh(e,a)}function Vh(i,e){if(e){const t=i.fragments;for(let s=i.skippedSegments;s<t.length;s++)t[s].addStart(e);i.fragmentHint&&i.fragmentHint.addStart(e)}}function tb(i,e=1/0){let t=1e3*i.targetduration;if(i.updated){const s=i.fragments;if(s.length&&t*4>e){const n=s[s.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function ib(i,e,t){if(!i)return null;let s=i.fragments[e-i.startSN];return s||(s=i.fragmentHint,s&&s.sn===e)?s:e<i.startSN&&t&&t.sn===e?t:null}function l0(i,e,t){return i?sb(i.partList,e,t):null}function sb(i,e,t){if(i)for(let s=i.length;s--;){const r=i[s];if(r.index===t&&r.fragment.sn===e)return r}return null}function rb(i){i.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(r=>{r.level=t,r.initSegment&&(r.initSegment.level=t)})})}function _k(i,e){return i!==e&&e?d0(i)!==d0(e):!1}function d0(i){return i.replace(/\?[^?]*$/,"")}function za(i,e){for(let s=0,r=i.length;s<r;s++){var t;if(((t=i[s])==null?void 0:t.cc)===e)return i[s]}return null}function Ak(i,e){return!!(i&&e.startCC<i.endCC&&e.endCC>i.startCC)}function u0(i,e){const t=i.start+e;i.startPTS=t,i.setStart(t),i.endPTS=t+i.duration}function nb(i,e){const t=e.fragments;for(let s=0,r=t.length;s<r;s++)u0(t[s],i);e.fragmentHint&&u0(e.fragmentHint,i),e.alignedSliding=!0}function Sk(i,e){i&&(ab(e,i),e.alignedSliding||iu(e,i),!e.alignedSliding&&!e.skippedSegments&&eb(i,e,!1))}function ab(i,e){if(!Ak(e,i))return;const t=Math.min(e.endCC,i.endCC),s=za(e.fragments,t),r=za(i.fragments,t);if(!s||!r)return;we.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const n=s.start-r.start;nb(n,i)}function iu(i,e){if(!i.hasProgramDateTime||!e.hasProgramDateTime)return;const t=i.fragments,s=e.fragments;if(!t.length||!s.length)return;let r,n;const a=Math.min(e.endCC,i.endCC);e.startCC<a&&i.startCC<a&&(r=za(s,a),n=za(t,a)),(!r||!n)&&(r=s[Math.floor(s.length/2)],n=za(t,r.cc)||t[Math.floor(t.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;const d=(l-o)/1e3-(n.start-r.start);nb(d,i)}function wt(i,e,t){Nt(i,e,t),i.addEventListener(e,t)}function Nt(i,e,t){i.removeEventListener(e,t)}const Ik={toString:function(i){let e="";const t=i.length;for(let s=0;s<t;s++)e+=`[${i.start(s).toFixed(3)}-${i.end(s).toFixed(3)}]`;return e}},P={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class Bm extends Wy{constructor(e,t,s,r,n){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=P.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:a,fragCurrent:o,media:l,mediaBuffer:d,state:u}=this,c=l?l.currentTime:0,h=ue.bufferInfo(d||l,c,a.maxBufferHole),f=!h.len;if(this.log(`Media seeking to ${X(c)?c.toFixed(3):c}, state: ${u}, ${f?"out of":"in"} buffer`),this.state===P.ENDED)this.resetLoadingState();else if(o){const m=a.maxFragLookUpTolerance,p=o.start-m,g=o.start+o.duration+m;if(f||g<h.start||p>h.end){const v=c>g;(c<p||v)&&(v&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0);const m=this.lastCurrentTime;if(c>m&&(this.lastCurrentTime=c),!this.loadingParts){const p=Math.max(h.end,c),g=this.shouldLoadParts(this.getLevelDetails(),p);g&&(this.log(`LL-Part loading ON after seeking to ${c.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=g)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${c} for seek without enough to start`),this.nextLoadPosition=c,f&&(this.startPosition=c)),f&&this.state===P.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=e,this.fragmentLoader=new JR(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Nm(e.config)}registerListeners(){const{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===P.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=P.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,r=this.config.timelineOffset||0;if(s<=r)return!1;const n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=ue.bufferedInfo(n,e.start,0));const a=e.nextStart;if(a&&a>r&&a<t.edge||this.media.currentTime<e.start)return!1;const l=t.partList;if(l!=null&&l.length){const u=l[l.length-1];return ue.isBuffered(this.media,u.start+u.duration/2)}const d=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(d)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;wt(s,"seeking",this.onMediaSeeking),wt(s,"ended",this.onMediaEnded);const r=this.config;this.levels&&r.autoStartLoad&&this.state===P.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,r=this.media;if(r!==null){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Nt(r,"seeking",this.onMediaSeeking),Nt(r,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=P.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const r=n=>{const a=n.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,!1,n.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,s,r).then(n=>{if(!n)return;const a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===P.FRAG_LOADING||!this.fragCurrent&&a===P.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=P.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(y.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(`Frag error: ${n?.message||n}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===gt.APPENDING){const n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.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)===gt.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const r={startOffset:e,endOffset:t,type:s};this.hls.trigger(y.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const r=s?.frag;if(!r||this.fragContextChanged(r)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:r}=this,{frag:n,payload:a}=s,o=n.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&Un(o.method)){const l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,$m(o.method)).catch(d=>{throw r.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:n}),d}).then(d=>{const u=self.performance.now();return r.trigger(y.FRAG_DECRYPTED,{frag:n,payload:d,stats:{tstart:l,tdecrypt:u}}),s.payload=d,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==P.STOPPED&&(this.state=P.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,r;const n=e.tracks;if(n&&!t.encrypted&&((s=n.audio)!=null&&s.encrypted||(r=n.video)!=null&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(y.ERROR,{type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?Ik.toString(ue.getBuffered(s)):"(detached)"})`),et(e)){var r;if(e.type!==J.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=P.IDLE;return}}const n=(r=this.levels)==null?void 0:r[e.level];n!=null&&n.fragmentError&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0)}this.state=P.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:r,partsLoaded:n}=e,a=!n||n.length===0||n.some(l=>!l),o=new Um(s.level,s.sn,s.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,r){var n;this.fragCurrent=e;const a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((n=e.decryptdata)!=null&&n.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=P.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(y.KEY_LOADED,h),this.state===P.KEY_LOADING&&(this.state=P.IDLE),h}),this.hls.trigger(y.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const l=this.fragPrevious;if(et(e)&&(!l||e.sn!==l.sn)){const h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${l?.sn}->${e.sn}`),this.loadingParts=h)}if(s=Math.max(e.start,s||0),this.loadingParts&&et(e)){const h=a.partList;if(h&&r){s>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const f=this.getNextPart(h,e,s);if(f>-1){const m=h[f];e=this.fragCurrent=m.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${f}/${h.length-1}) of ${this.fragInfo(e,!1,m)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=m.start+m.duration,this.state=P.FRAG_LOADING;let p;return o?p=o.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,m,t,r)).catch(g=>this.handleFragLoadError(g)):p=this.doFragPartsLoad(e,m,t,r).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(y.FRAG_LOADING,{frag:e,part:m,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(h,s))return Promise.resolve(null)}}if(et(e)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(d=a.partList)==null?void 0:d.filter(h=>h.loaded).map(h=>`[${h.start}-${h.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),X(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=P.FRAG_LOADING;const u=this.config.progressive&&e.type!==J.SUBTITLE;let c;return u&&o?c=o.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,r)).catch(h=>this.handleFragLoadError(h)):c=Promise.all([this.fragmentLoader.load(e,u?r:void 0),o]).then(([h])=>(!u&&r&&r(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(y.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,s,r){return new Promise((n,a)=>{var o;const l=[],d=(o=s.details)==null?void 0:o.partList,u=c=>{this.fragmentLoader.loadPart(e,c,r).then(h=>{l[c.index]=h;const f=h.part;this.hls.trigger(y.FRAG_LOADED,h);const m=l0(s.details,e.sn,c.index+1)||sb(d,e.sn,c.index+1);if(m)u(m);else return n({frag:e,part:f,partsLoaded:l})}).catch(a)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===w.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===ie.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(y.ERROR,t)}else this.hls.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==P.PARSING){!this.fragCurrent&&this.state!==P.STOPPED&&this.state!==P.ERROR&&(this.state=P.IDLE);return}const{frag:s,part:r,level:n}=t,a=self.performance.now();s.stats.parsing.end=a,r&&(r.stats.parsing.end=a);const o=this.getLevelDetails(),d=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(s,r,n,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const n=e.partList[0];if(n.fragment.type===J.SUBTITLE)return!1;const a=n.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=a){var r;if((this.hls.hasEnoughToStart?((r=this.media)==null?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:r,sn:n,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;const o=t[r],l=o.details,d=a>-1?l0(l,n,a):null,u=d?d.fragment:ib(l,n,s);return u?(s&&s!==u&&(u.stats=s.stats),{frag:u,part:d,level:o}):null}bufferFragmentData(e,t,s,r,n){if(this.state!==P.PARSING)return;const{data1:a,data2:o}=e;let l=a;if(o&&(l=li(a,o)),!l.length)return;const d=this.initPTS[t.cc],u=d?-d.baseTime/d.timescale:void 0,c={type:e.type,frag:t,part:s,chunkMeta:r,offset:u,parent:t.type,data:l};if(this.hls.trigger(y.BUFFER_APPENDING,c),e.dropped&&e.independent&&!s){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!ue.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,r=ue.bufferInfo(t,s,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,r.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;const r=this.getLoadPosition();if(!X(r))return null;const a=this.lastCurrentTime>r||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,a)}getFwdBufferInfoAtPos(e,t,s,r){const n=ue.bufferInfo(e,t,r);if(n.len===0&&n.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&(n.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(n.nextStart,a.end)-t,r);return ue.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,r=Math.max(Math.min(e-t,s.maxBufferLength),t),n=Math.max(e-t*3,s.maxMaxBufferLength/2,r);return n>=r?(s.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(e,t=J.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,r=s.length;if(!r)return null;const{config:n}=this,a=s[0].start,o=n.lowLatencyMode&&!!t.partList;let l=null;if(t.live){const c=n.initialLiveManifestSize;if(r<c)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${c})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var d;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(t);const h=this.hls.startPosition,f=this.hls.liveSyncPosition,m=l?(h!==-1&&h>=a?h:f)||l.start:e;this.log(`Setting startPosition to ${m} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${f} frag.start: ${(d=l)==null?void 0:d.start}`),this.startPosition=this.nextLoadPosition=m}}else e<=a&&(l=s[0]);if(!l){const c=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,c,t)}let u=this.filterReplacedPrimary(l,t);if(!u&&l){const c=l.sn-t.startSN;u=this.filterReplacedPrimary(s[c+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===gt.OK||s===gt.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,r,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,r,0);if(o!==null&&s.len+o.len>=n){const l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(c0(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(c0(this.config)&&e.type!==J.SUBTITLE){const s=this.hls.interstitialsManager,r=s?.bufferingItem;if(r){const a=r.event;if(a){if(a.appendInPlace||Math.abs(e.start-r.start)>1||r.start===0)return null}else if(e.end<=r.start&&t?.live===!1||e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}const n=s?.playerQueue;if(n)for(let a=n.length;a--;){const o=n[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let r=-1,n=!1,a=!0;for(let o=0,l=e.length;o<l;o++){const d=e[o];if(a=a&&!d.independent,r>-1&&s<d.start)break;const u=d.loaded;u?r=-1:(n||(d.independent||a)&&d.fragment===t)&&(d.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${d.start}`),r=o),n=u}return r}loadedEndOfParts(e,t){let s;for(let r=e.length;r--;){if(s=e[r],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let r=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),r=HR(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const n=s.sn+1;if(n>=e.startSN&&n<=e.endSN){const a=t[n-e.startSN];s.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=Gy(e,s.cc,s.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const n=this.hls.liveSyncPosition;n!==null&&(r=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,s){const{config:r}=this;let{fragPrevious:n}=this,{fragments:a,endSN:o}=s;const{fragmentHint:l}=s,{maxFragLookUpTolerance:d}=r,u=s.partList,c=!!(this.loadingParts&&u!=null&&u.length&&l);c&&!this.bitrateTest&&u[u.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn);let h;if(e<t){var f;const p=e<this.lastCurrentTime||e>t-d||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:d;h=Mr(n,a,e,p)}else h=a[a.length-1];if(h){const m=h.sn-s.startSN,p=this.fragmentTracker.getState(h);if((p===gt.OK||p===gt.PARTIAL&&h.gap)&&(n=h),n&&h.sn===n.sn&&(!c||u[0].fragment.sn>h.sn||!s.live)&&h.level===n.level){const v=a[m+1];h.sn<o&&this.fragmentTracker.getState(v)!==gt.OK?h=v:h=null}}return h}alignPlaylists(e,t,s){const r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const n=e.fragmentStart,a=!t,o=e.alignedSliding&&X(n);if(a||!o&&!n){Sk(s,e);const l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${r}`),l}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const r=this.timelineOffset;if(s===-1){const n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;a!==null&&X(a)?(s=t+a,a<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+r}this.nextLoadPosition=s+r}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&&et(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==P.FRAG_LOADING_WAITING_RETRY)&&(this.state=P.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const v=this.getCurrentContext(t.chunkMeta);v&&(t.frag=v.frag)}const r=t.frag;if(!r||r.type!==e||!this.levels)return;if(this.fragContextChanged(r)){var n;this.warn(`Frag load error must match current frag to retry ${r.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}const a=t.details===w.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(r,!0);const o=t.errorAction;if(!o){this.state=P.ERROR;return}const{action:l,flags:d,retryCount:u=0,retryConfig:c}=o,h=!!c,f=h&&l===St.RetryRequest,m=h&&!o.resolved&&d===Wt.MoveAllAlternatesMatchingHost,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!f&&m&&et(r)&&!r.endList&&p&&!Vy(t))this.resetFragmentErrors(e),this.treatAsGap(r),o.resolved=!0;else if((f||m)&&u<c.maxNumRetry){var g;const v=Bh((g=t.response)==null?void 0:g.code),b=Om(c,u);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+b,this.state=P.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,v){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${u+1}/${c.maxNumRetry} in ${b}ms`)}else if(c)if(this.resetFragmentErrors(e),u<c.maxNumRetry)!a&&l!==St.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${u})`);return}else l===St.SendAlternateToPenaltyBox?this.state=P.WAITING_LEVEL:this.state=P.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Bh(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=P.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===P.PARSING||this.state===P.PARSED){const t=e.frag,s=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,s),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.len,t?.duration||10);const a=!n;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===J.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==P.STOPPED&&(this.state=P.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const r=ue.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,s),this.state===P.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==P.STOPPED&&(this.state=P.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,r){const n=s.details;if(!n){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,d)=>{const u=e.elementaryStreams[d];if(u){const c=u.endPTS-u.startPTS;if(c<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${c})`),l||!1;const h=r?0:Jy(n,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(y.LEVEL_PTS_UPDATED,{details:n,level:s,drift:h,type:d,frag:e,start:u.startPTS,end:u.endPTS}),!0}return l},!1)){var o;const l=((o=this.transmuxer)==null?void 0:o.error)===null;if((s.fragmentError===0||l&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),l){const d=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(d.message),this.hls.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,error:d,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=P.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(y.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===J.MAIN?"level":"track"}fragInfo(e,t=!0,s){var r,n;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((r=t&&!s?e.startPTS:(s||e).start)!=null?r:NaN).toFixed(3)}-${((n=t&&!s?e.endPTS:(s||e).end)!=null?n:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function c0(i){return!!i.interstitialsController&&i.enableInterstitialPlayback!==!1}class ob{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=xk(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function xk(i,e){const t=new Uint8Array(e);let s=0;for(let r=0;r<i.length;r++){const n=i[r];t.set(n,s),s+=n.length}return t}var Ic={exports:{}},h0;function Lk(){return h0||(h0=1,(function(i){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function r(l,d,u){this.fn=l,this.context=d,this.once=u||!1}function n(l,d,u,c,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new r(u,c||l,h),m=t?t+d:d;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],f]:l._events[m].push(f):(l._events[m]=f,l._eventsCount++),l}function a(l,d){--l._eventsCount===0?l._events=new s:delete l._events[d]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],u,c;if(this._eventsCount===0)return d;for(c in u=this._events)e.call(u,c)&&d.push(t?c.slice(1):c);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(u)):d},o.prototype.listeners=function(d){var u=t?t+d:d,c=this._events[u];if(!c)return[];if(c.fn)return[c.fn];for(var h=0,f=c.length,m=new Array(f);h<f;h++)m[h]=c[h].fn;return m},o.prototype.listenerCount=function(d){var u=t?t+d:d,c=this._events[u];return c?c.fn?1:c.length:0},o.prototype.emit=function(d,u,c,h,f,m){var p=t?t+d:d;if(!this._events[p])return!1;var g=this._events[p],v=arguments.length,b,E;if(g.fn){switch(g.once&&this.removeListener(d,g.fn,void 0,!0),v){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,u),!0;case 3:return g.fn.call(g.context,u,c),!0;case 4:return g.fn.call(g.context,u,c,h),!0;case 5:return g.fn.call(g.context,u,c,h,f),!0;case 6:return g.fn.call(g.context,u,c,h,f,m),!0}for(E=1,b=new Array(v-1);E<v;E++)b[E-1]=arguments[E];g.fn.apply(g.context,b)}else{var T=g.length,A;for(E=0;E<T;E++)switch(g[E].once&&this.removeListener(d,g[E].fn,void 0,!0),v){case 1:g[E].fn.call(g[E].context);break;case 2:g[E].fn.call(g[E].context,u);break;case 3:g[E].fn.call(g[E].context,u,c);break;case 4:g[E].fn.call(g[E].context,u,c,h);break;default:if(!b)for(A=1,b=new Array(v-1);A<v;A++)b[A-1]=arguments[A];g[E].fn.apply(g[E].context,b)}}return!0},o.prototype.on=function(d,u,c){return n(this,d,u,c,!1)},o.prototype.once=function(d,u,c){return n(this,d,u,c,!0)},o.prototype.removeListener=function(d,u,c,h){var f=t?t+d:d;if(!this._events[f])return this;if(!u)return a(this,f),this;var m=this._events[f];if(m.fn)m.fn===u&&(!h||m.once)&&(!c||m.context===c)&&a(this,f);else{for(var p=0,g=[],v=m.length;p<v;p++)(m[p].fn!==u||h&&!m[p].once||c&&m[p].context!==c)&&g.push(m[p]);g.length?this._events[f]=g.length===1?g[0]:g:a(this,f)}return this},o.prototype.removeAllListeners=function(d){var u;return d?(u=t?t+d:d,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,i.exports=o})(Ic)),Ic.exports}var Rk=Lk(),Hm=JL(Rk);const vo="1.6.15",Zn={};function kk(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Dk(){const i=Zn[vo];if(i)return i.clientCount++,i;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),r={worker:new self.Worker(t),objectURL:t,clientCount:1};return Zn[vo]=r,r}function Ck(i){const e=Zn[i];if(e)return e.clientCount++,e;const t=new self.URL(i,self.location.href).href,r={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Zn[i]=r,r}function wk(i){const e=Zn[i||vo];if(e&&e.clientCount--===1){const{worker:s,objectURL:r}=e;delete Zn[i||vo],r&&self.URL.revokeObjectURL(r),s.terminate()}}function lb(i,e){return e+10<=i.length&&i[e]===51&&i[e+1]===68&&i[e+2]===73&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function Gm(i,e){return e+10<=i.length&&i[e]===73&&i[e+1]===68&&i[e+2]===51&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function Yu(i,e){let t=0;return t=(i[e]&127)<<21,t|=(i[e+1]&127)<<14,t|=(i[e+2]&127)<<7,t|=i[e+3]&127,t}function Eo(i,e){const t=e;let s=0;for(;Gm(i,e);){s+=10;const r=Yu(i,e+6);s+=r,lb(i,e+10)&&(s+=10),e+=s}if(s>0)return i.subarray(t,t+s)}function Mk(i,e,t,s){const r=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[t+2],a=n>>2&15;if(a>12){const f=new Error(`invalid ADTS sampling index:${a}`);i.emit(y.ERROR,y.ERROR,{type:ie.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(n>>6&3)+1,l=e[t+3]>>6&3|(n&1)<<2,d="mp4a.40."+o,u=r[a];let c=a;(o===5||o===29)&&(c-=3);const h=[o<<3|(c&14)>>1,(c&1)<<7|l<<3];return we.log(`manifest codec:${s}, parsed codec:${d}, channels:${l}, rate:${u} (ADTS object type:${o} sampling index:${a})`),{config:h,samplerate:u,channelCount:l,codec:d,parsedCodec:d,manifestCodec:s}}function db(i,e){return i[e]===255&&(i[e+1]&246)===240}function ub(i,e){return i[e+1]&1?7:9}function Km(i,e){return(i[e+3]&3)<<11|i[e+4]<<3|(i[e+5]&224)>>>5}function Pk(i,e){return e+5<i.length}function su(i,e){return e+1<i.length&&db(i,e)}function Ok(i,e){return Pk(i,e)&&db(i,e)&&Km(i,e)<=i.length-e}function Nk(i,e){if(su(i,e)){const t=ub(i,e);if(e+t>=i.length)return!1;const s=Km(i,e);if(s<=t)return!1;const r=e+s;return r===i.length||su(i,r)}return!1}function cb(i,e,t,s,r){if(!i.samplerate){const n=Mk(e,t,s,r);if(!n)return;Oe(i,n)}}function hb(i){return 1024*9e4/i}function Uk(i,e){const t=ub(i,e);if(e+t<=i.length){const s=Km(i,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function fb(i,e,t,s,r){const n=hb(i.samplerate),a=s+r*n,o=Uk(e,t);let l;if(o){const{frameLength:c,headerLength:h}=o,f=h+c,m=Math.max(0,t+f-e.length);m?(l=new Uint8Array(f-h),l.set(e.subarray(t+h,e.length),0)):l=e.subarray(t+h,t+f);const p={unit:l,pts:a};return m||i.samples.push(p),{sample:p,length:f,missing:m}}const d=e.length-t;return l=new Uint8Array(d),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:d,missing:-1}}function $k(i,e){return Gm(i,e)&&Yu(i,e+6)+10<=i.length-e}function Fk(i){return i instanceof ArrayBuffer?i:i.byteOffset==0&&i.byteLength==i.buffer.byteLength?i.buffer:new Uint8Array(i).buffer}function xc(i,e=0,t=1/0){return Bk(i,e,t,Uint8Array)}function Bk(i,e,t,s){const r=Hk(i);let n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);const a=Gk(i)?i.byteOffset:0,o=(a+i.byteLength)/n,l=(a+e)/n,d=Math.floor(Math.max(0,Math.min(l,o))),u=Math.floor(Math.min(d+Math.max(t,0),o));return new s(r,d,u-d)}function Hk(i){return i instanceof ArrayBuffer?i:i.buffer}function Gk(i){return i&&i.buffer instanceof ArrayBuffer&&i.byteLength!==void 0&&i.byteOffset!==void 0}function Kk(i){const e={key:i.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(i.size<2)return;if(i.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const s=i.data.subarray(1).indexOf(0);if(s===-1)return;const r=Xt(xc(i.data,1,s)),n=i.data[2+s],a=i.data.subarray(3+s).indexOf(0);if(a===-1)return;const o=Xt(xc(i.data,3+s,a));let l;return r==="-->"?l=Xt(xc(i.data,4+s+a)):l=Fk(i.data.subarray(4+s+a)),e.mimeType=r,e.pictureType=n,e.description=o,e.data=l,e}function Vk(i){if(i.size<2)return;const e=Xt(i.data,!0),t=new Uint8Array(i.data.subarray(e.length+1));return{key:i.type,info:e,data:t.buffer}}function Wk(i){if(i.size<2)return;if(i.type==="TXXX"){let t=1;const s=Xt(i.data.subarray(t),!0);t+=s.length+1;const r=Xt(i.data.subarray(t));return{key:i.type,info:s,data:r}}const e=Xt(i.data.subarray(1));return{key:i.type,info:"",data:e}}function qk(i){if(i.type==="WXXX"){if(i.size<2)return;let t=1;const s=Xt(i.data.subarray(t),!0);t+=s.length+1;const r=Xt(i.data.subarray(t));return{key:i.type,info:s,data:r}}const e=Xt(i.data);return{key:i.type,info:"",data:e}}function Yk(i){return i.type==="PRIV"?Vk(i):i.type[0]==="W"?qk(i):i.type==="APIC"?Kk(i):Wk(i)}function jk(i){const e=String.fromCharCode(i[0],i[1],i[2],i[3]),t=Yu(i,4),s=10;return{type:e,size:t,data:i.subarray(s,s+t)}}const Qo=10,zk=10;function mb(i){let e=0;const t=[];for(;Gm(i,e);){const s=Yu(i,e+6);i[e+5]>>6&1&&(e+=Qo),e+=Qo;const r=e+s;for(;e+zk<r;){const n=jk(i.subarray(e)),a=Yk(n);a&&t.push(a),e+=n.size+Qo}lb(i,e)&&(e+=Qo)}return t}function pb(i){return i&&i.key==="PRIV"&&i.info==="com.apple.streaming.transportStreamTimestamp"}function Qk(i){if(i.data.byteLength===8){const e=new Uint8Array(i.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 Vm(i){const e=mb(i);for(let t=0;t<e.length;t++){const s=e[t];if(pb(s))return Qk(s)}}let zt=(function(i){return i.audioId3="org.id3",i.dateRange="com.apple.quicktime.HLS",i.emsg="https://aomedia.org/emsg/ID3",i.misbklv="urn:misb:KLV:bin:1910.1",i})({});function Yi(i="",e=9e4){return{type:i,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Wm{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,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=li(this.cachedData,e),this.cachedData=null);let s=Eo(e,0),r=s?s.length:0,n;const a=this._audioTrack,o=this._id3Track,l=s?Vm(s):void 0,d=e.length;for((this.basePTS===null||this.frameIndex===0&&X(l))&&(this.basePTS=Xk(l,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:zt.audioId3,duration:Number.POSITIVE_INFINITY});r<d;){if(this.canParse(e,r)){const u=this.appendFrame(a,e,r);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r+=u.length,n=r):r=d}else $k(e,r)?(s=Eo(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:zt.audioId3,duration:Number.POSITIVE_INFINITY}),r+=s.length,n=r):r++;if(r===d&&n!==d){const u=e.slice(n);this.cachedData?this.cachedData=li(this.cachedData,u):this.cachedData=u}}return{audioTrack:a,videoTrack:Yi(),id3Track:o,textTrack:Yi()}}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:Yi(),id3Track:this._id3Track,textTrack:Yi()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Xk=(i,e,t)=>{if(X(i))return i*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let Xo=null;const Zk=[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],Jk=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],eD=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],tD=[0,1,1,4];function gb(i,e,t,s,r){if(t+24>e.length)return;const n=vb(e,t);if(n&&t+n.frameLength<=e.length){const a=n.samplesPerFrame*9e4/n.sampleRate,o=s+r*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return i.config=[],i.channelCount=n.channelCount,i.samplerate=n.sampleRate,i.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function vb(i,e){const t=i[e+1]>>3&3,s=i[e+1]>>1&3,r=i[e+2]>>4&15,n=i[e+2]>>2&3;if(t!==1&&r!==0&&r!==15&&n!==3){const a=i[e+2]>>1&1,o=i[e+3]>>6,l=t===3?3-s:s===3?3:4,d=Zk[l*14+r-1]*1e3,c=Jk[(t===3?0:t===2?1:2)*3+n],h=o===3?1:2,f=eD[t][s],m=tD[s],p=f*8*m,g=Math.floor(f*d/c+a)*m;if(Xo===null){const E=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Xo=E?parseInt(E[1]):0}return!!Xo&&Xo<=87&&s===2&&d>=224e3&&o===0&&(i[e+3]=i[e+3]|128),{sampleRate:c,channelCount:h,frameLength:g,samplesPerFrame:p}}}function qm(i,e){return i[e]===255&&(i[e+1]&224)===224&&(i[e+1]&6)!==0}function Eb(i,e){return e+1<i.length&&qm(i,e)}function iD(i,e){return qm(i,e)&&4<=i.length-e}function yb(i,e){if(e+1<i.length&&qm(i,e)){const s=vb(i,e);let r=4;s!=null&&s.frameLength&&(r=s.frameLength);const n=e+r;return n===i.length||Eb(i,n)}return!1}class sD extends Wm{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=Eo(e,0);let r=s?.length||0;if(yb(e,r))return!1;for(let n=e.length;r<n;r++)if(Nk(e,r))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Ok(e,t)}appendFrame(e,t,s){cb(e,this.observer,t,s,e.manifestCodec);const r=fb(e,t,s,this.basePTS,this.frameIndex);if(r&&r.missing===0)return r}}const bb=(i,e)=>{let t=0,s=5;e+=s;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=i[e];const o=Math.min(s,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,t=t?t<<o|r[0]:r[0],e+=1,s-=o}return t};class rD extends Wm{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const r=Tb(e,t,s,this.basePTS,this.frameIndex);if(r!==-1)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;const t=Eo(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&Vm(t)!==void 0&&bb(e,s)<16}}function Tb(i,e,t,s,r){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const n=e[t+4]>>6;if(n>=3)return-1;const o=[48e3,44100,32e3][n],l=e[t+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+n]*2;if(t+u>e.length)return-1;const c=e[t+6]>>5;let h=0;c===2?h+=2:(c&1&&c!==1&&(h+=2),c&4&&(h+=2));const f=(e[t+6]<<8|e[t+7])>>12-h&1,p=[2,1,2,3,3,4,4,5][c]+f,g=e[t+5]>>3,v=e[t+5]&7,b=new Uint8Array([n<<6|g<<1|v>>2,(v&3)<<6|c<<3|f<<2|l>>4,l<<4&224]),E=1536/o*9e4,T=s+r*E,A=e.subarray(t,t+u);return i.config=b,i.channelCount=p,i.samplerate=o,i.samples.push({unit:A,pts:T}),u}class nD extends Wm{resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Eo(e,0);let s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&Vm(t)!==void 0&&bb(e,s)<=16)return!1;for(let r=e.length;s<r;s++)if(yb(e,s))return we.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return iD(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return gb(e,t,s,this.basePTS,this.frameIndex)}}const aD=/\/emsg[-/]ID3/i;class oD{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,r){const n=this.videoTrack=Yi("video",1),a=this.audioTrack=Yi("audio",1),o=this.txtTrack=Yi("text",1);if(this.id3Track=Yi("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=Cy(e);if(l.video){const{id:d,timescale:u,codec:c,supplemental:h}=l.video;n.id=d,n.timescale=o.timescale=u,n.codec=c,n.supplemental=h}if(l.audio){const{id:d,timescale:u,codec:c}=l.audio;a.id=d,a.timescale=u,a.codec=c}o.id=Ry.text,n.sampleDuration=0,n.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return rR(e)}demux(e,t){this.timeOffset=t;let s=e;const r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=li(this.remainderData,e));const o=cR(s);this.remainderData=o.remainder,r.samples=o.valid||new Uint8Array}else r.samples=s;const a=this.extractID3Track(r,t);return n.samples=Dg(t,r),{videoTrack:r,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 r=this.extractID3Track(t,this.timeOffset);return s.samples=Dg(e,t),{videoTrack:t,audioTrack:Yi(),id3Track:r,textTrack:Yi()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const r=me(e.samples,["emsg"]);r&&r.forEach(n=>{const a=fR(n);if(aD.test(a.schemeIdUri)){const o=f0(a,t);let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const d=a.payload;s.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:zt.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=f0(a,t);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:zt.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 f0(i,e){return X(i.presentationTime)?i.presentationTime/i.timeScale:e+i.presentationTimeDelta/i.timeScale}class lD{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Nm(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Qs.cbc)}decryptAacSample(e,t,s){const r=e[t].unit;if(r.length<=16)return;const n=r.subarray(16,r.length-r.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);r.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let r=0;for(let n=32;n<e.length-16;n+=160,r+=16)s.set(e.subarray(n,n+16),r);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let r=0;for(let n=32;n<e.length-16;n+=160,r+=16)e.set(s.subarray(r,r+16),n);return e}decryptAvcSample(e,t,s,r,n){const a=Py(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,r)}).catch(r)}decryptAvcSamples(e,t,s,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){r();return}const n=e[t].units;for(;!(s>=n.length);s++){const a=n[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,s,r,a),!this.decrypter.isSync()))return}}}}class _b{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,r;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const n=s.units;r=n[n.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,r=s.length;if(r){const n=s[r-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const r=t.byteLength;let n=e.naluState||0;const a=n,o=[];let l=0,d,u,c,h=-1,f=0;for(n===-1&&(h=0,f=this.getNALuType(t,0),n=0,l=1);l<r;){if(d=t[l++],!n){n=d?0:1;continue}if(n===1){n=d?0:2;continue}if(!d)n=3;else if(d===1){if(u=l-n-1,h>=0){const m={data:t.subarray(h,u),type:f};o.push(m)}else{const m=this.getLastNalUnit(e.samples);m&&(a&&l<=4-a&&m.state&&(m.data=m.data.subarray(0,m.data.byteLength-a)),u>0&&(m.data=li(m.data,t.subarray(0,u)),m.state=0))}l<r?(c=this.getNALuType(t,l),h=l,f=c,n=0):n=-1}else n=0}if(h>=0&&n>=0){const m={data:t.subarray(h,r),type:f,state:n};o.push(m)}if(o.length===0){const m=this.getLastNalUnit(e.samples);m&&(m.data=li(m.data,t))}return e.naluState=n,o}}class Qa{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,r=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");r.set(e.subarray(s,s+n)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&we.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 dD extends _b{parsePES(e,t,s,r){const n=this.parseNALu(e,s.data,r);let a=this.VideoSample,o,l=!1;s.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach(d=>{var u,c;switch(d.type){case 1:{let p=!1;o=!0;const g=d.data;if(l&&g.length>4){const v=this.readSliceType(g);(v===2||v===4||v===7||v===9)&&(p=!0)}if(p){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=p;break}case 5:o=!0,(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,wm(d.data,1,s.pts,t.samples);break}case 7:{var f,m;o=!0,l=!0;const p=d.data,g=this.readSPS(p);if(!e.sps||e.width!==g.width||e.height!==g.height||((f=e.pixelRatio)==null?void 0:f[0])!==g.pixelRatio[0]||((m=e.pixelRatio)==null?void 0:m[1])!==g.pixelRatio[1]){e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.sps=[p];const v=p.subarray(1,4);let b="avc1.";for(let E=0;E<3;E++){let T=v[E].toString(16);T.length<2&&(T="0"+T),b+=T}e.codec=b}break}case 8:o=!0,e.pps=[d.data];break;case 9:o=!0,e.audFound=!0,(c=a)!=null&&c.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(d)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Qa(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,r=8,n;for(let a=0;a<e;a++)r!==0&&(n=t.readEG(),r=(s+n+256)%256),s=r===0?s:r}readSPS(e){const t=new Qa(e);let s=0,r=0,n=0,a=0,o,l,d;const u=t.readUByte.bind(t),c=t.readBits.bind(t),h=t.readUEG.bind(t),f=t.readBoolean.bind(t),m=t.skipBits.bind(t),p=t.skipEG.bind(t),g=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);u();const b=u();if(c(5),m(3),u(),g(),b===100||b===110||b===122||b===244||b===44||b===83||b===86||b===118||b===128){const L=h();if(L===3&&m(1),g(),g(),m(1),f())for(l=L!==3?8:12,d=0;d<l;d++)f()&&(d<6?v(16,t):v(64,t))}g();const E=h();if(E===0)h();else if(E===1)for(m(1),p(),p(),o=h(),d=0;d<o;d++)p();g(),m(1);const T=h(),A=h(),x=c(1);x===0&&m(1),m(1),f()&&(s=h(),r=h(),n=h(),a=h());let S=[1,1];if(f()&&f())switch(u()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:{S=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((T+1)*16-s*2-r*2),height:(2-x)*(A+1)*16-(x?2:4)*(n+a),pixelRatio:S}}}class uD extends _b{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,r){const n=this.parseNALu(e,s.data,r);let a=this.VideoSample,o,l=!1;s.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach(d=>{var u,c;switch(d.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,l){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 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,wm(d.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Oe(e.params,this.readVPS(d.data)),this.initVPS=d.data),e.vps=[d.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],d.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const f=this.readSPS(d.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 m in f.params)e.params[m]=f.params[m]}this.pushParameterSet(e.sps,d.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(d.data);for(const m in f)e.params[m]=f[m]}this.pushParameterSet(e.pps,d.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(c=a)!=null&&c.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(d)}),r&&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 r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[s]=e[r],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 Qa(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),r=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:r}}readSPS(e){const t=new Qa(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const r=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),u=t.readUByte(),c=t.readUByte(),h=t.readUByte(),f=t.readUByte(),m=t.readUByte(),p=t.readUByte(),g=t.readUByte(),v=t.readUByte(),b=[],E=[];for(let Te=0;Te<s;Te++)b.push(t.readBoolean()),E.push(t.readBoolean());if(s>0)for(let Te=s;Te<8;Te++)t.readBits(2);for(let Te=0;Te<s;Te++)b[Te]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),E[Te]&&t.readUByte();t.readUEG();const T=t.readUEG();T==3&&t.skipBits(1);const A=t.readUEG(),x=t.readUEG(),S=t.readBoolean();let L=0,R=0,I=0,M=0;S&&(L+=t.readUEG(),R+=t.readUEG(),I+=t.readUEG(),M+=t.readUEG());const B=t.readUEG(),q=t.readUEG(),z=t.readUEG(),K=t.readBoolean();for(let Te=K?0:s;Te<=s;Te++)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 ct=0;ct<4;ct++)for(let Ct=0;Ct<(ct===3?2:6);Ct++)if(!t.readBoolean())t.readUEG();else{const ei=Math.min(64,1<<4+(ct<<1));ct>1&&t.readEG();for(let _e=0;_e<ei;_e++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const G=t.readUEG();let N=0;for(let Te=0;Te<G;Te++){let ct=!1;if(Te!==0&&(ct=t.readBoolean()),ct){Te===G&&t.readUEG(),t.readBoolean(),t.readUEG();let Ct=0;for(let xi=0;xi<=N;xi++){const ei=t.readBoolean();let _e=!1;ei||(_e=t.readBoolean()),(ei||_e)&&Ct++}N=Ct}else{const Ct=t.readUEG(),xi=t.readUEG();N=Ct+xi;for(let ei=0;ei<Ct;ei++)t.readUEG(),t.readBoolean();for(let ei=0;ei<xi;ei++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const Te=t.readUEG();for(let ct=0;ct<Te;ct++){for(let Ct=0;Ct<z+4;Ct++)t.readBits(1);t.readBits(1)}}let U=0,$=1,re=1,he=!0,ce=1,pe=0;t.readBoolean(),t.readBoolean();let ut=!1;if(t.readBoolean()){if(t.readBoolean()){const Bt=t.readUByte(),Ro=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Br=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Bt>0&&Bt<16?($=Ro[Bt-1],re=Br[Bt-1]):Bt===255&&($=t.readBits(16),re=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(),ut=t.readBoolean(),ut&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ce=t.readBits(32),pe=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Br=t.readBoolean(),ko=t.readBoolean();let Js=!1;(Br||ko)&&(Js=t.readBoolean(),Js&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Js&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Do=0;Do<=s;Do++){he=t.readBoolean();const ac=he||t.readBoolean();let Co=!1;ac?t.readEG():Co=t.readBoolean();const Lt=Co?1:t.readUEG()+1;if(Br)for(let Ve=0;Ve<Lt;Ve++)t.readUEG(),t.readUEG(),Js&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(ko)for(let Ve=0;Ve<Lt;Ve++)t.readUEG(),t.readUEG(),Js&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),U=t.readUEG())}let Dt=A,Ft=x;if(S){let Te=1,ct=1;T===1?Te=ct=2:T==2&&(Te=2),Dt=A-Te*R-Te*L,Ft=x-ct*M-ct*I}const ci=r?["A","B","C"][r]:"",Ss=o<<24|l<<16|d<<8|u;let $r=0;for(let Te=0;Te<32;Te++)$r=($r|(Ss>>Te&1)<<31-Te)>>>0;let Fr=$r.toString(16);return a===1&&Fr==="2"&&(Fr="6"),{codecString:`hvc1.${ci}${a}.${Fr}.${n?"H":"L"}${v}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[o,l,d,u],general_constraint_indicator_flags:[c,h,f,m,p,g],general_level_idc:v,bit_depth:B+8,bit_depth_luma_minus8:B,bit_depth_chroma_minus8:q,min_spatial_segmentation_idc:U,chroma_format_idc:T,frame_rate:{fixed:he,fps:pe/ce}},width:Dt,height:Ft,pixelRatio:[$,re]}}readPPS(e){const t=new Qa(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 r=t.readBoolean(),n=t.readBoolean();let a=1;return n&&r?a=0:n?a=3:r&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Et=188;class Bs{constructor(e,t,s,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=r,this.videoParser=null}static probe(e,t){const s=Bs.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(Et*5,t-Et)+1,r=0;for(;r<s;){let n=!1,a=-1,o=0;for(let l=r;l<t;l+=Et)if(e[l]===71&&(t-l===Et||e[l+Et]===71)){if(o++,a===-1&&(a=l,a!==0&&(s=Math.min(a+Et*99,e.length-Et)+1)),n||(n=Wh(e,l)===0),n&&o>1&&(a===0&&o>2||l+Et>s))return a}else{if(o)return-1;break}r++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Ry[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Bs.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=Bs.createTrack("audio",r),this._id3Track=Bs.createTrack("id3"),this._txtTrack=Bs.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,r=!1){s||(this.sampleAes=null);let n;const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,d=this._txtTrack;let u=a.pid,c=a.pesData,h=o.pid,f=l.pid,m=o.pesData,p=l.pesData,g=null,v=this.pmtParsed,b=this._pmtId,E=e.length;if(this.remainderData&&(e=li(this.remainderData,e),E=e.length,this.remainderData=null),E<Et&&!r)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};const T=Math.max(0,Bs.syncOffset(e));E-=(E-T)%Et,E<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,E,e.buffer.byteLength-E));let A=0;for(let S=T;S<E;S+=Et)if(e[S]===71){const L=!!(e[S+1]&64),R=Wh(e,S),I=(e[S+3]&48)>>4;let M;if(I>1){if(M=S+5+e[S+4],M===S+Et)continue}else M=S+4;switch(R){case u:L&&(c&&(n=zr(c,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,d,n,!1)),c={data:[],size:0}),c&&(c.data.push(e.subarray(M,S+Et)),c.size+=S+Et-M);break;case h:if(L){if(m&&(n=zr(m,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n);break}m={data:[],size:0}}m&&(m.data.push(e.subarray(M,S+Et)),m.size+=S+Et-M);break;case f:L&&(p&&(n=zr(p,this.logger))&&this.parseID3PES(l,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(M,S+Et)),p.size+=S+Et-M);break;case 0:L&&(M+=e[M]+1),b=this._pmtId=cD(e,M);break;case b:{L&&(M+=e[M]+1);const B=hD(e,M,this.typeSupported,s,this.observer,this.logger);u=B.videoPid,u>0&&(a.pid=u,a.segmentCodec=B.segmentVideoCodec),h=B.audioPid,h>0&&(o.pid=h,o.segmentCodec=B.segmentAudioCodec),f=B.id3Pid,f>0&&(l.pid=f),g!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${S} after unknown PID '${g}'. Backtracking to sync byte @${T} to parse all TS packets.`),g=null,S=T-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=R;break}}else A++;A>0&&qh(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=c,o.pesData=m,l.pesData=p;const x={audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};return r&&this.extractRemainingSamples(x),x}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:r,textTrack:n}=e,a=s.pesData,o=t.pesData,l=r.pesData;let d;if(a&&(d=zr(a,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,n,d,!0),s.pesData=null)):s.pesData=a,o&&(d=zr(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,d);break;case"mp3":this.parseMPEGPES(t,d);break;case"ac3":this.parseAC3PES(t,d);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(d=zr(l,this.logger))?(this.parseID3PES(r,d),r.pesData=null):r.pesData=l}demuxSampleAes(e,t,s){const r=this.demux(e,s,!0,!this.config.progressive),n=this.sampleAes=new lD(this.observer,this.config,t);return this.decrypt(r,n)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new dD:e==="hevc"&&(this.videoParser=new uD))}decrypt(e,t){return new Promise(s=>{const{audioTrack:r,videoTrack:n}=e;r.samples&&r.segmentCodec==="aac"?t.decryptAacSamples(r.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{s(e)}):s(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const r=this.aacOverFlow;let n=t.data;if(r){this.aacOverFlow=null;const c=r.missing,h=r.sample.unit.byteLength;if(c===-1)n=li(r.sample.unit,n);else{const f=h-c;r.sample.unit.set(n.subarray(0,c),f),e.samples.push(r.sample),s=r.missing}}let a,o;for(a=s,o=n.length;a<o-1&&!su(n,a);a++);if(a!==s){let c;const h=a<o-1;if(h?c=`AAC PES did not start with ADTS header,offset:${a}`:c="No ADTS header found in AAC PES",qh(this.observer,new Error(c),h,this.logger),!h)return}cb(e,this.observer,n,a,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(r){const c=hb(e.samplerate);l=r.sample.pts+c}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let d=0,u;for(;a<o;)if(u=fb(e,n,a,l,d),a+=u.length,u.missing){this.aacOverFlow=u;break}else for(d++;a<o-1&&!su(n,a);a++);}parseMPEGPES(e,t){const s=t.data,r=s.length;let n=0,a=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<r;)if(Eb(s,a)){const l=gb(e,s,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(e,t){{const s=t.data,r=t.pts;if(r===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const n=s.length;let a=0,o=0,l;for(;o<n&&(l=Tb(e,s,o,r,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=Oe({},t,{type:this._videoTrack?zt.emsg:zt.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Wh(i,e){return((i[e+1]&31)<<8)+i[e+2]}function cD(i,e){return(i[e+10]&31)<<8|i[e+11]}function hD(i,e,t,s,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(i[e+1]&15)<<8|i[e+2],l=e+3+o-4,d=(i[e+10]&15)<<8|i[e+11];for(e+=12+d;e<l;){const u=Wh(i,e),c=(i[e+3]&15)<<8|i[e+4];switch(i[e]){case 207:if(!s){Lc("ADTS AAC",n);break}case 15:a.audioPid===-1&&(a.audioPid=u);break;case 21:a.id3Pid===-1&&(a.id3Pid=u);break;case 219:if(!s){Lc("H.264",n);break}case 27:a.videoPid===-1&&(a.videoPid=u);break;case 3:case 4:!t.mpeg&&!t.mp3?n.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=u,a.segmentAudioCodec="mp3");break;case 193:if(!s){Lc("AC-3",n);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=u,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&c>0){let h=e+5,f=c;for(;f>2;){switch(i[h]){case 106:t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=u,a.segmentAudioCodec="ac3");break}const p=i[h+1]+2;h+=p,f-=p}}break;case 194:case 135:return qh(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:a.videoPid===-1&&(a.videoPid=u,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}e+=c+5}return a}function qh(i,e,t,s){s.warn(`parsing error: ${e.message}`),i.emit(y.ERROR,y.ERROR,{type:ie.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Lc(i,e){e.log(`${i} with AES-128-CBC encryption found in unencrypted stream`)}function zr(i,e){let t=0,s,r,n,a,o;const l=i.data;if(!i||i.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=li(l[0],l[1]),l.splice(1,1);if(s=l[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(r=(s[4]<<8)+s[5],r&&r>i.size-6)return null;const u=s[7];u&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,u&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=s[8];let c=n+9;if(i.size<=c)return null;i.size-=c;const h=new Uint8Array(i.size);for(let f=0,m=l.length;f<m;f++){s=l[f];let p=s.byteLength;if(c)if(c>p){c-=p;continue}else s=s.subarray(c),p-=c,c=0;h.set(s,t),t+=p}return r&&(r-=n+3),{data:h,pts:a,dts:o,len:r}}return null}class fD{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 Rs=Math.pow(2,32)-1;class D{static init(){D.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 D.types)D.types.hasOwnProperty(e)&&(D.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]);D.HDLR_TYPES={video:t,audio:s};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);D.STTS=D.STSC=D.STCO=n,D.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),D.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),D.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),D.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);D.FTYP=D.box(D.types.ftyp,a,l,a,o),D.DINF=D.box(D.types.dinf,D.box(D.types.dref,r))}static box(e,...t){let s=8,r=t.length;const n=r;for(;r--;)s+=t[r].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),r=0,s=8;r<n;r++)a.set(t[r],s),s+=t[r].byteLength;return a}static hdlr(e){return D.box(D.types.hdlr,D.HDLR_TYPES[e])}static mdat(e){return D.box(D.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(Rs+1)),r=Math.floor(t%(Rs+1));return D.box(D.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,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(e){return D.box(D.types.mdia,D.mdhd(e.timescale||0,e.duration||0),D.hdlr(e.type),D.minf(e))}static mfhd(e){return D.box(D.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"?D.box(D.types.minf,D.box(D.types.smhd,D.SMHD),D.DINF,D.stbl(e)):D.box(D.types.minf,D.box(D.types.vmhd,D.VMHD),D.DINF,D.stbl(e))}static moof(e,t,s){return D.box(D.types.moof,D.mfhd(e),D.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=D.trak(e[t]);return D.box.apply(null,[D.types.moov,D.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(D.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=D.trex(e[t]);return D.box.apply(null,[D.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(Rs+1)),r=Math.floor(t%(Rs+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,r>>24,r>>16&255,r>>8&255,r&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return D.box(D.types.mvhd,n)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let r,n;for(r=0;r<t.length;r++)n=t[r].flags,s[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return D.box(D.types.sdtp,s)}static stbl(e){return D.box(D.types.stbl,D.stsd(e),D.box(D.types.stts,D.STTS),D.box(D.types.stsc,D.STSC),D.box(D.types.stsz,D.STSZ),D.box(D.types.stco,D.STCO))}static avc1(e){let t=[],s=[],r,n,a;for(r=0;r<e.sps.length;r++)n=e.sps[r],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(r=0;r<e.pps.length;r++)n=e.pps[r],a=n.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(n));const o=D.box(D.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),l=e.width,d=e.height,u=e.pixelRatio[0],c=e.pixelRatio[1];return D.box(D.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,D.box(D.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),D.box(D.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,c>>24,c>>16&255,c>>8&255,c&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 D.box(D.types.mp4a,D.audioStsd(e),D.box(D.types.esds,D.esds(e)))}static mp3(e){return D.box(D.types[".mp3"],D.audioStsd(e))}static ac3(e){return D.box(D.types["ac-3"],D.audioStsd(e),D.box(D.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return D.box(D.types.stsd,D.STSD,D.mp4a(e));if(t==="ac3"&&e.config)return D.box(D.types.stsd,D.STSD,D.ac3(e));if(t==="mp3"&&e.codec==="mp3")return D.box(D.types.stsd,D.STSD,D.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return D.box(D.types.stsd,D.STSD,D.avc1(e));if(t==="hevc"&&e.vps)return D.box(D.types.stsd,D.STSD,D.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),r=e.width||0,n=e.height||0,a=Math.floor(s/(Rs+1)),o=Math.floor(s%(Rs+1));return D.box(D.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,r&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){const s=D.sdtp(e),r=e.id,n=Math.floor(t/(Rs+1)),a=Math.floor(t%(Rs+1));return D.box(D.types.traf,D.box(D.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),D.box(D.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),D.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,D.box(D.types.trak,D.tkhd(e),D.mdia(e))}static trex(e){const t=e.id;return D.box(D.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||[],r=s.length,n=12+16*r,a=new Uint8Array(n);let o,l,d,u,c,h;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<r;o++)l=s[o],d=l.duration,u=l.size,c=l.flags,h=l.cts,a.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,c.degradPrio&61440,c.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*o);return D.box(D.types.trun,a)}static initSegment(e){D.types||D.init();const t=D.moov(e);return li(D.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],r=4,n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),r-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let a=n.length;for(let m=0;m<s.length;m+=1){a+=3;for(let p=0;p<s[m].length;p+=1)a+=2+s[m][p].length}const o=new Uint8Array(a);o.set(n,0),a=n.length;const l=s.length-1;for(let m=0;m<s.length;m+=1){o.set(new Uint8Array([32+m|(m===l?128:0),0,s[m].length]),a),a+=3;for(let p=0;p<s[m].length;p+=1)o.set(new Uint8Array([s[m][p].length>>8,s[m][p].length&255]),a),a+=2,o.set(s[m][p],a),a+=s[m][p].length}const d=D.box(D.types.hvcC,o),u=e.width,c=e.height,h=e.pixelRatio[0],f=e.pixelRatio[1];return D.box(D.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,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,D.box(D.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),D.box(D.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}}D.types=void 0;D.HDLR_TYPES=void 0;D.STTS=void 0;D.STSC=void 0;D.STCO=void 0;D.STSZ=void 0;D.VMHD=void 0;D.SMHD=void 0;D.STSD=void 0;D.FTYP=void 0;D.DINF=void 0;const Ab=9e4;function Ym(i,e,t=1,s=!1){const r=i*e*t;return s?Math.round(r):r}function mD(i,e,t=1,s=!1){return Ym(i,e,1/t,s)}function ca(i,e=!1){return Ym(i,1e3,1/Ab,e)}function pD(i,e=1){return Ym(i,Ab,1/e)}function m0(i){const{baseTime:e,timescale:t,trackId:s}=i;return`${e/t} (${e}/${t}) trackId: ${s}`}const gD=10*1e3,vD=1024,ED=1152,yD=1536;let Qr=null,Rc=null;function p0(i,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:i?2:1,isNonSync:i?0:1}}}class Vl extends di{constructor(e,t,s,r){if(super("mp4-remuxer",r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,Qr===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Qr=a?parseInt(a[1]):0}if(Rc===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);Rc=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&m0(t)} > ${e&&m0(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,r=e.reduce((n,a)=>{let o=a.pts,l=o-n;return l<-4294967296&&(t=!0,o=jt(o,s),l=o-n),l>0?n:o},s);return t&&this.debug("PTS rollover detected"),r}remux(e,t,s,r,n,a,o,l){let d,u,c,h,f,m,p=n,g=n;const v=e.pid>-1,b=t.pid>-1,E=t.samples.length,T=e.samples.length>0,A=o&&E>0||E>1;if((!v||T)&&(!b||A)||this.ISGenerated||o){if(this.ISGenerated){var S,L,R,I;const z=this.videoTrackConfig;(z&&(t.width!==z.width||t.height!==z.height||((S=t.pixelRatio)==null?void 0:S[0])!==((L=z.pixelRatio)==null?void 0:L[0])||((R=t.pixelRatio)==null?void 0:R[1])!==((I=z.pixelRatio)==null?void 0:I[1]))||!z&&A||this.nextAudioTs===null&&T)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,n,a));const M=this.isVideoContiguous;let B=-1,q;if(A&&(B=bD(t.samples),!M&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,B>0){this.warn(`Dropped ${B} out of ${E} video samples due to a missing keyframe`);const z=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(B),t.dropped+=B,g+=(t.samples[0].pts-z)/t.inputTimeScale,q=g}else B===-1&&(this.warn(`No keyframe found out of ${E} video samples`),m=!1);if(this.ISGenerated){if(T&&A){const z=this.getVideoStartPts(t.samples),H=(jt(e.samples[0].pts,z)-z)/t.inputTimeScale;p+=Math.max(0,H),g+=Math.max(0,-H)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,n,a)),u=this.remuxAudio(e,p,this.isAudioContiguous,a,b||A||l===J.AUDIO?g:void 0),A){const z=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,n,a)),d=this.remuxVideo(t,g,M,z)}}else A&&(d=this.remuxVideo(t,g,M,0));d&&(d.firstKeyFrame=B,d.independent=B!==-1,d.firstKeyFramePTS=q)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=Sb(s,n,this._initPTS,this._initDTS)),r.samples.length&&(h=Ib(r,n,this._initPTS))),{audio:u,video:d,initSegment:c,independent:m,text:h,id3:f}}computeInitPts(e,t,s,r){const n=Math.round(s*t);let a=jt(e,n);if(a<n+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${r}`);a<n+t;)a+=8589934592;return a-n}generateIS(e,t,s,r){const n=e.samples,a=t.samples,o=this.typeSupported,l={},d=this._initPTS;let u=!d||r,c="audio/mp4",h,f,m,p=-1;if(u&&(h=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(c="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:c,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):D.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(p=e.id,m=e.inputTimeScale,!d||m!==d.timescale?h=f=this.computeInitPts(n[0].pts,m,s,"audio"):u=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:D.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(p=t.id,m=t.inputTimeScale,!d||m!==d.timescale){const g=this.getVideoStartPts(a),v=jt(a[0].dts,g),b=this.computeInitPts(v,m,s,"video"),E=this.computeInitPts(g,m,s,"video");f=Math.min(f,b),h=Math.min(h,E)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u?(d&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${s} ${h/m} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${h/m} (${h}/${m}) trackId: ${p}`),this._initPTS={baseTime:h,timescale:m,trackId:p},this._initDTS={baseTime:f,timescale:m,trackId:p}):h=m=void 0,{tracks:l,initPTS:h,timescale:m,trackId:p}}remuxVideo(e,t,s,r){const n=e.inputTimeScale,a=e.samples,o=[],l=a.length,d=this._initPTS,u=d.baseTime*n/d.timescale;let c=this.nextVideoTs,h=8,f=this.videoSampleDuration,m,p,g=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,b=!1;if(!s||c===null){const U=u+t*n,$=a[0].pts-jt(a[0].dts,a[0].pts);Qr&&c!==null&&Math.abs(U-$-(c+u))<15e3?s=!0:c=U-$-u}const E=c+u;for(let U=0;U<l;U++){const $=a[U];$.pts=jt($.pts,E),$.dts=jt($.dts,E),$.dts<a[U>0?U-1:U].dts&&(b=!0)}b&&a.sort(function(U,$){const re=U.dts-$.dts,he=U.pts-$.pts;return re||he}),m=a[0].dts,p=a[a.length-1].dts;const T=p-m,A=T?Math.round(T/(l-1)):f||e.inputTimeScale/30;if(s){const U=m-E,$=U>A,re=U<-1;if(($||re)&&($?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ca(U,!0)} ms (${U}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ca(-U,!0)} ms (${U}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!re||E>=a[0].pts||Qr)){m=E;const he=a[0].pts-U;if($)a[0].dts=m,a[0].pts=he;else{let ce=!0;for(let pe=0;pe<a.length&&!(a[pe].dts>he&&ce);pe++){const ut=a[pe].pts;if(a[pe].dts-=U,a[pe].pts-=U,pe<a.length-1){const tt=a[pe+1].pts,Dt=a[pe].pts,Ft=tt<=Dt,ci=tt<=ut;ce=Ft==ci}}}this.log(`Video: Initial PTS/DTS adjusted: ${ca(he,!0)}/${ca(m,!0)}, delta: ${ca(U,!0)} ms`)}}m=Math.max(0,m);let x=0,S=0,L=m;for(let U=0;U<l;U++){const $=a[U],re=$.units,he=re.length;let ce=0;for(let pe=0;pe<he;pe++)ce+=re[pe].data.length;S+=ce,x+=he,$.length=ce,$.dts<L?($.dts=L,L+=A/4|0||1):L=$.dts,g=Math.min($.pts,g),v=Math.max($.pts,v)}p=a[l-1].dts;const R=S+4*x+8;let I;try{I=new Uint8Array(R)}catch(U){this.observer.emit(y.ERROR,y.ERROR,{type:ie.MUX_ERROR,details:w.REMUX_ALLOC_ERROR,fatal:!1,error:U,bytes:R,reason:`fail allocating video mdat ${R}`});return}const M=new DataView(I.buffer);M.setUint32(0,R),I.set(D.types.mdat,4);let B=!1,q=Number.POSITIVE_INFINITY,z=Number.POSITIVE_INFINITY,K=Number.NEGATIVE_INFINITY,H=Number.NEGATIVE_INFINITY;for(let U=0;U<l;U++){const $=a[U],re=$.units;let he=0;for(let ut=0,tt=re.length;ut<tt;ut++){const Dt=re[ut],Ft=Dt.data,ci=Dt.data.byteLength;M.setUint32(h,ci),h+=4,I.set(Ft,h),h+=ci,he+=4+ci}let ce;if(U<l-1)f=a[U+1].dts-$.dts,ce=a[U+1].pts-$.pts;else{const ut=this.config,tt=U>0?$.dts-a[U-1].dts:A;if(ce=U>0?$.pts-a[U-1].pts:A,ut.stretchShortVideoTrack&&this.nextAudioTs!==null){const Dt=Math.floor(ut.maxBufferHole*n),Ft=(r?g+r*n:this.nextAudioTs+u)-$.pts;Ft>Dt?(f=Ft-tt,f<0?f=tt:B=!0,this.log(`It is approximately ${Ft/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=tt}else f=tt}const pe=Math.round($.pts-$.dts);q=Math.min(q,f),K=Math.max(K,f),z=Math.min(z,ce),H=Math.max(H,ce),o.push(p0($.key,f,he,pe))}if(o.length){if(Qr){if(Qr<70){const U=o[0].flags;U.dependsOn=2,U.isNonSync=0}}else if(Rc&&H-z<K-q&&A/K<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let U=m;for(let $=0,re=o.length;$<re;$++){const he=U+o[$].duration,ce=U+o[$].cts;if($<re-1){const pe=he+o[$+1].cts;o[$].duration=pe-ce}else o[$].duration=$?o[$-1].duration:A;o[$].cts=0,U=he}}}f=B||!f?A:f;const j=p+f;this.nextVideoTs=c=j-u,this.videoSampleDuration=f,this.isVideoContiguous=!0;const W={data1:D.moof(e.sequenceNumber++,m,Oe(e,{samples:o})),data2:I,startPTS:(g-u)/n,endPTS:(v+f-u)/n,startDTS:(m-u)/n,endDTS:c/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,W}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return ED;case"ac3":return yD;default:return vD}}remuxAudio(e,t,s,r,n){const a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,l=a/o,d=this.getSamplesPerFrame(e),u=d*l,c=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],m=n!==void 0;let p=e.samples,g=h?0:8,v=this.nextAudioTs||-1;const b=c.baseTime*a/c.timescale,E=b+t*a;if(this.isAudioContiguous=s=s||p.length&&v>0&&(r&&Math.abs(E-(v+b))<9e3||Math.abs(jt(p[0].pts,E)-(v+b))<20*u),p.forEach(function(H){H.pts=jt(H.pts,E)}),!s||v<0){const H=p.length;if(p=p.filter(j=>j.pts>=0),H!==p.length&&this.warn(`Removed ${p.length-H} of ${H} samples (initPTS ${b} / ${a})`),!p.length)return;n===0?v=0:r&&!m?v=Math.max(0,E-b):v=p[0].pts-b}if(e.segmentCodec==="aac"){const H=this.config.maxAudioFramesDrift;for(let j=0,G=v+b;j<p.length;j++){const N=p[j],W=N.pts,U=W-G,$=Math.abs(1e3*U/a);if(U<=-H*u&&m)j===0&&(this.warn(`Audio frame @ ${(W/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*U/a)} ms.`),this.nextAudioTs=v=W-b,G=W);else if(U>=H*u&&$<gD&&m){let re=Math.round(U/u);for(G=W-re*u;G<0&&re&&u;)re--,G+=u;j===0&&(this.nextAudioTs=v=G-b),this.warn(`Injecting ${re} audio frames @ ${((G-b)/a).toFixed(3)}s due to ${Math.round(1e3*U/a)} ms gap.`);for(let he=0;he<re;he++){let ce=fD.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);ce||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),ce=N.unit.subarray()),p.splice(j,0,{unit:ce,pts:G}),G+=u,j++}}N.pts=G,G+=u}}let T=null,A=null,x,S=0,L=p.length;for(;L--;)S+=p[L].unit.byteLength;for(let H=0,j=p.length;H<j;H++){const G=p[H],N=G.unit;let W=G.pts;if(A!==null){const $=f[H-1];$.duration=Math.round((W-A)/l)}else if(s&&e.segmentCodec==="aac"&&(W=v+b),T=W,S>0){S+=g;try{x=new Uint8Array(S)}catch($){this.observer.emit(y.ERROR,y.ERROR,{type:ie.MUX_ERROR,details:w.REMUX_ALLOC_ERROR,fatal:!1,error:$,bytes:S,reason:`fail allocating audio mdat ${S}`});return}h||(new DataView(x.buffer).setUint32(0,S),x.set(D.types.mdat,4))}else return;x.set(N,g);const U=N.byteLength;g+=U,f.push(p0(!0,d,U,0)),A=W}const R=f.length;if(!R)return;const I=f[f.length-1];v=A-b,this.nextAudioTs=v+l*I.duration;const M=h?new Uint8Array(0):D.moof(e.sequenceNumber++,T/l,Oe({},e,{samples:f}));e.samples=[];const B=(T-b)/a,q=this.nextAudioTs/a,K={data1:M,data2:x,startPTS:B,endPTS:q,startDTS:B,endDTS:q,type:"audio",hasAudio:!0,hasVideo:!1,nb:R};return this.isAudioContiguous=!0,K}}function jt(i,e){let t;if(e===null)return i;for(e<i?t=-8589934592:t=8589934592;Math.abs(i-e)>4294967296;)i+=t;return i}function bD(i){for(let e=0;e<i.length;e++)if(i[e].key)return e;return-1}function Sb(i,e,t,s){const r=i.samples.length;if(!r)return;const n=i.inputTimeScale;for(let o=0;o<r;o++){const l=i.samples[o];l.pts=jt(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=jt(l.dts-s.baseTime*n/s.timescale,e*n)/n}const a=i.samples;return i.samples=[],{samples:a}}function Ib(i,e,t){const s=i.samples.length;if(!s)return;const r=i.inputTimeScale;for(let a=0;a<s;a++){const o=i.samples[a];o.pts=jt(o.pts-t.baseTime*r/t.timescale,e*r)/r}i.samples.sort((a,o)=>a.pts-o.pts);const n=i.samples;return i.samples=[],{samples:n}}class TD extends di{constructor(e,t,s,r){super("passthrough-remuxer",r),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,r){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,r),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:n,video:a}=this.initData=Cy(e);if(t)lR(e,t);else{const l=n||a;l!=null&&l.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${l.codec}")!`)}n&&(s=g0(n,Ue.AUDIO,this)),a&&(r=g0(a,Ue.VIDEO,this));const o={};n&&a?o.audiovideo={container:"video/mp4",codec:s+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:n?o.audio={container:"audio/mp4",codec:s,encrypted:n.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,r,n,a){var o,l;let{initPTS:d,lastEndTime:u}=this;const c={audio:void 0,video:void 0,text:r,id3:s,initSegment:void 0};X(u)||(u=this.lastEndTime=n||0);const h=t.samples;if(!h.length)return c;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let m=this.initData;if((o=m)!=null&&o.length||(this.generateInitSegment(h),m=this.initData),!((l=m)!=null&&l.length))return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const p=uR(h,m,this),g=m.audio?p[m.audio.id]:null,v=m.video?p[m.video.id]:null,b=Zo(v,1/0),E=Zo(g,1/0),T=Zo(v,0,!0),A=Zo(g,0,!0);let x=n,S=0;const L=g&&(!v||!d&&E<b||d&&d.trackId===m.audio.id),R=L?g:v;if(R){const G=R.timescale,N=R.start-n*G,W=L?m.audio.id:m.video.id;x=R.start/G,S=L?A-E:T-b,(a||!d)&&(_D(d,x,n,S)||G!==d.timescale)&&(d&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${N/G} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${x-n} (${N}/${G}) trackId: ${W}`),d=null,f.initPTS=N,f.timescale=G,f.trackId=W)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);d?(f.initPTS=d.baseTime,f.timescale=d.timescale,f.trackId=d.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=x,f.timescale=1,f.trackId=-1),this.initPTS=d={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const I=x-d.baseTime/d.timescale,M=I+S;S>0?this.lastEndTime=M:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const B=!!m.audio,q=!!m.video;let z="";B&&(z+="audio"),q&&(z+="video");const K=(m.audio?m.audio.encrypted:!1)||(m.video?m.video.encrypted:!1),H={data1:h,startPTS:I,startDTS:I,endPTS:M,endDTS:M,type:z,hasAudio:B,hasVideo:q,nb:1,dropped:0,encrypted:K};c.audio=B&&!q?H:void 0,c.video=q?H:void 0;const j=v?.sampleCount;if(j){const G=v.keyFrameIndex,N=G!==-1;H.nb=j,H.dropped=G===0||this.isVideoContiguous?0:N?G:j,H.independent=N,H.firstKeyFrame=G,N&&v.keyFrameStart&&(H.firstKeyFramePTS=(v.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(c.independent=N),this.isVideoContiguous||(this.isVideoContiguous=N),H.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${G}/${j} dropped: ${H.dropped} start: ${H.firstKeyFramePTS||"NA"}`)}return c.initSegment=f,c.id3=Sb(s,n,d,d),r.samples.length&&(c.text=Ib(r,n,d)),c}}function Zo(i,e,t=!1){return i?.start!==void 0?(i.start+(t?i.duration:0))/i.timescale:e}function _D(i,e,t,s){if(i===null)return!0;const r=Math.max(s,1),n=e-i.baseTime/i.timescale;return Math.abs(n-t)>r}function g0(i,e,t){const s=i.codec;return s&&s.length>4?s:e===Ue.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?zd(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let ms;try{ms=self.performance.now.bind(self.performance)}catch{ms=Date.now}const Wl=[{demux:oD,remux:TD},{demux:Bs,remux:Vl},{demux:sD,remux:Vl},{demux:nD,remux:Vl}];Wl.splice(2,0,{demux:rD,remux:Vl});class v0{constructor(e,t,s,r,n,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,r){const n=s.transmuxing;n.executeStart=ms();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;r&&(this.currentTransmuxState=r);const{contiguous:d,discontinuity:u,trackSwitch:c,accurateTimeOffset:h,timeOffset:f,initSegmentChange:m}=r||o,{audioCodec:p,videoCodec:g,defaultInitPts:v,duration:b,initSegmentData:E}=l,T=AD(a,t);if(T&&Un(T.method)){const L=this.getDecrypter(),R=$m(T.method);if(L.isSync()){let I=L.softwareDecrypt(a,T.key.buffer,T.iv.buffer,R);if(s.part>-1){const B=L.flush();I=B&&B.buffer}if(!I)return n.executeEnd=ms(),kc(s);a=new Uint8Array(I)}else return this.asyncResult=!0,this.decryptionPromise=L.webCryptoDecrypt(a,T.key.buffer,T.iv.buffer,R).then(I=>{const M=this.push(I,null,s);return this.decryptionPromise=null,M}),this.decryptionPromise}const A=this.needsProbing(u,c);if(A){const L=this.configureTransmuxer(a);if(L)return this.logger.warn(`[transmuxer] ${L.message}`),this.observer.emit(y.ERROR,y.ERROR,{type:ie.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,error:L,reason:L.message}),n.executeEnd=ms(),kc(s)}(u||c||m||A)&&this.resetInitSegment(E,p,g,b,t),(u||m||A)&&this.resetInitialTimestamp(v),d||this.resetContiguity();const x=this.transmux(a,T,f,h,s);this.asyncResult=yo(x);const S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,n.executeEnd=ms(),x}flush(e){const t=e.transmuxing;t.executeStart=ms();const{decrypter:s,currentTransmuxState:r,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));const a=[],{timeOffset:o}=r;if(s){const c=s.flush();c&&a.push(this.push(c.buffer,null,e))}const{demuxer:l,remuxer:d}=this;if(!l||!d){t.executeEnd=ms();const c=[kc(e)];return this.asyncResult?Promise.resolve(c):c}const u=l.flush(o);return yo(u)?(this.asyncResult=!0,u.then(c=>(this.flushRemux(a,c,e),a))):(this.flushRemux(a,u,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,s){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===J.MAIN?"level":"track"} ${s.level}`);const u=this.remuxer.remux(r,n,a,o,d,l,!0,this.id);e.push({remuxResult:u,chunkMeta:s}),s.transmuxing.executeEnd=ms()}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,r,n){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,s,r),o.resetInitSegment(e,t,s,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,r,n){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,s,r,n):a=this.transmuxUnencrypted(e,s,r,n),a}transmuxUnencrypted(e,t,s,r){const{audioTrack:n,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,a,o,l,t,s,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,s,r,n){return this.demuxer.demuxSampleAes(e,t,s).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,r,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:r}=this;let n;for(let c=0,h=Wl.length;c<h;c++){var a;if((a=Wl[c].demux)!=null&&a.probe(e,this.logger)){n=Wl[c];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,d=n.remux,u=n.demux;(!l||!(l instanceof d))&&(this.remuxer=new d(s,t,r,this.logger)),(!o||!(o instanceof u))&&(this.demuxer=new u(s,t,r,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 Nm(this.config)),e}}function AD(i,e){let t=null;return i.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const kc=i=>({remuxResult:{},chunkMeta:i});function yo(i){return"then"in i&&i.then instanceof Function}class SD{constructor(e,t,s,r,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=r,this.defaultInitPts=n||null}}class ID{constructor(e,t,s,r,n,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=r,this.timeOffset=n,this.initSegmentChange=a}}let E0=0;class xb{constructor(e,t,s,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=E0++,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=l=>{const d=l.data,u=this.hls;if(!(!u||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var c;const h=(c=this.workerContext)==null?void 0:c.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{u.logger[d.data.logType]&&u.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,u.trigger(d.event,d.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const d=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};const n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=s,this.onFlush=r;const a=(l,d)=>{d=d||{},d.frag=this.frag||void 0,l===y.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(l,d)};this.observer=new Hm,this.observer.on(y.FRAG_DECRYPTED,a),this.observer.on(y.ERROR,a);const o=Mg(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(n.workerPath||kk()){try{n.workerPath?(l.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=Ck(n.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=Dk());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:$e(n)})}catch(u){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new v0(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new v0(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=E0++;const t=this.hls.config,s=Mg(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:$e(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),wk(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,r,n,a,o,l,d,u){var c,h;d.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:m}=this,p=a?a.start:n.start,g=n.decryptdata,v=this.frag,b=!(v&&n.cc===v.cc),E=!(v&&d.level===v.level),T=v?d.sn-v.sn:-1,A=this.part?d.part-this.part.index:-1,x=T===0&&d.id>1&&d.id===v?.stats.chunkCount,S=!E&&(T===1||T===0&&(A===1||x&&A<=0)),L=self.performance.now();(E||T||n.stats.parsing.start===0)&&(n.stats.parsing.start=L),a&&(A||!S)&&(a.stats.parsing.start=L);const R=!(v&&((c=n.initSegment)==null?void 0:c.url)===((h=v.initSegment)==null?void 0:h.url)),I=new ID(b,S,l,E,p,R);if(!S||b||R){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===J.MAIN?"level":"track"}: ${d.level} id: ${d.id}
|
|
1433
1433
|
discontinuity: ${b}
|
|
1434
1434
|
trackSwitch: ${E}
|
|
1435
1435
|
contiguous: ${S}
|
|
1436
1436
|
accurateTimeOffset: ${l}
|
|
1437
1437
|
timeOffset: ${p}
|
|
1438
|
-
initSegmentChange: ${R}`);const M=new SD(s,r,t,o,u);this.configureTransmuxer(M)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:g,chunkMeta:d,state:I},e instanceof ArrayBuffer?[e]:[]);else if(m){const M=m.push(e,g,d,I);yo(M)?M.then(B=>{this.handleTransmuxComplete(B)}).catch(B=>{this.transmuxerError(B,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(M)}}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 r=s.flush(e);yo(r)?r.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")}):this.handleFlushResult(r,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.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 y0=100;class xD extends Bm{constructor(e,t,s){super(e,t,s,"audio-stream-controller",J.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(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(y.BUFFER_RESET,this.onBufferReset,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(y.BUFFER_RESET,this.onBufferReset,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:r,timescale:n,trackId:a}){if(s===J.MAIN){const o=t.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:r,timescale:n,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${r/n} (${r}/${n}) trackId: ${a}`),this.mainAnchor=t,this.state===O.WAITING_INIT_PTS){const d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==o)&&this.syncWithAnchor(t,d?.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(t,l)):this.state===O.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const r=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&r?.cc===t.cc)return;const n=(r||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=Gy(a,n,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===O.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=O.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(y0),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=O.IDLE):this.state=O.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case O.IDLE:this.doTickIdle();break;case O.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=e?.[t],r=s?.details;if(r&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(r))break;this.state=O.WAITING_INIT_PTS}break}case O.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case O.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:r,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=O.FRAG_LOADING;const o=r.flush().buffer,l={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),n&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=O.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:s,media:r,trackId:n}=this,a=t.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(s!=null&&s[n]))return;const o=s[n],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=O.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,Ue.AUDIO,J.AUDIO));const u=this.getFwdBufferInfo(d,J.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,l)){t.trigger(y.BUFFER_EOS,{type:"audio"}),this.state=O.ENDED;return}const c=u.len,h=t.maxBufferLength,f=l.fragments,m=f[0].start,p=this.getLoadPosition(),g=this.flushing?p:u.end;if(this.switchingTrack&&r){const E=p;l.PTSKnown&&E<m&&(u.end>m||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=m+.05)}if(c>=h&&!this.switchingTrack&&g<f[f.length-1].start)return;let v=this.getNextFragment(g,l);if(v&&this.isLoopLoading(v,g)&&(v=this.getNextFragmentLoopLoading(v,l,u,J.MAIN,h)),!v){this.bufferFlushed=!0;return}let b=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&b&&et(v)&&!v.endList&&(!l.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(b)===gt.OK&&(this.mainFragLoading=b=null),b&&et(b))){if(v.start>b.end){const T=this.fragmentTracker.getFragAtPos(g,J.MAIN);T&&T.end>b.end&&(b=T,this.mainFragLoading={frag:T,targetBufferTime:null})}if(v.start>b.end)return}this.loadFragment(v,o,g)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new go(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==O.STOPPED&&(this.setInterval(y0),this.state=O.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(y.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:r}=this,{details:n,id:a,groupId:o,track:l}=t;if(!r){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}const d=this.mainDetails;if(!d||n.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==O.STOPPED&&(this.state=O.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const u=r[a];let c=0;if(n.live||(s=u.details)!=null&&s.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(u.details){var h;c=this.alignPlaylists(n,u.details,(h=this.levelLastLoaded)==null?void 0:h.details)}n.alignedSliding||(ab(n,d),n.alignedSliding||iu(n,d),c=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,c),this.hls.trigger(y.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===O.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=O.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:r,payload:n}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const d=l[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}const u=d.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const c=a.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new xb(this.hls,J.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[s.cc],m=(t=s.initSegment)==null?void 0:t.data;if(f!==void 0){const g=r?r.index:-1,v=g!==-1,b=new Um(s.level,s.sn,s.stats.chunkCount,n.byteLength,g,v);h.push(n,m,c,"",s,r,u.totalduration,!1,b,f)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:p}=this.waitingData=this.waitingData||{frag:s,part:r,cache:new ob,complete:!1};p.push(new Uint8Array(n)),this.state!==O.STOPPED&&(this.state=O.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===J.MAIN&&et(t.frag)&&(this.mainFragLoading=t,this.state===O.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:r}=t;if(s.type!==J.AUDIO){!this.audioOnly&&s.type===J.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(et(s)){this.fragPrevious=s;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(y.AUDIO_TRACK_SWITCHED,Ce({},n)))}this.fragBufferedComplete(s,r),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=O.ERROR;return}switch(t.details){case w.FRAG_GAP:case w.FRAG_PARSING_ERROR:case w.FRAG_DECRYPT_ERROR:case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(J.AUDIO,t);break;case w.AUDIO_TRACK_LOAD_ERROR:case w.AUDIO_TRACK_LOAD_TIMEOUT:case w.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===O.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===pe.AUDIO_TRACK&&(this.state=O.IDLE);break;case w.BUFFER_ADD_CODEC_ERROR:case w.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case w.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case w.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Ue.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Ue.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===O.ENDED&&(this.state=O.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,J.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:d,level:u}=o,{details:c}=u,{audio:h,text:f,id3:m,initSegment:p}=n;if(this.fragContextChanged(l)||!c){this.fragmentTracker.removeFragment(l);return}if(this.state=O.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const g=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(u,p.tracks,g,a),r.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:s,tracks:p.tracks})}if(h){const{startPTS:g,endPTS:v,startDTS:b,endDTS:E}=h;d&&(d.elementaryStreams[Ue.AUDIO]={startPTS:g,endPTS:v,startDTS:b,endDTS:E}),l.setElementaryStreamInfo(Ue.AUDIO,g,v,b,E),this.bufferFragmentData(h,l,d,a)}if(m!=null&&(t=m.samples)!=null&&t.length){const g=Oe({id:s,frag:l,details:c},m);r.trigger(y.FRAG_PARSING_METADATA,g)}if(f){const g=Oe({id:s,frag:l,details:c},f);r.trigger(y.FRAG_PARSING_USERDATA,g)}}_bufferInitSegment(e,t,s,r){if(this.state!==O.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const n=t.audio;n.id=J.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),a&&a.split(",").length===1&&(n.levelCodec=a),this.hls.trigger(y.BUFFER_CODECS,t);const o=n.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:s,part:null,chunkMeta:r,parent:s.type,data:o};this.hls.trigger(y.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,s){const r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===gt.NOT_LOADED||r===gt.PARTIAL){var n;if(!et(e))this._loadInitSegment(e,t);else if((n=t.details)!=null&&n.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=O.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&iu(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:r,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;Lr({name:t,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},e,ur)||(Xd(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(y.AUDIO_TRACK_SWITCHED,Ce({},e))}}class jm extends di{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 r=t?.renditionReports;if(r){let n=-1;for(let a=0;a<r.length;a++){const o=r[a];let l;try{l=new self.URL(o.URI,t.url).href}catch(d){this.warn(`Could not construct new URL for Rendition Report: ${d}`),l=o.URI||""}if(l===e){n=a;break}else l===e.substring(0,l.length)&&(n=a)}if(n!==-1){const a=r[n],o=parseInt(a["LAST-MSN"])||t.lastPartSn;let l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const u=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&u>t.partTarget&&(l+=1)}const d=s&&Pg(s);return new Og(o,l>=0?l:void 0,d)}}}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:r,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;r.advancedDateTime=Date.now()-o;const l=this.hls.config.timelineOffset;if(l!==r.appliedTimelineOffset){const u=Math.max(l||0,0);r.appliedTimelineOffset=u,r.fragments.forEach(c=>{c.setStart(c.playlistOffset+u)})}if(r.live||s!=null&&s.live){const u="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(s),s&&r.fragments.length>0){Ek(s,r,this);const b=r.playlistParsingError;if(b){this.warn(b);const E=this.hls;if(!E.config.ignorePlaylistParsingErrors){var d;const{networkDetails:T}=t;E.trigger(y.ERROR,{type:ie.NETWORK_ERROR,details:w.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:b,reason:b.message,level:t.level||void 0,parent:(d=r.fragments[0])==null?void 0:d.type,networkDetails:T,stats:n});return}r.playlistParsingError=null}}r.requestScheduled===-1&&(r.requestScheduled=n.loading.start);const c=this.hls.mainForwardBufferInfo,h=c?c.end-c.len:0,f=(r.edge-h)*1e3,m=tb(r,f);if(r.requestScheduled+m<a?r.requestScheduled=a:r.requestScheduled+=m,this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),!this.canLoad||!r.live)return;let p,g,v;if(r.canBlockReload&&r.endSN&&r.advanced){const b=this.hls.config.lowLatencyMode,E=r.lastPartSn,T=r.endSN,A=r.lastPartIndex,x=A!==-1,S=E===T;x?S?(g=T+1,v=b?0:A):(g=E,v=b?A+1:r.maxPartIndex):g=T+1;const L=r.age,R=L+r.ageHeader;let I=Math.min(R-r.partTarget,r.targetduration*1.5);if(I>0){if(R>r.targetduration*3)this.log(`Playlist last advanced ${L.toFixed(2)}s ago. Omitting segment and part directives.`),g=void 0,v=void 0;else if(s!=null&&s.tuneInGoal&&R-r.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${I} with playlist age: ${r.age}`),I=0;else{const M=Math.floor(I/r.targetduration);if(g+=M,v!==void 0){const B=Math.round(I%r.targetduration/r.partTarget);v+=B}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${L.toFixed(2)}s goal: ${I} skip sn ${M} to part ${v}`)}r.tuneInGoal=I}if(p=this.getDeliveryDirectives(r,t.deliveryDirectives,g,v),b||!S){r.requestScheduled=a,this.loadingPlaylist(u,p);return}}else(r.canBlockReload||r.canSkipUntil)&&(p=this.getDeliveryDirectives(r,t.deliveryDirectives,g,v));p&&g!==void 0&&r.canBlockReload&&(r.requestScheduled=n.loading.first+Math.max(m-o*2,m/2)),this.scheduleLoading(u,p,r)}else this.clearTimer()}scheduleLoading(e,t,s){const r=s||e.details;if(!r){this.loadingPlaylist(e,t);return}const n=self.performance.now(),a=r.requestScheduled;if(n>=a){this.loadingPlaylist(e,t);return}const o=a-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,r){let n=Pg(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,r=t.part,n=Gl.No),new Og(s,r,n)}checkRetry(e){const t=e.details,s=Zd(e),r=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=r||{},l=!!r&&!!o&&(n===St.RetryRequest||!r.resolved&&n===St.SendAlternateToPenaltyBox);if(l){var d;if(a>=o.maxNumRetry)return!1;if(s&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const u=Om(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,r.resolved=!0}return l}}function Lb(i,e){if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++)if(!bo(i[t].attrs,e[t].attrs))return!1;return!0}function bo(i,e,t){const s=i["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>i[r]!==e[r])}function Yh(i,e){return e.label.toLowerCase()===i.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(i.lang||"").toLowerCase())}class LD extends jm{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(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(y.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:r,details:n}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==r){this.warn(`Audio track with id:${s} and group:${r} not found in active group ${a?.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${s} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,r=this.groupIds;let n=this.currentTrack;if(!s||r?.length!==s?.length||s!=null&&s.some(o=>r?.indexOf(o)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(h=>h.default)&&(this.selectDefaultTrack=!1),o.forEach((h,f)=>{h.id=f});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!n&&l){const h=Qi(l,o,ur);if(h>-1)n=o[h];else{const f=Qi(l,this.tracks);n=this.tracks[f]}}let d=this.findTrackId(n);d===-1&&n&&(d=this.findTrackId(null));const u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(y.AUDIO_TRACKS_UPDATED,u);const c=this.trackId;if(d!==-1&&c===-1)this.setAudioTrack(d);else if(o.length&&c===-1){var a;const h=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(h.message),this.hls.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===pe.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 r=this.currentTrack;if(r&&Lr(e,r,ur))return r;const n=Qi(e,this.tracksInGroup,ur);if(n>-1){const a=this.tracksInGroup[n];return this.setAudioTrack(n),a}else if(r){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=FR(e,t.levels,s,a,ur);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=Qi(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,r=t[e],n=r.details&&!r.details.live;if(e===this.trackId&&r===s&&n||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(y.AUDIO_TRACK_SWITCHING,Ce({},r)),n))return;const a=this.switchParams(r.url,s?.details,r.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const r=t[s];if(!(this.selectDefaultTrack&&!r.default)&&(!e||Lr(e,r,ur)))return s}if(e){const{name:s,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l}=e;for(let d=0;d<t.length;d++){const u=t[d];if(Lr({name:s,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l},u,ur))return d}for(let d=0;d<t.length;d++){const u=t[d];if(bo(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(let d=0;d<t.length;d++){const u=t[d];if(bo(e.attrs,u.attrs,["LANGUAGE"]))return d}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Xd(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(y.AUDIO_TRACK_LOADING,{url:n,id:s,groupId:r,deliveryDirectives:t||null,track:e})}}class RD{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 r=this.queues[t];r.push(e),r.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 r=t[0];try{r.execute()}catch(n){var s;if(r.onError(n),this.queues===null||this.tracks===null)return;const a=(s=this.tracks[e])==null?void 0:s.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
|
|
1438
|
+
initSegmentChange: ${R}`);const M=new SD(s,r,t,o,u);this.configureTransmuxer(M)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:g,chunkMeta:d,state:I},e instanceof ArrayBuffer?[e]:[]);else if(m){const M=m.push(e,g,d,I);yo(M)?M.then(B=>{this.handleTransmuxComplete(B)}).catch(B=>{this.transmuxerError(B,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(M)}}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 r=s.flush(e);yo(r)?r.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")}):this.handleFlushResult(r,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.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 y0=100;class xD extends Bm{constructor(e,t,s){super(e,t,s,"audio-stream-controller",J.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(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(y.BUFFER_RESET,this.onBufferReset,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(y.BUFFER_RESET,this.onBufferReset,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:r,timescale:n,trackId:a}){if(s===J.MAIN){const o=t.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:r,timescale:n,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${r/n} (${r}/${n}) trackId: ${a}`),this.mainAnchor=t,this.state===P.WAITING_INIT_PTS){const d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==o)&&this.syncWithAnchor(t,d?.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(t,l)):this.state===P.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const r=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&r?.cc===t.cc)return;const n=(r||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=Gy(a,n,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===P.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=P.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(y0),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=P.IDLE):this.state=P.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case P.IDLE:this.doTickIdle();break;case P.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=e?.[t],r=s?.details;if(r&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(r))break;this.state=P.WAITING_INIT_PTS}break}case P.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case P.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:r,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=P.FRAG_LOADING;const o=r.flush().buffer,l={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),n&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=P.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:s,media:r,trackId:n}=this,a=t.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(s!=null&&s[n]))return;const o=s[n],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=P.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,Ue.AUDIO,J.AUDIO));const u=this.getFwdBufferInfo(d,J.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,l)){t.trigger(y.BUFFER_EOS,{type:"audio"}),this.state=P.ENDED;return}const c=u.len,h=t.maxBufferLength,f=l.fragments,m=f[0].start,p=this.getLoadPosition(),g=this.flushing?p:u.end;if(this.switchingTrack&&r){const E=p;l.PTSKnown&&E<m&&(u.end>m||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=m+.05)}if(c>=h&&!this.switchingTrack&&g<f[f.length-1].start)return;let v=this.getNextFragment(g,l);if(v&&this.isLoopLoading(v,g)&&(v=this.getNextFragmentLoopLoading(v,l,u,J.MAIN,h)),!v){this.bufferFlushed=!0;return}let b=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&b&&et(v)&&!v.endList&&(!l.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(b)===gt.OK&&(this.mainFragLoading=b=null),b&&et(b))){if(v.start>b.end){const T=this.fragmentTracker.getFragAtPos(g,J.MAIN);T&&T.end>b.end&&(b=T,this.mainFragLoading={frag:T,targetBufferTime:null})}if(v.start>b.end)return}this.loadFragment(v,o,g)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new go(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==P.STOPPED&&(this.setInterval(y0),this.state=P.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(y.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:r}=this,{details:n,id:a,groupId:o,track:l}=t;if(!r){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}const d=this.mainDetails;if(!d||n.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==P.STOPPED&&(this.state=P.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const u=r[a];let c=0;if(n.live||(s=u.details)!=null&&s.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(u.details){var h;c=this.alignPlaylists(n,u.details,(h=this.levelLastLoaded)==null?void 0:h.details)}n.alignedSliding||(ab(n,d),n.alignedSliding||iu(n,d),c=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,c),this.hls.trigger(y.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===P.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=P.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:r,payload:n}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const d=l[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}const u=d.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const c=a.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new xb(this.hls,J.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[s.cc],m=(t=s.initSegment)==null?void 0:t.data;if(f!==void 0){const g=r?r.index:-1,v=g!==-1,b=new Um(s.level,s.sn,s.stats.chunkCount,n.byteLength,g,v);h.push(n,m,c,"",s,r,u.totalduration,!1,b,f)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:p}=this.waitingData=this.waitingData||{frag:s,part:r,cache:new ob,complete:!1};p.push(new Uint8Array(n)),this.state!==P.STOPPED&&(this.state=P.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===J.MAIN&&et(t.frag)&&(this.mainFragLoading=t,this.state===P.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:r}=t;if(s.type!==J.AUDIO){!this.audioOnly&&s.type===J.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(et(s)){this.fragPrevious=s;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(y.AUDIO_TRACK_SWITCHED,Ce({},n)))}this.fragBufferedComplete(s,r),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case w.FRAG_GAP:case w.FRAG_PARSING_ERROR:case w.FRAG_DECRYPT_ERROR:case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(J.AUDIO,t);break;case w.AUDIO_TRACK_LOAD_ERROR:case w.AUDIO_TRACK_LOAD_TIMEOUT:case w.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===ge.AUDIO_TRACK&&(this.state=P.IDLE);break;case w.BUFFER_ADD_CODEC_ERROR:case w.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case w.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case w.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Ue.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Ue.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===P.ENDED&&(this.state=P.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,J.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:d,level:u}=o,{details:c}=u,{audio:h,text:f,id3:m,initSegment:p}=n;if(this.fragContextChanged(l)||!c){this.fragmentTracker.removeFragment(l);return}if(this.state=P.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const g=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(u,p.tracks,g,a),r.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:s,tracks:p.tracks})}if(h){const{startPTS:g,endPTS:v,startDTS:b,endDTS:E}=h;d&&(d.elementaryStreams[Ue.AUDIO]={startPTS:g,endPTS:v,startDTS:b,endDTS:E}),l.setElementaryStreamInfo(Ue.AUDIO,g,v,b,E),this.bufferFragmentData(h,l,d,a)}if(m!=null&&(t=m.samples)!=null&&t.length){const g=Oe({id:s,frag:l,details:c},m);r.trigger(y.FRAG_PARSING_METADATA,g)}if(f){const g=Oe({id:s,frag:l,details:c},f);r.trigger(y.FRAG_PARSING_USERDATA,g)}}_bufferInitSegment(e,t,s,r){if(this.state!==P.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const n=t.audio;n.id=J.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),a&&a.split(",").length===1&&(n.levelCodec=a),this.hls.trigger(y.BUFFER_CODECS,t);const o=n.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:s,part:null,chunkMeta:r,parent:s.type,data:o};this.hls.trigger(y.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,s){const r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===gt.NOT_LOADED||r===gt.PARTIAL){var n;if(!et(e))this._loadInitSegment(e,t);else if((n=t.details)!=null&&n.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=P.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&iu(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:r,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;Lr({name:t,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},e,ur)||(Xd(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(y.AUDIO_TRACK_SWITCHED,Ce({},e))}}class jm extends di{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 r=t?.renditionReports;if(r){let n=-1;for(let a=0;a<r.length;a++){const o=r[a];let l;try{l=new self.URL(o.URI,t.url).href}catch(d){this.warn(`Could not construct new URL for Rendition Report: ${d}`),l=o.URI||""}if(l===e){n=a;break}else l===e.substring(0,l.length)&&(n=a)}if(n!==-1){const a=r[n],o=parseInt(a["LAST-MSN"])||t.lastPartSn;let l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const u=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&u>t.partTarget&&(l+=1)}const d=s&&Pg(s);return new Og(o,l>=0?l:void 0,d)}}}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:r,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;r.advancedDateTime=Date.now()-o;const l=this.hls.config.timelineOffset;if(l!==r.appliedTimelineOffset){const u=Math.max(l||0,0);r.appliedTimelineOffset=u,r.fragments.forEach(c=>{c.setStart(c.playlistOffset+u)})}if(r.live||s!=null&&s.live){const u="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(s),s&&r.fragments.length>0){Ek(s,r,this);const b=r.playlistParsingError;if(b){this.warn(b);const E=this.hls;if(!E.config.ignorePlaylistParsingErrors){var d;const{networkDetails:T}=t;E.trigger(y.ERROR,{type:ie.NETWORK_ERROR,details:w.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:b,reason:b.message,level:t.level||void 0,parent:(d=r.fragments[0])==null?void 0:d.type,networkDetails:T,stats:n});return}r.playlistParsingError=null}}r.requestScheduled===-1&&(r.requestScheduled=n.loading.start);const c=this.hls.mainForwardBufferInfo,h=c?c.end-c.len:0,f=(r.edge-h)*1e3,m=tb(r,f);if(r.requestScheduled+m<a?r.requestScheduled=a:r.requestScheduled+=m,this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),!this.canLoad||!r.live)return;let p,g,v;if(r.canBlockReload&&r.endSN&&r.advanced){const b=this.hls.config.lowLatencyMode,E=r.lastPartSn,T=r.endSN,A=r.lastPartIndex,x=A!==-1,S=E===T;x?S?(g=T+1,v=b?0:A):(g=E,v=b?A+1:r.maxPartIndex):g=T+1;const L=r.age,R=L+r.ageHeader;let I=Math.min(R-r.partTarget,r.targetduration*1.5);if(I>0){if(R>r.targetduration*3)this.log(`Playlist last advanced ${L.toFixed(2)}s ago. Omitting segment and part directives.`),g=void 0,v=void 0;else if(s!=null&&s.tuneInGoal&&R-r.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${I} with playlist age: ${r.age}`),I=0;else{const M=Math.floor(I/r.targetduration);if(g+=M,v!==void 0){const B=Math.round(I%r.targetduration/r.partTarget);v+=B}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${L.toFixed(2)}s goal: ${I} skip sn ${M} to part ${v}`)}r.tuneInGoal=I}if(p=this.getDeliveryDirectives(r,t.deliveryDirectives,g,v),b||!S){r.requestScheduled=a,this.loadingPlaylist(u,p);return}}else(r.canBlockReload||r.canSkipUntil)&&(p=this.getDeliveryDirectives(r,t.deliveryDirectives,g,v));p&&g!==void 0&&r.canBlockReload&&(r.requestScheduled=n.loading.first+Math.max(m-o*2,m/2)),this.scheduleLoading(u,p,r)}else this.clearTimer()}scheduleLoading(e,t,s){const r=s||e.details;if(!r){this.loadingPlaylist(e,t);return}const n=self.performance.now(),a=r.requestScheduled;if(n>=a){this.loadingPlaylist(e,t);return}const o=a-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,r){let n=Pg(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,r=t.part,n=Gl.No),new Og(s,r,n)}checkRetry(e){const t=e.details,s=Zd(e),r=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=r||{},l=!!r&&!!o&&(n===St.RetryRequest||!r.resolved&&n===St.SendAlternateToPenaltyBox);if(l){var d;if(a>=o.maxNumRetry)return!1;if(s&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const u=Om(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,r.resolved=!0}return l}}function Lb(i,e){if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++)if(!bo(i[t].attrs,e[t].attrs))return!1;return!0}function bo(i,e,t){const s=i["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>i[r]!==e[r])}function Yh(i,e){return e.label.toLowerCase()===i.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(i.lang||"").toLowerCase())}class LD extends jm{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(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(y.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:r,details:n}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==r){this.warn(`Audio track with id:${s} and group:${r} not found in active group ${a?.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${s} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,r=this.groupIds;let n=this.currentTrack;if(!s||r?.length!==s?.length||s!=null&&s.some(o=>r?.indexOf(o)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(h=>h.default)&&(this.selectDefaultTrack=!1),o.forEach((h,f)=>{h.id=f});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!n&&l){const h=Qi(l,o,ur);if(h>-1)n=o[h];else{const f=Qi(l,this.tracks);n=this.tracks[f]}}let d=this.findTrackId(n);d===-1&&n&&(d=this.findTrackId(null));const u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(y.AUDIO_TRACKS_UPDATED,u);const c=this.trackId;if(d!==-1&&c===-1)this.setAudioTrack(d);else if(o.length&&c===-1){var a;const h=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(h.message),this.hls.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===ge.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 r=this.currentTrack;if(r&&Lr(e,r,ur))return r;const n=Qi(e,this.tracksInGroup,ur);if(n>-1){const a=this.tracksInGroup[n];return this.setAudioTrack(n),a}else if(r){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=FR(e,t.levels,s,a,ur);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=Qi(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,r=t[e],n=r.details&&!r.details.live;if(e===this.trackId&&r===s&&n||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(y.AUDIO_TRACK_SWITCHING,Ce({},r)),n))return;const a=this.switchParams(r.url,s?.details,r.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const r=t[s];if(!(this.selectDefaultTrack&&!r.default)&&(!e||Lr(e,r,ur)))return s}if(e){const{name:s,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l}=e;for(let d=0;d<t.length;d++){const u=t[d];if(Lr({name:s,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l},u,ur))return d}for(let d=0;d<t.length;d++){const u=t[d];if(bo(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(let d=0;d<t.length;d++){const u=t[d];if(bo(e.attrs,u.attrs,["LANGUAGE"]))return d}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Xd(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(y.AUDIO_TRACK_LOADING,{url:n,id:s,groupId:r,deliveryDirectives:t||null,track:e})}}class RD{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 r=this.queues[t];r.push(e),r.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 r=t[0];try{r.execute()}catch(n){var s;if(r.onError(n),this.queues===null||this.tracks===null)return;const a=(s=this.tracks[e])==null?void 0:s.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
|
|
1439
1439
|
${this.list("video")}
|
|
1440
1440
|
${this.list("audio")}
|
|
1441
1441
|
${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],r=s?.buffer;return r?`SourceBuffer${r.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 b0=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Rb="HlsJsTrackRemovedError";class kD extends Error{constructor(e){super(e),this.name=Rb}}class DD extends di{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 r;this.hls&&((r=this.mediaSource)==null?void 0:r.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:r,mediaSource:n}=this;s&&this.log("Media source opened"),!(!r||!n)&&(n.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(y.MEDIA_ATTACHED,{media:r,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:r}=this;s!==r&&this.error(`Media element src was set while attaching MediaSource (${r} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=ZL(zs(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(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.BUFFER_RESET,this.onBufferReset,this),e.on(y.BUFFER_APPENDING,this.onBufferAppending,this),e.on(y.BUFFER_CODECS,this.onBufferCodecs,this),e.on(y.BUFFER_EOS,this.onBufferEos,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.FRAG_PARSED,this.onFragParsed,this),e.on(y.FRAG_CHANGED,this.onFragChanged,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.BUFFER_RESET,this.onBufferReset,this),e.off(y.BUFFER_APPENDING,this.onBufferAppending,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.BUFFER_EOS,this.onBufferEos,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.FRAG_PARSED,this.onFragParsed,this),e.off(y.FRAG_CHANGED,this.onFragChanged,this),e.off(y.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const n=this.isUpdating();n||this.operationQueue.removeBlockers();const a=this.isQueued();(n||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${n?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const r=this.transferData;return!this.sourceBufferCount&&r&&r.mediaSource===t?Oe(s,r.tracks):this.sourceBuffers.forEach(n=>{const[a]=n;a&&(s[a]=Oe({},this.tracks[a]),this.removeBuffer(a)),n[0]=n[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var s;let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const r=zs(this.appendSource);if(r){const n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const a=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(a),n)this._objectUrl=s.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{s.removeAttribute("src");const l=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||l&&a instanceof l,T0(s),CD(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,r=t.tracks,n=r?Object.keys(r):null,a=n?n.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(r&&n&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
|
|
1442
1442
|
required tracks: ${$e(s,(l,d)=>l==="initSegment"?void 0:d)};
|
|
1443
|
-
transfer tracks: ${$e(r,(l,d)=>l==="initSegment"?void 0:d)}}`),!Sy(r,s)){t.mediaSource=null,t.tracks=void 0;const l=e.currentTime,d=this.details,u=Math.max(l,d?.fragments[0].start||0);if(u-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(s)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(y.MEDIA_DETACHING,{}),this.onMediaAttaching(y.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,n.forEach(l=>{const d=l,u=r[d];if(u){const c=u.buffer;if(c){const h=this.fragmentTracker,f=u.id;if(h.hasFragments(f)||h.hasParts(f)){const g=ue.getBuffered(c);h.detectEvictedFragments(d,g,f,null,!0)}const m=Dc(d),p=[d,c];this.sourceBuffers[m]=p,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,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:r,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=n.readyState==="open";try{const l=n.sourceBuffers;for(let d=l.length;d--;)o&&l[d].abort(),n.removeSourceBuffer(l[d]);o&&n.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(r.removeEventListener("emptied",this._onMediaEmptied),s||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(r.removeAttribute("src"),this.appendSource&&T0(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(y.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 r;(r=this.mediaSource)!=null&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Dc(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new RD(this.tracks)}onBufferCodecs(e,t){var s;const r=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some(l=>!r[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(r)}" and "${n}" SourceBuffers`);return}n.forEach(l=>{var d,u;const c=t[l],{id:h,codec:f,levelCodec:m,container:p,metadata:g,supplemental:v}=c;let b=r[l];const E=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[l],T=E!=null&&E.buffer?E:b,A=T?.pendingCodec||T?.codec,x=T?.levelCodec;b||(b=r[l]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:p,levelCodec:m,metadata:g,id:h});const S=Hl(A,x),L=S?.replace(b0,"$1");let R=Hl(f,m);const I=(u=R)==null?void 0:u.replace(b0,"$1");R&&S&&L!==I&&(l.slice(0,5)==="audio"&&(R=zd(R,this.appendSource)),this.log(`switching codec ${A} to ${R}`),R!==(b.pendingCodec||b.codec)&&(b.pendingCodec=R),b.container=p,this.appendChangeType(l,p,R))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const r=`${t};codecs=${s}`,n={label:`change-type=${r}`,execute:()=>{const a=this.tracks[e];if(a){const o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),o.changeType(r),a.codec=s,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(n,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,r=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,J.MAIN))==null?void 0:t.gap)===!0)return;const a={label:"block-audio",execute:()=>{var o;const l=this.tracks.video;(this.lastVideoAppendEnd>r||l!=null&&l.buffer&&ue.isBuffered(l.buffer,r)||((o=this.fragmentTracker.getAppendedFrag(r,J.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:r,type:n,parent:a,frag:o,part:l,chunkMeta:d,offset:u}=t,c=d.buffering[n],{sn:h,cc:f}=o,m=self.performance.now();c.start=m;const p=o.stats.buffering,g=l?l.stats.buffering:null;p.start===0&&(p.start=m),g&&g.start===0&&(g.start=m);const v=s.audio;let b=!1;n==="audio"&&v?.container==="audio/mpeg"&&(b=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const E=s.video,T=E?.buffer;if(T&&h!=="initSegment"){const S=l||o,L=this.blockedAudioAppend;if(n==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(E.ending||E.ended)){const I=S.start+S.duration*.05,M=T.buffered,B=this.currentOp("video");!M.length&&!B?this.blockAudio(S):!B&&!ue.isBuffered(T,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(S)}else if(n==="video"){const R=S.end;if(L){const I=L.frag.start;(R>I||R<this.lastVideoAppendEnd||ue.isBuffered(T,I))&&this.unblockAudio()}this.lastVideoAppendEnd=R}}const A=(l||o).start,x={label:`append-${n}`,execute:()=>{var S;c.executeStart=self.performance.now();const L=(S=this.tracks[n])==null?void 0:S.buffer;L&&(b?this.updateTimestampOffset(L,A,.1,n,h,f):u!==void 0&&Q(u)&&this.updateTimestampOffset(L,u,1e-6,n,h,f)),this.appendExecutor(r,n)},onStart:()=>{},onComplete:()=>{const S=self.performance.now();c.executeEnd=c.end=S,p.first===0&&(p.first=S),g&&g.first===0&&(g.first=S);const L={};this.sourceBuffers.forEach(([R,I])=>{R&&(L[R]=ue.getBuffered(I))}),this.appendErrors[n]=0,n==="audio"||n==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(y.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:d,parent:o.type,timeRanges:L})},onError:S=>{var L;const R={type:ie.MEDIA_ERROR,parent:o.type,details:w.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:d,error:S,err:S,fatal:!1},I=(L=this.media)==null?void 0:L.error;if(S.code===DOMException.QUOTA_EXCEEDED_ERR||S.name=="QuotaExceededError"||"quota"in S)R.details=w.BUFFER_FULL_ERROR;else if(S.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!I)R.errorAction=Nn(!0);else if(S.name===Rb&&this.sourceBufferCount===0)R.errorAction=Nn(!0);else{const M=++this.appendErrors[n];this.warn(`Failed ${M}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${I||"no media error"})`),(M>=this.hls.config.appendErrorMaxRetry||I)&&(R.fatal=!0)}this.hls.trigger(y.ERROR,R)}};this.log(`queuing "${n}" append sn: ${h}${l?" p: "+l.index:""} of ${o.type===J.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(x,n,this.isPending(this.tracks[n]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(y.BUFFER_FLUSHED,{type:e})},onError:r=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,r)}}}onBufferFlushing(e,t){const{type:s,startOffset:r,endOffset:n}=t;s?this.append(this.getFlushOp(s,r,n),s):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,r,n),a)})}onFragParsed(e,t){const{frag:s,part:r}=t,n=[],a=r?r.elementaryStreams:s.elementaryStreams;a[Ue.AUDIOVIDEO]?n.push("audiovideo"):(a[Ue.AUDIO]&&n.push("audio"),a[Ue.VIDEO]&&n.push("video"));const o=()=>{const l=self.performance.now();s.stats.buffering.end=l,r&&(r.stats.buffering.end=l);const d=r?r.stats:s.stats;this.hls.trigger(y.FRAG_BUFFERED,{frag:s,part:r,stats:d,id:s.type})};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,n).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([a])=>{if(a){const o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});const r=((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)})?r?(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(y.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(y.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===w.BUFFER_APPEND_ERROR&&t.frag){var s;const r=(s=t.errorAction)==null?void 0:s.nextAutoLevel;Q(r)&&r!==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 r=e.config,n=s.currentTime,a=t.levelTargetDuration,o=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(Q(o)&&o>=0){const d=Math.max(o,a),u=Math.floor(n/a)*a-d;this.flushBackBuffer(n,a,u)}const l=r.frontBufferFlushThreshold;if(Q(l)&&l>0){const d=Math.max(r.maxBufferLength,l),u=Math.max(d,a),c=Math.floor(n/a)*a+u;this.flushFrontBuffer(n,a,c)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([r,n])=>{if(n){const o=ue.getBuffered(n);if(o.length>0&&s>o.start(0)){var a;this.hls.trigger(y.BACK_BUFFER_REACHED,{bufferEnd:s});const l=this.tracks[r];if((a=this.details)!=null&&a.live)this.hls.trigger(y.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(l!=null&&l.ended){this.log(`Cannot flush ${r} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:r})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([r,n])=>{if(n){const a=ue.getBuffered(n),o=a.length;if(o<2)return;const l=a.start(o-1),d=a.end(o-1);if(s>l||e>=l&&e<=d)return;this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:r})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||s?.readyState!=="open")return null;const r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const d=Math.max(0,t.fragmentStart),u=Math.max(d,r);return{duration:1/0,start:d,end:u}}return{duration:1/0}}const n=(e=this.overrides)==null?void 0:e.duration;if(n)return Q(n)?{duration:n}:null;const a=this.media.duration,o=Q(s.duration)?s.duration:0;return r>o&&r>a||!Q(a)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:s}){const r=this.mediaSource;!this.media||!r||r.readyState!=="open"||(r.duration!==e&&(Q(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${s}.`),r.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}) ${$e(s)}`),this.tracksReady){var r;const n=(r=this.transferData)==null?void 0:r.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const r=this.tracks[t];e[t]={buffer:s,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(y.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(y.ERROR,{type:ie.MEDIA_ERROR,details:w.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in e){const a=n,o=e[a];if(this.isPending(o)){const l=this.getTrackCodec(o,a),d=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${d})${this.currentOp(a)?" Queued":""} ${$e(o)}`);try{const u=s.addSourceBuffer(d),c=Dc(a),h=[a,u];t[c]=h,o.buffer=u}catch(u){var r;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(a),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[a],this.hls.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:a,mimeType:d,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let r=e.codec;s&&(t==="video"||t==="audiovideo")&&mo(s,"video")&&(r=bR(r,s));const n=Hl(r,e.levelCodec);return n?t.slice(0,5)==="audio"?zd(n,this.appendSource):n:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const r=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,a)=>{const o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(y.BUFFER_FLUSHED,{type:n})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s?.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${r}`,t),this.hls.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});const n=this.currentOp(e);n&&n.onError(r)}updateTimestampOffset(e,t,s,r,n,a){const o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:r,mediaSource:n}=this,a=this.tracks[e],o=a?.buffer;if(!r||!n||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const l=Q(r.duration)?r.duration:1/0,d=Q(n.duration)?n.duration:1/0,u=Math.max(0,t),c=Math.min(s,l,d);c>u&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${u},${c}] from the ${e} SourceBuffer`),o.remove(u,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],r=s?.buffer;if(!r)throw new kD(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,r.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,r=t.map(a=>this.appendBlocker(a));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then(a=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const r=(s=this.tracks[t])==null?void 0:s.buffer;!r||r.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 r=this.tracks[e];if(!r)return;const n=r.buffer;if(!n)return;const a=s.bind(this,e);r.listeners.push({event:t,listener:a}),n.addEventListener(t,a)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(r=>{s.removeEventListener(r.event,r.listener)}),t.listeners.length=0)}}function T0(i){const e=i.querySelectorAll("source");[].slice.call(e).forEach(t=>{i.removeChild(t)})}function CD(i,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,i.appendChild(t)}function Dc(i){return i==="audio"?1:0}class zm{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(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.BUFFER_CODECS,this.onBufferCodecs,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.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&&Q(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((r,n)=>this.isLevelAllowed(r)&&n<=e);return this.clientRect=null,zm.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 r=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let n=e.length-1;const a=Math.max(t,s);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=a||l.height>=a)&&r(l,e[o+1])){n=o;break}}return n}}const wD={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Mt=wD,MD={HLS:"h"},PD=MD;class ss{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof ss?s:new ss(s))),this.value=e,this.params=t}}const OD="Dict";function ND(i){return Array.isArray(i)?JSON.stringify(i):i instanceof Map?"Map{}":i instanceof Set?"Set{}":typeof i=="object"?JSON.stringify(i):String(i)}function UD(i,e,t,s){return new Error(`failed to ${i} "${ND(e)}" as ${t}`,{cause:s})}function rs(i,e,t){return UD("serialize",i,e,t)}class kb{constructor(e){this.description=e}}const _0="Bare Item",$D="Boolean";function FD(i){if(typeof i!="boolean")throw rs(i,$D);return i?"?1":"?0"}function BD(i){return btoa(String.fromCharCode(...i))}const HD="Byte Sequence";function GD(i){if(ArrayBuffer.isView(i)===!1)throw rs(i,HD);return`:${BD(i)}:`}const KD="Integer";function VD(i){return i<-999999999999999||999999999999999<i}function Db(i){if(VD(i))throw rs(i,KD);return i.toString()}function WD(i){return`@${Db(i.getTime()/1e3)}`}function Cb(i,e){if(i<0)return-Cb(-i,e);const t=Math.pow(10,e);if(Math.abs(i*t%1-.5)<Number.EPSILON){const r=Math.floor(i*t);return(r%2===0?r:r+1)/t}else return Math.round(i*t)/t}const qD="Decimal";function YD(i){const e=Cb(i,3);if(Math.floor(Math.abs(e)).toString().length>12)throw rs(i,qD);const t=e.toString();return t.includes(".")?t:`${t}.0`}const jD="String",zD=/[\x00-\x1f\x7f]+/;function QD(i){if(zD.test(i))throw rs(i,jD);return`"${i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function XD(i){return i.description||i.toString().slice(7,-1)}const ZD="Token";function A0(i){const e=XD(i);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw rs(e,ZD);return e}function jh(i){switch(typeof i){case"number":if(!Q(i))throw rs(i,_0);return Number.isInteger(i)?Db(i):YD(i);case"string":return QD(i);case"symbol":return A0(i);case"boolean":return FD(i);case"object":if(i instanceof Date)return WD(i);if(i instanceof Uint8Array)return GD(i);if(i instanceof kb)return A0(i);default:throw rs(i,_0)}}const JD="Key";function zh(i){if(/^[a-z*][a-z0-9\-_.*]*$/.test(i)===!1)throw rs(i,JD);return i}function Qm(i){return i==null?"":Object.entries(i).map(([e,t])=>t===!0?`;${zh(e)}`:`;${zh(e)}=${jh(t)}`).join("")}function wb(i){return i instanceof ss?`${jh(i.value)}${Qm(i.params)}`:jh(i)}function eC(i){return`(${i.value.map(wb).join(" ")})${Qm(i.params)}`}function tC(i,e={whitespace:!0}){if(typeof i!="object"||i==null)throw rs(i,OD);const t=i instanceof Map?i.entries():Object.entries(i),s=e?.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof ss||(n=new ss(n));let a=zh(r);return n.value===!0?a+=Qm(n.params):(a+="=",Array.isArray(n.value)?a+=eC(n):a+=wb(n)),a}).join(`,${s}`)}function Mb(i,e){return tC(i,e)}const Di="CMCD-Object",ze="CMCD-Request",ir="CMCD-Session",ks="CMCD-Status",iC={br:Di,ab:Di,d:Di,ot:Di,tb:Di,tpb:Di,lb:Di,tab:Di,lab:Di,url:Di,pb:ze,bl:ze,tbl:ze,dl:ze,ltc:ze,mtp:ze,nor:ze,nrr:ze,rc:ze,sn:ze,sta:ze,su:ze,ttfb:ze,ttfbb:ze,ttlb:ze,cmsdd:ze,cmsds:ze,smrt:ze,df:ze,cs:ze,ts:ze,cid:ir,pr:ir,sf:ir,sid:ir,st:ir,v:ir,msd:ir,bs:ks,bsd:ks,cdn:ks,rtp:ks,bg:ks,pt:ks,ec:ks,e:ks},sC={REQUEST:ze};function rC(i){return Object.keys(i).reduce((e,t)=>{var s;return(s=i[t])===null||s===void 0||s.forEach(r=>e[r]=t),e},{})}function nC(i,e){const t={};if(!i)return t;const s=Object.keys(i),r=e?rC(e):{};return s.reduce((n,a)=>{var o;const l=iC[a]||r[a]||sC.REQUEST,d=(o=n[l])!==null&&o!==void 0?o:n[l]={};return d[a]=i[a],n},t)}function aC(i){return["ot","sf","st","e","sta"].includes(i)}function oC(i){return typeof i=="number"?Q(i):i!=null&&i!==""&&i!==!1}const Pb="event";function lC(i,e){const t=new URL(i),s=new URL(e);if(t.origin!==s.origin)return i;const r=t.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+t.search+t.hash}const ql=i=>Math.round(i),Qh=(i,e)=>Array.isArray(i)?i.map(t=>Qh(t,e)):i instanceof ss&&typeof i.value=="string"?new ss(Qh(i.value,e),i.params):(e.baseUrl&&(i=lC(i,e.baseUrl)),e.version===1?encodeURIComponent(i):i),Jo=i=>ql(i/100)*100,dC=(i,e)=>{let t=i;return e.version>=2&&(i instanceof ss&&typeof i.value=="string"?t=new ss([i]):typeof i=="string"&&(t=[i])),Qh(t,e)},uC={br:ql,d:ql,bl:Jo,dl:Jo,mtp:Jo,nor:dC,rtp:Jo,tb:ql},Ob="request",Nb="response",Xm=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],cC=["e"],hC=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function ju(i){return hC.test(i)}function fC(i){return Xm.includes(i)||cC.includes(i)||ju(i)}const Ub=["d","dl","nor","ot","rtp","su"];function mC(i){return Xm.includes(i)||Ub.includes(i)||ju(i)}const pC=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function gC(i){return Xm.includes(i)||Ub.includes(i)||pC.includes(i)||ju(i)}const vC=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function EC(i){return vC.includes(i)||ju(i)}const yC={[Nb]:gC,[Pb]:fC,[Ob]:mC};function $b(i,e={}){const t={};if(i==null||typeof i!="object")return t;const s=e.version||i.v||1,r=e.reportingMode||Ob,n=s===1?EC:yC[r];let a=Object.keys(i).filter(n);const o=e.filter;typeof o=="function"&&(a=a.filter(o));const l=r===Nb||r===Pb;l&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");const d=Oe({},uC,e.formatters),u={version:s,reportingMode:r,baseUrl:e.baseUrl};return a.sort().forEach(c=>{let h=i[c];const f=d[c];if(typeof f=="function"&&(h=f(h,u)),c==="v"){if(s===1)return;h=s}c=="pr"&&h===1||(l&&c==="ts"&&!Q(h)&&(h=Date.now()),oC(h)&&(aC(c)&&typeof h=="string"&&(h=new kb(h)),t[c]=h))}),t}function bC(i,e={}){const t={};if(!i)return t;const s=$b(i,e),r=nC(s,e?.customHeaderMap);return Object.entries(r).reduce((n,[a,o])=>{const l=Mb(o,{whitespace:!1});return l&&(n[a]=l),n},t)}function TC(i,e,t){return Oe(i,bC(e,t))}const _C="CMCD";function AC(i,e={}){return i?Mb($b(i,e),{whitespace:!1}):""}function SC(i,e={}){if(!i)return"";const t=AC(i,e);return encodeURIComponent(t)}function IC(i,e={}){if(!i)return"";const t=SC(i,e);return`${_C}=${t}`}const S0=/CMCD=[^&#]+/;function xC(i,e,t){const s=IC(e,t);if(!s)return i;if(S0.test(i))return i.replace(S0,s);const r=i.includes("?")?"&":"?";return`${i}${r}${s}`}class LC{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=r=>{try{this.apply(r,{ot:Mt.MANIFEST,su:!this.initialized})}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=r=>{try{const{frag:n,part:a}=r,o=this.hls.levels[n.level],l=this.getObjectType(n),d={d:(a||n).duration*1e3,ot:l};(l===Mt.VIDEO||l===Mt.AUDIO||l==Mt.MUXED)&&(d.br=o.bitrate/1e3,d.tb=this.getTopBandwidth(l)/1e3,d.bl=this.getBufferLength(l));const u=a?this.getNextPart(a):this.getNextFrag(n);u!=null&&u.url&&u.url!==n.url&&(d.nor=u.url),this.apply(r,d)}catch(n){this.hls.logger.warn("Could not generate segment CMCD data.",n)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHED,this.onMediaDetached,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHED,this.onMediaDetached,this),e.off(y.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,r;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(r=t.tracks.video)==null?void 0:r.buffer}createData(){var e;return{v:1,sf:PD.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Oe(t,this.createData());const s=t.ot===Mt.INIT||t.ot===Mt.VIDEO||t.ot===Mt.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((a,o)=>(r.includes(o)&&(a[o]=t[o]),a),{}));const n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),TC(e.headers,t,n)):e.url=xC(e.url,t,n)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const r=e.sn-s.startSN;return s.fragments[r+1]}}getNextPart(e){var t;const{index:s,fragment:r}=e,n=(t=this.hls.levels[r.level])==null||(t=t.details)==null?void 0:t.partList;if(n){const{sn:a}=r;for(let o=n.length-1;o>=0;o--){const l=n[o];if(l.index===s&&l.fragment.sn===a)return n[o+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Mt.TIMED_TEXT;if(e.sn==="initSegment")return Mt.INIT;if(t==="audio")return Mt.AUDIO;if(t==="main")return this.hls.audioTracks.length?Mt.VIDEO:Mt.MUXED}getTopBandwidth(e){let t=0,s;const r=this.hls;if(e===Mt.AUDIO)s=r.audioTracks;else{const n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;s=r.levels.slice(0,a)}return s.forEach(n=>{n.bitrate>t&&(t=n.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===Mt.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:ue.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new s(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new s(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}}const RC=3e5;class kC extends di{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(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(s=>s!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if(s?.action===St.SendAlternateToPenaltyBox&&s.flags===Wt.MoveAllAlternatesMatchingHost){const r=this.levels;let n=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:d}=t.context;o&&r?a=this.getPathwayForGroupId(o,d,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&r&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),s.resolved=this.pathwayId!==a),t.details===w.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${r&&r.length} priorities: ${$e(n)} penalized: ${$e(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,r=performance.now();Object.keys(s).forEach(n=>{r-s[n]>RC&&delete s[n]});for(let n=0;n<e.length;n++){const a=e[n];if(a in s)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,rb(t),this.hls.trigger(y.LEVELS_UPDATED,{levels:t});const d=this.hls.levels[o];l&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const r=this.getLevelsForPathway(s).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===pe.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===pe.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},r={};e.forEach(n=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(u=>u.pathwayId===a))return;const d=this.getLevelsForPathway(o).map(u=>{const c=new Ye(u.attrs);c["PATHWAY-ID"]=a;const h=c.AUDIO&&`${c.AUDIO}_clone_${a}`,f=c.SUBTITLES&&`${c.SUBTITLES}_clone_${a}`;h&&(s[c.AUDIO]=h,c.AUDIO=h),f&&(r[c.SUBTITLES]=f,c.SUBTITLES=f);const m=Fb(u.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),p=new go({attrs:c,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:m,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let g=1;g<u.audioGroups.length;g++)p.addGroupId("audio",`${u.audioGroups[g]}_clone_${a}`);if(u.subtitleGroups)for(let g=1;g<u.subtitleGroups.length;g++)p.addGroupId("text",`${u.subtitleGroups[g]}_clone_${a}`);return p});t.push(...d),I0(this.audioTracks,s,l,a),I0(this.subtitleTracks,r,l,a)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+u)}const n={responseType:"json",url:r.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},d={onSuccess:(u,c,h,f)=>{this.log(`Loaded steering manifest: "${r}"`);const m=u.data;if(m?.VERSION!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":g,"PATHWAY-PRIORITY":v}=m;if(p)try{this.uri=new self.URL(p,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||h.url),g&&this.clonePathways(g);const b={steeringManifest:m,url:r.toString()};this.hls.trigger(y.STEERING_MANIFEST_LOADED,b),v&&this.updatePathwayPriority(v)},onError:(u,c,h,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${c.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let m=this.timeToLoad*1e3;if(u.code===429){const p=this.loader;if(typeof p?.getResponseHeader=="function"){const g=p.getResponseHeader("Retry-After");g&&(m=parseFloat(g)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,m)},onTimeout:(u,c,h)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,l,d)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const r=(s=this.hls)==null?void 0:s.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function I0(i,e,t,s){i&&Object.keys(e).forEach(r=>{const n=i.filter(a=>a.groupId===r).map(a=>{const o=Oe({},a);return o.details=void 0,o.attrs=new Ye(o.attrs),o.url=o.attrs.URI=Fb(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=s,o});i.push(...n)})}function Fb(i,e,t,s){const{HOST:r,PARAMS:n,[t]:a}=s;let o;e&&(o=a?.[e],o&&(i=o));const l=new self.URL(i);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(d=>{d&&l.searchParams.set(d,n[d])}),l.href}class $n extends di{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=$n.CDMCleanupPromise?[$n.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:s,initData:r}=t,n=`"${t.type}" event: init data type: "${s}"`;if(this.debug(n),r!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=ka(this.config));const o=a.map(_c).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=Kl(a);if(s!=="sinf"||o!==je.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let l;try{const f=mt(new Uint8Array(r)),m=Fm(JSON.parse(f).sinf),p=My(m);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(p.subarray(8,24))}catch(f){this.warn(`${n} Failed to parse sinf: ${f}`);return}const d=It(l),{keyIdToKeySessionPromise:u,mediaKeySessions:c}=this;let h=u[d];for(let f=0;f<c.length;f++){const m=c[f],p=m.decryptdata;if(!p.keyId)continue;const g=It(p.keyId);if(eu(l,p.keyId)||p.uri.replace(/-/g,"").indexOf(d)!==-1){if(h=u[g],!h)continue;if(p.pssh)break;delete u[g],p.pssh=new Uint8Array(r),p.keyId=l,h=u[d]=h.then(()=>this.generateRequestWithPreferredKeySession(m,s,r,"encrypted-event-key-match")),h.catch(v=>this.handleError(v));break}}h||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${c.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(y.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(y.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(y.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(y.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,r=t?.[e];if(r)return r.licenseUrl;if(e===je.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,l)=>!!a&&l.indexOf(a)===o,r=t.map(a=>a.audioCodec).filter(s),n=t.map(a=>a.videoCodec).filter(s);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{const l=d=>{const u=d.shift();this.getMediaKeysPromise(u,r,n).then(c=>a({keySystem:u,mediaKeys:c})).catch(c=>{d.length?l(d):c instanceof Vt?o(c):o(new Vt({type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_ACCESS,error:c,fatal:!0},c.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${s}`;return Qy===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return s(e,t)}getMediaKeysPromise(e,t,s){var r;const n=dk(e,t,s,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],o=(r=a)==null?void 0:r.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${$e(n)}`),o=this.requestMediaKeySystemAccess(e,n);const l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${e}": ${d}`)}),o.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);const u=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const c=l.mediaKeys=d.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,u.then(f=>f?this.setMediaKeysServerCertificate(h,e,f):h)));return c.catch(h=>{this.error(`Failed to create media-keys for "${e}"}: ${h}`)}),c})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${It(e.keyId||[])} keyUri: ${e.uri}`);const r=s.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),r=el(t),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(s,n,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${It(e.decryptdata.keyId||[])}
|
|
1444
|
-
} (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>_c(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:r})=>{const n=_c(r);n?t(n):s(new Error(`Unable to find format for key-system "${r}"`))}).catch(s)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=ka(this.config),s=e.map(Kl).filter(r=>!!r&&t.indexOf(r)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const r=DC(e,t[s]);if(r)return r}}loadKey(e){const t=e.keyInfo.decryptdata,s=el(t),r=this.bannedKeyIds[s];if(r||this.getKeyStatus(t)==="internal-error"){const o=x0(r||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}const n=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);const a=this.keyIdToKeySessionPromise[s];if(!a){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:l,mediaKeys:d})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(l,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:l,mediaKeys:d,decryptdata:t}))))).then(l=>{const d="cenc",u=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(l,d,u,"playlist-key")});return o.catch(l=>this.handleError(l,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return a.catch(o=>{if(o instanceof Vt){const l=Ce({},o.data);this.getKeyStatus(t)==="internal-error"&&(l.decryptdata=t);const d=new Vt(l,o.message);this.handleError(d,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Vt){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${It(s.keyId||[])})`:""}`),this.hls.trigger(y.ERROR,e.data)}else this.error(e.message),this.hls.trigger(y.ERROR,{type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=el(e),s=this.keyIdToKeySessionPromise[t];if(!s){const r=Kl(e.keyFormat),n=r?[r]:ka(this.config);return this.attemptKeySystemAccess(n)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=ka(this.config)),e.length===0)throw new Vt({type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${$e({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const r=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((n,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(n).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>s.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,s,r){var n;const a=(n=this.config.drmSystems)==null||(n=n[e.keySystem])==null?void 0:n.generateRequest;if(a)try{const m=a.call(this.hls,t,s,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,s=m.initData?m.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(m){if(this.warn(m.message),this.hls&&this.hls.config.debug)throw m}if(s===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);const o=el(e.decryptdata),l=e.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${o} URI: ${l} (init data type: ${t} length: ${s.byteLength})`);const d=new Hm,u=e._onmessage=m=>{const p=e.mediaKeysSession;if(!p){d.emit("error",new Error("invalid state"));return}const{messageType:g,message:v}=m;this.log(`"${g}" message event for session "${p.sessionId}" message size: ${v.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,v).catch(b=>{d.eventNames().length?d.emit("error",b):this.handleError(b)}):g==="license-release"?e.keySystem===je.FAIRPLAY&&this.updateKeySession(e,Gh("acknowledged")).then(()=>this.removeSession(e)).catch(b=>this.handleError(b)):this.warn(`unhandled media key message type "${g}"`)},c=(m,p)=>{p.keyStatus=m;let g;m.startsWith("usable")?d.emit("resolved"):m==="internal-error"||m==="output-restricted"||m==="output-downscaled"?g=x0(m,p.decryptdata):m==="expired"?g=new Error(`key expired (keyId: ${o})`):m==="released"?g=new Error("key released"):m==="status-pending"||this.warn(`unhandled key status change "${m}" (keyId: ${o})`),g&&(d.eventNames().length?d.emit("error",g):this.handleError(g))},h=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const g=this.getKeyStatuses(e);if(!Object.keys(g).some(T=>g[T]!=="status-pending"))return;if(g[o]==="expired"){this.log(`Expired key ${$e(g)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let b=g[o];if(b)c(b,e);else{var E;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(E=e.keyStatusTimeouts)[o]||(E[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const A=this.getKeyStatus(e.decryptdata);if(A&&A!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${A} from other session.`),c(A,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),b="internal-error",c(b,e)},1e3)),this.log(`No status for keyId ${o} (${$e(g)}).`)}};wt(e.mediaKeysSession,"message",u),wt(e.mediaKeysSession,"keystatuseschange",h);const f=new Promise((m,p)=>{d.on("error",p),d.on("resolved",m)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${l}`)}).catch(m=>{throw new Vt({type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_SESSION,error:m,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>(d.removeAllListeners(),this.removeSession(e).then(()=>{throw m}))).then(()=>(d.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,r)=>{if(typeof r=="string"&&typeof s=="object"){const o=r;r=s,s=o}const n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(e.keySystem===je.PLAYREADY&&n.length===16){const o=It(n);t[o]=s,jy(n)}const a=It(n);s==="internal-error"&&(this.bannedKeyIds[a]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=s}),t}fetchServerCertificate(e){const t=this.config,s=t.loader,r=new s(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:n},d=t.certLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{a(h.data)},onError:(h,f,m,p)=>{o(new Vt({type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:Ce({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${n}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,m)=>{o(new Vt({type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(h,f,m)=>{o(new Error("aborted"))}};r.load(l,u,c)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((r,n)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),r(e)}).catch(a=>{n(new Vt({type:ie.KEY_SYSTEM_ERROR,details:w.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(r=>{throw new Vt({type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:r,fatal:!1},r.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 r=new DOMParser().parseFromString(s,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let u;for(let c=0,h=n.length;c<h;c++){var a,o;u=n[c];const f=(a=u.querySelector("name"))==null?void 0:a.textContent,m=(o=u.querySelector("value"))==null?void 0:o.textContent;f&&m&&e.setRequestHeader(f,m)}}const l=r.querySelector("Challenge"),d=l?.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return Gh(atob(d))}setupLicenseXHR(e,t,s,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,s,r)}).catch(a=>{if(!s.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,s,r)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{const a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const d=this.config.licenseResponseCallback;if(d)try{l=d.call(this.hls,o,a,e)}catch(u){this.error(u)}r(l)}else{const l=s.errorRetry,d=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)n(new Vt({type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const u=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(r,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:d})=>{e.keySystem==je.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(l,d)),l.send(d)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,wt(s,"encrypted",this.onMediaEncrypted),wt(s,"waitingforkey",this.onWaitingForKey);const r=this.mediaResolved;r?r():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(Nt(e,"encrypted",this.onMediaEncrypted),Nt(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,js.clearKeyUriToKeyIdMap();const n=r.length;$n.CDMCleanupPromise=Promise.all(r.map(a=>this.removeSession(a)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:r}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${It(r?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);const{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(d=>self.clearTimeout(a[d]));const{drmSystemOptions:o}=this.config;return(ck(o)?new Promise((d,u)=>{self.setTimeout(()=>u(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(d).catch(u)}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${d}`)})}).then(()=>t.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}$n.CDMCleanupPromise=void 0;function el(i){if(!i)throw new Error("Could not read keyId of undefined decryptdata");if(i.keyId===null)throw new Error("keyId is null");return It(i.keyId)}function DC(i,e){if(i.keyId&&e.mediaKeysSession.keyStatuses.has(i.keyId))return e.mediaKeysSession.keyStatuses.get(i.keyId);if(i.matches(e.decryptdata))return e.keyStatus}class Vt extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function x0(i,e){const t=i==="output-restricted",s=t?w.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:w.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Vt({type:ie.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${i}"`)}class CC{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(y.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(y.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 r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&typeof r.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const r=performance.now();if(t){if(this.lastTime){const n=r-this.lastTime,a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,d=this.hls;if(d.trigger(y.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),l>0&&a>d.config.fpsDroppedMonitoringThreshold*o){let u=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=u)&&(u=u-1,d.trigger(y.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:d.currentLevel}),d.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=r,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 Bb(i,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=i,e.dispatchEvent(t)}function Hb(i,e){const t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues&&!i.cues.getCueById(e.id))try{if(i.addCue(e),!i.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){we.debug(`[texttrack-utils]: ${s}`);try{const r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,i.addCue(r)}catch(r){we.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}t==="disabled"&&(i.mode=t)}function Cn(i,e){const t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues)for(let s=i.cues.length;s--;)e&&i.cues[s].removeEventListener("enter",e),i.removeCue(i.cues[s]);t==="disabled"&&(i.mode=t)}function Xh(i,e,t,s){const r=i.mode;if(r==="disabled"&&(i.mode="hidden"),i.cues&&i.cues.length>0){const n=MC(i.cues,e,t);for(let a=0;a<n.length;a++)(!s||s(n[a]))&&i.removeCue(n[a])}r==="disabled"&&(i.mode=r)}function wC(i,e){if(e<=i[0].startTime)return 0;const t=i.length-1;if(e>i[t].endTime)return-1;let s=0,r=t,n;for(;s<=r;)if(n=Math.floor((r+s)/2),e<i[n].startTime)r=n-1;else if(e>i[n].startTime&&s<t)s=n+1;else return n;return i[s].startTime-e<e-i[r].startTime?s:r}function MC(i,e,t){const s=[],r=wC(i,e);if(r>-1)for(let n=r,a=i.length;n<a;n++){const o=i[n];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function Yl(i){const e=[];for(let t=0;t<i.length;t++){const s=i[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(i[t])}return e}class PC extends jm{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=Yl(this.media.textTracks);for(let n=0;n<s.length;n++)if(s[n].mode==="hidden")t=s[n];else if(s[n].mode==="showing"){t=s[n];break}const r=this.findTrackForTextTrack(t);this.subtitleTrack!==r&&this.setSubtitleTrack(r)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(y.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 r=!!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,r)return;Yl(s.textTracks).forEach(a=>{Cn(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:r,details:n}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${s} and group:${r} not found in active group ${a?.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${s} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,r=this.groupIds;let n=this.currentTrack;if(!s||r?.length!==s?.length||s!=null&&s.some(a=>r?.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,c)=>{u.id=c});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;const u=Qi(o,a);if(u>-1)n=a[u];else{const c=Qi(o,this.tracks);n=this.tracks[c]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));const d={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(y.SUBTITLE_TRACKS_UPDATED,d),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let r=0;r<t.length;r++){const n=t[r];if(!(s&&!n.default||!s&&!e)&&(!e||Lr(n,e)))return r}if(e){for(let r=0;r<t.length;r++){const n=t[r];if(bo(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){const n=t[r];if(bo(e.attrs,n.attrs,["LANGUAGE"]))return r}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const r=t[s];if(Yh(r,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===pe.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&&Lr(e,s))return s;const r=Qi(e,this.tracksInGroup);if(r>-1){const n=this.tracksInGroup[r];return this.setSubtitleTrack(r),n}else{if(s)return null;{const n=Qi(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(y.SUBTITLE_TRACK_LOADING,{url:n,id:s,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Yl(e.textTracks),s=this.currentTrack;let r;if(s&&(r=t.filter(n=>Yh(s,n))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==r&&(n.mode="disabled")}),r){const n=this.subtitleDisplay?"showing":"hidden";r.mode!==n&&(r.mode=n)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!Q(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r){this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:e});return}const n=!!r.details&&!r.details.live;if(e===this.trackId&&r===s&&n)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:a,groupId:o="",name:l,type:d,url:u}=r;this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:d,url:u});const c=this.switchParams(r.url,s?.details,r.details);this.loadPlaylist(c)}}function OC(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(r=="x"?n:n&3|8).toString(16)})}}}function Xa(i){let e=5381,t=i.length;for(;t;)e=e*33^i.charCodeAt(--t);return(e>>>0).toString()}const Fn=.025;let ru=(function(i){return i[i.Point=0]="Point",i[i.Range=1]="Range",i})({});function NC(i,e,t){return`${i.identifier}-${t+1}-${Xa(e)}`}class UC{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return Cc(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=Cc(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=Q(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 Cc(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)<Fn))}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"?ru.Range:ru.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 $C(this)}}function Cc(i,e){return i-e.start<e.duration/2&&!(Math.abs(i-(e.start+e.duration))<Fn)?e.start:e.start+e.duration}function Gb(i,e,t){const s=new self.URL(i,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function wc(i,e){for(;(t=i.assetList[++e])!=null&&t.error;)var t;return e}function $C(i){return`["${i.identifier}" ${i.cue.pre?"<pre>":i.cue.post?"<post>":""}${i.timelineStart.toFixed(2)}-${i.resumeTime.toFixed(2)}]`}function gn(i){const e=i.timelineStart,t=i.duration||0;return`["${i.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class FC{constructor(e,t,s,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(y.PLAYOUT_LIMIT_REACHED,{})};const n=this.hls=new e(t);this.interstitial=s,this.assetItem=r;const a=()=>{this.hasDetails=!0};n.once(y.LEVEL_LOADED,a),n.once(y.AUDIO_TRACK_LOADED,a),n.once(y.SUBTITLE_TRACK_LOADED,a),n.on(y.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(y.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,n.trigger(y.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Gb(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,n=ue.bufferInfo(e,r,0);return this.getAssetTime(n.end)>=s-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=ue.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var r;(r=this.hls)==null||r.on(e,t)}once(e,t,s){var r;(r=this.hls)==null||r.once(e,t)}off(e,t,s){var r;(r=this.hls)==null||r.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${gn(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const L0=.033;class BC extends di{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,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.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 r=this.items;if(r)for(r[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(n=r[s])!=null&&n.event;){var n;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let r=0;r<s.length;r++){let n=s[r];if(t&&t!=="primary"&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return r}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let r=e;r<=t&&s[r];r++){const n=s[r].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return r}return-1}findEventIndex(e){const t=this.items;if(t)for(let r=t.length;r--;){var s;if(((s=t[r].event)==null?void 0:s.identifier)===e)return r}return-1}findAssetIndex(e,t){const s=e.assetList,r=s.length;if(r>1)for(let n=0;n<r;n++){const a=s[n];if(!a.error){const o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||n===r-1))return n}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,r=s[s.length-1];if(r)return r.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:r}=s,n=this.events,a=this.parseDateRanges(r,{url:s.url},t),o=Object.keys(r),l=n?n.filter(d=>!o.includes(d.identifier)):[];a.length&&a.sort((d,u)=>{const c=d.cue.pre,h=d.cue.post,f=u.cue.pre,m=u.cue.post;if(c&&!f)return-1;if(f&&!c||h&&!m)return 1;if(m&&!h)return-1;if(!c&&!f&&!h&&!m){const p=d.startTime,g=u.startTime;if(p!==g)return p-g}return d.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=a,l.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(e,l)}updateSchedule(e,t=[],s=!1){const r=this.events||[];if(r.length||t.length||this.length<2){const n=this.items,a=this.parseSchedule(r,e);(s||t.length||n?.length!==a.length||a.some((l,d)=>Math.abs(l.playout.start-n[d].playout.start)>.005||Math.abs(l.playout.end-n[d].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,n))}}parseDateRanges(e,t,s){const r=[],n=Object.keys(e);for(let a=0;a<n.length;a++){const o=n[a],l=e[o];if(l.isInterstitial){let d=this.eventMap[o];d?d.setDateRange(l):(d=new UC(l,t),this.eventMap[o]=d,s===!1&&(d.appendInPlace=s)),r.push(d)}}return r}parseSchedule(e,t){const s=[],r=t.main.details,n=r.live?1/0:r.edge;let a=0;if(e=e.filter(l=>!l.error&&!(l.cue.once&&l.hasPlayed)),e.length){this.resolveOffsets(e,t);let l=0,d=0;if(e.forEach((u,c)=>{const h=u.cue.pre,f=u.cue.post,m=e[c-1]||null,p=u.appendInPlace,g=f?n:u.startOffset,v=u.duration,b=u.timelineOccupancy===ru.Range?v:0,E=u.resumptionOffset,T=m?.startTime===g,A=g+u.cumulativeDuration;let x=p?A+v:g+E;if(h||!f&&g<=0){const L=d;d+=b,u.timelineStart=A;const R=a;a+=v,s.push({event:u,start:A,end:x,playout:{start:R,end:a},integrated:{start:L,end:d}})}else if(g<=n){if(!T){const I=g-l;if(I>L0){const M=l,B=d;d+=I;const W=a;a+=I;const j={previousEvent:e[c-1]||null,nextEvent:u,start:M,end:M+I,playout:{start:W,end:a},integrated:{start:B,end:d}};s.push(j)}else I>0&&m&&(m.cumulativeDuration+=I,s[s.length-1].end=g)}f&&(x=A),u.timelineStart=A;const L=d;d+=b;const R=a;a+=v,s.push({event:u,start:A,end:x,playout:{start:R,end:a},integrated:{start:L,end:d}})}else return;const S=u.resumeTime;f||S>n?l=n:l=S}),l<n){var o;const u=l,c=d,h=n-l;d+=h;const f=a;a+=h,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:l,end:u+h,playout:{start:f,end:a},integrated:{start:c,end:d}})}this.setDurations(n,a,d)}else s.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,r=s.live?1/0:s.edge;let n=0,a=-1;e.forEach((o,l)=>{const d=o.cue.pre,u=o.cue.post,c=d?0:u?r:o.startTime;this.updateAssetDurations(o),a===c?o.cumulativeDuration=n:(n=0,a=c),!u&&o.snapOptions.in&&(o.resumeAnchor=Mr(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<L0&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=Q(o.resumeOffset)?o.resumeOffset:o.duration;n+=f})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(s-r)>Fn?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(a=>{const o=t[a].details,l=o.edge;if(s>=l)return this.log(`"${e.identifier}" resumption ${s} past ${a} playlist end ${l}`),!1;const d=Mr(null,o.fragments,s);if(!d)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(d.start-s)<Fn+u||Math.abs(d.end-s)<Fn+u?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${a} fragment bounds (${d.start}-${d.end} sn: ${d.sn} cc: ${d.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,r=!1,n=!1;for(let a=0;a<e.assetList.length;a++){const o=e.assetList[a],l=t+s;o.startOffset=s,o.timelineStart=l,r||(r=o.duration===null),n||(n=!!o.error);const d=o.error?0:o.duration||0;s+=d}r&&!n?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function fi(i){return`[${i.event?'"'+i.event.identifier+'"':"primary"}: ${i.start.toFixed(2)}-${i.end.toFixed(2)}]`}class HC{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let r;try{r=Gb(s,this.hls.sessionId,e.baseUrl)}catch(h){const f=this.assignAssetListError(e,w.ASSET_LIST_LOAD_ERROR,h,s);this.hls.trigger(y.ERROR,f);return}t&&r.protocol!=="data:"&&r.searchParams.set("_HLS_start_offset",""+t);const n=this.hls.config,a=n.loader,o=new a(n),l={responseType:"json",url:r.href},d=n.interstitialAssetListLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{const g=h.data,v=g?.ASSETS;if(!Array.isArray(v)){const b=this.assignAssetListError(e,w.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),m.url,f,p);this.hls.trigger(y.ERROR,b);return}e.assetListResponse=g,this.hls.trigger(y.ASSET_LIST_LOADED,{event:e,assetListResponse:g,networkDetails:p})},onError:(h,f,m,p)=>{const g=this.assignAssetListError(e,w.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${f.url})`),f.url,p,m);this.hls.trigger(y.ERROR,g)},onTimeout:(h,f,m)=>{const p=this.assignAssetListError(e,w.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,h,m);this.hls.trigger(y.ERROR,p)}};return o.load(l,u,c),this.hls.trigger(y.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,r,n,a){return e.error=s,{type:ie.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:s,networkDetails:a,stats:n}}}function R0(i){var e;i==null||(e=i.play())==null||e.catch(()=>{})}function tl(i,e){return`[${i}] Advancing timeline position to ${e}`}class GC extends di{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const r=s-this.timelinePos;if(Math.abs(r)<1/7056e5)return;const a=r<=-.01;this.timelinePos=s,this.bufferedPos=s;const o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(s,s-r)&&this.updateSchedule(!0),this.checkBuffer(),a&&s<o.start||s>=o.end){var l;const f=this.findItemIndex(o);let m=this.schedule.findItemIndexAtTime(s);if(m===-1&&(m=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${s} (resolving from ${f} to ${m})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&m>f){const p=this.schedule.findJumpRestrictedIndex(f+1,m);if(p>f){this.setSchedulePosition(p);return}}this.setSchedulePosition(m);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}return}const u=d.timelineStart,c=d.duration||0;if(a&&s<u||s>=u+c){var h;(h=o.event)!=null&&h.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,d)}},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 r=this.playingItem;if(!r||this.playingLastItem)return;if(s>=r.end){this.timelinePos=r.end;const o=this.findItemIndex(r);this.setSchedulePosition(o+1)}const n=this.playingAsset;if(!n)return;const a=n.timelineStart+(n.duration||0);s>=a&&this.setScheduleToAssetAtTime(s,n)},this.onScheduleUpdate=(s,r)=>{const n=this.schedule;if(!n)return;const a=this.playingItem,o=n.events||[],l=n.items||[],d=n.durations,u=s.map(p=>p.identifier),c=!!(o.length||u.length);(c||r)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
|
|
1445
|
-
Schedule: ${l.map(p=>fi(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let h=null,f=null;a&&(h=this.updateItem(a,this.timelinePos),this.itemsMatch(a,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const m=this.bufferingItem;if(m&&(f=this.updateItem(m,this.bufferedPos),this.itemsMatch(m,f)?this.bufferingItem=f:m.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(m.event,null))),s.forEach(p=>{p.assetList.forEach(g=>{this.clearAssetPlayer(g.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){const g=p.assetItem.timelineStart,v=p.timelineOffset-g;if(v)try{p.timelineOffset=g}catch(b){Math.abs(v)>Fn&&this.warn(`${b} ("${p.assetId}" ${p.timelineOffset}->${g})`)}}}),c||r){if(this.hls.trigger(y.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:d,removedIds:u}),this.isInterstitial(a)&&u.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(h,a),m&&f!==h&&this.trimInPlace(f,m),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new HC(e),this.schedule=new BC(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(y.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(y.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(y.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(y.MEDIA_ENDED,this.onMediaEnded,this),e.on(y.ERROR,this.onError,this),e.on(y.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(y.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(y.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(y.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(y.MEDIA_ENDED,this.onMediaEnded,this),e.off(y.ERROR,this.onError,this),e.off(y.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Nt(e,"play",this.onPlay),Nt(e,"pause",this.onPause),Nt(e,"seeking",this.onSeeking),Nt(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;wt(s,"seeking",this.onSeeking),wt(s,"timeupdate",this.onTimeupdate),wt(s,"play",this.onPlay),wt(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!r){this.clearScheduleState();const n=this.findItemIndex(s);this.setSchedulePosition(n)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,r=this.media;if(this.media=null,!s&&(r&&this.removeMediaListeners(r),this.detachedData)){const n=this.getBufferingPlayer();n&&(this.log(`Removing schedule state for detachedData and ${n}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=c=>c&&e.getAssetPlayer(c.identifier),r=(c,h,f,m,p)=>{if(c){let g=c[h].start;const v=c.event;if(v){if(h==="playout"||v.timelineOccupancy!==ru.Point){const b=s(f);b?.interstitial===v&&(g+=b.assetItem.startOffset+b[p])}}else{const b=m==="bufferedPos"?a():e[m];g+=b-c.start}return g}return 0},n=(c,h)=>{var f;if(c!==0&&h!=="primary"&&(f=e.schedule)!=null&&f.length){var m;const p=e.schedule.findItemIndexAtTime(c),g=(m=e.schedule.items)==null?void 0:m[p];if(g){const v=g[h].start-g.start;return c+v}}return c},a=()=>{const c=e.bufferedPos;return c===Number.MAX_VALUE?o("primary"):Math.max(c,0)},o=c=>{var h,f;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[c])||0},l=(c,h)=>{var f,m;const p=e.effectivePlayingItem;if(p!=null&&(f=p.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${c} "${h}"`);const g=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(c,h),b=(m=e.schedule.items)==null?void 0:m[v],E=e.getBufferingPlayer(),T=E?.interstitial,A=T?.appendInPlace,x=g&&e.itemsMatch(g,b);if(g&&(A||x)){const S=s(e.playingAsset),L=S?.media||e.primaryMedia;if(L){const R=h==="primary"?L.currentTime:r(g,h,e.playingAsset,"timelinePos","currentTime"),I=c-R,M=(A?R:L.currentTime)+I;if(M>=0&&(!S||A||M<=S.duration)){L.currentTime=M;return}}}if(b){let S=c;if(h!=="primary"){const R=b[h].start,I=c-R;S=b.start+I}const L=!e.isInterstitial(b);if((!e.isInterstitial(g)||g.event.appendInPlace)&&(L||b.event.appendInPlace)){const R=e.media||(A?E?.media:null);R&&(R.currentTime=S)}else if(g){const R=e.findItemIndex(g);if(v>R){const M=e.schedule.findJumpRestrictedIndex(R+1,v);if(M>R){e.setSchedulePosition(M);return}}let I=0;if(L)e.timelinePos=S,e.checkBuffer();else{const M=b.event.assetList,B=c-(b[h]||b).start;for(let W=M.length;W--;){const j=M[W];if(j.duration&&B>=j.startOffset&&B<j.startOffset+j.duration){I=W;break}}}e.setSchedulePosition(v,I)}}},d=()=>{const c=e.effectivePlayingItem;if(e.isInterstitial(c))return c;const h=t();return e.isInterstitial(h)?h:null},u={get bufferedEnd(){const c=t(),h=e.bufferingItem;if(h&&h===c){var f;return r(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const c=d(),h=e.effectivePlayingItem;return h&&h===c?r(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(c){const h=d(),f=e.effectivePlayingItem;f&&f===h&&l(c+f.playout.start,"playout")},get duration(){const c=d();return c?c.playout.end-c.playout.start:0},get assetPlayers(){var c;const h=(c=d())==null?void 0:c.event.assetList;return h?h.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var c;const h=(c=d())==null?void 0:c.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var c;return((c=e.schedule)==null||(c=c.events)==null?void 0:c.slice(0))||[]},get schedule(){var c;return((c=e.schedule)==null||(c=c.items)==null?void 0:c.slice(0))||[]},get interstitialPlayer(){return d()?u:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const c=t();return e.findItemIndex(c)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const c=e.effectivePlayingItem;return e.findItemIndex(c)},primary:{get bufferedEnd(){return a()},get currentTime(){const c=e.timelinePos;return c>0?c:0},set currentTime(c){l(c,"primary")},get duration(){return o("primary")},get seekableStart(){var c;return((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(c){l(c,"integrated")},get duration(){return o("integrated")},get seekableStart(){var c;return n(((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0,"integrated")}},skip:()=>{const c=e.effectivePlayingItem,h=c?.event;if(h&&!h.restrictions.skip){const f=e.findItemIndex(c);if(h.appendInPlace){const m=c.playout.start+c.event.duration;l(m+.001,"playout")}else e.advanceAfterAssetEnded(h,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let r=this.media;!r&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(r=this.primaryMedia);const n=(t=r)==null?void 0:t.currentTime;if(!(n===void 0||!Q(n)))return n}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,r=e.media;if(s&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}const n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${$e(n)}`),this.detachedData=n}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(e,t){var s,r;if(e.media===t)return;let n=null;const a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,d=(s=this.detachedData)==null?void 0:s.mediaSource;let u;if(a.media)l&&(n=a.transferMedia(),this.detachedData=n),u="Primary";else if(d){const m=this.getBufferingPlayer();m?(n=m.transferMedia(),u=`${m}`):u="detached MediaSource"}else u="detached media";if(!n){if(d)n=this.detachedData,this.log(`using detachedData: MediaSource ${$e(n)}`);else if(!this.detachedData||a.media===t){const m=this.playerQueue;m.length>1&&m.forEach(p=>{if(o&&p.interstitial.appendInPlace!==l){const g=p.interstitial;this.clearInterstitial(p.interstitial,null),g.appendInPlace=!1,g.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${g}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const c=n&&"mediaSource"in n&&((r=n.mediaSource)==null?void 0:r.readyState)!=="closed",h=c&&n?n:t;this.log(`${c?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${u} (media.currentTime: ${t.currentTime})`);const f=this.schedule;if(h===n&&f){const m=o&&e.assetId===f.assetIdAtEnd;h.overrides={duration:f.duration,endOfStream:!o||m,cueRemoval:!o}}e.attachMedia(h)}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,r=this.effectivePlayingItem;if(s===-1){const n=this.hls.startPosition;if(this.log(tl("checkStart",n)),this.timelinePos=n,t.length&&t[0].cue.pre){const a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(n>=0||!this.primaryLive){const a=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(r&&!this.playingItem){const n=e.findItemIndex(r);this.setSchedulePosition(n)}}advanceAssetBuffering(e,t){const s=e.event,r=s.findAssetIndex(t),n=wc(s,r);if(!s.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var a;const o=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,s){const r=wc(e,s);if(e.isAssetPastPlayoutLimit(r)){if(this.schedule){const n=this.schedule.items;if(n){const a=t+1,o=n.length;if(a>=o){this.setSchedulePosition(-1);return}const l=e.resumeTime;this.timelinePos<l&&(this.log(tl("advanceAfterAssetEnded",l)),this.timelinePos=l,e.appendInPlace&&this.advanceInPlace(l),this.checkBuffer(this.bufferedPos<l)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){const n=e.assetList[r];n&&this.advanceInPlace(n.timelineStart)}this.setSchedulePosition(t,r)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const r=t.parentIdentifier,n=s.getEvent(r);if(n){const a=s.findEventIndex(r),o=s.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1)}}setSchedulePosition(e,t){var s;const r=(s=this.schedule)==null?void 0:s.items;if(!r||this.playbackDisabled)return;const n=e>=0?r[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&fi(n)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){const u=a.event,c=this.playingAsset,h=c?.identifier,f=h?this.getAssetPlayer(h):null;if(f&&h&&(!this.eventItemsMatch(a,n)||t!==void 0&&h!==u.assetList[t].identifier)){var l;const m=u.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${m+1}/${u.assetList.length} ${gn(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(y.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:m,event:u,schedule:r.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),m);return}this.retreiveMediaSource(h,n),f.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${fi(a)}`),u.hasPlayed=!0,this.hls.trigger(y.INTERSTITIAL_ENDED,{event:u,schedule:r.slice(0),scheduleIndex:e}),u.cue.once)){var d;this.updateSchedule();const m=(d=this.schedule)==null?void 0:d.items;if(n&&m){const p=this.findItemIndex(n);this.advanceSchedule(p,m,t,a,o)}return}}this.advanceSchedule(e,r,t,a,o)}advanceSchedule(e,t,s,r,n){const a=this.schedule;if(!a)return;const o=t[e]||null,l=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(u=>{const c=u.interstitial,h=a.findEventIndex(c.identifier);(h<e||h>e+1)&&this.clearInterstitial(c,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const u=o.event;if(s===void 0){s=a.findAssetIndex(u,this.timelinePos);const m=wc(u,s-1);if(u.isAssetPastPlayoutLimit(m)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,e,s);return}s=m}const c=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let h=this.preloadAssets(u,s);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${fi(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(y.INTERSTITIAL_STARTED,{event:u,schedule:t.slice(0),scheduleIndex:e})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const f=u.assetList[s];if(!f){this.advanceAfterAssetEnded(u,e,s||0);return}if(h||(h=this.getAssetPlayer(f.identifier)),h===null||h.destroyed){const m=u.assetList.length;this.warn(`asset ${s+1}/${m} player destroyed ${u}`),h=this.createAssetPlayer(u,f,s),h.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(h,s,t,e,l),this.shouldPlay&&R0(h.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&R0(this.hls.media)):n&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,s){var r,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${fi(e)}`),!((r=this.detachedData)!=null&&r.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(tl("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!s)return;const a=(n=this.schedule)==null?void 0:n.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${fi(e)}`),this.hls.trigger(y.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const r=this.primaryDetails;if(t===0)return this.hls.startPosition;if(r&&(s<r.fragmentStart||s>r.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:ue.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 r=this.primaryMedia;if(!r)return;const n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,r),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(tl("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const r=this.hls;!r.loadingEnabled||!r.media||Math.abs((((s=r.mainForwardBufferInfo)==null?void 0:s.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(y.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(y.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const r=Ce(Ce({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=Ce(Ce({},this.altSelection),{},{audio:s});return}const n=Ce(Ce({},r),{},{audio:s});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=Ce(Ce({},this.altSelection),{},{subtitles:s});return}const n=Ce(Ce({},r),{},{subtitles:s});this.mediaSelection=n}onAudioTrackSwitching(e,t){const s=Ug(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setAudioOption(t)||r.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Ug(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setSubtitleOption(t)||t.id!==-1&&r.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 r=this.timelinePos;this.bufferedPos=r,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let r=0;r<t.length;r++){const n=t[r];if(n.cue.post){var s;const a=this.schedule.findEventIndex(n.identifier),o=(s=this.schedule.items)==null?void 0:s[a];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const r=(s=this.schedule)==null?void 0:s.items;if(e&&r){const n=this.findItemIndex(e,t);return r[n]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((n,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(n.identifier,null)});const s=e.end+.25,r=ue.bufferInfo(this.primaryMedia,s,0);(r.end>s||(r.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${fi(e)} (was ${fi(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s)return;const r=ue.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,s,e)}updateBufferedPos(e,t,s){const r=this.schedule,n=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}const a=this.playingItem,o=this.findItemIndex(a);let l=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var d;const u=this.findItemIndex(n),c=Math.min(u+1,t.length-1),h=t[c];if((l===-1&&n&&e>=n.end||(d=h.event)!=null&&d.appendInPlace&&e+.01>=h.start)&&(l=c),this.isInterstitial(n)){const f=n.event;if(c-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>u&&l>o)this.bufferedToItem(h);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&h.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0)}}else s&&a&&!this.itemsMatch(a,n)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(r=>{const n=this.getAssetPlayer(r.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:r,events:n}=s;if(!r||!n)return t;const a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${fi(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const d=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((u,c)=>{const h=this.getAssetPlayer(u.identifier);h&&(c===d&&h.loadSource(),h.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(y.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;const r=this.detachedData;r?r.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,r=s.assetList.length===0&&!s.assetListLoader,n=s.cue.once;if(r||!n){const a=this.preloadAssets(s,t);if(a!=null&&a.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){const s=e.assetUrl,r=e.assetList.length,n=r===0&&!e.assetListLoader,a=e.cue.once;if(n){const l=e.timelineStart;if(e.appendInPlace){var o;const h=this.playingItem;!this.isInterstitial(h)&&(h==null||(o=h.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let d,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 h=u-l;h>0&&(d=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:r} ${e}${d?` live-start: ${u} start-offset: ${d}`:""}`),s)return this.createAsset(e,0,0,l,e.duration,s);const c=this.assetListLoader.loadAssetList(e,d);c&&(e.assetListLoader=c)}else if(!a&&r){for(let d=t;d<r;d++){const u=e.assetList[d],c=this.getAssetPlayerQueueIndex(u.identifier);(c===-1||this.playerQueue[c].destroyed)&&!u.error&&this.createAssetPlayer(e,u,d)}const l=e.assetList[t];if(l){const d=this.getAssetPlayer(l.identifier);return d&&d.loadSource(),d}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(r=>{this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})})}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,r,n,a){const o={parentIdentifier:e.identifier,identifier:NC(e,a,t),duration:n,startOffset:s,timelineStart:r,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){const r=this.hls,n=r.userConfig;let a=n.videoPreference;const o=r.loadLevelObj||r.levels[r.currentLevel];(a||o)&&(a=Oe({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));const l=r.audioTracks[r.audioTrack],d=r.subtitleTracks[r.subtitleTrack];let u=0;if(this.primaryLive||e.appendInPlace){const T=this.timelinePos-t.timelineStart;if(T>1){const A=t.duration;A&&T<A&&(u=T)}}const c=t.identifier,h=Ce(Ce({},n),{},{maxMaxBufferLength:Math.min(180,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:l||n.audioPreference,subtitlePreference:d||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(h.timelineOffset=t.timelineStart));const f=h.cmcd;f!=null&&f.sessionId&&f.contentId&&(h.cmcd=Oe({},f,{contentId:Xa(t.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${e} and asset ${c}`);const m=new FC(this.HlsPlayerClass,h,e,t);this.playerQueue.push(m),e.assetList[s]=t;let p=!0;const g=T=>{if(T.live){var A;const L=new Error(`Interstitials MUST be VOD assets ${e}`),R={fatal:!0,type:ie.OTHER_ERROR,details:w.INTERSTITIAL_ASSET_ITEM_ERROR,error:L},I=((A=this.schedule)==null?void 0:A.findEventIndex(e.identifier))||-1;this.handleAssetItemError(R,e,I,s,L.message);return}const x=T.edge-T.fragmentStart,S=t.duration;(p||S===null||x>S)&&(p=!1,this.log(`Interstitial asset "${c}" duration change ${S} > ${x}`),t.duration=x,this.updateSchedule())};m.on(y.LEVEL_UPDATED,(T,{details:A})=>g(A)),m.on(y.LEVEL_PTS_UPDATED,(T,{details:A})=>g(A)),m.on(y.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const v=(T,A)=>{const x=this.getAssetPlayer(c);if(x&&A.tracks){x.off(y.BUFFER_CODECS,v),x.tracks=A.tracks;const S=this.primaryMedia;this.bufferingAsset===x.assetItem&&S&&!x.media&&this.bufferAssetPlayer(x,S)}};m.on(y.BUFFER_CODECS,v);const b=()=>{var T;const A=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${A}`),!A||!this.schedule)return;const x=this.schedule.findEventIndex(e.identifier),S=(T=this.schedule.items)==null?void 0:T[x];this.isInterstitial(S)&&this.advanceAssetBuffering(S,t)};m.on(y.BUFFERED_TO_END,b);const E=T=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;const x=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,x,T)};return m.once(y.MEDIA_ENDED,E(s)),m.once(y.PLAYOUT_LIMIT_REACHED,E(1/0)),m.on(y.ERROR,(T,A)=>{if(!this.schedule)return;const x=this.getAssetPlayer(c);if(A.details===w.BUFFER_STALLED_ERROR){if(x!=null&&x.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(A,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${A.error} ${e}`)}),m.on(y.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;const A=new Error(`Asset player destroyed unexpectedly ${c}`),x={fatal:!0,type:ie.OTHER_ERROR,details:w.INTERSTITIAL_ASSET_ITEM_ERROR,error:A};this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),s,A.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${gn(t)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:m}),m}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){const r=this.playerQueue[s];this.log(`clear ${r} toSegment: ${t&&fi(t)}`),this.transferMediaFromPlayer(r,t),this.playerQueue.splice(s,1),r.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,r,n){const{interstitial:a,assetItem:o,assetId:l}=e,d=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!u||u.identifier!==l)&&(u&&(this.clearAssetPlayer(u.identifier,s[r]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${gn(o)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:s.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var s,r;if(!this.schedule)return;const{interstitial:n,assetItem:a}=e,o=this.schedule.findEventIndex(n.identifier),l=(s=this.schedule.items)==null?void 0:s[o];if(!l)return;e.loadSource(),this.setBufferingItem(l),this.bufferingAsset=a;const d=this.getBufferingPlayer();if(d===e)return;const u=n.appendInPlace;if(u&&d?.interstitial.appendInPlace===!1)return;const c=d?.tracks||((r=this.detachedData)==null?void 0:r.tracks)||this.requiredTracks;if(u&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(c&&!Sy(c,e.tracks)){const h=new Error(`Asset ${gn(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),f={fatal:!0,type:ie.OTHER_ERROR,details:w.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},m=n.findAssetIndex(a);this.handleAssetItemError(f,n,o,m,h.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const r=s.currentTime,n=t.findAssetIndex(e,r),a=e.assetList[n];if(a){const o=this.getAssetPlayer(a.identifier);if(o){const l=o.currentTime||r-a.timelineStart,d=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+d} in ${o} ${e} (media.currentTime: ${r})`),l&&(d/s.playbackRate<.5||o.bufferedInPlaceToEnd(s))&&o.hls){const u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,n)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,r,n){if(e.details===w.BUFFER_STALLED_ERROR)return;const a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&gn(a)} ${e.error}`),!this.schedule)return;const o=a?.identifier||"",l=this.getAssetPlayerQueueIndex(o),d=this.playerQueue[l]||null,u=this.schedule.items,c=Oe({},e,{fatal:!1,errorAction:Nn(!0),asset:a,assetListIndex:r,event:t,schedule:u,scheduleIndex:s,player:d});if(this.hls.trigger(y.INTERSTITIAL_ASSET_ERROR,c),!e.fatal)return;const h=this.playingAsset,f=this.bufferingAsset,m=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=m),!t.assetList.some(p=>!p.error))t.error=m;else for(let p=r;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):h&&h.identifier===o?this.advanceAfterAssetEnded(t,s,r):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;let r=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${r} playing: ${fi(s)} error: ${e.error}`),r===-1&&(r=this.hls.startPosition);const a=this.updateItem(s,r);this.itemsMatch(s,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(r===-1){this.checkStart();return}if(!this.schedule)return;const n=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(n)}onAssetListLoaded(e,t){var s,r;const n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(a)))return;const l=n.timelineStart,d=n.duration;let u=0;o.forEach((p,g)=>{const v=parseFloat(p.DURATION);this.createAsset(n,g,u,l+u,v,p.URI),u+=v}),n.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${d}) ${n}`);const c=this.waitingItem,h=c?.event.identifier===a;this.updateSchedule();const f=(r=this.bufferingItem)==null?void 0:r.event;if(h){var m;const p=this.schedule.findEventIndex(a),g=(m=this.schedule.items)==null?void 0:m[p];if(g){if(!this.playingItem&&this.timelinePos>g.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){n.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${n}`),this.log(n.error.message),this.updateSchedule(!0),this.primaryFallback(n);return}this.setBufferingItem(g)}this.setSchedulePosition(p)}else if(f?.identifier===a){const p=n.assetList[0];if(p){const g=this.getAssetPlayer(p.identifier);if(f.appendInPlace){const v=this.primaryMedia;g&&v&&this.bufferAssetPlayer(g,v)}else g&&g.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case w.ASSET_LIST_PARSING_ERROR:case w.ASSET_LIST_LOAD_ERROR:case w.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case w.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const k0=500;class KC extends Bm{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",J.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(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(y.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(y.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=O.IDLE,this.setInterval(k0),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:r}=t;if(this.fragContextChanged(s)||(et(s)&&(this.fragPrevious=s),this.state=O.IDLE),!r)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a;const o=s.start;for(let d=0;d<n.length;d++)if(o>=n[d].start&&o<=n[d].end){a=n[d];break}const l=s.start+s.duration;a?a.end=l:(a={start:o,end:l},n.push(a)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:r}=t;if(s===0&&r!==Number.POSITIVE_INFINITY){const n=r-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=n){a.shift();continue}else if(a[o].start<n)a[o].start=n;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,n,J.SUBTITLE)}}onError(e,t){const s=t.frag;s?.type===J.SUBTITLE&&(t.details===w.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==O.STOPPED&&(this.state=O.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Lb(this.levels,t)){this.levels=t.map(s=>new go(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const r=new go(s);return this.tracksBuffered[r.id]=[],r}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,J.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const r=this.levels[this.currentTrackId];r!=null&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==O.STOPPED&&this.setInterval(k0)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:r,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=n[o];if(o>=n.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(a.live||(s=l.details)!=null&&s.live){if(a.deltaUpdateFailed)return;const c=this.mainDetails;if(!c){this.startFragRequested=!1;return}const h=c.fragments[0];if(!l.details)a.hasProgramDateTime&&c.hasProgramDateTime?(iu(a,c),d=a.fragmentStart):h&&(d=h.start,Vh(a,d));else{var u;d=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details),d===0&&h&&(d=h.start,Vh(a,d))}c&&!this.startFragRequested&&this.setStartPosition(c,d)}l.details=a,this.levelLastLoaded=l,o===r&&(this.hls.trigger(y.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===O.IDLE&&(Mr(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,r=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&r!=null&&r.key&&r.iv&&Un(r.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(s),r.key.buffer,r.iv.buffer,$m(r.method)).catch(o=>{throw n.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const l=performance.now();n.trigger(y.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=O.IDLE})}}doTick(){if(!this.media){this.state=O.IDLE;return}if(this.state===O.IDLE){const{currentTrackId:e,levels:t}=this,s=t?.[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:r}=this,n=this.getLoadPosition(),a=ue.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,r.maxBufferHole),{end:o,len:l}=a,d=s.details,u=this.hls.maxBufferLength+d.levelTargetDuration;if(l>u)return;const c=d.fragments,h=c.length,f=d.edge;let m=null;const p=this.fragPrevious;if(o<f){const b=r.maxFragLookUpTolerance,E=o>f-b?0:b;m=Mr(p,c,Math.max(c[0].start,o),E),!m&&p&&p.start<c[0].start&&(m=c[0])}else m=c[h-1];if(m=this.filterReplacedPrimary(m,s.details),!m)return;const g=m.sn-d.startSN,v=c[g-1];if(v&&v.cc===m.cc&&this.fragmentTracker.getState(v)===gt.NOT_LOADED&&(m=v),this.fragmentTracker.getState(m)===gt.NOT_LOADED){const b=this.mapToInitFragWhenRequired(m);b&&this.loadFragment(b,s,o)}}}loadFragment(e,t,s){et(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new VC(this.tracksBuffered[this.currentTrackId]||[])}}class VC{constructor(e){this.buffered=void 0;const t=(s,r,n)=>{if(r=r>>>0,r>n-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][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 WC={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},Kb=i=>String.fromCharCode(WC[i]||i),yi=15,ls=100,qC={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},YC={17:2,18:4,21:6,22:8,23:10,19:13,20:15},jC={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},zC={25:2,26:4,29:6,30:8,31:10,27:13,28:15},QC=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class XC{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;we.log(`${this.time} [${e}] ${s}`)}}}const sr=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class Vb{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 r=t[s];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class ZC{constructor(){this.uchar=" ",this.penState=new Vb}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 JC{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Vb,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<ls;t++)this.chars.push(new ZC);this.logger=e}equals(e){for(let t=0;t<ls;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<ls;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<ls;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>ls&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ls)}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=Kb(e);if(this.pos>=ls){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<ls;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<ls;s++){const r=this.chars[s].uchar;r!==" "&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class Mc{constructor(e){this.rows=[],this.currRow=yi-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<yi;t++)this.rows.push(new JC(e));this.logger=e}reset(){for(let e=0;e<yi;e++)this.rows[e].clear();this.currRow=yi-1}equals(e){let t=!0;for(let s=0;s<yi;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<yi;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<yi;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 = "+$e(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<yi;o++)this.rows[o].clear();const n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[n].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let d=0;d<this.nrRollUpRows;d++)this.rows[t-this.nrRollUpRows+d+1].copy(a.rows[n+d])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const n=e.indent,a=Math.max(n-1,0);s.setCursor(e.indent),e.color=s.chars[a].penState.foreground}const r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+$e(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="",r=-1;for(let n=0;n<yi;n++){const a=this.rows[n].getTextString();a&&(r=n+1,e?t.push("Row "+r+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
|
|
1443
|
+
transfer tracks: ${$e(r,(l,d)=>l==="initSegment"?void 0:d)}}`),!Sy(r,s)){t.mediaSource=null,t.tracks=void 0;const l=e.currentTime,d=this.details,u=Math.max(l,d?.fragments[0].start||0);if(u-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(s)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(y.MEDIA_DETACHING,{}),this.onMediaAttaching(y.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,n.forEach(l=>{const d=l,u=r[d];if(u){const c=u.buffer;if(c){const h=this.fragmentTracker,f=u.id;if(h.hasFragments(f)||h.hasParts(f)){const g=ue.getBuffered(c);h.detectEvictedFragments(d,g,f,null,!0)}const m=Dc(d),p=[d,c];this.sourceBuffers[m]=p,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,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:r,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=n.readyState==="open";try{const l=n.sourceBuffers;for(let d=l.length;d--;)o&&l[d].abort(),n.removeSourceBuffer(l[d]);o&&n.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(r.removeEventListener("emptied",this._onMediaEmptied),s||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(r.removeAttribute("src"),this.appendSource&&T0(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(y.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 r;(r=this.mediaSource)!=null&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Dc(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new RD(this.tracks)}onBufferCodecs(e,t){var s;const r=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some(l=>!r[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(r)}" and "${n}" SourceBuffers`);return}n.forEach(l=>{var d,u;const c=t[l],{id:h,codec:f,levelCodec:m,container:p,metadata:g,supplemental:v}=c;let b=r[l];const E=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[l],T=E!=null&&E.buffer?E:b,A=T?.pendingCodec||T?.codec,x=T?.levelCodec;b||(b=r[l]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:p,levelCodec:m,metadata:g,id:h});const S=Hl(A,x),L=S?.replace(b0,"$1");let R=Hl(f,m);const I=(u=R)==null?void 0:u.replace(b0,"$1");R&&S&&L!==I&&(l.slice(0,5)==="audio"&&(R=zd(R,this.appendSource)),this.log(`switching codec ${A} to ${R}`),R!==(b.pendingCodec||b.codec)&&(b.pendingCodec=R),b.container=p,this.appendChangeType(l,p,R))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const r=`${t};codecs=${s}`,n={label:`change-type=${r}`,execute:()=>{const a=this.tracks[e];if(a){const o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),o.changeType(r),a.codec=s,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(n,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,r=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,J.MAIN))==null?void 0:t.gap)===!0)return;const a={label:"block-audio",execute:()=>{var o;const l=this.tracks.video;(this.lastVideoAppendEnd>r||l!=null&&l.buffer&&ue.isBuffered(l.buffer,r)||((o=this.fragmentTracker.getAppendedFrag(r,J.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:r,type:n,parent:a,frag:o,part:l,chunkMeta:d,offset:u}=t,c=d.buffering[n],{sn:h,cc:f}=o,m=self.performance.now();c.start=m;const p=o.stats.buffering,g=l?l.stats.buffering:null;p.start===0&&(p.start=m),g&&g.start===0&&(g.start=m);const v=s.audio;let b=!1;n==="audio"&&v?.container==="audio/mpeg"&&(b=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const E=s.video,T=E?.buffer;if(T&&h!=="initSegment"){const S=l||o,L=this.blockedAudioAppend;if(n==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(E.ending||E.ended)){const I=S.start+S.duration*.05,M=T.buffered,B=this.currentOp("video");!M.length&&!B?this.blockAudio(S):!B&&!ue.isBuffered(T,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(S)}else if(n==="video"){const R=S.end;if(L){const I=L.frag.start;(R>I||R<this.lastVideoAppendEnd||ue.isBuffered(T,I))&&this.unblockAudio()}this.lastVideoAppendEnd=R}}const A=(l||o).start,x={label:`append-${n}`,execute:()=>{var S;c.executeStart=self.performance.now();const L=(S=this.tracks[n])==null?void 0:S.buffer;L&&(b?this.updateTimestampOffset(L,A,.1,n,h,f):u!==void 0&&X(u)&&this.updateTimestampOffset(L,u,1e-6,n,h,f)),this.appendExecutor(r,n)},onStart:()=>{},onComplete:()=>{const S=self.performance.now();c.executeEnd=c.end=S,p.first===0&&(p.first=S),g&&g.first===0&&(g.first=S);const L={};this.sourceBuffers.forEach(([R,I])=>{R&&(L[R]=ue.getBuffered(I))}),this.appendErrors[n]=0,n==="audio"||n==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(y.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:d,parent:o.type,timeRanges:L})},onError:S=>{var L;const R={type:ie.MEDIA_ERROR,parent:o.type,details:w.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:d,error:S,err:S,fatal:!1},I=(L=this.media)==null?void 0:L.error;if(S.code===DOMException.QUOTA_EXCEEDED_ERR||S.name=="QuotaExceededError"||"quota"in S)R.details=w.BUFFER_FULL_ERROR;else if(S.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!I)R.errorAction=Nn(!0);else if(S.name===Rb&&this.sourceBufferCount===0)R.errorAction=Nn(!0);else{const M=++this.appendErrors[n];this.warn(`Failed ${M}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${I||"no media error"})`),(M>=this.hls.config.appendErrorMaxRetry||I)&&(R.fatal=!0)}this.hls.trigger(y.ERROR,R)}};this.log(`queuing "${n}" append sn: ${h}${l?" p: "+l.index:""} of ${o.type===J.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(x,n,this.isPending(this.tracks[n]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(y.BUFFER_FLUSHED,{type:e})},onError:r=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,r)}}}onBufferFlushing(e,t){const{type:s,startOffset:r,endOffset:n}=t;s?this.append(this.getFlushOp(s,r,n),s):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,r,n),a)})}onFragParsed(e,t){const{frag:s,part:r}=t,n=[],a=r?r.elementaryStreams:s.elementaryStreams;a[Ue.AUDIOVIDEO]?n.push("audiovideo"):(a[Ue.AUDIO]&&n.push("audio"),a[Ue.VIDEO]&&n.push("video"));const o=()=>{const l=self.performance.now();s.stats.buffering.end=l,r&&(r.stats.buffering.end=l);const d=r?r.stats:s.stats;this.hls.trigger(y.FRAG_BUFFERED,{frag:s,part:r,stats:d,id:s.type})};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,n).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([a])=>{if(a){const o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});const r=((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)})?r?(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(y.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(y.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===w.BUFFER_APPEND_ERROR&&t.frag){var s;const r=(s=t.errorAction)==null?void 0:s.nextAutoLevel;X(r)&&r!==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 r=e.config,n=s.currentTime,a=t.levelTargetDuration,o=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(X(o)&&o>=0){const d=Math.max(o,a),u=Math.floor(n/a)*a-d;this.flushBackBuffer(n,a,u)}const l=r.frontBufferFlushThreshold;if(X(l)&&l>0){const d=Math.max(r.maxBufferLength,l),u=Math.max(d,a),c=Math.floor(n/a)*a+u;this.flushFrontBuffer(n,a,c)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([r,n])=>{if(n){const o=ue.getBuffered(n);if(o.length>0&&s>o.start(0)){var a;this.hls.trigger(y.BACK_BUFFER_REACHED,{bufferEnd:s});const l=this.tracks[r];if((a=this.details)!=null&&a.live)this.hls.trigger(y.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(l!=null&&l.ended){this.log(`Cannot flush ${r} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:r})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([r,n])=>{if(n){const a=ue.getBuffered(n),o=a.length;if(o<2)return;const l=a.start(o-1),d=a.end(o-1);if(s>l||e>=l&&e<=d)return;this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:r})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||s?.readyState!=="open")return null;const r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const d=Math.max(0,t.fragmentStart),u=Math.max(d,r);return{duration:1/0,start:d,end:u}}return{duration:1/0}}const n=(e=this.overrides)==null?void 0:e.duration;if(n)return X(n)?{duration:n}:null;const a=this.media.duration,o=X(s.duration)?s.duration:0;return r>o&&r>a||!X(a)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:s}){const r=this.mediaSource;!this.media||!r||r.readyState!=="open"||(r.duration!==e&&(X(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${s}.`),r.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}) ${$e(s)}`),this.tracksReady){var r;const n=(r=this.transferData)==null?void 0:r.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const r=this.tracks[t];e[t]={buffer:s,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(y.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(y.ERROR,{type:ie.MEDIA_ERROR,details:w.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in e){const a=n,o=e[a];if(this.isPending(o)){const l=this.getTrackCodec(o,a),d=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${d})${this.currentOp(a)?" Queued":""} ${$e(o)}`);try{const u=s.addSourceBuffer(d),c=Dc(a),h=[a,u];t[c]=h,o.buffer=u}catch(u){var r;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(a),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[a],this.hls.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:a,mimeType:d,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let r=e.codec;s&&(t==="video"||t==="audiovideo")&&mo(s,"video")&&(r=bR(r,s));const n=Hl(r,e.levelCodec);return n?t.slice(0,5)==="audio"?zd(n,this.appendSource):n:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const r=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,a)=>{const o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(y.BUFFER_FLUSHED,{type:n})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s?.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${r}`,t),this.hls.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});const n=this.currentOp(e);n&&n.onError(r)}updateTimestampOffset(e,t,s,r,n,a){const o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:r,mediaSource:n}=this,a=this.tracks[e],o=a?.buffer;if(!r||!n||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const l=X(r.duration)?r.duration:1/0,d=X(n.duration)?n.duration:1/0,u=Math.max(0,t),c=Math.min(s,l,d);c>u&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${u},${c}] from the ${e} SourceBuffer`),o.remove(u,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],r=s?.buffer;if(!r)throw new kD(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,r.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,r=t.map(a=>this.appendBlocker(a));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then(a=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const r=(s=this.tracks[t])==null?void 0:s.buffer;!r||r.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 r=this.tracks[e];if(!r)return;const n=r.buffer;if(!n)return;const a=s.bind(this,e);r.listeners.push({event:t,listener:a}),n.addEventListener(t,a)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(r=>{s.removeEventListener(r.event,r.listener)}),t.listeners.length=0)}}function T0(i){const e=i.querySelectorAll("source");[].slice.call(e).forEach(t=>{i.removeChild(t)})}function CD(i,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,i.appendChild(t)}function Dc(i){return i==="audio"?1:0}class zm{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(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.BUFFER_CODECS,this.onBufferCodecs,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.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&&X(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((r,n)=>this.isLevelAllowed(r)&&n<=e);return this.clientRect=null,zm.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 r=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let n=e.length-1;const a=Math.max(t,s);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=a||l.height>=a)&&r(l,e[o+1])){n=o;break}}return n}}const wD={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Mt=wD,MD={HLS:"h"},PD=MD;class ss{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof ss?s:new ss(s))),this.value=e,this.params=t}}const OD="Dict";function ND(i){return Array.isArray(i)?JSON.stringify(i):i instanceof Map?"Map{}":i instanceof Set?"Set{}":typeof i=="object"?JSON.stringify(i):String(i)}function UD(i,e,t,s){return new Error(`failed to ${i} "${ND(e)}" as ${t}`,{cause:s})}function rs(i,e,t){return UD("serialize",i,e,t)}class kb{constructor(e){this.description=e}}const _0="Bare Item",$D="Boolean";function FD(i){if(typeof i!="boolean")throw rs(i,$D);return i?"?1":"?0"}function BD(i){return btoa(String.fromCharCode(...i))}const HD="Byte Sequence";function GD(i){if(ArrayBuffer.isView(i)===!1)throw rs(i,HD);return`:${BD(i)}:`}const KD="Integer";function VD(i){return i<-999999999999999||999999999999999<i}function Db(i){if(VD(i))throw rs(i,KD);return i.toString()}function WD(i){return`@${Db(i.getTime()/1e3)}`}function Cb(i,e){if(i<0)return-Cb(-i,e);const t=Math.pow(10,e);if(Math.abs(i*t%1-.5)<Number.EPSILON){const r=Math.floor(i*t);return(r%2===0?r:r+1)/t}else return Math.round(i*t)/t}const qD="Decimal";function YD(i){const e=Cb(i,3);if(Math.floor(Math.abs(e)).toString().length>12)throw rs(i,qD);const t=e.toString();return t.includes(".")?t:`${t}.0`}const jD="String",zD=/[\x00-\x1f\x7f]+/;function QD(i){if(zD.test(i))throw rs(i,jD);return`"${i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function XD(i){return i.description||i.toString().slice(7,-1)}const ZD="Token";function A0(i){const e=XD(i);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw rs(e,ZD);return e}function jh(i){switch(typeof i){case"number":if(!X(i))throw rs(i,_0);return Number.isInteger(i)?Db(i):YD(i);case"string":return QD(i);case"symbol":return A0(i);case"boolean":return FD(i);case"object":if(i instanceof Date)return WD(i);if(i instanceof Uint8Array)return GD(i);if(i instanceof kb)return A0(i);default:throw rs(i,_0)}}const JD="Key";function zh(i){if(/^[a-z*][a-z0-9\-_.*]*$/.test(i)===!1)throw rs(i,JD);return i}function Qm(i){return i==null?"":Object.entries(i).map(([e,t])=>t===!0?`;${zh(e)}`:`;${zh(e)}=${jh(t)}`).join("")}function wb(i){return i instanceof ss?`${jh(i.value)}${Qm(i.params)}`:jh(i)}function eC(i){return`(${i.value.map(wb).join(" ")})${Qm(i.params)}`}function tC(i,e={whitespace:!0}){if(typeof i!="object"||i==null)throw rs(i,OD);const t=i instanceof Map?i.entries():Object.entries(i),s=e?.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof ss||(n=new ss(n));let a=zh(r);return n.value===!0?a+=Qm(n.params):(a+="=",Array.isArray(n.value)?a+=eC(n):a+=wb(n)),a}).join(`,${s}`)}function Mb(i,e){return tC(i,e)}const Di="CMCD-Object",ze="CMCD-Request",ir="CMCD-Session",ks="CMCD-Status",iC={br:Di,ab:Di,d:Di,ot:Di,tb:Di,tpb:Di,lb:Di,tab:Di,lab:Di,url:Di,pb:ze,bl:ze,tbl:ze,dl:ze,ltc:ze,mtp:ze,nor:ze,nrr:ze,rc:ze,sn:ze,sta:ze,su:ze,ttfb:ze,ttfbb:ze,ttlb:ze,cmsdd:ze,cmsds:ze,smrt:ze,df:ze,cs:ze,ts:ze,cid:ir,pr:ir,sf:ir,sid:ir,st:ir,v:ir,msd:ir,bs:ks,bsd:ks,cdn:ks,rtp:ks,bg:ks,pt:ks,ec:ks,e:ks},sC={REQUEST:ze};function rC(i){return Object.keys(i).reduce((e,t)=>{var s;return(s=i[t])===null||s===void 0||s.forEach(r=>e[r]=t),e},{})}function nC(i,e){const t={};if(!i)return t;const s=Object.keys(i),r=e?rC(e):{};return s.reduce((n,a)=>{var o;const l=iC[a]||r[a]||sC.REQUEST,d=(o=n[l])!==null&&o!==void 0?o:n[l]={};return d[a]=i[a],n},t)}function aC(i){return["ot","sf","st","e","sta"].includes(i)}function oC(i){return typeof i=="number"?X(i):i!=null&&i!==""&&i!==!1}const Pb="event";function lC(i,e){const t=new URL(i),s=new URL(e);if(t.origin!==s.origin)return i;const r=t.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+t.search+t.hash}const ql=i=>Math.round(i),Qh=(i,e)=>Array.isArray(i)?i.map(t=>Qh(t,e)):i instanceof ss&&typeof i.value=="string"?new ss(Qh(i.value,e),i.params):(e.baseUrl&&(i=lC(i,e.baseUrl)),e.version===1?encodeURIComponent(i):i),Jo=i=>ql(i/100)*100,dC=(i,e)=>{let t=i;return e.version>=2&&(i instanceof ss&&typeof i.value=="string"?t=new ss([i]):typeof i=="string"&&(t=[i])),Qh(t,e)},uC={br:ql,d:ql,bl:Jo,dl:Jo,mtp:Jo,nor:dC,rtp:Jo,tb:ql},Ob="request",Nb="response",Xm=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],cC=["e"],hC=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function ju(i){return hC.test(i)}function fC(i){return Xm.includes(i)||cC.includes(i)||ju(i)}const Ub=["d","dl","nor","ot","rtp","su"];function mC(i){return Xm.includes(i)||Ub.includes(i)||ju(i)}const pC=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function gC(i){return Xm.includes(i)||Ub.includes(i)||pC.includes(i)||ju(i)}const vC=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function EC(i){return vC.includes(i)||ju(i)}const yC={[Nb]:gC,[Pb]:fC,[Ob]:mC};function $b(i,e={}){const t={};if(i==null||typeof i!="object")return t;const s=e.version||i.v||1,r=e.reportingMode||Ob,n=s===1?EC:yC[r];let a=Object.keys(i).filter(n);const o=e.filter;typeof o=="function"&&(a=a.filter(o));const l=r===Nb||r===Pb;l&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");const d=Oe({},uC,e.formatters),u={version:s,reportingMode:r,baseUrl:e.baseUrl};return a.sort().forEach(c=>{let h=i[c];const f=d[c];if(typeof f=="function"&&(h=f(h,u)),c==="v"){if(s===1)return;h=s}c=="pr"&&h===1||(l&&c==="ts"&&!X(h)&&(h=Date.now()),oC(h)&&(aC(c)&&typeof h=="string"&&(h=new kb(h)),t[c]=h))}),t}function bC(i,e={}){const t={};if(!i)return t;const s=$b(i,e),r=nC(s,e?.customHeaderMap);return Object.entries(r).reduce((n,[a,o])=>{const l=Mb(o,{whitespace:!1});return l&&(n[a]=l),n},t)}function TC(i,e,t){return Oe(i,bC(e,t))}const _C="CMCD";function AC(i,e={}){return i?Mb($b(i,e),{whitespace:!1}):""}function SC(i,e={}){if(!i)return"";const t=AC(i,e);return encodeURIComponent(t)}function IC(i,e={}){if(!i)return"";const t=SC(i,e);return`${_C}=${t}`}const S0=/CMCD=[^&#]+/;function xC(i,e,t){const s=IC(e,t);if(!s)return i;if(S0.test(i))return i.replace(S0,s);const r=i.includes("?")?"&":"?";return`${i}${r}${s}`}class LC{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=r=>{try{this.apply(r,{ot:Mt.MANIFEST,su:!this.initialized})}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=r=>{try{const{frag:n,part:a}=r,o=this.hls.levels[n.level],l=this.getObjectType(n),d={d:(a||n).duration*1e3,ot:l};(l===Mt.VIDEO||l===Mt.AUDIO||l==Mt.MUXED)&&(d.br=o.bitrate/1e3,d.tb=this.getTopBandwidth(l)/1e3,d.bl=this.getBufferLength(l));const u=a?this.getNextPart(a):this.getNextFrag(n);u!=null&&u.url&&u.url!==n.url&&(d.nor=u.url),this.apply(r,d)}catch(n){this.hls.logger.warn("Could not generate segment CMCD data.",n)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHED,this.onMediaDetached,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHED,this.onMediaDetached,this),e.off(y.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,r;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(r=t.tracks.video)==null?void 0:r.buffer}createData(){var e;return{v:1,sf:PD.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Oe(t,this.createData());const s=t.ot===Mt.INIT||t.ot===Mt.VIDEO||t.ot===Mt.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((a,o)=>(r.includes(o)&&(a[o]=t[o]),a),{}));const n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),TC(e.headers,t,n)):e.url=xC(e.url,t,n)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const r=e.sn-s.startSN;return s.fragments[r+1]}}getNextPart(e){var t;const{index:s,fragment:r}=e,n=(t=this.hls.levels[r.level])==null||(t=t.details)==null?void 0:t.partList;if(n){const{sn:a}=r;for(let o=n.length-1;o>=0;o--){const l=n[o];if(l.index===s&&l.fragment.sn===a)return n[o+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Mt.TIMED_TEXT;if(e.sn==="initSegment")return Mt.INIT;if(t==="audio")return Mt.AUDIO;if(t==="main")return this.hls.audioTracks.length?Mt.VIDEO:Mt.MUXED}getTopBandwidth(e){let t=0,s;const r=this.hls;if(e===Mt.AUDIO)s=r.audioTracks;else{const n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;s=r.levels.slice(0,a)}return s.forEach(n=>{n.bitrate>t&&(t=n.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===Mt.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:ue.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new s(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new s(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}}const RC=3e5;class kC extends di{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(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(s=>s!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if(s?.action===St.SendAlternateToPenaltyBox&&s.flags===Wt.MoveAllAlternatesMatchingHost){const r=this.levels;let n=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:d}=t.context;o&&r?a=this.getPathwayForGroupId(o,d,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&r&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),s.resolved=this.pathwayId!==a),t.details===w.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${r&&r.length} priorities: ${$e(n)} penalized: ${$e(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,r=performance.now();Object.keys(s).forEach(n=>{r-s[n]>RC&&delete s[n]});for(let n=0;n<e.length;n++){const a=e[n];if(a in s)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,rb(t),this.hls.trigger(y.LEVELS_UPDATED,{levels:t});const d=this.hls.levels[o];l&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const r=this.getLevelsForPathway(s).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===ge.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===ge.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},r={};e.forEach(n=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(u=>u.pathwayId===a))return;const d=this.getLevelsForPathway(o).map(u=>{const c=new Ye(u.attrs);c["PATHWAY-ID"]=a;const h=c.AUDIO&&`${c.AUDIO}_clone_${a}`,f=c.SUBTITLES&&`${c.SUBTITLES}_clone_${a}`;h&&(s[c.AUDIO]=h,c.AUDIO=h),f&&(r[c.SUBTITLES]=f,c.SUBTITLES=f);const m=Fb(u.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),p=new go({attrs:c,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:m,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let g=1;g<u.audioGroups.length;g++)p.addGroupId("audio",`${u.audioGroups[g]}_clone_${a}`);if(u.subtitleGroups)for(let g=1;g<u.subtitleGroups.length;g++)p.addGroupId("text",`${u.subtitleGroups[g]}_clone_${a}`);return p});t.push(...d),I0(this.audioTracks,s,l,a),I0(this.subtitleTracks,r,l,a)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+u)}const n={responseType:"json",url:r.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},d={onSuccess:(u,c,h,f)=>{this.log(`Loaded steering manifest: "${r}"`);const m=u.data;if(m?.VERSION!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":g,"PATHWAY-PRIORITY":v}=m;if(p)try{this.uri=new self.URL(p,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||h.url),g&&this.clonePathways(g);const b={steeringManifest:m,url:r.toString()};this.hls.trigger(y.STEERING_MANIFEST_LOADED,b),v&&this.updatePathwayPriority(v)},onError:(u,c,h,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${c.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let m=this.timeToLoad*1e3;if(u.code===429){const p=this.loader;if(typeof p?.getResponseHeader=="function"){const g=p.getResponseHeader("Retry-After");g&&(m=parseFloat(g)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,m)},onTimeout:(u,c,h)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,l,d)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const r=(s=this.hls)==null?void 0:s.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function I0(i,e,t,s){i&&Object.keys(e).forEach(r=>{const n=i.filter(a=>a.groupId===r).map(a=>{const o=Oe({},a);return o.details=void 0,o.attrs=new Ye(o.attrs),o.url=o.attrs.URI=Fb(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=s,o});i.push(...n)})}function Fb(i,e,t,s){const{HOST:r,PARAMS:n,[t]:a}=s;let o;e&&(o=a?.[e],o&&(i=o));const l=new self.URL(i);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(d=>{d&&l.searchParams.set(d,n[d])}),l.href}class $n extends di{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=$n.CDMCleanupPromise?[$n.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:s,initData:r}=t,n=`"${t.type}" event: init data type: "${s}"`;if(this.debug(n),r!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=ka(this.config));const o=a.map(_c).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=Kl(a);if(s!=="sinf"||o!==je.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let l;try{const f=mt(new Uint8Array(r)),m=Fm(JSON.parse(f).sinf),p=My(m);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(p.subarray(8,24))}catch(f){this.warn(`${n} Failed to parse sinf: ${f}`);return}const d=It(l),{keyIdToKeySessionPromise:u,mediaKeySessions:c}=this;let h=u[d];for(let f=0;f<c.length;f++){const m=c[f],p=m.decryptdata;if(!p.keyId)continue;const g=It(p.keyId);if(eu(l,p.keyId)||p.uri.replace(/-/g,"").indexOf(d)!==-1){if(h=u[g],!h)continue;if(p.pssh)break;delete u[g],p.pssh=new Uint8Array(r),p.keyId=l,h=u[d]=h.then(()=>this.generateRequestWithPreferredKeySession(m,s,r,"encrypted-event-key-match")),h.catch(v=>this.handleError(v));break}}h||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${c.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(y.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(y.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(y.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(y.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,r=t?.[e];if(r)return r.licenseUrl;if(e===je.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,l)=>!!a&&l.indexOf(a)===o,r=t.map(a=>a.audioCodec).filter(s),n=t.map(a=>a.videoCodec).filter(s);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{const l=d=>{const u=d.shift();this.getMediaKeysPromise(u,r,n).then(c=>a({keySystem:u,mediaKeys:c})).catch(c=>{d.length?l(d):c instanceof Vt?o(c):o(new Vt({type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_ACCESS,error:c,fatal:!0},c.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${s}`;return Qy===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return s(e,t)}getMediaKeysPromise(e,t,s){var r;const n=dk(e,t,s,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],o=(r=a)==null?void 0:r.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${$e(n)}`),o=this.requestMediaKeySystemAccess(e,n);const l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${e}": ${d}`)}),o.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);const u=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const c=l.mediaKeys=d.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,u.then(f=>f?this.setMediaKeysServerCertificate(h,e,f):h)));return c.catch(h=>{this.error(`Failed to create media-keys for "${e}"}: ${h}`)}),c})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${It(e.keyId||[])} keyUri: ${e.uri}`);const r=s.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),r=el(t),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(s,n,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${It(e.decryptdata.keyId||[])}
|
|
1444
|
+
} (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>_c(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:r})=>{const n=_c(r);n?t(n):s(new Error(`Unable to find format for key-system "${r}"`))}).catch(s)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=ka(this.config),s=e.map(Kl).filter(r=>!!r&&t.indexOf(r)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const r=DC(e,t[s]);if(r)return r}}loadKey(e){const t=e.keyInfo.decryptdata,s=el(t),r=this.bannedKeyIds[s];if(r||this.getKeyStatus(t)==="internal-error"){const o=x0(r||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}const n=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);const a=this.keyIdToKeySessionPromise[s];if(!a){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:l,mediaKeys:d})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(l,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:l,mediaKeys:d,decryptdata:t}))))).then(l=>{const d="cenc",u=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(l,d,u,"playlist-key")});return o.catch(l=>this.handleError(l,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return a.catch(o=>{if(o instanceof Vt){const l=Ce({},o.data);this.getKeyStatus(t)==="internal-error"&&(l.decryptdata=t);const d=new Vt(l,o.message);this.handleError(d,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Vt){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${It(s.keyId||[])})`:""}`),this.hls.trigger(y.ERROR,e.data)}else this.error(e.message),this.hls.trigger(y.ERROR,{type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=el(e),s=this.keyIdToKeySessionPromise[t];if(!s){const r=Kl(e.keyFormat),n=r?[r]:ka(this.config);return this.attemptKeySystemAccess(n)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=ka(this.config)),e.length===0)throw new Vt({type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${$e({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const r=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((n,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(n).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>s.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,s,r){var n;const a=(n=this.config.drmSystems)==null||(n=n[e.keySystem])==null?void 0:n.generateRequest;if(a)try{const m=a.call(this.hls,t,s,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,s=m.initData?m.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(m){if(this.warn(m.message),this.hls&&this.hls.config.debug)throw m}if(s===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);const o=el(e.decryptdata),l=e.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${o} URI: ${l} (init data type: ${t} length: ${s.byteLength})`);const d=new Hm,u=e._onmessage=m=>{const p=e.mediaKeysSession;if(!p){d.emit("error",new Error("invalid state"));return}const{messageType:g,message:v}=m;this.log(`"${g}" message event for session "${p.sessionId}" message size: ${v.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,v).catch(b=>{d.eventNames().length?d.emit("error",b):this.handleError(b)}):g==="license-release"?e.keySystem===je.FAIRPLAY&&this.updateKeySession(e,Gh("acknowledged")).then(()=>this.removeSession(e)).catch(b=>this.handleError(b)):this.warn(`unhandled media key message type "${g}"`)},c=(m,p)=>{p.keyStatus=m;let g;m.startsWith("usable")?d.emit("resolved"):m==="internal-error"||m==="output-restricted"||m==="output-downscaled"?g=x0(m,p.decryptdata):m==="expired"?g=new Error(`key expired (keyId: ${o})`):m==="released"?g=new Error("key released"):m==="status-pending"||this.warn(`unhandled key status change "${m}" (keyId: ${o})`),g&&(d.eventNames().length?d.emit("error",g):this.handleError(g))},h=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const g=this.getKeyStatuses(e);if(!Object.keys(g).some(T=>g[T]!=="status-pending"))return;if(g[o]==="expired"){this.log(`Expired key ${$e(g)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let b=g[o];if(b)c(b,e);else{var E;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(E=e.keyStatusTimeouts)[o]||(E[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const A=this.getKeyStatus(e.decryptdata);if(A&&A!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${A} from other session.`),c(A,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),b="internal-error",c(b,e)},1e3)),this.log(`No status for keyId ${o} (${$e(g)}).`)}};wt(e.mediaKeysSession,"message",u),wt(e.mediaKeysSession,"keystatuseschange",h);const f=new Promise((m,p)=>{d.on("error",p),d.on("resolved",m)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${l}`)}).catch(m=>{throw new Vt({type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_SESSION,error:m,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>(d.removeAllListeners(),this.removeSession(e).then(()=>{throw m}))).then(()=>(d.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,r)=>{if(typeof r=="string"&&typeof s=="object"){const o=r;r=s,s=o}const n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(e.keySystem===je.PLAYREADY&&n.length===16){const o=It(n);t[o]=s,jy(n)}const a=It(n);s==="internal-error"&&(this.bannedKeyIds[a]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=s}),t}fetchServerCertificate(e){const t=this.config,s=t.loader,r=new s(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:n},d=t.certLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{a(h.data)},onError:(h,f,m,p)=>{o(new Vt({type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:Ce({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${n}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,m)=>{o(new Vt({type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(h,f,m)=>{o(new Error("aborted"))}};r.load(l,u,c)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((r,n)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),r(e)}).catch(a=>{n(new Vt({type:ie.KEY_SYSTEM_ERROR,details:w.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(r=>{throw new Vt({type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:r,fatal:!1},r.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 r=new DOMParser().parseFromString(s,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let u;for(let c=0,h=n.length;c<h;c++){var a,o;u=n[c];const f=(a=u.querySelector("name"))==null?void 0:a.textContent,m=(o=u.querySelector("value"))==null?void 0:o.textContent;f&&m&&e.setRequestHeader(f,m)}}const l=r.querySelector("Challenge"),d=l?.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return Gh(atob(d))}setupLicenseXHR(e,t,s,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,s,r)}).catch(a=>{if(!s.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,s,r)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{const a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const d=this.config.licenseResponseCallback;if(d)try{l=d.call(this.hls,o,a,e)}catch(u){this.error(u)}r(l)}else{const l=s.errorRetry,d=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)n(new Vt({type:ie.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const u=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(r,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:d})=>{e.keySystem==je.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(l,d)),l.send(d)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,wt(s,"encrypted",this.onMediaEncrypted),wt(s,"waitingforkey",this.onWaitingForKey);const r=this.mediaResolved;r?r():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(Nt(e,"encrypted",this.onMediaEncrypted),Nt(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,js.clearKeyUriToKeyIdMap();const n=r.length;$n.CDMCleanupPromise=Promise.all(r.map(a=>this.removeSession(a)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:r}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${It(r?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);const{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(d=>self.clearTimeout(a[d]));const{drmSystemOptions:o}=this.config;return(ck(o)?new Promise((d,u)=>{self.setTimeout(()=>u(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(d).catch(u)}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${d}`)})}).then(()=>t.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}$n.CDMCleanupPromise=void 0;function el(i){if(!i)throw new Error("Could not read keyId of undefined decryptdata");if(i.keyId===null)throw new Error("keyId is null");return It(i.keyId)}function DC(i,e){if(i.keyId&&e.mediaKeysSession.keyStatuses.has(i.keyId))return e.mediaKeysSession.keyStatuses.get(i.keyId);if(i.matches(e.decryptdata))return e.keyStatus}class Vt extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function x0(i,e){const t=i==="output-restricted",s=t?w.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:w.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Vt({type:ie.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${i}"`)}class CC{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(y.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(y.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 r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&typeof r.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const r=performance.now();if(t){if(this.lastTime){const n=r-this.lastTime,a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,d=this.hls;if(d.trigger(y.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),l>0&&a>d.config.fpsDroppedMonitoringThreshold*o){let u=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=u)&&(u=u-1,d.trigger(y.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:d.currentLevel}),d.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=r,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 Bb(i,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=i,e.dispatchEvent(t)}function Hb(i,e){const t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues&&!i.cues.getCueById(e.id))try{if(i.addCue(e),!i.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){we.debug(`[texttrack-utils]: ${s}`);try{const r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,i.addCue(r)}catch(r){we.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}t==="disabled"&&(i.mode=t)}function Cn(i,e){const t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues)for(let s=i.cues.length;s--;)e&&i.cues[s].removeEventListener("enter",e),i.removeCue(i.cues[s]);t==="disabled"&&(i.mode=t)}function Xh(i,e,t,s){const r=i.mode;if(r==="disabled"&&(i.mode="hidden"),i.cues&&i.cues.length>0){const n=MC(i.cues,e,t);for(let a=0;a<n.length;a++)(!s||s(n[a]))&&i.removeCue(n[a])}r==="disabled"&&(i.mode=r)}function wC(i,e){if(e<=i[0].startTime)return 0;const t=i.length-1;if(e>i[t].endTime)return-1;let s=0,r=t,n;for(;s<=r;)if(n=Math.floor((r+s)/2),e<i[n].startTime)r=n-1;else if(e>i[n].startTime&&s<t)s=n+1;else return n;return i[s].startTime-e<e-i[r].startTime?s:r}function MC(i,e,t){const s=[],r=wC(i,e);if(r>-1)for(let n=r,a=i.length;n<a;n++){const o=i[n];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function Yl(i){const e=[];for(let t=0;t<i.length;t++){const s=i[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(i[t])}return e}class PC extends jm{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=Yl(this.media.textTracks);for(let n=0;n<s.length;n++)if(s[n].mode==="hidden")t=s[n];else if(s[n].mode==="showing"){t=s[n];break}const r=this.findTrackForTextTrack(t);this.subtitleTrack!==r&&this.setSubtitleTrack(r)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(y.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 r=!!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,r)return;Yl(s.textTracks).forEach(a=>{Cn(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:r,details:n}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${s} and group:${r} not found in active group ${a?.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${s} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,r=this.groupIds;let n=this.currentTrack;if(!s||r?.length!==s?.length||s!=null&&s.some(a=>r?.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,c)=>{u.id=c});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;const u=Qi(o,a);if(u>-1)n=a[u];else{const c=Qi(o,this.tracks);n=this.tracks[c]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));const d={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(y.SUBTITLE_TRACKS_UPDATED,d),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let r=0;r<t.length;r++){const n=t[r];if(!(s&&!n.default||!s&&!e)&&(!e||Lr(n,e)))return r}if(e){for(let r=0;r<t.length;r++){const n=t[r];if(bo(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){const n=t[r];if(bo(e.attrs,n.attrs,["LANGUAGE"]))return r}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const r=t[s];if(Yh(r,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===ge.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&&Lr(e,s))return s;const r=Qi(e,this.tracksInGroup);if(r>-1){const n=this.tracksInGroup[r];return this.setSubtitleTrack(r),n}else{if(s)return null;{const n=Qi(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(y.SUBTITLE_TRACK_LOADING,{url:n,id:s,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Yl(e.textTracks),s=this.currentTrack;let r;if(s&&(r=t.filter(n=>Yh(s,n))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==r&&(n.mode="disabled")}),r){const n=this.subtitleDisplay?"showing":"hidden";r.mode!==n&&(r.mode=n)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!X(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r){this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:e});return}const n=!!r.details&&!r.details.live;if(e===this.trackId&&r===s&&n)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:a,groupId:o="",name:l,type:d,url:u}=r;this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:d,url:u});const c=this.switchParams(r.url,s?.details,r.details);this.loadPlaylist(c)}}function OC(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(r=="x"?n:n&3|8).toString(16)})}}}function Xa(i){let e=5381,t=i.length;for(;t;)e=e*33^i.charCodeAt(--t);return(e>>>0).toString()}const Fn=.025;let ru=(function(i){return i[i.Point=0]="Point",i[i.Range=1]="Range",i})({});function NC(i,e,t){return`${i.identifier}-${t+1}-${Xa(e)}`}class UC{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return Cc(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=Cc(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=X(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 Cc(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)<Fn))}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"?ru.Range:ru.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 $C(this)}}function Cc(i,e){return i-e.start<e.duration/2&&!(Math.abs(i-(e.start+e.duration))<Fn)?e.start:e.start+e.duration}function Gb(i,e,t){const s=new self.URL(i,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function wc(i,e){for(;(t=i.assetList[++e])!=null&&t.error;)var t;return e}function $C(i){return`["${i.identifier}" ${i.cue.pre?"<pre>":i.cue.post?"<post>":""}${i.timelineStart.toFixed(2)}-${i.resumeTime.toFixed(2)}]`}function gn(i){const e=i.timelineStart,t=i.duration||0;return`["${i.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class FC{constructor(e,t,s,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(y.PLAYOUT_LIMIT_REACHED,{})};const n=this.hls=new e(t);this.interstitial=s,this.assetItem=r;const a=()=>{this.hasDetails=!0};n.once(y.LEVEL_LOADED,a),n.once(y.AUDIO_TRACK_LOADED,a),n.once(y.SUBTITLE_TRACK_LOADED,a),n.on(y.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(y.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,n.trigger(y.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Gb(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,n=ue.bufferInfo(e,r,0);return this.getAssetTime(n.end)>=s-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=ue.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var r;(r=this.hls)==null||r.on(e,t)}once(e,t,s){var r;(r=this.hls)==null||r.once(e,t)}off(e,t,s){var r;(r=this.hls)==null||r.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${gn(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const L0=.033;class BC extends di{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,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.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 r=this.items;if(r)for(r[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(n=r[s])!=null&&n.event;){var n;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let r=0;r<s.length;r++){let n=s[r];if(t&&t!=="primary"&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return r}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let r=e;r<=t&&s[r];r++){const n=s[r].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return r}return-1}findEventIndex(e){const t=this.items;if(t)for(let r=t.length;r--;){var s;if(((s=t[r].event)==null?void 0:s.identifier)===e)return r}return-1}findAssetIndex(e,t){const s=e.assetList,r=s.length;if(r>1)for(let n=0;n<r;n++){const a=s[n];if(!a.error){const o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||n===r-1))return n}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,r=s[s.length-1];if(r)return r.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:r}=s,n=this.events,a=this.parseDateRanges(r,{url:s.url},t),o=Object.keys(r),l=n?n.filter(d=>!o.includes(d.identifier)):[];a.length&&a.sort((d,u)=>{const c=d.cue.pre,h=d.cue.post,f=u.cue.pre,m=u.cue.post;if(c&&!f)return-1;if(f&&!c||h&&!m)return 1;if(m&&!h)return-1;if(!c&&!f&&!h&&!m){const p=d.startTime,g=u.startTime;if(p!==g)return p-g}return d.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=a,l.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(e,l)}updateSchedule(e,t=[],s=!1){const r=this.events||[];if(r.length||t.length||this.length<2){const n=this.items,a=this.parseSchedule(r,e);(s||t.length||n?.length!==a.length||a.some((l,d)=>Math.abs(l.playout.start-n[d].playout.start)>.005||Math.abs(l.playout.end-n[d].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,n))}}parseDateRanges(e,t,s){const r=[],n=Object.keys(e);for(let a=0;a<n.length;a++){const o=n[a],l=e[o];if(l.isInterstitial){let d=this.eventMap[o];d?d.setDateRange(l):(d=new UC(l,t),this.eventMap[o]=d,s===!1&&(d.appendInPlace=s)),r.push(d)}}return r}parseSchedule(e,t){const s=[],r=t.main.details,n=r.live?1/0:r.edge;let a=0;if(e=e.filter(l=>!l.error&&!(l.cue.once&&l.hasPlayed)),e.length){this.resolveOffsets(e,t);let l=0,d=0;if(e.forEach((u,c)=>{const h=u.cue.pre,f=u.cue.post,m=e[c-1]||null,p=u.appendInPlace,g=f?n:u.startOffset,v=u.duration,b=u.timelineOccupancy===ru.Range?v:0,E=u.resumptionOffset,T=m?.startTime===g,A=g+u.cumulativeDuration;let x=p?A+v:g+E;if(h||!f&&g<=0){const L=d;d+=b,u.timelineStart=A;const R=a;a+=v,s.push({event:u,start:A,end:x,playout:{start:R,end:a},integrated:{start:L,end:d}})}else if(g<=n){if(!T){const I=g-l;if(I>L0){const M=l,B=d;d+=I;const q=a;a+=I;const z={previousEvent:e[c-1]||null,nextEvent:u,start:M,end:M+I,playout:{start:q,end:a},integrated:{start:B,end:d}};s.push(z)}else I>0&&m&&(m.cumulativeDuration+=I,s[s.length-1].end=g)}f&&(x=A),u.timelineStart=A;const L=d;d+=b;const R=a;a+=v,s.push({event:u,start:A,end:x,playout:{start:R,end:a},integrated:{start:L,end:d}})}else return;const S=u.resumeTime;f||S>n?l=n:l=S}),l<n){var o;const u=l,c=d,h=n-l;d+=h;const f=a;a+=h,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:l,end:u+h,playout:{start:f,end:a},integrated:{start:c,end:d}})}this.setDurations(n,a,d)}else s.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,r=s.live?1/0:s.edge;let n=0,a=-1;e.forEach((o,l)=>{const d=o.cue.pre,u=o.cue.post,c=d?0:u?r:o.startTime;this.updateAssetDurations(o),a===c?o.cumulativeDuration=n:(n=0,a=c),!u&&o.snapOptions.in&&(o.resumeAnchor=Mr(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<L0&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=X(o.resumeOffset)?o.resumeOffset:o.duration;n+=f})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(s-r)>Fn?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(a=>{const o=t[a].details,l=o.edge;if(s>=l)return this.log(`"${e.identifier}" resumption ${s} past ${a} playlist end ${l}`),!1;const d=Mr(null,o.fragments,s);if(!d)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(d.start-s)<Fn+u||Math.abs(d.end-s)<Fn+u?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${a} fragment bounds (${d.start}-${d.end} sn: ${d.sn} cc: ${d.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,r=!1,n=!1;for(let a=0;a<e.assetList.length;a++){const o=e.assetList[a],l=t+s;o.startOffset=s,o.timelineStart=l,r||(r=o.duration===null),n||(n=!!o.error);const d=o.error?0:o.duration||0;s+=d}r&&!n?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function fi(i){return`[${i.event?'"'+i.event.identifier+'"':"primary"}: ${i.start.toFixed(2)}-${i.end.toFixed(2)}]`}class HC{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let r;try{r=Gb(s,this.hls.sessionId,e.baseUrl)}catch(h){const f=this.assignAssetListError(e,w.ASSET_LIST_LOAD_ERROR,h,s);this.hls.trigger(y.ERROR,f);return}t&&r.protocol!=="data:"&&r.searchParams.set("_HLS_start_offset",""+t);const n=this.hls.config,a=n.loader,o=new a(n),l={responseType:"json",url:r.href},d=n.interstitialAssetListLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{const g=h.data,v=g?.ASSETS;if(!Array.isArray(v)){const b=this.assignAssetListError(e,w.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),m.url,f,p);this.hls.trigger(y.ERROR,b);return}e.assetListResponse=g,this.hls.trigger(y.ASSET_LIST_LOADED,{event:e,assetListResponse:g,networkDetails:p})},onError:(h,f,m,p)=>{const g=this.assignAssetListError(e,w.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${f.url})`),f.url,p,m);this.hls.trigger(y.ERROR,g)},onTimeout:(h,f,m)=>{const p=this.assignAssetListError(e,w.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,h,m);this.hls.trigger(y.ERROR,p)}};return o.load(l,u,c),this.hls.trigger(y.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,r,n,a){return e.error=s,{type:ie.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:s,networkDetails:a,stats:n}}}function R0(i){var e;i==null||(e=i.play())==null||e.catch(()=>{})}function tl(i,e){return`[${i}] Advancing timeline position to ${e}`}class GC extends di{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const r=s-this.timelinePos;if(Math.abs(r)<1/7056e5)return;const a=r<=-.01;this.timelinePos=s,this.bufferedPos=s;const o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(s,s-r)&&this.updateSchedule(!0),this.checkBuffer(),a&&s<o.start||s>=o.end){var l;const f=this.findItemIndex(o);let m=this.schedule.findItemIndexAtTime(s);if(m===-1&&(m=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${s} (resolving from ${f} to ${m})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&m>f){const p=this.schedule.findJumpRestrictedIndex(f+1,m);if(p>f){this.setSchedulePosition(p);return}}this.setSchedulePosition(m);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}return}const u=d.timelineStart,c=d.duration||0;if(a&&s<u||s>=u+c){var h;(h=o.event)!=null&&h.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,d)}},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 r=this.playingItem;if(!r||this.playingLastItem)return;if(s>=r.end){this.timelinePos=r.end;const o=this.findItemIndex(r);this.setSchedulePosition(o+1)}const n=this.playingAsset;if(!n)return;const a=n.timelineStart+(n.duration||0);s>=a&&this.setScheduleToAssetAtTime(s,n)},this.onScheduleUpdate=(s,r)=>{const n=this.schedule;if(!n)return;const a=this.playingItem,o=n.events||[],l=n.items||[],d=n.durations,u=s.map(p=>p.identifier),c=!!(o.length||u.length);(c||r)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
|
|
1445
|
+
Schedule: ${l.map(p=>fi(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let h=null,f=null;a&&(h=this.updateItem(a,this.timelinePos),this.itemsMatch(a,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const m=this.bufferingItem;if(m&&(f=this.updateItem(m,this.bufferedPos),this.itemsMatch(m,f)?this.bufferingItem=f:m.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(m.event,null))),s.forEach(p=>{p.assetList.forEach(g=>{this.clearAssetPlayer(g.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){const g=p.assetItem.timelineStart,v=p.timelineOffset-g;if(v)try{p.timelineOffset=g}catch(b){Math.abs(v)>Fn&&this.warn(`${b} ("${p.assetId}" ${p.timelineOffset}->${g})`)}}}),c||r){if(this.hls.trigger(y.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:d,removedIds:u}),this.isInterstitial(a)&&u.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(h,a),m&&f!==h&&this.trimInPlace(f,m),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new HC(e),this.schedule=new BC(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(y.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(y.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(y.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(y.MEDIA_ENDED,this.onMediaEnded,this),e.on(y.ERROR,this.onError,this),e.on(y.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(y.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(y.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(y.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(y.MEDIA_ENDED,this.onMediaEnded,this),e.off(y.ERROR,this.onError,this),e.off(y.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Nt(e,"play",this.onPlay),Nt(e,"pause",this.onPause),Nt(e,"seeking",this.onSeeking),Nt(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;wt(s,"seeking",this.onSeeking),wt(s,"timeupdate",this.onTimeupdate),wt(s,"play",this.onPlay),wt(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!r){this.clearScheduleState();const n=this.findItemIndex(s);this.setSchedulePosition(n)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,r=this.media;if(this.media=null,!s&&(r&&this.removeMediaListeners(r),this.detachedData)){const n=this.getBufferingPlayer();n&&(this.log(`Removing schedule state for detachedData and ${n}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=c=>c&&e.getAssetPlayer(c.identifier),r=(c,h,f,m,p)=>{if(c){let g=c[h].start;const v=c.event;if(v){if(h==="playout"||v.timelineOccupancy!==ru.Point){const b=s(f);b?.interstitial===v&&(g+=b.assetItem.startOffset+b[p])}}else{const b=m==="bufferedPos"?a():e[m];g+=b-c.start}return g}return 0},n=(c,h)=>{var f;if(c!==0&&h!=="primary"&&(f=e.schedule)!=null&&f.length){var m;const p=e.schedule.findItemIndexAtTime(c),g=(m=e.schedule.items)==null?void 0:m[p];if(g){const v=g[h].start-g.start;return c+v}}return c},a=()=>{const c=e.bufferedPos;return c===Number.MAX_VALUE?o("primary"):Math.max(c,0)},o=c=>{var h,f;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[c])||0},l=(c,h)=>{var f,m;const p=e.effectivePlayingItem;if(p!=null&&(f=p.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${c} "${h}"`);const g=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(c,h),b=(m=e.schedule.items)==null?void 0:m[v],E=e.getBufferingPlayer(),T=E?.interstitial,A=T?.appendInPlace,x=g&&e.itemsMatch(g,b);if(g&&(A||x)){const S=s(e.playingAsset),L=S?.media||e.primaryMedia;if(L){const R=h==="primary"?L.currentTime:r(g,h,e.playingAsset,"timelinePos","currentTime"),I=c-R,M=(A?R:L.currentTime)+I;if(M>=0&&(!S||A||M<=S.duration)){L.currentTime=M;return}}}if(b){let S=c;if(h!=="primary"){const R=b[h].start,I=c-R;S=b.start+I}const L=!e.isInterstitial(b);if((!e.isInterstitial(g)||g.event.appendInPlace)&&(L||b.event.appendInPlace)){const R=e.media||(A?E?.media:null);R&&(R.currentTime=S)}else if(g){const R=e.findItemIndex(g);if(v>R){const M=e.schedule.findJumpRestrictedIndex(R+1,v);if(M>R){e.setSchedulePosition(M);return}}let I=0;if(L)e.timelinePos=S,e.checkBuffer();else{const M=b.event.assetList,B=c-(b[h]||b).start;for(let q=M.length;q--;){const z=M[q];if(z.duration&&B>=z.startOffset&&B<z.startOffset+z.duration){I=q;break}}}e.setSchedulePosition(v,I)}}},d=()=>{const c=e.effectivePlayingItem;if(e.isInterstitial(c))return c;const h=t();return e.isInterstitial(h)?h:null},u={get bufferedEnd(){const c=t(),h=e.bufferingItem;if(h&&h===c){var f;return r(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const c=d(),h=e.effectivePlayingItem;return h&&h===c?r(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(c){const h=d(),f=e.effectivePlayingItem;f&&f===h&&l(c+f.playout.start,"playout")},get duration(){const c=d();return c?c.playout.end-c.playout.start:0},get assetPlayers(){var c;const h=(c=d())==null?void 0:c.event.assetList;return h?h.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var c;const h=(c=d())==null?void 0:c.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var c;return((c=e.schedule)==null||(c=c.events)==null?void 0:c.slice(0))||[]},get schedule(){var c;return((c=e.schedule)==null||(c=c.items)==null?void 0:c.slice(0))||[]},get interstitialPlayer(){return d()?u:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const c=t();return e.findItemIndex(c)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const c=e.effectivePlayingItem;return e.findItemIndex(c)},primary:{get bufferedEnd(){return a()},get currentTime(){const c=e.timelinePos;return c>0?c:0},set currentTime(c){l(c,"primary")},get duration(){return o("primary")},get seekableStart(){var c;return((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(c){l(c,"integrated")},get duration(){return o("integrated")},get seekableStart(){var c;return n(((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0,"integrated")}},skip:()=>{const c=e.effectivePlayingItem,h=c?.event;if(h&&!h.restrictions.skip){const f=e.findItemIndex(c);if(h.appendInPlace){const m=c.playout.start+c.event.duration;l(m+.001,"playout")}else e.advanceAfterAssetEnded(h,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let r=this.media;!r&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(r=this.primaryMedia);const n=(t=r)==null?void 0:t.currentTime;if(!(n===void 0||!X(n)))return n}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,r=e.media;if(s&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}const n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${$e(n)}`),this.detachedData=n}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(e,t){var s,r;if(e.media===t)return;let n=null;const a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,d=(s=this.detachedData)==null?void 0:s.mediaSource;let u;if(a.media)l&&(n=a.transferMedia(),this.detachedData=n),u="Primary";else if(d){const m=this.getBufferingPlayer();m?(n=m.transferMedia(),u=`${m}`):u="detached MediaSource"}else u="detached media";if(!n){if(d)n=this.detachedData,this.log(`using detachedData: MediaSource ${$e(n)}`);else if(!this.detachedData||a.media===t){const m=this.playerQueue;m.length>1&&m.forEach(p=>{if(o&&p.interstitial.appendInPlace!==l){const g=p.interstitial;this.clearInterstitial(p.interstitial,null),g.appendInPlace=!1,g.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${g}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const c=n&&"mediaSource"in n&&((r=n.mediaSource)==null?void 0:r.readyState)!=="closed",h=c&&n?n:t;this.log(`${c?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${u} (media.currentTime: ${t.currentTime})`);const f=this.schedule;if(h===n&&f){const m=o&&e.assetId===f.assetIdAtEnd;h.overrides={duration:f.duration,endOfStream:!o||m,cueRemoval:!o}}e.attachMedia(h)}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,r=this.effectivePlayingItem;if(s===-1){const n=this.hls.startPosition;if(this.log(tl("checkStart",n)),this.timelinePos=n,t.length&&t[0].cue.pre){const a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(n>=0||!this.primaryLive){const a=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(r&&!this.playingItem){const n=e.findItemIndex(r);this.setSchedulePosition(n)}}advanceAssetBuffering(e,t){const s=e.event,r=s.findAssetIndex(t),n=wc(s,r);if(!s.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var a;const o=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,s){const r=wc(e,s);if(e.isAssetPastPlayoutLimit(r)){if(this.schedule){const n=this.schedule.items;if(n){const a=t+1,o=n.length;if(a>=o){this.setSchedulePosition(-1);return}const l=e.resumeTime;this.timelinePos<l&&(this.log(tl("advanceAfterAssetEnded",l)),this.timelinePos=l,e.appendInPlace&&this.advanceInPlace(l),this.checkBuffer(this.bufferedPos<l)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){const n=e.assetList[r];n&&this.advanceInPlace(n.timelineStart)}this.setSchedulePosition(t,r)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const r=t.parentIdentifier,n=s.getEvent(r);if(n){const a=s.findEventIndex(r),o=s.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1)}}setSchedulePosition(e,t){var s;const r=(s=this.schedule)==null?void 0:s.items;if(!r||this.playbackDisabled)return;const n=e>=0?r[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&fi(n)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){const u=a.event,c=this.playingAsset,h=c?.identifier,f=h?this.getAssetPlayer(h):null;if(f&&h&&(!this.eventItemsMatch(a,n)||t!==void 0&&h!==u.assetList[t].identifier)){var l;const m=u.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${m+1}/${u.assetList.length} ${gn(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(y.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:m,event:u,schedule:r.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),m);return}this.retreiveMediaSource(h,n),f.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${fi(a)}`),u.hasPlayed=!0,this.hls.trigger(y.INTERSTITIAL_ENDED,{event:u,schedule:r.slice(0),scheduleIndex:e}),u.cue.once)){var d;this.updateSchedule();const m=(d=this.schedule)==null?void 0:d.items;if(n&&m){const p=this.findItemIndex(n);this.advanceSchedule(p,m,t,a,o)}return}}this.advanceSchedule(e,r,t,a,o)}advanceSchedule(e,t,s,r,n){const a=this.schedule;if(!a)return;const o=t[e]||null,l=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(u=>{const c=u.interstitial,h=a.findEventIndex(c.identifier);(h<e||h>e+1)&&this.clearInterstitial(c,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const u=o.event;if(s===void 0){s=a.findAssetIndex(u,this.timelinePos);const m=wc(u,s-1);if(u.isAssetPastPlayoutLimit(m)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,e,s);return}s=m}const c=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let h=this.preloadAssets(u,s);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${fi(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(y.INTERSTITIAL_STARTED,{event:u,schedule:t.slice(0),scheduleIndex:e})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const f=u.assetList[s];if(!f){this.advanceAfterAssetEnded(u,e,s||0);return}if(h||(h=this.getAssetPlayer(f.identifier)),h===null||h.destroyed){const m=u.assetList.length;this.warn(`asset ${s+1}/${m} player destroyed ${u}`),h=this.createAssetPlayer(u,f,s),h.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(h,s,t,e,l),this.shouldPlay&&R0(h.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&R0(this.hls.media)):n&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,s){var r,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${fi(e)}`),!((r=this.detachedData)!=null&&r.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(tl("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!s)return;const a=(n=this.schedule)==null?void 0:n.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${fi(e)}`),this.hls.trigger(y.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const r=this.primaryDetails;if(t===0)return this.hls.startPosition;if(r&&(s<r.fragmentStart||s>r.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:ue.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 r=this.primaryMedia;if(!r)return;const n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,r),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(tl("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const r=this.hls;!r.loadingEnabled||!r.media||Math.abs((((s=r.mainForwardBufferInfo)==null?void 0:s.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(y.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(y.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const r=Ce(Ce({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=Ce(Ce({},this.altSelection),{},{audio:s});return}const n=Ce(Ce({},r),{},{audio:s});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=Ce(Ce({},this.altSelection),{},{subtitles:s});return}const n=Ce(Ce({},r),{},{subtitles:s});this.mediaSelection=n}onAudioTrackSwitching(e,t){const s=Ug(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setAudioOption(t)||r.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Ug(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setSubtitleOption(t)||t.id!==-1&&r.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 r=this.timelinePos;this.bufferedPos=r,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let r=0;r<t.length;r++){const n=t[r];if(n.cue.post){var s;const a=this.schedule.findEventIndex(n.identifier),o=(s=this.schedule.items)==null?void 0:s[a];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const r=(s=this.schedule)==null?void 0:s.items;if(e&&r){const n=this.findItemIndex(e,t);return r[n]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((n,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(n.identifier,null)});const s=e.end+.25,r=ue.bufferInfo(this.primaryMedia,s,0);(r.end>s||(r.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${fi(e)} (was ${fi(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s)return;const r=ue.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,s,e)}updateBufferedPos(e,t,s){const r=this.schedule,n=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}const a=this.playingItem,o=this.findItemIndex(a);let l=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var d;const u=this.findItemIndex(n),c=Math.min(u+1,t.length-1),h=t[c];if((l===-1&&n&&e>=n.end||(d=h.event)!=null&&d.appendInPlace&&e+.01>=h.start)&&(l=c),this.isInterstitial(n)){const f=n.event;if(c-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>u&&l>o)this.bufferedToItem(h);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&h.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0)}}else s&&a&&!this.itemsMatch(a,n)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(r=>{const n=this.getAssetPlayer(r.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:r,events:n}=s;if(!r||!n)return t;const a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${fi(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const d=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((u,c)=>{const h=this.getAssetPlayer(u.identifier);h&&(c===d&&h.loadSource(),h.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(y.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;const r=this.detachedData;r?r.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,r=s.assetList.length===0&&!s.assetListLoader,n=s.cue.once;if(r||!n){const a=this.preloadAssets(s,t);if(a!=null&&a.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){const s=e.assetUrl,r=e.assetList.length,n=r===0&&!e.assetListLoader,a=e.cue.once;if(n){const l=e.timelineStart;if(e.appendInPlace){var o;const h=this.playingItem;!this.isInterstitial(h)&&(h==null||(o=h.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let d,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 h=u-l;h>0&&(d=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:r} ${e}${d?` live-start: ${u} start-offset: ${d}`:""}`),s)return this.createAsset(e,0,0,l,e.duration,s);const c=this.assetListLoader.loadAssetList(e,d);c&&(e.assetListLoader=c)}else if(!a&&r){for(let d=t;d<r;d++){const u=e.assetList[d],c=this.getAssetPlayerQueueIndex(u.identifier);(c===-1||this.playerQueue[c].destroyed)&&!u.error&&this.createAssetPlayer(e,u,d)}const l=e.assetList[t];if(l){const d=this.getAssetPlayer(l.identifier);return d&&d.loadSource(),d}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(r=>{this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})})}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,r,n,a){const o={parentIdentifier:e.identifier,identifier:NC(e,a,t),duration:n,startOffset:s,timelineStart:r,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){const r=this.hls,n=r.userConfig;let a=n.videoPreference;const o=r.loadLevelObj||r.levels[r.currentLevel];(a||o)&&(a=Oe({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));const l=r.audioTracks[r.audioTrack],d=r.subtitleTracks[r.subtitleTrack];let u=0;if(this.primaryLive||e.appendInPlace){const T=this.timelinePos-t.timelineStart;if(T>1){const A=t.duration;A&&T<A&&(u=T)}}const c=t.identifier,h=Ce(Ce({},n),{},{maxMaxBufferLength:Math.min(180,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:l||n.audioPreference,subtitlePreference:d||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(h.timelineOffset=t.timelineStart));const f=h.cmcd;f!=null&&f.sessionId&&f.contentId&&(h.cmcd=Oe({},f,{contentId:Xa(t.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${e} and asset ${c}`);const m=new FC(this.HlsPlayerClass,h,e,t);this.playerQueue.push(m),e.assetList[s]=t;let p=!0;const g=T=>{if(T.live){var A;const L=new Error(`Interstitials MUST be VOD assets ${e}`),R={fatal:!0,type:ie.OTHER_ERROR,details:w.INTERSTITIAL_ASSET_ITEM_ERROR,error:L},I=((A=this.schedule)==null?void 0:A.findEventIndex(e.identifier))||-1;this.handleAssetItemError(R,e,I,s,L.message);return}const x=T.edge-T.fragmentStart,S=t.duration;(p||S===null||x>S)&&(p=!1,this.log(`Interstitial asset "${c}" duration change ${S} > ${x}`),t.duration=x,this.updateSchedule())};m.on(y.LEVEL_UPDATED,(T,{details:A})=>g(A)),m.on(y.LEVEL_PTS_UPDATED,(T,{details:A})=>g(A)),m.on(y.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const v=(T,A)=>{const x=this.getAssetPlayer(c);if(x&&A.tracks){x.off(y.BUFFER_CODECS,v),x.tracks=A.tracks;const S=this.primaryMedia;this.bufferingAsset===x.assetItem&&S&&!x.media&&this.bufferAssetPlayer(x,S)}};m.on(y.BUFFER_CODECS,v);const b=()=>{var T;const A=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${A}`),!A||!this.schedule)return;const x=this.schedule.findEventIndex(e.identifier),S=(T=this.schedule.items)==null?void 0:T[x];this.isInterstitial(S)&&this.advanceAssetBuffering(S,t)};m.on(y.BUFFERED_TO_END,b);const E=T=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;const x=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,x,T)};return m.once(y.MEDIA_ENDED,E(s)),m.once(y.PLAYOUT_LIMIT_REACHED,E(1/0)),m.on(y.ERROR,(T,A)=>{if(!this.schedule)return;const x=this.getAssetPlayer(c);if(A.details===w.BUFFER_STALLED_ERROR){if(x!=null&&x.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(A,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${A.error} ${e}`)}),m.on(y.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;const A=new Error(`Asset player destroyed unexpectedly ${c}`),x={fatal:!0,type:ie.OTHER_ERROR,details:w.INTERSTITIAL_ASSET_ITEM_ERROR,error:A};this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),s,A.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${gn(t)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:m}),m}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){const r=this.playerQueue[s];this.log(`clear ${r} toSegment: ${t&&fi(t)}`),this.transferMediaFromPlayer(r,t),this.playerQueue.splice(s,1),r.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,r,n){const{interstitial:a,assetItem:o,assetId:l}=e,d=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!u||u.identifier!==l)&&(u&&(this.clearAssetPlayer(u.identifier,s[r]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${gn(o)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:s.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var s,r;if(!this.schedule)return;const{interstitial:n,assetItem:a}=e,o=this.schedule.findEventIndex(n.identifier),l=(s=this.schedule.items)==null?void 0:s[o];if(!l)return;e.loadSource(),this.setBufferingItem(l),this.bufferingAsset=a;const d=this.getBufferingPlayer();if(d===e)return;const u=n.appendInPlace;if(u&&d?.interstitial.appendInPlace===!1)return;const c=d?.tracks||((r=this.detachedData)==null?void 0:r.tracks)||this.requiredTracks;if(u&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(c&&!Sy(c,e.tracks)){const h=new Error(`Asset ${gn(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),f={fatal:!0,type:ie.OTHER_ERROR,details:w.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},m=n.findAssetIndex(a);this.handleAssetItemError(f,n,o,m,h.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const r=s.currentTime,n=t.findAssetIndex(e,r),a=e.assetList[n];if(a){const o=this.getAssetPlayer(a.identifier);if(o){const l=o.currentTime||r-a.timelineStart,d=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+d} in ${o} ${e} (media.currentTime: ${r})`),l&&(d/s.playbackRate<.5||o.bufferedInPlaceToEnd(s))&&o.hls){const u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,n)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,r,n){if(e.details===w.BUFFER_STALLED_ERROR)return;const a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&gn(a)} ${e.error}`),!this.schedule)return;const o=a?.identifier||"",l=this.getAssetPlayerQueueIndex(o),d=this.playerQueue[l]||null,u=this.schedule.items,c=Oe({},e,{fatal:!1,errorAction:Nn(!0),asset:a,assetListIndex:r,event:t,schedule:u,scheduleIndex:s,player:d});if(this.hls.trigger(y.INTERSTITIAL_ASSET_ERROR,c),!e.fatal)return;const h=this.playingAsset,f=this.bufferingAsset,m=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=m),!t.assetList.some(p=>!p.error))t.error=m;else for(let p=r;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):h&&h.identifier===o?this.advanceAfterAssetEnded(t,s,r):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;let r=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${r} playing: ${fi(s)} error: ${e.error}`),r===-1&&(r=this.hls.startPosition);const a=this.updateItem(s,r);this.itemsMatch(s,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(r===-1){this.checkStart();return}if(!this.schedule)return;const n=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(n)}onAssetListLoaded(e,t){var s,r;const n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(a)))return;const l=n.timelineStart,d=n.duration;let u=0;o.forEach((p,g)=>{const v=parseFloat(p.DURATION);this.createAsset(n,g,u,l+u,v,p.URI),u+=v}),n.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${d}) ${n}`);const c=this.waitingItem,h=c?.event.identifier===a;this.updateSchedule();const f=(r=this.bufferingItem)==null?void 0:r.event;if(h){var m;const p=this.schedule.findEventIndex(a),g=(m=this.schedule.items)==null?void 0:m[p];if(g){if(!this.playingItem&&this.timelinePos>g.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){n.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${n}`),this.log(n.error.message),this.updateSchedule(!0),this.primaryFallback(n);return}this.setBufferingItem(g)}this.setSchedulePosition(p)}else if(f?.identifier===a){const p=n.assetList[0];if(p){const g=this.getAssetPlayer(p.identifier);if(f.appendInPlace){const v=this.primaryMedia;g&&v&&this.bufferAssetPlayer(g,v)}else g&&g.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case w.ASSET_LIST_PARSING_ERROR:case w.ASSET_LIST_LOAD_ERROR:case w.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case w.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const k0=500;class KC extends Bm{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",J.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(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(y.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(y.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=P.IDLE,this.setInterval(k0),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:r}=t;if(this.fragContextChanged(s)||(et(s)&&(this.fragPrevious=s),this.state=P.IDLE),!r)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a;const o=s.start;for(let d=0;d<n.length;d++)if(o>=n[d].start&&o<=n[d].end){a=n[d];break}const l=s.start+s.duration;a?a.end=l:(a={start:o,end:l},n.push(a)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:r}=t;if(s===0&&r!==Number.POSITIVE_INFINITY){const n=r-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=n){a.shift();continue}else if(a[o].start<n)a[o].start=n;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,n,J.SUBTITLE)}}onError(e,t){const s=t.frag;s?.type===J.SUBTITLE&&(t.details===w.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==P.STOPPED&&(this.state=P.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Lb(this.levels,t)){this.levels=t.map(s=>new go(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const r=new go(s);return this.tracksBuffered[r.id]=[],r}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,J.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const r=this.levels[this.currentTrackId];r!=null&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==P.STOPPED&&this.setInterval(k0)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:r,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=n[o];if(o>=n.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(a.live||(s=l.details)!=null&&s.live){if(a.deltaUpdateFailed)return;const c=this.mainDetails;if(!c){this.startFragRequested=!1;return}const h=c.fragments[0];if(!l.details)a.hasProgramDateTime&&c.hasProgramDateTime?(iu(a,c),d=a.fragmentStart):h&&(d=h.start,Vh(a,d));else{var u;d=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details),d===0&&h&&(d=h.start,Vh(a,d))}c&&!this.startFragRequested&&this.setStartPosition(c,d)}l.details=a,this.levelLastLoaded=l,o===r&&(this.hls.trigger(y.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===P.IDLE&&(Mr(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,r=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&r!=null&&r.key&&r.iv&&Un(r.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(s),r.key.buffer,r.iv.buffer,$m(r.method)).catch(o=>{throw n.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const l=performance.now();n.trigger(y.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=P.IDLE})}}doTick(){if(!this.media){this.state=P.IDLE;return}if(this.state===P.IDLE){const{currentTrackId:e,levels:t}=this,s=t?.[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:r}=this,n=this.getLoadPosition(),a=ue.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,r.maxBufferHole),{end:o,len:l}=a,d=s.details,u=this.hls.maxBufferLength+d.levelTargetDuration;if(l>u)return;const c=d.fragments,h=c.length,f=d.edge;let m=null;const p=this.fragPrevious;if(o<f){const b=r.maxFragLookUpTolerance,E=o>f-b?0:b;m=Mr(p,c,Math.max(c[0].start,o),E),!m&&p&&p.start<c[0].start&&(m=c[0])}else m=c[h-1];if(m=this.filterReplacedPrimary(m,s.details),!m)return;const g=m.sn-d.startSN,v=c[g-1];if(v&&v.cc===m.cc&&this.fragmentTracker.getState(v)===gt.NOT_LOADED&&(m=v),this.fragmentTracker.getState(m)===gt.NOT_LOADED){const b=this.mapToInitFragWhenRequired(m);b&&this.loadFragment(b,s,o)}}}loadFragment(e,t,s){et(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new VC(this.tracksBuffered[this.currentTrackId]||[])}}class VC{constructor(e){this.buffered=void 0;const t=(s,r,n)=>{if(r=r>>>0,r>n-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][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 WC={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},Kb=i=>String.fromCharCode(WC[i]||i),yi=15,ls=100,qC={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},YC={17:2,18:4,21:6,22:8,23:10,19:13,20:15},jC={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},zC={25:2,26:4,29:6,30:8,31:10,27:13,28:15},QC=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class XC{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;we.log(`${this.time} [${e}] ${s}`)}}}const sr=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class Vb{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 r=t[s];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class ZC{constructor(){this.uchar=" ",this.penState=new Vb}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 JC{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Vb,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<ls;t++)this.chars.push(new ZC);this.logger=e}equals(e){for(let t=0;t<ls;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<ls;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<ls;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>ls&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ls)}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=Kb(e);if(this.pos>=ls){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<ls;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<ls;s++){const r=this.chars[s].uchar;r!==" "&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class Mc{constructor(e){this.rows=[],this.currRow=yi-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<yi;t++)this.rows.push(new JC(e));this.logger=e}reset(){for(let e=0;e<yi;e++)this.rows[e].clear();this.currRow=yi-1}equals(e){let t=!0;for(let s=0;s<yi;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<yi;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<yi;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 = "+$e(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<yi;o++)this.rows[o].clear();const n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[n].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let d=0;d<this.nrRollUpRows;d++)this.rows[t-this.nrRollUpRows+d+1].copy(a.rows[n+d])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const n=e.indent,a=Math.max(n-1,0);s.setCursor(e.indent),e.color=s.chars[a].penState.foreground}const r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+$e(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="",r=-1;for(let n=0;n<yi;n++){const a=this.rows[n].getTextString();a&&(r=n+1,e?t.push("Row "+r+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
|
|
1446
1446
|
`)),s}getTextAndFormat(){return this.rows}}class D0{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 Mc(s),this.nonDisplayedMemory=new Mc(s),this.lastOutputScreen=new Mc(s),this.currRollUpRow=this.displayedMemory.rows[yi-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[yi-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,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[s]}this.logger.log(2,"MIDROW: "+$e(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 C0{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=tw(),this.logger=void 0;const r=this.logger=new XC;this.channels=[null,new D0(e,t,r),new D0(e+1,s,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const r=t[s]&127,n=t[s+1]&127;let a=!1,o=null;if(r===0&&n===0)continue;this.logger.log(3,()=>"["+sr([t[s],t[s+1]])+"] -> ("+sr([r,n])+")");const l=this.cmdHistory;if(r>=16&&r<=31){if(ew(r,n,l)){il(null,null,l),this.logger.log(3,()=>"Repeated command ("+sr([r,n])+") is dropped");continue}il(r,n,this.cmdHistory),a=this.parseCmd(r,n),a||(a=this.parseMidrow(r,n)),a||(a=this.parsePAC(r,n)),a||(a=this.parseBackgroundAttributes(r,n))}else il(null,null,l);if(!a&&(o=this.parseChars(r,n),o)){const u=this.currentChannel;u&&u>0?this.channels[u].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+sr([r,n])+" orig: "+sr([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=33&&t<=35;if(!(s||r))return!1;const n=e===20||e===21||e===23?1:2,a=this.channels[n];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[s];return r?(r.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+sr([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const r=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(r||n))return!1;const a=e<=23?1:2;t>=64&&t<=95?s=a===1?qC[e]:jC[e]:s=a===1?YC[e]:zC[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 r={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,r.underline=(s&1)===1,s<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(r.italics=!0,r.color="white"):r.indent=Math.floor((s-16)/2)*4,r}parseChars(e,t){let s,r=null,n=null;if(e>=25?(s=2,n=e-8):(s=1,n=e),n>=17&&n<=19){let a;n===17?a=t+80:n===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+Kb(a)+"' in channel "+s),r=[a]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>"Char codes = "+sr(r).join(",")),r}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=45&&t<=47;if(!(s||r))return!1;let n;const a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=QC[n],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}il(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 il(i,e,t){t.a=i,t.b=e}function ew(i,e,t){return t.a===i&&t.b===e}function tw(){return{a:null,b:null}}var Zm=(function(){if(tu!=null&&tu.VTTCue)return self.VTTCue;const i=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const d=l.toLowerCase();return~o.indexOf(d)?d:!1}function s(o){return t(i,o)}function r(o){return t(e,o)}function n(o,...l){let d=1;for(;d<arguments.length;d++){const u=arguments[d];for(const c in u)o[c]=u[c]}return o}function a(o,l,d){const u=this,c={enumerable:!0};u.hasBeenReset=!1;let h="",f=!1,m=o,p=l,g=d,v=null,b="",E=!0,T="auto",A="start",x=50,S="middle",L=50,R="middle";Object.defineProperty(u,"id",n({},c,{get:function(){return h},set:function(I){h=""+I}})),Object.defineProperty(u,"pauseOnExit",n({},c,{get:function(){return f},set:function(I){f=!!I}})),Object.defineProperty(u,"startTime",n({},c,{get:function(){return m},set:function(I){if(typeof I!="number")throw new TypeError("Start time must be set to a number.");m=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",n({},c,{get:function(){return p},set:function(I){if(typeof I!="number")throw new TypeError("End time must be set to a number.");p=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",n({},c,{get:function(){return g},set:function(I){g=""+I,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",n({},c,{get:function(){return v},set:function(I){v=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",n({},c,{get:function(){return b},set:function(I){const M=s(I);if(M===!1)throw new SyntaxError("An invalid or illegal string was specified.");b=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",n({},c,{get:function(){return E},set:function(I){E=!!I,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",n({},c,{get:function(){return T},set:function(I){if(typeof I!="number"&&I!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");T=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",n({},c,{get:function(){return A},set:function(I){const M=r(I);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");A=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",n({},c,{get:function(){return x},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");x=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",n({},c,{get:function(){return S},set:function(I){const M=r(I);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");S=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",n({},c,{get:function(){return L},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");L=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",n({},c,{get:function(){return R},set:function(I){const M=r(I);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");R=M,this.hasBeenReset=!0}})),u.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})();class iw{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Wb(i){function e(s,r,n,a){return(s|0)*3600+(r|0)*60+(n|0)+parseFloat(a||0)}const t=i.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class sw{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 r=0;r<s.length;++r)if(t===s[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function qb(i,e,t,s){const r=s?i.split(s):[i];for(const n in r){if(typeof r[n]!="string")continue;const a=r[n].split(t);if(a.length!==2)continue;const o=a[0],l=a[1];e(o,l)}}const Zh=new Zm(0,0,""),sl=Zh.align==="middle"?"middle":"center";function rw(i,e,t){const s=i;function r(){const o=Wb(i);if(o===null)throw new Error("Malformed timestamp: "+s);return i=i.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){const d=new sw;qb(o,function(h,f){let m;switch(h){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){d.set(h,t[p].region);break}break;case"vertical":d.alt(h,f,["rl","lr"]);break;case"line":m=f.split(","),d.integer(h,m[0]),d.percent(h,m[0])&&d.set("snapToLines",!1),d.alt(h,m[0],["auto"]),m.length===2&&d.alt("lineAlign",m[1],["start",sl,"end"]);break;case"position":m=f.split(","),d.percent(h,m[0]),m.length===2&&d.alt("positionAlign",m[1],["start",sl,"end","line-left","line-right","auto"]);break;case"size":d.percent(h,f);break;case"align":d.alt(h,f,["start",sl,"end","left","right"]);break}},/:/,/\s/),l.region=d.get("region",null),l.vertical=d.get("vertical","");let u=d.get("line","auto");u==="auto"&&Zh.line===-1&&(u=-1),l.line=u,l.lineAlign=d.get("lineAlign","start"),l.snapToLines=d.get("snapToLines",!0),l.size=d.get("size",100),l.align=d.get("align",sl);let c=d.get("position","auto");c==="auto"&&Zh.position===50&&(c=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=c}function a(){i=i.replace(/^\s+/,"")}if(a(),e.startTime=r(),a(),i.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);i=i.slice(3),a(),e.endTime=r(),a(),n(i,e)}function Yb(i){return i.replace(/<br(?: \/)?>/gi,`
|
|
1447
1447
|
`)}class nw{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new iw,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function s(){let n=t.buffer,a=0;for(n=Yb(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
|
|
1448
1448
|
`;)++a;const o=n.slice(0,a);return n[a]==="\r"&&++a,n[a]===`
|
|
1449
1449
|
`&&++a,t.buffer=n.slice(a),o}function r(n){qb(n,function(a,o){},/:/)}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=s();const o=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:n=s(),t.state){case"HEADER":/:/.test(n)?r(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new Zm(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{rw(n,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=n.indexOf("-->")!==-1;if(!n||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
|
|
1450
1450
|
`),t.cue.text+=n}continue;case"BADCUE":n||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
|
|
1451
1451
|
|
|
1452
|
-
`,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 aw=/\r\n|\n\r|\n|\r/g,Pc=function(e,t,s=0){return e.slice(s,s+t.length)===t},ow=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!
|
|
1452
|
+
`,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 aw=/\r\n|\n\r|\n|\r/g,Pc=function(e,t,s=0){return e.slice(s,s+t.length)===t},ow=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!X(t)||!X(s)||!X(r)||!X(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*r,t+=3600*1e3*n,t};function Jm(i,e,t){return Xa(i.toString())+Xa(e.toString())+Xa(t)}const lw=function(e,t,s){let r=e[t],n=e[r.prevCC];if(!n||!n.new&&r.new){e.ccOffset=e.presentationOffset=r.start,r.new=!1;return}for(;(a=n)!=null&&a.new;){var a;e.ccOffset+=r.start-n.start,r.new=!1,r=n,n=e[r.prevCC]}e.presentationOffset=s};function dw(i,e,t,s,r,n,a){const o=new nw,l=Xt(new Uint8Array(i)).trim().replace(aw,`
|
|
1453
1453
|
`).split(`
|
|
1454
1454
|
`),d=[],u=e?pD(e.baseTime,e.timescale):0;let c="00:00.000",h=0,f=0,m,p=!0;o.oncue=function(g){const v=t[s];let b=t.ccOffset;const E=(h-u)/9e4;if(v!=null&&v.new&&(f!==void 0?b=t.ccOffset=v.start:lw(t,s,E)),E){if(!e){m=new Error("Missing initPTS for VTT MPEGTS");return}b=E-t.presentationOffset}const T=g.endTime-g.startTime,A=jt((g.startTime+b-f)*9e4,r*9e4)/9e4;g.startTime=Math.max(A,0),g.endTime=Math.max(A+T,0);const x=g.text.trim();g.text=decodeURIComponent(encodeURIComponent(x)),g.id||(g.id=Jm(g.startTime,g.endTime,x)),g.endTime>0&&d.push(g)},o.onparsingerror=function(g){m=g},o.onflush=function(){if(m){a(m);return}n(d)},l.forEach(g=>{if(p)if(Pc(g,"X-TIMESTAMP-MAP=")){p=!1,g.slice(16).split(",").forEach(v=>{Pc(v,"LOCAL:")?c=v.slice(6):Pc(v,"MPEGTS:")&&(h=parseInt(v.slice(7)))});try{f=ow(c)/1e3}catch(v){m=v}return}else g===""&&(p=!1);o.parse(g+`
|
|
1455
|
-
`)}),o.flush()}const Oc="stpp.ttml.im1t",jb=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,zb=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,uw={left:"start",center:"center",right:"end",start:"start",end:"end"};function w0(i,e,t,s){const r=
|
|
1456
|
-
`:(n=s.childNodes)!=null&&n.length?Qb(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function hw(i,e,t){const s="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=i!=null&&i.hasAttribute("style")?i.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(r=t[a]),n.reduce((o,l)=>{const d=Uc(e,s,l)||Uc(i,s,l)||Uc(r,s,l);return d&&(o[l]=d),o},{})}function Uc(i,e,t){return i&&i.hasAttributeNS(e,t)?i.getAttributeNS(e,t):null}function P0(i){return new Error(`Could not parse ttml timestamp ${i}`)}function $c(i,e){if(!i)return null;let t=Wb(i);return t===null&&(jb.test(i)?t=fw(i,e):zb.test(i)&&(t=mw(i,e))),t}function fw(i,e){const t=jb.exec(i),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 mw(i,e){const t=zb.exec(i),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 rl{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 pw{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=N0(),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(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(y.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(y.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new rl(this,"textTrack1"),t=new rl(this,"textTrack2"),s=new rl(this,"textTrack3"),r=new rl(this,"textTrack4");this.cea608Parser1=new C0(1,e,t),this.cea608Parser2=new C0(3,s,r)}addCues(e,t,s,r,n){let a=!1;for(let o=n.length;o--;){const l=n[o],d=gw(l[0],l[1],t,s);if(d>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],s),a=!0,d/(s-t)>.5))return}if(a||n.push([t,s]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,s,r)}else{const o=this.Cues.newCue(null,t,s,r);this.hls.trigger(y.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:r,timescale:n,trackId:a}){const{unparsedVttFrags:o}=this;s===J.MAIN&&(this.initPTS[t.cc]={baseTime:r,timescale:n,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(l=>{this.initPTS[l.frag.cc]?this.onFragLoaded(y.FRAG_LOADED,l):this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:l.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let r=0;r<s.textTracks.length;r++){const n=s.textTracks[r];if(O0(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:r}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)s[e]=o,Cn(s[e]),Bb(s[e],r);else{const l=this.createTextTrack("captions",n,a);l&&(l[e]=!0,s[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,r={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(y.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}createTextTrack(e,t,s){const r=this.media;if(r)return r.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:r}=this;Object.keys(r).forEach(n=>{Cn(r[n]),delete r[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=N0(),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++)Cn(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],r=s.some(n=>n.textCodec===Oc);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(Lb(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const a=this.media,o=a?Yl(a.textTracks):null;if(this.tracks.forEach((l,d)=>{let u;if(o){let c=null;for(let h=0;h<o.length;h++)if(o[h]&&O0(o[h],l)){c=o[h],o[h]=null;break}c&&(u=c)}if(u)Cn(u);else{const c=Xb(l);u=this.createTextTrack(c,l.name,l.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),o!=null&&o.length){const l=o.filter(d=>d!==null).map(d=>d.label);l.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(y.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const r=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!r)return;const n=`textTrack${r[1]}`,a=this.captionsProperties[n];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===J.MAIN){var s,r;const{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:d}=t.frag,u=(s=(r=t.part)==null?void 0:r.index)!=null?s:-1;n&&a&&(d!==o+1||d===o&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=d,this.lastPartIndex=u}}onFragLoaded(e,t){const{frag:s,payload:r}=t;if(s.type===J.SUBTITLE)if(r.byteLength){const n=s.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){const o=this.tracks[s.level],l=this.vttCCs;l[s.cc]||(l[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Oc?this._parseIMSC1(s,r):this._parseVTTs(t)}}else this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;w0(t,this.initPTS[e.cc],r=>{this._appendCues(r,e.level),s.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},r=>{s.logger.log(`Failed to parse IMSC1: ${r}`),s.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:r})})}_parseVTTs(e){var t;const{frag:s,payload:r}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[s.cc]&&o===-1){a.push(e);return}const l=this.hls,d=(t=s.initSegment)!=null&&t.data?li(s.initSegment.data,new Uint8Array(r)).buffer:r;dw(d,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,u=>{this._appendCues(u,s.level),l.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},u=>{const c=u.message==="Missing initPTS for VTT MPEGTS";c?a.push(e):this._fallbackToIMSC1(s,r),l.logger.log(`Failed to parse VTT cue: ${u}`),!(c&&o>s.cc)&&l.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:u})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||w0(t,this.initPTS[e.cc],()=>{s.textCodec=Oc,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const r=this.textTracks[t];if(!r||r.mode==="disabled")return;e.forEach(n=>Hb(r,n))}else{const r=this.tracks[t];if(!r)return;const n=r.default?"default":"subtitles"+t;s.trigger(y.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===J.SUBTITLE&&this.onFragLoaded(y.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:r}=t;if(!(s.type===J.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let n=0;n<r.length;n++){const a=r[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(r[n].pts,o[0]),this.cea608Parser2.addData(r[n].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:r,type:n}){const{media:a}=this;if(!(!a||a.currentTime<s)){if(!n||n==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>Xh(o[l],t,s))}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>Xh(o[l],t,r))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let r=2;for(let n=0;n<s;n++){const a=e[r++],o=127&e[r++],l=127&e[r++];if(o===0&&l===0)continue;if((4&a)!==0){const u=3&a;(u===0||u===1)&&(t[u].push(o),t[u].push(l))}}return t}}function Xb(i){return i.characteristics&&/transcribes-spoken-dialog/gi.test(i.characteristics)&&/describes-music-and-sound/gi.test(i.characteristics)?"captions":"subtitles"}function O0(i,e){return!!i&&i.kind===Xb(e)&&Yh(e,i)}function gw(i,e,t,s){return Math.min(e,s)-Math.max(i,t)}function N0(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const vw=/\s/,Ew={newCue(i,e,t,s){const r=[];let n,a,o,l,d;const u=self.VTTCue||self.TextTrackCue;for(let h=0;h<s.rows.length;h++)if(n=s.rows[h],o=!0,l=0,d="",!n.isEmpty()){var c;for(let p=0;p<n.chars.length;p++)vw.test(n.chars[p].uchar)&&o?l++:(d+=n.chars[p].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=Yb(d.trim()),m=Jm(e,t,f);i!=null&&(c=i.cues)!=null&&c.getCueById(m)||(a=new u(e,t,f),a.id=m,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a))}return i&&r.length&&(r.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),r.forEach(h=>Hb(i,h))),r}};function yw(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const bw=/(\d+)-(\d+)\/(\d+)/;class U0{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||Sw,this.controller=new self.AbortController,this.stats=new Cm}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 r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const n=Tw(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=l&&Q(l)?l:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},t.timeout),(yo(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(c=>{var h;this.response=this.loader=c;const f=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},d-(f-r.loading.start)),!c.ok){const{status:p,statusText:g}=c;throw new Iw(g||"fetch, bad network response",p,c)}r.loading.first=f,r.total=Aw(c.headers)||r.total;const m=(h=this.callbacks)==null?void 0:h.onProgress;return m&&Q(t.highWaterMark)?this.loadProgressively(c,r,e,t.highWaterMark,m):a?c.arrayBuffer():e.responseType==="json"?c.json():c.text()}).then(c=>{var h,f;const m=this.response;if(!m)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const p=c[o];p&&(r.loaded=r.total=p);const g={url:m.url,data:c,code:m.status},v=(h=this.callbacks)==null?void 0:h.onProgress;v&&!Q(t.highWaterMark)&&v(r,e,c,m),(f=this.callbacks)==null||f.onSuccess(g,r,e,m)}).catch(c=>{var h;if(self.clearTimeout(this.requestTimeout),r.aborted)return;const f=c&&c.code||0,m=c?c.message:null;(h=this.callbacks)==null||h.onError({code:f,text:m},e,c?c.details:null,r)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,r=0,n){const a=new ob,o=e.body.getReader(),l=()=>o.read().then(d=>{if(d.done)return a.dataLength&&n(t,s,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const u=d.value,c=u.length;return t.loaded+=c,c<r||a.dataLength?(a.push(u),a.dataLength>=r&&n(t,s,a.flush().buffer,e)):n(t,s,u.buffer,e),l()}).catch(()=>Promise.reject());return l()}}function Tw(i,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Oe({},i.headers))};return i.rangeEnd&&t.headers.set("Range","bytes="+i.rangeStart+"-"+String(i.rangeEnd-1)),t}function _w(i){const e=bw.exec(i);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Aw(i){const e=i.get("Content-Range");if(e){const s=_w(e);if(Q(s))return s}const t=i.get("Content-Length");if(t)return parseInt(t)}function Sw(i,e){return new self.Request(i.url,e)}class Iw extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const xw=/^age:\s*[\d.]+\s*$/im;class Zb{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 Cm,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,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return n(s,t.url)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),n(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},t,s,r)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=s.loadPolicy;if(r)for(const o in r)e.setRequestHeader(o,r[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=n&&Q(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const r=t.readyState,n=this.config;if(!s.aborted&&r>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const d=t.status,u=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){const m=u??t.response;if(m!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=t.responseType==="arraybuffer"?m.byteLength:m.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const g=(a=this.callbacks)==null?void 0:a.onProgress;g&&g(s,e,m,t);const v={url:t.responseURL,data:m,code:d};(o=this.callbacks)==null||o.onSuccess(v,s,e,t);return}}const c=n.loadPolicy.errorRetry,h=s.retry,f={url:e.url,data:void 0,code:d};if(Jd(c,h,!1,f))this.retry(c);else{var l;we.error(`${d} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:d,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Jd(e,t,!0))this.retry(e);else{var s;we.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=Om(e,s.retry),s.retry++,we.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&xw.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 Lw={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Rw=Ce(Ce({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Zb,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:BR,bufferController:DD,capLevelController:zm,errorController:WR,fpsController:CC,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:Qy,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:Lw},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},kw()),{},{subtitleStreamController:KC,subtitleTrackController:PC,timelineController:pw,audioStreamController:xD,audioTrackController:LD,emeController:$n,cmcdController:LC,contentSteeringController:kC,interstitialsController:GC});function kw(){return{cueHandler:Ew,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 Dw(i,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=Jh(i),r=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return r.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,d=[];n.forEach(u=>{const c=`${a}Loading${u}`,h=e[c];if(h!==void 0&&l){d.push(c);const f=s[o].default;switch(e[o]={default:f},u){case"TimeOut":f.maxLoadTimeMs=h,f.maxTimeToFirstByteMs=h;break;case"MaxRetry":f.errorRetry.maxNumRetry=h,f.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":f.errorRetry.retryDelayMs=h,f.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=h,f.timeoutRetry.maxRetryDelayMs=h;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${$e(e[o])}`)}),Ce(Ce({},s),e)}function Jh(i){return i&&typeof i=="object"?Array.isArray(i)?i.map(Jh):Object.keys(i).reduce((e,t)=>(e[t]=Jh(i[t]),e),{}):i}function Cw(i,e){const t=i.loader;t!==U0&&t!==Zb?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),i.progressive=!1):yw()&&(i.loader=U0,i.progressive=!0,i.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const jl=2,ww=.1,Mw=.05,Pw=100;class Ow extends Wy{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.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(Pw),this.mediaSource=t.mediaSource;const s=this.media=t.media;wt(s,"playing",this.onMediaPlaying),wt(s,"waiting",this.onMediaWaiting),wt(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(Nt(s,"playing",this.onMediaPlaying),Nt(s,"waiting",this.onMediaWaiting),Nt(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,r;const n=(s=this.hls)==null?void 0:s.config;if(!n)return;const a=this.media;if(!a)return;const{seeking:o}=a,l=this.seeking&&!o,d=!this.seeking&&o,u=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||l){l&&this.stallResolved(e);return}if(u){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1}));return}if(!ue.getBuffered(a).length){this.nudgeRetry=0;return}const c=ue.bufferInfo(a,e,0),h=c.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const x=$0(this.hls.inFlightFragments,e),S=c.len>jl,L=!h||x||h-e>jl&&!f.getPartialFragment(e);if(S||L)return;this.moved=!1}const m=(r=this.hls)==null?void 0:r.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(c.len>0)&&!h)return;const S=Math.max(h,c.start||0)-e,R=!!(m!=null&&m.live)?m.targetduration*2:jl,I=nl(e,f);if(S>0&&(S<=R||I)){a.paused||this._trySkipBufferHole(I);return}}const p=n.detectStallWithCurrentTimeMs,g=self.performance.now(),v=this.waiting;let b=this.stalled;if(b===null)if(v>0&&g-v<p)b=this.stalled=v;else{this.stalled=g;return}const E=g-b;if(!o&&(E>=p||v)&&this.hls){var T;if(((T=this.mediaSource)==null?void 0:T.readyState)==="ended"&&!(m!=null&&m.live)&&Math.abs(e-(m?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return}const A=ue.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(A,E,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(y.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&r&&r.length>1&&e>r.end(0)){const n=ue.bufferedInfo(ue.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){const a=ue.timeRangesToArray(r),o=ue.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const l=ue.bufferedInfo(a,e,0).bufferedIndex,d=a[o].end,u=a[o+1].start;if((l===-1||l>o)&&u-d<1&&e-d<2){const c=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${u} buffered index: ${l}`);this.warn(c.message),this.media.currentTime+=1e-6;let h=nl(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);const f=ue.bufferInfo(this.media,e,0);this.hls.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,s){var r,n;const{fragmentTracker:a,media:o}=this,l=(r=this.hls)==null?void 0:r.config;if(!o||!a||!l)return;const d=(n=this.hls)==null?void 0:n.latestLevelDetails,u=nl(s,a);if((u||d!=null&&d.live&&s<d.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;const c=e.buffered,h=this.adjacentTraversal(e,s);(c&&c.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-s<l.maxBufferHole||h))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,r=e.nextStart;if(s&&r){const n=s.getFragAtPos(t,J.MAIN),a=s.getFragAtPos(r,J.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:r,stalled:n}=this;if(!r&&n!==null&&s&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${$e(e)})`);this.warn(a.message),t.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:r}=this,n=(t=this.hls)==null?void 0:t.config;if(!r||!s||!n)return 0;const a=r.currentTime,o=ue.bufferInfo(r,a,0),l=a<o.start?o.start:o.nextStart;if(l&&this.hls){const u=o.len<=n.maxBufferHole,c=o.len>0&&o.len<1&&r.readyState<3,h=l-a;if(h>0&&(u||c)){if(h>n.maxBufferHole){let m=!1;if(a===0){const p=s.getAppendedFrag(0,J.MAIN);p&&l<p.end&&(m=!0)}if(!m&&e){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||$0(this.hls.inFlightFragments,l))return 0;let g=!1,v=e.end;for(;v<l;){const b=nl(v,s);if(b)v+=b.duration;else{g=!0;break}}if(g)return 0}}const f=Math.max(l+Mw,a+ww);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,r.currentTime=f,!(e!=null&&e.gap)){const m=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),p={type:ie.MEDIA_ERROR,details:w.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(y.ERROR,p)}return f}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:r}=this,n=t?.config;if(!s||!n)return 0;const a=s.currentTime;if(this.nudgeRetry++,r<n.nudgeMaxRetry){const o=a+(r+1)*n.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),s.currentTime=o,t.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function $0(i,e){const t=F0(i.main);if(t&&t.start<=e)return t;const s=F0(i.audio);return s&&s.start<=e?s:null}function F0(i){if(!i)return null;switch(i.state){case O.IDLE:case O.STOPPED:case O.ENDED:case O.ERROR:return null}return i.frag}function nl(i,e){return e.getAppendedFrag(i,J.MAIN)||e.getPartialFragment(i)}const Nw=.25;function ef(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Fc(i,e,t,s,r){let n=new i(e,t,"");try{n.value=s,r&&(n.type=r)}catch{n=new i(e,t,$e(r?Ce({type:r},s):s))}return n}const al=(()=>{const i=ef();try{i&&new i(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Uw{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(y.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Cn(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 Bb(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:r}=this.hls.config;if(!s&&!r)return;const{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=ef();if(a)for(let o=0;o<n.length;o++){const l=n[o].type;if(l===zt.emsg&&!s||!r)continue;const d=mb(n[o].data),u=n[o].pts;let c=u+n[o].duration;c>al&&(c=al),c-u<=0&&(c=u+Nw);for(let f=0;f<d.length;f++){const m=d[f];if(!pb(m)){this.updateId3CueEnds(u,l);const p=Fc(a,u,c,m,l);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var s;const r=(s=this.id3Track)==null?void 0:s.cues;if(r)for(let n=r.length;n--;){const a=r[n];a.type===t&&a.startTime<e&&a.endTime===al&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:r}){const{id3Track:n,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let d;r==="audio"?d=u=>u.type===zt.audioId3&&l:r==="video"?d=u=>u.type===zt.emsg&&o:d=u=>u.type===zt.audioId3&&l||u.type===zt.emsg&&o,Xh(n,t,s,d)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;const o=ef();if(s&&r&&!a){const{fragmentStart:p,fragmentEnd:g}=e;let v=this.assetCue;v?(v.startTime=p,v.endTime=g):o&&(v=this.assetCue=Fc(o,p,g,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:d}=e,u=Object.keys(d);let c=this.dateRangeCuesAppended;if(l&&t){var h;if((h=l.cues)!=null&&h.length){const p=Object.keys(c).filter(g=>!u.includes(g));for(let g=p.length;g--;){var f;const v=p[g],b=(f=c[v])==null?void 0:f.cues;delete c[v],b&&Object.keys(b).forEach(E=>{const T=b[E];if(T){T.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(T)}catch{}}})}}else c=this.dateRangeCuesAppended={}}const m=e.fragments[e.fragments.length-1];if(!(u.length===0||!Q(m?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<u.length;p++){const g=u[p],v=d[g],b=v.startTime,E=c[g],T=E?.cues||{};let A=E?.durationKnown||!1,x=al;const{duration:S,endDate:L}=v;if(L&&S!==null)x=b+S,A=!0;else if(v.endOnNext&&!A){const I=u.reduce((M,B)=>{if(B!==v.id){const W=d[B];if(W.class===v.class&&W.startDate>v.startDate&&(!M||v.startDate<M.startDate))return W}return M},null);I&&(x=I.startTime,A=!0)}const R=Object.keys(v.attr);for(let I=0;I<R.length;I++){const M=R[I];if(!rk(M))continue;const B=T[M];if(B)A&&!(E!=null&&E.durationKnown)?B.endTime=x:Math.abs(B.startTime-b)>.01&&(B.startTime=b,B.endTime=x);else if(o){let W=v.attr[M];nk(M)&&(W=Iy(W));const K=Fc(o,b,x,{key:M,data:W},zt.dateRange);K&&(K.id=g,this.id3Track.addCue(K),T[M]=K,a&&(M==="X-ASSET-LIST"||M==="X-ASSET-URL")&&K.addEventListener("enter",this.onEventCueEnter))}}c[g]={cues:T,dateRange:v,durationKnown:A}}}}}class $w{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 r=this.computeLatency();if(r===null)return;this._latency=r;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!s.live)return;const o=this.targetLatency;if(o===null)return;const l=r-o,d=Math.min(this.maxLatency,o+s.targetduration);if(l<d&&l>.05&&this.forwardBufferLength>1){const c=Math.min(2,Math.max(1,a)),h=Math.round(2/(1+Math.exp(-.75*l-this.edgeStalled))*20)/20,f=Math.min(c,Math.max(1,h));this.changeMediaPlaybackRate(t,f)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:s,targetduration:r}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let d=o&&s||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||d===0)&&(d=n!==void 0?n:a*r);const u=r;return d+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 r=s.edge,n=e-t-this.edgeStalled,a=r-s.totalduration,o=r-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(a,n),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.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===w.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,r;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(r=this.targetLatency)==null?void 0:r.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 Fw extends jm{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(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.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,r=[],n={},a={};let o=!1,l=!1,d=!1;t.levels.forEach(u=>{const c=u.attrs;let{audioCodec:h,videoCodec:f}=u;h&&(u.audioCodec=h=zd(h,s)||void 0),f&&(f=u.videoCodec=TR(f));const{width:m,height:p,unknownCodecs:g}=u,v=g?.length||0;if(o||(o=!!(m&&p)),l||(l=!!f),d||(d=!!h),v||h&&!this.isAudioSupported(h)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${c.CODECS}"`);return}const{CODECS:b,"FRAME-RATE":E,"HDCP-LEVEL":T,"PATHWAY-ID":A,RESOLUTION:x,"VIDEO-RANGE":S}=c,R=`${`${A||"."}-`}${u.bitrate}-${x}-${E}-${b}-${S}-${T}`;if(n[R])if(n[R].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const I=a[R]+=1;u.attrs["PATHWAY-ID"]=new Array(I+1).join(".");const M=this.createLevel(u);n[R]=M,r.push(M)}else n[R].addGroupId("audio",c.AUDIO),n[R].addGroupId("text",c.SUBTITLES);else{const I=this.createLevel(u);n[R]=I,a[R]=1,r.push(I)}}),this.filterAndSortMediaOptions(r,t,o,l,d)}createLevel(e){const t=new go(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const r=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(r.message),t.supportedResult=Uy(r,[])}return t}isAudioSupported(e){return mo(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return mo(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,r,n){var a;let o=[],l=[],d=e;const u=((a=t.stats)==null?void 0:a.parsing)||{};if((s||r)&&n&&(d=d.filter(({videoCodec:b,videoRange:E,width:T,height:A})=>(!!b||!!(T&&A))&&CR(E))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let b="no level with compatible codecs found in manifest",E=b;t.levels.length&&(E=`one or more CODECS in variant not supported: ${$e(t.levels.map(A=>A.attrs.CODECS).filter((A,x,S)=>S.indexOf(A)===x))}`,this.warn(E),b+=` (${E})`);const T=new Error(b);this.hls.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:T,reason:E})}}),u.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(b=>!b.audioCodec||this.isAudioSupported(b.audioCodec)),B0(o)),t.subtitles&&(l=t.subtitles,B0(l));const c=d.slice(0);d.sort((b,E)=>{if(b.attrs["HDCP-LEVEL"]!==E.attrs["HDCP-LEVEL"])return(b.attrs["HDCP-LEVEL"]||"")>(E.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&b.height!==E.height)return b.height-E.height;if(b.frameRate!==E.frameRate)return b.frameRate-E.frameRate;if(b.videoRange!==E.videoRange)return Qd.indexOf(b.videoRange)-Qd.indexOf(E.videoRange);if(b.videoCodec!==E.videoCodec){const T=Cg(b.videoCodec),A=Cg(E.videoCodec);if(T!==A)return A-T}if(b.uri===E.uri&&b.codecSet!==E.codecSet){const T=jd(b.codecSet),A=jd(E.codecSet);if(T!==A)return A-T}return b.averageBitrate!==E.averageBitrate?b.averageBitrate-E.averageBitrate:0});let h=c[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==c.length)){for(let b=0;b<c.length;b++)if(c[b].pathwayId===d[0].pathwayId){h=c[b];break}}this._levels=d;for(let b=0;b<d.length;b++)if(d[b]===h){var f;this._firstLevel=b;const E=h.bitrate,T=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${E}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){const A=Math.min(E,this.hls.config.abrEwmaDefaultEstimateMax);A>T&&T===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=A)}break}const m=n&&!r,p=this.hls.config,g=!!(p.audioStreamController&&p.audioTrackController),v={levels:d,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:g&&!m&&o.some(b=>!!b.url)};u.end=performance.now(),this.hls.trigger(y.MANIFEST_PARSED,v)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const u=new Error("invalid level idx"),c=e<0;if(this.hls.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.LEVEL_SWITCH_ERROR,level:e,fatal:c,error:u,reason:u.message}),c)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,r=this.currentLevel,n=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&r&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${s}${n?" with Pathway "+n:""}`);const l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(y.LEVEL_SWITCHING,l);const d=a.details;if(!d||d.live){const u=this.switchParams(a.uri,r?.details,d);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(r=>t.indexOf(r)!==-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===pe.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===J.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(n=>!!s[n]))return;const r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(e,t){var s;const{level:r,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(r,t,l)}else(s=t.deliveryDirectives)!=null&&s.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a?.age;this.log(`Loading level index ${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(y.LEVEL_LOADING,{url:s,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const s=this._levels.filter((n,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));rb(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 r=s.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(y.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(y.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function B0(i){const e={};i.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function Jb(){return self.SourceBuffer||self.WebKitSourceBuffer}function eT(){if(!zs())return!1;const e=Jb();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Bw(){if(!eT())return!1;const i=zs();return typeof i?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>i.isTypeSupported(po(e,"video")))||["mp4a.40.2","fLaC"].some(e=>i.isTypeSupported(po(e,"audio"))))}function Hw(){var i;const e=Jb();return typeof(e==null||(i=e.prototype)==null?void 0:i.changeType)=="function"}const Gw=100;class Kw extends Bm{constructor(e,t,s){super(e,t,s,"stream-controller",J.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 r=this.media,n=r?r.currentTime:null;if(n===null||!Q(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;const a=this.getFwdBufferInfoAtPos(r,n,J.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${n} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.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:r}=this;if(this.stopLoad(),this.setInterval(Gw),this.level=-1,!this.startFragRequested){let n=r.startLevel;n===-1&&(r.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=r.firstAutoLevel),r.nextLoadLevel=n,this.level=r.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=O.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=O.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case O.WAITING_LEVEL:{const{levels:e,level:t}=this,s=e?.[t],r=s?.details;if(r&&(!r.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(r))break;this.state=O.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=O.IDLE;break}break}case O.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===O.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:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[n]))return;const a=s[n],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(y.BUFFER_EOS,p),this.state=O.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;const d=a.details;if(!d||this.state===O.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=O.WAITING_LEVEL,this.startFragRequested=!1;return}const u=o.len,c=this.getMaxBufferLength(a.maxBitrate);if(u>=c)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(h,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&et(f)&&this.fragmentTracker.getState(f)!==gt.OK){var m;const g=((m=this.backtrackFragment)!=null?m:f).sn-d.startSN,v=d.fragments[g-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){const g=this.audioOnly&&!this.altAudio?Ue.AUDIO:Ue.VIDEO,v=(g===Ue.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,g,J.MAIN)}f=this.getNextFragmentLoopLoading(f,d,o,J.MAIN,c)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(e,t,s){const r=this.fragmentTracker.getState(e);r===gt.NOT_LOADED||r===gt.PARTIAL?et(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,J.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const n=this.getLevelDetails();if(n!=null&&n.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,l=e[o],d=this.fragLastKbps;d&&this.fragCurrent?s=this.fragCurrent.duration*l.maxBitrate/(1e3*d)+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 l=o.maxStartPTS?o.maxStartPTS:o.start,d=o.duration,u=Math.max(a.end,l+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(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 O.KEY_LOADING:case O.FRAG_LOADING:case O.FRAG_LOADING_WAITING_RETRY:case O.PARSING:case O.PARSED:this.state=O.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;wt(s,"playing",this.onMediaPlaying),wt(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(Nt(s,"playing",this.onMediaPlaying),Nt(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(y.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,r=!1;for(let n=0;n<t.levels.length;n++){const a=t.levels[n].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&r&&!Hw(),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!==O.IDLE)return;const r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=O.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:r,startFragRequested:n}=this,a=t.level,o=t.details,l=o.totalduration;if(!r){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const d=t.levelInfo,u=this.fragCurrent;u&&(this.state===O.FRAG_LOADING||this.state===O.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let c=0;if(o.live||(s=d.details)!=null&&s.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,d.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(d.details=o,this.levelLastLoaded=d,n||this.setStartPosition(o,c),this.hls.trigger(y.LEVEL_UPDATED,{details:o,level:a}),this.state===O.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=O.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const r=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,l=n>=a-t.maxFragLookUpTolerance&&n<=o;if(r!==null&&s.duration>r&&(n<r||!l)){const u=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&s.readyState<4||n<o-u)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),s.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var d;const c=ue.bufferInfo(s,r,0);if(!((d=c.buffered)!=null&&d.length)){s.currentTime=r;return}if(c.start<=n){s.currentTime=r;return}const{nextStart:f}=ue.bufferedInfo(c.buffered,n,0);f&&(s.currentTime=f)}else s.currentTime=r}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:r,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=a[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}const l=o.details;if(!l){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const d=o.videoCodec,u=l.PTSKnown||!l.live,c=(t=s.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new xb(this.hls,J.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=r?r.index:-1,p=m!==-1,g=new Um(s.level,s.sn,s.stats.chunkCount,n.byteLength,m,p),v=this.initPTS[s.cc];f.push(n,c,h,d,s,r,l.totalduration,u,g,v)}onAudioTrackSwitching(e,t){const s=this.hls,r=this.altAudio!==0;if(Xd(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(r){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(y.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(y.AUDIO_TRACK_SWITCHED,t)}),s.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(y.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=Xd(t.url,this.hls);if(s){const r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let r,n,a=!1;for(const o in s){const l=s[o];if(l.id==="main"){if(n=o,r=l,o==="video"){const d=s[o];d&&(this.videoBuffer=d.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:r}=t,n=s.type===J.MAIN;if(n){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===O.PARSED&&(this.state=O.IDLE);return}const o=r?r.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),et(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,r)}const a=this.media;a&&(!this._hasEnoughToStart&&ue.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=O.ERROR;return}switch(t.details){case w.FRAG_GAP:case w.FRAG_PARSING_ERROR:case w.FRAG_DECRYPT_ERROR:case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(J.MAIN,t);break;case w.LEVEL_LOAD_ERROR:case w.LEVEL_LOAD_TIMEOUT:case w.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===O.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===pe.LEVEL&&(this.state=O.IDLE);break;case w.BUFFER_ADD_CODEC_ERROR:case w.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case w.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case w.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=O.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Ue.AUDIO||!this.altAudio){const s=(t===Ue.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,J.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 r=this.timelineOffset;r&&s&&(s+=r);const n=this.getLevelDetails(),a=ue.getBuffered(e),o=a.length?a.start(0):0,l=o-s,d=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<d||this.loadingParts&&l<2*(n?.partTarget||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),s+=l,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:r}=this,n=s?.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=O.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),r.trigger(y.FRAG_LOADED,s),n.bitrateTest=!1}).catch(s=>{this.state===O.STOPPED||this.state===O.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}const{frag:o,part:l,level:d}=a,{video:u,text:c,id3:h,initSegment:f}=r,{details:m}=d,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=O.PARSING,f){const g=f.tracks;if(g){const T=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(d,g,T,n),s.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:T,id:t,tracks:g})}const v=f.initPTS,b=f.timescale,E=this.initPTS[o.cc];if(Q(v)&&(!E||E.baseTime!==v||E.timescale!==b)){const T=f.trackId;this.initPTS[o.cc]={baseTime:v,timescale:b,trackId:T},s.trigger(y.INIT_PTS_FOUND,{frag:o,id:t,initPTS:v,timescale:b,trackId:T})}}if(u&&m){p&&u.type==="audiovideo"&&this.logMuxedErr(o);const g=m.fragments[o.sn-1-m.startSN],v=o.sn===m.startSN,b=!g||o.cc>g.cc;if(r.independent!==!1){const{startPTS:E,endPTS:T,startDTS:A,endDTS:x}=u;if(l)l.elementaryStreams[u.type]={startPTS:E,endPTS:T,startDTS:A,endDTS:x};else if(u.firstKeyFrame&&u.independent&&n.id===1&&!b&&(this.couldBacktrack=!0),u.dropped&&u.independent){const S=this.getMainFwdBufferInfo(),L=(S?S.end:this.getLoadPosition())+this.config.maxBufferHole,R=u.firstKeyFramePTS?u.firstKeyFramePTS:E;if(!v&&L<R-this.config.maxBufferHole&&!b){this.backtrack(o);return}else b&&(o.gap=!0);o.setElementaryStreamInfo(u.type,o.start,T,o.start,x,!0)}else v&&E-(m.appliedTimelineOffset||0)>jl&&(o.gap=!0);o.setElementaryStreamInfo(u.type,E,T,A,x),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,l,n,v||b)}else if(v||b)o.gap=!0;else{this.backtrack(o);return}}if(p){const{startPTS:g,endPTS:v,startDTS:b,endDTS:E}=p;l&&(l.elementaryStreams[Ue.AUDIO]={startPTS:g,endPTS:v,startDTS:b,endDTS:E}),o.setElementaryStreamInfo(Ue.AUDIO,g,v,b,E),this.bufferFragmentData(p,o,l,n)}if(m&&h!=null&&h.samples.length){const g={id:t,frag:o,details:m,samples:h.samples};s.trigger(y.FRAG_PARSING_METADATA,g)}if(m&&c){const g={id:t,frag:o,details:m,samples:c.samples};s.trigger(y.FRAG_PARSING_USERDATA,g)}}logMuxedErr(e){this.warn(`${et(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,r){if(this.state!==O.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:n,video:a,audiovideo:o}=t;if(n){const d=e.audioCodec;let u=Hl(n.codec,d);u==="mp4a"&&(u="mp4a.40.5");const c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");const h=n.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&c.indexOf("firefox")===-1&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),d&&d!==u&&this.log(`Swapping manifest audio codec "${d}" for "${u}"`),n.levelCodec=u,n.id=J.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${u||""}/${d||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=J.MAIN;const d=a.codec;if(d?.length===4)switch(d){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||""}/${d}]${a.codec!==d?" 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 l=Object.keys(t);if(l.length){if(this.hls.trigger(y.BUFFER_CODECS,t),!this.hls)return;l.forEach(d=>{const c=t[d].initSegment;c!=null&&c.byteLength&&this.hls.trigger(y.BUFFER_APPENDING,{type:d,data:c,frag:s,part:null,chunkMeta:r,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,J.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e?.[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=O.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(ue.isBuffered(e,s)?t=this.getAppendedFrag(s):ue.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const r=this.fragPlaying,n=t.level;(!r||t.sn!==r.sn||r.level!==n)&&(this.fragPlaying=t,this.hls.trigger(y.FRAG_CHANGED,{frag:t}),(!r||r.level!==n)&&this.hls.trigger(y.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return Q(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(Q(t)){const s=this.getLevelDetails(),r=this.currentFrag||(s?Mr(null,s.fragments,t):null);if(r){const n=r.programDateTime;if(n!==null){const a=n+(t-r.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 Vw extends di{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const r=this.keyIdToKeyInfo[s].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=w.KEY_LOAD_ERROR,s,r,n){return new fs({type:ie.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:s,networkDetails:r})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,n=t.length;r<n;r++){const a=t[r];if(e.cc<=a.cc&&(!et(e)||!et(a)||e.sn<a.sn)||!s&&r==n-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);const l=Kl(o);if(l)return this.emeController.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){const r=ka(this.config);if(r.length)return this.emeController.getKeySystemAccess(r)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,r;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const d=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,d))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=Bc(n);let l=this.keyIdToKeyInfo[o];if((s=l)!=null&&s.decryptdata.key)return n.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&(r=l)!=null&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(u=>{const{keyInfo:c}=u;return n.key=c.decryptdata.key,{frag:e,keyInfo:c}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${n.keyId?" keyId: "+It(n.keyId):""} URI: ${n.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&(r=t.initSegment)!=null&&r.data){const a=dR(t.initSegment.data);if(a.length){let o=a[0];o.some(l=>l!==0)?(this.log(`Using keyId found in init segment ${It(o)}`),js.setKeyIdForUri(e.decryptdata.uri,o)):(o=js.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${It(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!et(t))return Promise.resolve(s);const n=this.emeController.loadKey(s);return(e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,s))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,r=s.loader,n=new r(s);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=s.keyLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{const{frag:g,keyInfo:v}=m,b=Bc(v.decryptdata);if(!g.decryptdata||v!==this.keyIdToKeyInfo[b])return o(this.createKeyLoadError(g,w.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));v.decryptdata.key=g.decryptdata.key=new Uint8Array(h.data),g.keyLoader=null,v.loader=null,a({frag:g,keyInfo:v})},onError:(h,f,m,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),m,Ce({url:l.url,data:void 0},h)))},onTimeout:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};n.load(l,u,c)})}resetLoader(e){const{frag:t,keyInfo:s,url:r}=e,n=s.loader;t.keyLoader===n&&(t.keyLoader=null,s.loader=null);const a=Bc(s.decryptdata)||r;delete this.keyIdToKeyInfo[a],n&&n.destroy()}}function Bc(i){if(i.keyFormat!==xt.FAIRPLAY){const e=i.keyId;if(e)return It(e)}return i.uri}function H0(i){const{type:e}=i;switch(e){case pe.AUDIO_TRACK:return J.AUDIO;case pe.SUBTITLE_TRACK:return J.SUBTITLE;default:return J.MAIN}}function Hc(i,e){let t=i.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Ww{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(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,r=t.loader,n=s||r,a=new n(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:pe.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:r,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:s,level:r,pathwayId:n,responseType:"text",type:pe.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){const{id:s,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:pe.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:s,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:pe.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const s=this.loaders[pe.LEVEL];if(s){const r=s.context;r&&!t.levels.some(n=>n===r.levelOrTrack)&&(s.abort(),delete this.loaders[pe.LEVEL])}}load(e){var t;const s=this.hls.config;let r=this.getInternalLoader(e);if(r){const d=this.hls.logger,u=r.context;if(u&&u.levelOrTrack===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}let n;if(e.type===pe.MANIFEST?n=s.manifestLoadPolicy.default:n=Oe({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),Q((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===pe.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===pe.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===pe.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){const u=d.partTarget,c=d.targetduration;if(u&&c){const h=Math.max(u*3,c*.8)*1e3;n=Oe({},n,{maxTimeToFirstByteMs:Math.min(h,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,n.maxTimeToFirstByteMs)})}}}const a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(d,u,c,h)=>{const f=this.getInternalLoader(c);this.resetInternalLoader(c.type);const m=d.data;u.parsing.start=performance.now(),Xi.isMediaPlaylist(m)||c.type!==pe.MANIFEST?this.handleTrackOrLevelPlaylist(d,u,c,h||null,f):this.handleMasterPlaylist(d,u,c,h)},onError:(d,u,c,h)=>{this.handleNetworkError(u,c,!1,d,h)},onTimeout:(d,u,c)=>{this.handleNetworkError(u,c,!0,void 0,d)}};r.load(e,o,l)}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,r){const n=this.hls,a=e.data,o=Hc(e,s),l=Xi.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,l.playlistParsingError,r,t);return}const{contentSteering:d,levels:u,sessionData:c,sessionKeys:h,startTimeOffset:f,variableList:m}=l;this.variableList=m,u.forEach(b=>{const{unknownCodecs:E}=b;if(E){const{preferManagedMediaSource:T}=this.hls.config;let{audioCodec:A,videoCodec:x}=b;for(let S=E.length;S--;){const L=E[S];mo(L,"audio",T)?(b.audioCodec=A=A?`${A},${L}`:L,Xn.audio[A.substring(0,4)]=2,E.splice(S,1)):mo(L,"video",T)&&(b.videoCodec=x=x?`${x},${L}`:L,Xn.video[x.substring(0,4)]=2,E.splice(S,1))}}});const{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":v}=Xi.parseMasterPlaylistMedia(a,o,l);p.length&&!p.some(E=>!E.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ye({}),bitrate:0,url:""})),n.trigger(y.MANIFEST_LOADED,{levels:u,audioTracks:p,subtitles:g,captions:v,contentSteering:d,url:o,stats:t,networkDetails:r,sessionData:c,sessionKeys:h,startTimeOffset:f,variableList:m})}handleTrackOrLevelPlaylist(e,t,s,r,n){const a=this.hls,{id:o,level:l,type:d}=s,u=Hc(e,s),c=Q(l)?l:Q(o)?o:0,h=H0(s),f=Xi.parseLevelPlaylist(e.data,u,c,h,0,this.variableList);if(d===pe.MANIFEST){const m={attrs:new Ye({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=t.loading.start+tb(f,0),a.trigger(y.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:u,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,r,n)}handleManifestParsingError(e,t,s,r,n){this.hls.trigger(y.ERROR,{type:ie.NETWORK_ERROR,details:w.MANIFEST_PARSING_ERROR,fatal:t.type===pe.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:r,stats:n})}handleNetworkError(e,t,s=!1,r,n){let a=`A network ${s?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===pe.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===pe.AUDIO_TRACK||e.type===pe.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=w.UNKNOWN,d=!1;const u=this.getInternalLoader(e);switch(e.type){case pe.MANIFEST:l=s?w.MANIFEST_LOAD_TIMEOUT:w.MANIFEST_LOAD_ERROR,d=!0;break;case pe.LEVEL:l=s?w.LEVEL_LOAD_TIMEOUT:w.LEVEL_LOAD_ERROR,d=!1;break;case pe.AUDIO_TRACK:l=s?w.AUDIO_TRACK_LOAD_TIMEOUT:w.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case pe.SUBTITLE_TRACK:l=s?w.SUBTITLE_TRACK_LOAD_TIMEOUT:w.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(e.type);const c={type:ie.NETWORK_ERROR,details:l,fatal:d,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:n};if(r){const h=t?.url||e.url;c.response=Ce({url:h,data:void 0},r)}this.hls.trigger(y.ERROR,c)}handlePlaylistLoaded(e,t,s,r,n,a){const o=this.hls,{type:l,level:d,levelOrTrack:u,id:c,groupId:h,deliveryDirectives:f}=r,m=Hc(t,r),p=H0(r);let g=typeof r.level=="number"&&p===J.MAIN?d:void 0;const v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(y.ERROR,{type:ie.NETWORK_ERROR,details:w.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:v,reason:v.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const b=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(y.ERROR,{type:ie.NETWORK_ERROR,details:w.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:b,reason:b.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:s});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case pe.MANIFEST:case pe.LEVEL:if(g){if(!u)g=0;else if(u!==o.levels[g]){const b=o.levels.indexOf(u);b>-1&&(g=b)}}o.trigger(y.LEVEL_LOADED,{details:e,levelInfo:u||o.levels[0],level:g||0,id:c||0,stats:s,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:l===pe.MANIFEST});break;case pe.AUDIO_TRACK:o.trigger(y.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:h||"",stats:s,networkDetails:n,deliveryDirectives:f});break;case pe.SUBTITLE_TRACK:o.trigger(y.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:h||"",stats:s,networkDetails:n,deliveryDirectives:f});break}}}class Vs{static get version(){return vo}static isMSESupported(){return eT()}static isSupported(){return Bw()}static getMediaSource(){return zs()}static get Events(){return y}static get MetadataSchema(){return zt}static get ErrorTypes(){return ie}static get ErrorDetails(){return w}static get DefaultConfig(){return Vs.defaultConfig?Vs.defaultConfig:Rw}static set DefaultConfig(e){Vs.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 Hm,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=XL(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=Dw(Vs.DefaultConfig,e,t);this.userConfig=e,s.progressive&&Cw(s,t);const{abrController:r,bufferController:n,capLevelController:a,errorController:o,fpsController:l}=s,d=new o(this),u=this.abrController=new r(this),c=new qR(this),h=s.interstitialsController,f=h?this.interstitialsController=new h(this,Vs):null,m=this.bufferController=new n(this,c),p=this.capLevelController=new a(this),g=new l(this),v=new Ww(this),b=s.contentSteeringController,E=b?new b(this):null,T=this.levelController=new Fw(this,E),A=new Uw(this),x=new Vw(this.config,this.logger),S=this.streamController=new Kw(this,c,x),L=this.gapController=new Ow(this,c);p.setStreamController(S),g.setStreamController(S);const R=[v,T,S];f&&R.splice(1,0,f),E&&R.splice(1,0,E),this.networkControllers=R;const I=[u,m,L,p,g,A,c];this.audioTrackController=this.createController(s.audioTrackController,R);const M=s.audioStreamController;M&&R.push(this.audioStreamController=new M(this,c,x)),this.subtitleTrackController=this.createController(s.subtitleTrackController,R);const B=s.subtitleStreamController;B&&R.push(this.subtititleStreamController=new B(this,c,x)),this.createController(s.timelineController,I),x.emeController=this.emeController=this.createController(s.emeController,I),this.cmcdController=this.createController(s.cmcdController,I),this.latencyController=this.createController($w,I),this.coreComponents=I,R.push(d);const W=d.onErrorOut;typeof W=="function"&&this.on(y.ERROR,W,d),this.on(y.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,r){this._emitter.off(e,t,s,r)}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 r=e===y.ERROR;this.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,fatal:r,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(y.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,r=t?e:{media:s};this._media=s,this.trigger(y.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(y.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(y.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,r=this._url=Dm.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&s&&(s!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(y.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={[J.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[J.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[J.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=OC()),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){DR(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 r=0;r<s;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,s)for(let n=r;n--;){const a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=s)return n}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}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=By(t);return $y(e,s,navigator.mediaCapabilities)}}Vs.defaultConfig=void 0;var Ee=Vs,Fe={VIDEO:"video",THUMBNAIL:"thumbnail",STORYBOARD:"storyboard",DRM:"drm"},ae={NOT_AN_ERROR:0,NETWORK_OFFLINE:2000002,NETWORK_UNKNOWN_ERROR:2e6,NETWORK_NO_STATUS:2000001,NETWORK_INVALID_URL:24e5,NETWORK_NOT_FOUND:2404e3,NETWORK_NOT_READY:2412e3,NETWORK_GENERIC_SERVER_FAIL:25e5,NETWORK_TOKEN_MISSING:2403201,NETWORK_TOKEN_MALFORMED:2412202,NETWORK_TOKEN_EXPIRED:2403210,NETWORK_TOKEN_AUD_MISSING:2403221,NETWORK_TOKEN_AUD_MISMATCH:2403222,NETWORK_TOKEN_SUB_MISMATCH:2403232,ENCRYPTED_ERROR:5e6,ENCRYPTED_UNSUPPORTED_KEY_SYSTEM:5000001,ENCRYPTED_GENERATE_REQUEST_FAILED:5000002,ENCRYPTED_UPDATE_LICENSE_FAILED:5000003,ENCRYPTED_UPDATE_SERVER_CERT_FAILED:5000004,ENCRYPTED_CDM_ERROR:5000005,ENCRYPTED_OUTPUT_RESTRICTED:5000006,ENCRYPTED_MISSING_TOKEN:5000002},zu=i=>i===Fe.VIDEO?"playback":i,Ps=class Da extends Error{constructor(e,t=Da.MEDIA_ERR_CUSTOM,s,r){var n;super(e),this.name="MediaError",this.code=t,this.context=r,this.fatal=s??(t>=Da.MEDIA_ERR_NETWORK&&t<=Da.MEDIA_ERR_ENCRYPTED),this.message||(this.message=(n=Da.defaultMessages[this.code])!=null?n:"")}};Ps.MEDIA_ERR_ABORTED=1,Ps.MEDIA_ERR_NETWORK=2,Ps.MEDIA_ERR_DECODE=3,Ps.MEDIA_ERR_SRC_NOT_SUPPORTED=4,Ps.MEDIA_ERR_ENCRYPTED=5,Ps.MEDIA_ERR_CUSTOM=100,Ps.defaultMessages={1:"You aborted the media playback",2:"A network error caused the media download to fail.",3:"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.",4:"An unsupported error occurred. The server or network failed, or your browser does not support this format.",5:"The media is encrypted and there are no keys to decrypt it."};var X=Ps,qw=i=>i==null,ep=(i,e)=>qw(e)?!1:i in e,tf={ANY:"any",MUTED:"muted"},ke={ON_DEMAND:"on-demand",LIVE:"live",UNKNOWN:"unknown"},Zi={MSE:"mse",NATIVE:"native"},Ca={HEADER:"header",QUERY:"query",NONE:"none"},nu=Object.values(Ca),vs={M3U8:"application/vnd.apple.mpegurl",MP4:"video/mp4"},G0={HLS:vs.M3U8};[...Object.values(vs)];var ol={upTo720p:"720p",upTo1080p:"1080p",upTo1440p:"1440p",upTo2160p:"2160p"},Xr={noLessThan480p:"480p",noLessThan540p:"540p",noLessThan720p:"720p",noLessThan1080p:"1080p",noLessThan1440p:"1440p",noLessThan2160p:"2160p"},Yw="en",sf={code:Yw},nt=(i,e,t,s,r=i)=>{r.addEventListener(e,t,s),i.addEventListener("teardown",()=>{r.removeEventListener(e,t)},{once:!0})};function jw(i,e,t){e&&t>e&&(t=e);for(let s=0;s<i.length;s++)if(i.start(s)<=t&&i.end(s)>=t)return!0;return!1}var tp=i=>{let e=i.indexOf("?");if(e<0)return[i];let t=i.slice(0,e),s=i.slice(e);return[t,s]},Qu=i=>{let{type:e}=i;if(e){let t=e.toUpperCase();return ep(t,G0)?G0[t]:e}return zw(i)},tT=i=>i==="VOD"?ke.ON_DEMAND:ke.LIVE,iT=i=>i==="EVENT"?Number.POSITIVE_INFINITY:i==="VOD"?Number.NaN:0,zw=i=>{let{src:e}=i;if(!e)return"";let t="";try{t=new URL(e).pathname}catch{console.error("invalid url")}let s=t.lastIndexOf(".");if(s<0)return Xw(i)?vs.M3U8:"";let r=t.slice(s+1).toUpperCase();return ep(r,vs)?vs[r]:""},Qw="mux.com",Xw=({src:i,customDomain:e=Qw})=>{let t;try{t=new URL(`${i}`)}catch{return!1}let s=t.protocol==="https:",r=t.hostname===`stream.${e}`.toLowerCase(),n=t.pathname.split("/"),a=n.length===2,o=!(n!=null&&n[1].includes("."));return s&&r&&a&&o},Bn=i=>{let e=(i??"").split(".")[1];if(e)try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(atob(t).split("").map(function(r){return"%"+("00"+r.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(s)}catch{return}},Zw=({exp:i},e=Date.now())=>!i||i*1e3<e,Jw=({sub:i},e)=>i!==e,eM=({aud:i},e)=>!i,tM=({aud:i},e)=>i!==e,sT="en";function re(i,e=!0){var t,s;let r=e&&(s=(t=sf)==null?void 0:t[i])!=null?s:i,n=e?sf.code:sT;return new iM(r,n)}var iM=class{constructor(i,e=(t=>(t=sf)!=null?t:sT)()){this.message=i,this.locale=e}format(i){return this.message.replace(/\{(\w+)\}/g,(e,t)=>{var s;return(s=i[t])!=null?s:""})}toString(){return this.message}},sM=Object.values(tf),K0=i=>typeof i=="boolean"||typeof i=="string"&&sM.includes(i),rM=(i,e,t)=>{let{autoplay:s}=i,r=!1,n=!1,a=K0(s)?s:!!s,o=()=>{r||nt(e,"playing",()=>{r=!0},{once:!0})};if(o(),nt(e,"loadstart",()=>{r=!1,o(),Gc(e,a)},{once:!0}),nt(e,"loadstart",()=>{t||(i.streamType&&i.streamType!==ke.UNKNOWN?n=i.streamType===ke.LIVE:n=!Number.isFinite(e.duration)),Gc(e,a)},{once:!0}),t&&t.once(Ee.Events.LEVEL_LOADED,(l,d)=>{var u;i.streamType&&i.streamType!==ke.UNKNOWN?n=i.streamType===ke.LIVE:n=(u=d.details.live)!=null?u:!1}),!a){let l=()=>{!n||Number.isFinite(i.startTime)||(t!=null&&t.liveSyncPosition?e.currentTime=t.liveSyncPosition:Number.isFinite(e.seekable.end(0))&&(e.currentTime=e.seekable.end(0)))};t&&nt(e,"play",()=>{e.preload==="metadata"?t.once(Ee.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{r||(a=K0(l)?l:!!l,Gc(e,a))}},Gc=(i,e)=>{if(!e)return;let t=i.muted,s=()=>i.muted=t;switch(e){case tf.ANY:i.play().catch(()=>{i.muted=!0,i.play().catch(s)});break;case tf.MUTED:i.muted=!0,i.play().catch(s);break;default:i.play().catch(()=>{});break}},nM=({preload:i,src:e},t,s)=>{let r=c=>{c!=null&&["","none","metadata","auto"].includes(c)?t.setAttribute("preload",c):t.removeAttribute("preload")};if(!s)return r(i),r;let n=!1,a=!1,o=s.config.maxBufferLength,l=s.config.maxBufferSize,d=c=>{r(c);let h=c??t.preload;a||h==="none"||(h==="metadata"?(s.config.maxBufferLength=1,s.config.maxBufferSize=1):(s.config.maxBufferLength=o,s.config.maxBufferSize=l),u())},u=()=>{!n&&e&&(n=!0,s.loadSource(e))};return nt(t,"play",()=>{a=!0,s.config.maxBufferLength=o,s.config.maxBufferSize=l,u()},{once:!0}),d(i),d};function aM(i,e){var t;if(!("videoTracks"in i))return;let s=new WeakMap;e.on(Ee.Events.MANIFEST_PARSED,function(l,d){o();let u=i.addVideoTrack("main");u.selected=!0;for(let[c,h]of d.levels.entries()){let f=u.addRendition(h.url[0],h.width,h.height,h.videoCodec,h.bitrate);s.set(h,`${c}`),f.id=`${c}`}}),e.on(Ee.Events.AUDIO_TRACKS_UPDATED,function(l,d){a();for(let u of d.audioTracks){let c=u.default?"main":"alternative",h=i.addAudioTrack(c,u.name,u.lang);h.id=`${u.id}`,u.default&&(h.enabled=!0)}}),i.audioTracks.addEventListener("change",()=>{var l;let d=+((l=[...i.audioTracks].find(c=>c.enabled))==null?void 0:l.id),u=e.audioTracks.map(c=>c.id);d!=e.audioTrack&&u.includes(d)&&(e.audioTrack=d)}),e.on(Ee.Events.LEVELS_UPDATED,function(l,d){var u;let c=i.videoTracks[(u=i.videoTracks.selectedIndex)!=null?u:0];if(!c)return;let h=d.levels.map(f=>s.get(f));for(let f of i.videoRenditions)f.id&&!h.includes(f.id)&&c.removeRendition(f)});let r=l=>{let d=l.target.selectedIndex;d!=e.nextLevel&&(e.nextLevel=d)};(t=i.videoRenditions)==null||t.addEventListener("change",r);let n=()=>{for(let l of i.videoTracks)i.removeVideoTrack(l)},a=()=>{for(let l of i.audioTracks)i.removeAudioTrack(l)},o=()=>{n(),a()};e.once(Ee.Events.DESTROYING,o)}var Kc=i=>"time"in i?i.time:i.startTime;function oM(i,e){e.on(Ee.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(r,{tracks:n})=>{n.forEach(a=>{var o,l;let d=(o=a.subtitleTrack)!=null?o:a.closedCaptions,u=e.subtitleTracks.findIndex(({lang:h,name:f,type:m})=>h==d?.lang&&f===a.label&&m.toLowerCase()===a.kind),c=((l=a._id)!=null?l:a.default)?"default":`${a.kind}${u}`;ip(i,a.kind,a.label,d?.lang,c,a.default)})});let t=()=>{if(!e.subtitleTracks.length)return;let r=Array.from(i.textTracks).find(o=>o.id&&o.mode==="showing"&&["subtitles","captions"].includes(o.kind));if(!r)return;let n=e.subtitleTracks[e.subtitleTrack],a=n?n.default?"default":`${e.subtitleTracks[e.subtitleTrack].type.toLowerCase()}${e.subtitleTrack}`:void 0;if(e.subtitleTrack<0||r?.id!==a){let o=e.subtitleTracks.findIndex(({lang:l,name:d,type:u,default:c})=>r.id==="default"&&c||l==r.language&&d===r.label&&u.toLowerCase()===r.kind);e.subtitleTrack=o}r?.id===a&&r.cues&&Array.from(r.cues).forEach(o=>{r.addCue(o)})};i.textTracks.addEventListener("change",t),e.on(Ee.Events.CUES_PARSED,(r,{track:n,cues:a})=>{let o=i.textTracks.getTrackById(n);if(!o)return;let l=o.mode==="disabled";l&&(o.mode="hidden"),a.forEach(d=>{var u;(u=o.cues)!=null&&u.getCueById(d.id)||o.addCue(d)}),l&&(o.mode="disabled")}),e.once(Ee.Events.DESTROYING,()=>{i.textTracks.removeEventListener("change",t),i.querySelectorAll("track[data-removeondestroy]").forEach(r=>{r.remove()})});let s=()=>{Array.from(i.textTracks).forEach(r=>{var n,a;if(!["subtitles","caption"].includes(r.kind)&&(r.label==="thumbnails"||r.kind==="chapters")){if(!((n=r.cues)!=null&&n.length)){let o="track";r.kind&&(o+=`[kind="${r.kind}"]`),r.label&&(o+=`[label="${r.label}"]`);let l=i.querySelector(o),d=(a=l?.getAttribute("src"))!=null?a:"";l?.removeAttribute("src"),setTimeout(()=>{l?.setAttribute("src",d)},0)}r.mode!=="hidden"&&(r.mode="hidden")}})};e.once(Ee.Events.MANIFEST_LOADED,s),e.once(Ee.Events.MEDIA_ATTACHED,s)}function ip(i,e,t,s,r,n){let a=document.createElement("track");return a.kind=e,a.label=t,s&&(a.srclang=s),r&&(a.id=r),n&&(a.default=!0),a.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",a.setAttribute("data-removeondestroy",""),i.append(a),a.track}function lM(i,e){let t=Array.prototype.find.call(i.querySelectorAll("track"),s=>s.track===e);t?.remove()}function Lo(i,e,t){var s;return(s=Array.from(i.querySelectorAll("track")).find(r=>r.track.label===e&&r.track.kind===t))==null?void 0:s.track}async function rT(i,e,t,s){let r=Lo(i,t,s);return r||(r=ip(i,s,t),r.mode="hidden",await new Promise(n=>setTimeout(()=>n(void 0),0))),r.mode!=="hidden"&&(r.mode="hidden"),[...e].sort((n,a)=>Kc(a)-Kc(n)).forEach(n=>{var a,o;let l=n.value,d=Kc(n);if("endTime"in n&&n.endTime!=null)r?.addCue(new VTTCue(d,n.endTime,s==="chapters"?l:JSON.stringify(l??null)));else{let u=Array.prototype.findIndex.call(r?.cues,m=>m.startTime>=d),c=(a=r?.cues)==null?void 0:a[u],h=c?c.startTime:Number.isFinite(i.duration)?i.duration:Number.MAX_SAFE_INTEGER,f=(o=r?.cues)==null?void 0:o[u-1];f&&(f.endTime=d),r?.addCue(new VTTCue(d,h,s==="chapters"?l:JSON.stringify(l??null)))}}),i.textTracks.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),r}var sp="cuepoints",nT=Object.freeze({label:sp});async function aT(i,e,t=nT){return rT(i,e,t.label,"metadata")}var rf=i=>({time:i.startTime,value:JSON.parse(i.text)});function dM(i,e={label:sp}){let t=Lo(i,e.label,"metadata");return t!=null&&t.cues?Array.from(t.cues,s=>rf(s)):[]}function oT(i,e={label:sp}){var t,s;let r=Lo(i,e.label,"metadata");if(!((t=r?.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return rf(r.activeCues[0]);let{currentTime:n}=i,a=Array.prototype.find.call((s=r.activeCues)!=null?s:[],({startTime:o,endTime:l})=>o<=n&&l>n);return rf(a||r.activeCues[0])}async function uM(i,e=nT){return new Promise(t=>{nt(i,"loadstart",async()=>{let s=await aT(i,[],e);nt(i,"cuechange",()=>{let r=oT(i);if(r){let n=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:r});i.dispatchEvent(n)}},{},s),t(s)})})}var rp="chapters",lT=Object.freeze({label:rp}),nf=i=>({startTime:i.startTime,endTime:i.endTime,value:i.text});async function dT(i,e,t=lT){return rT(i,e,t.label,"chapters")}function cM(i,e={label:rp}){var t;let s=Lo(i,e.label,"chapters");return(t=s?.cues)!=null&&t.length?Array.from(s.cues,r=>nf(r)):[]}function uT(i,e={label:rp}){var t,s;let r=Lo(i,e.label,"chapters");if(!((t=r?.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return nf(r.activeCues[0]);let{currentTime:n}=i,a=Array.prototype.find.call((s=r.activeCues)!=null?s:[],({startTime:o,endTime:l})=>o<=n&&l>n);return nf(a||r.activeCues[0])}async function hM(i,e=lT){return new Promise(t=>{nt(i,"loadstart",async()=>{let s=await dT(i,[],e);nt(i,"cuechange",()=>{let r=uT(i);if(r){let n=new CustomEvent("chapterchange",{composed:!0,bubbles:!0,detail:r});i.dispatchEvent(n)}},{},s),t(s)})})}function fM(i,e){if(e){let t=e.playingDate;if(t!=null)return new Date(t.getTime()-i.currentTime*1e3)}return typeof i.getStartDate=="function"?i.getStartDate():new Date(NaN)}function mM(i,e){if(e&&e.playingDate)return e.playingDate;if(typeof i.getStartDate=="function"){let t=i.getStartDate();return new Date(t.getTime()+i.currentTime*1e3)}return new Date(NaN)}var Za={VIDEO:"v",THUMBNAIL:"t",STORYBOARD:"s",DRM:"d"},pM=i=>{if(i===Fe.VIDEO)return Za.VIDEO;if(i===Fe.DRM)return Za.DRM},gM=(i,e)=>{var t,s;let r=zu(i),n=`${r}Token`;return(t=e.tokens)!=null&&t[r]?(s=e.tokens)==null?void 0:s[r]:ep(n,e)?e[n]:void 0},au=(i,e,t,s,r=!1,n=!(a=>(a=globalThis.navigator)==null?void 0:a.onLine)())=>{var a,o;if(n){let v=re("Your device appears to be offline",r),b,E=X.MEDIA_ERR_NETWORK,T=new X(v,E,!1,b);return T.errorCategory=e,T.muxCode=ae.NETWORK_OFFLINE,T.data=i,T}let l="status"in i?i.status:i.code,d=Date.now(),u=X.MEDIA_ERR_NETWORK;if(l===200)return;let c=zu(e),h=gM(e,t),f=pM(e),[m]=tp((a=t.playbackId)!=null?a:"");if(!l||!m)return;let p=Bn(h);if(h&&!p){let v=re("The {tokenNamePrefix}-token provided is invalid or malformed.",r).format({tokenNamePrefix:c}),b=re("Compact JWT string: {token}",r).format({token:h}),E=new X(v,u,!0,b);return E.errorCategory=e,E.muxCode=ae.NETWORK_TOKEN_MALFORMED,E.data=i,E}if(l>=500){let v=new X("",u,s??!0);return v.errorCategory=e,v.muxCode=ae.NETWORK_UNKNOWN_ERROR,v}if(l===403)if(p){if(Zw(p,d)){let v={timeStyle:"medium",dateStyle:"medium"},b=re("The video’s secured {tokenNamePrefix}-token has expired.",r).format({tokenNamePrefix:c}),E=re("Expired at: {expiredDate}. Current time: {currentDate}.",r).format({expiredDate:new Intl.DateTimeFormat("en",v).format((o=p.exp)!=null?o:0*1e3),currentDate:new Intl.DateTimeFormat("en",v).format(d)}),T=new X(b,u,!0,E);return T.errorCategory=e,T.muxCode=ae.NETWORK_TOKEN_EXPIRED,T.data=i,T}if(Jw(p,m)){let v=re("The video’s playback ID does not match the one encoded in the {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c}),b=re("Specified playback ID: {playbackId} and the playback ID encoded in the {tokenNamePrefix}-token: {tokenPlaybackId}",r).format({tokenNamePrefix:c,playbackId:m,tokenPlaybackId:p.sub}),E=new X(v,u,!0,b);return E.errorCategory=e,E.muxCode=ae.NETWORK_TOKEN_SUB_MISMATCH,E.data=i,E}if(eM(p)){let v=re("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),b=re("The {tokenNamePrefix}-token has no aud value. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f}),E=new X(v,u,!0,b);return E.errorCategory=e,E.muxCode=ae.NETWORK_TOKEN_AUD_MISSING,E.data=i,E}if(tM(p,f)){let v=re("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),b=re("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f,aud:p.aud}),E=new X(v,u,!0,b);return E.errorCategory=e,E.muxCode=ae.NETWORK_TOKEN_AUD_MISMATCH,E.data=i,E}}else{let v=re("Authorization error trying to access this {category} URL. If this is a signed URL, you might need to provide a {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c,category:e}),b=re("Specified playback ID: {playbackId}",r).format({playbackId:m}),E=new X(v,u,s??!0,b);return E.errorCategory=e,E.muxCode=ae.NETWORK_TOKEN_MISSING,E.data=i,E}if(l===412){let v=re("This playback-id may belong to a live stream that is not currently active or an asset that is not ready.",r),b=re("Specified playback ID: {playbackId}",r).format({playbackId:m}),E=new X(v,u,s??!0,b);return E.errorCategory=e,E.muxCode=ae.NETWORK_NOT_READY,E.streamType=t.streamType===ke.LIVE?"live":t.streamType===ke.ON_DEMAND?"on-demand":"unknown",E.data=i,E}if(l===404){let v=re("This URL or playback-id does not exist. You may have used an Asset ID or an ID from a different resource.",r),b=re("Specified playback ID: {playbackId}",r).format({playbackId:m}),E=new X(v,u,s??!0,b);return E.errorCategory=e,E.muxCode=ae.NETWORK_NOT_FOUND,E.data=i,E}if(l===400){let v=re("The URL or playback-id was invalid. You may have used an invalid value as a playback-id."),b=re("Specified playback ID: {playbackId}",r).format({playbackId:m}),E=new X(v,u,s??!0,b);return E.errorCategory=e,E.muxCode=ae.NETWORK_INVALID_URL,E.data=i,E}let g=new X("",u,s??!0);return g.errorCategory=e,g.muxCode=ae.NETWORK_UNKNOWN_ERROR,g.data=i,g},V0=Ee.DefaultConfig.capLevelController,vM={"720p":921600,"1080p":2073600,"1440p":4194304,"2160p":8294400};function EM(i){let e=i.toLowerCase().trim();return vM[e]}var af=class wa extends V0{constructor(e){super(e)}static setMaxAutoResolution(e,t){t?wa.maxAutoResolution.set(e,t):wa.maxAutoResolution.delete(e)}getMaxAutoResolution(){var e;let t=this.hls;return(e=wa.maxAutoResolution.get(t))!=null?e:void 0}get levels(){var e;return(e=this.hls.levels)!=null?e:[]}getValidLevels(e){return this.levels.filter((t,s)=>this.isLevelAllowed(t)&&s<=e)}getMaxLevelCapped(e){let t=this.getValidLevels(e),s=this.getMaxAutoResolution();if(!s)return super.getMaxLevel(e);let r=EM(s);if(!r)return super.getMaxLevel(e);let n=t.filter(l=>l.width*l.height<=r),a=n.findIndex(l=>l.width*l.height===r);if(a!==-1){let l=n[a];return t.findIndex(d=>d===l)}if(n.length===0)return 0;let o=n[n.length-1];return t.findIndex(l=>l===o)}getMaxLevel(e){if(this.getMaxAutoResolution()!==void 0)return this.getMaxLevelCapped(e);let t=super.getMaxLevel(e),s=this.getValidLevels(e);if(!s[t])return t;let r=Math.min(s[t].width,s[t].height),n=wa.minMaxResolution;return r>=n?t:V0.getMaxLevelByMediaSize(s,n*(16/9),n)}};af.minMaxResolution=720,af.maxAutoResolution=new WeakMap;var yM=af,Vc=yM,zl={FAIRPLAY:"fairplay",PLAYREADY:"playready",WIDEVINE:"widevine"},bM=i=>{if(i.includes("fps"))return zl.FAIRPLAY;if(i.includes("playready"))return zl.PLAYREADY;if(i.includes("widevine"))return zl.WIDEVINE},TM=i=>{let e=i.split(`
|
|
1455
|
+
`)}),o.flush()}const Oc="stpp.ttml.im1t",jb=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,zb=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,uw={left:"start",center:"center",right:"end",start:"start",end:"end"};function w0(i,e,t,s){const r=me(new Uint8Array(i),["mdat"]);if(r.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const n=r.map(o=>Xt(o)),a=mD(e.baseTime,1,e.timescale);try{n.forEach(o=>t(cw(o,a)))}catch(o){s(o)}}function cw(i,e){const r=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((c,h)=>(c[h]=r.getAttribute(`ttp:${h}`)||n[h],c),{}),o=r.getAttribute("xml:space")!=="preserve",l=M0(Nc(r,"styling","style")),d=M0(Nc(r,"layout","region")),u=Nc(r,"body","[begin]");return[].map.call(u,c=>{const h=Qb(c,o);if(!h||!c.hasAttribute("begin"))return null;const f=$c(c.getAttribute("begin"),a),m=$c(c.getAttribute("dur"),a);let p=$c(c.getAttribute("end"),a);if(f===null)throw P0(c);if(p===null){if(m===null)throw P0(c);p=f+m}const g=new Zm(f-e,p-e,h);g.id=Jm(g.startTime,g.endTime,g.text);const v=d[c.getAttribute("region")],b=l[c.getAttribute("style")],E=hw(v,b,l),{textAlign:T}=E;if(T){const A=uw[T];A&&(g.lineAlign=A),g.align=T}return Oe(g,E),g}).filter(c=>c!==null)}function Nc(i,e,t){const s=i.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function M0(i){return i.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Qb(i,e){return[].slice.call(i.childNodes).reduce((t,s,r)=>{var n;return s.nodeName==="br"&&r?t+`
|
|
1456
|
+
`:(n=s.childNodes)!=null&&n.length?Qb(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function hw(i,e,t){const s="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=i!=null&&i.hasAttribute("style")?i.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(r=t[a]),n.reduce((o,l)=>{const d=Uc(e,s,l)||Uc(i,s,l)||Uc(r,s,l);return d&&(o[l]=d),o},{})}function Uc(i,e,t){return i&&i.hasAttributeNS(e,t)?i.getAttributeNS(e,t):null}function P0(i){return new Error(`Could not parse ttml timestamp ${i}`)}function $c(i,e){if(!i)return null;let t=Wb(i);return t===null&&(jb.test(i)?t=fw(i,e):zb.test(i)&&(t=mw(i,e))),t}function fw(i,e){const t=jb.exec(i),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 mw(i,e){const t=zb.exec(i),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 rl{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 pw{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=N0(),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(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(y.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(y.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new rl(this,"textTrack1"),t=new rl(this,"textTrack2"),s=new rl(this,"textTrack3"),r=new rl(this,"textTrack4");this.cea608Parser1=new C0(1,e,t),this.cea608Parser2=new C0(3,s,r)}addCues(e,t,s,r,n){let a=!1;for(let o=n.length;o--;){const l=n[o],d=gw(l[0],l[1],t,s);if(d>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],s),a=!0,d/(s-t)>.5))return}if(a||n.push([t,s]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,s,r)}else{const o=this.Cues.newCue(null,t,s,r);this.hls.trigger(y.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:r,timescale:n,trackId:a}){const{unparsedVttFrags:o}=this;s===J.MAIN&&(this.initPTS[t.cc]={baseTime:r,timescale:n,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(l=>{this.initPTS[l.frag.cc]?this.onFragLoaded(y.FRAG_LOADED,l):this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:l.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let r=0;r<s.textTracks.length;r++){const n=s.textTracks[r];if(O0(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:r}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)s[e]=o,Cn(s[e]),Bb(s[e],r);else{const l=this.createTextTrack("captions",n,a);l&&(l[e]=!0,s[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,r={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(y.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}createTextTrack(e,t,s){const r=this.media;if(r)return r.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:r}=this;Object.keys(r).forEach(n=>{Cn(r[n]),delete r[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=N0(),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++)Cn(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],r=s.some(n=>n.textCodec===Oc);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(Lb(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const a=this.media,o=a?Yl(a.textTracks):null;if(this.tracks.forEach((l,d)=>{let u;if(o){let c=null;for(let h=0;h<o.length;h++)if(o[h]&&O0(o[h],l)){c=o[h],o[h]=null;break}c&&(u=c)}if(u)Cn(u);else{const c=Xb(l);u=this.createTextTrack(c,l.name,l.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),o!=null&&o.length){const l=o.filter(d=>d!==null).map(d=>d.label);l.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(y.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const r=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!r)return;const n=`textTrack${r[1]}`,a=this.captionsProperties[n];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===J.MAIN){var s,r;const{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:d}=t.frag,u=(s=(r=t.part)==null?void 0:r.index)!=null?s:-1;n&&a&&(d!==o+1||d===o&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=d,this.lastPartIndex=u}}onFragLoaded(e,t){const{frag:s,payload:r}=t;if(s.type===J.SUBTITLE)if(r.byteLength){const n=s.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){const o=this.tracks[s.level],l=this.vttCCs;l[s.cc]||(l[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Oc?this._parseIMSC1(s,r):this._parseVTTs(t)}}else this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;w0(t,this.initPTS[e.cc],r=>{this._appendCues(r,e.level),s.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},r=>{s.logger.log(`Failed to parse IMSC1: ${r}`),s.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:r})})}_parseVTTs(e){var t;const{frag:s,payload:r}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[s.cc]&&o===-1){a.push(e);return}const l=this.hls,d=(t=s.initSegment)!=null&&t.data?li(s.initSegment.data,new Uint8Array(r)).buffer:r;dw(d,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,u=>{this._appendCues(u,s.level),l.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},u=>{const c=u.message==="Missing initPTS for VTT MPEGTS";c?a.push(e):this._fallbackToIMSC1(s,r),l.logger.log(`Failed to parse VTT cue: ${u}`),!(c&&o>s.cc)&&l.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:u})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||w0(t,this.initPTS[e.cc],()=>{s.textCodec=Oc,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const r=this.textTracks[t];if(!r||r.mode==="disabled")return;e.forEach(n=>Hb(r,n))}else{const r=this.tracks[t];if(!r)return;const n=r.default?"default":"subtitles"+t;s.trigger(y.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===J.SUBTITLE&&this.onFragLoaded(y.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:r}=t;if(!(s.type===J.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let n=0;n<r.length;n++){const a=r[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(r[n].pts,o[0]),this.cea608Parser2.addData(r[n].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:r,type:n}){const{media:a}=this;if(!(!a||a.currentTime<s)){if(!n||n==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>Xh(o[l],t,s))}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>Xh(o[l],t,r))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let r=2;for(let n=0;n<s;n++){const a=e[r++],o=127&e[r++],l=127&e[r++];if(o===0&&l===0)continue;if((4&a)!==0){const u=3&a;(u===0||u===1)&&(t[u].push(o),t[u].push(l))}}return t}}function Xb(i){return i.characteristics&&/transcribes-spoken-dialog/gi.test(i.characteristics)&&/describes-music-and-sound/gi.test(i.characteristics)?"captions":"subtitles"}function O0(i,e){return!!i&&i.kind===Xb(e)&&Yh(e,i)}function gw(i,e,t,s){return Math.min(e,s)-Math.max(i,t)}function N0(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const vw=/\s/,Ew={newCue(i,e,t,s){const r=[];let n,a,o,l,d;const u=self.VTTCue||self.TextTrackCue;for(let h=0;h<s.rows.length;h++)if(n=s.rows[h],o=!0,l=0,d="",!n.isEmpty()){var c;for(let p=0;p<n.chars.length;p++)vw.test(n.chars[p].uchar)&&o?l++:(d+=n.chars[p].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=Yb(d.trim()),m=Jm(e,t,f);i!=null&&(c=i.cues)!=null&&c.getCueById(m)||(a=new u(e,t,f),a.id=m,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a))}return i&&r.length&&(r.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),r.forEach(h=>Hb(i,h))),r}};function yw(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const bw=/(\d+)-(\d+)\/(\d+)/;class U0{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||Sw,this.controller=new self.AbortController,this.stats=new Cm}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 r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const n=Tw(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=l&&X(l)?l:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},t.timeout),(yo(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(c=>{var h;this.response=this.loader=c;const f=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},d-(f-r.loading.start)),!c.ok){const{status:p,statusText:g}=c;throw new Iw(g||"fetch, bad network response",p,c)}r.loading.first=f,r.total=Aw(c.headers)||r.total;const m=(h=this.callbacks)==null?void 0:h.onProgress;return m&&X(t.highWaterMark)?this.loadProgressively(c,r,e,t.highWaterMark,m):a?c.arrayBuffer():e.responseType==="json"?c.json():c.text()}).then(c=>{var h,f;const m=this.response;if(!m)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const p=c[o];p&&(r.loaded=r.total=p);const g={url:m.url,data:c,code:m.status},v=(h=this.callbacks)==null?void 0:h.onProgress;v&&!X(t.highWaterMark)&&v(r,e,c,m),(f=this.callbacks)==null||f.onSuccess(g,r,e,m)}).catch(c=>{var h;if(self.clearTimeout(this.requestTimeout),r.aborted)return;const f=c&&c.code||0,m=c?c.message:null;(h=this.callbacks)==null||h.onError({code:f,text:m},e,c?c.details:null,r)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,r=0,n){const a=new ob,o=e.body.getReader(),l=()=>o.read().then(d=>{if(d.done)return a.dataLength&&n(t,s,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const u=d.value,c=u.length;return t.loaded+=c,c<r||a.dataLength?(a.push(u),a.dataLength>=r&&n(t,s,a.flush().buffer,e)):n(t,s,u.buffer,e),l()}).catch(()=>Promise.reject());return l()}}function Tw(i,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Oe({},i.headers))};return i.rangeEnd&&t.headers.set("Range","bytes="+i.rangeStart+"-"+String(i.rangeEnd-1)),t}function _w(i){const e=bw.exec(i);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Aw(i){const e=i.get("Content-Range");if(e){const s=_w(e);if(X(s))return s}const t=i.get("Content-Length");if(t)return parseInt(t)}function Sw(i,e){return new self.Request(i.url,e)}class Iw extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const xw=/^age:\s*[\d.]+\s*$/im;class Zb{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 Cm,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,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return n(s,t.url)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),n(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},t,s,r)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=s.loadPolicy;if(r)for(const o in r)e.setRequestHeader(o,r[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=n&&X(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const r=t.readyState,n=this.config;if(!s.aborted&&r>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const d=t.status,u=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){const m=u??t.response;if(m!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=t.responseType==="arraybuffer"?m.byteLength:m.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const g=(a=this.callbacks)==null?void 0:a.onProgress;g&&g(s,e,m,t);const v={url:t.responseURL,data:m,code:d};(o=this.callbacks)==null||o.onSuccess(v,s,e,t);return}}const c=n.loadPolicy.errorRetry,h=s.retry,f={url:e.url,data:void 0,code:d};if(Jd(c,h,!1,f))this.retry(c);else{var l;we.error(`${d} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:d,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Jd(e,t,!0))this.retry(e);else{var s;we.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=Om(e,s.retry),s.retry++,we.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&xw.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 Lw={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Rw=Ce(Ce({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Zb,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:BR,bufferController:DD,capLevelController:zm,errorController:WR,fpsController:CC,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:Qy,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:Lw},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},kw()),{},{subtitleStreamController:KC,subtitleTrackController:PC,timelineController:pw,audioStreamController:xD,audioTrackController:LD,emeController:$n,cmcdController:LC,contentSteeringController:kC,interstitialsController:GC});function kw(){return{cueHandler:Ew,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 Dw(i,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=Jh(i),r=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return r.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,d=[];n.forEach(u=>{const c=`${a}Loading${u}`,h=e[c];if(h!==void 0&&l){d.push(c);const f=s[o].default;switch(e[o]={default:f},u){case"TimeOut":f.maxLoadTimeMs=h,f.maxTimeToFirstByteMs=h;break;case"MaxRetry":f.errorRetry.maxNumRetry=h,f.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":f.errorRetry.retryDelayMs=h,f.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=h,f.timeoutRetry.maxRetryDelayMs=h;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${$e(e[o])}`)}),Ce(Ce({},s),e)}function Jh(i){return i&&typeof i=="object"?Array.isArray(i)?i.map(Jh):Object.keys(i).reduce((e,t)=>(e[t]=Jh(i[t]),e),{}):i}function Cw(i,e){const t=i.loader;t!==U0&&t!==Zb?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),i.progressive=!1):yw()&&(i.loader=U0,i.progressive=!0,i.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const jl=2,ww=.1,Mw=.05,Pw=100;class Ow extends Wy{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.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(Pw),this.mediaSource=t.mediaSource;const s=this.media=t.media;wt(s,"playing",this.onMediaPlaying),wt(s,"waiting",this.onMediaWaiting),wt(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(Nt(s,"playing",this.onMediaPlaying),Nt(s,"waiting",this.onMediaWaiting),Nt(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,r;const n=(s=this.hls)==null?void 0:s.config;if(!n)return;const a=this.media;if(!a)return;const{seeking:o}=a,l=this.seeking&&!o,d=!this.seeking&&o,u=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||l){l&&this.stallResolved(e);return}if(u){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1}));return}if(!ue.getBuffered(a).length){this.nudgeRetry=0;return}const c=ue.bufferInfo(a,e,0),h=c.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const x=$0(this.hls.inFlightFragments,e),S=c.len>jl,L=!h||x||h-e>jl&&!f.getPartialFragment(e);if(S||L)return;this.moved=!1}const m=(r=this.hls)==null?void 0:r.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(c.len>0)&&!h)return;const S=Math.max(h,c.start||0)-e,R=!!(m!=null&&m.live)?m.targetduration*2:jl,I=nl(e,f);if(S>0&&(S<=R||I)){a.paused||this._trySkipBufferHole(I);return}}const p=n.detectStallWithCurrentTimeMs,g=self.performance.now(),v=this.waiting;let b=this.stalled;if(b===null)if(v>0&&g-v<p)b=this.stalled=v;else{this.stalled=g;return}const E=g-b;if(!o&&(E>=p||v)&&this.hls){var T;if(((T=this.mediaSource)==null?void 0:T.readyState)==="ended"&&!(m!=null&&m.live)&&Math.abs(e-(m?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return}const A=ue.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(A,E,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(y.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&r&&r.length>1&&e>r.end(0)){const n=ue.bufferedInfo(ue.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){const a=ue.timeRangesToArray(r),o=ue.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const l=ue.bufferedInfo(a,e,0).bufferedIndex,d=a[o].end,u=a[o+1].start;if((l===-1||l>o)&&u-d<1&&e-d<2){const c=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${u} buffered index: ${l}`);this.warn(c.message),this.media.currentTime+=1e-6;let h=nl(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);const f=ue.bufferInfo(this.media,e,0);this.hls.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,s){var r,n;const{fragmentTracker:a,media:o}=this,l=(r=this.hls)==null?void 0:r.config;if(!o||!a||!l)return;const d=(n=this.hls)==null?void 0:n.latestLevelDetails,u=nl(s,a);if((u||d!=null&&d.live&&s<d.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;const c=e.buffered,h=this.adjacentTraversal(e,s);(c&&c.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-s<l.maxBufferHole||h))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,r=e.nextStart;if(s&&r){const n=s.getFragAtPos(t,J.MAIN),a=s.getFragAtPos(r,J.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:r,stalled:n}=this;if(!r&&n!==null&&s&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${$e(e)})`);this.warn(a.message),t.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:r}=this,n=(t=this.hls)==null?void 0:t.config;if(!r||!s||!n)return 0;const a=r.currentTime,o=ue.bufferInfo(r,a,0),l=a<o.start?o.start:o.nextStart;if(l&&this.hls){const u=o.len<=n.maxBufferHole,c=o.len>0&&o.len<1&&r.readyState<3,h=l-a;if(h>0&&(u||c)){if(h>n.maxBufferHole){let m=!1;if(a===0){const p=s.getAppendedFrag(0,J.MAIN);p&&l<p.end&&(m=!0)}if(!m&&e){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||$0(this.hls.inFlightFragments,l))return 0;let g=!1,v=e.end;for(;v<l;){const b=nl(v,s);if(b)v+=b.duration;else{g=!0;break}}if(g)return 0}}const f=Math.max(l+Mw,a+ww);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,r.currentTime=f,!(e!=null&&e.gap)){const m=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),p={type:ie.MEDIA_ERROR,details:w.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(y.ERROR,p)}return f}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:r}=this,n=t?.config;if(!s||!n)return 0;const a=s.currentTime;if(this.nudgeRetry++,r<n.nudgeMaxRetry){const o=a+(r+1)*n.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),s.currentTime=o,t.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function $0(i,e){const t=F0(i.main);if(t&&t.start<=e)return t;const s=F0(i.audio);return s&&s.start<=e?s:null}function F0(i){if(!i)return null;switch(i.state){case P.IDLE:case P.STOPPED:case P.ENDED:case P.ERROR:return null}return i.frag}function nl(i,e){return e.getAppendedFrag(i,J.MAIN)||e.getPartialFragment(i)}const Nw=.25;function ef(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Fc(i,e,t,s,r){let n=new i(e,t,"");try{n.value=s,r&&(n.type=r)}catch{n=new i(e,t,$e(r?Ce({type:r},s):s))}return n}const al=(()=>{const i=ef();try{i&&new i(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Uw{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(y.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Cn(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 Bb(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:r}=this.hls.config;if(!s&&!r)return;const{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=ef();if(a)for(let o=0;o<n.length;o++){const l=n[o].type;if(l===zt.emsg&&!s||!r)continue;const d=mb(n[o].data),u=n[o].pts;let c=u+n[o].duration;c>al&&(c=al),c-u<=0&&(c=u+Nw);for(let f=0;f<d.length;f++){const m=d[f];if(!pb(m)){this.updateId3CueEnds(u,l);const p=Fc(a,u,c,m,l);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var s;const r=(s=this.id3Track)==null?void 0:s.cues;if(r)for(let n=r.length;n--;){const a=r[n];a.type===t&&a.startTime<e&&a.endTime===al&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:r}){const{id3Track:n,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let d;r==="audio"?d=u=>u.type===zt.audioId3&&l:r==="video"?d=u=>u.type===zt.emsg&&o:d=u=>u.type===zt.audioId3&&l||u.type===zt.emsg&&o,Xh(n,t,s,d)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;const o=ef();if(s&&r&&!a){const{fragmentStart:p,fragmentEnd:g}=e;let v=this.assetCue;v?(v.startTime=p,v.endTime=g):o&&(v=this.assetCue=Fc(o,p,g,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:d}=e,u=Object.keys(d);let c=this.dateRangeCuesAppended;if(l&&t){var h;if((h=l.cues)!=null&&h.length){const p=Object.keys(c).filter(g=>!u.includes(g));for(let g=p.length;g--;){var f;const v=p[g],b=(f=c[v])==null?void 0:f.cues;delete c[v],b&&Object.keys(b).forEach(E=>{const T=b[E];if(T){T.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(T)}catch{}}})}}else c=this.dateRangeCuesAppended={}}const m=e.fragments[e.fragments.length-1];if(!(u.length===0||!X(m?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<u.length;p++){const g=u[p],v=d[g],b=v.startTime,E=c[g],T=E?.cues||{};let A=E?.durationKnown||!1,x=al;const{duration:S,endDate:L}=v;if(L&&S!==null)x=b+S,A=!0;else if(v.endOnNext&&!A){const I=u.reduce((M,B)=>{if(B!==v.id){const q=d[B];if(q.class===v.class&&q.startDate>v.startDate&&(!M||v.startDate<M.startDate))return q}return M},null);I&&(x=I.startTime,A=!0)}const R=Object.keys(v.attr);for(let I=0;I<R.length;I++){const M=R[I];if(!rk(M))continue;const B=T[M];if(B)A&&!(E!=null&&E.durationKnown)?B.endTime=x:Math.abs(B.startTime-b)>.01&&(B.startTime=b,B.endTime=x);else if(o){let q=v.attr[M];nk(M)&&(q=Iy(q));const K=Fc(o,b,x,{key:M,data:q},zt.dateRange);K&&(K.id=g,this.id3Track.addCue(K),T[M]=K,a&&(M==="X-ASSET-LIST"||M==="X-ASSET-URL")&&K.addEventListener("enter",this.onEventCueEnter))}}c[g]={cues:T,dateRange:v,durationKnown:A}}}}}class $w{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 r=this.computeLatency();if(r===null)return;this._latency=r;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!s.live)return;const o=this.targetLatency;if(o===null)return;const l=r-o,d=Math.min(this.maxLatency,o+s.targetduration);if(l<d&&l>.05&&this.forwardBufferLength>1){const c=Math.min(2,Math.max(1,a)),h=Math.round(2/(1+Math.exp(-.75*l-this.edgeStalled))*20)/20,f=Math.min(c,Math.max(1,h));this.changeMediaPlaybackRate(t,f)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:s,targetduration:r}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let d=o&&s||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||d===0)&&(d=n!==void 0?n:a*r);const u=r;return d+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 r=s.edge,n=e-t-this.edgeStalled,a=r-s.totalduration,o=r-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(a,n),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.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===w.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,r;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(r=this.targetLatency)==null?void 0:r.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 Fw extends jm{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(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.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,r=[],n={},a={};let o=!1,l=!1,d=!1;t.levels.forEach(u=>{const c=u.attrs;let{audioCodec:h,videoCodec:f}=u;h&&(u.audioCodec=h=zd(h,s)||void 0),f&&(f=u.videoCodec=TR(f));const{width:m,height:p,unknownCodecs:g}=u,v=g?.length||0;if(o||(o=!!(m&&p)),l||(l=!!f),d||(d=!!h),v||h&&!this.isAudioSupported(h)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${c.CODECS}"`);return}const{CODECS:b,"FRAME-RATE":E,"HDCP-LEVEL":T,"PATHWAY-ID":A,RESOLUTION:x,"VIDEO-RANGE":S}=c,R=`${`${A||"."}-`}${u.bitrate}-${x}-${E}-${b}-${S}-${T}`;if(n[R])if(n[R].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const I=a[R]+=1;u.attrs["PATHWAY-ID"]=new Array(I+1).join(".");const M=this.createLevel(u);n[R]=M,r.push(M)}else n[R].addGroupId("audio",c.AUDIO),n[R].addGroupId("text",c.SUBTITLES);else{const I=this.createLevel(u);n[R]=I,a[R]=1,r.push(I)}}),this.filterAndSortMediaOptions(r,t,o,l,d)}createLevel(e){const t=new go(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const r=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(r.message),t.supportedResult=Uy(r,[])}return t}isAudioSupported(e){return mo(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return mo(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,r,n){var a;let o=[],l=[],d=e;const u=((a=t.stats)==null?void 0:a.parsing)||{};if((s||r)&&n&&(d=d.filter(({videoCodec:b,videoRange:E,width:T,height:A})=>(!!b||!!(T&&A))&&CR(E))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let b="no level with compatible codecs found in manifest",E=b;t.levels.length&&(E=`one or more CODECS in variant not supported: ${$e(t.levels.map(A=>A.attrs.CODECS).filter((A,x,S)=>S.indexOf(A)===x))}`,this.warn(E),b+=` (${E})`);const T=new Error(b);this.hls.trigger(y.ERROR,{type:ie.MEDIA_ERROR,details:w.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:T,reason:E})}}),u.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(b=>!b.audioCodec||this.isAudioSupported(b.audioCodec)),B0(o)),t.subtitles&&(l=t.subtitles,B0(l));const c=d.slice(0);d.sort((b,E)=>{if(b.attrs["HDCP-LEVEL"]!==E.attrs["HDCP-LEVEL"])return(b.attrs["HDCP-LEVEL"]||"")>(E.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&b.height!==E.height)return b.height-E.height;if(b.frameRate!==E.frameRate)return b.frameRate-E.frameRate;if(b.videoRange!==E.videoRange)return Qd.indexOf(b.videoRange)-Qd.indexOf(E.videoRange);if(b.videoCodec!==E.videoCodec){const T=Cg(b.videoCodec),A=Cg(E.videoCodec);if(T!==A)return A-T}if(b.uri===E.uri&&b.codecSet!==E.codecSet){const T=jd(b.codecSet),A=jd(E.codecSet);if(T!==A)return A-T}return b.averageBitrate!==E.averageBitrate?b.averageBitrate-E.averageBitrate:0});let h=c[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==c.length)){for(let b=0;b<c.length;b++)if(c[b].pathwayId===d[0].pathwayId){h=c[b];break}}this._levels=d;for(let b=0;b<d.length;b++)if(d[b]===h){var f;this._firstLevel=b;const E=h.bitrate,T=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${E}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){const A=Math.min(E,this.hls.config.abrEwmaDefaultEstimateMax);A>T&&T===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=A)}break}const m=n&&!r,p=this.hls.config,g=!!(p.audioStreamController&&p.audioTrackController),v={levels:d,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:g&&!m&&o.some(b=>!!b.url)};u.end=performance.now(),this.hls.trigger(y.MANIFEST_PARSED,v)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const u=new Error("invalid level idx"),c=e<0;if(this.hls.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.LEVEL_SWITCH_ERROR,level:e,fatal:c,error:u,reason:u.message}),c)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,r=this.currentLevel,n=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&r&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${s}${n?" with Pathway "+n:""}`);const l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(y.LEVEL_SWITCHING,l);const d=a.details;if(!d||d.live){const u=this.switchParams(a.uri,r?.details,d);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(r=>t.indexOf(r)!==-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===ge.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===J.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(n=>!!s[n]))return;const r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(e,t){var s;const{level:r,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(r,t,l)}else(s=t.deliveryDirectives)!=null&&s.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a?.age;this.log(`Loading level index ${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(y.LEVEL_LOADING,{url:s,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const s=this._levels.filter((n,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));rb(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 r=s.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(y.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(y.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function B0(i){const e={};i.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function Jb(){return self.SourceBuffer||self.WebKitSourceBuffer}function eT(){if(!zs())return!1;const e=Jb();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Bw(){if(!eT())return!1;const i=zs();return typeof i?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>i.isTypeSupported(po(e,"video")))||["mp4a.40.2","fLaC"].some(e=>i.isTypeSupported(po(e,"audio"))))}function Hw(){var i;const e=Jb();return typeof(e==null||(i=e.prototype)==null?void 0:i.changeType)=="function"}const Gw=100;class Kw extends Bm{constructor(e,t,s){super(e,t,s,"stream-controller",J.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 r=this.media,n=r?r.currentTime:null;if(n===null||!X(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;const a=this.getFwdBufferInfoAtPos(r,n,J.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${n} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.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:r}=this;if(this.stopLoad(),this.setInterval(Gw),this.level=-1,!this.startFragRequested){let n=r.startLevel;n===-1&&(r.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=r.firstAutoLevel),r.nextLoadLevel=n,this.level=r.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=P.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=P.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case P.WAITING_LEVEL:{const{levels:e,level:t}=this,s=e?.[t],r=s?.details;if(r&&(!r.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(r))break;this.state=P.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=P.IDLE;break}break}case P.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===P.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[n]))return;const a=s[n],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(y.BUFFER_EOS,p),this.state=P.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;const d=a.details;if(!d||this.state===P.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=P.WAITING_LEVEL,this.startFragRequested=!1;return}const u=o.len,c=this.getMaxBufferLength(a.maxBitrate);if(u>=c)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(h,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&et(f)&&this.fragmentTracker.getState(f)!==gt.OK){var m;const g=((m=this.backtrackFragment)!=null?m:f).sn-d.startSN,v=d.fragments[g-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){const g=this.audioOnly&&!this.altAudio?Ue.AUDIO:Ue.VIDEO,v=(g===Ue.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,g,J.MAIN)}f=this.getNextFragmentLoopLoading(f,d,o,J.MAIN,c)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(e,t,s){const r=this.fragmentTracker.getState(e);r===gt.NOT_LOADED||r===gt.PARTIAL?et(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,J.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const n=this.getLevelDetails();if(n!=null&&n.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,l=e[o],d=this.fragLastKbps;d&&this.fragCurrent?s=this.fragCurrent.duration*l.maxBitrate/(1e3*d)+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 l=o.maxStartPTS?o.maxStartPTS:o.start,d=o.duration,u=Math.max(a.end,l+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(u,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case P.KEY_LOADING:case P.FRAG_LOADING:case P.FRAG_LOADING_WAITING_RETRY:case P.PARSING:case P.PARSED:this.state=P.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;wt(s,"playing",this.onMediaPlaying),wt(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(Nt(s,"playing",this.onMediaPlaying),Nt(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(y.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,r=!1;for(let n=0;n<t.levels.length;n++){const a=t.levels[n].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&r&&!Hw(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==P.IDLE)return;const r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=P.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:r,startFragRequested:n}=this,a=t.level,o=t.details,l=o.totalduration;if(!r){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const d=t.levelInfo,u=this.fragCurrent;u&&(this.state===P.FRAG_LOADING||this.state===P.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let c=0;if(o.live||(s=d.details)!=null&&s.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,d.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(d.details=o,this.levelLastLoaded=d,n||this.setStartPosition(o,c),this.hls.trigger(y.LEVEL_UPDATED,{details:o,level:a}),this.state===P.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=P.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const r=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,l=n>=a-t.maxFragLookUpTolerance&&n<=o;if(r!==null&&s.duration>r&&(n<r||!l)){const u=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&s.readyState<4||n<o-u)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),s.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var d;const c=ue.bufferInfo(s,r,0);if(!((d=c.buffered)!=null&&d.length)){s.currentTime=r;return}if(c.start<=n){s.currentTime=r;return}const{nextStart:f}=ue.bufferedInfo(c.buffered,n,0);f&&(s.currentTime=f)}else s.currentTime=r}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:r,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=a[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}const l=o.details;if(!l){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const d=o.videoCodec,u=l.PTSKnown||!l.live,c=(t=s.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new xb(this.hls,J.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=r?r.index:-1,p=m!==-1,g=new Um(s.level,s.sn,s.stats.chunkCount,n.byteLength,m,p),v=this.initPTS[s.cc];f.push(n,c,h,d,s,r,l.totalduration,u,g,v)}onAudioTrackSwitching(e,t){const s=this.hls,r=this.altAudio!==0;if(Xd(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(r){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(y.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(y.AUDIO_TRACK_SWITCHED,t)}),s.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(y.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=Xd(t.url,this.hls);if(s){const r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let r,n,a=!1;for(const o in s){const l=s[o];if(l.id==="main"){if(n=o,r=l,o==="video"){const d=s[o];d&&(this.videoBuffer=d.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:r}=t,n=s.type===J.MAIN;if(n){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===P.PARSED&&(this.state=P.IDLE);return}const o=r?r.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),et(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,r)}const a=this.media;a&&(!this._hasEnoughToStart&&ue.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case w.FRAG_GAP:case w.FRAG_PARSING_ERROR:case w.FRAG_DECRYPT_ERROR:case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(J.MAIN,t);break;case w.LEVEL_LOAD_ERROR:case w.LEVEL_LOAD_TIMEOUT:case w.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===ge.LEVEL&&(this.state=P.IDLE);break;case w.BUFFER_ADD_CODEC_ERROR:case w.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case w.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case w.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=P.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Ue.AUDIO||!this.altAudio){const s=(t===Ue.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,J.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 r=this.timelineOffset;r&&s&&(s+=r);const n=this.getLevelDetails(),a=ue.getBuffered(e),o=a.length?a.start(0):0,l=o-s,d=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<d||this.loadingParts&&l<2*(n?.partTarget||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),s+=l,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:r}=this,n=s?.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=P.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),r.trigger(y.FRAG_LOADED,s),n.bitrateTest=!1}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}const{frag:o,part:l,level:d}=a,{video:u,text:c,id3:h,initSegment:f}=r,{details:m}=d,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=P.PARSING,f){const g=f.tracks;if(g){const T=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(d,g,T,n),s.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:T,id:t,tracks:g})}const v=f.initPTS,b=f.timescale,E=this.initPTS[o.cc];if(X(v)&&(!E||E.baseTime!==v||E.timescale!==b)){const T=f.trackId;this.initPTS[o.cc]={baseTime:v,timescale:b,trackId:T},s.trigger(y.INIT_PTS_FOUND,{frag:o,id:t,initPTS:v,timescale:b,trackId:T})}}if(u&&m){p&&u.type==="audiovideo"&&this.logMuxedErr(o);const g=m.fragments[o.sn-1-m.startSN],v=o.sn===m.startSN,b=!g||o.cc>g.cc;if(r.independent!==!1){const{startPTS:E,endPTS:T,startDTS:A,endDTS:x}=u;if(l)l.elementaryStreams[u.type]={startPTS:E,endPTS:T,startDTS:A,endDTS:x};else if(u.firstKeyFrame&&u.independent&&n.id===1&&!b&&(this.couldBacktrack=!0),u.dropped&&u.independent){const S=this.getMainFwdBufferInfo(),L=(S?S.end:this.getLoadPosition())+this.config.maxBufferHole,R=u.firstKeyFramePTS?u.firstKeyFramePTS:E;if(!v&&L<R-this.config.maxBufferHole&&!b){this.backtrack(o);return}else b&&(o.gap=!0);o.setElementaryStreamInfo(u.type,o.start,T,o.start,x,!0)}else v&&E-(m.appliedTimelineOffset||0)>jl&&(o.gap=!0);o.setElementaryStreamInfo(u.type,E,T,A,x),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,l,n,v||b)}else if(v||b)o.gap=!0;else{this.backtrack(o);return}}if(p){const{startPTS:g,endPTS:v,startDTS:b,endDTS:E}=p;l&&(l.elementaryStreams[Ue.AUDIO]={startPTS:g,endPTS:v,startDTS:b,endDTS:E}),o.setElementaryStreamInfo(Ue.AUDIO,g,v,b,E),this.bufferFragmentData(p,o,l,n)}if(m&&h!=null&&h.samples.length){const g={id:t,frag:o,details:m,samples:h.samples};s.trigger(y.FRAG_PARSING_METADATA,g)}if(m&&c){const g={id:t,frag:o,details:m,samples:c.samples};s.trigger(y.FRAG_PARSING_USERDATA,g)}}logMuxedErr(e){this.warn(`${et(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,r){if(this.state!==P.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:n,video:a,audiovideo:o}=t;if(n){const d=e.audioCodec;let u=Hl(n.codec,d);u==="mp4a"&&(u="mp4a.40.5");const c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");const h=n.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&c.indexOf("firefox")===-1&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),d&&d!==u&&this.log(`Swapping manifest audio codec "${d}" for "${u}"`),n.levelCodec=u,n.id=J.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${u||""}/${d||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=J.MAIN;const d=a.codec;if(d?.length===4)switch(d){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||""}/${d}]${a.codec!==d?" 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 l=Object.keys(t);if(l.length){if(this.hls.trigger(y.BUFFER_CODECS,t),!this.hls)return;l.forEach(d=>{const c=t[d].initSegment;c!=null&&c.byteLength&&this.hls.trigger(y.BUFFER_APPENDING,{type:d,data:c,frag:s,part:null,chunkMeta:r,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,J.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e?.[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=P.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(ue.isBuffered(e,s)?t=this.getAppendedFrag(s):ue.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const r=this.fragPlaying,n=t.level;(!r||t.sn!==r.sn||r.level!==n)&&(this.fragPlaying=t,this.hls.trigger(y.FRAG_CHANGED,{frag:t}),(!r||r.level!==n)&&this.hls.trigger(y.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return X(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(X(t)){const s=this.getLevelDetails(),r=this.currentFrag||(s?Mr(null,s.fragments,t):null);if(r){const n=r.programDateTime;if(n!==null){const a=n+(t-r.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 Vw extends di{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const r=this.keyIdToKeyInfo[s].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=w.KEY_LOAD_ERROR,s,r,n){return new fs({type:ie.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:s,networkDetails:r})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,n=t.length;r<n;r++){const a=t[r];if(e.cc<=a.cc&&(!et(e)||!et(a)||e.sn<a.sn)||!s&&r==n-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);const l=Kl(o);if(l)return this.emeController.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){const r=ka(this.config);if(r.length)return this.emeController.getKeySystemAccess(r)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,r;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const d=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,d))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=Bc(n);let l=this.keyIdToKeyInfo[o];if((s=l)!=null&&s.decryptdata.key)return n.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&(r=l)!=null&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(u=>{const{keyInfo:c}=u;return n.key=c.decryptdata.key,{frag:e,keyInfo:c}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${n.keyId?" keyId: "+It(n.keyId):""} URI: ${n.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&(r=t.initSegment)!=null&&r.data){const a=dR(t.initSegment.data);if(a.length){let o=a[0];o.some(l=>l!==0)?(this.log(`Using keyId found in init segment ${It(o)}`),js.setKeyIdForUri(e.decryptdata.uri,o)):(o=js.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${It(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!et(t))return Promise.resolve(s);const n=this.emeController.loadKey(s);return(e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,s))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,r=s.loader,n=new r(s);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=s.keyLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{const{frag:g,keyInfo:v}=m,b=Bc(v.decryptdata);if(!g.decryptdata||v!==this.keyIdToKeyInfo[b])return o(this.createKeyLoadError(g,w.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));v.decryptdata.key=g.decryptdata.key=new Uint8Array(h.data),g.keyLoader=null,v.loader=null,a({frag:g,keyInfo:v})},onError:(h,f,m,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),m,Ce({url:l.url,data:void 0},h)))},onTimeout:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};n.load(l,u,c)})}resetLoader(e){const{frag:t,keyInfo:s,url:r}=e,n=s.loader;t.keyLoader===n&&(t.keyLoader=null,s.loader=null);const a=Bc(s.decryptdata)||r;delete this.keyIdToKeyInfo[a],n&&n.destroy()}}function Bc(i){if(i.keyFormat!==xt.FAIRPLAY){const e=i.keyId;if(e)return It(e)}return i.uri}function H0(i){const{type:e}=i;switch(e){case ge.AUDIO_TRACK:return J.AUDIO;case ge.SUBTITLE_TRACK:return J.SUBTITLE;default:return J.MAIN}}function Hc(i,e){let t=i.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Ww{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(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,r=t.loader,n=s||r,a=new n(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ge.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:r,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:s,level:r,pathwayId:n,responseType:"text",type:ge.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){const{id:s,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:ge.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:s,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:ge.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const s=this.loaders[ge.LEVEL];if(s){const r=s.context;r&&!t.levels.some(n=>n===r.levelOrTrack)&&(s.abort(),delete this.loaders[ge.LEVEL])}}load(e){var t;const s=this.hls.config;let r=this.getInternalLoader(e);if(r){const d=this.hls.logger,u=r.context;if(u&&u.levelOrTrack===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}let n;if(e.type===ge.MANIFEST?n=s.manifestLoadPolicy.default:n=Oe({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),X((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===ge.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===ge.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===ge.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){const u=d.partTarget,c=d.targetduration;if(u&&c){const h=Math.max(u*3,c*.8)*1e3;n=Oe({},n,{maxTimeToFirstByteMs:Math.min(h,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,n.maxTimeToFirstByteMs)})}}}const a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(d,u,c,h)=>{const f=this.getInternalLoader(c);this.resetInternalLoader(c.type);const m=d.data;u.parsing.start=performance.now(),Xi.isMediaPlaylist(m)||c.type!==ge.MANIFEST?this.handleTrackOrLevelPlaylist(d,u,c,h||null,f):this.handleMasterPlaylist(d,u,c,h)},onError:(d,u,c,h)=>{this.handleNetworkError(u,c,!1,d,h)},onTimeout:(d,u,c)=>{this.handleNetworkError(u,c,!0,void 0,d)}};r.load(e,o,l)}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,r){const n=this.hls,a=e.data,o=Hc(e,s),l=Xi.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,l.playlistParsingError,r,t);return}const{contentSteering:d,levels:u,sessionData:c,sessionKeys:h,startTimeOffset:f,variableList:m}=l;this.variableList=m,u.forEach(b=>{const{unknownCodecs:E}=b;if(E){const{preferManagedMediaSource:T}=this.hls.config;let{audioCodec:A,videoCodec:x}=b;for(let S=E.length;S--;){const L=E[S];mo(L,"audio",T)?(b.audioCodec=A=A?`${A},${L}`:L,Xn.audio[A.substring(0,4)]=2,E.splice(S,1)):mo(L,"video",T)&&(b.videoCodec=x=x?`${x},${L}`:L,Xn.video[x.substring(0,4)]=2,E.splice(S,1))}}});const{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":v}=Xi.parseMasterPlaylistMedia(a,o,l);p.length&&!p.some(E=>!E.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ye({}),bitrate:0,url:""})),n.trigger(y.MANIFEST_LOADED,{levels:u,audioTracks:p,subtitles:g,captions:v,contentSteering:d,url:o,stats:t,networkDetails:r,sessionData:c,sessionKeys:h,startTimeOffset:f,variableList:m})}handleTrackOrLevelPlaylist(e,t,s,r,n){const a=this.hls,{id:o,level:l,type:d}=s,u=Hc(e,s),c=X(l)?l:X(o)?o:0,h=H0(s),f=Xi.parseLevelPlaylist(e.data,u,c,h,0,this.variableList);if(d===ge.MANIFEST){const m={attrs:new Ye({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=t.loading.start+tb(f,0),a.trigger(y.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:u,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,r,n)}handleManifestParsingError(e,t,s,r,n){this.hls.trigger(y.ERROR,{type:ie.NETWORK_ERROR,details:w.MANIFEST_PARSING_ERROR,fatal:t.type===ge.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:r,stats:n})}handleNetworkError(e,t,s=!1,r,n){let a=`A network ${s?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===ge.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===ge.AUDIO_TRACK||e.type===ge.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=w.UNKNOWN,d=!1;const u=this.getInternalLoader(e);switch(e.type){case ge.MANIFEST:l=s?w.MANIFEST_LOAD_TIMEOUT:w.MANIFEST_LOAD_ERROR,d=!0;break;case ge.LEVEL:l=s?w.LEVEL_LOAD_TIMEOUT:w.LEVEL_LOAD_ERROR,d=!1;break;case ge.AUDIO_TRACK:l=s?w.AUDIO_TRACK_LOAD_TIMEOUT:w.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case ge.SUBTITLE_TRACK:l=s?w.SUBTITLE_TRACK_LOAD_TIMEOUT:w.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(e.type);const c={type:ie.NETWORK_ERROR,details:l,fatal:d,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:n};if(r){const h=t?.url||e.url;c.response=Ce({url:h,data:void 0},r)}this.hls.trigger(y.ERROR,c)}handlePlaylistLoaded(e,t,s,r,n,a){const o=this.hls,{type:l,level:d,levelOrTrack:u,id:c,groupId:h,deliveryDirectives:f}=r,m=Hc(t,r),p=H0(r);let g=typeof r.level=="number"&&p===J.MAIN?d:void 0;const v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(y.ERROR,{type:ie.NETWORK_ERROR,details:w.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:v,reason:v.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const b=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(y.ERROR,{type:ie.NETWORK_ERROR,details:w.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:b,reason:b.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:s});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case ge.MANIFEST:case ge.LEVEL:if(g){if(!u)g=0;else if(u!==o.levels[g]){const b=o.levels.indexOf(u);b>-1&&(g=b)}}o.trigger(y.LEVEL_LOADED,{details:e,levelInfo:u||o.levels[0],level:g||0,id:c||0,stats:s,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:l===ge.MANIFEST});break;case ge.AUDIO_TRACK:o.trigger(y.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:h||"",stats:s,networkDetails:n,deliveryDirectives:f});break;case ge.SUBTITLE_TRACK:o.trigger(y.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:h||"",stats:s,networkDetails:n,deliveryDirectives:f});break}}}class Vs{static get version(){return vo}static isMSESupported(){return eT()}static isSupported(){return Bw()}static getMediaSource(){return zs()}static get Events(){return y}static get MetadataSchema(){return zt}static get ErrorTypes(){return ie}static get ErrorDetails(){return w}static get DefaultConfig(){return Vs.defaultConfig?Vs.defaultConfig:Rw}static set DefaultConfig(e){Vs.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 Hm,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=XL(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=Dw(Vs.DefaultConfig,e,t);this.userConfig=e,s.progressive&&Cw(s,t);const{abrController:r,bufferController:n,capLevelController:a,errorController:o,fpsController:l}=s,d=new o(this),u=this.abrController=new r(this),c=new qR(this),h=s.interstitialsController,f=h?this.interstitialsController=new h(this,Vs):null,m=this.bufferController=new n(this,c),p=this.capLevelController=new a(this),g=new l(this),v=new Ww(this),b=s.contentSteeringController,E=b?new b(this):null,T=this.levelController=new Fw(this,E),A=new Uw(this),x=new Vw(this.config,this.logger),S=this.streamController=new Kw(this,c,x),L=this.gapController=new Ow(this,c);p.setStreamController(S),g.setStreamController(S);const R=[v,T,S];f&&R.splice(1,0,f),E&&R.splice(1,0,E),this.networkControllers=R;const I=[u,m,L,p,g,A,c];this.audioTrackController=this.createController(s.audioTrackController,R);const M=s.audioStreamController;M&&R.push(this.audioStreamController=new M(this,c,x)),this.subtitleTrackController=this.createController(s.subtitleTrackController,R);const B=s.subtitleStreamController;B&&R.push(this.subtititleStreamController=new B(this,c,x)),this.createController(s.timelineController,I),x.emeController=this.emeController=this.createController(s.emeController,I),this.cmcdController=this.createController(s.cmcdController,I),this.latencyController=this.createController($w,I),this.coreComponents=I,R.push(d);const q=d.onErrorOut;typeof q=="function"&&this.on(y.ERROR,q,d),this.on(y.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,r){this._emitter.off(e,t,s,r)}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 r=e===y.ERROR;this.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,fatal:r,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(y.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(y.ERROR,{type:ie.OTHER_ERROR,details:w.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,r=t?e:{media:s};this._media=s,this.trigger(y.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(y.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(y.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,r=this._url=Dm.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&s&&(s!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(y.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={[J.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[J.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[J.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=OC()),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){DR(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 r=0;r<s;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,s)for(let n=r;n--;){const a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=s)return n}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}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=By(t);return $y(e,s,navigator.mediaCapabilities)}}Vs.defaultConfig=void 0;var Ee=Vs,Fe={VIDEO:"video",THUMBNAIL:"thumbnail",STORYBOARD:"storyboard",DRM:"drm"},ae={NOT_AN_ERROR:0,NETWORK_OFFLINE:2000002,NETWORK_UNKNOWN_ERROR:2e6,NETWORK_NO_STATUS:2000001,NETWORK_INVALID_URL:24e5,NETWORK_NOT_FOUND:2404e3,NETWORK_NOT_READY:2412e3,NETWORK_GENERIC_SERVER_FAIL:25e5,NETWORK_TOKEN_MISSING:2403201,NETWORK_TOKEN_MALFORMED:2412202,NETWORK_TOKEN_EXPIRED:2403210,NETWORK_TOKEN_AUD_MISSING:2403221,NETWORK_TOKEN_AUD_MISMATCH:2403222,NETWORK_TOKEN_SUB_MISMATCH:2403232,ENCRYPTED_ERROR:5e6,ENCRYPTED_UNSUPPORTED_KEY_SYSTEM:5000001,ENCRYPTED_GENERATE_REQUEST_FAILED:5000002,ENCRYPTED_UPDATE_LICENSE_FAILED:5000003,ENCRYPTED_UPDATE_SERVER_CERT_FAILED:5000004,ENCRYPTED_CDM_ERROR:5000005,ENCRYPTED_OUTPUT_RESTRICTED:5000006,ENCRYPTED_MISSING_TOKEN:5000002},zu=i=>i===Fe.VIDEO?"playback":i,Ps=class Da extends Error{constructor(e,t=Da.MEDIA_ERR_CUSTOM,s,r){var n;super(e),this.name="MediaError",this.code=t,this.context=r,this.fatal=s??(t>=Da.MEDIA_ERR_NETWORK&&t<=Da.MEDIA_ERR_ENCRYPTED),this.message||(this.message=(n=Da.defaultMessages[this.code])!=null?n:"")}};Ps.MEDIA_ERR_ABORTED=1,Ps.MEDIA_ERR_NETWORK=2,Ps.MEDIA_ERR_DECODE=3,Ps.MEDIA_ERR_SRC_NOT_SUPPORTED=4,Ps.MEDIA_ERR_ENCRYPTED=5,Ps.MEDIA_ERR_CUSTOM=100,Ps.defaultMessages={1:"You aborted the media playback",2:"A network error caused the media download to fail.",3:"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.",4:"An unsupported error occurred. The server or network failed, or your browser does not support this format.",5:"The media is encrypted and there are no keys to decrypt it."};var Z=Ps,qw=i=>i==null,ep=(i,e)=>qw(e)?!1:i in e,tf={ANY:"any",MUTED:"muted"},ke={ON_DEMAND:"on-demand",LIVE:"live",UNKNOWN:"unknown"},Zi={MSE:"mse",NATIVE:"native"},Ca={HEADER:"header",QUERY:"query",NONE:"none"},nu=Object.values(Ca),vs={M3U8:"application/vnd.apple.mpegurl",MP4:"video/mp4"},G0={HLS:vs.M3U8};[...Object.values(vs)];var ol={upTo720p:"720p",upTo1080p:"1080p",upTo1440p:"1440p",upTo2160p:"2160p"},Xr={noLessThan480p:"480p",noLessThan540p:"540p",noLessThan720p:"720p",noLessThan1080p:"1080p",noLessThan1440p:"1440p",noLessThan2160p:"2160p"},Yw="en",sf={code:Yw},nt=(i,e,t,s,r=i)=>{r.addEventListener(e,t,s),i.addEventListener("teardown",()=>{r.removeEventListener(e,t)},{once:!0})};function jw(i,e,t){e&&t>e&&(t=e);for(let s=0;s<i.length;s++)if(i.start(s)<=t&&i.end(s)>=t)return!0;return!1}var tp=i=>{let e=i.indexOf("?");if(e<0)return[i];let t=i.slice(0,e),s=i.slice(e);return[t,s]},Qu=i=>{let{type:e}=i;if(e){let t=e.toUpperCase();return ep(t,G0)?G0[t]:e}return zw(i)},tT=i=>i==="VOD"?ke.ON_DEMAND:ke.LIVE,iT=i=>i==="EVENT"?Number.POSITIVE_INFINITY:i==="VOD"?Number.NaN:0,zw=i=>{let{src:e}=i;if(!e)return"";let t="";try{t=new URL(e).pathname}catch{console.error("invalid url")}let s=t.lastIndexOf(".");if(s<0)return Xw(i)?vs.M3U8:"";let r=t.slice(s+1).toUpperCase();return ep(r,vs)?vs[r]:""},Qw="mux.com",Xw=({src:i,customDomain:e=Qw})=>{let t;try{t=new URL(`${i}`)}catch{return!1}let s=t.protocol==="https:",r=t.hostname===`stream.${e}`.toLowerCase(),n=t.pathname.split("/"),a=n.length===2,o=!(n!=null&&n[1].includes("."));return s&&r&&a&&o},Bn=i=>{let e=(i??"").split(".")[1];if(e)try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(atob(t).split("").map(function(r){return"%"+("00"+r.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(s)}catch{return}},Zw=({exp:i},e=Date.now())=>!i||i*1e3<e,Jw=({sub:i},e)=>i!==e,eM=({aud:i},e)=>!i,tM=({aud:i},e)=>i!==e,sT="en";function se(i,e=!0){var t,s;let r=e&&(s=(t=sf)==null?void 0:t[i])!=null?s:i,n=e?sf.code:sT;return new iM(r,n)}var iM=class{constructor(i,e=(t=>(t=sf)!=null?t:sT)()){this.message=i,this.locale=e}format(i){return this.message.replace(/\{(\w+)\}/g,(e,t)=>{var s;return(s=i[t])!=null?s:""})}toString(){return this.message}},sM=Object.values(tf),K0=i=>typeof i=="boolean"||typeof i=="string"&&sM.includes(i),rM=(i,e,t)=>{let{autoplay:s}=i,r=!1,n=!1,a=K0(s)?s:!!s,o=()=>{r||nt(e,"playing",()=>{r=!0},{once:!0})};if(o(),nt(e,"loadstart",()=>{r=!1,o(),Gc(e,a)},{once:!0}),nt(e,"loadstart",()=>{t||(i.streamType&&i.streamType!==ke.UNKNOWN?n=i.streamType===ke.LIVE:n=!Number.isFinite(e.duration)),Gc(e,a)},{once:!0}),t&&t.once(Ee.Events.LEVEL_LOADED,(l,d)=>{var u;i.streamType&&i.streamType!==ke.UNKNOWN?n=i.streamType===ke.LIVE:n=(u=d.details.live)!=null?u:!1}),!a){let l=()=>{!n||Number.isFinite(i.startTime)||(t!=null&&t.liveSyncPosition?e.currentTime=t.liveSyncPosition:Number.isFinite(e.seekable.end(0))&&(e.currentTime=e.seekable.end(0)))};t&&nt(e,"play",()=>{e.preload==="metadata"?t.once(Ee.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{r||(a=K0(l)?l:!!l,Gc(e,a))}},Gc=(i,e)=>{if(!e)return;let t=i.muted,s=()=>i.muted=t;switch(e){case tf.ANY:i.play().catch(()=>{i.muted=!0,i.play().catch(s)});break;case tf.MUTED:i.muted=!0,i.play().catch(s);break;default:i.play().catch(()=>{});break}},nM=({preload:i,src:e},t,s)=>{let r=c=>{c!=null&&["","none","metadata","auto"].includes(c)?t.setAttribute("preload",c):t.removeAttribute("preload")};if(!s)return r(i),r;let n=!1,a=!1,o=s.config.maxBufferLength,l=s.config.maxBufferSize,d=c=>{r(c);let h=c??t.preload;a||h==="none"||(h==="metadata"?(s.config.maxBufferLength=1,s.config.maxBufferSize=1):(s.config.maxBufferLength=o,s.config.maxBufferSize=l),u())},u=()=>{!n&&e&&(n=!0,s.loadSource(e))};return nt(t,"play",()=>{a=!0,s.config.maxBufferLength=o,s.config.maxBufferSize=l,u()},{once:!0}),d(i),d};function aM(i,e){var t;if(!("videoTracks"in i))return;let s=new WeakMap;e.on(Ee.Events.MANIFEST_PARSED,function(l,d){o();let u=i.addVideoTrack("main");u.selected=!0;for(let[c,h]of d.levels.entries()){let f=u.addRendition(h.url[0],h.width,h.height,h.videoCodec,h.bitrate);s.set(h,`${c}`),f.id=`${c}`}}),e.on(Ee.Events.AUDIO_TRACKS_UPDATED,function(l,d){a();for(let u of d.audioTracks){let c=u.default?"main":"alternative",h=i.addAudioTrack(c,u.name,u.lang);h.id=`${u.id}`,u.default&&(h.enabled=!0)}}),i.audioTracks.addEventListener("change",()=>{var l;let d=+((l=[...i.audioTracks].find(c=>c.enabled))==null?void 0:l.id),u=e.audioTracks.map(c=>c.id);d!=e.audioTrack&&u.includes(d)&&(e.audioTrack=d)}),e.on(Ee.Events.LEVELS_UPDATED,function(l,d){var u;let c=i.videoTracks[(u=i.videoTracks.selectedIndex)!=null?u:0];if(!c)return;let h=d.levels.map(f=>s.get(f));for(let f of i.videoRenditions)f.id&&!h.includes(f.id)&&c.removeRendition(f)});let r=l=>{let d=l.target.selectedIndex;d!=e.nextLevel&&(e.nextLevel=d)};(t=i.videoRenditions)==null||t.addEventListener("change",r);let n=()=>{for(let l of i.videoTracks)i.removeVideoTrack(l)},a=()=>{for(let l of i.audioTracks)i.removeAudioTrack(l)},o=()=>{n(),a()};e.once(Ee.Events.DESTROYING,o)}var Kc=i=>"time"in i?i.time:i.startTime;function oM(i,e){e.on(Ee.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(r,{tracks:n})=>{n.forEach(a=>{var o,l;let d=(o=a.subtitleTrack)!=null?o:a.closedCaptions,u=e.subtitleTracks.findIndex(({lang:h,name:f,type:m})=>h==d?.lang&&f===a.label&&m.toLowerCase()===a.kind),c=((l=a._id)!=null?l:a.default)?"default":`${a.kind}${u}`;ip(i,a.kind,a.label,d?.lang,c,a.default)})});let t=()=>{if(!e.subtitleTracks.length)return;let r=Array.from(i.textTracks).find(o=>o.id&&o.mode==="showing"&&["subtitles","captions"].includes(o.kind));if(!r)return;let n=e.subtitleTracks[e.subtitleTrack],a=n?n.default?"default":`${e.subtitleTracks[e.subtitleTrack].type.toLowerCase()}${e.subtitleTrack}`:void 0;if(e.subtitleTrack<0||r?.id!==a){let o=e.subtitleTracks.findIndex(({lang:l,name:d,type:u,default:c})=>r.id==="default"&&c||l==r.language&&d===r.label&&u.toLowerCase()===r.kind);e.subtitleTrack=o}r?.id===a&&r.cues&&Array.from(r.cues).forEach(o=>{r.addCue(o)})};i.textTracks.addEventListener("change",t),e.on(Ee.Events.CUES_PARSED,(r,{track:n,cues:a})=>{let o=i.textTracks.getTrackById(n);if(!o)return;let l=o.mode==="disabled";l&&(o.mode="hidden"),a.forEach(d=>{var u;(u=o.cues)!=null&&u.getCueById(d.id)||o.addCue(d)}),l&&(o.mode="disabled")}),e.once(Ee.Events.DESTROYING,()=>{i.textTracks.removeEventListener("change",t),i.querySelectorAll("track[data-removeondestroy]").forEach(r=>{r.remove()})});let s=()=>{Array.from(i.textTracks).forEach(r=>{var n,a;if(!["subtitles","caption"].includes(r.kind)&&(r.label==="thumbnails"||r.kind==="chapters")){if(!((n=r.cues)!=null&&n.length)){let o="track";r.kind&&(o+=`[kind="${r.kind}"]`),r.label&&(o+=`[label="${r.label}"]`);let l=i.querySelector(o),d=(a=l?.getAttribute("src"))!=null?a:"";l?.removeAttribute("src"),setTimeout(()=>{l?.setAttribute("src",d)},0)}r.mode!=="hidden"&&(r.mode="hidden")}})};e.once(Ee.Events.MANIFEST_LOADED,s),e.once(Ee.Events.MEDIA_ATTACHED,s)}function ip(i,e,t,s,r,n){let a=document.createElement("track");return a.kind=e,a.label=t,s&&(a.srclang=s),r&&(a.id=r),n&&(a.default=!0),a.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",a.setAttribute("data-removeondestroy",""),i.append(a),a.track}function lM(i,e){let t=Array.prototype.find.call(i.querySelectorAll("track"),s=>s.track===e);t?.remove()}function Lo(i,e,t){var s;return(s=Array.from(i.querySelectorAll("track")).find(r=>r.track.label===e&&r.track.kind===t))==null?void 0:s.track}async function rT(i,e,t,s){let r=Lo(i,t,s);return r||(r=ip(i,s,t),r.mode="hidden",await new Promise(n=>setTimeout(()=>n(void 0),0))),r.mode!=="hidden"&&(r.mode="hidden"),[...e].sort((n,a)=>Kc(a)-Kc(n)).forEach(n=>{var a,o;let l=n.value,d=Kc(n);if("endTime"in n&&n.endTime!=null)r?.addCue(new VTTCue(d,n.endTime,s==="chapters"?l:JSON.stringify(l??null)));else{let u=Array.prototype.findIndex.call(r?.cues,m=>m.startTime>=d),c=(a=r?.cues)==null?void 0:a[u],h=c?c.startTime:Number.isFinite(i.duration)?i.duration:Number.MAX_SAFE_INTEGER,f=(o=r?.cues)==null?void 0:o[u-1];f&&(f.endTime=d),r?.addCue(new VTTCue(d,h,s==="chapters"?l:JSON.stringify(l??null)))}}),i.textTracks.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),r}var sp="cuepoints",nT=Object.freeze({label:sp});async function aT(i,e,t=nT){return rT(i,e,t.label,"metadata")}var rf=i=>({time:i.startTime,value:JSON.parse(i.text)});function dM(i,e={label:sp}){let t=Lo(i,e.label,"metadata");return t!=null&&t.cues?Array.from(t.cues,s=>rf(s)):[]}function oT(i,e={label:sp}){var t,s;let r=Lo(i,e.label,"metadata");if(!((t=r?.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return rf(r.activeCues[0]);let{currentTime:n}=i,a=Array.prototype.find.call((s=r.activeCues)!=null?s:[],({startTime:o,endTime:l})=>o<=n&&l>n);return rf(a||r.activeCues[0])}async function uM(i,e=nT){return new Promise(t=>{nt(i,"loadstart",async()=>{let s=await aT(i,[],e);nt(i,"cuechange",()=>{let r=oT(i);if(r){let n=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:r});i.dispatchEvent(n)}},{},s),t(s)})})}var rp="chapters",lT=Object.freeze({label:rp}),nf=i=>({startTime:i.startTime,endTime:i.endTime,value:i.text});async function dT(i,e,t=lT){return rT(i,e,t.label,"chapters")}function cM(i,e={label:rp}){var t;let s=Lo(i,e.label,"chapters");return(t=s?.cues)!=null&&t.length?Array.from(s.cues,r=>nf(r)):[]}function uT(i,e={label:rp}){var t,s;let r=Lo(i,e.label,"chapters");if(!((t=r?.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return nf(r.activeCues[0]);let{currentTime:n}=i,a=Array.prototype.find.call((s=r.activeCues)!=null?s:[],({startTime:o,endTime:l})=>o<=n&&l>n);return nf(a||r.activeCues[0])}async function hM(i,e=lT){return new Promise(t=>{nt(i,"loadstart",async()=>{let s=await dT(i,[],e);nt(i,"cuechange",()=>{let r=uT(i);if(r){let n=new CustomEvent("chapterchange",{composed:!0,bubbles:!0,detail:r});i.dispatchEvent(n)}},{},s),t(s)})})}function fM(i,e){if(e){let t=e.playingDate;if(t!=null)return new Date(t.getTime()-i.currentTime*1e3)}return typeof i.getStartDate=="function"?i.getStartDate():new Date(NaN)}function mM(i,e){if(e&&e.playingDate)return e.playingDate;if(typeof i.getStartDate=="function"){let t=i.getStartDate();return new Date(t.getTime()+i.currentTime*1e3)}return new Date(NaN)}var Za={VIDEO:"v",THUMBNAIL:"t",STORYBOARD:"s",DRM:"d"},pM=i=>{if(i===Fe.VIDEO)return Za.VIDEO;if(i===Fe.DRM)return Za.DRM},gM=(i,e)=>{var t,s;let r=zu(i),n=`${r}Token`;return(t=e.tokens)!=null&&t[r]?(s=e.tokens)==null?void 0:s[r]:ep(n,e)?e[n]:void 0},au=(i,e,t,s,r=!1,n=!(a=>(a=globalThis.navigator)==null?void 0:a.onLine)())=>{var a,o;if(n){let v=se("Your device appears to be offline",r),b,E=Z.MEDIA_ERR_NETWORK,T=new Z(v,E,!1,b);return T.errorCategory=e,T.muxCode=ae.NETWORK_OFFLINE,T.data=i,T}let l="status"in i?i.status:i.code,d=Date.now(),u=Z.MEDIA_ERR_NETWORK;if(l===200)return;let c=zu(e),h=gM(e,t),f=pM(e),[m]=tp((a=t.playbackId)!=null?a:"");if(!l||!m)return;let p=Bn(h);if(h&&!p){let v=se("The {tokenNamePrefix}-token provided is invalid or malformed.",r).format({tokenNamePrefix:c}),b=se("Compact JWT string: {token}",r).format({token:h}),E=new Z(v,u,!0,b);return E.errorCategory=e,E.muxCode=ae.NETWORK_TOKEN_MALFORMED,E.data=i,E}if(l>=500){let v=new Z("",u,s??!0);return v.errorCategory=e,v.muxCode=ae.NETWORK_UNKNOWN_ERROR,v}if(l===403)if(p){if(Zw(p,d)){let v={timeStyle:"medium",dateStyle:"medium"},b=se("The video’s secured {tokenNamePrefix}-token has expired.",r).format({tokenNamePrefix:c}),E=se("Expired at: {expiredDate}. Current time: {currentDate}.",r).format({expiredDate:new Intl.DateTimeFormat("en",v).format((o=p.exp)!=null?o:0*1e3),currentDate:new Intl.DateTimeFormat("en",v).format(d)}),T=new Z(b,u,!0,E);return T.errorCategory=e,T.muxCode=ae.NETWORK_TOKEN_EXPIRED,T.data=i,T}if(Jw(p,m)){let v=se("The video’s playback ID does not match the one encoded in the {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c}),b=se("Specified playback ID: {playbackId} and the playback ID encoded in the {tokenNamePrefix}-token: {tokenPlaybackId}",r).format({tokenNamePrefix:c,playbackId:m,tokenPlaybackId:p.sub}),E=new Z(v,u,!0,b);return E.errorCategory=e,E.muxCode=ae.NETWORK_TOKEN_SUB_MISMATCH,E.data=i,E}if(eM(p)){let v=se("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),b=se("The {tokenNamePrefix}-token has no aud value. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f}),E=new Z(v,u,!0,b);return E.errorCategory=e,E.muxCode=ae.NETWORK_TOKEN_AUD_MISSING,E.data=i,E}if(tM(p,f)){let v=se("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),b=se("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f,aud:p.aud}),E=new Z(v,u,!0,b);return E.errorCategory=e,E.muxCode=ae.NETWORK_TOKEN_AUD_MISMATCH,E.data=i,E}}else{let v=se("Authorization error trying to access this {category} URL. If this is a signed URL, you might need to provide a {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c,category:e}),b=se("Specified playback ID: {playbackId}",r).format({playbackId:m}),E=new Z(v,u,s??!0,b);return E.errorCategory=e,E.muxCode=ae.NETWORK_TOKEN_MISSING,E.data=i,E}if(l===412){let v=se("This playback-id may belong to a live stream that is not currently active or an asset that is not ready.",r),b=se("Specified playback ID: {playbackId}",r).format({playbackId:m}),E=new Z(v,u,s??!0,b);return E.errorCategory=e,E.muxCode=ae.NETWORK_NOT_READY,E.streamType=t.streamType===ke.LIVE?"live":t.streamType===ke.ON_DEMAND?"on-demand":"unknown",E.data=i,E}if(l===404){let v=se("This URL or playback-id does not exist. You may have used an Asset ID or an ID from a different resource.",r),b=se("Specified playback ID: {playbackId}",r).format({playbackId:m}),E=new Z(v,u,s??!0,b);return E.errorCategory=e,E.muxCode=ae.NETWORK_NOT_FOUND,E.data=i,E}if(l===400){let v=se("The URL or playback-id was invalid. You may have used an invalid value as a playback-id."),b=se("Specified playback ID: {playbackId}",r).format({playbackId:m}),E=new Z(v,u,s??!0,b);return E.errorCategory=e,E.muxCode=ae.NETWORK_INVALID_URL,E.data=i,E}let g=new Z("",u,s??!0);return g.errorCategory=e,g.muxCode=ae.NETWORK_UNKNOWN_ERROR,g.data=i,g},V0=Ee.DefaultConfig.capLevelController,vM={"720p":921600,"1080p":2073600,"1440p":4194304,"2160p":8294400};function EM(i){let e=i.toLowerCase().trim();return vM[e]}var af=class wa extends V0{constructor(e){super(e)}static setMaxAutoResolution(e,t){t?wa.maxAutoResolution.set(e,t):wa.maxAutoResolution.delete(e)}getMaxAutoResolution(){var e;let t=this.hls;return(e=wa.maxAutoResolution.get(t))!=null?e:void 0}get levels(){var e;return(e=this.hls.levels)!=null?e:[]}getValidLevels(e){return this.levels.filter((t,s)=>this.isLevelAllowed(t)&&s<=e)}getMaxLevelCapped(e){let t=this.getValidLevels(e),s=this.getMaxAutoResolution();if(!s)return super.getMaxLevel(e);let r=EM(s);if(!r)return super.getMaxLevel(e);let n=t.filter(l=>l.width*l.height<=r),a=n.findIndex(l=>l.width*l.height===r);if(a!==-1){let l=n[a];return t.findIndex(d=>d===l)}if(n.length===0)return 0;let o=n[n.length-1];return t.findIndex(l=>l===o)}getMaxLevel(e){if(this.getMaxAutoResolution()!==void 0)return this.getMaxLevelCapped(e);let t=super.getMaxLevel(e),s=this.getValidLevels(e);if(!s[t])return t;let r=Math.min(s[t].width,s[t].height),n=wa.minMaxResolution;return r>=n?t:V0.getMaxLevelByMediaSize(s,n*(16/9),n)}};af.minMaxResolution=720,af.maxAutoResolution=new WeakMap;var yM=af,Vc=yM,zl={FAIRPLAY:"fairplay",PLAYREADY:"playready",WIDEVINE:"widevine"},bM=i=>{if(i.includes("fps"))return zl.FAIRPLAY;if(i.includes("playready"))return zl.PLAYREADY;if(i.includes("widevine"))return zl.WIDEVINE},TM=i=>{let e=i.split(`
|
|
1457
1457
|
`).find((t,s,r)=>s&&r[s-1].startsWith("#EXT-X-STREAM-INF"));return fetch(e).then(t=>t.status!==200?Promise.reject(t):t.text())},_M=i=>{let e=i.split(`
|
|
1458
1458
|
`).filter(s=>s.startsWith("#EXT-X-SESSION-DATA"));if(!e.length)return{};let t={};for(let s of e){let r=SM(s),n=r["DATA-ID"];n&&(t[n]={...r})}return{sessionData:t}},AM=/([A-Z0-9-]+)="?(.*?)"?(?:,|$)/g;function SM(i){let e=[...i.matchAll(AM)];return Object.fromEntries(e.map(([,t,s])=>[t,s]))}var IM=i=>{var e,t,s;let r=i.split(`
|
|
1459
|
-
`),n=(t=((e=r.find(d=>d.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),a=tT(n),o=iT(n),l;if(a===ke.LIVE){let d=r.find(u=>u.startsWith("#EXT-X-PART-INF"));if(d)l=+d.split(":")[1].split("=")[1]*2;else{let u=r.find(h=>h.startsWith("#EXT-X-TARGETDURATION")),c=(s=u?.split(":"))==null?void 0:s[1];l=+(c??6)*3}}return{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}},xM=async(i,e)=>{if(e===vs.MP4)return{streamType:ke.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0,sessionData:void 0};if(e===vs.M3U8){let t=await fetch(i);if(!t.ok)return Promise.reject(t);let s=await t.text(),r=await TM(s);return{..._M(s),...IM(r)}}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${i}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0,sessionData:void 0}},LM=async(i,e,t=Qu({src:i}))=>{var s,r,n,a;let{streamType:o,targetLiveWindow:l,liveEdgeStartOffset:d,sessionData:u}=await xM(i,t),c=u?.["com.apple.hls.chapters"];(c!=null&&c.URI||c!=null&&c.VALUE.toLocaleLowerCase().startsWith("http"))&&np((s=c.URI)!=null?s:c.VALUE,e),((r=Ze.get(e))!=null?r:{}).liveEdgeStartOffset=d,((n=Ze.get(e))!=null?n:{}).targetLiveWindow=l,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((a=Ze.get(e))!=null?a:{}).streamType=o,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},np=async(i,e)=>{var t,s;try{let r=await fetch(i);if(!r.ok)throw new Error(`Failed to fetch Mux metadata: ${r.status} ${r.statusText}`);let n=await r.json(),a={};if(!((t=n?.[0])!=null&&t.metadata))return;for(let l of n[0].metadata)l.key&&l.value&&(a[l.key]=l.value);((s=Ze.get(e))!=null?s:{}).metadata=a;let o=new CustomEvent("muxmetadata");e.dispatchEvent(o)}catch(r){console.error(r)}},RM=i=>{var e;let t=i.type,s=tT(t),r=iT(t),n,a=!!((e=i.partList)!=null&&e.length);return s===ke.LIVE&&(n=a?i.partTarget*2:i.targetduration*3),{streamType:s,targetLiveWindow:r,liveEdgeStartOffset:n,lowLatency:a}},kM=(i,e,t)=>{var s,r,n,a,o,l,d,u;let{streamType:c,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:m}=RM(i);if(c===ke.LIVE){m?(t.config.backBufferLength=(s=t.userConfig.backBufferLength)!=null?s:4,t.config.maxFragLookUpTolerance=(r=t.userConfig.maxFragLookUpTolerance)!=null?r:.001,t.config.abrBandWidthUpFactor=(n=t.userConfig.abrBandWidthUpFactor)!=null?n:t.config.abrBandWidthFactor):t.config.backBufferLength=(a=t.userConfig.backBufferLength)!=null?a:8;let p=Object.freeze({get length(){return e.seekable.length},start(g){return e.seekable.start(g)},end(g){var v;return g>this.length||g<0||Number.isFinite(e.duration)?e.seekable.end(g):(v=t.liveSyncPosition)!=null?v:e.seekable.end(g)}});((o=Ze.get(e))!=null?o:{}).seekable=p}((l=Ze.get(e))!=null?l:{}).liveEdgeStartOffset=f,((d=Ze.get(e))!=null?d:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((u=Ze.get(e))!=null?u:{}).streamType=c,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},W0,q0,cT=(q0=(W0=globalThis?.navigator)==null?void 0:W0.userAgent)!=null?q0:"",Y0,j0,z0,DM=(z0=(j0=(Y0=globalThis?.navigator)==null?void 0:Y0.userAgentData)==null?void 0:j0.platform)!=null?z0:"",CM=cT.toLowerCase().includes("android")||["x11","android"].some(i=>DM.toLowerCase().includes(i)),wM=i=>/^((?!chrome|android).)*safari/i.test(cT)&&!!i.canPlayType("application/vnd.apple.mpegurl"),Ze=new WeakMap,Es="mux.com",Q0,X0,hT=(X0=(Q0=Ee).isSupported)==null?void 0:X0.call(Q0),MM=i=>CM||!wM(i),ap=()=>{if(typeof window<"u")return km.utils.now()},PM=km.utils.generateUUID,of=({playbackId:i,customDomain:e=Es,maxResolution:t,minResolution:s,renditionOrder:r,programStartTime:n,programEndTime:a,assetStartTime:o,assetEndTime:l,playbackToken:d,tokens:{playback:u=d}={},extraSourceParams:c={}}={})=>{if(!i)return;let[h,f=""]=tp(i),m=new URL(`https://stream.${e}/${h}.m3u8${f}`);return u||m.searchParams.has("token")?(m.searchParams.forEach((p,g)=>{g!="token"&&m.searchParams.delete(g)}),u&&m.searchParams.set("token",u)):(t&&m.searchParams.set("max_resolution",t),s&&(m.searchParams.set("min_resolution",s),t&&+t.slice(0,-1)<+s.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",s,"maxResolution",t)),r&&m.searchParams.set("rendition_order",r),n&&m.searchParams.set("program_start_time",`${n}`),a&&m.searchParams.set("program_end_time",`${a}`),o&&m.searchParams.set("asset_start_time",`${o}`),l&&m.searchParams.set("asset_end_time",`${l}`),Object.entries(c).forEach(([p,g])=>{g!=null&&m.searchParams.set(p,g)})),m.toString()},Xu=i=>{if(!i)return;let[e]=i.split("?");return e||void 0},op=i=>{if(!i||!i.startsWith("https://stream."))return;let[e]=new URL(i).pathname.slice(1).split(/\.m3u8|\//);return e||void 0},OM=i=>{var e,t,s;return(e=i?.metadata)!=null&&e.video_id?i.metadata.video_id:bT(i)&&(s=(t=Xu(i.playbackId))!=null?t:op(i.src))!=null?s:i.src},fT=i=>{var e;return(e=Ze.get(i))==null?void 0:e.error},NM=i=>{var e;return(e=Ze.get(i))==null?void 0:e.metadata},lf=i=>{var e,t;return(t=(e=Ze.get(i))==null?void 0:e.streamType)!=null?t:ke.UNKNOWN},UM=i=>{var e,t;return(t=(e=Ze.get(i))==null?void 0:e.targetLiveWindow)!=null?t:Number.NaN},lp=i=>{var e,t;return(t=(e=Ze.get(i))==null?void 0:e.seekable)!=null?t:i.seekable},$M=i=>{var e;let t=(e=Ze.get(i))==null?void 0:e.liveEdgeStartOffset;if(typeof t!="number")return Number.NaN;let s=lp(i);return s.length?s.end(s.length-1)-t:Number.NaN},dp=.034,FM=(i,e,t=dp)=>Math.abs(i-e)<=t,mT=(i,e,t=dp)=>i>e||FM(i,e,t),BM=(i,e=dp)=>i.paused&&mT(i.currentTime,i.duration,e),pT=(i,e)=>{var t,s,r;if(!e||!i.buffered.length)return;if(i.readyState>2)return!1;let n=e.currentLevel>=0?(s=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:s.details:(r=e.levels.find(c=>!!c.details))==null?void 0:r.details;if(!n||n.live)return;let{fragments:a}=n;if(!(a!=null&&a.length))return;if(i.currentTime<i.duration-(n.targetduration+.5))return!1;let o=a[a.length-1];if(i.currentTime<=o.start)return!1;let l=o.start+o.duration/2,d=i.buffered.start(i.buffered.length-1),u=i.buffered.end(i.buffered.length-1);return l>d&&l<u},gT=(i,e)=>i.ended||i.loop?i.ended:e&&pT(i,e)?!0:BM(i),HM=(i,e,t)=>{vT(e,t,i);let{metadata:s={}}=i,{view_session_id:r=PM()}=s,n=OM(i);s.view_session_id=r,s.video_id=n,i.metadata=s;let a=u=>{var c;(c=e.mux)==null||c.emit("hb",{view_drm_type:u})};i.drmTypeCb=a,Ze.set(e,{retryCount:0});let o=GM(i,e),l=nM(i,e,o);i!=null&&i.muxDataKeepSession&&e!=null&&e.mux&&!e.mux.deleted?o&&e.mux.addHLSJS({hlsjs:o,Hls:o?Ee:void 0}):jM(i,e,o),zM(i,e,o),uM(e),hM(e);let d=rM(i,e,o);return{engine:o,setAutoplay:d,setPreload:l}},vT=(i,e,t)=>{let s=e?.engine;i!=null&&i.mux&&!i.mux.deleted&&(t!=null&&t.muxDataKeepSession?s&&i.mux.removeHLSJS():(i.mux.destroy(),delete i.mux)),s&&(s.detachMedia(),s.destroy()),i&&(i.hasAttribute("src")&&(i.removeAttribute("src"),i.load()),i.removeEventListener("error",_T),i.removeEventListener("error",df),i.removeEventListener("durationchange",TT),Ze.delete(i),i.dispatchEvent(new Event("teardown")))};function ET(i,e){var t;let s=Qu(i);if(s!==vs.M3U8)return!0;let r=!s||((t=e.canPlayType(s))!=null?t:!0),{preferPlayback:n}=i,a=n===Zi.MSE,o=n===Zi.NATIVE,l=hT&&(a||MM(e));return r&&(o||!l)}var GM=(i,e)=>{let{debug:t,streamType:s,startTime:r=-1,metadata:n,preferCmcd:a,_hlsConfig:o={},maxAutoResolution:l}=i,d=Qu(i)===vs.M3U8,u=ET(i,e);if(d&&!u&&hT){let c={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelToPlayerSize:!0,capLevelOnFPSDrop:!0},h=KM(s),f=VM(i),m=[Ca.QUERY,Ca.HEADER].includes(a)?{useHeaders:a===Ca.HEADER,sessionId:n?.view_session_id,contentId:n?.video_id}:void 0,p=o.capLevelToPlayerSize==null?{capLevelController:Vc}:{},g=new Ee({debug:t,startPosition:r,cmcd:m,xhrSetup:(v,b)=>{var E,T;if(a&&a!==Ca.QUERY)return;let A=new URL(b);if(!A.searchParams.has("CMCD"))return;let x=((T=(E=A.searchParams.get("CMCD"))==null?void 0:E.split(","))!=null?T:[]).filter(S=>S.startsWith("sid")||S.startsWith("cid")).join(",");A.searchParams.set("CMCD",x),v.open("GET",A)},...p,...c,...h,...f,...o});return p.capLevelController===Vc&&l!==void 0&&Vc.setMaxAutoResolution(g,l),g.on(Ee.Events.MANIFEST_PARSED,async function(v,b){var E,T;let A=(E=b.sessionData)==null?void 0:E["com.apple.hls.chapters"];(A!=null&&A.URI||A!=null&&A.VALUE.toLocaleLowerCase().startsWith("http"))&&np((T=A?.URI)!=null?T:A?.VALUE,e)}),g}},KM=i=>i===ke.LIVE?{backBufferLength:8}:{},VM=i=>{let{tokens:{drm:e}={},playbackId:t,drmTypeCb:s}=i,r=Xu(t);return!e||!r?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:Ql(i,"fairplay"),serverCertificateUrl:yT(i,"fairplay")},"com.widevine.alpha":{licenseUrl:Ql(i,"widevine")},"com.microsoft.playready":{licenseUrl:Ql(i,"playready")}},requestMediaKeySystemAccessFunc:(n,a)=>(n==="com.widevine.alpha"&&(a=[...a.map(o=>{var l;let d=(l=o.videoCapabilities)==null?void 0:l.map(u=>({...u,robustness:"HW_SECURE_ALL"}));return{...o,videoCapabilities:d}}),...a]),navigator.requestMediaKeySystemAccess(n,a).then(o=>{let l=bM(n);return s?.(l),o}))}},WM=async i=>{let e=await fetch(i);return e.status!==200?Promise.reject(e):await e.arrayBuffer()},qM=async(i,e)=>{let t=await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:i});if(t.status!==200)return Promise.reject(t);let s=await t.arrayBuffer();return new Uint8Array(s)},YM=(i,e)=>{let t=async n=>{let a=await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[n],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}]).then(l=>{var d;return(d=i.drmTypeCb)==null||d.call(i,zl.FAIRPLAY),l}).catch(()=>{let l=re("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),d=new X(l,X.MEDIA_ERR_ENCRYPTED,!0);d.errorCategory=Fe.DRM,d.muxCode=ae.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,Qt(e,d)});if(!a)return;let o=await a.createMediaKeys();try{let l=await WM(yT(i,"fairplay")).catch(d=>{if(d instanceof Response){let u=au(d,Fe.DRM,i);return console.error("mediaError",u?.message,u?.context),u?Promise.reject(u):Promise.reject(new Error("Unexpected error in app cert request"))}return Promise.reject(d)});await o.setServerCertificate(l).catch(()=>{let d=re("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."),u=new X(d,X.MEDIA_ERR_ENCRYPTED,!0);return u.errorCategory=Fe.DRM,u.muxCode=ae.ENCRYPTED_UPDATE_SERVER_CERT_FAILED,Promise.reject(u)})}catch(l){Qt(e,l);return}await e.setMediaKeys(o)},s=n=>{let a;if(n==="internal-error"){let o=re("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser.");a=new X(o,X.MEDIA_ERR_ENCRYPTED,!0),a.errorCategory=Fe.DRM,a.muxCode=ae.ENCRYPTED_CDM_ERROR}else if(n==="output-restricted"||n==="output-downscaled"){let o=re("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");a=new X(o,X.MEDIA_ERR_ENCRYPTED,!1),a.errorCategory=Fe.DRM,a.muxCode=ae.ENCRYPTED_OUTPUT_RESTRICTED}a&&Qt(e,a)},r=async(n,a)=>{let o=e.mediaKeys.createSession(),l=()=>{o.keyStatuses.forEach(u=>s(u))},d=async u=>{let c=u.message;try{let h=await qM(c,Ql(i,"fairplay"));try{await o.update(h)}catch{let f=re("Failed to update DRM license. This may be an issue with the player or your protected content."),m=new X(f,X.MEDIA_ERR_ENCRYPTED,!0);m.errorCategory=Fe.DRM,m.muxCode=ae.ENCRYPTED_UPDATE_LICENSE_FAILED,Qt(e,m)}}catch(h){if(h instanceof Response){let f=au(h,Fe.DRM,i);if(console.error("mediaError",f?.message,f?.context),f){Qt(e,f);return}console.error("Unexpected error in license key request",h);return}console.error(h)}};o.addEventListener("keystatuseschange",l),o.addEventListener("message",d),e.addEventListener("teardown",()=>{o.removeEventListener("keystatuseschange",l),o.removeEventListener("message",d),o.close()},{once:!0}),await o.generateRequest(n,a).catch(u=>{console.error("Failed to generate license request",u);let c=re("Failed to generate a DRM license request. This may be an issue with the player or your protected content."),h=new X(c,X.MEDIA_ERR_ENCRYPTED,!0);return h.errorCategory=Fe.DRM,h.muxCode=ae.ENCRYPTED_GENERATE_REQUEST_FAILED,Promise.reject(h)})};nt(e,"encrypted",async n=>{try{let a=n.initDataType;if(a!=="skd"){console.error(`Received unexpected initialization data type "${a}"`);return}e.mediaKeys||await t(a);let o=n.initData;if(o==null){console.error(`Could not start encrypted playback due to missing initData in ${n.type} event`);return}await r(a,o)}catch(a){Qt(e,a);return}})},Ql=({playbackId:i,tokens:{drm:e}={},customDomain:t=Es},s)=>{let r=Xu(i);return`https://license.${t.toLocaleLowerCase().endsWith(Es)?t:Es}/license/${s}/${r}?token=${e}`},yT=({playbackId:i,tokens:{drm:e}={},customDomain:t=Es},s)=>{let r=Xu(i);return`https://license.${t.toLocaleLowerCase().endsWith(Es)?t:Es}/appcert/${s}/${r}?token=${e}`},bT=({playbackId:i,src:e,customDomain:t})=>{if(i)return!0;if(typeof e!="string")return!1;let s=window?.location.href,r=new URL(e,s).hostname.toLocaleLowerCase();return r.includes(Es)||!!t&&r.includes(t.toLocaleLowerCase())},jM=(i,e,t)=>{var s;let{envKey:r,disableTracking:n,muxDataSDK:a=km,muxDataSDKOptions:o={}}=i,l=bT(i);if(!n&&(r||l)){let{playerInitTime:d,playerSoftwareName:u,playerSoftwareVersion:c,beaconCollectionDomain:h,debug:f,disableCookies:m}=i,p={...i.metadata,video_title:((s=i?.metadata)==null?void 0:s.video_title)||void 0},g=v=>typeof v.player_error_code=="string"?!1:typeof i.errorTranslator=="function"?i.errorTranslator(v):v;a.monitor(e,{debug:f,beaconCollectionDomain:h,hlsjs:t,Hls:t?Ee:void 0,automaticErrorTracking:!1,errorTranslator:g,disableCookies:m,...o,data:{...r?{env_key:r}:{},player_software_name:u,player_software:u,player_software_version:c,player_init_time:d,...p}})}},zM=(i,e,t)=>{var s,r;let n=ET(i,e),{src:a,customDomain:o=Es}=i,l=()=>{e.ended||i.disablePseudoEnded||!gT(e,t)||(pT(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},d,u,c=()=>{let h=lp(e),f,m;h.length>0&&(f=h.start(0),m=h.end(0)),(u!==m||d!==f)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),d=f,u=m};if(nt(e,"durationchange",c),e&&n){let h=Qu(i);if(typeof a=="string"){if(a.endsWith(".mp4")&&a.includes(o)){let p=op(a),g=new URL(`https://stream.${o}/${p}/metadata.json`);np(g.toString(),e)}let f=()=>{if(lf(e)!==ke.LIVE||Number.isFinite(e.duration))return;let p=setInterval(c,1e3);e.addEventListener("teardown",()=>{clearInterval(p)},{once:!0}),nt(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(p)})},m=async()=>LM(a,e,h).then(f).catch(p=>{if(p instanceof Response){let g=au(p,Fe.VIDEO,i);if(g){Qt(e,g);return}}});if(e.preload==="none"){let p=()=>{m(),e.removeEventListener("loadedmetadata",g)},g=()=>{m(),e.removeEventListener("play",p)};nt(e,"play",p,{once:!0}),nt(e,"loadedmetadata",g,{once:!0})}else m();(s=i.tokens)!=null&&s.drm?YM(i,e):nt(e,"encrypted",()=>{let p=re("Attempting to play DRM-protected content without providing a DRM token."),g=new X(p,X.MEDIA_ERR_ENCRYPTED,!0);g.errorCategory=Fe.DRM,g.muxCode=ae.ENCRYPTED_MISSING_TOKEN,Qt(e,g)},{once:!0}),e.setAttribute("src",a),i.startTime&&(((r=Ze.get(e))!=null?r:{}).startTime=i.startTime,e.addEventListener("durationchange",TT,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",_T),e.addEventListener("error",df),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(f=>{f.remove()})},{once:!0}),nt(e,"pause",l),nt(e,"seeked",l),nt(e,"play",()=>{e.ended||mT(e.currentTime,e.duration)&&(e.currentTime=e.seekable.length?e.seekable.start(0):0)})}else t&&a?(t.once(Ee.Events.LEVEL_LOADED,(h,f)=>{kM(f.details,e,t),c(),lf(e)===ke.LIVE&&!Number.isFinite(e.duration)&&(t.on(Ee.Events.LEVEL_UPDATED,c),nt(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(Ee.Events.LEVELS_UPDATED,c)}))}),t.on(Ee.Events.ERROR,(h,f)=>{var m,p;let g=QM(f,i);if(g.muxCode===ae.NETWORK_NOT_READY){let v=(m=Ze.get(e))!=null?m:{},b=(p=v.retryCount)!=null?p:0;if(b<6){let E=b===0?5e3:6e4,T=new X(`Retrying in ${E/1e3} seconds...`,g.code,g.fatal);Object.assign(T,g),Qt(e,T),setTimeout(()=>{v.retryCount=b+1,f.details==="manifestLoadError"&&f.url&&t.loadSource(f.url)},E);return}else{v.retryCount=0;let E=new X('Try again later or <a href="#" onclick="window.location.reload(); return false;" style="color: #4a90e2;">click here to retry</a>',g.code,g.fatal);Object.assign(E,g),Qt(e,E);return}}Qt(e,g)}),t.on(Ee.Events.MANIFEST_LOADED,()=>{let h=Ze.get(e);h&&h.error&&(h.error=null,h.retryCount=0,e.dispatchEvent(new Event("emptied")),e.dispatchEvent(new Event("loadstart")))}),e.addEventListener("error",df),nt(e,"waiting",l),aM(i,t),oM(e,t),t.attachMedia(e)):console.error("It looks like the video you're trying to play will not work on this system! If possible, try upgrading to the newest versions of your browser or software.")};function TT(i){var e;let t=i.target,s=(e=Ze.get(t))==null?void 0:e.startTime;if(s&&jw(t.seekable,t.duration,s)){let r=t.preload==="auto";r&&(t.preload="none"),t.currentTime=s,r&&(t.preload="auto")}}async function _T(i){if(!i.isTrusted)return;i.stopImmediatePropagation();let e=i.target;if(!(e!=null&&e.error))return;let{message:t,code:s}=e.error,r=new X(t,s);if(e.src&&s===X.MEDIA_ERR_SRC_NOT_SUPPORTED&&e.readyState===HTMLMediaElement.HAVE_NOTHING){setTimeout(()=>{var n;let a=(n=fT(e))!=null?n:e.error;a?.code===X.MEDIA_ERR_SRC_NOT_SUPPORTED&&Qt(e,r)},500);return}if(e.src&&(s!==X.MEDIA_ERR_DECODE||s!==void 0))try{let{status:n}=await fetch(e.src);r.data={response:{code:n}}}catch{}Qt(e,r)}function Qt(i,e){var t;e.fatal&&(((t=Ze.get(i))!=null?t:{}).error=e,i.dispatchEvent(new CustomEvent("error",{detail:e})))}function df(i){var e,t;if(!(i instanceof CustomEvent)||!(i.detail instanceof X))return;let s=i.target,r=i.detail;!r||!r.fatal||(((e=Ze.get(s))!=null?e:{}).error=r,(t=s.mux)==null||t.emit("error",{player_error_code:r.code,player_error_message:r.message,player_error_context:r.context}))}var QM=(i,e)=>{var t,s,r;i.fatal?console.error("getErrorFromHlsErrorData()",i):e.debug&&console.warn("getErrorFromHlsErrorData() (non-fatal)",i);let n={[Ee.ErrorTypes.NETWORK_ERROR]:X.MEDIA_ERR_NETWORK,[Ee.ErrorTypes.MEDIA_ERROR]:X.MEDIA_ERR_DECODE,[Ee.ErrorTypes.KEY_SYSTEM_ERROR]:X.MEDIA_ERR_ENCRYPTED},a=u=>[Ee.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,Ee.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED].includes(u.details)?X.MEDIA_ERR_NETWORK:n[u.type],o=u=>{if(u.type===Ee.ErrorTypes.KEY_SYSTEM_ERROR)return Fe.DRM;if(u.type===Ee.ErrorTypes.NETWORK_ERROR)return Fe.VIDEO},l,d=a(i);if(d===X.MEDIA_ERR_NETWORK&&i.response){let u=(t=o(i))!=null?t:Fe.VIDEO;l=(s=au(i.response,u,e,i.fatal))!=null?s:new X("",d,i.fatal)}else if(d===X.MEDIA_ERR_ENCRYPTED)if(i.details===Ee.ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE){let u=re("Attempting to play DRM-protected content without providing a DRM token.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Fe.DRM,l.muxCode=ae.ENCRYPTED_MISSING_TOKEN}else if(i.details===Ee.ErrorDetails.KEY_SYSTEM_NO_ACCESS){let u=re("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Fe.DRM,l.muxCode=ae.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM}else if(i.details===Ee.ErrorDetails.KEY_SYSTEM_NO_SESSION){let u=re("Failed to generate a DRM license request. This may be an issue with the player or your protected content.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,!0),l.errorCategory=Fe.DRM,l.muxCode=ae.ENCRYPTED_GENERATE_REQUEST_FAILED}else if(i.details===Ee.ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED){let u=re("Failed to update DRM license. This may be an issue with the player or your protected content.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Fe.DRM,l.muxCode=ae.ENCRYPTED_UPDATE_LICENSE_FAILED}else if(i.details===Ee.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED){let u=re("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Fe.DRM,l.muxCode=ae.ENCRYPTED_UPDATE_SERVER_CERT_FAILED}else if(i.details===Ee.ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR){let u=re("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Fe.DRM,l.muxCode=ae.ENCRYPTED_CDM_ERROR}else if(i.details===Ee.ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED){let u=re("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");l=new X(u,X.MEDIA_ERR_ENCRYPTED,!1),l.errorCategory=Fe.DRM,l.muxCode=ae.ENCRYPTED_OUTPUT_RESTRICTED}else l=new X(i.error.message,X.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Fe.DRM,l.muxCode=ae.ENCRYPTED_ERROR;else l=new X("",d,i.fatal);return l.context||(l.context=`${i.url?`url: ${i.url}
|
|
1459
|
+
`),n=(t=((e=r.find(d=>d.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),a=tT(n),o=iT(n),l;if(a===ke.LIVE){let d=r.find(u=>u.startsWith("#EXT-X-PART-INF"));if(d)l=+d.split(":")[1].split("=")[1]*2;else{let u=r.find(h=>h.startsWith("#EXT-X-TARGETDURATION")),c=(s=u?.split(":"))==null?void 0:s[1];l=+(c??6)*3}}return{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}},xM=async(i,e)=>{if(e===vs.MP4)return{streamType:ke.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0,sessionData:void 0};if(e===vs.M3U8){let t=await fetch(i);if(!t.ok)return Promise.reject(t);let s=await t.text(),r=await TM(s);return{..._M(s),...IM(r)}}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${i}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0,sessionData:void 0}},LM=async(i,e,t=Qu({src:i}))=>{var s,r,n,a;let{streamType:o,targetLiveWindow:l,liveEdgeStartOffset:d,sessionData:u}=await xM(i,t),c=u?.["com.apple.hls.chapters"];(c!=null&&c.URI||c!=null&&c.VALUE.toLocaleLowerCase().startsWith("http"))&&np((s=c.URI)!=null?s:c.VALUE,e),((r=Ze.get(e))!=null?r:{}).liveEdgeStartOffset=d,((n=Ze.get(e))!=null?n:{}).targetLiveWindow=l,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((a=Ze.get(e))!=null?a:{}).streamType=o,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},np=async(i,e)=>{var t,s;try{let r=await fetch(i);if(!r.ok)throw new Error(`Failed to fetch Mux metadata: ${r.status} ${r.statusText}`);let n=await r.json(),a={};if(!((t=n?.[0])!=null&&t.metadata))return;for(let l of n[0].metadata)l.key&&l.value&&(a[l.key]=l.value);((s=Ze.get(e))!=null?s:{}).metadata=a;let o=new CustomEvent("muxmetadata");e.dispatchEvent(o)}catch(r){console.error(r)}},RM=i=>{var e;let t=i.type,s=tT(t),r=iT(t),n,a=!!((e=i.partList)!=null&&e.length);return s===ke.LIVE&&(n=a?i.partTarget*2:i.targetduration*3),{streamType:s,targetLiveWindow:r,liveEdgeStartOffset:n,lowLatency:a}},kM=(i,e,t)=>{var s,r,n,a,o,l,d,u;let{streamType:c,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:m}=RM(i);if(c===ke.LIVE){m?(t.config.backBufferLength=(s=t.userConfig.backBufferLength)!=null?s:4,t.config.maxFragLookUpTolerance=(r=t.userConfig.maxFragLookUpTolerance)!=null?r:.001,t.config.abrBandWidthUpFactor=(n=t.userConfig.abrBandWidthUpFactor)!=null?n:t.config.abrBandWidthFactor):t.config.backBufferLength=(a=t.userConfig.backBufferLength)!=null?a:8;let p=Object.freeze({get length(){return e.seekable.length},start(g){return e.seekable.start(g)},end(g){var v;return g>this.length||g<0||Number.isFinite(e.duration)?e.seekable.end(g):(v=t.liveSyncPosition)!=null?v:e.seekable.end(g)}});((o=Ze.get(e))!=null?o:{}).seekable=p}((l=Ze.get(e))!=null?l:{}).liveEdgeStartOffset=f,((d=Ze.get(e))!=null?d:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((u=Ze.get(e))!=null?u:{}).streamType=c,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},W0,q0,cT=(q0=(W0=globalThis?.navigator)==null?void 0:W0.userAgent)!=null?q0:"",Y0,j0,z0,DM=(z0=(j0=(Y0=globalThis?.navigator)==null?void 0:Y0.userAgentData)==null?void 0:j0.platform)!=null?z0:"",CM=cT.toLowerCase().includes("android")||["x11","android"].some(i=>DM.toLowerCase().includes(i)),wM=i=>/^((?!chrome|android).)*safari/i.test(cT)&&!!i.canPlayType("application/vnd.apple.mpegurl"),Ze=new WeakMap,Es="mux.com",Q0,X0,hT=(X0=(Q0=Ee).isSupported)==null?void 0:X0.call(Q0),MM=i=>CM||!wM(i),ap=()=>{if(typeof window<"u")return km.utils.now()},PM=km.utils.generateUUID,of=({playbackId:i,customDomain:e=Es,maxResolution:t,minResolution:s,renditionOrder:r,programStartTime:n,programEndTime:a,assetStartTime:o,assetEndTime:l,playbackToken:d,tokens:{playback:u=d}={},extraSourceParams:c={}}={})=>{if(!i)return;let[h,f=""]=tp(i),m=new URL(`https://stream.${e}/${h}.m3u8${f}`);return u||m.searchParams.has("token")?(m.searchParams.forEach((p,g)=>{g!="token"&&m.searchParams.delete(g)}),u&&m.searchParams.set("token",u)):(t&&m.searchParams.set("max_resolution",t),s&&(m.searchParams.set("min_resolution",s),t&&+t.slice(0,-1)<+s.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",s,"maxResolution",t)),r&&m.searchParams.set("rendition_order",r),n&&m.searchParams.set("program_start_time",`${n}`),a&&m.searchParams.set("program_end_time",`${a}`),o&&m.searchParams.set("asset_start_time",`${o}`),l&&m.searchParams.set("asset_end_time",`${l}`),Object.entries(c).forEach(([p,g])=>{g!=null&&m.searchParams.set(p,g)})),m.toString()},Xu=i=>{if(!i)return;let[e]=i.split("?");return e||void 0},op=i=>{if(!i||!i.startsWith("https://stream."))return;let[e]=new URL(i).pathname.slice(1).split(/\.m3u8|\//);return e||void 0},OM=i=>{var e,t,s;return(e=i?.metadata)!=null&&e.video_id?i.metadata.video_id:bT(i)&&(s=(t=Xu(i.playbackId))!=null?t:op(i.src))!=null?s:i.src},fT=i=>{var e;return(e=Ze.get(i))==null?void 0:e.error},NM=i=>{var e;return(e=Ze.get(i))==null?void 0:e.metadata},lf=i=>{var e,t;return(t=(e=Ze.get(i))==null?void 0:e.streamType)!=null?t:ke.UNKNOWN},UM=i=>{var e,t;return(t=(e=Ze.get(i))==null?void 0:e.targetLiveWindow)!=null?t:Number.NaN},lp=i=>{var e,t;return(t=(e=Ze.get(i))==null?void 0:e.seekable)!=null?t:i.seekable},$M=i=>{var e;let t=(e=Ze.get(i))==null?void 0:e.liveEdgeStartOffset;if(typeof t!="number")return Number.NaN;let s=lp(i);return s.length?s.end(s.length-1)-t:Number.NaN},dp=.034,FM=(i,e,t=dp)=>Math.abs(i-e)<=t,mT=(i,e,t=dp)=>i>e||FM(i,e,t),BM=(i,e=dp)=>i.paused&&mT(i.currentTime,i.duration,e),pT=(i,e)=>{var t,s,r;if(!e||!i.buffered.length)return;if(i.readyState>2)return!1;let n=e.currentLevel>=0?(s=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:s.details:(r=e.levels.find(c=>!!c.details))==null?void 0:r.details;if(!n||n.live)return;let{fragments:a}=n;if(!(a!=null&&a.length))return;if(i.currentTime<i.duration-(n.targetduration+.5))return!1;let o=a[a.length-1];if(i.currentTime<=o.start)return!1;let l=o.start+o.duration/2,d=i.buffered.start(i.buffered.length-1),u=i.buffered.end(i.buffered.length-1);return l>d&&l<u},gT=(i,e)=>i.ended||i.loop?i.ended:e&&pT(i,e)?!0:BM(i),HM=(i,e,t)=>{vT(e,t,i);let{metadata:s={}}=i,{view_session_id:r=PM()}=s,n=OM(i);s.view_session_id=r,s.video_id=n,i.metadata=s;let a=u=>{var c;(c=e.mux)==null||c.emit("hb",{view_drm_type:u})};i.drmTypeCb=a,Ze.set(e,{retryCount:0});let o=GM(i,e),l=nM(i,e,o);i!=null&&i.muxDataKeepSession&&e!=null&&e.mux&&!e.mux.deleted?o&&e.mux.addHLSJS({hlsjs:o,Hls:o?Ee:void 0}):jM(i,e,o),zM(i,e,o),uM(e),hM(e);let d=rM(i,e,o);return{engine:o,setAutoplay:d,setPreload:l}},vT=(i,e,t)=>{let s=e?.engine;i!=null&&i.mux&&!i.mux.deleted&&(t!=null&&t.muxDataKeepSession?s&&i.mux.removeHLSJS():(i.mux.destroy(),delete i.mux)),s&&(s.detachMedia(),s.destroy()),i&&(i.hasAttribute("src")&&(i.removeAttribute("src"),i.load()),i.removeEventListener("error",_T),i.removeEventListener("error",df),i.removeEventListener("durationchange",TT),Ze.delete(i),i.dispatchEvent(new Event("teardown")))};function ET(i,e){var t;let s=Qu(i);if(s!==vs.M3U8)return!0;let r=!s||((t=e.canPlayType(s))!=null?t:!0),{preferPlayback:n}=i,a=n===Zi.MSE,o=n===Zi.NATIVE,l=hT&&(a||MM(e));return r&&(o||!l)}var GM=(i,e)=>{let{debug:t,streamType:s,startTime:r=-1,metadata:n,preferCmcd:a,_hlsConfig:o={},maxAutoResolution:l}=i,d=Qu(i)===vs.M3U8,u=ET(i,e);if(d&&!u&&hT){let c={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelToPlayerSize:!0,capLevelOnFPSDrop:!0},h=KM(s),f=VM(i),m=[Ca.QUERY,Ca.HEADER].includes(a)?{useHeaders:a===Ca.HEADER,sessionId:n?.view_session_id,contentId:n?.video_id}:void 0,p=o.capLevelToPlayerSize==null?{capLevelController:Vc}:{},g=new Ee({debug:t,startPosition:r,cmcd:m,xhrSetup:(v,b)=>{var E,T;if(a&&a!==Ca.QUERY)return;let A=new URL(b);if(!A.searchParams.has("CMCD"))return;let x=((T=(E=A.searchParams.get("CMCD"))==null?void 0:E.split(","))!=null?T:[]).filter(S=>S.startsWith("sid")||S.startsWith("cid")).join(",");A.searchParams.set("CMCD",x),v.open("GET",A)},...p,...c,...h,...f,...o});return p.capLevelController===Vc&&l!==void 0&&Vc.setMaxAutoResolution(g,l),g.on(Ee.Events.MANIFEST_PARSED,async function(v,b){var E,T;let A=(E=b.sessionData)==null?void 0:E["com.apple.hls.chapters"];(A!=null&&A.URI||A!=null&&A.VALUE.toLocaleLowerCase().startsWith("http"))&&np((T=A?.URI)!=null?T:A?.VALUE,e)}),g}},KM=i=>i===ke.LIVE?{backBufferLength:8}:{},VM=i=>{let{tokens:{drm:e}={},playbackId:t,drmTypeCb:s}=i,r=Xu(t);return!e||!r?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:Ql(i,"fairplay"),serverCertificateUrl:yT(i,"fairplay")},"com.widevine.alpha":{licenseUrl:Ql(i,"widevine")},"com.microsoft.playready":{licenseUrl:Ql(i,"playready")}},requestMediaKeySystemAccessFunc:(n,a)=>(n==="com.widevine.alpha"&&(a=[...a.map(o=>{var l;let d=(l=o.videoCapabilities)==null?void 0:l.map(u=>({...u,robustness:"HW_SECURE_ALL"}));return{...o,videoCapabilities:d}}),...a]),navigator.requestMediaKeySystemAccess(n,a).then(o=>{let l=bM(n);return s?.(l),o}))}},WM=async i=>{let e=await fetch(i);return e.status!==200?Promise.reject(e):await e.arrayBuffer()},qM=async(i,e)=>{let t=await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:i});if(t.status!==200)return Promise.reject(t);let s=await t.arrayBuffer();return new Uint8Array(s)},YM=(i,e)=>{let t=async n=>{let a=await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[n],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}]).then(l=>{var d;return(d=i.drmTypeCb)==null||d.call(i,zl.FAIRPLAY),l}).catch(()=>{let l=se("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),d=new Z(l,Z.MEDIA_ERR_ENCRYPTED,!0);d.errorCategory=Fe.DRM,d.muxCode=ae.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,Qt(e,d)});if(!a)return;let o=await a.createMediaKeys();try{let l=await WM(yT(i,"fairplay")).catch(d=>{if(d instanceof Response){let u=au(d,Fe.DRM,i);return console.error("mediaError",u?.message,u?.context),u?Promise.reject(u):Promise.reject(new Error("Unexpected error in app cert request"))}return Promise.reject(d)});await o.setServerCertificate(l).catch(()=>{let d=se("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."),u=new Z(d,Z.MEDIA_ERR_ENCRYPTED,!0);return u.errorCategory=Fe.DRM,u.muxCode=ae.ENCRYPTED_UPDATE_SERVER_CERT_FAILED,Promise.reject(u)})}catch(l){Qt(e,l);return}await e.setMediaKeys(o)},s=n=>{let a;if(n==="internal-error"){let o=se("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser.");a=new Z(o,Z.MEDIA_ERR_ENCRYPTED,!0),a.errorCategory=Fe.DRM,a.muxCode=ae.ENCRYPTED_CDM_ERROR}else if(n==="output-restricted"||n==="output-downscaled"){let o=se("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");a=new Z(o,Z.MEDIA_ERR_ENCRYPTED,!1),a.errorCategory=Fe.DRM,a.muxCode=ae.ENCRYPTED_OUTPUT_RESTRICTED}a&&Qt(e,a)},r=async(n,a)=>{let o=e.mediaKeys.createSession(),l=()=>{o.keyStatuses.forEach(u=>s(u))},d=async u=>{let c=u.message;try{let h=await qM(c,Ql(i,"fairplay"));try{await o.update(h)}catch{let f=se("Failed to update DRM license. This may be an issue with the player or your protected content."),m=new Z(f,Z.MEDIA_ERR_ENCRYPTED,!0);m.errorCategory=Fe.DRM,m.muxCode=ae.ENCRYPTED_UPDATE_LICENSE_FAILED,Qt(e,m)}}catch(h){if(h instanceof Response){let f=au(h,Fe.DRM,i);if(console.error("mediaError",f?.message,f?.context),f){Qt(e,f);return}console.error("Unexpected error in license key request",h);return}console.error(h)}};o.addEventListener("keystatuseschange",l),o.addEventListener("message",d),e.addEventListener("teardown",()=>{o.removeEventListener("keystatuseschange",l),o.removeEventListener("message",d),o.close()},{once:!0}),await o.generateRequest(n,a).catch(u=>{console.error("Failed to generate license request",u);let c=se("Failed to generate a DRM license request. This may be an issue with the player or your protected content."),h=new Z(c,Z.MEDIA_ERR_ENCRYPTED,!0);return h.errorCategory=Fe.DRM,h.muxCode=ae.ENCRYPTED_GENERATE_REQUEST_FAILED,Promise.reject(h)})};nt(e,"encrypted",async n=>{try{let a=n.initDataType;if(a!=="skd"){console.error(`Received unexpected initialization data type "${a}"`);return}e.mediaKeys||await t(a);let o=n.initData;if(o==null){console.error(`Could not start encrypted playback due to missing initData in ${n.type} event`);return}await r(a,o)}catch(a){Qt(e,a);return}})},Ql=({playbackId:i,tokens:{drm:e}={},customDomain:t=Es},s)=>{let r=Xu(i);return`https://license.${t.toLocaleLowerCase().endsWith(Es)?t:Es}/license/${s}/${r}?token=${e}`},yT=({playbackId:i,tokens:{drm:e}={},customDomain:t=Es},s)=>{let r=Xu(i);return`https://license.${t.toLocaleLowerCase().endsWith(Es)?t:Es}/appcert/${s}/${r}?token=${e}`},bT=({playbackId:i,src:e,customDomain:t})=>{if(i)return!0;if(typeof e!="string")return!1;let s=window?.location.href,r=new URL(e,s).hostname.toLocaleLowerCase();return r.includes(Es)||!!t&&r.includes(t.toLocaleLowerCase())},jM=(i,e,t)=>{var s;let{envKey:r,disableTracking:n,muxDataSDK:a=km,muxDataSDKOptions:o={}}=i,l=bT(i);if(!n&&(r||l)){let{playerInitTime:d,playerSoftwareName:u,playerSoftwareVersion:c,beaconCollectionDomain:h,debug:f,disableCookies:m}=i,p={...i.metadata,video_title:((s=i?.metadata)==null?void 0:s.video_title)||void 0},g=v=>typeof v.player_error_code=="string"?!1:typeof i.errorTranslator=="function"?i.errorTranslator(v):v;a.monitor(e,{debug:f,beaconCollectionDomain:h,hlsjs:t,Hls:t?Ee:void 0,automaticErrorTracking:!1,errorTranslator:g,disableCookies:m,...o,data:{...r?{env_key:r}:{},player_software_name:u,player_software:u,player_software_version:c,player_init_time:d,...p}})}},zM=(i,e,t)=>{var s,r;let n=ET(i,e),{src:a,customDomain:o=Es}=i,l=()=>{e.ended||i.disablePseudoEnded||!gT(e,t)||(pT(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},d,u,c=()=>{let h=lp(e),f,m;h.length>0&&(f=h.start(0),m=h.end(0)),(u!==m||d!==f)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),d=f,u=m};if(nt(e,"durationchange",c),e&&n){let h=Qu(i);if(typeof a=="string"){if(a.endsWith(".mp4")&&a.includes(o)){let p=op(a),g=new URL(`https://stream.${o}/${p}/metadata.json`);np(g.toString(),e)}let f=()=>{if(lf(e)!==ke.LIVE||Number.isFinite(e.duration))return;let p=setInterval(c,1e3);e.addEventListener("teardown",()=>{clearInterval(p)},{once:!0}),nt(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(p)})},m=async()=>LM(a,e,h).then(f).catch(p=>{if(p instanceof Response){let g=au(p,Fe.VIDEO,i);if(g){Qt(e,g);return}}});if(e.preload==="none"){let p=()=>{m(),e.removeEventListener("loadedmetadata",g)},g=()=>{m(),e.removeEventListener("play",p)};nt(e,"play",p,{once:!0}),nt(e,"loadedmetadata",g,{once:!0})}else m();(s=i.tokens)!=null&&s.drm?YM(i,e):nt(e,"encrypted",()=>{let p=se("Attempting to play DRM-protected content without providing a DRM token."),g=new Z(p,Z.MEDIA_ERR_ENCRYPTED,!0);g.errorCategory=Fe.DRM,g.muxCode=ae.ENCRYPTED_MISSING_TOKEN,Qt(e,g)},{once:!0}),e.setAttribute("src",a),i.startTime&&(((r=Ze.get(e))!=null?r:{}).startTime=i.startTime,e.addEventListener("durationchange",TT,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",_T),e.addEventListener("error",df),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(f=>{f.remove()})},{once:!0}),nt(e,"pause",l),nt(e,"seeked",l),nt(e,"play",()=>{e.ended||mT(e.currentTime,e.duration)&&(e.currentTime=e.seekable.length?e.seekable.start(0):0)})}else t&&a?(t.once(Ee.Events.LEVEL_LOADED,(h,f)=>{kM(f.details,e,t),c(),lf(e)===ke.LIVE&&!Number.isFinite(e.duration)&&(t.on(Ee.Events.LEVEL_UPDATED,c),nt(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(Ee.Events.LEVELS_UPDATED,c)}))}),t.on(Ee.Events.ERROR,(h,f)=>{var m,p;let g=QM(f,i);if(g.muxCode===ae.NETWORK_NOT_READY){let v=(m=Ze.get(e))!=null?m:{},b=(p=v.retryCount)!=null?p:0;if(b<6){let E=b===0?5e3:6e4,T=new Z(`Retrying in ${E/1e3} seconds...`,g.code,g.fatal);Object.assign(T,g),Qt(e,T),setTimeout(()=>{v.retryCount=b+1,f.details==="manifestLoadError"&&f.url&&t.loadSource(f.url)},E);return}else{v.retryCount=0;let E=new Z('Try again later or <a href="#" onclick="window.location.reload(); return false;" style="color: #4a90e2;">click here to retry</a>',g.code,g.fatal);Object.assign(E,g),Qt(e,E);return}}Qt(e,g)}),t.on(Ee.Events.MANIFEST_LOADED,()=>{let h=Ze.get(e);h&&h.error&&(h.error=null,h.retryCount=0,e.dispatchEvent(new Event("emptied")),e.dispatchEvent(new Event("loadstart")))}),e.addEventListener("error",df),nt(e,"waiting",l),aM(i,t),oM(e,t),t.attachMedia(e)):console.error("It looks like the video you're trying to play will not work on this system! If possible, try upgrading to the newest versions of your browser or software.")};function TT(i){var e;let t=i.target,s=(e=Ze.get(t))==null?void 0:e.startTime;if(s&&jw(t.seekable,t.duration,s)){let r=t.preload==="auto";r&&(t.preload="none"),t.currentTime=s,r&&(t.preload="auto")}}async function _T(i){if(!i.isTrusted)return;i.stopImmediatePropagation();let e=i.target;if(!(e!=null&&e.error))return;let{message:t,code:s}=e.error,r=new Z(t,s);if(e.src&&s===Z.MEDIA_ERR_SRC_NOT_SUPPORTED&&e.readyState===HTMLMediaElement.HAVE_NOTHING){setTimeout(()=>{var n;let a=(n=fT(e))!=null?n:e.error;a?.code===Z.MEDIA_ERR_SRC_NOT_SUPPORTED&&Qt(e,r)},500);return}if(e.src&&(s!==Z.MEDIA_ERR_DECODE||s!==void 0))try{let{status:n}=await fetch(e.src);r.data={response:{code:n}}}catch{}Qt(e,r)}function Qt(i,e){var t;e.fatal&&(((t=Ze.get(i))!=null?t:{}).error=e,i.dispatchEvent(new CustomEvent("error",{detail:e})))}function df(i){var e,t;if(!(i instanceof CustomEvent)||!(i.detail instanceof Z))return;let s=i.target,r=i.detail;!r||!r.fatal||(((e=Ze.get(s))!=null?e:{}).error=r,(t=s.mux)==null||t.emit("error",{player_error_code:r.code,player_error_message:r.message,player_error_context:r.context}))}var QM=(i,e)=>{var t,s,r;i.fatal?console.error("getErrorFromHlsErrorData()",i):e.debug&&console.warn("getErrorFromHlsErrorData() (non-fatal)",i);let n={[Ee.ErrorTypes.NETWORK_ERROR]:Z.MEDIA_ERR_NETWORK,[Ee.ErrorTypes.MEDIA_ERROR]:Z.MEDIA_ERR_DECODE,[Ee.ErrorTypes.KEY_SYSTEM_ERROR]:Z.MEDIA_ERR_ENCRYPTED},a=u=>[Ee.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,Ee.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED].includes(u.details)?Z.MEDIA_ERR_NETWORK:n[u.type],o=u=>{if(u.type===Ee.ErrorTypes.KEY_SYSTEM_ERROR)return Fe.DRM;if(u.type===Ee.ErrorTypes.NETWORK_ERROR)return Fe.VIDEO},l,d=a(i);if(d===Z.MEDIA_ERR_NETWORK&&i.response){let u=(t=o(i))!=null?t:Fe.VIDEO;l=(s=au(i.response,u,e,i.fatal))!=null?s:new Z("",d,i.fatal)}else if(d===Z.MEDIA_ERR_ENCRYPTED)if(i.details===Ee.ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE){let u=se("Attempting to play DRM-protected content without providing a DRM token.");l=new Z(u,Z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Fe.DRM,l.muxCode=ae.ENCRYPTED_MISSING_TOKEN}else if(i.details===Ee.ErrorDetails.KEY_SYSTEM_NO_ACCESS){let u=se("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.");l=new Z(u,Z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Fe.DRM,l.muxCode=ae.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM}else if(i.details===Ee.ErrorDetails.KEY_SYSTEM_NO_SESSION){let u=se("Failed to generate a DRM license request. This may be an issue with the player or your protected content.");l=new Z(u,Z.MEDIA_ERR_ENCRYPTED,!0),l.errorCategory=Fe.DRM,l.muxCode=ae.ENCRYPTED_GENERATE_REQUEST_FAILED}else if(i.details===Ee.ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED){let u=se("Failed to update DRM license. This may be an issue with the player or your protected content.");l=new Z(u,Z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Fe.DRM,l.muxCode=ae.ENCRYPTED_UPDATE_LICENSE_FAILED}else if(i.details===Ee.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED){let u=se("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate.");l=new Z(u,Z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Fe.DRM,l.muxCode=ae.ENCRYPTED_UPDATE_SERVER_CERT_FAILED}else if(i.details===Ee.ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR){let u=se("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser.");l=new Z(u,Z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Fe.DRM,l.muxCode=ae.ENCRYPTED_CDM_ERROR}else if(i.details===Ee.ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED){let u=se("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");l=new Z(u,Z.MEDIA_ERR_ENCRYPTED,!1),l.errorCategory=Fe.DRM,l.muxCode=ae.ENCRYPTED_OUTPUT_RESTRICTED}else l=new Z(i.error.message,Z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Fe.DRM,l.muxCode=ae.ENCRYPTED_ERROR;else l=new Z("",d,i.fatal);return l.context||(l.context=`${i.url?`url: ${i.url}
|
|
1460
1460
|
`:""}${i.response&&(i.response.code||i.response.text)?`response: ${i.response.code}, ${i.response.text}
|
|
1461
1461
|
`:""}${i.reason?`failure reason: ${i.reason}
|
|
1462
1462
|
`:""}${i.level?`level: ${i.level}
|
|
@@ -1538,7 +1538,7 @@ Schedule: ${l.map(p=>fi(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
|
|
|
1538
1538
|
</slot>
|
|
1539
1539
|
`}get preferCmcd(){var e;return(e=this.getAttribute(C.PREFER_CMCD))!=null?e:void 0}set preferCmcd(e){e!==this.preferCmcd&&(e?nu.includes(e)?this.setAttribute(C.PREFER_CMCD,e):console.warn(`Invalid value for preferCmcd. Must be one of ${nu.join()}`):this.removeAttribute(C.PREFER_CMCD))}get playerInitTime(){return this.hasAttribute(C.PLAYER_INIT_TIME)?+this.getAttribute(C.PLAYER_INIT_TIME):At(this,Xl)}set playerInitTime(e){e!=this.playerInitTime&&(e==null?this.removeAttribute(C.PLAYER_INIT_TIME):this.setAttribute(C.PLAYER_INIT_TIME,`${+e}`))}get playerSoftwareName(){var e;return(e=At(this,td))!=null?e:J0}set playerSoftwareName(e){ri(this,td,e)}get playerSoftwareVersion(){var e;return(e=At(this,ed))!=null?e:Z0}set playerSoftwareVersion(e){ri(this,ed,e)}get _hls(){var e;return(e=At(this,Hi))==null?void 0:e.engine}get mux(){var e;return(e=this.nativeEl)==null?void 0:e.mux}get error(){var e;return(e=fT(this.nativeEl))!=null?e:null}get errorTranslator(){return At(this,id)}set errorTranslator(e){ri(this,id,e)}get src(){return this.getAttribute("src")}set src(e){e!==this.src&&(e==null?this.removeAttribute("src"):this.setAttribute("src",e))}get type(){var e;return(e=this.getAttribute(C.TYPE))!=null?e:void 0}set type(e){e!==this.type&&(e?this.setAttribute(C.TYPE,e):this.removeAttribute(C.TYPE))}get preload(){let e=this.getAttribute("preload");return e===""?"auto":["none","metadata","auto"].includes(e)?e:super.preload}set preload(e){e!=this.getAttribute("preload")&&(["","none","metadata","auto"].includes(e)?this.setAttribute("preload",e):this.removeAttribute("preload"))}get debug(){return this.getAttribute(C.DEBUG)!=null}set debug(e){e!==this.debug&&(e?this.setAttribute(C.DEBUG,""):this.removeAttribute(C.DEBUG))}get disableTracking(){return this.hasAttribute(C.DISABLE_TRACKING)}set disableTracking(e){e!==this.disableTracking&&this.toggleAttribute(C.DISABLE_TRACKING,!!e)}get disableCookies(){return this.hasAttribute(C.DISABLE_COOKIES)}set disableCookies(e){e!==this.disableCookies&&(e?this.setAttribute(C.DISABLE_COOKIES,""):this.removeAttribute(C.DISABLE_COOKIES))}get disablePseudoEnded(){return this.hasAttribute(C.DISABLE_PSEUDO_ENDED)}set disablePseudoEnded(e){e!==this.disablePseudoEnded&&(e?this.setAttribute(C.DISABLE_PSEUDO_ENDED,""):this.removeAttribute(C.DISABLE_PSEUDO_ENDED))}get startTime(){let e=this.getAttribute(C.START_TIME);if(e==null)return;let t=+e;return Number.isNaN(t)?void 0:t}set startTime(e){e!==this.startTime&&(e==null?this.removeAttribute(C.START_TIME):this.setAttribute(C.START_TIME,`${e}`))}get playbackId(){var e;return this.hasAttribute(C.PLAYBACK_ID)?this.getAttribute(C.PLAYBACK_ID):(e=op(this.src))!=null?e:void 0}set playbackId(e){e!==this.playbackId&&(e?this.setAttribute(C.PLAYBACK_ID,e):this.removeAttribute(C.PLAYBACK_ID))}get maxResolution(){var e;return(e=this.getAttribute(C.MAX_RESOLUTION))!=null?e:void 0}set maxResolution(e){e!==this.maxResolution&&(e?this.setAttribute(C.MAX_RESOLUTION,e):this.removeAttribute(C.MAX_RESOLUTION))}get minResolution(){var e;return(e=this.getAttribute(C.MIN_RESOLUTION))!=null?e:void 0}set minResolution(e){e!==this.minResolution&&(e?this.setAttribute(C.MIN_RESOLUTION,e):this.removeAttribute(C.MIN_RESOLUTION))}get maxAutoResolution(){var e;return(e=this.getAttribute(C.MAX_AUTO_RESOLUTION))!=null?e:void 0}set maxAutoResolution(e){e==null?this.removeAttribute(C.MAX_AUTO_RESOLUTION):this.setAttribute(C.MAX_AUTO_RESOLUTION,e)}get renditionOrder(){var e;return(e=this.getAttribute(C.RENDITION_ORDER))!=null?e:void 0}set renditionOrder(e){e!==this.renditionOrder&&(e?this.setAttribute(C.RENDITION_ORDER,e):this.removeAttribute(C.RENDITION_ORDER))}get programStartTime(){let e=this.getAttribute(C.PROGRAM_START_TIME);if(e==null)return;let t=+e;return Number.isNaN(t)?void 0:t}set programStartTime(e){e==null?this.removeAttribute(C.PROGRAM_START_TIME):this.setAttribute(C.PROGRAM_START_TIME,`${e}`)}get programEndTime(){let e=this.getAttribute(C.PROGRAM_END_TIME);if(e==null)return;let t=+e;return Number.isNaN(t)?void 0:t}set programEndTime(e){e==null?this.removeAttribute(C.PROGRAM_END_TIME):this.setAttribute(C.PROGRAM_END_TIME,`${e}`)}get assetStartTime(){let e=this.getAttribute(C.ASSET_START_TIME);if(e==null)return;let t=+e;return Number.isNaN(t)?void 0:t}set assetStartTime(e){e==null?this.removeAttribute(C.ASSET_START_TIME):this.setAttribute(C.ASSET_START_TIME,`${e}`)}get assetEndTime(){let e=this.getAttribute(C.ASSET_END_TIME);if(e==null)return;let t=+e;return Number.isNaN(t)?void 0:t}set assetEndTime(e){e==null?this.removeAttribute(C.ASSET_END_TIME):this.setAttribute(C.ASSET_END_TIME,`${e}`)}get customDomain(){var e;return(e=this.getAttribute(C.CUSTOM_DOMAIN))!=null?e:void 0}set customDomain(e){e!==this.customDomain&&(e?this.setAttribute(C.CUSTOM_DOMAIN,e):this.removeAttribute(C.CUSTOM_DOMAIN))}get drmToken(){var e;return(e=this.getAttribute(C.DRM_TOKEN))!=null?e:void 0}set drmToken(e){e!==this.drmToken&&(e?this.setAttribute(C.DRM_TOKEN,e):this.removeAttribute(C.DRM_TOKEN))}get playbackToken(){var e,t,s,r;if(this.hasAttribute(C.PLAYBACK_TOKEN))return(e=this.getAttribute(C.PLAYBACK_TOKEN))!=null?e:void 0;if(this.hasAttribute(C.PLAYBACK_ID)){let[,n]=tp((t=this.playbackId)!=null?t:"");return(s=new URLSearchParams(n).get("token"))!=null?s:void 0}if(this.src)return(r=new URLSearchParams(this.src).get("token"))!=null?r:void 0}set playbackToken(e){e!==this.playbackToken&&(e?this.setAttribute(C.PLAYBACK_TOKEN,e):this.removeAttribute(C.PLAYBACK_TOKEN))}get tokens(){let e=this.getAttribute(C.PLAYBACK_TOKEN),t=this.getAttribute(C.DRM_TOKEN);return{...At(this,Zl),...e!=null?{playback:e}:{},...t!=null?{drm:t}:{}}}set tokens(e){ri(this,Zl,e??{})}get ended(){return gT(this.nativeEl,this._hls)}get envKey(){var e;return(e=this.getAttribute(C.ENV_KEY))!=null?e:void 0}set envKey(e){e!==this.envKey&&(e?this.setAttribute(C.ENV_KEY,e):this.removeAttribute(C.ENV_KEY))}get beaconCollectionDomain(){var e;return(e=this.getAttribute(C.BEACON_COLLECTION_DOMAIN))!=null?e:void 0}set beaconCollectionDomain(e){e!==this.beaconCollectionDomain&&(e?this.setAttribute(C.BEACON_COLLECTION_DOMAIN,e):this.removeAttribute(C.BEACON_COLLECTION_DOMAIN))}get streamType(){var e;return(e=this.getAttribute(C.STREAM_TYPE))!=null?e:lf(this.nativeEl)}set streamType(e){e!==this.streamType&&(e?this.setAttribute(C.STREAM_TYPE,e):this.removeAttribute(C.STREAM_TYPE))}get targetLiveWindow(){return this.hasAttribute(C.TARGET_LIVE_WINDOW)?+this.getAttribute(C.TARGET_LIVE_WINDOW):UM(this.nativeEl)}set targetLiveWindow(e){e!=this.targetLiveWindow&&(e==null?this.removeAttribute(C.TARGET_LIVE_WINDOW):this.setAttribute(C.TARGET_LIVE_WINDOW,`${+e}`))}get liveEdgeStart(){var e,t;if(this.hasAttribute(C.LIVE_EDGE_OFFSET)){let{liveEdgeOffset:s}=this,r=(e=this.nativeEl.seekable.end(0))!=null?e:0,n=(t=this.nativeEl.seekable.start(0))!=null?t:0;return Math.max(n,r-s)}return $M(this.nativeEl)}get liveEdgeOffset(){if(this.hasAttribute(C.LIVE_EDGE_OFFSET))return+this.getAttribute(C.LIVE_EDGE_OFFSET)}set liveEdgeOffset(e){e!=this.liveEdgeOffset&&(e==null?this.removeAttribute(C.LIVE_EDGE_OFFSET):this.setAttribute(C.LIVE_EDGE_OFFSET,`${+e}`))}get seekable(){return lp(this.nativeEl)}async addCuePoints(e){return aT(this.nativeEl,e)}get activeCuePoint(){return oT(this.nativeEl)}get cuePoints(){return dM(this.nativeEl)}async addChapters(e){return dT(this.nativeEl,e)}get activeChapter(){return uT(this.nativeEl)}get chapters(){return cM(this.nativeEl)}getStartDate(){return fM(this.nativeEl,this._hls)}get currentPdt(){return mM(this.nativeEl,this._hls)}get preferPlayback(){let e=this.getAttribute(C.PREFER_PLAYBACK);if(e===Zi.MSE||e===Zi.NATIVE)return e}set preferPlayback(e){e!==this.preferPlayback&&(e===Zi.MSE||e===Zi.NATIVE?this.setAttribute(C.PREFER_PLAYBACK,e):this.removeAttribute(C.PREFER_PLAYBACK))}get metadata(){return{...this.getAttributeNames().filter(e=>e.startsWith("metadata-")&&![C.METADATA_URL].includes(e)).reduce((e,t)=>{let s=this.getAttribute(t);return s!=null&&(e[t.replace(/^metadata-/,"").replace(/-/g,"_")]=s),e},{}),...At(this,Pa)}}set metadata(e){ri(this,Pa,e??{}),this.mux&&this.mux.emit("hb",At(this,Pa))}get _hlsConfig(){return At(this,Jl)}set _hlsConfig(e){ri(this,Jl,e)}get logo(){var e;return(e=this.getAttribute(C.LOGO))!=null?e:At(this,Oa)}set logo(e){e?this.setAttribute(C.LOGO,e):this.removeAttribute(C.LOGO)}load(){ri(this,Hi,HM(this,this.nativeEl,At(this,Hi)))}unload(){vT(this.nativeEl,At(this,Hi),this),ri(this,Hi,void 0)}attributeChangedCallback(e,t,s){var r,n;switch(ll.observedAttributes.includes(e)&&!["src","autoplay","preload"].includes(e)&&super.attributeChangedCallback(e,t,s),e){case C.PLAYER_SOFTWARE_NAME:this.playerSoftwareName=s??void 0;break;case C.PLAYER_SOFTWARE_VERSION:this.playerSoftwareVersion=s??void 0;break;case"src":{let a=!!t,o=!!s;!a&&o?dl(this,vn,Na).call(this):a&&!o?this.unload():a&&o&&(this.unload(),dl(this,vn,Na).call(this));break}case"autoplay":if(s===t)break;(r=At(this,Hi))==null||r.setAutoplay(this.autoplay);break;case"preload":if(s===t)break;(n=At(this,Hi))==null||n.setPreload(s);break;case C.PLAYBACK_ID:this.src=of(this);break;case C.DEBUG:{let a=this.debug;this.mux&&console.info("Cannot toggle debug mode of mux data after initialization. Make sure you set all metadata to override before setting the src."),this._hls&&(this._hls.config.debug=a);break}case C.METADATA_URL:s&&fetch(s).then(a=>a.json()).then(a=>this.metadata=a).catch(()=>console.error(`Unable to load or parse metadata JSON from metadata-url ${s}!`));break;case C.STREAM_TYPE:(s==null||s!==t)&&this.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}));break;case C.TARGET_LIVE_WINDOW:(s==null||s!==t)&&this.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0,detail:this.targetLiveWindow}));break;case C.LOGO:(s==null||s!==t)&&this.updateLogo();break;case C.DISABLE_TRACKING:{if(s==null||s!==t){let a=this.currentTime,o=this.paused;this.unload(),dl(this,vn,Na).call(this).then(()=>{this.currentTime=a,o||this.play()})}break}case C.DISABLE_COOKIES:{(s==null||s!==t)&&this.disableCookies&&document.cookie.split(";").forEach(a=>{a.trim().startsWith("muxData")&&(document.cookie=a.replace(/^ +/,"").replace(/=.*/,"=;expires="+new Date().toUTCString()+";path=/"))});break}}}updateLogo(){if(!this.shadowRoot)return;let e=this.shadowRoot.querySelector('slot[name="logo"]');if(!e)return;let t=this.constructor.getLogoHTML(At(this,Oa)||this.logo);e.innerHTML=t}connectedCallback(){var e;(e=super.connectedCallback)==null||e.call(this),this.nativeEl&&this.src&&!At(this,Hi)&&dl(this,vn,Na).call(this)}disconnectedCallback(){this.unload()}handleEvent(e){e.target===this.nativeEl&&this.dispatchEvent(new CustomEvent(e.type,{composed:!0,detail:e.detail}))}};Hi=new WeakMap,Ma=new WeakMap,Xl=new WeakMap,Pa=new WeakMap,Zl=new WeakMap,Jl=new WeakMap,ed=new WeakMap,td=new WeakMap,id=new WeakMap,Oa=new WeakMap,vn=new WeakSet,Na=async function(){At(this,Ma)||(await ri(this,Ma,Promise.resolve()),ri(this,Ma,null),this.load())};const Rr=new WeakMap;class Wc extends Error{}class lP extends Error{}const dP=["application/x-mpegURL","application/vnd.apple.mpegurl","audio/mpegurl"],uP=globalThis.WeakRef?class extends Set{add(i){super.add(new WeakRef(i))}forEach(i){super.forEach(e=>{const t=e.deref();t&&i(t)})}}:Set;function cP(i){globalThis.chrome?.cast?.isAvailable?globalThis.cast?.framework?i():customElements.whenDefined("google-cast-button").then(i):globalThis.__onGCastApiAvailable=()=>{customElements.whenDefined("google-cast-button").then(i)}}function hP(){return globalThis.chrome}function fP(){const i="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1";if(globalThis.chrome?.cast||document.querySelector(`script[src="${i}"]`))return;const e=document.createElement("script");e.src=i,document.head.append(e)}function Ws(){return globalThis.cast?.framework?.CastContext.getInstance()}function cp(){return Ws()?.getCurrentSession()}function hp(){return cp()?.getSessionObj().media[0]}function mP(i){return new Promise((e,t)=>{hp().editTracksInfo(i,e,t)})}function pP(i){return new Promise((e,t)=>{hp().getStatus(i,e,t)})}function ev(i){return Ws().setOptions({...LT(),...i})}function LT(){return{receiverApplicationId:"CC1AD845",autoJoinPolicy:"origin_scoped",androidReceiverCompatible:!1,language:"en-US",resumeSavedSession:!0}}function gP(i){if(!i)return;const e=/\.([a-zA-Z0-9]+)(?:\?.*)?$/,t=i.match(e);return t?t[1]:null}function vP(i){const e=i.split(`
|
|
1540
1540
|
`),t=[];for(let s=0;s<e.length;s++)if(e[s].trim().startsWith("#EXT-X-STREAM-INF")){const n=e[s+1]?e[s+1].trim():"";n&&!n.startsWith("#")&&t.push(n)}return t}function EP(i){return i.split(`
|
|
1541
|
-
`).find(s=>!s.trim().startsWith("#")&&s.trim()!=="")}async function yP(i){try{const t=(await fetch(i,{method:"HEAD"})).headers.get("Content-Type");return dP.some(s=>t===s)}catch(e){return console.error("Error while trying to get the Content-Type of the manifest",e),!1}}async function bP(i){try{const e=await(await fetch(i)).text();let t=e;const s=vP(e);if(s.length>0){const a=new URL(s[0],i).toString();t=await(await fetch(a)).text()}const r=EP(t);return gP(r)}catch(e){console.error("Error while trying to parse the manifest playlist",e);return}}const sd=new uP,Ds=new WeakSet;let ft;cP(()=>{if(!globalThis.chrome?.cast?.isAvailable){console.debug("chrome.cast.isAvailable",globalThis.chrome?.cast?.isAvailable);return}ft||(ft=cast.framework,Ws().addEventListener(ft.CastContextEventType.CAST_STATE_CHANGED,i=>{sd.forEach(e=>Rr.get(e).onCastStateChanged?.(i))}),Ws().addEventListener(ft.CastContextEventType.SESSION_STATE_CHANGED,i=>{sd.forEach(e=>Rr.get(e).onSessionStateChanged?.(i))}),sd.forEach(i=>Rr.get(i).init?.()))});let tv=0;class TP extends EventTarget{#e;#s;#i;#r;#t="disconnected";#a=!1;#n=new Set;#l=new WeakMap;constructor(e){super(),this.#e=e,sd.add(this),Rr.set(this,{init:()=>this.#h(),onCastStateChanged:()=>this.#u(),onSessionStateChanged:()=>this.#m(),getCastPlayer:()=>this.#o}),this.#h()}get#o(){if(Ds.has(this.#e))return this.#i}get state(){return this.#t}async watchAvailability(e){if(this.#e.disableRemotePlayback)throw new Wc("disableRemotePlayback attribute is present.");return this.#l.set(e,++tv),this.#n.add(e),queueMicrotask(()=>e(this.#c())),tv}async cancelWatchAvailability(e){if(this.#e.disableRemotePlayback)throw new Wc("disableRemotePlayback attribute is present.");e?this.#n.delete(e):this.#n.clear()}async prompt(){if(this.#e.disableRemotePlayback)throw new Wc("disableRemotePlayback attribute is present.");if(!globalThis.chrome?.cast?.isAvailable)throw new lP("The RemotePlayback API is disabled on this platform.");const e=Ds.has(this.#e);Ds.add(this.#e),ev(this.#e.castOptions),Object.entries(this.#r).forEach(([t,s])=>{this.#i.controller.addEventListener(t,s)});try{await Ws().requestSession()}catch(t){if(e||Ds.delete(this.#e),t==="cancel")return;throw new Error(t)}Rr.get(this.#e)?.loadOnPrompt?.()}#d(){Ds.has(this.#e)&&(Object.entries(this.#r).forEach(([e,t])=>{this.#i.controller.removeEventListener(e,t)}),Ds.delete(this.#e),this.#e.muted=this.#i.isMuted,this.#e.currentTime=this.#i.savedPlayerState.currentTime,this.#i.savedPlayerState.isPaused===!1&&this.#e.play())}#c(){const e=Ws()?.getCastState();return e&&e!=="NO_DEVICES_AVAILABLE"}#u(){const e=Ws().getCastState();if(Ds.has(this.#e)&&e==="CONNECTING"&&(this.#t="connecting",this.dispatchEvent(new Event("connecting"))),!this.#a&&e?.includes("CONNECT")){this.#a=!0;for(let t of this.#n)t(!0)}else if(this.#a&&(!e||e==="NO_DEVICES_AVAILABLE")){this.#a=!1;for(let t of this.#n)t(!1)}}async#m(){const{SESSION_RESUMED:e}=ft.SessionState;if(Ws().getSessionState()===e&&this.#e.castSrc===hp()?.media.contentId){Ds.add(this.#e),Object.entries(this.#r).forEach(([t,s])=>{this.#i.controller.addEventListener(t,s)});try{await pP(new chrome.cast.media.GetStatusRequest)}catch(t){console.error(t)}this.#r[ft.RemotePlayerEventType.IS_PAUSED_CHANGED](),this.#r[ft.RemotePlayerEventType.PLAYER_STATE_CHANGED]()}}#h(){!ft||this.#s||(this.#s=!0,ev(this.#e.castOptions),this.#e.textTracks.addEventListener("change",()=>this.#f()),this.#u(),this.#i=new ft.RemotePlayer,new ft.RemotePlayerController(this.#i),this.#r={[ft.RemotePlayerEventType.IS_CONNECTED_CHANGED]:({value:e})=>{e===!0?(this.#t="connected",this.dispatchEvent(new Event("connect"))):(this.#d(),this.#t="disconnected",this.dispatchEvent(new Event("disconnect")))},[ft.RemotePlayerEventType.DURATION_CHANGED]:()=>{this.#e.dispatchEvent(new Event("durationchange"))},[ft.RemotePlayerEventType.VOLUME_LEVEL_CHANGED]:()=>{this.#e.dispatchEvent(new Event("volumechange"))},[ft.RemotePlayerEventType.IS_MUTED_CHANGED]:()=>{this.#e.dispatchEvent(new Event("volumechange"))},[ft.RemotePlayerEventType.CURRENT_TIME_CHANGED]:()=>{this.#o?.isMediaLoaded&&this.#e.dispatchEvent(new Event("timeupdate"))},[ft.RemotePlayerEventType.VIDEO_INFO_CHANGED]:()=>{this.#e.dispatchEvent(new Event("resize"))},[ft.RemotePlayerEventType.IS_PAUSED_CHANGED]:()=>{this.#e.dispatchEvent(new Event(this.paused?"pause":"play"))},[ft.RemotePlayerEventType.PLAYER_STATE_CHANGED]:()=>{this.#o?.playerState!==chrome.cast.media.PlayerState.PAUSED&&this.#e.dispatchEvent(new Event({[chrome.cast.media.PlayerState.PLAYING]:"playing",[chrome.cast.media.PlayerState.BUFFERING]:"waiting",[chrome.cast.media.PlayerState.IDLE]:"emptied"}[this.#o?.playerState]))},[ft.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED]:async()=>{this.#o?.isMediaLoaded&&(await Promise.resolve(),this.#p())}})}#p(){this.#f()}async#f(){if(!this.#o)return;const t=(this.#i.mediaInfo?.tracks??[]).filter(({type:c})=>c===chrome.cast.media.TrackType.TEXT),s=[...this.#e.textTracks].filter(({kind:c})=>c==="subtitles"||c==="captions"),r=t.map(({language:c,name:h,trackId:f})=>{const{mode:m}=s.find(p=>p.language===c&&p.label===h)??{};return m?{mode:m,trackId:f}:!1}).filter(Boolean),a=r.filter(({mode:c})=>c!=="showing").map(({trackId:c})=>c),o=r.find(({mode:c})=>c==="showing"),l=cp()?.getSessionObj().media[0]?.activeTrackIds??[];let d=l;if(l.length&&(d=d.filter(c=>!a.includes(c))),o?.trackId&&(d=[...d,o.trackId]),d=[...new Set(d)],!((c,h)=>c.length===h.length&&c.every(f=>h.includes(f)))(l,d))try{const c=new chrome.cast.media.EditTracksInfoRequest(d);await mP(c)}catch(c){console.error(c)}}}const _P=i=>class extends i{static observedAttributes=[...i.observedAttributes??[],"cast-src","cast-content-type","cast-stream-type","cast-receiver"];#e={paused:!1};#s=LT();#i;#r;get remote(){return this.#r?this.#r:hP()?(this.disableRemotePlayback||fP(),Rr.set(this,{loadOnPrompt:()=>this.#a()}),this.#r=new TP(this)):super.remote}get#t(){return Rr.get(this.remote)?.getCastPlayer?.()}attributeChangedCallback(t,s,r){if(super.attributeChangedCallback(t,s,r),t==="cast-receiver"&&r){this.#s.receiverApplicationId=r;return}if(this.#t)switch(t){case"cast-stream-type":case"cast-src":this.load();break}}async#a(){this.#e.paused=super.paused,super.pause(),this.muted=super.muted;try{await this.load()}catch(t){console.error(t)}}async load(){if(!this.#t)return super.load();const t=new chrome.cast.media.MediaInfo(this.castSrc,this.castContentType);t.customData=this.castCustomData;const s=[...this.querySelectorAll("track")].filter(({kind:o,src:l})=>l&&(o==="subtitles"||o==="captions")),r=[];let n=0;if(s.length&&(t.tracks=s.map(o=>{const l=++n;r.length===0&&o.track.mode==="showing"&&r.push(l);const d=new chrome.cast.media.Track(l,chrome.cast.media.TrackType.TEXT);return d.trackContentId=o.src,d.trackContentType="text/vtt",d.subtype=o.kind==="captions"?chrome.cast.media.TextTrackType.CAPTIONS:chrome.cast.media.TextTrackType.SUBTITLES,d.name=o.label,d.language=o.srclang,d})),this.castStreamType==="live"?t.streamType=chrome.cast.media.StreamType.LIVE:t.streamType=chrome.cast.media.StreamType.BUFFERED,t.metadata=new chrome.cast.media.GenericMediaMetadata,t.metadata.title=this.title,t.metadata.images=[{url:this.poster}],yP(this.castSrc)){const o=await bP(this.castSrc);o?.includes("m4s")||o?.includes("mp4")?(t.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.FMP4,t.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.FMP4):o?.includes("ts")&&(t.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.TS,t.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.TS)}const a=new chrome.cast.media.LoadRequest(t);a.currentTime=super.currentTime??0,a.autoplay=!this.#e.paused,a.activeTrackIds=r,await cp()?.loadMedia(a),this.dispatchEvent(new Event("volumechange"))}play(){if(this.#t){this.#t.isPaused&&this.#t.controller?.playOrPause();return}return super.play()}pause(){if(this.#t){this.#t.isPaused||this.#t.controller?.playOrPause();return}super.pause()}get castOptions(){return this.#s}get castReceiver(){return this.getAttribute("cast-receiver")??void 0}set castReceiver(t){this.castReceiver!=t&&this.setAttribute("cast-receiver",`${t}`)}get castSrc(){return this.getAttribute("cast-src")??this.querySelector("source")?.src??this.currentSrc}set castSrc(t){this.castSrc!=t&&this.setAttribute("cast-src",`${t}`)}get castContentType(){return this.getAttribute("cast-content-type")??void 0}set castContentType(t){this.setAttribute("cast-content-type",`${t}`)}get castStreamType(){return this.getAttribute("cast-stream-type")??this.streamType??void 0}set castStreamType(t){this.setAttribute("cast-stream-type",`${t}`)}get castCustomData(){return this.#i}set castCustomData(t){const s=typeof t;if(!["object","undefined"].includes(s)){console.error(`castCustomData must be nullish or an object but value was of type ${s}`);return}this.#i=t}get readyState(){if(this.#t)switch(this.#t.playerState){case chrome.cast.media.PlayerState.IDLE:return 0;case chrome.cast.media.PlayerState.BUFFERING:return 2;default:return 3}return super.readyState}get paused(){return this.#t?this.#t.isPaused:super.paused}get muted(){return this.#t?this.#t?.isMuted:super.muted}set muted(t){if(this.#t){(t&&!this.#t.isMuted||!t&&this.#t.isMuted)&&this.#t.controller?.muteOrUnmute();return}super.muted=t}get volume(){return this.#t?this.#t?.volumeLevel??1:super.volume}set volume(t){if(this.#t){this.#t.volumeLevel=+t,this.#t.controller?.setVolumeLevel();return}super.volume=t}get duration(){return this.#t&&this.#t?.isMediaLoaded?this.#t?.duration??NaN:super.duration}get currentTime(){return this.#t&&this.#t?.isMediaLoaded?this.#t?.currentTime??0:super.currentTime}set currentTime(t){if(this.#t){this.#t.currentTime=t,this.#t.controller?.seek();return}super.currentTime=t}};class Zu extends Event{track;constructor(e,t){super(e),this.track=t.track}}const cf=new WeakMap;function ee(i){return cf.get(i)??AP(i,{})}function AP(i,e){let t=cf.get(i);return t||cf.set(i,t={}),Object.assign(t,e)}function hf(i,e){const t=i.videoTracks;ee(e).media=i,ee(e).renditionSet||(ee(e).renditionSet=new Set);const s=ee(t).trackSet;s.add(e);const r=s.size-1;r in mf.prototype||Object.defineProperty(mf.prototype,r,{get(){return[...ee(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new Zu("addtrack",{track:e}))})}function ff(i){const e=ee(i).media?.videoTracks;if(!e)return;ee(e).trackSet.delete(i),queueMicrotask(()=>{e.dispatchEvent(new Zu("removetrack",{track:i}))})}function SP(i){const e=ee(i).media.videoTracks??[];let t=!1;for(const s of e)s!==i&&(s.selected=!1,t=!0);if(t){if(ee(e).changeRequested)return;ee(e).changeRequested=!0,queueMicrotask(()=>{delete ee(e).changeRequested,e.dispatchEvent(new Event("change"))})}}class mf extends EventTarget{#e;#s;#i;constructor(){super(),ee(this).trackSet=new Set}get#r(){return ee(this).trackSet}[Symbol.iterator](){return this.#r.values()}get length(){return this.#r.size}getTrackById(e){return[...this.#r].find(t=>t.id===e)??null}get selectedIndex(){return[...this.#r].findIndex(e=>e.selected)}get onaddtrack(){return this.#e}set onaddtrack(e){this.#e&&(this.removeEventListener("addtrack",this.#e),this.#e=void 0),typeof e=="function"&&(this.#e=e,this.addEventListener("addtrack",e))}get onremovetrack(){return this.#s}set onremovetrack(e){this.#s&&(this.removeEventListener("removetrack",this.#s),this.#s=void 0),typeof e=="function"&&(this.#s=e,this.addEventListener("removetrack",e))}get onchange(){return this.#i}set onchange(e){this.#i&&(this.removeEventListener("change",this.#i),this.#i=void 0),typeof e=="function"&&(this.#i=e,this.addEventListener("change",e))}}class Ju extends Event{rendition;constructor(e,t){super(e),this.rendition=t.rendition}}function IP(i,e){const t=ee(i).media.videoRenditions;ee(e).media=ee(i).media,ee(e).track=i;const s=ee(i).renditionSet;s.add(e);const r=s.size-1;r in pf.prototype||Object.defineProperty(pf.prototype,r,{get(){return En(this)[r]}}),queueMicrotask(()=>{i.selected&&t.dispatchEvent(new Ju("addrendition",{rendition:e}))})}function xP(i){const e=ee(i).media.videoRenditions,t=ee(i).track;ee(t).renditionSet.delete(i),queueMicrotask(()=>{ee(i).track.selected&&e.dispatchEvent(new Ju("removerendition",{rendition:i}))})}function LP(i){const e=ee(i).media.videoRenditions;!e||ee(e).changeRequested||(ee(e).changeRequested=!0,queueMicrotask(()=>{delete ee(e).changeRequested,ee(i).track.selected&&e.dispatchEvent(new Event("change"))}))}function En(i){return[...ee(i).media.videoTracks].filter(t=>t.selected).flatMap(t=>[...ee(t).renditionSet])}class pf extends EventTarget{#e;#s;#i;[Symbol.iterator](){return En(this).values()}get length(){return En(this).length}getRenditionById(e){return En(this).find(t=>`${t.id}`==`${e}`)??null}get selectedIndex(){return En(this).findIndex(e=>e.selected)}set selectedIndex(e){for(const[t,s]of En(this).entries())s.selected=t===e}get onaddrendition(){return this.#e}set onaddrendition(e){this.#e&&(this.removeEventListener("addrendition",this.#e),this.#e=void 0),typeof e=="function"&&(this.#e=e,this.addEventListener("addrendition",e))}get onremoverendition(){return this.#s}set onremoverendition(e){this.#s&&(this.removeEventListener("removerendition",this.#s),this.#s=void 0),typeof e=="function"&&(this.#s=e,this.addEventListener("removerendition",e))}get onchange(){return this.#i}set onchange(e){this.#i&&(this.removeEventListener("change",this.#i),this.#i=void 0),typeof e=="function"&&(this.#i=e,this.addEventListener("change",e))}}class RP{src;id;width;height;bitrate;frameRate;codec;#e=!1;get selected(){return this.#e}set selected(e){this.#e!==e&&(this.#e=e,LP(this))}}class RT{id;kind;label="";language="";sourceBuffer;#e=!1;addRendition(e,t,s,r,n,a){const o=new RP;return o.src=e,o.width=t,o.height=s,o.frameRate=a,o.bitrate=n,o.codec=r,IP(this,o),o}removeRendition(e){xP(e)}get selected(){return this.#e}set selected(e){this.#e!==e&&(this.#e=e,e===!0&&SP(this))}}function kP(i,e){const t=ee(i).media.audioRenditions;ee(e).media=ee(i).media,ee(e).track=i;const s=ee(i).renditionSet;s.add(e);const r=s.size-1;r in gf.prototype||Object.defineProperty(gf.prototype,r,{get(){return yn(this)[r]}}),queueMicrotask(()=>{i.enabled&&t.dispatchEvent(new Ju("addrendition",{rendition:e}))})}function DP(i){const e=ee(i).media.audioRenditions,t=ee(i).track;ee(t).renditionSet.delete(i),queueMicrotask(()=>{ee(i).track.enabled&&e.dispatchEvent(new Ju("removerendition",{rendition:i}))})}function CP(i){const e=ee(i).media.audioRenditions;!e||ee(e).changeRequested||(ee(e).changeRequested=!0,queueMicrotask(()=>{delete ee(e).changeRequested,ee(i).track.enabled&&e.dispatchEvent(new Event("change"))}))}function yn(i){return[...ee(i).media.audioTracks].filter(t=>t.enabled).flatMap(t=>[...ee(t).renditionSet])}class gf extends EventTarget{#e;#s;#i;[Symbol.iterator](){return yn(this).values()}get length(){return yn(this).length}getRenditionById(e){return yn(this).find(t=>`${t.id}`==`${e}`)??null}get selectedIndex(){return yn(this).findIndex(e=>e.selected)}set selectedIndex(e){for(const[t,s]of yn(this).entries())s.selected=t===e}get onaddrendition(){return this.#e}set onaddrendition(e){this.#e&&(this.removeEventListener("addrendition",this.#e),this.#e=void 0),typeof e=="function"&&(this.#e=e,this.addEventListener("addrendition",e))}get onremoverendition(){return this.#s}set onremoverendition(e){this.#s&&(this.removeEventListener("removerendition",this.#s),this.#s=void 0),typeof e=="function"&&(this.#s=e,this.addEventListener("removerendition",e))}get onchange(){return this.#i}set onchange(e){this.#i&&(this.removeEventListener("change",this.#i),this.#i=void 0),typeof e=="function"&&(this.#i=e,this.addEventListener("change",e))}}class wP{src;id;bitrate;codec;#e=!1;get selected(){return this.#e}set selected(e){this.#e!==e&&(this.#e=e,CP(this))}}function vf(i,e){const t=i.audioTracks;ee(e).media=i,ee(e).renditionSet||(ee(e).renditionSet=new Set);const s=ee(t).trackSet;s.add(e);const r=s.size-1;r in yf.prototype||Object.defineProperty(yf.prototype,r,{get(){return[...ee(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new Zu("addtrack",{track:e}))})}function Ef(i){const e=ee(i).media?.audioTracks;if(!e)return;ee(e).trackSet.delete(i),queueMicrotask(()=>{e.dispatchEvent(new Zu("removetrack",{track:i}))})}function MP(i){const e=ee(i).media.audioTracks;!e||ee(e).changeRequested||(ee(e).changeRequested=!0,queueMicrotask(()=>{delete ee(e).changeRequested,e.dispatchEvent(new Event("change"))}))}class yf extends EventTarget{#e;#s;#i;constructor(){super(),ee(this).trackSet=new Set}get#r(){return ee(this).trackSet}[Symbol.iterator](){return this.#r.values()}get length(){return this.#r.size}getTrackById(e){return[...this.#r].find(t=>t.id===e)??null}get onaddtrack(){return this.#e}set onaddtrack(e){this.#e&&(this.removeEventListener("addtrack",this.#e),this.#e=void 0),typeof e=="function"&&(this.#e=e,this.addEventListener("addtrack",e))}get onremovetrack(){return this.#s}set onremovetrack(e){this.#s&&(this.removeEventListener("removetrack",this.#s),this.#s=void 0),typeof e=="function"&&(this.#s=e,this.addEventListener("removetrack",e))}get onchange(){return this.#i}set onchange(e){this.#i&&(this.removeEventListener("change",this.#i),this.#i=void 0),typeof e=="function"&&(this.#i=e,this.addEventListener("change",e))}}class kT{id;kind;label="";language="";sourceBuffer;#e=!1;addRendition(e,t,s){const r=new wP;return r.src=e,r.codec=t,r.bitrate=s,kP(this,r),r}removeRendition(e){DP(e)}get enabled(){return this.#e}set enabled(e){this.#e!==e&&(this.#e=e,MP(this))}}const iv=ou(globalThis.HTMLMediaElement,"video"),sv=ou(globalThis.HTMLMediaElement,"audio");function PP(i){if(!i?.prototype)return i;const e=ou(i,"video");(!e||`${e}`.includes("[native code]"))&&Object.defineProperty(i.prototype,"videoTracks",{get(){return OP(this)}});const t=ou(i,"audio");(!t||`${t}`.includes("[native code]"))&&Object.defineProperty(i.prototype,"audioTracks",{get(){return NP(this)}}),"addVideoTrack"in i.prototype||(i.prototype.addVideoTrack=function(n,a="",o=""){const l=new RT;return l.kind=n,l.label=a,l.language=o,hf(this,l),l}),"removeVideoTrack"in i.prototype||(i.prototype.removeVideoTrack=ff),"addAudioTrack"in i.prototype||(i.prototype.addAudioTrack=function(n,a="",o=""){const l=new kT;return l.kind=n,l.label=a,l.language=o,vf(this,l),l}),"removeAudioTrack"in i.prototype||(i.prototype.removeAudioTrack=Ef),"videoRenditions"in i.prototype||Object.defineProperty(i.prototype,"videoRenditions",{get(){return s(this)}});const s=n=>{let a=ee(n).videoRenditions;return a||(a=new pf,ee(a).media=n,ee(n).videoRenditions=a),a};"audioRenditions"in i.prototype||Object.defineProperty(i.prototype,"audioRenditions",{get(){return r(this)}});const r=n=>{let a=ee(n).audioRenditions;return a||(a=new gf,ee(a).media=n,ee(n).audioRenditions=a),a};return i}function ou(i,e){if(i?.prototype)return Object.getOwnPropertyDescriptor(i.prototype,`${e}Tracks`)?.get}function OP(i){let e=ee(i).videoTracks;if(!e&&(e=new mf,ee(i).videoTracks=e,iv)){const t=iv.call(i.nativeEl??i);for(const s of t)hf(i,s);t.addEventListener("change",()=>{e.dispatchEvent(new Event("change"))}),t.addEventListener("addtrack",s=>{if([...e].some(r=>r instanceof RT)){for(const r of t)ff(r);return}hf(i,s.track)}),t.addEventListener("removetrack",s=>{ff(s.track)})}return e}function NP(i){let e=ee(i).audioTracks;if(!e&&(e=new yf,ee(i).audioTracks=e,sv)){const t=sv.call(i.nativeEl??i);for(const s of t)vf(i,s);t.addEventListener("change",()=>{e.dispatchEvent(new Event("change"))}),t.addEventListener("addtrack",s=>{if([...e].some(r=>r instanceof kT)){for(const r of t)Ef(r);return}vf(i,s.track)}),t.addEventListener("removetrack",s=>{Ef(s.track)})}return e}var DT=i=>{throw TypeError(i)},CT=(i,e,t)=>e.has(i)||DT("Cannot "+t),UP=(i,e,t)=>(CT(i,e,"read from private field"),t?t.call(i):e.get(i)),$P=(i,e,t)=>e.has(i)?DT("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),FP=(i,e,t,s)=>(CT(i,e,"write to private field"),e.set(i,t),t),wT=class{addEventListener(){}removeEventListener(){}dispatchEvent(e){return!0}};if(typeof DocumentFragment>"u"){class i extends wT{}globalThis.DocumentFragment=i}var BP=class extends wT{},HP={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(BP)}},GP={customElements:HP},KP=typeof window>"u"||typeof globalThis.customElements>"u",qc=KP?GP:globalThis,rd,rv=class extends _P(PP(oP)){constructor(){super(...arguments),$P(this,rd)}get autoplay(){let i=this.getAttribute("autoplay");return i===null?!1:i===""?!0:i}set autoplay(i){let e=this.autoplay;i!==e&&(i?this.setAttribute("autoplay",typeof i=="string"?i:""):this.removeAttribute("autoplay"))}get muxCastCustomData(){return{mux:{playbackId:this.playbackId,minResolution:this.minResolution,maxResolution:this.maxResolution,renditionOrder:this.renditionOrder,customDomain:this.customDomain,tokens:{drm:this.drmToken},envKey:this.envKey,metadata:this.metadata,disableCookies:this.disableCookies,disableTracking:this.disableTracking,beaconCollectionDomain:this.beaconCollectionDomain,startTime:this.startTime,preferCmcd:this.preferCmcd}}}get castCustomData(){var i;return(i=UP(this,rd))!=null?i:this.muxCastCustomData}set castCustomData(i){FP(this,rd,i)}};rd=new WeakMap;qc.customElements.get("mux-video")||(qc.customElements.define("mux-video",rv),qc.MuxVideoElement=rv);var MT=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},he=(i,e,t)=>(MT(i,e,"read from private field"),t?t.call(i):e.get(i)),ji=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},gs=(i,e,t,s)=>(MT(i,e,"write to private field"),e.set(i,t),t),bn,nd,cr,Ua,Os,Ns,Us,hr,Tn,ad,vi;const nv=1,av=0,VP=1,WP={processCallback(i,e,t){if(t){for(const[s,r]of e)if(s in t){const n=t[s];typeof n=="boolean"&&r instanceof Si&&typeof r.element[r.attributeName]=="boolean"?r.booleanValue=n:typeof n=="function"&&r instanceof Si?r.element[r.attributeName]=n:r.value=n}}}};class ec extends k.DocumentFragment{constructor(e,t,s=WP){var r;super(),ji(this,bn,void 0),ji(this,nd,void 0),this.append(e.content.cloneNode(!0)),gs(this,bn,PT(this)),gs(this,nd,s),(r=s.createCallback)==null||r.call(s,this,he(this,bn),t),s.processCallback(this,he(this,bn),t)}update(e){he(this,nd).processCallback(this,he(this,bn),e)}}bn=new WeakMap;nd=new WeakMap;const PT=(i,e=[])=>{let t,s;for(const r of i.attributes||[])if(r.value.includes("{{")){const n=new YP;for([t,s]of lv(r.value))if(!t)n.append(s);else{const a=new Si(i,r.name,r.namespaceURI);n.append(a),e.push([s,a])}r.value=n.toString()}for(const r of i.childNodes)if(r.nodeType===nv&&!(r instanceof HTMLTemplateElement))PT(r,e);else{const n=r.data;if(r.nodeType===nv||n.includes("{{")){const a=[];if(n)for([t,s]of lv(n))if(!t)a.push(new Text(s));else{const o=new sa(i);a.push(o),e.push([s,o])}else if(r instanceof HTMLTemplateElement){const o=new UT(i,r);a.push(o),e.push([o.expression,o])}r.replaceWith(...a.flatMap(o=>o.replacementNodes||[o]))}}return e},ov={},lv=i=>{let e="",t=0,s=ov[i],r=0,n;if(s)return s;for(s=[];n=i[r];r++)n==="{"&&i[r+1]==="{"&&i[r-1]!=="\\"&&i[r+2]&&++t==1?(e&&s.push([av,e]),e="",r++):n==="}"&&i[r+1]==="}"&&i[r-1]!=="\\"&&!--t?(s.push([VP,e.trim()]),e="",r++):e+=n||"";return e&&s.push([av,(t>0?"{{":"")+e]),ov[i]=s},qP=11;class OT{get value(){return""}set value(e){}toString(){return this.value}}const NT=new WeakMap;class YP{constructor(){ji(this,cr,[])}[Symbol.iterator](){return he(this,cr).values()}get length(){return he(this,cr).length}item(e){return he(this,cr)[e]}append(...e){for(const t of e)t instanceof Si&&NT.set(t,this),he(this,cr).push(t)}toString(){return he(this,cr).join("")}}cr=new WeakMap;class Si extends OT{constructor(e,t,s){super(),ji(this,hr),ji(this,Ua,""),ji(this,Os,void 0),ji(this,Ns,void 0),ji(this,Us,void 0),gs(this,Os,e),gs(this,Ns,t),gs(this,Us,s)}get attributeName(){return he(this,Ns)}get attributeNamespace(){return he(this,Us)}get element(){return he(this,Os)}get value(){return he(this,Ua)}set value(e){he(this,Ua)!==e&&(gs(this,Ua,e),!he(this,hr,Tn)||he(this,hr,Tn).length===1?e==null?he(this,Os).removeAttributeNS(he(this,Us),he(this,Ns)):he(this,Os).setAttributeNS(he(this,Us),he(this,Ns),e):he(this,Os).setAttributeNS(he(this,Us),he(this,Ns),he(this,hr,Tn).toString()))}get booleanValue(){return he(this,Os).hasAttributeNS(he(this,Us),he(this,Ns))}set booleanValue(e){if(!he(this,hr,Tn)||he(this,hr,Tn).length===1)this.value=e?"":null;else throw new DOMException("Value is not fully templatized")}}Ua=new WeakMap;Os=new WeakMap;Ns=new WeakMap;Us=new WeakMap;hr=new WeakSet;Tn=function(){return NT.get(this)};class sa extends OT{constructor(e,t){super(),ji(this,ad,void 0),ji(this,vi,void 0),gs(this,ad,e),gs(this,vi,t?[...t]:[new Text])}get replacementNodes(){return he(this,vi)}get parentNode(){return he(this,ad)}get nextSibling(){return he(this,vi)[he(this,vi).length-1].nextSibling}get previousSibling(){return he(this,vi)[0].previousSibling}get value(){return he(this,vi).map(e=>e.textContent).join("")}set value(e){this.replace(e)}replace(...e){const t=e.flat().flatMap(s=>s==null?[new Text]:s.forEach?[...s]:s.nodeType===qP?[...s.childNodes]:s.nodeType?[s]:[new Text(s)]);t.length||t.push(new Text),gs(this,vi,jP(he(this,vi)[0].parentNode,he(this,vi),t,this.nextSibling))}}ad=new WeakMap;vi=new WeakMap;class UT extends sa{constructor(e,t){const s=t.getAttribute("directive")||t.getAttribute("type");let r=t.getAttribute("expression")||t.getAttribute(s)||"";r.startsWith("{{")&&(r=r.trim().slice(2,-2).trim()),super(e),this.expression=r,this.template=t,this.directive=s}}function jP(i,e,t,s=null){let r=0,n,a,o,l=t.length,d=e.length;for(;r<l&&r<d&&e[r]==t[r];)r++;for(;r<l&&r<d&&t[l-1]==e[d-1];)s=t[--d,--l];if(r==d)for(;r<l;)i.insertBefore(t[r++],s);if(r==l)for(;r<d;)i.removeChild(e[r++]);else{for(n=e[r];r<l;)o=t[r++],a=n?n.nextSibling:s,n==o?n=a:r<l&&t[r]==a?(i.replaceChild(o,n),n=a):i.insertBefore(o,n);for(;n!=s;)a=n.nextSibling,i.removeChild(n),n=a}return t}const dv={string:i=>String(i)};class $T{constructor(e){this.template=e,this.state=void 0}}const Tr=new WeakMap,_r=new WeakMap,bf={partial:(i,e)=>{e[i.expression]=new $T(i.template)},if:(i,e)=>{var t;if(FT(i.expression,e))if(Tr.get(i)!==i.template){Tr.set(i,i.template);const s=new ec(i.template,e,fp);i.replace(s),_r.set(i,s)}else(t=_r.get(i))==null||t.update(e);else i.replace(""),Tr.delete(i),_r.delete(i)}},zP=Object.keys(bf),fp={processCallback(i,e,t){var s,r;if(t)for(const[n,a]of e){if(a instanceof UT){if(!a.directive){const l=zP.find(d=>a.template.hasAttribute(d));l&&(a.directive=l,a.expression=a.template.getAttribute(l))}(s=bf[a.directive])==null||s.call(bf,a,t);continue}let o=FT(n,t);if(o instanceof $T){Tr.get(a)!==o.template?(Tr.set(a,o.template),o=new ec(o.template,o.state,fp),a.value=o,_r.set(a,o)):(r=_r.get(a))==null||r.update(o.state);continue}o?(a instanceof Si&&a.attributeName.startsWith("aria-")&&(o=String(o)),a instanceof Si?typeof o=="boolean"?a.booleanValue=o:typeof o=="function"?a.element[a.attributeName]=o:a.value=o:(a.value=o,Tr.delete(a),_r.delete(a))):a instanceof Si?a.value=void 0:(a.value=void 0,Tr.delete(a),_r.delete(a))}}},uv={"!":i=>!i,"!!":i=>!!i,"==":(i,e)=>i==e,"!=":(i,e)=>i!=e,">":(i,e)=>i>e,">=":(i,e)=>i>=e,"<":(i,e)=>i<e,"<=":(i,e)=>i<=e,"??":(i,e)=>i??e,"|":(i,e)=>{var t;return(t=dv[e])==null?void 0:t.call(dv,i)}};function QP(i){return XP(i,{boolean:/true|false/,number:/-?\d+\.?\d*/,string:/(["'])((?:\\.|[^\\])*?)\1/,operator:/[!=><][=!]?|\?\?|\|/,ws:/\s+/,param:/[$a-z_][$\w]*/i}).filter(({type:e})=>e!=="ws")}function FT(i,e={}){var t,s,r,n,a,o,l;const d=QP(i);if(d.length===0||d.some(({type:u})=>!u))return ha(i);if(((t=d[0])==null?void 0:t.token)===">"){const u=e[(s=d[1])==null?void 0:s.token];if(!u)return ha(i);const c={...e};u.state=c;const h=d.slice(2);for(let f=0;f<h.length;f+=3){const m=(r=h[f])==null?void 0:r.token,p=(n=h[f+1])==null?void 0:n.token,g=(a=h[f+2])==null?void 0:a.token;m&&p==="="&&(c[m]=fa(g,e))}return u}if(d.length===1)return ul(d[0])?fa(d[0].token,e):ha(i);if(d.length===2){const u=(o=d[0])==null?void 0:o.token,c=uv[u];if(!c||!ul(d[1]))return ha(i);const h=fa(d[1].token,e);return c(h)}if(d.length===3){const u=(l=d[1])==null?void 0:l.token,c=uv[u];if(!c||!ul(d[0])||!ul(d[2]))return ha(i);const h=fa(d[0].token,e);if(u==="|")return c(h,d[2].token);const f=fa(d[2].token,e);return c(h,f)}}function ha(i){return console.warn(`Warning: invalid expression \`${i}\``),!1}function ul({type:i}){return["number","boolean","string","param"].includes(i)}function fa(i,e){const t=i[0],s=i.slice(-1);return i==="true"||i==="false"?i==="true":t===s&&["'",'"'].includes(t)?i.slice(1,-1):qv(i)?parseFloat(i):e[i]}function XP(i,e){let t,s,r;const n=[];for(;i;){r=null,t=i.length;for(const a in e)s=e[a].exec(i),s&&s.index<t&&(r={token:s[0],type:a,matches:s.slice(1)},t=s.index);t&&n.push({token:i.substr(0,t),type:void 0}),r&&n.push(r),i=i.substr(t+(r?r.token.length:0))}return n}var mp=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Tf=(i,e,t)=>(mp(i,e,"read from private field"),t?t.call(i):e.get(i)),ma=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Ar=(i,e,t,s)=>(mp(i,e,"write to private field"),e.set(i,t),t),Yc=(i,e,t)=>(mp(i,e,"access private method"),t),Hn,od,Gn,_f,BT,ld,Af;const jc={mediatargetlivewindow:"targetlivewindow",mediastreamtype:"streamtype"},HT=lt.createElement("template");HT.innerHTML=`
|
|
1541
|
+
`).find(s=>!s.trim().startsWith("#")&&s.trim()!=="")}async function yP(i){try{const t=(await fetch(i,{method:"HEAD"})).headers.get("Content-Type");return dP.some(s=>t===s)}catch(e){return console.error("Error while trying to get the Content-Type of the manifest",e),!1}}async function bP(i){try{const e=await(await fetch(i)).text();let t=e;const s=vP(e);if(s.length>0){const a=new URL(s[0],i).toString();t=await(await fetch(a)).text()}const r=EP(t);return gP(r)}catch(e){console.error("Error while trying to parse the manifest playlist",e);return}}const sd=new uP,Ds=new WeakSet;let ft;cP(()=>{if(!globalThis.chrome?.cast?.isAvailable){console.debug("chrome.cast.isAvailable",globalThis.chrome?.cast?.isAvailable);return}ft||(ft=cast.framework,Ws().addEventListener(ft.CastContextEventType.CAST_STATE_CHANGED,i=>{sd.forEach(e=>Rr.get(e).onCastStateChanged?.(i))}),Ws().addEventListener(ft.CastContextEventType.SESSION_STATE_CHANGED,i=>{sd.forEach(e=>Rr.get(e).onSessionStateChanged?.(i))}),sd.forEach(i=>Rr.get(i).init?.()))});let tv=0;class TP extends EventTarget{#e;#s;#i;#r;#t="disconnected";#a=!1;#n=new Set;#l=new WeakMap;constructor(e){super(),this.#e=e,sd.add(this),Rr.set(this,{init:()=>this.#h(),onCastStateChanged:()=>this.#u(),onSessionStateChanged:()=>this.#m(),getCastPlayer:()=>this.#o}),this.#h()}get#o(){if(Ds.has(this.#e))return this.#i}get state(){return this.#t}async watchAvailability(e){if(this.#e.disableRemotePlayback)throw new Wc("disableRemotePlayback attribute is present.");return this.#l.set(e,++tv),this.#n.add(e),queueMicrotask(()=>e(this.#c())),tv}async cancelWatchAvailability(e){if(this.#e.disableRemotePlayback)throw new Wc("disableRemotePlayback attribute is present.");e?this.#n.delete(e):this.#n.clear()}async prompt(){if(this.#e.disableRemotePlayback)throw new Wc("disableRemotePlayback attribute is present.");if(!globalThis.chrome?.cast?.isAvailable)throw new lP("The RemotePlayback API is disabled on this platform.");const e=Ds.has(this.#e);Ds.add(this.#e),ev(this.#e.castOptions),Object.entries(this.#r).forEach(([t,s])=>{this.#i.controller.addEventListener(t,s)});try{await Ws().requestSession()}catch(t){if(e||Ds.delete(this.#e),t==="cancel")return;throw new Error(t)}Rr.get(this.#e)?.loadOnPrompt?.()}#d(){Ds.has(this.#e)&&(Object.entries(this.#r).forEach(([e,t])=>{this.#i.controller.removeEventListener(e,t)}),Ds.delete(this.#e),this.#e.muted=this.#i.isMuted,this.#e.currentTime=this.#i.savedPlayerState.currentTime,this.#i.savedPlayerState.isPaused===!1&&this.#e.play())}#c(){const e=Ws()?.getCastState();return e&&e!=="NO_DEVICES_AVAILABLE"}#u(){const e=Ws().getCastState();if(Ds.has(this.#e)&&e==="CONNECTING"&&(this.#t="connecting",this.dispatchEvent(new Event("connecting"))),!this.#a&&e?.includes("CONNECT")){this.#a=!0;for(let t of this.#n)t(!0)}else if(this.#a&&(!e||e==="NO_DEVICES_AVAILABLE")){this.#a=!1;for(let t of this.#n)t(!1)}}async#m(){const{SESSION_RESUMED:e}=ft.SessionState;if(Ws().getSessionState()===e&&this.#e.castSrc===hp()?.media.contentId){Ds.add(this.#e),Object.entries(this.#r).forEach(([t,s])=>{this.#i.controller.addEventListener(t,s)});try{await pP(new chrome.cast.media.GetStatusRequest)}catch(t){console.error(t)}this.#r[ft.RemotePlayerEventType.IS_PAUSED_CHANGED](),this.#r[ft.RemotePlayerEventType.PLAYER_STATE_CHANGED]()}}#h(){!ft||this.#s||(this.#s=!0,ev(this.#e.castOptions),this.#e.textTracks.addEventListener("change",()=>this.#f()),this.#u(),this.#i=new ft.RemotePlayer,new ft.RemotePlayerController(this.#i),this.#r={[ft.RemotePlayerEventType.IS_CONNECTED_CHANGED]:({value:e})=>{e===!0?(this.#t="connected",this.dispatchEvent(new Event("connect"))):(this.#d(),this.#t="disconnected",this.dispatchEvent(new Event("disconnect")))},[ft.RemotePlayerEventType.DURATION_CHANGED]:()=>{this.#e.dispatchEvent(new Event("durationchange"))},[ft.RemotePlayerEventType.VOLUME_LEVEL_CHANGED]:()=>{this.#e.dispatchEvent(new Event("volumechange"))},[ft.RemotePlayerEventType.IS_MUTED_CHANGED]:()=>{this.#e.dispatchEvent(new Event("volumechange"))},[ft.RemotePlayerEventType.CURRENT_TIME_CHANGED]:()=>{this.#o?.isMediaLoaded&&this.#e.dispatchEvent(new Event("timeupdate"))},[ft.RemotePlayerEventType.VIDEO_INFO_CHANGED]:()=>{this.#e.dispatchEvent(new Event("resize"))},[ft.RemotePlayerEventType.IS_PAUSED_CHANGED]:()=>{this.#e.dispatchEvent(new Event(this.paused?"pause":"play"))},[ft.RemotePlayerEventType.PLAYER_STATE_CHANGED]:()=>{this.#o?.playerState!==chrome.cast.media.PlayerState.PAUSED&&this.#e.dispatchEvent(new Event({[chrome.cast.media.PlayerState.PLAYING]:"playing",[chrome.cast.media.PlayerState.BUFFERING]:"waiting",[chrome.cast.media.PlayerState.IDLE]:"emptied"}[this.#o?.playerState]))},[ft.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED]:async()=>{this.#o?.isMediaLoaded&&(await Promise.resolve(),this.#p())}})}#p(){this.#f()}async#f(){if(!this.#o)return;const t=(this.#i.mediaInfo?.tracks??[]).filter(({type:c})=>c===chrome.cast.media.TrackType.TEXT),s=[...this.#e.textTracks].filter(({kind:c})=>c==="subtitles"||c==="captions"),r=t.map(({language:c,name:h,trackId:f})=>{const{mode:m}=s.find(p=>p.language===c&&p.label===h)??{};return m?{mode:m,trackId:f}:!1}).filter(Boolean),a=r.filter(({mode:c})=>c!=="showing").map(({trackId:c})=>c),o=r.find(({mode:c})=>c==="showing"),l=cp()?.getSessionObj().media[0]?.activeTrackIds??[];let d=l;if(l.length&&(d=d.filter(c=>!a.includes(c))),o?.trackId&&(d=[...d,o.trackId]),d=[...new Set(d)],!((c,h)=>c.length===h.length&&c.every(f=>h.includes(f)))(l,d))try{const c=new chrome.cast.media.EditTracksInfoRequest(d);await mP(c)}catch(c){console.error(c)}}}const _P=i=>class extends i{static observedAttributes=[...i.observedAttributes??[],"cast-src","cast-content-type","cast-stream-type","cast-receiver"];#e={paused:!1};#s=LT();#i;#r;get remote(){return this.#r?this.#r:hP()?(this.disableRemotePlayback||fP(),Rr.set(this,{loadOnPrompt:()=>this.#a()}),this.#r=new TP(this)):super.remote}get#t(){return Rr.get(this.remote)?.getCastPlayer?.()}attributeChangedCallback(t,s,r){if(super.attributeChangedCallback(t,s,r),t==="cast-receiver"&&r){this.#s.receiverApplicationId=r;return}if(this.#t)switch(t){case"cast-stream-type":case"cast-src":this.load();break}}async#a(){this.#e.paused=super.paused,super.pause(),this.muted=super.muted;try{await this.load()}catch(t){console.error(t)}}async load(){if(!this.#t)return super.load();const t=new chrome.cast.media.MediaInfo(this.castSrc,this.castContentType);t.customData=this.castCustomData;const s=[...this.querySelectorAll("track")].filter(({kind:o,src:l})=>l&&(o==="subtitles"||o==="captions")),r=[];let n=0;if(s.length&&(t.tracks=s.map(o=>{const l=++n;r.length===0&&o.track.mode==="showing"&&r.push(l);const d=new chrome.cast.media.Track(l,chrome.cast.media.TrackType.TEXT);return d.trackContentId=o.src,d.trackContentType="text/vtt",d.subtype=o.kind==="captions"?chrome.cast.media.TextTrackType.CAPTIONS:chrome.cast.media.TextTrackType.SUBTITLES,d.name=o.label,d.language=o.srclang,d})),this.castStreamType==="live"?t.streamType=chrome.cast.media.StreamType.LIVE:t.streamType=chrome.cast.media.StreamType.BUFFERED,t.metadata=new chrome.cast.media.GenericMediaMetadata,t.metadata.title=this.title,t.metadata.images=[{url:this.poster}],yP(this.castSrc)){const o=await bP(this.castSrc);o?.includes("m4s")||o?.includes("mp4")?(t.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.FMP4,t.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.FMP4):o?.includes("ts")&&(t.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.TS,t.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.TS)}const a=new chrome.cast.media.LoadRequest(t);a.currentTime=super.currentTime??0,a.autoplay=!this.#e.paused,a.activeTrackIds=r,await cp()?.loadMedia(a),this.dispatchEvent(new Event("volumechange"))}play(){if(this.#t){this.#t.isPaused&&this.#t.controller?.playOrPause();return}return super.play()}pause(){if(this.#t){this.#t.isPaused||this.#t.controller?.playOrPause();return}super.pause()}get castOptions(){return this.#s}get castReceiver(){return this.getAttribute("cast-receiver")??void 0}set castReceiver(t){this.castReceiver!=t&&this.setAttribute("cast-receiver",`${t}`)}get castSrc(){return this.getAttribute("cast-src")??this.querySelector("source")?.src??this.currentSrc}set castSrc(t){this.castSrc!=t&&this.setAttribute("cast-src",`${t}`)}get castContentType(){return this.getAttribute("cast-content-type")??void 0}set castContentType(t){this.setAttribute("cast-content-type",`${t}`)}get castStreamType(){return this.getAttribute("cast-stream-type")??this.streamType??void 0}set castStreamType(t){this.setAttribute("cast-stream-type",`${t}`)}get castCustomData(){return this.#i}set castCustomData(t){const s=typeof t;if(!["object","undefined"].includes(s)){console.error(`castCustomData must be nullish or an object but value was of type ${s}`);return}this.#i=t}get readyState(){if(this.#t)switch(this.#t.playerState){case chrome.cast.media.PlayerState.IDLE:return 0;case chrome.cast.media.PlayerState.BUFFERING:return 2;default:return 3}return super.readyState}get paused(){return this.#t?this.#t.isPaused:super.paused}get muted(){return this.#t?this.#t?.isMuted:super.muted}set muted(t){if(this.#t){(t&&!this.#t.isMuted||!t&&this.#t.isMuted)&&this.#t.controller?.muteOrUnmute();return}super.muted=t}get volume(){return this.#t?this.#t?.volumeLevel??1:super.volume}set volume(t){if(this.#t){this.#t.volumeLevel=+t,this.#t.controller?.setVolumeLevel();return}super.volume=t}get duration(){return this.#t&&this.#t?.isMediaLoaded?this.#t?.duration??NaN:super.duration}get currentTime(){return this.#t&&this.#t?.isMediaLoaded?this.#t?.currentTime??0:super.currentTime}set currentTime(t){if(this.#t){this.#t.currentTime=t,this.#t.controller?.seek();return}super.currentTime=t}};class Zu extends Event{track;constructor(e,t){super(e),this.track=t.track}}const cf=new WeakMap;function ee(i){return cf.get(i)??AP(i,{})}function AP(i,e){let t=cf.get(i);return t||cf.set(i,t={}),Object.assign(t,e)}function hf(i,e){const t=i.videoTracks;ee(e).media=i,ee(e).renditionSet||(ee(e).renditionSet=new Set);const s=ee(t).trackSet;s.add(e);const r=s.size-1;r in mf.prototype||Object.defineProperty(mf.prototype,r,{get(){return[...ee(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new Zu("addtrack",{track:e}))})}function ff(i){const e=ee(i).media?.videoTracks;if(!e)return;ee(e).trackSet.delete(i),queueMicrotask(()=>{e.dispatchEvent(new Zu("removetrack",{track:i}))})}function SP(i){const e=ee(i).media.videoTracks??[];let t=!1;for(const s of e)s!==i&&(s.selected=!1,t=!0);if(t){if(ee(e).changeRequested)return;ee(e).changeRequested=!0,queueMicrotask(()=>{delete ee(e).changeRequested,e.dispatchEvent(new Event("change"))})}}class mf extends EventTarget{#e;#s;#i;constructor(){super(),ee(this).trackSet=new Set}get#r(){return ee(this).trackSet}[Symbol.iterator](){return this.#r.values()}get length(){return this.#r.size}getTrackById(e){return[...this.#r].find(t=>t.id===e)??null}get selectedIndex(){return[...this.#r].findIndex(e=>e.selected)}get onaddtrack(){return this.#e}set onaddtrack(e){this.#e&&(this.removeEventListener("addtrack",this.#e),this.#e=void 0),typeof e=="function"&&(this.#e=e,this.addEventListener("addtrack",e))}get onremovetrack(){return this.#s}set onremovetrack(e){this.#s&&(this.removeEventListener("removetrack",this.#s),this.#s=void 0),typeof e=="function"&&(this.#s=e,this.addEventListener("removetrack",e))}get onchange(){return this.#i}set onchange(e){this.#i&&(this.removeEventListener("change",this.#i),this.#i=void 0),typeof e=="function"&&(this.#i=e,this.addEventListener("change",e))}}class Ju extends Event{rendition;constructor(e,t){super(e),this.rendition=t.rendition}}function IP(i,e){const t=ee(i).media.videoRenditions;ee(e).media=ee(i).media,ee(e).track=i;const s=ee(i).renditionSet;s.add(e);const r=s.size-1;r in pf.prototype||Object.defineProperty(pf.prototype,r,{get(){return En(this)[r]}}),queueMicrotask(()=>{i.selected&&t.dispatchEvent(new Ju("addrendition",{rendition:e}))})}function xP(i){const e=ee(i).media.videoRenditions,t=ee(i).track;ee(t).renditionSet.delete(i),queueMicrotask(()=>{ee(i).track.selected&&e.dispatchEvent(new Ju("removerendition",{rendition:i}))})}function LP(i){const e=ee(i).media.videoRenditions;!e||ee(e).changeRequested||(ee(e).changeRequested=!0,queueMicrotask(()=>{delete ee(e).changeRequested,ee(i).track.selected&&e.dispatchEvent(new Event("change"))}))}function En(i){return[...ee(i).media.videoTracks].filter(t=>t.selected).flatMap(t=>[...ee(t).renditionSet])}class pf extends EventTarget{#e;#s;#i;[Symbol.iterator](){return En(this).values()}get length(){return En(this).length}getRenditionById(e){return En(this).find(t=>`${t.id}`==`${e}`)??null}get selectedIndex(){return En(this).findIndex(e=>e.selected)}set selectedIndex(e){for(const[t,s]of En(this).entries())s.selected=t===e}get onaddrendition(){return this.#e}set onaddrendition(e){this.#e&&(this.removeEventListener("addrendition",this.#e),this.#e=void 0),typeof e=="function"&&(this.#e=e,this.addEventListener("addrendition",e))}get onremoverendition(){return this.#s}set onremoverendition(e){this.#s&&(this.removeEventListener("removerendition",this.#s),this.#s=void 0),typeof e=="function"&&(this.#s=e,this.addEventListener("removerendition",e))}get onchange(){return this.#i}set onchange(e){this.#i&&(this.removeEventListener("change",this.#i),this.#i=void 0),typeof e=="function"&&(this.#i=e,this.addEventListener("change",e))}}class RP{src;id;width;height;bitrate;frameRate;codec;#e=!1;get selected(){return this.#e}set selected(e){this.#e!==e&&(this.#e=e,LP(this))}}class RT{id;kind;label="";language="";sourceBuffer;#e=!1;addRendition(e,t,s,r,n,a){const o=new RP;return o.src=e,o.width=t,o.height=s,o.frameRate=a,o.bitrate=n,o.codec=r,IP(this,o),o}removeRendition(e){xP(e)}get selected(){return this.#e}set selected(e){this.#e!==e&&(this.#e=e,e===!0&&SP(this))}}function kP(i,e){const t=ee(i).media.audioRenditions;ee(e).media=ee(i).media,ee(e).track=i;const s=ee(i).renditionSet;s.add(e);const r=s.size-1;r in gf.prototype||Object.defineProperty(gf.prototype,r,{get(){return yn(this)[r]}}),queueMicrotask(()=>{i.enabled&&t.dispatchEvent(new Ju("addrendition",{rendition:e}))})}function DP(i){const e=ee(i).media.audioRenditions,t=ee(i).track;ee(t).renditionSet.delete(i),queueMicrotask(()=>{ee(i).track.enabled&&e.dispatchEvent(new Ju("removerendition",{rendition:i}))})}function CP(i){const e=ee(i).media.audioRenditions;!e||ee(e).changeRequested||(ee(e).changeRequested=!0,queueMicrotask(()=>{delete ee(e).changeRequested,ee(i).track.enabled&&e.dispatchEvent(new Event("change"))}))}function yn(i){return[...ee(i).media.audioTracks].filter(t=>t.enabled).flatMap(t=>[...ee(t).renditionSet])}class gf extends EventTarget{#e;#s;#i;[Symbol.iterator](){return yn(this).values()}get length(){return yn(this).length}getRenditionById(e){return yn(this).find(t=>`${t.id}`==`${e}`)??null}get selectedIndex(){return yn(this).findIndex(e=>e.selected)}set selectedIndex(e){for(const[t,s]of yn(this).entries())s.selected=t===e}get onaddrendition(){return this.#e}set onaddrendition(e){this.#e&&(this.removeEventListener("addrendition",this.#e),this.#e=void 0),typeof e=="function"&&(this.#e=e,this.addEventListener("addrendition",e))}get onremoverendition(){return this.#s}set onremoverendition(e){this.#s&&(this.removeEventListener("removerendition",this.#s),this.#s=void 0),typeof e=="function"&&(this.#s=e,this.addEventListener("removerendition",e))}get onchange(){return this.#i}set onchange(e){this.#i&&(this.removeEventListener("change",this.#i),this.#i=void 0),typeof e=="function"&&(this.#i=e,this.addEventListener("change",e))}}class wP{src;id;bitrate;codec;#e=!1;get selected(){return this.#e}set selected(e){this.#e!==e&&(this.#e=e,CP(this))}}function vf(i,e){const t=i.audioTracks;ee(e).media=i,ee(e).renditionSet||(ee(e).renditionSet=new Set);const s=ee(t).trackSet;s.add(e);const r=s.size-1;r in yf.prototype||Object.defineProperty(yf.prototype,r,{get(){return[...ee(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new Zu("addtrack",{track:e}))})}function Ef(i){const e=ee(i).media?.audioTracks;if(!e)return;ee(e).trackSet.delete(i),queueMicrotask(()=>{e.dispatchEvent(new Zu("removetrack",{track:i}))})}function MP(i){const e=ee(i).media.audioTracks;!e||ee(e).changeRequested||(ee(e).changeRequested=!0,queueMicrotask(()=>{delete ee(e).changeRequested,e.dispatchEvent(new Event("change"))}))}class yf extends EventTarget{#e;#s;#i;constructor(){super(),ee(this).trackSet=new Set}get#r(){return ee(this).trackSet}[Symbol.iterator](){return this.#r.values()}get length(){return this.#r.size}getTrackById(e){return[...this.#r].find(t=>t.id===e)??null}get onaddtrack(){return this.#e}set onaddtrack(e){this.#e&&(this.removeEventListener("addtrack",this.#e),this.#e=void 0),typeof e=="function"&&(this.#e=e,this.addEventListener("addtrack",e))}get onremovetrack(){return this.#s}set onremovetrack(e){this.#s&&(this.removeEventListener("removetrack",this.#s),this.#s=void 0),typeof e=="function"&&(this.#s=e,this.addEventListener("removetrack",e))}get onchange(){return this.#i}set onchange(e){this.#i&&(this.removeEventListener("change",this.#i),this.#i=void 0),typeof e=="function"&&(this.#i=e,this.addEventListener("change",e))}}class kT{id;kind;label="";language="";sourceBuffer;#e=!1;addRendition(e,t,s){const r=new wP;return r.src=e,r.codec=t,r.bitrate=s,kP(this,r),r}removeRendition(e){DP(e)}get enabled(){return this.#e}set enabled(e){this.#e!==e&&(this.#e=e,MP(this))}}const iv=ou(globalThis.HTMLMediaElement,"video"),sv=ou(globalThis.HTMLMediaElement,"audio");function PP(i){if(!i?.prototype)return i;const e=ou(i,"video");(!e||`${e}`.includes("[native code]"))&&Object.defineProperty(i.prototype,"videoTracks",{get(){return OP(this)}});const t=ou(i,"audio");(!t||`${t}`.includes("[native code]"))&&Object.defineProperty(i.prototype,"audioTracks",{get(){return NP(this)}}),"addVideoTrack"in i.prototype||(i.prototype.addVideoTrack=function(n,a="",o=""){const l=new RT;return l.kind=n,l.label=a,l.language=o,hf(this,l),l}),"removeVideoTrack"in i.prototype||(i.prototype.removeVideoTrack=ff),"addAudioTrack"in i.prototype||(i.prototype.addAudioTrack=function(n,a="",o=""){const l=new kT;return l.kind=n,l.label=a,l.language=o,vf(this,l),l}),"removeAudioTrack"in i.prototype||(i.prototype.removeAudioTrack=Ef),"videoRenditions"in i.prototype||Object.defineProperty(i.prototype,"videoRenditions",{get(){return s(this)}});const s=n=>{let a=ee(n).videoRenditions;return a||(a=new pf,ee(a).media=n,ee(n).videoRenditions=a),a};"audioRenditions"in i.prototype||Object.defineProperty(i.prototype,"audioRenditions",{get(){return r(this)}});const r=n=>{let a=ee(n).audioRenditions;return a||(a=new gf,ee(a).media=n,ee(n).audioRenditions=a),a};return i}function ou(i,e){if(i?.prototype)return Object.getOwnPropertyDescriptor(i.prototype,`${e}Tracks`)?.get}function OP(i){let e=ee(i).videoTracks;if(!e&&(e=new mf,ee(i).videoTracks=e,iv)){const t=iv.call(i.nativeEl??i);for(const s of t)hf(i,s);t.addEventListener("change",()=>{e.dispatchEvent(new Event("change"))}),t.addEventListener("addtrack",s=>{if([...e].some(r=>r instanceof RT)){for(const r of t)ff(r);return}hf(i,s.track)}),t.addEventListener("removetrack",s=>{ff(s.track)})}return e}function NP(i){let e=ee(i).audioTracks;if(!e&&(e=new yf,ee(i).audioTracks=e,sv)){const t=sv.call(i.nativeEl??i);for(const s of t)vf(i,s);t.addEventListener("change",()=>{e.dispatchEvent(new Event("change"))}),t.addEventListener("addtrack",s=>{if([...e].some(r=>r instanceof kT)){for(const r of t)Ef(r);return}vf(i,s.track)}),t.addEventListener("removetrack",s=>{Ef(s.track)})}return e}var DT=i=>{throw TypeError(i)},CT=(i,e,t)=>e.has(i)||DT("Cannot "+t),UP=(i,e,t)=>(CT(i,e,"read from private field"),t?t.call(i):e.get(i)),$P=(i,e,t)=>e.has(i)?DT("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),FP=(i,e,t,s)=>(CT(i,e,"write to private field"),e.set(i,t),t),wT=class{addEventListener(){}removeEventListener(){}dispatchEvent(e){return!0}};if(typeof DocumentFragment>"u"){class i extends wT{}globalThis.DocumentFragment=i}var BP=class extends wT{},HP={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(BP)}},GP={customElements:HP},KP=typeof window>"u"||typeof globalThis.customElements>"u",qc=KP?GP:globalThis,rd,rv=class extends _P(PP(oP)){constructor(){super(...arguments),$P(this,rd)}get autoplay(){let i=this.getAttribute("autoplay");return i===null?!1:i===""?!0:i}set autoplay(i){let e=this.autoplay;i!==e&&(i?this.setAttribute("autoplay",typeof i=="string"?i:""):this.removeAttribute("autoplay"))}get muxCastCustomData(){return{mux:{playbackId:this.playbackId,minResolution:this.minResolution,maxResolution:this.maxResolution,renditionOrder:this.renditionOrder,customDomain:this.customDomain,tokens:{drm:this.drmToken},envKey:this.envKey,metadata:this.metadata,disableCookies:this.disableCookies,disableTracking:this.disableTracking,beaconCollectionDomain:this.beaconCollectionDomain,startTime:this.startTime,preferCmcd:this.preferCmcd}}}get castCustomData(){var i;return(i=UP(this,rd))!=null?i:this.muxCastCustomData}set castCustomData(i){FP(this,rd,i)}};rd=new WeakMap;qc.customElements.get("mux-video")||(qc.customElements.define("mux-video",rv),qc.MuxVideoElement=rv);var MT=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},fe=(i,e,t)=>(MT(i,e,"read from private field"),t?t.call(i):e.get(i)),ji=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},gs=(i,e,t,s)=>(MT(i,e,"write to private field"),e.set(i,t),t),bn,nd,cr,Ua,Os,Ns,Us,hr,Tn,ad,vi;const nv=1,av=0,VP=1,WP={processCallback(i,e,t){if(t){for(const[s,r]of e)if(s in t){const n=t[s];typeof n=="boolean"&&r instanceof Si&&typeof r.element[r.attributeName]=="boolean"?r.booleanValue=n:typeof n=="function"&&r instanceof Si?r.element[r.attributeName]=n:r.value=n}}}};class ec extends k.DocumentFragment{constructor(e,t,s=WP){var r;super(),ji(this,bn,void 0),ji(this,nd,void 0),this.append(e.content.cloneNode(!0)),gs(this,bn,PT(this)),gs(this,nd,s),(r=s.createCallback)==null||r.call(s,this,fe(this,bn),t),s.processCallback(this,fe(this,bn),t)}update(e){fe(this,nd).processCallback(this,fe(this,bn),e)}}bn=new WeakMap;nd=new WeakMap;const PT=(i,e=[])=>{let t,s;for(const r of i.attributes||[])if(r.value.includes("{{")){const n=new YP;for([t,s]of lv(r.value))if(!t)n.append(s);else{const a=new Si(i,r.name,r.namespaceURI);n.append(a),e.push([s,a])}r.value=n.toString()}for(const r of i.childNodes)if(r.nodeType===nv&&!(r instanceof HTMLTemplateElement))PT(r,e);else{const n=r.data;if(r.nodeType===nv||n.includes("{{")){const a=[];if(n)for([t,s]of lv(n))if(!t)a.push(new Text(s));else{const o=new sa(i);a.push(o),e.push([s,o])}else if(r instanceof HTMLTemplateElement){const o=new UT(i,r);a.push(o),e.push([o.expression,o])}r.replaceWith(...a.flatMap(o=>o.replacementNodes||[o]))}}return e},ov={},lv=i=>{let e="",t=0,s=ov[i],r=0,n;if(s)return s;for(s=[];n=i[r];r++)n==="{"&&i[r+1]==="{"&&i[r-1]!=="\\"&&i[r+2]&&++t==1?(e&&s.push([av,e]),e="",r++):n==="}"&&i[r+1]==="}"&&i[r-1]!=="\\"&&!--t?(s.push([VP,e.trim()]),e="",r++):e+=n||"";return e&&s.push([av,(t>0?"{{":"")+e]),ov[i]=s},qP=11;class OT{get value(){return""}set value(e){}toString(){return this.value}}const NT=new WeakMap;class YP{constructor(){ji(this,cr,[])}[Symbol.iterator](){return fe(this,cr).values()}get length(){return fe(this,cr).length}item(e){return fe(this,cr)[e]}append(...e){for(const t of e)t instanceof Si&&NT.set(t,this),fe(this,cr).push(t)}toString(){return fe(this,cr).join("")}}cr=new WeakMap;class Si extends OT{constructor(e,t,s){super(),ji(this,hr),ji(this,Ua,""),ji(this,Os,void 0),ji(this,Ns,void 0),ji(this,Us,void 0),gs(this,Os,e),gs(this,Ns,t),gs(this,Us,s)}get attributeName(){return fe(this,Ns)}get attributeNamespace(){return fe(this,Us)}get element(){return fe(this,Os)}get value(){return fe(this,Ua)}set value(e){fe(this,Ua)!==e&&(gs(this,Ua,e),!fe(this,hr,Tn)||fe(this,hr,Tn).length===1?e==null?fe(this,Os).removeAttributeNS(fe(this,Us),fe(this,Ns)):fe(this,Os).setAttributeNS(fe(this,Us),fe(this,Ns),e):fe(this,Os).setAttributeNS(fe(this,Us),fe(this,Ns),fe(this,hr,Tn).toString()))}get booleanValue(){return fe(this,Os).hasAttributeNS(fe(this,Us),fe(this,Ns))}set booleanValue(e){if(!fe(this,hr,Tn)||fe(this,hr,Tn).length===1)this.value=e?"":null;else throw new DOMException("Value is not fully templatized")}}Ua=new WeakMap;Os=new WeakMap;Ns=new WeakMap;Us=new WeakMap;hr=new WeakSet;Tn=function(){return NT.get(this)};class sa extends OT{constructor(e,t){super(),ji(this,ad,void 0),ji(this,vi,void 0),gs(this,ad,e),gs(this,vi,t?[...t]:[new Text])}get replacementNodes(){return fe(this,vi)}get parentNode(){return fe(this,ad)}get nextSibling(){return fe(this,vi)[fe(this,vi).length-1].nextSibling}get previousSibling(){return fe(this,vi)[0].previousSibling}get value(){return fe(this,vi).map(e=>e.textContent).join("")}set value(e){this.replace(e)}replace(...e){const t=e.flat().flatMap(s=>s==null?[new Text]:s.forEach?[...s]:s.nodeType===qP?[...s.childNodes]:s.nodeType?[s]:[new Text(s)]);t.length||t.push(new Text),gs(this,vi,jP(fe(this,vi)[0].parentNode,fe(this,vi),t,this.nextSibling))}}ad=new WeakMap;vi=new WeakMap;class UT extends sa{constructor(e,t){const s=t.getAttribute("directive")||t.getAttribute("type");let r=t.getAttribute("expression")||t.getAttribute(s)||"";r.startsWith("{{")&&(r=r.trim().slice(2,-2).trim()),super(e),this.expression=r,this.template=t,this.directive=s}}function jP(i,e,t,s=null){let r=0,n,a,o,l=t.length,d=e.length;for(;r<l&&r<d&&e[r]==t[r];)r++;for(;r<l&&r<d&&t[l-1]==e[d-1];)s=t[--d,--l];if(r==d)for(;r<l;)i.insertBefore(t[r++],s);if(r==l)for(;r<d;)i.removeChild(e[r++]);else{for(n=e[r];r<l;)o=t[r++],a=n?n.nextSibling:s,n==o?n=a:r<l&&t[r]==a?(i.replaceChild(o,n),n=a):i.insertBefore(o,n);for(;n!=s;)a=n.nextSibling,i.removeChild(n),n=a}return t}const dv={string:i=>String(i)};class $T{constructor(e){this.template=e,this.state=void 0}}const Tr=new WeakMap,_r=new WeakMap,bf={partial:(i,e)=>{e[i.expression]=new $T(i.template)},if:(i,e)=>{var t;if(FT(i.expression,e))if(Tr.get(i)!==i.template){Tr.set(i,i.template);const s=new ec(i.template,e,fp);i.replace(s),_r.set(i,s)}else(t=_r.get(i))==null||t.update(e);else i.replace(""),Tr.delete(i),_r.delete(i)}},zP=Object.keys(bf),fp={processCallback(i,e,t){var s,r;if(t)for(const[n,a]of e){if(a instanceof UT){if(!a.directive){const l=zP.find(d=>a.template.hasAttribute(d));l&&(a.directive=l,a.expression=a.template.getAttribute(l))}(s=bf[a.directive])==null||s.call(bf,a,t);continue}let o=FT(n,t);if(o instanceof $T){Tr.get(a)!==o.template?(Tr.set(a,o.template),o=new ec(o.template,o.state,fp),a.value=o,_r.set(a,o)):(r=_r.get(a))==null||r.update(o.state);continue}o?(a instanceof Si&&a.attributeName.startsWith("aria-")&&(o=String(o)),a instanceof Si?typeof o=="boolean"?a.booleanValue=o:typeof o=="function"?a.element[a.attributeName]=o:a.value=o:(a.value=o,Tr.delete(a),_r.delete(a))):a instanceof Si?a.value=void 0:(a.value=void 0,Tr.delete(a),_r.delete(a))}}},uv={"!":i=>!i,"!!":i=>!!i,"==":(i,e)=>i==e,"!=":(i,e)=>i!=e,">":(i,e)=>i>e,">=":(i,e)=>i>=e,"<":(i,e)=>i<e,"<=":(i,e)=>i<=e,"??":(i,e)=>i??e,"|":(i,e)=>{var t;return(t=dv[e])==null?void 0:t.call(dv,i)}};function QP(i){return XP(i,{boolean:/true|false/,number:/-?\d+\.?\d*/,string:/(["'])((?:\\.|[^\\])*?)\1/,operator:/[!=><][=!]?|\?\?|\|/,ws:/\s+/,param:/[$a-z_][$\w]*/i}).filter(({type:e})=>e!=="ws")}function FT(i,e={}){var t,s,r,n,a,o,l;const d=QP(i);if(d.length===0||d.some(({type:u})=>!u))return ha(i);if(((t=d[0])==null?void 0:t.token)===">"){const u=e[(s=d[1])==null?void 0:s.token];if(!u)return ha(i);const c={...e};u.state=c;const h=d.slice(2);for(let f=0;f<h.length;f+=3){const m=(r=h[f])==null?void 0:r.token,p=(n=h[f+1])==null?void 0:n.token,g=(a=h[f+2])==null?void 0:a.token;m&&p==="="&&(c[m]=fa(g,e))}return u}if(d.length===1)return ul(d[0])?fa(d[0].token,e):ha(i);if(d.length===2){const u=(o=d[0])==null?void 0:o.token,c=uv[u];if(!c||!ul(d[1]))return ha(i);const h=fa(d[1].token,e);return c(h)}if(d.length===3){const u=(l=d[1])==null?void 0:l.token,c=uv[u];if(!c||!ul(d[0])||!ul(d[2]))return ha(i);const h=fa(d[0].token,e);if(u==="|")return c(h,d[2].token);const f=fa(d[2].token,e);return c(h,f)}}function ha(i){return console.warn(`Warning: invalid expression \`${i}\``),!1}function ul({type:i}){return["number","boolean","string","param"].includes(i)}function fa(i,e){const t=i[0],s=i.slice(-1);return i==="true"||i==="false"?i==="true":t===s&&["'",'"'].includes(t)?i.slice(1,-1):qv(i)?parseFloat(i):e[i]}function XP(i,e){let t,s,r;const n=[];for(;i;){r=null,t=i.length;for(const a in e)s=e[a].exec(i),s&&s.index<t&&(r={token:s[0],type:a,matches:s.slice(1)},t=s.index);t&&n.push({token:i.substr(0,t),type:void 0}),r&&n.push(r),i=i.substr(t+(r?r.token.length:0))}return n}var mp=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Tf=(i,e,t)=>(mp(i,e,"read from private field"),t?t.call(i):e.get(i)),ma=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Ar=(i,e,t,s)=>(mp(i,e,"write to private field"),e.set(i,t),t),Yc=(i,e,t)=>(mp(i,e,"access private method"),t),Hn,od,Gn,_f,BT,ld,Af;const jc={mediatargetlivewindow:"targetlivewindow",mediastreamtype:"streamtype"},HT=lt.createElement("template");HT.innerHTML=`
|
|
1542
1542
|
<style>
|
|
1543
1543
|
:host {
|
|
1544
1544
|
display: inline-block;
|
|
@@ -1919,7 +1919,7 @@ Schedule: ${l.map(p=>fi(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
|
|
|
1919
1919
|
<path d="M4.5 14.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Zm7.5 0a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Zm7.5 0a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Z"/>
|
|
1920
1920
|
</svg>
|
|
1921
1921
|
</slot>
|
|
1922
|
-
`}function mO(){return te("Settings")}class Sp extends ra{static get observedAttributes(){return[...super.observedAttributes,"target"]}connectedCallback(){super.connectedCallback(),this.setAttribute("aria-label",te("settings"))}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:Ut(this).querySelector("media-settings-menu")}}Sp.getSlotTemplateHTML=fO;Sp.getTooltipContentHTML=mO;k.customElements.get("media-settings-menu-button")||k.customElements.define("media-settings-menu-button",Sp);var Ip=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},r_=(i,e,t)=>(Ip(i,e,"read from private field"),t?t.call(i):e.get(i)),cl=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Ff=(i,e,t,s)=>(Ip(i,e,"write to private field"),e.set(i,t),t),hl=(i,e,t)=>(Ip(i,e,"access private method"),t),$a,mu,pd,Bf,gd,Hf;class pO extends ui{constructor(){super(...arguments),cl(this,pd),cl(this,gd),cl(this,$a,[]),cl(this,mu,void 0)}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_AUDIO_TRACK_LIST,_.MEDIA_AUDIO_TRACK_ENABLED,_.MEDIA_AUDIO_TRACK_UNAVAILABLE]}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_AUDIO_TRACK_ENABLED&&t!==s?this.value=s:e===_.MEDIA_AUDIO_TRACK_LIST&&t!==s&&(Ff(this,$a,eA(s??"")),hl(this,pd,Bf).call(this))}connectedCallback(){super.connectedCallback(),this.addEventListener("change",hl(this,gd,Hf))}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",hl(this,gd,Hf))}get anchorElement(){var e;return this.anchor!=="auto"?super.anchorElement:(e=Ut(this))==null?void 0:e.querySelector("media-audio-track-menu-button")}get mediaAudioTrackList(){return r_(this,$a)}set mediaAudioTrackList(e){Ff(this,$a,e),hl(this,pd,Bf).call(this)}get mediaAudioTrackEnabled(){var e;return(e=He(this,_.MEDIA_AUDIO_TRACK_ENABLED))!=null?e:""}set mediaAudioTrackEnabled(e){Ge(this,_.MEDIA_AUDIO_TRACK_ENABLED,e)}}$a=new WeakMap;mu=new WeakMap;pd=new WeakSet;Bf=function(){if(r_(this,mu)===JSON.stringify(this.mediaAudioTrackList))return;Ff(this,mu,JSON.stringify(this.mediaAudioTrackList));const i=this.mediaAudioTrackList;this.defaultSlot.textContent="",i.sort((e,t)=>e.id.localeCompare(t.id,void 0,{numeric:!0}));for(const e of i){const t=this.formatMenuItemText(e.label,e),s=Jn({type:"radio",text:t,value:`${e.id}`,checked:e.enabled});s.prepend(Cr(this,"checked-indicator")),this.defaultSlot.append(s)}};gd=new WeakSet;Hf=function(){if(this.value==null)return;const i=new k.CustomEvent(
|
|
1922
|
+
`}function mO(){return te("Settings")}class Sp extends ra{static get observedAttributes(){return[...super.observedAttributes,"target"]}connectedCallback(){super.connectedCallback(),this.setAttribute("aria-label",te("settings"))}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:Ut(this).querySelector("media-settings-menu")}}Sp.getSlotTemplateHTML=fO;Sp.getTooltipContentHTML=mO;k.customElements.get("media-settings-menu-button")||k.customElements.define("media-settings-menu-button",Sp);var Ip=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},r_=(i,e,t)=>(Ip(i,e,"read from private field"),t?t.call(i):e.get(i)),cl=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Ff=(i,e,t,s)=>(Ip(i,e,"write to private field"),e.set(i,t),t),hl=(i,e,t)=>(Ip(i,e,"access private method"),t),$a,mu,pd,Bf,gd,Hf;class pO extends ui{constructor(){super(...arguments),cl(this,pd),cl(this,gd),cl(this,$a,[]),cl(this,mu,void 0)}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_AUDIO_TRACK_LIST,_.MEDIA_AUDIO_TRACK_ENABLED,_.MEDIA_AUDIO_TRACK_UNAVAILABLE]}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_AUDIO_TRACK_ENABLED&&t!==s?this.value=s:e===_.MEDIA_AUDIO_TRACK_LIST&&t!==s&&(Ff(this,$a,eA(s??"")),hl(this,pd,Bf).call(this))}connectedCallback(){super.connectedCallback(),this.addEventListener("change",hl(this,gd,Hf))}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",hl(this,gd,Hf))}get anchorElement(){var e;return this.anchor!=="auto"?super.anchorElement:(e=Ut(this))==null?void 0:e.querySelector("media-audio-track-menu-button")}get mediaAudioTrackList(){return r_(this,$a)}set mediaAudioTrackList(e){Ff(this,$a,e),hl(this,pd,Bf).call(this)}get mediaAudioTrackEnabled(){var e;return(e=He(this,_.MEDIA_AUDIO_TRACK_ENABLED))!=null?e:""}set mediaAudioTrackEnabled(e){Ge(this,_.MEDIA_AUDIO_TRACK_ENABLED,e)}}$a=new WeakMap;mu=new WeakMap;pd=new WeakSet;Bf=function(){if(r_(this,mu)===JSON.stringify(this.mediaAudioTrackList))return;Ff(this,mu,JSON.stringify(this.mediaAudioTrackList));const i=this.mediaAudioTrackList;this.defaultSlot.textContent="",i.sort((e,t)=>e.id.localeCompare(t.id,void 0,{numeric:!0}));for(const e of i){const t=this.formatMenuItemText(e.label,e),s=Jn({type:"radio",text:t,value:`${e.id}`,checked:e.enabled});s.prepend(Cr(this,"checked-indicator")),this.defaultSlot.append(s)}};gd=new WeakSet;Hf=function(){if(this.value==null)return;const i=new k.CustomEvent(Q.MEDIA_AUDIO_TRACK_REQUEST,{composed:!0,bubbles:!0,detail:this.value});this.dispatchEvent(i)};k.customElements.get("media-audio-track-menu")||k.customElements.define("media-audio-track-menu",pO);const gO=`<svg aria-hidden="true" viewBox="0 0 24 24">
|
|
1923
1923
|
<path d="M11 17H9.5V7H11v10Zm-3-3H6.5v-4H8v4Zm6-5h-1.5v6H14V9Zm3 7h-1.5V8H17v8Z"/>
|
|
1924
1924
|
<path d="M22 12c0 5.523-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2s10 4.477 10 10Zm-2 0a8 8 0 1 0-16 0 8 8 0 0 0 16 0Z"/>
|
|
1925
1925
|
</svg>`;function vO(){return`
|
|
@@ -1935,7 +1935,7 @@ Schedule: ${l.map(p=>fi(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
|
|
|
1935
1935
|
</svg>`;function _O(i){return`
|
|
1936
1936
|
${ui.getTemplateHTML(i)}
|
|
1937
1937
|
<slot name="captions-indicator" hidden>${TO}</slot>
|
|
1938
|
-
`}class n_ extends ui{constructor(){super(...arguments),Qc(this,vd),Qc(this,Ed),Qc(this,pu,void 0)}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_SUBTITLES_LIST,_.MEDIA_SUBTITLES_SHOWING]}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_SUBTITLES_LIST&&t!==s?fl(this,vd,Gf).call(this):e===_.MEDIA_SUBTITLES_SHOWING&&t!==s&&(this.value=s||"",fl(this,vd,Gf).call(this))}connectedCallback(){super.connectedCallback(),this.addEventListener("change",fl(this,Ed,Kf))}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",fl(this,Ed,Kf))}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:Ut(this).querySelector("media-captions-menu-button")}get mediaSubtitlesList(){return hv(this,_.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){fv(this,_.MEDIA_SUBTITLES_LIST,e)}get mediaSubtitlesShowing(){return hv(this,_.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){fv(this,_.MEDIA_SUBTITLES_SHOWING,e)}}pu=new WeakMap;vd=new WeakSet;Gf=function(){var i;const e=yO(this,pu)!==JSON.stringify(this.mediaSubtitlesList),t=this.value!==this.getAttribute(_.MEDIA_SUBTITLES_SHOWING);if(!e&&!t)return;bO(this,pu,JSON.stringify(this.mediaSubtitlesList)),this.defaultSlot.textContent="";const s=!this.value,r=Jn({type:"radio",text:this.formatMenuItemText(te("Off")),value:"off",checked:s});r.prepend(Cr(this,"checked-indicator")),this.defaultSlot.append(r);const n=this.mediaSubtitlesList;for(const a of n){const o=Jn({type:"radio",text:this.formatMenuItemText(a.label,a),value:lh(a),checked:this.value==lh(a)});o.prepend(Cr(this,"checked-indicator")),((i=a.kind)!=null?i:"subs")==="captions"&&o.append(Cr(this,"captions-indicator")),this.defaultSlot.append(o)}};Ed=new WeakSet;Kf=function(){const i=this.mediaSubtitlesShowing,e=this.getAttribute(_.MEDIA_SUBTITLES_SHOWING),t=this.value!==e;if(i?.length&&t&&this.dispatchEvent(new k.CustomEvent(
|
|
1938
|
+
`}class n_ extends ui{constructor(){super(...arguments),Qc(this,vd),Qc(this,Ed),Qc(this,pu,void 0)}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_SUBTITLES_LIST,_.MEDIA_SUBTITLES_SHOWING]}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_SUBTITLES_LIST&&t!==s?fl(this,vd,Gf).call(this):e===_.MEDIA_SUBTITLES_SHOWING&&t!==s&&(this.value=s||"",fl(this,vd,Gf).call(this))}connectedCallback(){super.connectedCallback(),this.addEventListener("change",fl(this,Ed,Kf))}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",fl(this,Ed,Kf))}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:Ut(this).querySelector("media-captions-menu-button")}get mediaSubtitlesList(){return hv(this,_.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){fv(this,_.MEDIA_SUBTITLES_LIST,e)}get mediaSubtitlesShowing(){return hv(this,_.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){fv(this,_.MEDIA_SUBTITLES_SHOWING,e)}}pu=new WeakMap;vd=new WeakSet;Gf=function(){var i;const e=yO(this,pu)!==JSON.stringify(this.mediaSubtitlesList),t=this.value!==this.getAttribute(_.MEDIA_SUBTITLES_SHOWING);if(!e&&!t)return;bO(this,pu,JSON.stringify(this.mediaSubtitlesList)),this.defaultSlot.textContent="";const s=!this.value,r=Jn({type:"radio",text:this.formatMenuItemText(te("Off")),value:"off",checked:s});r.prepend(Cr(this,"checked-indicator")),this.defaultSlot.append(r);const n=this.mediaSubtitlesList;for(const a of n){const o=Jn({type:"radio",text:this.formatMenuItemText(a.label,a),value:lh(a),checked:this.value==lh(a)});o.prepend(Cr(this,"checked-indicator")),((i=a.kind)!=null?i:"subs")==="captions"&&o.append(Cr(this,"captions-indicator")),this.defaultSlot.append(o)}};Ed=new WeakSet;Kf=function(){const i=this.mediaSubtitlesShowing,e=this.getAttribute(_.MEDIA_SUBTITLES_SHOWING),t=this.value!==e;if(i?.length&&t&&this.dispatchEvent(new k.CustomEvent(Q.MEDIA_DISABLE_SUBTITLES_REQUEST,{composed:!0,bubbles:!0,detail:i})),!this.value||!t)return;const s=new k.CustomEvent(Q.MEDIA_SHOW_SUBTITLES_REQUEST,{composed:!0,bubbles:!0,detail:this.value});this.dispatchEvent(s)};n_.getTemplateHTML=_O;const hv=(i,e)=>{const t=i.getAttribute(e);return t?Su(t):[]},fv=(i,e,t)=>{if(!t?.length){i.removeAttribute(e);return}const s=ao(t);i.getAttribute(e)!==s&&i.setAttribute(e,s)};k.customElements.get("media-captions-menu")||k.customElements.define("media-captions-menu",n_);const AO=`<svg aria-hidden="true" viewBox="0 0 26 24">
|
|
1939
1939
|
<path d="M22.83 5.68a2.58 2.58 0 0 0-2.3-2.5c-3.62-.24-11.44-.24-15.06 0a2.58 2.58 0 0 0-2.3 2.5c-.23 4.21-.23 8.43 0 12.64a2.58 2.58 0 0 0 2.3 2.5c3.62.24 11.44.24 15.06 0a2.58 2.58 0 0 0 2.3-2.5c.23-4.21.23-8.43 0-12.64Zm-11.39 9.45a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.92 3.92 0 0 1 .92-2.77 3.18 3.18 0 0 1 2.43-1 2.94 2.94 0 0 1 2.13.78c.364.359.62.813.74 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.17 1.61 1.61 0 0 0-1.29.58 2.79 2.79 0 0 0-.5 1.89 3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.48 1.48 0 0 0 1-.37 2.1 2.1 0 0 0 .59-1.14l1.4.44a3.23 3.23 0 0 1-1.07 1.69Zm7.22 0a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.88 3.88 0 0 1 .93-2.77 3.14 3.14 0 0 1 2.42-1 3 3 0 0 1 2.16.82 2.8 2.8 0 0 1 .73 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.21 1.61 1.61 0 0 0-1.29.58A2.79 2.79 0 0 0 15 12a3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.44 1.44 0 0 0 1-.37 2.1 2.1 0 0 0 .6-1.15l1.4.44a3.17 3.17 0 0 1-1.1 1.7Z"/>
|
|
1940
1940
|
</svg>`,SO=`<svg aria-hidden="true" viewBox="0 0 26 24">
|
|
1941
1941
|
<path d="M17.73 14.09a1.4 1.4 0 0 1-1 .37 1.579 1.579 0 0 1-1.27-.58A3 3 0 0 1 15 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34A2.89 2.89 0 0 0 19 9.07a3 3 0 0 0-2.14-.78 3.14 3.14 0 0 0-2.42 1 3.91 3.91 0 0 0-.93 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.17 3.17 0 0 0 1.07-1.74l-1.4-.45c-.083.43-.3.822-.62 1.12Zm-7.22 0a1.43 1.43 0 0 1-1 .37 1.58 1.58 0 0 1-1.27-.58A3 3 0 0 1 7.76 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34a2.81 2.81 0 0 0-.74-1.32 2.94 2.94 0 0 0-2.13-.78 3.18 3.18 0 0 0-2.43 1 4 4 0 0 0-.92 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.23 3.23 0 0 0 1.07-1.74l-1.4-.45a2.06 2.06 0 0 1-.6 1.07Zm12.32-8.41a2.59 2.59 0 0 0-2.3-2.51C18.72 3.05 15.86 3 13 3c-2.86 0-5.72.05-7.53.17a2.59 2.59 0 0 0-2.3 2.51c-.23 4.207-.23 8.423 0 12.63a2.57 2.57 0 0 0 2.3 2.5c1.81.13 4.67.19 7.53.19 2.86 0 5.72-.06 7.53-.19a2.57 2.57 0 0 0 2.3-2.5c.23-4.207.23-8.423 0-12.63Zm-1.49 12.53a1.11 1.11 0 0 1-.91 1.11c-1.67.11-4.45.18-7.43.18-2.98 0-5.76-.07-7.43-.18a1.11 1.11 0 0 1-.91-1.11c-.21-4.14-.21-8.29 0-12.43a1.11 1.11 0 0 1 .91-1.11C7.24 4.56 10 4.49 13 4.49s5.76.07 7.43.18a1.11 1.11 0 0 1 .91 1.11c.21 4.14.21 8.29 0 12.43Z"/>
|
|
@@ -1959,7 +1959,7 @@ Schedule: ${l.map(p=>fi(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
|
|
|
1959
1959
|
<slot name="on">${AO}</slot>
|
|
1960
1960
|
<slot name="off">${SO}</slot>
|
|
1961
1961
|
</slot>
|
|
1962
|
-
`}function xO(){return te("Captions")}const mv=i=>{i.setAttribute("data-captions-enabled",hE(i).toString())},pv=i=>{i.setAttribute("aria-label",te("closed captions"))};class Rp extends ra{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_SUBTITLES_LIST,_.MEDIA_SUBTITLES_SHOWING,_.MEDIA_LANG]}connectedCallback(){super.connectedCallback(),pv(this),mv(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_SUBTITLES_SHOWING?mv(this):e===_.MEDIA_LANG&&pv(this)}get invokeTargetElement(){var e;return this.invokeTarget!=null?super.invokeTargetElement:(e=Ut(this))==null?void 0:e.querySelector("media-captions-menu")}get mediaSubtitlesList(){return gv(this,_.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){vv(this,_.MEDIA_SUBTITLES_LIST,e)}get mediaSubtitlesShowing(){return gv(this,_.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){vv(this,_.MEDIA_SUBTITLES_SHOWING,e)}}Rp.getSlotTemplateHTML=IO;Rp.getTooltipContentHTML=xO;const gv=(i,e)=>{const t=i.getAttribute(e);return t?Su(t):[]},vv=(i,e,t)=>{if(!t?.length){i.removeAttribute(e);return}const s=ao(t);i.getAttribute(e)!==s&&i.setAttribute(e,s)};k.customElements.get("media-captions-menu-button")||k.customElements.define("media-captions-menu-button",Rp);var a_=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},_n=(i,e,t)=>(a_(i,e,"read from private field"),t?t.call(i):e.get(i)),Xc=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Zr=(i,e,t)=>(a_(i,e,"access private method"),t),Hs,An,Fa,yd,Vf;const Zc={RATES:"rates"};class LO extends ui{constructor(){super(),Xc(this,An),Xc(this,yd),Xc(this,Hs,new am(this,Zc.RATES,{defaultValue:GE})),Zr(this,An,Fa).call(this)}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PLAYBACK_RATE,Zc.RATES]}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_PLAYBACK_RATE&&t!=s?(this.value=s,Zr(this,An,Fa).call(this)):e===Zc.RATES&&t!=s&&(_n(this,Hs).value=s,Zr(this,An,Fa).call(this))}connectedCallback(){super.connectedCallback(),this.addEventListener("change",Zr(this,yd,Vf))}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",Zr(this,yd,Vf))}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:Ut(this).querySelector("media-playback-rate-menu-button")}get rates(){return _n(this,Hs)}set rates(e){e?Array.isArray(e)?_n(this,Hs).value=e.join(" "):typeof e=="string"&&(_n(this,Hs).value=e):_n(this,Hs).value="",Zr(this,An,Fa).call(this)}get mediaPlaybackRate(){return Be(this,_.MEDIA_PLAYBACK_RATE,Dn)}set mediaPlaybackRate(e){Xe(this,_.MEDIA_PLAYBACK_RATE,e)}}Hs=new WeakMap;An=new WeakSet;Fa=function(){this.defaultSlot.textContent="";const i=this.mediaPlaybackRate,e=new Set(Array.from(_n(this,Hs)).map(s=>Number(s)));i>0&&!e.has(i)&&e.add(i);const t=Array.from(e).sort((s,r)=>s-r);for(const s of t){const r=Jn({type:"radio",text:this.formatMenuItemText(`${s}x`,s),value:s.toString(),checked:i===s});r.prepend(Cr(this,"checked-indicator")),this.defaultSlot.append(r)}};yd=new WeakSet;Vf=function(){if(!this.value)return;const i=new k.CustomEvent(
|
|
1962
|
+
`}function xO(){return te("Captions")}const mv=i=>{i.setAttribute("data-captions-enabled",hE(i).toString())},pv=i=>{i.setAttribute("aria-label",te("closed captions"))};class Rp extends ra{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_SUBTITLES_LIST,_.MEDIA_SUBTITLES_SHOWING,_.MEDIA_LANG]}connectedCallback(){super.connectedCallback(),pv(this),mv(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_SUBTITLES_SHOWING?mv(this):e===_.MEDIA_LANG&&pv(this)}get invokeTargetElement(){var e;return this.invokeTarget!=null?super.invokeTargetElement:(e=Ut(this))==null?void 0:e.querySelector("media-captions-menu")}get mediaSubtitlesList(){return gv(this,_.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){vv(this,_.MEDIA_SUBTITLES_LIST,e)}get mediaSubtitlesShowing(){return gv(this,_.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){vv(this,_.MEDIA_SUBTITLES_SHOWING,e)}}Rp.getSlotTemplateHTML=IO;Rp.getTooltipContentHTML=xO;const gv=(i,e)=>{const t=i.getAttribute(e);return t?Su(t):[]},vv=(i,e,t)=>{if(!t?.length){i.removeAttribute(e);return}const s=ao(t);i.getAttribute(e)!==s&&i.setAttribute(e,s)};k.customElements.get("media-captions-menu-button")||k.customElements.define("media-captions-menu-button",Rp);var a_=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},_n=(i,e,t)=>(a_(i,e,"read from private field"),t?t.call(i):e.get(i)),Xc=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Zr=(i,e,t)=>(a_(i,e,"access private method"),t),Hs,An,Fa,yd,Vf;const Zc={RATES:"rates"};class LO extends ui{constructor(){super(),Xc(this,An),Xc(this,yd),Xc(this,Hs,new am(this,Zc.RATES,{defaultValue:GE})),Zr(this,An,Fa).call(this)}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PLAYBACK_RATE,Zc.RATES]}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_PLAYBACK_RATE&&t!=s?(this.value=s,Zr(this,An,Fa).call(this)):e===Zc.RATES&&t!=s&&(_n(this,Hs).value=s,Zr(this,An,Fa).call(this))}connectedCallback(){super.connectedCallback(),this.addEventListener("change",Zr(this,yd,Vf))}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",Zr(this,yd,Vf))}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:Ut(this).querySelector("media-playback-rate-menu-button")}get rates(){return _n(this,Hs)}set rates(e){e?Array.isArray(e)?_n(this,Hs).value=e.join(" "):typeof e=="string"&&(_n(this,Hs).value=e):_n(this,Hs).value="",Zr(this,An,Fa).call(this)}get mediaPlaybackRate(){return Be(this,_.MEDIA_PLAYBACK_RATE,Dn)}set mediaPlaybackRate(e){Xe(this,_.MEDIA_PLAYBACK_RATE,e)}}Hs=new WeakMap;An=new WeakSet;Fa=function(){this.defaultSlot.textContent="";const i=this.mediaPlaybackRate,e=new Set(Array.from(_n(this,Hs)).map(s=>Number(s)));i>0&&!e.has(i)&&e.add(i);const t=Array.from(e).sort((s,r)=>s-r);for(const s of t){const r=Jn({type:"radio",text:this.formatMenuItemText(`${s}x`,s),value:s.toString(),checked:i===s});r.prepend(Cr(this,"checked-indicator")),this.defaultSlot.append(r)}};yd=new WeakSet;Vf=function(){if(!this.value)return;const i=new k.CustomEvent(Q.MEDIA_PLAYBACK_RATE_REQUEST,{composed:!0,bubbles:!0,detail:this.value});this.dispatchEvent(i)};k.customElements.get("media-playback-rate-menu")||k.customElements.define("media-playback-rate-menu",LO);const bd=1;function RO(i){return`
|
|
1963
1963
|
<style>
|
|
1964
1964
|
:host {
|
|
1965
1965
|
min-width: 5ch;
|
|
@@ -1975,7 +1975,7 @@ Schedule: ${l.map(p=>fi(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
|
|
|
1975
1975
|
}
|
|
1976
1976
|
</style>
|
|
1977
1977
|
<slot name="icon">${i.mediaplaybackrate||bd}x</slot>
|
|
1978
|
-
`}function kO(){return te("Playback rate")}class kp extends ra{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PLAYBACK_RATE]}constructor(){var e;super(),this.container=this.shadowRoot.querySelector('slot[name="icon"]'),this.container.innerHTML=`${(e=this.mediaPlaybackRate)!=null?e:bd}x`}attributeChangedCallback(e,t,s){if(super.attributeChangedCallback(e,t,s),e===_.MEDIA_PLAYBACK_RATE){const r=s?+s:Number.NaN,n=Number.isNaN(r)?bd:r;this.container.innerHTML=`${n}x`,this.setAttribute("aria-label",te("Playback rate {playbackRate}",{playbackRate:n}))}}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:Ut(this).querySelector("media-playback-rate-menu")}get mediaPlaybackRate(){return Be(this,_.MEDIA_PLAYBACK_RATE,bd)}set mediaPlaybackRate(e){Xe(this,_.MEDIA_PLAYBACK_RATE,e)}}kp.getSlotTemplateHTML=RO;kp.getTooltipContentHTML=kO;k.customElements.get("media-playback-rate-menu-button")||k.customElements.define("media-playback-rate-menu-button",kp);var Dp=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Ba=(i,e,t)=>(Dp(i,e,"read from private field"),t?t.call(i):e.get(i)),ml=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Ev=(i,e,t,s)=>(Dp(i,e,"write to private field"),e.set(i,t),t),Jr=(i,e,t)=>(Dp(i,e,"access private method"),t),Ha,wn,Sn,Ga,Td,Wf;class DO extends ui{constructor(){super(...arguments),ml(this,Sn),ml(this,Td),ml(this,Ha,[]),ml(this,wn,{})}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_RENDITION_LIST,_.MEDIA_RENDITION_SELECTED,_.MEDIA_RENDITION_UNAVAILABLE,_.MEDIA_HEIGHT]}static formatMenuItemText(e,t){return super.formatMenuItemText(e,t)}static formatRendition(e,{showBitrate:t=!1}={}){const s=`${Math.min(e.width,e.height)}p`;if(t&&e.bitrate){const r=e.bitrate/1e6,n=`${r.toFixed(r<1?1:0)} Mbps`;return`${s} (${n})`}return this.formatMenuItemText(s,e)}static compareRendition(e,t){var s,r;return t.height===e.height?((s=t.bitrate)!=null?s:0)-((r=e.bitrate)!=null?r:0):t.height-e.height}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_RENDITION_SELECTED&&t!==s?(this.value=s??"auto",Jr(this,Sn,Ga).call(this)):e===_.MEDIA_RENDITION_LIST&&t!==s?(Ev(this,Ha,Q_(s)),Jr(this,Sn,Ga).call(this)):e===_.MEDIA_HEIGHT&&t!==s&&Jr(this,Sn,Ga).call(this)}connectedCallback(){super.connectedCallback(),this.addEventListener("change",Jr(this,Td,Wf))}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",Jr(this,Td,Wf))}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:Ut(this).querySelector("media-rendition-menu-button")}get mediaRenditionList(){return Ba(this,Ha)}set mediaRenditionList(e){Ev(this,Ha,e),Jr(this,Sn,Ga).call(this)}get mediaRenditionSelected(){return He(this,_.MEDIA_RENDITION_SELECTED)}set mediaRenditionSelected(e){Ge(this,_.MEDIA_RENDITION_SELECTED,e)}get mediaHeight(){return Be(this,_.MEDIA_HEIGHT)}set mediaHeight(e){Xe(this,_.MEDIA_HEIGHT,e)}compareRendition(e,t){return this.constructor.compareRendition(e,t)}formatMenuItemText(e,t){return this.constructor.formatMenuItemText(e,t)}formatRendition(e,t){return this.constructor.formatRendition(e,t)}showRenditionBitrate(e){return this.mediaRenditionList.some(t=>t!==e&&t.height===e.height&&t.bitrate!==e.bitrate)}}Ha=new WeakMap;wn=new WeakMap;Sn=new WeakSet;Ga=function(){if(Ba(this,wn).mediaRenditionList===JSON.stringify(this.mediaRenditionList)&&Ba(this,wn).mediaHeight===this.mediaHeight)return;Ba(this,wn).mediaRenditionList=JSON.stringify(this.mediaRenditionList),Ba(this,wn).mediaHeight=this.mediaHeight;const i=this.mediaRenditionList.sort(this.compareRendition.bind(this)),e=i.find(a=>a.id===this.mediaRenditionSelected);for(const a of i)a.selected=a===e;this.defaultSlot.textContent="";const t=!this.mediaRenditionSelected;for(const a of i){const o=this.formatRendition(a,{showBitrate:this.showRenditionBitrate(a)}),l=Jn({type:"radio",text:o,value:`${a.id}`,checked:a.selected&&!t});l.prepend(Cr(this,"checked-indicator")),this.defaultSlot.append(l)}const s=e&&this.showRenditionBitrate(e),r=t?e?this.formatMenuItemText(`${te("Auto")} • ${this.formatRendition(e,{showBitrate:s})}`,e):this.formatMenuItemText(`${te("Auto")} (${this.mediaHeight}p)`):this.formatMenuItemText(te("Auto")),n=Jn({type:"radio",text:r,value:"auto",checked:t});n.dataset.description=r,n.prepend(Cr(this,"checked-indicator")),this.defaultSlot.append(n)};Td=new WeakSet;Wf=function(){if(this.value==null)return;const i=new k.CustomEvent(
|
|
1978
|
+
`}function kO(){return te("Playback rate")}class kp extends ra{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PLAYBACK_RATE]}constructor(){var e;super(),this.container=this.shadowRoot.querySelector('slot[name="icon"]'),this.container.innerHTML=`${(e=this.mediaPlaybackRate)!=null?e:bd}x`}attributeChangedCallback(e,t,s){if(super.attributeChangedCallback(e,t,s),e===_.MEDIA_PLAYBACK_RATE){const r=s?+s:Number.NaN,n=Number.isNaN(r)?bd:r;this.container.innerHTML=`${n}x`,this.setAttribute("aria-label",te("Playback rate {playbackRate}",{playbackRate:n}))}}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:Ut(this).querySelector("media-playback-rate-menu")}get mediaPlaybackRate(){return Be(this,_.MEDIA_PLAYBACK_RATE,bd)}set mediaPlaybackRate(e){Xe(this,_.MEDIA_PLAYBACK_RATE,e)}}kp.getSlotTemplateHTML=RO;kp.getTooltipContentHTML=kO;k.customElements.get("media-playback-rate-menu-button")||k.customElements.define("media-playback-rate-menu-button",kp);var Dp=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Ba=(i,e,t)=>(Dp(i,e,"read from private field"),t?t.call(i):e.get(i)),ml=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Ev=(i,e,t,s)=>(Dp(i,e,"write to private field"),e.set(i,t),t),Jr=(i,e,t)=>(Dp(i,e,"access private method"),t),Ha,wn,Sn,Ga,Td,Wf;class DO extends ui{constructor(){super(...arguments),ml(this,Sn),ml(this,Td),ml(this,Ha,[]),ml(this,wn,{})}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_RENDITION_LIST,_.MEDIA_RENDITION_SELECTED,_.MEDIA_RENDITION_UNAVAILABLE,_.MEDIA_HEIGHT]}static formatMenuItemText(e,t){return super.formatMenuItemText(e,t)}static formatRendition(e,{showBitrate:t=!1}={}){const s=`${Math.min(e.width,e.height)}p`;if(t&&e.bitrate){const r=e.bitrate/1e6,n=`${r.toFixed(r<1?1:0)} Mbps`;return`${s} (${n})`}return this.formatMenuItemText(s,e)}static compareRendition(e,t){var s,r;return t.height===e.height?((s=t.bitrate)!=null?s:0)-((r=e.bitrate)!=null?r:0):t.height-e.height}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_RENDITION_SELECTED&&t!==s?(this.value=s??"auto",Jr(this,Sn,Ga).call(this)):e===_.MEDIA_RENDITION_LIST&&t!==s?(Ev(this,Ha,Q_(s)),Jr(this,Sn,Ga).call(this)):e===_.MEDIA_HEIGHT&&t!==s&&Jr(this,Sn,Ga).call(this)}connectedCallback(){super.connectedCallback(),this.addEventListener("change",Jr(this,Td,Wf))}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",Jr(this,Td,Wf))}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:Ut(this).querySelector("media-rendition-menu-button")}get mediaRenditionList(){return Ba(this,Ha)}set mediaRenditionList(e){Ev(this,Ha,e),Jr(this,Sn,Ga).call(this)}get mediaRenditionSelected(){return He(this,_.MEDIA_RENDITION_SELECTED)}set mediaRenditionSelected(e){Ge(this,_.MEDIA_RENDITION_SELECTED,e)}get mediaHeight(){return Be(this,_.MEDIA_HEIGHT)}set mediaHeight(e){Xe(this,_.MEDIA_HEIGHT,e)}compareRendition(e,t){return this.constructor.compareRendition(e,t)}formatMenuItemText(e,t){return this.constructor.formatMenuItemText(e,t)}formatRendition(e,t){return this.constructor.formatRendition(e,t)}showRenditionBitrate(e){return this.mediaRenditionList.some(t=>t!==e&&t.height===e.height&&t.bitrate!==e.bitrate)}}Ha=new WeakMap;wn=new WeakMap;Sn=new WeakSet;Ga=function(){if(Ba(this,wn).mediaRenditionList===JSON.stringify(this.mediaRenditionList)&&Ba(this,wn).mediaHeight===this.mediaHeight)return;Ba(this,wn).mediaRenditionList=JSON.stringify(this.mediaRenditionList),Ba(this,wn).mediaHeight=this.mediaHeight;const i=this.mediaRenditionList.sort(this.compareRendition.bind(this)),e=i.find(a=>a.id===this.mediaRenditionSelected);for(const a of i)a.selected=a===e;this.defaultSlot.textContent="";const t=!this.mediaRenditionSelected;for(const a of i){const o=this.formatRendition(a,{showBitrate:this.showRenditionBitrate(a)}),l=Jn({type:"radio",text:o,value:`${a.id}`,checked:a.selected&&!t});l.prepend(Cr(this,"checked-indicator")),this.defaultSlot.append(l)}const s=e&&this.showRenditionBitrate(e),r=t?e?this.formatMenuItemText(`${te("Auto")} • ${this.formatRendition(e,{showBitrate:s})}`,e):this.formatMenuItemText(`${te("Auto")} (${this.mediaHeight}p)`):this.formatMenuItemText(te("Auto")),n=Jn({type:"radio",text:r,value:"auto",checked:t});n.dataset.description=r,n.prepend(Cr(this,"checked-indicator")),this.defaultSlot.append(n)};Td=new WeakSet;Wf=function(){if(this.value==null)return;const i=new k.CustomEvent(Q.MEDIA_RENDITION_REQUEST,{composed:!0,bubbles:!0,detail:this.value});this.dispatchEvent(i)};k.customElements.get("media-rendition-menu")||k.customElements.define("media-rendition-menu",DO);const CO=`<svg aria-hidden="true" viewBox="0 0 24 24">
|
|
1979
1979
|
<path d="M13.5 2.5h2v6h-2v-2h-11v-2h11v-2Zm4 2h4v2h-4v-2Zm-12 4h2v6h-2v-2h-3v-2h3v-2Zm4 2h12v2h-12v-2Zm1 4h2v6h-2v-2h-8v-2h8v-2Zm4 2h7v2h-7v-2Z" />
|
|
1980
1980
|
</svg>`;function wO(){return`
|
|
1981
1981
|
<style>
|
|
@@ -2011,7 +2011,7 @@ Schedule: ${l.map(p=>fi(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
|
|
|
2011
2011
|
min-height: var(--media-control-height, 24px);
|
|
2012
2012
|
}
|
|
2013
2013
|
</style>
|
|
2014
|
-
`}class Pp extends Zs{}Pp.shadowRootOptions={mode:"open"};Pp.getTemplateHTML=OO;k.customElements.get("media-context-menu-item")||k.customElements.define("media-context-menu-item",Pp);var c_=i=>{throw TypeError(i)},Op=(i,e,t)=>e.has(i)||c_("Cannot "+t),De=(i,e,t)=>(Op(i,e,"read from private field"),t?t.call(i):e.get(i)),Ti=(i,e,t)=>e.has(i)?c_("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),is=(i,e,t,s)=>(Op(i,e,"write to private field"),e.set(i,t),t),at=(i,e,t)=>(Op(i,e,"access private method"),t),rc=class{addEventListener(){}removeEventListener(){}dispatchEvent(i){return!0}};if(typeof DocumentFragment>"u"){class i extends rc{}globalThis.DocumentFragment=i}var Np=class extends rc{},NO=class extends rc{},UO={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(Np)}},Id,$O=class{constructor(e,t={}){Ti(this,Id),is(this,Id,t?.detail)}get detail(){return De(this,Id)}initCustomEvent(){}};Id=new WeakMap;function FO(i,e){return new Np}var h_={document:{createElement:FO},DocumentFragment,customElements:UO,CustomEvent:$O,EventTarget:rc,HTMLElement:Np,HTMLVideoElement:NO},f_=typeof window>"u"||typeof globalThis.customElements>"u",zi=f_?h_:globalThis,Eu=f_?h_.document:globalThis.document;function BO(i){let e="";return Object.entries(i).forEach(([t,s])=>{s!=null&&(e+=`${jf(t)}: ${s}; `)}),e?e.trim():void 0}function jf(i){return i.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function m_(i){return i.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase())}function qt(i){if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}function p_(i){let e=HO(i).toString();return e?"?"+e:""}function HO(i){let e={};for(let t in i)i[t]!=null&&(e[t]=i[t]);return new URLSearchParams(e)}var g_=(i,e)=>!i||!e?!1:i.contains(e)?!0:g_(i,e.getRootNode().host),v_="mux.com",GO=()=>{try{return"3.10.2"}catch{}return"UNKNOWN"},KO=GO(),E_=()=>KO,VO=(i,{token:e,customDomain:t=v_,thumbnailTime:s,programTime:r}={})=>{var n;let a=e==null?s:void 0,{aud:o}=(n=Bn(e))!=null?n:{};if(!(e&&o!=="t"))return`https://image.${t}/${i}/thumbnail.webp${p_({token:e,time:a,program_time:r})}`},WO=(i,{token:e,customDomain:t=v_,programStartTime:s,programEndTime:r}={})=>{var n;let{aud:a}=(n=Bn(e))!=null?n:{};if(!(e&&a!=="s"))return`https://image.${t}/${i}/storyboard.vtt${p_({token:e,format:"webp",program_start_time:s,program_end_time:r})}`},Up=i=>{if(i){if([ke.LIVE,ke.ON_DEMAND].includes(i))return i;if(i!=null&&i.includes("live"))return ke.LIVE}},qO={crossorigin:"crossOrigin",playsinline:"playsInline"};function YO(i){var e;return(e=qO[i])!=null?e:m_(i)}var In,xn,Ot,jO=class{constructor(e,t){Ti(this,In),Ti(this,xn),Ti(this,Ot,[]),is(this,In,e),is(this,xn,t)}[Symbol.iterator](){return De(this,Ot).values()}get length(){return De(this,Ot).length}get value(){var e;return(e=De(this,Ot).join(" "))!=null?e:""}set value(e){var t;e!==this.value&&(is(this,Ot,[]),this.add(...(t=e?.split(" "))!=null?t:[]))}toString(){return this.value}item(e){return De(this,Ot)[e]}values(){return De(this,Ot).values()}keys(){return De(this,Ot).keys()}forEach(e){De(this,Ot).forEach(e)}add(...e){var t,s;e.forEach(r=>{this.contains(r)||De(this,Ot).push(r)}),!(this.value===""&&!((t=De(this,In))!=null&&t.hasAttribute(`${De(this,xn)}`)))&&((s=De(this,In))==null||s.setAttribute(`${De(this,xn)}`,`${this.value}`))}remove(...e){var t;e.forEach(s=>{De(this,Ot).splice(De(this,Ot).indexOf(s),1)}),(t=De(this,In))==null||t.setAttribute(`${De(this,xn)}`,`${this.value}`)}contains(e){return De(this,Ot).includes(e)}toggle(e,t){return typeof t<"u"?t?(this.add(e),!0):(this.remove(e),!1):this.contains(e)?(this.remove(e),!1):(this.add(e),!0)}replace(e,t){this.remove(e),this.add(t)}};In=new WeakMap,xn=new WeakMap,Ot=new WeakMap;var y_=`[mux-player ${E_()}]`;function ps(...i){console.warn(y_,...i)}function ai(...i){console.error(y_,...i)}function b_(i){var e;let t=(e=i.message)!=null?e:"";i.context&&(t+=` ${i.context}`),i.file&&(t+=` ${
|
|
2014
|
+
`}class Pp extends Zs{}Pp.shadowRootOptions={mode:"open"};Pp.getTemplateHTML=OO;k.customElements.get("media-context-menu-item")||k.customElements.define("media-context-menu-item",Pp);var c_=i=>{throw TypeError(i)},Op=(i,e,t)=>e.has(i)||c_("Cannot "+t),De=(i,e,t)=>(Op(i,e,"read from private field"),t?t.call(i):e.get(i)),Ti=(i,e,t)=>e.has(i)?c_("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),is=(i,e,t,s)=>(Op(i,e,"write to private field"),e.set(i,t),t),at=(i,e,t)=>(Op(i,e,"access private method"),t),rc=class{addEventListener(){}removeEventListener(){}dispatchEvent(i){return!0}};if(typeof DocumentFragment>"u"){class i extends rc{}globalThis.DocumentFragment=i}var Np=class extends rc{},NO=class extends rc{},UO={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(Np)}},Id,$O=class{constructor(e,t={}){Ti(this,Id),is(this,Id,t?.detail)}get detail(){return De(this,Id)}initCustomEvent(){}};Id=new WeakMap;function FO(i,e){return new Np}var h_={document:{createElement:FO},DocumentFragment,customElements:UO,CustomEvent:$O,EventTarget:rc,HTMLElement:Np,HTMLVideoElement:NO},f_=typeof window>"u"||typeof globalThis.customElements>"u",zi=f_?h_:globalThis,Eu=f_?h_.document:globalThis.document;function BO(i){let e="";return Object.entries(i).forEach(([t,s])=>{s!=null&&(e+=`${jf(t)}: ${s}; `)}),e?e.trim():void 0}function jf(i){return i.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function m_(i){return i.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase())}function qt(i){if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}function p_(i){let e=HO(i).toString();return e?"?"+e:""}function HO(i){let e={};for(let t in i)i[t]!=null&&(e[t]=i[t]);return new URLSearchParams(e)}var g_=(i,e)=>!i||!e?!1:i.contains(e)?!0:g_(i,e.getRootNode().host),v_="mux.com",GO=()=>{try{return"3.10.2"}catch{}return"UNKNOWN"},KO=GO(),E_=()=>KO,VO=(i,{token:e,customDomain:t=v_,thumbnailTime:s,programTime:r}={})=>{var n;let a=e==null?s:void 0,{aud:o}=(n=Bn(e))!=null?n:{};if(!(e&&o!=="t"))return`https://image.${t}/${i}/thumbnail.webp${p_({token:e,time:a,program_time:r})}`},WO=(i,{token:e,customDomain:t=v_,programStartTime:s,programEndTime:r}={})=>{var n;let{aud:a}=(n=Bn(e))!=null?n:{};if(!(e&&a!=="s"))return`https://image.${t}/${i}/storyboard.vtt${p_({token:e,format:"webp",program_start_time:s,program_end_time:r})}`},Up=i=>{if(i){if([ke.LIVE,ke.ON_DEMAND].includes(i))return i;if(i!=null&&i.includes("live"))return ke.LIVE}},qO={crossorigin:"crossOrigin",playsinline:"playsInline"};function YO(i){var e;return(e=qO[i])!=null?e:m_(i)}var In,xn,Ot,jO=class{constructor(e,t){Ti(this,In),Ti(this,xn),Ti(this,Ot,[]),is(this,In,e),is(this,xn,t)}[Symbol.iterator](){return De(this,Ot).values()}get length(){return De(this,Ot).length}get value(){var e;return(e=De(this,Ot).join(" "))!=null?e:""}set value(e){var t;e!==this.value&&(is(this,Ot,[]),this.add(...(t=e?.split(" "))!=null?t:[]))}toString(){return this.value}item(e){return De(this,Ot)[e]}values(){return De(this,Ot).values()}keys(){return De(this,Ot).keys()}forEach(e){De(this,Ot).forEach(e)}add(...e){var t,s;e.forEach(r=>{this.contains(r)||De(this,Ot).push(r)}),!(this.value===""&&!((t=De(this,In))!=null&&t.hasAttribute(`${De(this,xn)}`)))&&((s=De(this,In))==null||s.setAttribute(`${De(this,xn)}`,`${this.value}`))}remove(...e){var t;e.forEach(s=>{De(this,Ot).splice(De(this,Ot).indexOf(s),1)}),(t=De(this,In))==null||t.setAttribute(`${De(this,xn)}`,`${this.value}`)}contains(e){return De(this,Ot).includes(e)}toggle(e,t){return typeof t<"u"?t?(this.add(e),!0):(this.remove(e),!1):this.contains(e)?(this.remove(e),!1):(this.add(e),!0)}replace(e,t){this.remove(e),this.add(t)}};In=new WeakMap,xn=new WeakMap,Ot=new WeakMap;var y_=`[mux-player ${E_()}]`;function ps(...i){console.warn(y_,...i)}function ai(...i){console.error(y_,...i)}function b_(i){var e;let t=(e=i.message)!=null?e:"";i.context&&(t+=` ${i.context}`),i.file&&(t+=` ${se("Read more: ")}
|
|
2015
2015
|
https://github.com/muxinc/elements/blob/main/errors/${i.file}`),ps(t)}var Rt={AUTOPLAY:"autoplay",CROSSORIGIN:"crossorigin",LOOP:"loop",MUTED:"muted",PLAYSINLINE:"playsinline",PRELOAD:"preload"},fr={VOLUME:"volume",PLAYBACKRATE:"playbackrate",MUTED:"muted"},yv=Object.freeze({length:0,start(i){let e=i>>>0;if(e>=this.length)throw new DOMException(`Failed to execute 'start' on 'TimeRanges': The index provided (${e}) is greater than or equal to the maximum bound (${this.length}).`);return 0},end(i){let e=i>>>0;if(e>=this.length)throw new DOMException(`Failed to execute 'end' on 'TimeRanges': The index provided (${e}) is greater than or equal to the maximum bound (${this.length}).`);return 0}}),zO=Object.values(Rt).filter(i=>Rt.PLAYSINLINE!==i),QO=Object.values(fr),XO=[...zO,...QO],ZO=class extends zi.HTMLElement{static get observedAttributes(){return XO}constructor(){super()}attributeChangedCallback(i,e,t){var s,r;switch(i){case fr.MUTED:{this.media&&(this.media.muted=t!=null,this.media.defaultMuted=t!=null);return}case fr.VOLUME:{let n=(s=qt(t))!=null?s:1;this.media&&(this.media.volume=n);return}case fr.PLAYBACKRATE:{let n=(r=qt(t))!=null?r:1;this.media&&(this.media.playbackRate=n,this.media.defaultPlaybackRate=n);return}}}play(){var i,e;return(e=(i=this.media)==null?void 0:i.play())!=null?e:Promise.reject()}pause(){var i;(i=this.media)==null||i.pause()}load(){var i;(i=this.media)==null||i.load()}get media(){var i;return(i=this.shadowRoot)==null?void 0:i.querySelector("mux-video")}get audioTracks(){return this.media.audioTracks}get videoTracks(){return this.media.videoTracks}get audioRenditions(){return this.media.audioRenditions}get videoRenditions(){return this.media.videoRenditions}get paused(){var i,e;return(e=(i=this.media)==null?void 0:i.paused)!=null?e:!0}get duration(){var i,e;return(e=(i=this.media)==null?void 0:i.duration)!=null?e:NaN}get ended(){var i,e;return(e=(i=this.media)==null?void 0:i.ended)!=null?e:!1}get buffered(){var i,e;return(e=(i=this.media)==null?void 0:i.buffered)!=null?e:yv}get seekable(){var i,e;return(e=(i=this.media)==null?void 0:i.seekable)!=null?e:yv}get readyState(){var i,e;return(e=(i=this.media)==null?void 0:i.readyState)!=null?e:0}get videoWidth(){var i,e;return(e=(i=this.media)==null?void 0:i.videoWidth)!=null?e:0}get videoHeight(){var i,e;return(e=(i=this.media)==null?void 0:i.videoHeight)!=null?e:0}get currentSrc(){var i,e;return(e=(i=this.media)==null?void 0:i.currentSrc)!=null?e:""}get currentTime(){var i,e;return(e=(i=this.media)==null?void 0:i.currentTime)!=null?e:0}set currentTime(i){this.media&&(this.media.currentTime=Number(i))}get volume(){var i,e;return(e=(i=this.media)==null?void 0:i.volume)!=null?e:1}set volume(i){this.media&&(this.media.volume=Number(i))}get playbackRate(){var i,e;return(e=(i=this.media)==null?void 0:i.playbackRate)!=null?e:1}set playbackRate(i){this.media&&(this.media.playbackRate=Number(i))}get defaultPlaybackRate(){var i;return(i=qt(this.getAttribute(fr.PLAYBACKRATE)))!=null?i:1}set defaultPlaybackRate(i){i!=null?this.setAttribute(fr.PLAYBACKRATE,`${i}`):this.removeAttribute(fr.PLAYBACKRATE)}get crossOrigin(){return ga(this,Rt.CROSSORIGIN)}set crossOrigin(i){this.setAttribute(Rt.CROSSORIGIN,`${i}`)}get autoplay(){return ga(this,Rt.AUTOPLAY)!=null}set autoplay(i){i?this.setAttribute(Rt.AUTOPLAY,typeof i=="string"?i:""):this.removeAttribute(Rt.AUTOPLAY)}get loop(){return ga(this,Rt.LOOP)!=null}set loop(i){i?this.setAttribute(Rt.LOOP,""):this.removeAttribute(Rt.LOOP)}get muted(){var i,e;return(e=(i=this.media)==null?void 0:i.muted)!=null?e:!1}set muted(i){this.media&&(this.media.muted=!!i)}get defaultMuted(){return ga(this,Rt.MUTED)!=null}set defaultMuted(i){i?this.setAttribute(Rt.MUTED,""):this.removeAttribute(Rt.MUTED)}get playsInline(){return ga(this,Rt.PLAYSINLINE)!=null}set playsInline(i){ai("playsInline is set to true by default and is not currently supported as a setter.")}get preload(){return this.media?this.media.preload:this.getAttribute("preload")}set preload(i){["","none","metadata","auto"].includes(i)?this.setAttribute(Rt.PRELOAD,i):this.removeAttribute(Rt.PRELOAD)}};function ga(i,e){return i.media?i.media.getAttribute(e):i.getAttribute(e)}var bv=ZO,JO=`:host {
|
|
2016
2016
|
--media-control-display: var(--controls);
|
|
2017
2017
|
--media-loading-indicator-display: var(--loading-indicator);
|
|
@@ -2168,7 +2168,7 @@ media-poster-image:not([src]):not([placeholdersrc]) {
|
|
|
2168
2168
|
${JO}
|
|
2169
2169
|
</style>
|
|
2170
2170
|
${g2(i)}
|
|
2171
|
-
`,f2=i=>{let e=i.hotKeys?`${i.hotKeys}`:"";return Up(i.streamType)==="live"&&(e+=" noarrowleft noarrowright"),e},m2={TOP:"top",CENTER:"center",BOTTOM:"bottom",LAYER:"layer",MEDIA_LAYER:"media-layer",POSTER_LAYER:"poster-layer",VERTICAL_LAYER:"vertical-layer",CENTERED_LAYER:"centered-layer",GESTURE_LAYER:"gesture-layer",CONTROLLER_LAYER:"controller",BUTTON:"button",RANGE:"range",THUMB:"thumb",DISPLAY:"display",CONTROL_BAR:"control-bar",MENU_BUTTON:"menu-button",MENU:"menu",MENU_ITEM:"menu-item",OPTION:"option",POSTER:"poster",LIVE:"live",PLAY:"play",PRE_PLAY:"pre-play",SEEK_BACKWARD:"seek-backward",SEEK_FORWARD:"seek-forward",MUTE:"mute",CAPTIONS:"captions",AIRPLAY:"airplay",PIP:"pip",FULLSCREEN:"fullscreen",CAST:"cast",PLAYBACK_RATE:"playback-rate",VOLUME:"volume",TIME:"time",TITLE:"title",AUDIO_TRACK:"audio-track",RENDITION:"rendition"},p2=Object.values(m2).join(", "),g2=i=>{var e,t,s,r,n,a,o,l,d,u,c,h,f,m,p,g,v,b,E,T,A,x,S,L,R,I,M,B,
|
|
2171
|
+
`,f2=i=>{let e=i.hotKeys?`${i.hotKeys}`:"";return Up(i.streamType)==="live"&&(e+=" noarrowleft noarrowright"),e},m2={TOP:"top",CENTER:"center",BOTTOM:"bottom",LAYER:"layer",MEDIA_LAYER:"media-layer",POSTER_LAYER:"poster-layer",VERTICAL_LAYER:"vertical-layer",CENTERED_LAYER:"centered-layer",GESTURE_LAYER:"gesture-layer",CONTROLLER_LAYER:"controller",BUTTON:"button",RANGE:"range",THUMB:"thumb",DISPLAY:"display",CONTROL_BAR:"control-bar",MENU_BUTTON:"menu-button",MENU:"menu",MENU_ITEM:"menu-item",OPTION:"option",POSTER:"poster",LIVE:"live",PLAY:"play",PRE_PLAY:"pre-play",SEEK_BACKWARD:"seek-backward",SEEK_FORWARD:"seek-forward",MUTE:"mute",CAPTIONS:"captions",AIRPLAY:"airplay",PIP:"pip",FULLSCREEN:"fullscreen",CAST:"cast",PLAYBACK_RATE:"playback-rate",VOLUME:"volume",TIME:"time",TITLE:"title",AUDIO_TRACK:"audio-track",RENDITION:"rendition"},p2=Object.values(m2).join(", "),g2=i=>{var e,t,s,r,n,a,o,l,d,u,c,h,f,m,p,g,v,b,E,T,A,x,S,L,R,I,M,B,q,z,K,H,j,G,N,W,U,$;return xd`
|
|
2172
2172
|
<media-theme
|
|
2173
2173
|
template="${i.themeTemplate||!1}"
|
|
2174
2174
|
defaultstreamtype="${(e=i.defaultStreamType)!=null?e:!1}"
|
|
@@ -2213,17 +2213,17 @@ media-poster-image:not([src]):not([placeholdersrc]) {
|
|
|
2213
2213
|
start-time="${i.startTime!=null?i.startTime:!1}"
|
|
2214
2214
|
beacon-collection-domain="${(M=i.beaconCollectionDomain)!=null?M:!1}"
|
|
2215
2215
|
player-init-time="${(B=i.playerInitTime)!=null?B:!1}"
|
|
2216
|
-
player-software-name="${(
|
|
2217
|
-
player-software-version="${(
|
|
2216
|
+
player-software-name="${(q=i.playerSoftwareName)!=null?q:!1}"
|
|
2217
|
+
player-software-version="${(z=i.playerSoftwareVersion)!=null?z:!1}"
|
|
2218
2218
|
env-key="${(K=i.envKey)!=null?K:!1}"
|
|
2219
|
-
custom-domain="${(
|
|
2219
|
+
custom-domain="${(H=i.customDomain)!=null?H:!1}"
|
|
2220
2220
|
src="${i.src?i.src:i.playbackId?of(i):!1}"
|
|
2221
2221
|
cast-src="${i.src?i.src:i.playbackId?of(i):!1}"
|
|
2222
|
-
cast-receiver="${(
|
|
2223
|
-
drm-token="${(
|
|
2222
|
+
cast-receiver="${(j=i.castReceiver)!=null?j:!1}"
|
|
2223
|
+
drm-token="${(N=(G=i.tokens)==null?void 0:G.drm)!=null?N:!1}"
|
|
2224
2224
|
exportparts="video"
|
|
2225
|
-
disable-pseudo-ended="${(
|
|
2226
|
-
max-auto-resolution="${(
|
|
2225
|
+
disable-pseudo-ended="${(W=i.disablePseudoEnded)!=null?W:!1}"
|
|
2226
|
+
max-auto-resolution="${(U=i.maxAutoResolution)!=null?U:!1}"
|
|
2227
2227
|
>
|
|
2228
2228
|
${i.storyboard?xd`<track label="thumbnails" default kind="metadata" src="${i.storyboard}" />`:xd``}
|
|
2229
2229
|
<slot></slot>
|
|
@@ -2233,11 +2233,11 @@ media-poster-image:not([src]):not([placeholdersrc]) {
|
|
|
2233
2233
|
part="poster"
|
|
2234
2234
|
exportparts="poster, img"
|
|
2235
2235
|
src="${i.poster?i.poster:!1}"
|
|
2236
|
-
placeholdersrc="${(
|
|
2236
|
+
placeholdersrc="${($=i.placeholder)!=null?$:!1}"
|
|
2237
2237
|
></media-poster-image>
|
|
2238
2238
|
</slot>
|
|
2239
2239
|
</media-theme>
|
|
2240
|
-
`},A_=i=>i.charAt(0).toUpperCase()+i.slice(1),v2=(i,e=!1)=>{var t,s;if(i.muxCode){let r=A_((t=i.errorCategory)!=null?t:"video"),n=zu((s=i.errorCategory)!=null?s:Fe.VIDEO);if(i.muxCode===ae.NETWORK_OFFLINE)return
|
|
2240
|
+
`},A_=i=>i.charAt(0).toUpperCase()+i.slice(1),v2=(i,e=!1)=>{var t,s;if(i.muxCode){let r=A_((t=i.errorCategory)!=null?t:"video"),n=zu((s=i.errorCategory)!=null?s:Fe.VIDEO);if(i.muxCode===ae.NETWORK_OFFLINE)return se("Your device appears to be offline",e);if(i.muxCode===ae.NETWORK_TOKEN_EXPIRED)return se("{category} URL has expired",e).format({category:r});if([ae.NETWORK_TOKEN_SUB_MISMATCH,ae.NETWORK_TOKEN_AUD_MISMATCH,ae.NETWORK_TOKEN_AUD_MISSING,ae.NETWORK_TOKEN_MALFORMED].includes(i.muxCode))return se("{category} URL is formatted incorrectly",e).format({category:r});if(i.muxCode===ae.NETWORK_TOKEN_MISSING)return se("Invalid {categoryName} URL",e).format({categoryName:n});if(i.muxCode===ae.NETWORK_NOT_FOUND)return se("{category} does not exist",e).format({category:r});if(i.muxCode===ae.NETWORK_NOT_READY){let a=i.streamType==="live"?"Live stream":"Video";return se("{mediaType} is not currently available",e).format({mediaType:a})}}if(i.code){if(i.code===Z.MEDIA_ERR_NETWORK)return se("Network Error",e);if(i.code===Z.MEDIA_ERR_DECODE)return se("Media Error",e);if(i.code===Z.MEDIA_ERR_SRC_NOT_SUPPORTED)return se("Source Not Supported",e)}return se("Error",e)},E2=(i,e=!1)=>{var t,s;if(i.muxCode){let r=A_((t=i.errorCategory)!=null?t:"video"),n=zu((s=i.errorCategory)!=null?s:Fe.VIDEO);return i.muxCode===ae.NETWORK_OFFLINE?se("Check your internet connection and try reloading this video.",e):i.muxCode===ae.NETWORK_TOKEN_EXPIRED?se("The video’s secured {tokenNamePrefix}-token has expired.",e).format({tokenNamePrefix:n}):i.muxCode===ae.NETWORK_TOKEN_SUB_MISMATCH?se("The video’s playback ID does not match the one encoded in the {tokenNamePrefix}-token.",e).format({tokenNamePrefix:n}):i.muxCode===ae.NETWORK_TOKEN_MALFORMED?se("{category} URL is formatted incorrectly",e).format({category:r}):[ae.NETWORK_TOKEN_AUD_MISMATCH,ae.NETWORK_TOKEN_AUD_MISSING].includes(i.muxCode)?se("The {tokenNamePrefix}-token is formatted with incorrect information.",e).format({tokenNamePrefix:n}):[ae.NETWORK_TOKEN_MISSING,ae.NETWORK_INVALID_URL].includes(i.muxCode)?se("The video URL or {tokenNamePrefix}-token are formatted with incorrect or incomplete information.",e).format({tokenNamePrefix:n}):i.muxCode===ae.NETWORK_NOT_FOUND?"":i.message}return i.code&&(i.code===Z.MEDIA_ERR_NETWORK||i.code===Z.MEDIA_ERR_DECODE||(i.code,Z.MEDIA_ERR_SRC_NOT_SUPPORTED)),i.message},y2=(i,e=!1)=>{let t=v2(i,e).toString(),s=E2(i,e).toString();return{title:t,message:s}},b2=i=>{if(i.muxCode){if(i.muxCode===ae.NETWORK_TOKEN_EXPIRED)return"403-expired-token.md";if(i.muxCode===ae.NETWORK_TOKEN_MALFORMED)return"403-malformatted-token.md";if([ae.NETWORK_TOKEN_AUD_MISMATCH,ae.NETWORK_TOKEN_AUD_MISSING].includes(i.muxCode))return"403-incorrect-aud-value.md";if(i.muxCode===ae.NETWORK_TOKEN_SUB_MISMATCH)return"403-playback-id-mismatch.md";if(i.muxCode===ae.NETWORK_TOKEN_MISSING)return"missing-signed-tokens.md";if(i.muxCode===ae.NETWORK_NOT_FOUND)return"404-not-found.md";if(i.muxCode===ae.NETWORK_NOT_READY)return"412-not-playable.md"}if(i.code){if(i.code===Z.MEDIA_ERR_NETWORK)return"";if(i.code===Z.MEDIA_ERR_DECODE)return"media-decode-error.md";if(i.code===Z.MEDIA_ERR_SRC_NOT_SUPPORTED)return"media-src-not-supported.md"}return""},Av=(i,e)=>{let t=b2(i);return{message:i.message,context:i.context,file:t}},T2=`<template id="media-theme-gerwig">
|
|
2241
2241
|
<style>
|
|
2242
2242
|
@keyframes pre-play-hide {
|
|
2243
2243
|
0% {
|
|
@@ -3369,7 +3369,7 @@ media-poster-image:not([src]):not([placeholdersrc]) {
|
|
|
3369
3369
|
<slot></slot>
|
|
3370
3370
|
</media-controller>
|
|
3371
3371
|
</template>
|
|
3372
|
-
`,zf=Eu.createElement("template");"innerHTML"in zf&&(zf.innerHTML=T2);var Sv,Iv,S_=class extends tc{};S_.template=(Iv=(Sv=zf.content)==null?void 0:Sv.children)==null?void 0:Iv[0];zi.customElements.get("media-theme-gerwig")||zi.customElements.define("media-theme-gerwig",S_);var _2="gerwig",cs={SRC:"src",POSTER:"poster"},
|
|
3372
|
+
`,zf=Eu.createElement("template");"innerHTML"in zf&&(zf.innerHTML=T2);var Sv,Iv,S_=class extends tc{};S_.template=(Iv=(Sv=zf.content)==null?void 0:Sv.children)==null?void 0:Iv[0];zi.customElements.get("media-theme-gerwig")||zi.customElements.define("media-theme-gerwig",S_);var _2="gerwig",cs={SRC:"src",POSTER:"poster"},F={STYLE:"style",DEFAULT_HIDDEN_CAPTIONS:"default-hidden-captions",PRIMARY_COLOR:"primary-color",SECONDARY_COLOR:"secondary-color",ACCENT_COLOR:"accent-color",FORWARD_SEEK_OFFSET:"forward-seek-offset",BACKWARD_SEEK_OFFSET:"backward-seek-offset",PLAYBACK_TOKEN:"playback-token",THUMBNAIL_TOKEN:"thumbnail-token",STORYBOARD_TOKEN:"storyboard-token",FULLSCREEN_ELEMENT:"fullscreen-element",DRM_TOKEN:"drm-token",STORYBOARD_SRC:"storyboard-src",THUMBNAIL_TIME:"thumbnail-time",AUDIO:"audio",NOHOTKEYS:"nohotkeys",HOTKEYS:"hotkeys",PLAYBACK_RATES:"playbackrates",DEFAULT_SHOW_REMAINING_TIME:"default-show-remaining-time",DEFAULT_DURATION:"default-duration",TITLE:"title",VIDEO_TITLE:"video-title",PLACEHOLDER:"placeholder",THEME:"theme",DEFAULT_STREAM_TYPE:"default-stream-type",TARGET_LIVE_WINDOW:"target-live-window",EXTRA_SOURCE_PARAMS:"extra-source-params",NO_VOLUME_PREF:"no-volume-pref",NO_MUTED_PREF:"no-muted-pref",CAST_RECEIVER:"cast-receiver",NO_TOOLTIPS:"no-tooltips",PROUDLY_DISPLAY_MUX_BADGE:"proudly-display-mux-badge",DISABLE_PSEUDO_ENDED:"disable-pseudo-ended"},Qf=["audio","backwardseekoffset","defaultduration","defaultshowremainingtime","defaultsubtitles","noautoseektolive","disabled","exportparts","forwardseekoffset","hideduration","hotkeys","nohotkeys","playbackrates","defaultstreamtype","streamtype","style","targetlivewindow","template","title","videotitle","novolumepref","nomutedpref","proudlydisplaymuxbadge"];function A2(i,e){var t,s,r;return{src:!i.playbackId&&i.src,playbackId:i.playbackId,hasSrc:!!i.playbackId||!!i.src||!!i.currentSrc,poster:i.poster,storyboard:((t=i.media)==null?void 0:t.currentSrc)&&i.storyboard,storyboardSrc:i.getAttribute(F.STORYBOARD_SRC),fullscreenElement:i.getAttribute(F.FULLSCREEN_ELEMENT),placeholder:i.getAttribute("placeholder"),themeTemplate:I2(i),thumbnailTime:!i.tokens.thumbnail&&i.thumbnailTime,autoplay:i.autoplay,crossOrigin:i.crossOrigin,loop:i.loop,noHotKeys:i.hasAttribute(F.NOHOTKEYS),hotKeys:i.getAttribute(F.HOTKEYS),muted:i.muted,paused:i.paused,preload:i.preload,envKey:i.envKey,preferCmcd:i.preferCmcd,debug:i.debug,disableTracking:i.disableTracking,disableCookies:i.disableCookies,tokens:i.tokens,beaconCollectionDomain:i.beaconCollectionDomain,maxResolution:i.maxResolution,minResolution:i.minResolution,maxAutoResolution:i.maxAutoResolution,programStartTime:i.programStartTime,programEndTime:i.programEndTime,assetStartTime:i.assetStartTime,assetEndTime:i.assetEndTime,renditionOrder:i.renditionOrder,metadata:i.metadata,playerInitTime:i.playerInitTime,playerSoftwareName:i.playerSoftwareName,playerSoftwareVersion:i.playerSoftwareVersion,startTime:i.startTime,preferPlayback:i.preferPlayback,audio:i.audio,defaultStreamType:i.defaultStreamType,targetLiveWindow:i.getAttribute(C.TARGET_LIVE_WINDOW),streamType:Up(i.getAttribute(C.STREAM_TYPE)),primaryColor:i.getAttribute(F.PRIMARY_COLOR),secondaryColor:i.getAttribute(F.SECONDARY_COLOR),accentColor:i.getAttribute(F.ACCENT_COLOR),forwardSeekOffset:i.forwardSeekOffset,backwardSeekOffset:i.backwardSeekOffset,defaultHiddenCaptions:i.defaultHiddenCaptions,defaultDuration:i.defaultDuration,defaultShowRemainingTime:i.defaultShowRemainingTime,hideDuration:x2(i),playbackRates:i.getAttribute(F.PLAYBACK_RATES),customDomain:(s=i.getAttribute(C.CUSTOM_DOMAIN))!=null?s:void 0,title:i.getAttribute(F.TITLE),videoTitle:(r=i.getAttribute(F.VIDEO_TITLE))!=null?r:i.getAttribute(F.TITLE),novolumepref:i.hasAttribute(F.NO_VOLUME_PREF),nomutedpref:i.hasAttribute(F.NO_MUTED_PREF),proudlyDisplayMuxBadge:i.hasAttribute(F.PROUDLY_DISPLAY_MUX_BADGE),castReceiver:i.castReceiver,disablePseudoEnded:i.hasAttribute(F.DISABLE_PSEUDO_ENDED),...e,extraSourceParams:i.extraSourceParams}}var S2=vm.formatErrorMessage;vm.formatErrorMessage=i=>{var e,t;if(i instanceof Z){let s=y2(i,!1);return`
|
|
3373
3373
|
${s!=null&&s.title?`<h3>${s.title}</h3>`:""}
|
|
3374
3374
|
${s!=null&&s.message||s!=null&&s.linkUrl?`<p>
|
|
3375
3375
|
${s?.message}
|
|
@@ -3377,10 +3377,10 @@ media-poster-image:not([src]):not([placeholdersrc]) {
|
|
|
3377
3377
|
href="${s.linkUrl}"
|
|
3378
3378
|
target="_blank"
|
|
3379
3379
|
rel="external noopener"
|
|
3380
|
-
aria-label="${(e=s.linkText)!=null?e:""} ${
|
|
3380
|
+
aria-label="${(e=s.linkText)!=null?e:""} ${se("(opens in a new window)")}"
|
|
3381
3381
|
>${(t=s.linkText)!=null?t:s.linkUrl}</a
|
|
3382
3382
|
>`:""}
|
|
3383
3383
|
</p>`:""}
|
|
3384
|
-
`}return S2(i)};function I2(i){var e,t;let s=i.theme;if(s){let r=(t=(e=i.getRootNode())==null?void 0:e.getElementById)==null?void 0:t.call(e,s);if(r&&r instanceof HTMLTemplateElement)return r;s.startsWith("media-theme-")||(s=`media-theme-${s}`);let n=zi.customElements.get(s);if(n!=null&&n.template)return n.template}}function x2(i){var e;let t=(e=i.mediaController)==null?void 0:e.querySelector("media-time-display");return t&&getComputedStyle(t).getPropertyValue("--media-duration-display-display").trim()==="none"}function xv(i){let e=i.videoTitle?{video_title:i.videoTitle}:{};return i.getAttributeNames().filter(t=>t.startsWith("metadata-")).reduce((t,s)=>{let r=i.getAttribute(s);return r!==null&&(t[s.replace(/^metadata-/,"").replace(/-/g,"_")]=r),t},e)}var L2=Object.values(C),R2=Object.values(cs),k2=Object.values(U),Lv=E_(),Rv="mux-player",kv={isDialogOpen:!1},D2={redundant_streams:!0},Ld,Rd,kd,mr,Dd,qn,Qe,$s,I_,Xf,pr,Dv,Cv,wv,Mv,C2=class extends bv{constructor(){super(),Ti(this,Qe),Ti(this,Ld),Ti(this,Rd,!1),Ti(this,kd,{}),Ti(this,mr,!0),Ti(this,Dd,new jO(this,"hotkeys")),Ti(this,qn,{...kv,onCloseErrorDialog:i=>{var e;((e=i.composedPath()[0])==null?void 0:e.localName)==="media-error-dialog"&&at(this,Qe,Xf).call(this,{isDialogOpen:!1})},onFocusInErrorDialog:i=>{var e;((e=i.composedPath()[0])==null?void 0:e.localName)==="media-error-dialog"&&(g_(this,Eu.activeElement)||i.preventDefault())}}),is(this,Ld,ap()),this.attachShadow({mode:"open"}),at(this,Qe,I_).call(this),this.isConnected&&at(this,Qe,$s).call(this)}static get NAME(){return Rv}static get VERSION(){return Lv}static get observedAttributes(){var i;return[...(i=bv.observedAttributes)!=null?i:[],...R2,...L2,...k2]}get mediaTheme(){var i;return(i=this.shadowRoot)==null?void 0:i.querySelector("media-theme")}get mediaController(){var i,e;return(e=(i=this.mediaTheme)==null?void 0:i.shadowRoot)==null?void 0:e.querySelector("media-controller")}connectedCallback(){let i=this.media;i&&(i.metadata=xv(this))}attributeChangedCallback(i,e,t){switch(at(this,Qe,$s).call(this),super.attributeChangedCallback(i,e,t),i){case U.HOTKEYS:De(this,Dd).value=t;break;case U.THUMBNAIL_TIME:{t!=null&&this.tokens.thumbnail&&ps(re("Use of thumbnail-time with thumbnail-token is currently unsupported. Ignore thumbnail-time.").toString());break}case U.THUMBNAIL_TOKEN:{if(t){let s=Bn(t);if(s){let{aud:r}=s,n=Za.THUMBNAIL;r!==n&&ps(re("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"thumbnail"}))}}break}case U.STORYBOARD_TOKEN:{if(t){let s=Bn(t);if(s){let{aud:r}=s,n=Za.STORYBOARD;r!==n&&ps(re("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"storyboard"}))}}break}case U.DRM_TOKEN:{if(t){let s=Bn(t);if(s){let{aud:r}=s,n=Za.DRM;r!==n&&ps(re("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"drm"}))}}break}case C.PLAYBACK_ID:{t!=null&&t.includes("?token")&&ai(re("The specificed playback ID {playbackId} contains a token which must be provided via the playback-token attribute.").format({playbackId:t}));break}case C.STREAM_TYPE:{t&&![ke.LIVE,ke.ON_DEMAND,ke.UNKNOWN].includes(t)?["ll-live","live:dvr","ll-live:dvr"].includes(this.streamType)?this.targetLiveWindow=t.includes("dvr")?Number.POSITIVE_INFINITY:0:b_({file:"invalid-stream-type.md",message:re("Invalid stream-type value supplied: `{streamType}`. Please provide stream-type as either: `on-demand` or `live`").format({streamType:this.streamType})}):t===ke.LIVE?this.getAttribute(U.TARGET_LIVE_WINDOW)==null&&(this.targetLiveWindow=0):this.targetLiveWindow=Number.NaN;break}case U.FULLSCREEN_ELEMENT:{if(t!=null||t!==e){let s=Eu.getElementById(t),r=s?.querySelector("mux-player");this.mediaController&&s&&r&&(this.mediaController.fullscreenElement=s)}break}}[C.PLAYBACK_ID,cs.SRC,U.PLAYBACK_TOKEN].includes(i)&&e!==t&&is(this,qn,{...De(this,qn),...kv}),at(this,Qe,pr).call(this,{[YO(i)]:t})}async requestFullscreen(i){var e;if(!(!this.mediaController||this.mediaController.hasAttribute(_.MEDIA_IS_FULLSCREEN)))return(e=this.mediaController)==null||e.dispatchEvent(new zi.CustomEvent(z.MEDIA_ENTER_FULLSCREEN_REQUEST,{composed:!0,bubbles:!0})),new Promise((t,s)=>{var r;(r=this.mediaController)==null||r.addEventListener(ys.MEDIA_IS_FULLSCREEN,()=>t(),{once:!0})})}async exitFullscreen(){var i;if(!(!this.mediaController||!this.mediaController.hasAttribute(_.MEDIA_IS_FULLSCREEN)))return(i=this.mediaController)==null||i.dispatchEvent(new zi.CustomEvent(z.MEDIA_EXIT_FULLSCREEN_REQUEST,{composed:!0,bubbles:!0})),new Promise((e,t)=>{var s;(s=this.mediaController)==null||s.addEventListener(ys.MEDIA_IS_FULLSCREEN,()=>e(),{once:!0})})}get preferCmcd(){var i;return(i=this.getAttribute(C.PREFER_CMCD))!=null?i:void 0}set preferCmcd(i){i!==this.preferCmcd&&(i?nu.includes(i)?this.setAttribute(C.PREFER_CMCD,i):ps(`Invalid value for preferCmcd. Must be one of ${nu.join()}`):this.removeAttribute(C.PREFER_CMCD))}get hasPlayed(){var i,e;return(e=(i=this.mediaController)==null?void 0:i.hasAttribute(_.MEDIA_HAS_PLAYED))!=null?e:!1}get inLiveWindow(){var i;return(i=this.mediaController)==null?void 0:i.hasAttribute(_.MEDIA_TIME_IS_LIVE)}get _hls(){var i;return(i=this.media)==null?void 0:i._hls}get mux(){var i;return(i=this.media)==null?void 0:i.mux}get theme(){var i;return(i=this.getAttribute(U.THEME))!=null?i:_2}set theme(i){this.setAttribute(U.THEME,`${i}`)}get themeProps(){let i=this.mediaTheme;if(!i)return;let e={};for(let t of i.getAttributeNames()){if(Qf.includes(t))continue;let s=i.getAttribute(t);e[m_(t)]=s===""?!0:s}return e}set themeProps(i){var e,t;at(this,Qe,$s).call(this);let s={...this.themeProps,...i};for(let r in s){if(Qf.includes(r))continue;let n=i?.[r];typeof n=="boolean"||n==null?(e=this.mediaTheme)==null||e.toggleAttribute(jf(r),!!n):(t=this.mediaTheme)==null||t.setAttribute(jf(r),n)}}get playbackId(){var i;return(i=this.getAttribute(C.PLAYBACK_ID))!=null?i:void 0}set playbackId(i){i?this.setAttribute(C.PLAYBACK_ID,i):this.removeAttribute(C.PLAYBACK_ID)}get src(){var i,e;return this.playbackId?(i=nr(this,cs.SRC))!=null?i:void 0:(e=this.getAttribute(cs.SRC))!=null?e:void 0}set src(i){i?this.setAttribute(cs.SRC,i):this.removeAttribute(cs.SRC)}get poster(){var i;let e=this.getAttribute(cs.POSTER);if(e!=null)return e;let{tokens:t}=this;if(t.playback&&!t.thumbnail){ps("Missing expected thumbnail token. No poster image will be shown");return}if(this.playbackId&&!this.audio)return VO(this.playbackId,{customDomain:this.customDomain,thumbnailTime:(i=this.thumbnailTime)!=null?i:this.startTime,programTime:this.programStartTime,token:t.thumbnail})}set poster(i){i||i===""?this.setAttribute(cs.POSTER,i):this.removeAttribute(cs.POSTER)}get storyboardSrc(){var i;return(i=this.getAttribute(U.STORYBOARD_SRC))!=null?i:void 0}set storyboardSrc(i){i?this.setAttribute(U.STORYBOARD_SRC,i):this.removeAttribute(U.STORYBOARD_SRC)}get storyboard(){let{tokens:i}=this;if(this.storyboardSrc&&!i.storyboard)return this.storyboardSrc;if(!(this.audio||!this.playbackId||!this.streamType||[ke.LIVE,ke.UNKNOWN].includes(this.streamType)||i.playback&&!i.storyboard))return WO(this.playbackId,{customDomain:this.customDomain,token:i.storyboard,programStartTime:this.programStartTime,programEndTime:this.programEndTime})}get audio(){return this.hasAttribute(U.AUDIO)}set audio(i){if(!i){this.removeAttribute(U.AUDIO);return}this.setAttribute(U.AUDIO,"")}get hotkeys(){return De(this,Dd)}get nohotkeys(){return this.hasAttribute(U.NOHOTKEYS)}set nohotkeys(i){if(!i){this.removeAttribute(U.NOHOTKEYS);return}this.setAttribute(U.NOHOTKEYS,"")}get thumbnailTime(){return qt(this.getAttribute(U.THUMBNAIL_TIME))}set thumbnailTime(i){this.setAttribute(U.THUMBNAIL_TIME,`${i}`)}get videoTitle(){var i,e;return(e=(i=this.getAttribute(U.VIDEO_TITLE))!=null?i:this.getAttribute(U.TITLE))!=null?e:""}set videoTitle(i){i!==this.videoTitle&&(i?this.setAttribute(U.VIDEO_TITLE,i):this.removeAttribute(U.VIDEO_TITLE))}get placeholder(){var i;return(i=nr(this,U.PLACEHOLDER))!=null?i:""}set placeholder(i){this.setAttribute(U.PLACEHOLDER,`${i}`)}get primaryColor(){var i,e;let t=this.getAttribute(U.PRIMARY_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=zi.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_primary-color"))==null?void 0:e.trim(),t))return t}set primaryColor(i){this.setAttribute(U.PRIMARY_COLOR,`${i}`)}get secondaryColor(){var i,e;let t=this.getAttribute(U.SECONDARY_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=zi.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_secondary-color"))==null?void 0:e.trim(),t))return t}set secondaryColor(i){this.setAttribute(U.SECONDARY_COLOR,`${i}`)}get accentColor(){var i,e;let t=this.getAttribute(U.ACCENT_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=zi.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_accent-color"))==null?void 0:e.trim(),t))return t}set accentColor(i){this.setAttribute(U.ACCENT_COLOR,`${i}`)}get defaultShowRemainingTime(){return this.hasAttribute(U.DEFAULT_SHOW_REMAINING_TIME)}set defaultShowRemainingTime(i){i?this.setAttribute(U.DEFAULT_SHOW_REMAINING_TIME,""):this.removeAttribute(U.DEFAULT_SHOW_REMAINING_TIME)}get playbackRates(){if(this.hasAttribute(U.PLAYBACK_RATES))return this.getAttribute(U.PLAYBACK_RATES).trim().split(/\s*,?\s+/).map(i=>Number(i)).filter(i=>!Number.isNaN(i)).sort((i,e)=>i-e)}set playbackRates(i){if(!i){this.removeAttribute(U.PLAYBACK_RATES);return}this.setAttribute(U.PLAYBACK_RATES,i.join(" "))}get forwardSeekOffset(){var i;return(i=qt(this.getAttribute(U.FORWARD_SEEK_OFFSET)))!=null?i:10}set forwardSeekOffset(i){this.setAttribute(U.FORWARD_SEEK_OFFSET,`${i}`)}get backwardSeekOffset(){var i;return(i=qt(this.getAttribute(U.BACKWARD_SEEK_OFFSET)))!=null?i:10}set backwardSeekOffset(i){this.setAttribute(U.BACKWARD_SEEK_OFFSET,`${i}`)}get defaultHiddenCaptions(){return this.hasAttribute(U.DEFAULT_HIDDEN_CAPTIONS)}set defaultHiddenCaptions(i){i?this.setAttribute(U.DEFAULT_HIDDEN_CAPTIONS,""):this.removeAttribute(U.DEFAULT_HIDDEN_CAPTIONS)}get defaultDuration(){return qt(this.getAttribute(U.DEFAULT_DURATION))}set defaultDuration(i){i==null?this.removeAttribute(U.DEFAULT_DURATION):this.setAttribute(U.DEFAULT_DURATION,`${i}`)}get playerInitTime(){return this.hasAttribute(C.PLAYER_INIT_TIME)?qt(this.getAttribute(C.PLAYER_INIT_TIME)):De(this,Ld)}set playerInitTime(i){i!=this.playerInitTime&&(i==null?this.removeAttribute(C.PLAYER_INIT_TIME):this.setAttribute(C.PLAYER_INIT_TIME,`${+i}`))}get playerSoftwareName(){var i;return(i=this.getAttribute(C.PLAYER_SOFTWARE_NAME))!=null?i:Rv}get playerSoftwareVersion(){var i;return(i=this.getAttribute(C.PLAYER_SOFTWARE_VERSION))!=null?i:Lv}get beaconCollectionDomain(){var i;return(i=this.getAttribute(C.BEACON_COLLECTION_DOMAIN))!=null?i:void 0}set beaconCollectionDomain(i){i!==this.beaconCollectionDomain&&(i?this.setAttribute(C.BEACON_COLLECTION_DOMAIN,i):this.removeAttribute(C.BEACON_COLLECTION_DOMAIN))}get maxResolution(){var i;return(i=this.getAttribute(C.MAX_RESOLUTION))!=null?i:void 0}set maxResolution(i){i!==this.maxResolution&&(i?this.setAttribute(C.MAX_RESOLUTION,i):this.removeAttribute(C.MAX_RESOLUTION))}get minResolution(){var i;return(i=this.getAttribute(C.MIN_RESOLUTION))!=null?i:void 0}set minResolution(i){i!==this.minResolution&&(i?this.setAttribute(C.MIN_RESOLUTION,i):this.removeAttribute(C.MIN_RESOLUTION))}get maxAutoResolution(){var i;return(i=this.getAttribute(C.MAX_AUTO_RESOLUTION))!=null?i:void 0}set maxAutoResolution(i){i==null?this.removeAttribute(C.MAX_AUTO_RESOLUTION):this.setAttribute(C.MAX_AUTO_RESOLUTION,i)}get renditionOrder(){var i;return(i=this.getAttribute(C.RENDITION_ORDER))!=null?i:void 0}set renditionOrder(i){i!==this.renditionOrder&&(i?this.setAttribute(C.RENDITION_ORDER,i):this.removeAttribute(C.RENDITION_ORDER))}get programStartTime(){return qt(this.getAttribute(C.PROGRAM_START_TIME))}set programStartTime(i){i==null?this.removeAttribute(C.PROGRAM_START_TIME):this.setAttribute(C.PROGRAM_START_TIME,`${i}`)}get programEndTime(){return qt(this.getAttribute(C.PROGRAM_END_TIME))}set programEndTime(i){i==null?this.removeAttribute(C.PROGRAM_END_TIME):this.setAttribute(C.PROGRAM_END_TIME,`${i}`)}get assetStartTime(){return qt(this.getAttribute(C.ASSET_START_TIME))}set assetStartTime(i){i==null?this.removeAttribute(C.ASSET_START_TIME):this.setAttribute(C.ASSET_START_TIME,`${i}`)}get assetEndTime(){return qt(this.getAttribute(C.ASSET_END_TIME))}set assetEndTime(i){i==null?this.removeAttribute(C.ASSET_END_TIME):this.setAttribute(C.ASSET_END_TIME,`${i}`)}get extraSourceParams(){return this.hasAttribute(U.EXTRA_SOURCE_PARAMS)?[...new URLSearchParams(this.getAttribute(U.EXTRA_SOURCE_PARAMS)).entries()].reduce((i,[e,t])=>(i[e]=t,i),{}):D2}set extraSourceParams(i){i==null?this.removeAttribute(U.EXTRA_SOURCE_PARAMS):this.setAttribute(U.EXTRA_SOURCE_PARAMS,new URLSearchParams(i).toString())}get customDomain(){var i;return(i=this.getAttribute(C.CUSTOM_DOMAIN))!=null?i:void 0}set customDomain(i){i!==this.customDomain&&(i?this.setAttribute(C.CUSTOM_DOMAIN,i):this.removeAttribute(C.CUSTOM_DOMAIN))}get envKey(){var i;return(i=nr(this,C.ENV_KEY))!=null?i:void 0}set envKey(i){this.setAttribute(C.ENV_KEY,`${i}`)}get noVolumePref(){return this.hasAttribute(U.NO_VOLUME_PREF)}set noVolumePref(i){i?this.setAttribute(U.NO_VOLUME_PREF,""):this.removeAttribute(U.NO_VOLUME_PREF)}get noMutedPref(){return this.hasAttribute(U.NO_MUTED_PREF)}set noMutedPref(i){i?this.setAttribute(U.NO_MUTED_PREF,""):this.removeAttribute(U.NO_MUTED_PREF)}get debug(){return nr(this,C.DEBUG)!=null}set debug(i){i?this.setAttribute(C.DEBUG,""):this.removeAttribute(C.DEBUG)}get disableTracking(){return nr(this,C.DISABLE_TRACKING)!=null}set disableTracking(i){this.toggleAttribute(C.DISABLE_TRACKING,!!i)}get disableCookies(){return nr(this,C.DISABLE_COOKIES)!=null}set disableCookies(i){i?this.setAttribute(C.DISABLE_COOKIES,""):this.removeAttribute(C.DISABLE_COOKIES)}get streamType(){var i,e,t;return(t=(e=this.getAttribute(C.STREAM_TYPE))!=null?e:(i=this.media)==null?void 0:i.streamType)!=null?t:ke.UNKNOWN}set streamType(i){this.setAttribute(C.STREAM_TYPE,`${i}`)}get defaultStreamType(){var i,e,t;return(t=(e=this.getAttribute(U.DEFAULT_STREAM_TYPE))!=null?e:(i=this.mediaController)==null?void 0:i.getAttribute(U.DEFAULT_STREAM_TYPE))!=null?t:ke.ON_DEMAND}set defaultStreamType(i){i?this.setAttribute(U.DEFAULT_STREAM_TYPE,i):this.removeAttribute(U.DEFAULT_STREAM_TYPE)}get targetLiveWindow(){var i,e;return this.hasAttribute(U.TARGET_LIVE_WINDOW)?+this.getAttribute(U.TARGET_LIVE_WINDOW):(e=(i=this.media)==null?void 0:i.targetLiveWindow)!=null?e:Number.NaN}set targetLiveWindow(i){i==this.targetLiveWindow||Number.isNaN(i)&&Number.isNaN(this.targetLiveWindow)||(i==null?this.removeAttribute(U.TARGET_LIVE_WINDOW):this.setAttribute(U.TARGET_LIVE_WINDOW,`${+i}`))}get liveEdgeStart(){var i;return(i=this.media)==null?void 0:i.liveEdgeStart}get startTime(){return qt(nr(this,C.START_TIME))}set startTime(i){this.setAttribute(C.START_TIME,`${i}`)}get preferPlayback(){let i=this.getAttribute(C.PREFER_PLAYBACK);if(i===Zi.MSE||i===Zi.NATIVE)return i}set preferPlayback(i){i!==this.preferPlayback&&(i===Zi.MSE||i===Zi.NATIVE?this.setAttribute(C.PREFER_PLAYBACK,i):this.removeAttribute(C.PREFER_PLAYBACK))}get metadata(){var i;return(i=this.media)==null?void 0:i.metadata}set metadata(i){if(at(this,Qe,$s).call(this),!this.media){ai("underlying media element missing when trying to set metadata. metadata will not be set.");return}this.media.metadata={...xv(this),...i}}get _hlsConfig(){var i;return(i=this.media)==null?void 0:i._hlsConfig}set _hlsConfig(i){if(at(this,Qe,$s).call(this),!this.media){ai("underlying media element missing when trying to set _hlsConfig. _hlsConfig will not be set.");return}this.media._hlsConfig=i}async addCuePoints(i){var e;if(at(this,Qe,$s).call(this),!this.media){ai("underlying media element missing when trying to addCuePoints. cuePoints will not be added.");return}return(e=this.media)==null?void 0:e.addCuePoints(i)}get activeCuePoint(){var i;return(i=this.media)==null?void 0:i.activeCuePoint}get cuePoints(){var i,e;return(e=(i=this.media)==null?void 0:i.cuePoints)!=null?e:[]}addChapters(i){var e;if(at(this,Qe,$s).call(this),!this.media){ai("underlying media element missing when trying to addChapters. chapters will not be added.");return}return(e=this.media)==null?void 0:e.addChapters(i)}get activeChapter(){var i;return(i=this.media)==null?void 0:i.activeChapter}get chapters(){var i,e;return(e=(i=this.media)==null?void 0:i.chapters)!=null?e:[]}getStartDate(){var i;return(i=this.media)==null?void 0:i.getStartDate()}get currentPdt(){var i;return(i=this.media)==null?void 0:i.currentPdt}get tokens(){let i=this.getAttribute(U.PLAYBACK_TOKEN),e=this.getAttribute(U.DRM_TOKEN),t=this.getAttribute(U.THUMBNAIL_TOKEN),s=this.getAttribute(U.STORYBOARD_TOKEN);return{...De(this,kd),...i!=null?{playback:i}:{},...e!=null?{drm:e}:{},...t!=null?{thumbnail:t}:{},...s!=null?{storyboard:s}:{}}}set tokens(i){is(this,kd,i??{})}get playbackToken(){var i;return(i=this.getAttribute(U.PLAYBACK_TOKEN))!=null?i:void 0}set playbackToken(i){this.setAttribute(U.PLAYBACK_TOKEN,`${i}`)}get drmToken(){var i;return(i=this.getAttribute(U.DRM_TOKEN))!=null?i:void 0}set drmToken(i){this.setAttribute(U.DRM_TOKEN,`${i}`)}get thumbnailToken(){var i;return(i=this.getAttribute(U.THUMBNAIL_TOKEN))!=null?i:void 0}set thumbnailToken(i){this.setAttribute(U.THUMBNAIL_TOKEN,`${i}`)}get storyboardToken(){var i;return(i=this.getAttribute(U.STORYBOARD_TOKEN))!=null?i:void 0}set storyboardToken(i){this.setAttribute(U.STORYBOARD_TOKEN,`${i}`)}addTextTrack(i,e,t,s){var r;let n=(r=this.media)==null?void 0:r.nativeEl;if(n)return ip(n,i,e,t,s)}removeTextTrack(i){var e;let t=(e=this.media)==null?void 0:e.nativeEl;if(t)return lM(t,i)}get textTracks(){var i;return(i=this.media)==null?void 0:i.textTracks}get castReceiver(){var i;return(i=this.getAttribute(U.CAST_RECEIVER))!=null?i:void 0}set castReceiver(i){i!==this.castReceiver&&(i?this.setAttribute(U.CAST_RECEIVER,i):this.removeAttribute(U.CAST_RECEIVER))}get castCustomData(){var i;return(i=this.media)==null?void 0:i.castCustomData}set castCustomData(i){if(!this.media){ai("underlying media element missing when trying to set castCustomData. castCustomData will not be set.");return}this.media.castCustomData=i}get noTooltips(){return this.hasAttribute(U.NO_TOOLTIPS)}set noTooltips(i){if(!i){this.removeAttribute(U.NO_TOOLTIPS);return}this.setAttribute(U.NO_TOOLTIPS,"")}get proudlyDisplayMuxBadge(){return this.hasAttribute(U.PROUDLY_DISPLAY_MUX_BADGE)}set proudlyDisplayMuxBadge(i){i?this.setAttribute(U.PROUDLY_DISPLAY_MUX_BADGE,""):this.removeAttribute(U.PROUDLY_DISPLAY_MUX_BADGE)}};Ld=new WeakMap,Rd=new WeakMap,kd=new WeakMap,mr=new WeakMap,Dd=new WeakMap,qn=new WeakMap,Qe=new WeakSet,$s=function(){var i,e,t,s;if(!De(this,Rd)){is(this,Rd,!0),at(this,Qe,pr).call(this);try{if(customElements.upgrade(this.mediaTheme),!(this.mediaTheme instanceof zi.HTMLElement))throw""}catch{ai("<media-theme> failed to upgrade!")}try{customElements.upgrade(this.media)}catch{ai("underlying media element failed to upgrade!")}try{if(customElements.upgrade(this.mediaController),!(this.mediaController instanceof TE))throw""}catch{ai("<media-controller> failed to upgrade!")}at(this,Qe,Dv).call(this),at(this,Qe,Cv).call(this),at(this,Qe,wv).call(this),is(this,mr,(e=(i=this.mediaController)==null?void 0:i.hasAttribute(ne.USER_INACTIVE))!=null?e:!0),at(this,Qe,Mv).call(this),(t=this.media)==null||t.addEventListener("streamtypechange",()=>at(this,Qe,pr).call(this)),(s=this.media)==null||s.addEventListener("loadstart",()=>at(this,Qe,pr).call(this))}},I_=function(){var i,e;try{(i=window?.CSS)==null||i.registerProperty({name:"--media-primary-color",syntax:"<color>",inherits:!0}),(e=window?.CSS)==null||e.registerProperty({name:"--media-secondary-color",syntax:"<color>",inherits:!0})}catch{}},Xf=function(i){Object.assign(De(this,qn),i),at(this,Qe,pr).call(this)},pr=function(i={}){u2(h2(A2(this,{...De(this,qn),...i})),this.shadowRoot)},Dv=function(){let i=e=>{var t,s;if(!(e!=null&&e.startsWith("theme-")))return;let r=e.replace(/^theme-/,"");if(Qf.includes(r))return;let n=this.getAttribute(e);n!=null?(t=this.mediaTheme)==null||t.setAttribute(r,n):(s=this.mediaTheme)==null||s.removeAttribute(r)};new MutationObserver(e=>{for(let{attributeName:t}of e)i(t)}).observe(this,{attributes:!0}),this.getAttributeNames().forEach(i)},Cv=function(){let i=e=>{var t;let s=(t=this.media)==null?void 0:t.error;if(!(s instanceof X)){let{message:n,code:a}=s??{};s=new X(n,a)}if(!(s!=null&&s.fatal)){ps(s),s.data&&ps(`${s.name} data:`,s.data);return}let r=Av(s);r.message&&b_(r),ai(s),s.data&&ai(`${s.name} data:`,s.data),at(this,Qe,Xf).call(this,{isDialogOpen:!0})};this.addEventListener("error",i),this.media&&(this.media.errorTranslator=(e={})=>{var t,s,r;if(!(((t=this.media)==null?void 0:t.error)instanceof X))return e;let n=Av((s=this.media)==null?void 0:s.error);return{player_error_code:(r=this.media)==null?void 0:r.error.code,player_error_message:n.message?String(n.message):e.player_error_message,player_error_context:n.context?String(n.context):e.player_error_context}})},wv=function(){var i,e,t,s;let r=()=>at(this,Qe,pr).call(this);(e=(i=this.media)==null?void 0:i.textTracks)==null||e.addEventListener("addtrack",r),(s=(t=this.media)==null?void 0:t.textTracks)==null||s.addEventListener("removetrack",r)},Mv=function(){var i,e;if(!/Firefox/i.test(navigator.userAgent))return;let t,s=new WeakMap,r=()=>this.streamType===ke.LIVE&&!this.secondaryColor&&this.offsetWidth>=800,n=(l,d,u=!1)=>{r()||Array.from(l&&l.activeCues||[]).forEach(c=>{if(!(!c.snapToLines||c.line<-5||c.line>=0&&c.line<10))if(!d||this.paused){let h=c.text.split(`
|
|
3385
|
-
`).length,f=-3;this.streamType===ke.LIVE&&(f=-2);let m=f-h;if(c.line===m&&!u)return;s.has(c)||s.set(c,c.line),c.line=m}else setTimeout(()=>{c.line=s.get(c)||"auto"},500)})},a=()=>{var l,d;n(t,(d=(l=this.mediaController)==null?void 0:l.hasAttribute(ne.USER_INACTIVE))!=null?d:!1)},o=()=>{var l,d;let u=Array.from(((d=(l=this.mediaController)==null?void 0:l.media)==null?void 0:d.textTracks)||[]).filter(c=>["subtitles","captions"].includes(c.kind)&&c.mode==="showing")[0];u!==t&&t?.removeEventListener("cuechange",a),t=u,t?.addEventListener("cuechange",a),n(t,De(this,mr))};o(),(i=this.textTracks)==null||i.addEventListener("change",o),(e=this.textTracks)==null||e.addEventListener("addtrack",o),this.addEventListener("userinactivechange",()=>{var l,d;let u=(d=(l=this.mediaController)==null?void 0:l.hasAttribute(ne.USER_INACTIVE))!=null?d:!0;De(this,mr)!==u&&(is(this,mr,u),n(t,De(this,mr)))})};function nr(i,e){return i.media?i.media.getAttribute(e):i.getAttribute(e)}var Pv=C2,x_=class{addEventListener(){}removeEventListener(){}dispatchEvent(i){return!0}};if(typeof DocumentFragment>"u"){class i extends x_{}globalThis.DocumentFragment=i}var w2=class extends x_{},M2={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(w2)}},P2={customElements:M2},O2=typeof window>"u"||typeof globalThis.customElements>"u",eh=O2?P2:globalThis;eh.customElements.get("mux-player")||(eh.customElements.define("mux-player",Pv),eh.MuxPlayerElement=Pv);var L_=parseInt(ve.version)>=19,Ov={className:"class",classname:"class",htmlFor:"for",crossOrigin:"crossorigin",viewBox:"viewBox",playsInline:"playsinline",autoPlay:"autoplay",playbackRate:"playbackrate"},N2=i=>i==null,U2=(i,e)=>N2(e)?!1:i in e,$2=i=>i.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`),F2=(i,e)=>{if(!(!L_&&typeof e=="boolean"&&!e)){if(U2(i,Ov))return Ov[i];if(typeof e<"u")return/[A-Z]/.test(i)?$2(i):i}},B2=(i,e)=>!L_&&typeof i=="boolean"?"":i,H2=(i={})=>{let{ref:e,...t}=i;return Object.entries(t).reduce((s,[r,n])=>{let a=F2(r,n);if(!a)return s;let o=B2(n);return s[a]=o,s},{})};function Nv(i,e){if(typeof i=="function")return i(e);i!=null&&(i.current=e)}function G2(...i){return e=>{let t=!1,s=i.map(r=>{let n=Nv(r,e);return!t&&typeof n=="function"&&(t=!0),n});if(t)return()=>{for(let r=0;r<s.length;r++){let n=s[r];typeof n=="function"?n():Nv(i[r],null)}}}}function K2(...i){return Se.useCallback(G2(...i),i)}var V2=Object.prototype.hasOwnProperty,W2=(i,e)=>{if(Object.is(i,e))return!0;if(typeof i!="object"||i===null||typeof e!="object"||e===null)return!1;if(Array.isArray(i))return!Array.isArray(e)||i.length!==e.length?!1:i.some((r,n)=>e[n]===r);let t=Object.keys(i),s=Object.keys(e);if(t.length!==s.length)return!1;for(let r=0;r<t.length;r++)if(!V2.call(e,t[r])||!Object.is(i[t[r]],e[t[r]]))return!1;return!0},R_=(i,e,t)=>!W2(e,i[t]),q2=(i,e,t)=>{i[t]=e},Y2=(i,e,t,s=q2,r=R_)=>Se.useEffect(()=>{let n=t?.current;n&&r(n,e,i)&&s(n,e,i)},[t?.current,e]),wi=Y2,j2=()=>{try{return"3.10.2"}catch{}return"UNKNOWN"},z2=j2(),Q2=()=>z2,Ke=(i,e,t)=>Se.useEffect(()=>{let s=e?.current;if(!s||!t)return;let r=i,n=t;return s.addEventListener(r,n),()=>{s.removeEventListener(r,n)}},[e?.current,t,i]),X2=ve.forwardRef(({children:i,...e},t)=>ve.createElement("mux-player",{suppressHydrationWarning:!0,...H2(e),ref:t},i)),Z2=(i,e)=>{let{onAbort:t,onCanPlay:s,onCanPlayThrough:r,onEmptied:n,onLoadStart:a,onLoadedData:o,onLoadedMetadata:l,onProgress:d,onDurationChange:u,onVolumeChange:c,onRateChange:h,onResize:f,onWaiting:m,onPlay:p,onPlaying:g,onTimeUpdate:v,onPause:b,onSeeking:E,onSeeked:T,onStalled:A,onSuspend:x,onEnded:S,onError:L,onCuePointChange:R,onChapterChange:I,metadata:M,tokens:B,paused:W,playbackId:j,playbackRates:K,currentTime:F,themeProps:Y,extraSourceParams:P,castCustomData:G,_hlsConfig:Z,...$}=e;return wi("tokens",B,i),wi("playbackId",j,i),wi("playbackRates",K,i),wi("metadata",M,i),wi("extraSourceParams",P,i),wi("_hlsConfig",Z,i),wi("themeProps",Y,i),wi("castCustomData",G,i),wi("paused",W,i,(H,se)=>{se!=null&&(se?H.pause():H.play())},(H,se,ge)=>H.hasAttribute("autoplay")&&!H.hasPlayed?!1:R_(H,se,ge)),wi("currentTime",F,i,(H,se)=>{se!=null&&(H.currentTime=se)}),Ke("abort",i,t),Ke("canplay",i,s),Ke("canplaythrough",i,r),Ke("emptied",i,n),Ke("loadstart",i,a),Ke("loadeddata",i,o),Ke("loadedmetadata",i,l),Ke("progress",i,d),Ke("durationchange",i,u),Ke("volumechange",i,c),Ke("ratechange",i,h),Ke("resize",i,f),Ke("waiting",i,m),Ke("play",i,p),Ke("playing",i,g),Ke("timeupdate",i,v),Ke("pause",i,b),Ke("seeking",i,E),Ke("seeked",i,T),Ke("stalled",i,A),Ke("suspend",i,x),Ke("ended",i,S),Ke("error",i,L),Ke("cuepointchange",i,R),Ke("chapterchange",i,I),[$]},J2=Q2(),eN="mux-player-react",tN=ve.forwardRef((i,e)=>{var t;let s=Se.useRef(null),r=K2(s,e),[n]=Z2(s,i),[a]=Se.useState((t=i.playerInitTime)!=null?t:ap());return ve.createElement(X2,{ref:r,defaultHiddenCaptions:i.defaultHiddenCaptions,playerSoftwareName:eN,playerSoftwareVersion:J2,playerInitTime:a,...n})}),iN=tN;const sN=U_({time:F_(),expiresAt:$_()}).transform(i=>({time:Number(i.time),expiresAt:new Date(i.expiresAt)}));function k_(){const i=Gv(),t=M_().find(s=>s.formAction==="/video-player");if(t&&t.state!=="idle"){const s=t.json;if(s)return{...i.preferences?.player,...s}}return i.preferences?.player??null}function Uv(i){const e=Se.useRef(i);return Se.useEffect(()=>{e.current=i},[i]),e}function rN({muxPlayerRef:i,...e}){const t=k_(),s=Bv(),[r,n]=Se.useState(!1),a=`${e.playbackId}:currentTime`,[o,l]=Se.useState(0),d=Uv(s),u=Uv(t);Se.useEffect(()=>{if(typeof document>"u")return;const h=sessionStorage.getItem(a);if(h)try{const{time:f,expiresAt:m}=sN.parse(JSON.parse(h));if(m.getTime()<Date.now())throw new Error("Time expired");l(f)}catch{sessionStorage.removeItem(a)}},[a]);const c=N_(()=>{const h=i.current;if(!h)return;const f=Array.from(h.textTracks??[]).find(p=>p.kind==="subtitles"),m={playbackRate:h.playbackRate,volumeRate:h.volume,subtitle:f?{id:f.id,mode:f.mode}:{id:null,mode:"disabled"}};Zf(m,u.current)||d.current.submit(m,{method:"POST",action:"/video-player",encType:"application/json"})},300);return Se.useEffect(()=>{if(!r)return;const h=i.current?.textTracks;if(!h)return;const f=setTimeout(()=>{const m=u.current?.subtitle;if(m?.id)try{const p=h.getTrackById(m.id);p&&(p.mode=m.mode??"hidden")}catch(p){console.warn("Failed to restore subtitle preferences:",p)}},100);return h.addEventListener("change",c),()=>{clearTimeout(f),h.removeEventListener("change",c)}},[r,i,u,c]),N.jsx("div",{className:"flex aspect-video flex-col",children:N.jsx(iN,{ref:i,playbackRates:[.5,.75,.8,.9,1,1.25,1.5,1.75,2,2.5,3,3.5,4],volume:t?.volumeRate??1,playbackRate:t?.playbackRate??1,thumbnailTime:o,onRateChange:c,onVolumeChange:c,streamType:"on-demand",defaultHiddenCaptions:!0,currentTime:o,onTimeUpdate:()=>sessionStorage.setItem(a,JSON.stringify({time:i.current?.currentTime,expiresAt:new Date(Date.now()+1e3*60*30).toISOString()})),accentColor:"#427cf0",targetLiveWindow:NaN,minResolution:nN(t?.minResolution),maxResolution:aN(t?.maxResolution),onLoadedMetadata:()=>n(!0),...e})})}function Zf(i,e){if(i===e)return!0;if(typeof i!=typeof e||typeof i!="object"||typeof e!="object"||i===null||e===null||Array.isArray(i)!==Array.isArray(e))return!1;if(Array.isArray(i)&&Array.isArray(e)){if(i.length!==e.length)return!1;for(let r=0;r<i.length;r++)if(!Zf(i[r],e[r]))return!1;return!0}const t=Object.keys(i),s=Object.keys(e);if(t.length!==s.length)return!1;for(const r of t)if(!Zf(i[r],e[r]))return!1;return!0}function nN(i){if(i)return i<=480?Xr.noLessThan480p:i<=540?Xr.noLessThan540p:i<=720?Xr.noLessThan720p:i<=1080?Xr.noLessThan1080p:i<=1440?Xr.noLessThan1440p:Xr.noLessThan2160p}function aN(i){if(i)return i<=720?ol.upTo720p:i<=1080?ol.upTo1080p:i<=1440?ol.upTo1440p:ol.upTo2160p}function oN({progress:i,size:e=16,strokeWidth:t=2,className:s}){const r=i===void 0,n=(e-t)/2,a=2*Math.PI*n,o=e/2,l=i!==void 0?Math.min(100,Math.max(0,i)):0,d=a-l/100*a;return N.jsxs("svg",{width:e,height:e,viewBox:`0 0 ${e} ${e}`,className:th(r&&"animate-spin","text-current",s),role:"progressbar","aria-valuenow":r?void 0:l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":r?"Downloading...":`Download progress: ${l}%`,children:[N.jsx("circle",{cx:o,cy:o,r:n,fill:"none",stroke:"currentColor",strokeWidth:t,opacity:.25}),N.jsx("circle",{cx:o,cy:o,r:n,fill:"none",stroke:"currentColor",strokeWidth:t,strokeLinecap:"round",strokeDasharray:a,strokeDashoffset:r?a*.75:d,transform:`rotate(-90 ${o} ${o})`,className:th(!r&&"transition-[stroke-dashoffset] duration-300 ease-out")})]})}function lN(i){return N.jsx("svg",{viewBox:"0 0 20 20","aria-hidden":"true",...i,children:N.jsx("path",{fill:"currentColor",d:"M10 2a1 1 0 0 1 1 1v7.59l2.3-2.3a1 1 0 1 1 1.4 1.42l-4 4a1 1 0 0 1-1.4 0l-4-4a1 1 0 1 1 1.4-1.42l2.3 2.3V3a1 1 0 0 1 1-1Zm-6 12a1 1 0 0 1 1 1v1h10v-1a1 1 0 1 1 2 0v2a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-2a1 1 0 0 1 1-1Z"})})}function dN(i){return N.jsxs("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",...i,children:[N.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"M6.75 7.75L7.59115 17.4233C7.68102 18.4568 8.54622 19.25 9.58363 19.25H14.4164C15.4538 19.25 16.319 18.4568 16.4088 17.4233L17.25 7.75"}),N.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"M9.75 7.5V6.75C9.75 5.64543 10.6454 4.75 11.75 4.75H12.25C13.3546 4.75 14.25 5.64543 14.25 6.75V7.5"}),N.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"M5 7.75H19"})]})}function uN({isAvailable:i,isBusy:e=!1,downloadProgress:t,onDownload:s,onDelete:r}){const n=e&&!i,a=n,o=i?"Delete offline video":n?t!==void 0?`Downloading: ${Math.round(t)}%`:"Downloading...":"Download offline video",l=i?r:s,d=i?"text-foreground-destructive hover:bg-foreground-destructive/10":"text-foreground hover:bg-muted";return N.jsx(B_,{content:o,children:N.jsx("button",{type:"button",onClick:l,disabled:e,className:`${d} inline-flex h-7 w-7 items-center justify-center rounded disabled:cursor-not-allowed disabled:opacity-50`,"aria-label":o,children:a?N.jsx(oN,{progress:t,size:16,strokeWidth:2,className:"h-4 w-4"}):i?N.jsx(dN,{className:"h-4 w-4"}):N.jsx(lN,{className:"h-4 w-4"})})})}const D_=Se.createContext(null),$v={best:"best available",high:"high",medium:"medium",low:"low"};function cN(i){return i==="high"||i==="medium"||i==="low"?$v[i]:$v.best}function hN(i,e){const[t,s]=Se.useState(!1),[r,n]=Se.useState(!1),a=`/resources/offline-videos/${encodeURIComponent(i)}`;return Se.useEffect(()=>{if(typeof window>"u")return;s(!1),n(!1);const o=new AbortController;let l=!0;return fetch(a,{method:"HEAD",signal:o.signal}).then(d=>{l&&s(d.ok)}).catch(()=>{l&&s(!1)}).finally(()=>{l&&n(!0)}),()=>{l=!1,o.abort()}},[a,e]),{available:t,checked:r,offlineUrl:a}}function fN(){return N.jsx("div",{className:"relative aspect-video w-full shrink-0 shadow-lg",children:N.jsx("div",{className:"text-foreground-destructive absolute inset-0 z-10 flex items-center justify-center p-8",children:N.jsx(Jf,{name:"WifiNoConnection",size:"xl",children:N.jsxs("span",{children:["Offline video not available. Download offline videos in"," ",N.jsx(Ln,{to:"/preferences",className:"underline",children:"Preferences"}),"."]})})})})}function n3({children:i,epicVideoInfosPromise:e}){return N.jsx(D_.Provider,{value:e,children:i})}function C_(i){let e=new URL("https://epicweb.dev");try{e=new URL(i)}catch(c){return console.error(c),"Epic Video"}const t=e.pathname.split("/").filter(Boolean),s=t.includes("solution");let r=t.pop();const n=["problem","solution","embed","exercise"],a=c=>c&&!n.includes(c);for(;!a(r);)r=t.pop();if(!r)return"Epic Video";r=r.replace(/~[^ ]*$/,"");const o=r.split("-"),l=["the","a","an","and","but","or","for","nor","on","at","to","from","by","of","in","with","as","npm","git","ssh","cli"],d=["OAuth","UI","UX","API","CSS","HTML","JS","TS","SVG","AI","CSRF","CORS","HTTP","HTTPS","URL","URI","DB","SQL","JSON","YAML","YML","useActionData","useAsyncError","useAsyncValue","useBeforeUnload","useFetcher","useFetchers","useFormAction","useHref","useLoaderData","useLocation","useMatches","useNavigate","useNavigation","useNavigationType","useOutlet","useOutletContext","useParams","useResolvedPath","useRevalidator","useRouteError","useRouteLoaderData","useSearchParams","useSubmit","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useReducer","useRef","useState","useSyncExternalStore","useTransition","useForm","useFieldset","useFieldList","useEventSource","useHydrated","useAuthenticityToken","useShouldHydrate","useGlobalNavigationState","useLocales","useDelegatedAnchors","useDebounceFetcher","useFetcherType"],u=o.filter(Boolean).map((c,h)=>{const f=c.toLowerCase(),m=d.find(p=>p.toLowerCase()===f);return m||(l.includes(f)&&h>0?f:f[0]?.toUpperCase()+f.slice(1))}).join(" ");return s?`${u} (🏁 solution)`:u}function mN({url:i,title:e="Video Embed",loadingContent:t=N.jsx(yu,{children:N.jsxs("span",{children:['Loading "',e,'"']})})}){const s=Hv(),[r,n]=Se.useState(!1);return Kv()?N.jsxs("div",{className:"relative aspect-video w-full shrink-0 shadow-lg",children:[r?null:N.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center p-8",children:t}),N.jsx("iframe",{onLoad:()=>n(!0),onError:()=>n(!0),src:i,className:th("absolute inset-0 flex h-full w-full transition-opacity duration-300",r?"opacity-100":"opacity-0"),title:e,sandbox:"allow-forms allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox",allowFullScreen:!0,style:{colorScheme:s}})]}):N.jsx("div",{className:"not-prose relative aspect-video w-full shrink-0 shadow-lg",children:N.jsx("div",{className:"text-foreground-destructive absolute inset-0 z-10 flex items-center justify-center p-8",children:N.jsx(Jf,{name:"WifiNoConnection",size:"xl",children:N.jsxs("span",{children:["Unable to load the video ",N.jsx("a",{href:i,className:"underline",children:`"${e??i}"`})," when offline"]})})})})}function w_({url:i,title:e,duration:t,durationEstimate:s,actions:r}){return N.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-base",children:[r?N.jsx("span",{className:"flex items-center gap-1",children:r}):null,t?N.jsx("span",{className:"opacity-70",children:Fv(t)}):s?N.jsxs("span",{className:"opacity-70",children:["~",Fv(s)]}):null,N.jsxs("a",{href:i,target:"_blank",className:"flex items-center gap-1 no-underline opacity-70 transition hover:underline hover:opacity-100",rel:"noreferrer",children:[N.jsx(Jf,{className:"shrink-0",name:"Video",size:"lg"}),e," ",N.jsx("span",{"aria-hidden":!0,children:"↗︎"})]})]})}function a3({url:i,title:e}){const t=e??C_(i),{product:{host:s,displayName:r}}=G_(),n=H_(),a=Se.useContext(D_),o=N.jsx(w_,{url:i,title:t});return N.jsx("div",{className:"not-prose",children:N.jsx(Se.Suspense,{fallback:N.jsxs("div",{children:[N.jsx("div",{className:"flex aspect-video w-full items-center justify-center",children:N.jsx(yu,{children:t})}),N.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[o,N.jsx("div",{className:"h-[32px]"})]})]}),children:N.jsx(P_,{errorElement:N.jsx("div",{children:"Sorry, failed loading videos. Check the terminal output?"}),resolve:a,children:l=>{const d=l?.[i],u=ENV.EPICSHOP_DEPLOYED?N.jsxs("div",{children:[N.jsx(Ln,{to:ENV.EPICSHOP_GITHUB_REPO,className:"underline",children:"Run locally"})," for transcripts"]}):N.jsxs("div",{children:[N.jsx(Ln,{to:"/login",className:"underline",children:n?"Upgrade":"Login"})," for transcripts"]});if(!d)return N.jsxs("div",{children:[N.jsx(Ea,{url:i,title:t}),N.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[o,u]})]});const c=d;return c.status==="success"?N.jsx(pN,{url:i,title:e??c.title??t,muxPlaybackId:c.muxPlaybackId,transcript:c.transcript,duration:c.duration,durationEstimate:c.durationEstimate}):c.type==="region-restricted"?N.jsxs("div",{children:[N.jsxs("div",{className:"flex aspect-video min-h-full min-w-full flex-col items-center justify-start gap-2 overflow-y-scroll border-2 p-4 lg:justify-center lg:gap-4 lg:text-xl",children:[N.jsx("div",{className:"text-foreground-destructive",children:"Error: Region Restricted"}),N.jsxs("div",{children:["We've detected you're connecting from"," ",c.requestCountry," but your license has restricted access to ",c.restrictedCountry]}),N.jsxs("div",{children:["To continue watching uninterrupted, please"," ",N.jsxs("a",{href:`https://${s}/products`,className:"underline",children:["upgrade your ",r," license"]})," ","to a full Pro license."]})]}),N.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[o,N.jsxs("div",{children:[N.jsx(Ln,{to:`https://${s}/products`,className:"underline",children:"Upgrade"})," for transcripts"]})]})]}):c.statusCode===401?N.jsxs("div",{children:[N.jsx(Ea,{url:i,title:t}),N.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[o,u]})]}):c.statusCode===403?N.jsxs("div",{children:[N.jsx(Ea,{url:i,title:t}),N.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[o,N.jsxs("div",{children:[N.jsx(Ln,{to:`https://${s}/products`,className:"underline",children:"Upgrade"})," for transcripts"]})]})]}):c.statusCode===404?N.jsxs("div",{children:[N.jsx(Ea,{url:i,title:t}),N.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[o,N.jsx("div",{children:"Transcripts not found"})]})]}):(console.error(c),N.jsxs("div",{children:[N.jsx(Ea,{url:i,title:t}),N.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[o,N.jsx("div",{className:"text-foreground-destructive",children:"Unknown error (check console)"})]})]}))}})})})}function pN({url:i,title:e=C_(i),muxPlaybackId:t,transcript:s,duration:r,durationEstimate:n}){const a=Se.useRef(null),o=Se.useRef(null),l=Kv(),d=k_(),u=Gv(),c=cN(u.preferences?.offlineVideo?.downloadResolution),[h,f]=Se.useState(0),m=hN(t,h),p=m.available,g=Bv(),v=g.state!=="idle",[b,E]=Se.useState(void 0),T=v&&!m.available,A=O_(`/resources/offline-video-progress/${encodeURIComponent(t)}`,{enabled:T});Se.useEffect(()=>{if(A)try{const P=JSON.parse(A);if(P.status==="complete"||P.status==="error"){E(void 0);return}if(P.totalBytes&&P.totalBytes>0){const G=P.bytesDownloaded/P.totalBytes*100;E(G)}else E(void 0)}catch{}},[A]),Se.useEffect(()=>{T||E(void 0)},[T]);const x=`${t}:currentTime`,[S,L]=Se.useState(null),R=/(\d+:\d+)/g,I=[];let M,B=0;for(;M=R.exec(s);){const P=M[1];if(!R.lastIndex||!P)break;const G=M.index,Z=R.lastIndex,$=s.slice(B+1,G-1);I.push(N.jsx("span",{children:$},`span-${G}`)),I.push(N.jsx("button",{className:"underline",onClick:H=>{const se=o.current??a.current;if(se){se.currentTime=gN(P);try{se.play().catch(()=>{})}catch{}se.scrollIntoView({behavior:"smooth",inline:"center",block:"start"}),H.currentTarget.blur()}},children:P},`button-${G}`)),B=Z}I.push(N.jsx("span",{children:s.slice(B+1,s.length)},s.length)),Se.useEffect(()=>{o.current&&(typeof d?.playbackRate=="number"&&(o.current.playbackRate=d.playbackRate),typeof d?.volumeRate=="number"&&(o.current.volume=d.volumeRate))},[d?.playbackRate,d?.volumeRate,p]),Se.useEffect(()=>{if(!p||typeof document>"u")return;const P=sessionStorage.getItem(x);if(!P){L(null);return}try{const G=JSON.parse(P),Z=G.expiresAt?new Date(G.expiresAt).getTime():0;if(typeof G.time!="number"||Number.isNaN(G.time)||!Z||Z<Date.now())throw new Error("Time expired");L(G.time)}catch{sessionStorage.removeItem(x),L(null)}},[x,p]),Se.useEffect(()=>{if(!p)return;const P=o.current;if(!P||S==null)return;const G=()=>{const Z=Number.isFinite(P.duration)?P.duration:0,$=Z?Math.min(S,Math.max(Z-1,0)):S;$>0&&(P.currentTime=$)};if(P.readyState>=1){G();return}return P.addEventListener("loadedmetadata",G),()=>{P.removeEventListener("loadedmetadata",G)}},[S,p]);const W=Se.useCallback(()=>{if(typeof document>"u")return;const P=o.current;if(!P)return;const G=Number.isFinite(P.duration)?P.duration:0;if(G&&G-P.currentTime<=1){sessionStorage.removeItem(x);return}sessionStorage.setItem(x,JSON.stringify({time:P.currentTime,expiresAt:new Date(Date.now()+1e3*60*30).toISOString()}))},[x]);Se.useEffect(()=>{g.state==="idle"&&g.data?.status&&f(P=>P+1)},[g.state,g.data]),Se.useEffect(()=>{if(g.state!=="idle")return;const P=g.data;if(!P||P.action!=="download"||P.status!=="error")return;const G=P.message??"Offline video download failed. Check the terminal logs.";$p.error("Offline video download failed",{description:G})},[g.state,g.data]);const j=Se.useCallback(()=>{$p.success(`Download of ${e} has started (${c} quality).`,{description:N.jsxs("span",{children:["Go to"," ",N.jsx(Ln,{className:"underline",to:"/preferences",children:"Preferences"})," ","to download all workshop videos at once."]})}),g.submit({intent:"download-video",playbackId:t,title:e,url:i},{method:"post",action:"/resources/offline-videos"})},[t,g,e,i,c]),K=Se.useCallback(()=>{g.submit({intent:"delete-video",playbackId:t},{method:"post",action:"/resources/offline-videos"})},[t,g]),F=Se.useCallback(P=>{P&&P.setAttribute("seekoffset","10")},[]),Y=N.jsx(uN,{isAvailable:m.available,isBusy:v,downloadProgress:b,onDownload:j,onDelete:K});return N.jsxs("div",{children:[N.jsx("div",{className:"shadow-lg",children:p?N.jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-black",children:N.jsxs(gI,{tabIndex:0,"aria-label":`${e} video player`,onPointerDown:P=>{P.currentTarget.focus()},className:"focus-visible:ring-ring flex h-full w-full flex-col justify-end outline-none focus-visible:ring-2 focus-visible:ring-offset-2",style:{"--media-primary-color":"hsl(var(--background))","--media-text-color":"hsl(var(--background))","--media-secondary-color":"transparent","--media-control-background":"transparent","--media-control-hover-background":"hsl(var(--background) / 0.18)","--media-control-height":"18px","--media-range-padding":"2px","--media-time-range-hover-height":"18px","--media-time-range-hover-bottom":"-4px","--media-range-track-height":"3px","--media-range-thumb-height":"8px","--media-range-thumb-width":"8px","--media-range-track-background":"hsl(var(--background) / 0.35)","--media-range-track-pointer-background":"hsl(var(--background) / 0.85)"},children:[N.jsx("video",{ref:o,slot:"media","aria-label":e,className:"h-full w-full",playsInline:!0,preload:"metadata",src:m.offlineUrl,onTimeUpdate:W}),N.jsxs("div",{className:"bg-foreground/40 text-background w-full space-y-1 px-3 pt-1 pb-1.5 text-sm leading-none backdrop-blur select-none",children:[N.jsx(xI,{className:"w-full"}),N.jsxs(vI,{className:"w-full items-center gap-3",children:[N.jsxs("div",{className:"flex items-center gap-3",children:[N.jsx(_I,{}),N.jsx(AI,{ref:F,seekOffset:10}),N.jsx(SI,{ref:F,seekOffset:10}),N.jsx(II,{showDuration:!0,className:"text-background text-xs tabular-nums"}),N.jsx(yI,{}),N.jsx(LI,{className:"w-24"})]}),N.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[N.jsx(TI,{className:"text-background text-xs",rates:[.5,.75,.8,.9,1,1.25,1.5,1.75,2,2.5,3,3.5,4]}),N.jsx(bI,{}),N.jsx(EI,{})]})]})]})]})}):!l&&m.checked?N.jsx(fN,{}):l?N.jsx(rN,{playbackId:t,muxPlayerRef:a,title:e}):N.jsx("div",{className:"flex aspect-video w-full items-center justify-center",children:N.jsx(yu,{children:"Checking offline videos..."})})}),N.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[N.jsx(w_,{url:i,title:e,duration:r,durationEstimate:n,actions:Y}),N.jsxs("details",{children:[N.jsx("summary",{children:"Transcript"}),N.jsx("div",{className:"bg-accent text-accent-foreground rounded-md p-2 whitespace-pre-line",children:I})]})]})]})}function gN(i){const e=i.split(":");let t=0,s=1;for(;e.length>0;)t+=s*parseInt(e.pop()??"0",10),s*=60;return t}function Fv(i){const e=Math.floor(i/3600),t=Math.floor(i%3600/60),s=Math.floor(i%60);return e>0?`${e}:${t.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`:`${t}:${s.toString().padStart(2,"0")}`}function Ea({url:i,title:e}){const t=Hv();let s=new URL("https://epicweb.dev");try{s=new URL(i)}catch(r){return console.error(r),N.jsxs("div",{children:['Invalid URL: "',i,'"']})}return s.pathname=s.pathname.endsWith("/")?`${s.pathname}embed`:`${s.pathname}/embed`,s.searchParams.set("theme",t),s.host==="www.epicai.pro"&&!s.pathname.startsWith("/workshops/")&&(s.pathname=`/posts/${s.pathname}`),N.jsx(mN,{url:s.toString(),title:e,loadingContent:N.jsx(yu,{children:N.jsxs("span",{children:['Loading "',N.jsx("a",{className:"underline",href:i,children:e}),'"']})})})}export{a3 as D,n3 as E,mN as V};
|
|
3386
|
-
//# sourceMappingURL=epic-video-
|
|
3384
|
+
`}return S2(i)};function I2(i){var e,t;let s=i.theme;if(s){let r=(t=(e=i.getRootNode())==null?void 0:e.getElementById)==null?void 0:t.call(e,s);if(r&&r instanceof HTMLTemplateElement)return r;s.startsWith("media-theme-")||(s=`media-theme-${s}`);let n=zi.customElements.get(s);if(n!=null&&n.template)return n.template}}function x2(i){var e;let t=(e=i.mediaController)==null?void 0:e.querySelector("media-time-display");return t&&getComputedStyle(t).getPropertyValue("--media-duration-display-display").trim()==="none"}function xv(i){let e=i.videoTitle?{video_title:i.videoTitle}:{};return i.getAttributeNames().filter(t=>t.startsWith("metadata-")).reduce((t,s)=>{let r=i.getAttribute(s);return r!==null&&(t[s.replace(/^metadata-/,"").replace(/-/g,"_")]=r),t},e)}var L2=Object.values(C),R2=Object.values(cs),k2=Object.values(F),Lv=E_(),Rv="mux-player",kv={isDialogOpen:!1},D2={redundant_streams:!0},Ld,Rd,kd,mr,Dd,qn,Qe,$s,I_,Xf,pr,Dv,Cv,wv,Mv,C2=class extends bv{constructor(){super(),Ti(this,Qe),Ti(this,Ld),Ti(this,Rd,!1),Ti(this,kd,{}),Ti(this,mr,!0),Ti(this,Dd,new jO(this,"hotkeys")),Ti(this,qn,{...kv,onCloseErrorDialog:i=>{var e;((e=i.composedPath()[0])==null?void 0:e.localName)==="media-error-dialog"&&at(this,Qe,Xf).call(this,{isDialogOpen:!1})},onFocusInErrorDialog:i=>{var e;((e=i.composedPath()[0])==null?void 0:e.localName)==="media-error-dialog"&&(g_(this,Eu.activeElement)||i.preventDefault())}}),is(this,Ld,ap()),this.attachShadow({mode:"open"}),at(this,Qe,I_).call(this),this.isConnected&&at(this,Qe,$s).call(this)}static get NAME(){return Rv}static get VERSION(){return Lv}static get observedAttributes(){var i;return[...(i=bv.observedAttributes)!=null?i:[],...R2,...L2,...k2]}get mediaTheme(){var i;return(i=this.shadowRoot)==null?void 0:i.querySelector("media-theme")}get mediaController(){var i,e;return(e=(i=this.mediaTheme)==null?void 0:i.shadowRoot)==null?void 0:e.querySelector("media-controller")}connectedCallback(){let i=this.media;i&&(i.metadata=xv(this))}attributeChangedCallback(i,e,t){switch(at(this,Qe,$s).call(this),super.attributeChangedCallback(i,e,t),i){case F.HOTKEYS:De(this,Dd).value=t;break;case F.THUMBNAIL_TIME:{t!=null&&this.tokens.thumbnail&&ps(se("Use of thumbnail-time with thumbnail-token is currently unsupported. Ignore thumbnail-time.").toString());break}case F.THUMBNAIL_TOKEN:{if(t){let s=Bn(t);if(s){let{aud:r}=s,n=Za.THUMBNAIL;r!==n&&ps(se("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"thumbnail"}))}}break}case F.STORYBOARD_TOKEN:{if(t){let s=Bn(t);if(s){let{aud:r}=s,n=Za.STORYBOARD;r!==n&&ps(se("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"storyboard"}))}}break}case F.DRM_TOKEN:{if(t){let s=Bn(t);if(s){let{aud:r}=s,n=Za.DRM;r!==n&&ps(se("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"drm"}))}}break}case C.PLAYBACK_ID:{t!=null&&t.includes("?token")&&ai(se("The specificed playback ID {playbackId} contains a token which must be provided via the playback-token attribute.").format({playbackId:t}));break}case C.STREAM_TYPE:{t&&![ke.LIVE,ke.ON_DEMAND,ke.UNKNOWN].includes(t)?["ll-live","live:dvr","ll-live:dvr"].includes(this.streamType)?this.targetLiveWindow=t.includes("dvr")?Number.POSITIVE_INFINITY:0:b_({file:"invalid-stream-type.md",message:se("Invalid stream-type value supplied: `{streamType}`. Please provide stream-type as either: `on-demand` or `live`").format({streamType:this.streamType})}):t===ke.LIVE?this.getAttribute(F.TARGET_LIVE_WINDOW)==null&&(this.targetLiveWindow=0):this.targetLiveWindow=Number.NaN;break}case F.FULLSCREEN_ELEMENT:{if(t!=null||t!==e){let s=Eu.getElementById(t),r=s?.querySelector("mux-player");this.mediaController&&s&&r&&(this.mediaController.fullscreenElement=s)}break}}[C.PLAYBACK_ID,cs.SRC,F.PLAYBACK_TOKEN].includes(i)&&e!==t&&is(this,qn,{...De(this,qn),...kv}),at(this,Qe,pr).call(this,{[YO(i)]:t})}async requestFullscreen(i){var e;if(!(!this.mediaController||this.mediaController.hasAttribute(_.MEDIA_IS_FULLSCREEN)))return(e=this.mediaController)==null||e.dispatchEvent(new zi.CustomEvent(Q.MEDIA_ENTER_FULLSCREEN_REQUEST,{composed:!0,bubbles:!0})),new Promise((t,s)=>{var r;(r=this.mediaController)==null||r.addEventListener(ys.MEDIA_IS_FULLSCREEN,()=>t(),{once:!0})})}async exitFullscreen(){var i;if(!(!this.mediaController||!this.mediaController.hasAttribute(_.MEDIA_IS_FULLSCREEN)))return(i=this.mediaController)==null||i.dispatchEvent(new zi.CustomEvent(Q.MEDIA_EXIT_FULLSCREEN_REQUEST,{composed:!0,bubbles:!0})),new Promise((e,t)=>{var s;(s=this.mediaController)==null||s.addEventListener(ys.MEDIA_IS_FULLSCREEN,()=>e(),{once:!0})})}get preferCmcd(){var i;return(i=this.getAttribute(C.PREFER_CMCD))!=null?i:void 0}set preferCmcd(i){i!==this.preferCmcd&&(i?nu.includes(i)?this.setAttribute(C.PREFER_CMCD,i):ps(`Invalid value for preferCmcd. Must be one of ${nu.join()}`):this.removeAttribute(C.PREFER_CMCD))}get hasPlayed(){var i,e;return(e=(i=this.mediaController)==null?void 0:i.hasAttribute(_.MEDIA_HAS_PLAYED))!=null?e:!1}get inLiveWindow(){var i;return(i=this.mediaController)==null?void 0:i.hasAttribute(_.MEDIA_TIME_IS_LIVE)}get _hls(){var i;return(i=this.media)==null?void 0:i._hls}get mux(){var i;return(i=this.media)==null?void 0:i.mux}get theme(){var i;return(i=this.getAttribute(F.THEME))!=null?i:_2}set theme(i){this.setAttribute(F.THEME,`${i}`)}get themeProps(){let i=this.mediaTheme;if(!i)return;let e={};for(let t of i.getAttributeNames()){if(Qf.includes(t))continue;let s=i.getAttribute(t);e[m_(t)]=s===""?!0:s}return e}set themeProps(i){var e,t;at(this,Qe,$s).call(this);let s={...this.themeProps,...i};for(let r in s){if(Qf.includes(r))continue;let n=i?.[r];typeof n=="boolean"||n==null?(e=this.mediaTheme)==null||e.toggleAttribute(jf(r),!!n):(t=this.mediaTheme)==null||t.setAttribute(jf(r),n)}}get playbackId(){var i;return(i=this.getAttribute(C.PLAYBACK_ID))!=null?i:void 0}set playbackId(i){i?this.setAttribute(C.PLAYBACK_ID,i):this.removeAttribute(C.PLAYBACK_ID)}get src(){var i,e;return this.playbackId?(i=nr(this,cs.SRC))!=null?i:void 0:(e=this.getAttribute(cs.SRC))!=null?e:void 0}set src(i){i?this.setAttribute(cs.SRC,i):this.removeAttribute(cs.SRC)}get poster(){var i;let e=this.getAttribute(cs.POSTER);if(e!=null)return e;let{tokens:t}=this;if(t.playback&&!t.thumbnail){ps("Missing expected thumbnail token. No poster image will be shown");return}if(this.playbackId&&!this.audio)return VO(this.playbackId,{customDomain:this.customDomain,thumbnailTime:(i=this.thumbnailTime)!=null?i:this.startTime,programTime:this.programStartTime,token:t.thumbnail})}set poster(i){i||i===""?this.setAttribute(cs.POSTER,i):this.removeAttribute(cs.POSTER)}get storyboardSrc(){var i;return(i=this.getAttribute(F.STORYBOARD_SRC))!=null?i:void 0}set storyboardSrc(i){i?this.setAttribute(F.STORYBOARD_SRC,i):this.removeAttribute(F.STORYBOARD_SRC)}get storyboard(){let{tokens:i}=this;if(this.storyboardSrc&&!i.storyboard)return this.storyboardSrc;if(!(this.audio||!this.playbackId||!this.streamType||[ke.LIVE,ke.UNKNOWN].includes(this.streamType)||i.playback&&!i.storyboard))return WO(this.playbackId,{customDomain:this.customDomain,token:i.storyboard,programStartTime:this.programStartTime,programEndTime:this.programEndTime})}get audio(){return this.hasAttribute(F.AUDIO)}set audio(i){if(!i){this.removeAttribute(F.AUDIO);return}this.setAttribute(F.AUDIO,"")}get hotkeys(){return De(this,Dd)}get nohotkeys(){return this.hasAttribute(F.NOHOTKEYS)}set nohotkeys(i){if(!i){this.removeAttribute(F.NOHOTKEYS);return}this.setAttribute(F.NOHOTKEYS,"")}get thumbnailTime(){return qt(this.getAttribute(F.THUMBNAIL_TIME))}set thumbnailTime(i){this.setAttribute(F.THUMBNAIL_TIME,`${i}`)}get videoTitle(){var i,e;return(e=(i=this.getAttribute(F.VIDEO_TITLE))!=null?i:this.getAttribute(F.TITLE))!=null?e:""}set videoTitle(i){i!==this.videoTitle&&(i?this.setAttribute(F.VIDEO_TITLE,i):this.removeAttribute(F.VIDEO_TITLE))}get placeholder(){var i;return(i=nr(this,F.PLACEHOLDER))!=null?i:""}set placeholder(i){this.setAttribute(F.PLACEHOLDER,`${i}`)}get primaryColor(){var i,e;let t=this.getAttribute(F.PRIMARY_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=zi.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_primary-color"))==null?void 0:e.trim(),t))return t}set primaryColor(i){this.setAttribute(F.PRIMARY_COLOR,`${i}`)}get secondaryColor(){var i,e;let t=this.getAttribute(F.SECONDARY_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=zi.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_secondary-color"))==null?void 0:e.trim(),t))return t}set secondaryColor(i){this.setAttribute(F.SECONDARY_COLOR,`${i}`)}get accentColor(){var i,e;let t=this.getAttribute(F.ACCENT_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=zi.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_accent-color"))==null?void 0:e.trim(),t))return t}set accentColor(i){this.setAttribute(F.ACCENT_COLOR,`${i}`)}get defaultShowRemainingTime(){return this.hasAttribute(F.DEFAULT_SHOW_REMAINING_TIME)}set defaultShowRemainingTime(i){i?this.setAttribute(F.DEFAULT_SHOW_REMAINING_TIME,""):this.removeAttribute(F.DEFAULT_SHOW_REMAINING_TIME)}get playbackRates(){if(this.hasAttribute(F.PLAYBACK_RATES))return this.getAttribute(F.PLAYBACK_RATES).trim().split(/\s*,?\s+/).map(i=>Number(i)).filter(i=>!Number.isNaN(i)).sort((i,e)=>i-e)}set playbackRates(i){if(!i){this.removeAttribute(F.PLAYBACK_RATES);return}this.setAttribute(F.PLAYBACK_RATES,i.join(" "))}get forwardSeekOffset(){var i;return(i=qt(this.getAttribute(F.FORWARD_SEEK_OFFSET)))!=null?i:10}set forwardSeekOffset(i){this.setAttribute(F.FORWARD_SEEK_OFFSET,`${i}`)}get backwardSeekOffset(){var i;return(i=qt(this.getAttribute(F.BACKWARD_SEEK_OFFSET)))!=null?i:10}set backwardSeekOffset(i){this.setAttribute(F.BACKWARD_SEEK_OFFSET,`${i}`)}get defaultHiddenCaptions(){return this.hasAttribute(F.DEFAULT_HIDDEN_CAPTIONS)}set defaultHiddenCaptions(i){i?this.setAttribute(F.DEFAULT_HIDDEN_CAPTIONS,""):this.removeAttribute(F.DEFAULT_HIDDEN_CAPTIONS)}get defaultDuration(){return qt(this.getAttribute(F.DEFAULT_DURATION))}set defaultDuration(i){i==null?this.removeAttribute(F.DEFAULT_DURATION):this.setAttribute(F.DEFAULT_DURATION,`${i}`)}get playerInitTime(){return this.hasAttribute(C.PLAYER_INIT_TIME)?qt(this.getAttribute(C.PLAYER_INIT_TIME)):De(this,Ld)}set playerInitTime(i){i!=this.playerInitTime&&(i==null?this.removeAttribute(C.PLAYER_INIT_TIME):this.setAttribute(C.PLAYER_INIT_TIME,`${+i}`))}get playerSoftwareName(){var i;return(i=this.getAttribute(C.PLAYER_SOFTWARE_NAME))!=null?i:Rv}get playerSoftwareVersion(){var i;return(i=this.getAttribute(C.PLAYER_SOFTWARE_VERSION))!=null?i:Lv}get beaconCollectionDomain(){var i;return(i=this.getAttribute(C.BEACON_COLLECTION_DOMAIN))!=null?i:void 0}set beaconCollectionDomain(i){i!==this.beaconCollectionDomain&&(i?this.setAttribute(C.BEACON_COLLECTION_DOMAIN,i):this.removeAttribute(C.BEACON_COLLECTION_DOMAIN))}get maxResolution(){var i;return(i=this.getAttribute(C.MAX_RESOLUTION))!=null?i:void 0}set maxResolution(i){i!==this.maxResolution&&(i?this.setAttribute(C.MAX_RESOLUTION,i):this.removeAttribute(C.MAX_RESOLUTION))}get minResolution(){var i;return(i=this.getAttribute(C.MIN_RESOLUTION))!=null?i:void 0}set minResolution(i){i!==this.minResolution&&(i?this.setAttribute(C.MIN_RESOLUTION,i):this.removeAttribute(C.MIN_RESOLUTION))}get maxAutoResolution(){var i;return(i=this.getAttribute(C.MAX_AUTO_RESOLUTION))!=null?i:void 0}set maxAutoResolution(i){i==null?this.removeAttribute(C.MAX_AUTO_RESOLUTION):this.setAttribute(C.MAX_AUTO_RESOLUTION,i)}get renditionOrder(){var i;return(i=this.getAttribute(C.RENDITION_ORDER))!=null?i:void 0}set renditionOrder(i){i!==this.renditionOrder&&(i?this.setAttribute(C.RENDITION_ORDER,i):this.removeAttribute(C.RENDITION_ORDER))}get programStartTime(){return qt(this.getAttribute(C.PROGRAM_START_TIME))}set programStartTime(i){i==null?this.removeAttribute(C.PROGRAM_START_TIME):this.setAttribute(C.PROGRAM_START_TIME,`${i}`)}get programEndTime(){return qt(this.getAttribute(C.PROGRAM_END_TIME))}set programEndTime(i){i==null?this.removeAttribute(C.PROGRAM_END_TIME):this.setAttribute(C.PROGRAM_END_TIME,`${i}`)}get assetStartTime(){return qt(this.getAttribute(C.ASSET_START_TIME))}set assetStartTime(i){i==null?this.removeAttribute(C.ASSET_START_TIME):this.setAttribute(C.ASSET_START_TIME,`${i}`)}get assetEndTime(){return qt(this.getAttribute(C.ASSET_END_TIME))}set assetEndTime(i){i==null?this.removeAttribute(C.ASSET_END_TIME):this.setAttribute(C.ASSET_END_TIME,`${i}`)}get extraSourceParams(){return this.hasAttribute(F.EXTRA_SOURCE_PARAMS)?[...new URLSearchParams(this.getAttribute(F.EXTRA_SOURCE_PARAMS)).entries()].reduce((i,[e,t])=>(i[e]=t,i),{}):D2}set extraSourceParams(i){i==null?this.removeAttribute(F.EXTRA_SOURCE_PARAMS):this.setAttribute(F.EXTRA_SOURCE_PARAMS,new URLSearchParams(i).toString())}get customDomain(){var i;return(i=this.getAttribute(C.CUSTOM_DOMAIN))!=null?i:void 0}set customDomain(i){i!==this.customDomain&&(i?this.setAttribute(C.CUSTOM_DOMAIN,i):this.removeAttribute(C.CUSTOM_DOMAIN))}get envKey(){var i;return(i=nr(this,C.ENV_KEY))!=null?i:void 0}set envKey(i){this.setAttribute(C.ENV_KEY,`${i}`)}get noVolumePref(){return this.hasAttribute(F.NO_VOLUME_PREF)}set noVolumePref(i){i?this.setAttribute(F.NO_VOLUME_PREF,""):this.removeAttribute(F.NO_VOLUME_PREF)}get noMutedPref(){return this.hasAttribute(F.NO_MUTED_PREF)}set noMutedPref(i){i?this.setAttribute(F.NO_MUTED_PREF,""):this.removeAttribute(F.NO_MUTED_PREF)}get debug(){return nr(this,C.DEBUG)!=null}set debug(i){i?this.setAttribute(C.DEBUG,""):this.removeAttribute(C.DEBUG)}get disableTracking(){return nr(this,C.DISABLE_TRACKING)!=null}set disableTracking(i){this.toggleAttribute(C.DISABLE_TRACKING,!!i)}get disableCookies(){return nr(this,C.DISABLE_COOKIES)!=null}set disableCookies(i){i?this.setAttribute(C.DISABLE_COOKIES,""):this.removeAttribute(C.DISABLE_COOKIES)}get streamType(){var i,e,t;return(t=(e=this.getAttribute(C.STREAM_TYPE))!=null?e:(i=this.media)==null?void 0:i.streamType)!=null?t:ke.UNKNOWN}set streamType(i){this.setAttribute(C.STREAM_TYPE,`${i}`)}get defaultStreamType(){var i,e,t;return(t=(e=this.getAttribute(F.DEFAULT_STREAM_TYPE))!=null?e:(i=this.mediaController)==null?void 0:i.getAttribute(F.DEFAULT_STREAM_TYPE))!=null?t:ke.ON_DEMAND}set defaultStreamType(i){i?this.setAttribute(F.DEFAULT_STREAM_TYPE,i):this.removeAttribute(F.DEFAULT_STREAM_TYPE)}get targetLiveWindow(){var i,e;return this.hasAttribute(F.TARGET_LIVE_WINDOW)?+this.getAttribute(F.TARGET_LIVE_WINDOW):(e=(i=this.media)==null?void 0:i.targetLiveWindow)!=null?e:Number.NaN}set targetLiveWindow(i){i==this.targetLiveWindow||Number.isNaN(i)&&Number.isNaN(this.targetLiveWindow)||(i==null?this.removeAttribute(F.TARGET_LIVE_WINDOW):this.setAttribute(F.TARGET_LIVE_WINDOW,`${+i}`))}get liveEdgeStart(){var i;return(i=this.media)==null?void 0:i.liveEdgeStart}get startTime(){return qt(nr(this,C.START_TIME))}set startTime(i){this.setAttribute(C.START_TIME,`${i}`)}get preferPlayback(){let i=this.getAttribute(C.PREFER_PLAYBACK);if(i===Zi.MSE||i===Zi.NATIVE)return i}set preferPlayback(i){i!==this.preferPlayback&&(i===Zi.MSE||i===Zi.NATIVE?this.setAttribute(C.PREFER_PLAYBACK,i):this.removeAttribute(C.PREFER_PLAYBACK))}get metadata(){var i;return(i=this.media)==null?void 0:i.metadata}set metadata(i){if(at(this,Qe,$s).call(this),!this.media){ai("underlying media element missing when trying to set metadata. metadata will not be set.");return}this.media.metadata={...xv(this),...i}}get _hlsConfig(){var i;return(i=this.media)==null?void 0:i._hlsConfig}set _hlsConfig(i){if(at(this,Qe,$s).call(this),!this.media){ai("underlying media element missing when trying to set _hlsConfig. _hlsConfig will not be set.");return}this.media._hlsConfig=i}async addCuePoints(i){var e;if(at(this,Qe,$s).call(this),!this.media){ai("underlying media element missing when trying to addCuePoints. cuePoints will not be added.");return}return(e=this.media)==null?void 0:e.addCuePoints(i)}get activeCuePoint(){var i;return(i=this.media)==null?void 0:i.activeCuePoint}get cuePoints(){var i,e;return(e=(i=this.media)==null?void 0:i.cuePoints)!=null?e:[]}addChapters(i){var e;if(at(this,Qe,$s).call(this),!this.media){ai("underlying media element missing when trying to addChapters. chapters will not be added.");return}return(e=this.media)==null?void 0:e.addChapters(i)}get activeChapter(){var i;return(i=this.media)==null?void 0:i.activeChapter}get chapters(){var i,e;return(e=(i=this.media)==null?void 0:i.chapters)!=null?e:[]}getStartDate(){var i;return(i=this.media)==null?void 0:i.getStartDate()}get currentPdt(){var i;return(i=this.media)==null?void 0:i.currentPdt}get tokens(){let i=this.getAttribute(F.PLAYBACK_TOKEN),e=this.getAttribute(F.DRM_TOKEN),t=this.getAttribute(F.THUMBNAIL_TOKEN),s=this.getAttribute(F.STORYBOARD_TOKEN);return{...De(this,kd),...i!=null?{playback:i}:{},...e!=null?{drm:e}:{},...t!=null?{thumbnail:t}:{},...s!=null?{storyboard:s}:{}}}set tokens(i){is(this,kd,i??{})}get playbackToken(){var i;return(i=this.getAttribute(F.PLAYBACK_TOKEN))!=null?i:void 0}set playbackToken(i){this.setAttribute(F.PLAYBACK_TOKEN,`${i}`)}get drmToken(){var i;return(i=this.getAttribute(F.DRM_TOKEN))!=null?i:void 0}set drmToken(i){this.setAttribute(F.DRM_TOKEN,`${i}`)}get thumbnailToken(){var i;return(i=this.getAttribute(F.THUMBNAIL_TOKEN))!=null?i:void 0}set thumbnailToken(i){this.setAttribute(F.THUMBNAIL_TOKEN,`${i}`)}get storyboardToken(){var i;return(i=this.getAttribute(F.STORYBOARD_TOKEN))!=null?i:void 0}set storyboardToken(i){this.setAttribute(F.STORYBOARD_TOKEN,`${i}`)}addTextTrack(i,e,t,s){var r;let n=(r=this.media)==null?void 0:r.nativeEl;if(n)return ip(n,i,e,t,s)}removeTextTrack(i){var e;let t=(e=this.media)==null?void 0:e.nativeEl;if(t)return lM(t,i)}get textTracks(){var i;return(i=this.media)==null?void 0:i.textTracks}get castReceiver(){var i;return(i=this.getAttribute(F.CAST_RECEIVER))!=null?i:void 0}set castReceiver(i){i!==this.castReceiver&&(i?this.setAttribute(F.CAST_RECEIVER,i):this.removeAttribute(F.CAST_RECEIVER))}get castCustomData(){var i;return(i=this.media)==null?void 0:i.castCustomData}set castCustomData(i){if(!this.media){ai("underlying media element missing when trying to set castCustomData. castCustomData will not be set.");return}this.media.castCustomData=i}get noTooltips(){return this.hasAttribute(F.NO_TOOLTIPS)}set noTooltips(i){if(!i){this.removeAttribute(F.NO_TOOLTIPS);return}this.setAttribute(F.NO_TOOLTIPS,"")}get proudlyDisplayMuxBadge(){return this.hasAttribute(F.PROUDLY_DISPLAY_MUX_BADGE)}set proudlyDisplayMuxBadge(i){i?this.setAttribute(F.PROUDLY_DISPLAY_MUX_BADGE,""):this.removeAttribute(F.PROUDLY_DISPLAY_MUX_BADGE)}};Ld=new WeakMap,Rd=new WeakMap,kd=new WeakMap,mr=new WeakMap,Dd=new WeakMap,qn=new WeakMap,Qe=new WeakSet,$s=function(){var i,e,t,s;if(!De(this,Rd)){is(this,Rd,!0),at(this,Qe,pr).call(this);try{if(customElements.upgrade(this.mediaTheme),!(this.mediaTheme instanceof zi.HTMLElement))throw""}catch{ai("<media-theme> failed to upgrade!")}try{customElements.upgrade(this.media)}catch{ai("underlying media element failed to upgrade!")}try{if(customElements.upgrade(this.mediaController),!(this.mediaController instanceof TE))throw""}catch{ai("<media-controller> failed to upgrade!")}at(this,Qe,Dv).call(this),at(this,Qe,Cv).call(this),at(this,Qe,wv).call(this),is(this,mr,(e=(i=this.mediaController)==null?void 0:i.hasAttribute(ne.USER_INACTIVE))!=null?e:!0),at(this,Qe,Mv).call(this),(t=this.media)==null||t.addEventListener("streamtypechange",()=>at(this,Qe,pr).call(this)),(s=this.media)==null||s.addEventListener("loadstart",()=>at(this,Qe,pr).call(this))}},I_=function(){var i,e;try{(i=window?.CSS)==null||i.registerProperty({name:"--media-primary-color",syntax:"<color>",inherits:!0}),(e=window?.CSS)==null||e.registerProperty({name:"--media-secondary-color",syntax:"<color>",inherits:!0})}catch{}},Xf=function(i){Object.assign(De(this,qn),i),at(this,Qe,pr).call(this)},pr=function(i={}){u2(h2(A2(this,{...De(this,qn),...i})),this.shadowRoot)},Dv=function(){let i=e=>{var t,s;if(!(e!=null&&e.startsWith("theme-")))return;let r=e.replace(/^theme-/,"");if(Qf.includes(r))return;let n=this.getAttribute(e);n!=null?(t=this.mediaTheme)==null||t.setAttribute(r,n):(s=this.mediaTheme)==null||s.removeAttribute(r)};new MutationObserver(e=>{for(let{attributeName:t}of e)i(t)}).observe(this,{attributes:!0}),this.getAttributeNames().forEach(i)},Cv=function(){let i=e=>{var t;let s=(t=this.media)==null?void 0:t.error;if(!(s instanceof Z)){let{message:n,code:a}=s??{};s=new Z(n,a)}if(!(s!=null&&s.fatal)){ps(s),s.data&&ps(`${s.name} data:`,s.data);return}let r=Av(s);r.message&&b_(r),ai(s),s.data&&ai(`${s.name} data:`,s.data),at(this,Qe,Xf).call(this,{isDialogOpen:!0})};this.addEventListener("error",i),this.media&&(this.media.errorTranslator=(e={})=>{var t,s,r;if(!(((t=this.media)==null?void 0:t.error)instanceof Z))return e;let n=Av((s=this.media)==null?void 0:s.error);return{player_error_code:(r=this.media)==null?void 0:r.error.code,player_error_message:n.message?String(n.message):e.player_error_message,player_error_context:n.context?String(n.context):e.player_error_context}})},wv=function(){var i,e,t,s;let r=()=>at(this,Qe,pr).call(this);(e=(i=this.media)==null?void 0:i.textTracks)==null||e.addEventListener("addtrack",r),(s=(t=this.media)==null?void 0:t.textTracks)==null||s.addEventListener("removetrack",r)},Mv=function(){var i,e;if(!/Firefox/i.test(navigator.userAgent))return;let t,s=new WeakMap,r=()=>this.streamType===ke.LIVE&&!this.secondaryColor&&this.offsetWidth>=800,n=(l,d,u=!1)=>{r()||Array.from(l&&l.activeCues||[]).forEach(c=>{if(!(!c.snapToLines||c.line<-5||c.line>=0&&c.line<10))if(!d||this.paused){let h=c.text.split(`
|
|
3385
|
+
`).length,f=-3;this.streamType===ke.LIVE&&(f=-2);let m=f-h;if(c.line===m&&!u)return;s.has(c)||s.set(c,c.line),c.line=m}else setTimeout(()=>{c.line=s.get(c)||"auto"},500)})},a=()=>{var l,d;n(t,(d=(l=this.mediaController)==null?void 0:l.hasAttribute(ne.USER_INACTIVE))!=null?d:!1)},o=()=>{var l,d;let u=Array.from(((d=(l=this.mediaController)==null?void 0:l.media)==null?void 0:d.textTracks)||[]).filter(c=>["subtitles","captions"].includes(c.kind)&&c.mode==="showing")[0];u!==t&&t?.removeEventListener("cuechange",a),t=u,t?.addEventListener("cuechange",a),n(t,De(this,mr))};o(),(i=this.textTracks)==null||i.addEventListener("change",o),(e=this.textTracks)==null||e.addEventListener("addtrack",o),this.addEventListener("userinactivechange",()=>{var l,d;let u=(d=(l=this.mediaController)==null?void 0:l.hasAttribute(ne.USER_INACTIVE))!=null?d:!0;De(this,mr)!==u&&(is(this,mr,u),n(t,De(this,mr)))})};function nr(i,e){return i.media?i.media.getAttribute(e):i.getAttribute(e)}var Pv=C2,x_=class{addEventListener(){}removeEventListener(){}dispatchEvent(i){return!0}};if(typeof DocumentFragment>"u"){class i extends x_{}globalThis.DocumentFragment=i}var w2=class extends x_{},M2={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(w2)}},P2={customElements:M2},O2=typeof window>"u"||typeof globalThis.customElements>"u",eh=O2?P2:globalThis;eh.customElements.get("mux-player")||(eh.customElements.define("mux-player",Pv),eh.MuxPlayerElement=Pv);var L_=parseInt(ve.version)>=19,Ov={className:"class",classname:"class",htmlFor:"for",crossOrigin:"crossorigin",viewBox:"viewBox",playsInline:"playsinline",autoPlay:"autoplay",playbackRate:"playbackrate"},N2=i=>i==null,U2=(i,e)=>N2(e)?!1:i in e,$2=i=>i.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`),F2=(i,e)=>{if(!(!L_&&typeof e=="boolean"&&!e)){if(U2(i,Ov))return Ov[i];if(typeof e<"u")return/[A-Z]/.test(i)?$2(i):i}},B2=(i,e)=>!L_&&typeof i=="boolean"?"":i,H2=(i={})=>{let{ref:e,...t}=i;return Object.entries(t).reduce((s,[r,n])=>{let a=F2(r,n);if(!a)return s;let o=B2(n);return s[a]=o,s},{})};function Nv(i,e){if(typeof i=="function")return i(e);i!=null&&(i.current=e)}function G2(...i){return e=>{let t=!1,s=i.map(r=>{let n=Nv(r,e);return!t&&typeof n=="function"&&(t=!0),n});if(t)return()=>{for(let r=0;r<s.length;r++){let n=s[r];typeof n=="function"?n():Nv(i[r],null)}}}}function K2(...i){return Se.useCallback(G2(...i),i)}var V2=Object.prototype.hasOwnProperty,W2=(i,e)=>{if(Object.is(i,e))return!0;if(typeof i!="object"||i===null||typeof e!="object"||e===null)return!1;if(Array.isArray(i))return!Array.isArray(e)||i.length!==e.length?!1:i.some((r,n)=>e[n]===r);let t=Object.keys(i),s=Object.keys(e);if(t.length!==s.length)return!1;for(let r=0;r<t.length;r++)if(!V2.call(e,t[r])||!Object.is(i[t[r]],e[t[r]]))return!1;return!0},R_=(i,e,t)=>!W2(e,i[t]),q2=(i,e,t)=>{i[t]=e},Y2=(i,e,t,s=q2,r=R_)=>Se.useEffect(()=>{let n=t?.current;n&&r(n,e,i)&&s(n,e,i)},[t?.current,e]),wi=Y2,j2=()=>{try{return"3.10.2"}catch{}return"UNKNOWN"},z2=j2(),Q2=()=>z2,Ke=(i,e,t)=>Se.useEffect(()=>{let s=e?.current;if(!s||!t)return;let r=i,n=t;return s.addEventListener(r,n),()=>{s.removeEventListener(r,n)}},[e?.current,t,i]),X2=ve.forwardRef(({children:i,...e},t)=>ve.createElement("mux-player",{suppressHydrationWarning:!0,...H2(e),ref:t},i)),Z2=(i,e)=>{let{onAbort:t,onCanPlay:s,onCanPlayThrough:r,onEmptied:n,onLoadStart:a,onLoadedData:o,onLoadedMetadata:l,onProgress:d,onDurationChange:u,onVolumeChange:c,onRateChange:h,onResize:f,onWaiting:m,onPlay:p,onPlaying:g,onTimeUpdate:v,onPause:b,onSeeking:E,onSeeked:T,onStalled:A,onSuspend:x,onEnded:S,onError:L,onCuePointChange:R,onChapterChange:I,metadata:M,tokens:B,paused:q,playbackId:z,playbackRates:K,currentTime:H,themeProps:j,extraSourceParams:G,castCustomData:N,_hlsConfig:W,...U}=e;return wi("tokens",B,i),wi("playbackId",z,i),wi("playbackRates",K,i),wi("metadata",M,i),wi("extraSourceParams",G,i),wi("_hlsConfig",W,i),wi("themeProps",j,i),wi("castCustomData",N,i),wi("paused",q,i,($,re)=>{re!=null&&(re?$.pause():$.play())},($,re,he)=>$.hasAttribute("autoplay")&&!$.hasPlayed?!1:R_($,re,he)),wi("currentTime",H,i,($,re)=>{re!=null&&($.currentTime=re)}),Ke("abort",i,t),Ke("canplay",i,s),Ke("canplaythrough",i,r),Ke("emptied",i,n),Ke("loadstart",i,a),Ke("loadeddata",i,o),Ke("loadedmetadata",i,l),Ke("progress",i,d),Ke("durationchange",i,u),Ke("volumechange",i,c),Ke("ratechange",i,h),Ke("resize",i,f),Ke("waiting",i,m),Ke("play",i,p),Ke("playing",i,g),Ke("timeupdate",i,v),Ke("pause",i,b),Ke("seeking",i,E),Ke("seeked",i,T),Ke("stalled",i,A),Ke("suspend",i,x),Ke("ended",i,S),Ke("error",i,L),Ke("cuepointchange",i,R),Ke("chapterchange",i,I),[U]},J2=Q2(),eN="mux-player-react",tN=ve.forwardRef((i,e)=>{var t;let s=Se.useRef(null),r=K2(s,e),[n]=Z2(s,i),[a]=Se.useState((t=i.playerInitTime)!=null?t:ap());return ve.createElement(X2,{ref:r,defaultHiddenCaptions:i.defaultHiddenCaptions,playerSoftwareName:eN,playerSoftwareVersion:J2,playerInitTime:a,...n})}),iN=tN;const sN=U_({time:F_(),expiresAt:$_()}).transform(i=>({time:Number(i.time),expiresAt:new Date(i.expiresAt)}));function k_(){const i=Gv(),t=M_().find(s=>s.formAction==="/video-player");if(t&&t.state!=="idle"){const s=t.json;if(s)return{...i.preferences?.player,...s}}return i.preferences?.player??null}function Uv(i){const e=Se.useRef(i);return Se.useEffect(()=>{e.current=i},[i]),e}function rN({muxPlayerRef:i,...e}){const t=k_(),s=Bv(),[r,n]=Se.useState(!1),a=`${e.playbackId}:currentTime`,[o,l]=Se.useState(0),d=Uv(s),u=Uv(t);Se.useEffect(()=>{if(typeof document>"u")return;const h=sessionStorage.getItem(a);if(h)try{const{time:f,expiresAt:m}=sN.parse(JSON.parse(h));if(m.getTime()<Date.now())throw new Error("Time expired");l(f)}catch{sessionStorage.removeItem(a)}},[a]);const c=N_(()=>{const h=i.current;if(!h)return;const f=Array.from(h.textTracks??[]).find(p=>p.kind==="subtitles"),m={playbackRate:h.playbackRate,volumeRate:h.volume,subtitle:f?{id:f.id,mode:f.mode}:{id:null,mode:"disabled"}};Zf(m,u.current)||d.current.submit(m,{method:"POST",action:"/video-player",encType:"application/json"})},300);return Se.useEffect(()=>{if(!r)return;const h=i.current?.textTracks;if(!h)return;const f=setTimeout(()=>{const m=u.current?.subtitle;if(m?.id)try{const p=h.getTrackById(m.id);p&&(p.mode=m.mode??"hidden")}catch(p){console.warn("Failed to restore subtitle preferences:",p)}},100);return h.addEventListener("change",c),()=>{clearTimeout(f),h.removeEventListener("change",c)}},[r,i,u,c]),O.jsx("div",{className:"flex aspect-video flex-col",children:O.jsx(iN,{ref:i,playbackRates:[.5,.75,.8,.9,1,1.25,1.5,1.75,2,2.5,3,3.5,4],volume:t?.volumeRate??1,playbackRate:t?.playbackRate??1,thumbnailTime:o,onRateChange:c,onVolumeChange:c,streamType:"on-demand",defaultHiddenCaptions:!0,currentTime:o,onTimeUpdate:()=>sessionStorage.setItem(a,JSON.stringify({time:i.current?.currentTime,expiresAt:new Date(Date.now()+1e3*60*30).toISOString()})),accentColor:"#427cf0",targetLiveWindow:NaN,minResolution:nN(t?.minResolution),maxResolution:aN(t?.maxResolution),onLoadedMetadata:()=>n(!0),...e})})}function Zf(i,e){if(i===e)return!0;if(typeof i!=typeof e||typeof i!="object"||typeof e!="object"||i===null||e===null||Array.isArray(i)!==Array.isArray(e))return!1;if(Array.isArray(i)&&Array.isArray(e)){if(i.length!==e.length)return!1;for(let r=0;r<i.length;r++)if(!Zf(i[r],e[r]))return!1;return!0}const t=Object.keys(i),s=Object.keys(e);if(t.length!==s.length)return!1;for(const r of t)if(!Zf(i[r],e[r]))return!1;return!0}function nN(i){if(i)return i<=480?Xr.noLessThan480p:i<=540?Xr.noLessThan540p:i<=720?Xr.noLessThan720p:i<=1080?Xr.noLessThan1080p:i<=1440?Xr.noLessThan1440p:Xr.noLessThan2160p}function aN(i){if(i)return i<=720?ol.upTo720p:i<=1080?ol.upTo1080p:i<=1440?ol.upTo1440p:ol.upTo2160p}function oN({progress:i,size:e=16,strokeWidth:t=2,className:s}){const r=i===void 0,n=(e-t)/2,a=2*Math.PI*n,o=e/2,l=i!==void 0?Math.min(100,Math.max(0,i)):0,d=a-l/100*a;return O.jsxs("svg",{width:e,height:e,viewBox:`0 0 ${e} ${e}`,className:th(r&&"animate-spin","text-current",s),role:"progressbar","aria-valuenow":r?void 0:l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":r?"Downloading...":`Download progress: ${l}%`,children:[O.jsx("circle",{cx:o,cy:o,r:n,fill:"none",stroke:"currentColor",strokeWidth:t,opacity:.25}),O.jsx("circle",{cx:o,cy:o,r:n,fill:"none",stroke:"currentColor",strokeWidth:t,strokeLinecap:"round",strokeDasharray:a,strokeDashoffset:r?a*.75:d,transform:`rotate(-90 ${o} ${o})`,className:th(!r&&"transition-[stroke-dashoffset] duration-300 ease-out")})]})}function lN(i){return O.jsx("svg",{viewBox:"0 0 20 20","aria-hidden":"true",...i,children:O.jsx("path",{fill:"currentColor",d:"M10 2a1 1 0 0 1 1 1v7.59l2.3-2.3a1 1 0 1 1 1.4 1.42l-4 4a1 1 0 0 1-1.4 0l-4-4a1 1 0 1 1 1.4-1.42l2.3 2.3V3a1 1 0 0 1 1-1Zm-6 12a1 1 0 0 1 1 1v1h10v-1a1 1 0 1 1 2 0v2a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-2a1 1 0 0 1 1-1Z"})})}function dN(i){return O.jsxs("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",...i,children:[O.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"M6.75 7.75L7.59115 17.4233C7.68102 18.4568 8.54622 19.25 9.58363 19.25H14.4164C15.4538 19.25 16.319 18.4568 16.4088 17.4233L17.25 7.75"}),O.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"M9.75 7.5V6.75C9.75 5.64543 10.6454 4.75 11.75 4.75H12.25C13.3546 4.75 14.25 5.64543 14.25 6.75V7.5"}),O.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"M5 7.75H19"})]})}function uN({isAvailable:i,isBusy:e=!1,downloadProgress:t,onDownload:s,onDelete:r}){const n=e&&!i,a=n,o=i?"Delete offline video":n?t!==void 0?`Downloading: ${Math.round(t)}%`:"Downloading...":"Download offline video",l=i?r:s,d=i?"text-foreground-destructive hover:bg-foreground-destructive/10":"text-foreground hover:bg-muted";return O.jsx(B_,{content:o,children:O.jsx("button",{type:"button",onClick:l,disabled:e,className:`${d} inline-flex h-7 w-7 items-center justify-center rounded disabled:cursor-not-allowed disabled:opacity-50`,"aria-label":o,children:a?O.jsx(oN,{progress:t,size:16,strokeWidth:2,className:"h-4 w-4"}):i?O.jsx(dN,{className:"h-4 w-4"}):O.jsx(lN,{className:"h-4 w-4"})})})}const D_=Se.createContext(null),$v={best:"best available",high:"high",medium:"medium",low:"low"};function cN(i){return i==="high"||i==="medium"||i==="low"?$v[i]:$v.best}function hN(i,e){const[t,s]=Se.useState(!1),[r,n]=Se.useState(!1),a=`/resources/offline-videos/${encodeURIComponent(i)}`;return Se.useEffect(()=>{if(typeof window>"u")return;s(!1),n(!1);const o=new AbortController;let l=!0;return fetch(a,{method:"HEAD",signal:o.signal}).then(d=>{l&&s(d.ok)}).catch(()=>{l&&s(!1)}).finally(()=>{l&&n(!0)}),()=>{l=!1,o.abort()}},[a,e]),{available:t,checked:r,offlineUrl:a}}function fN(){return O.jsx("div",{className:"relative aspect-video w-full shrink-0 shadow-lg",children:O.jsx("div",{className:"text-foreground-destructive absolute inset-0 z-10 flex items-center justify-center p-8",children:O.jsx(Jf,{name:"WifiNoConnection",size:"xl",children:O.jsxs("span",{children:["Offline video not available. Download offline videos in"," ",O.jsx(Ln,{to:"/preferences",className:"underline",children:"Preferences"}),"."]})})})})}function n3({children:i,epicVideoInfosPromise:e}){return O.jsx(D_.Provider,{value:e,children:i})}function C_(i){let e=new URL("https://epicweb.dev");try{e=new URL(i)}catch(c){return console.error(c),"Epic Video"}const t=e.pathname.split("/").filter(Boolean),s=t.includes("solution");let r=t.pop();const n=["problem","solution","embed","exercise"],a=c=>c&&!n.includes(c);for(;!a(r);)r=t.pop();if(!r)return"Epic Video";r=r.replace(/~[^ ]*$/,"");const o=r.split("-"),l=["the","a","an","and","but","or","for","nor","on","at","to","from","by","of","in","with","as","npm","git","ssh","cli"],d=["OAuth","UI","UX","API","CSS","HTML","JS","TS","SVG","AI","CSRF","CORS","HTTP","HTTPS","URL","URI","DB","SQL","JSON","YAML","YML","useActionData","useAsyncError","useAsyncValue","useBeforeUnload","useFetcher","useFetchers","useFormAction","useHref","useLoaderData","useLocation","useMatches","useNavigate","useNavigation","useNavigationType","useOutlet","useOutletContext","useParams","useResolvedPath","useRevalidator","useRouteError","useRouteLoaderData","useSearchParams","useSubmit","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useReducer","useRef","useState","useSyncExternalStore","useTransition","useForm","useFieldset","useFieldList","useEventSource","useHydrated","useAuthenticityToken","useShouldHydrate","useGlobalNavigationState","useLocales","useDelegatedAnchors","useDebounceFetcher","useFetcherType"],u=o.filter(Boolean).map((c,h)=>{const f=c.toLowerCase(),m=d.find(p=>p.toLowerCase()===f);return m||(l.includes(f)&&h>0?f:f[0]?.toUpperCase()+f.slice(1))}).join(" ");return s?`${u} (🏁 solution)`:u}function mN({url:i,title:e="Video Embed",loadingContent:t=O.jsx(yu,{children:O.jsxs("span",{children:['Loading "',e,'"']})})}){const s=Hv(),[r,n]=Se.useState(!1);return Kv()?O.jsxs("div",{className:"relative aspect-video w-full shrink-0 shadow-lg",children:[r?null:O.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center p-8",children:t}),O.jsx("iframe",{onLoad:()=>n(!0),onError:()=>n(!0),src:i,className:th("absolute inset-0 flex h-full w-full transition-opacity duration-300",r?"opacity-100":"opacity-0"),title:e,sandbox:"allow-forms allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox",allowFullScreen:!0,style:{colorScheme:s}})]}):O.jsx("div",{className:"not-prose relative aspect-video w-full shrink-0 shadow-lg",children:O.jsx("div",{className:"text-foreground-destructive absolute inset-0 z-10 flex items-center justify-center p-8",children:O.jsx(Jf,{name:"WifiNoConnection",size:"xl",children:O.jsxs("span",{children:["Unable to load the video ",O.jsx("a",{href:i,className:"underline",children:`"${e??i}"`})," when offline"]})})})})}function w_({url:i,title:e,duration:t,durationEstimate:s,actions:r}){return O.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-base",children:[r?O.jsx("span",{className:"flex items-center gap-1",children:r}):null,t?O.jsx("span",{className:"opacity-70",children:Fv(t)}):s?O.jsxs("span",{className:"opacity-70",children:["~",Fv(s)]}):null,O.jsxs("a",{href:i,target:"_blank",className:"flex items-center gap-1 no-underline opacity-70 transition hover:underline hover:opacity-100",rel:"noreferrer",children:[O.jsx(Jf,{className:"shrink-0",name:"Video",size:"lg"}),e," ",O.jsx("span",{"aria-hidden":!0,children:"↗︎"})]})]})}function a3({url:i,title:e}){const t=e??C_(i),{product:{host:s,displayName:r}}=G_(),n=H_(),a=Se.useContext(D_),o=O.jsx(w_,{url:i,title:t});return O.jsx("div",{className:"not-prose",children:O.jsx(Se.Suspense,{fallback:O.jsxs("div",{children:[O.jsx("div",{className:"flex aspect-video w-full items-center justify-center",children:O.jsx(yu,{children:t})}),O.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[o,O.jsx("div",{className:"h-[32px]"})]})]}),children:O.jsx(P_,{errorElement:O.jsx("div",{children:"Sorry, failed loading videos. Check the terminal output?"}),resolve:a,children:l=>{const d=l?.[i],u=ENV.EPICSHOP_DEPLOYED?O.jsxs("div",{children:[O.jsx(Ln,{to:ENV.EPICSHOP_GITHUB_REPO,className:"underline",children:"Run locally"})," for transcripts"]}):O.jsxs("div",{children:[O.jsx(Ln,{to:"/login",className:"underline",children:n?"Upgrade":"Login"})," for transcripts"]});if(!d)return O.jsxs("div",{children:[O.jsx(Ea,{url:i,title:t}),O.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[o,u]})]});const c=d;return c.status==="success"?O.jsx(pN,{url:i,title:e??c.title??t,muxPlaybackId:c.muxPlaybackId,transcript:c.transcript,duration:c.duration,durationEstimate:c.durationEstimate}):c.type==="region-restricted"?O.jsxs("div",{children:[O.jsxs("div",{className:"flex aspect-video min-h-full min-w-full flex-col items-center justify-start gap-2 overflow-y-scroll border-2 p-4 lg:justify-center lg:gap-4 lg:text-xl",children:[O.jsx("div",{className:"text-foreground-destructive",children:"Error: Region Restricted"}),O.jsxs("div",{children:["We've detected you're connecting from"," ",c.requestCountry," but your license has restricted access to ",c.restrictedCountry]}),O.jsxs("div",{children:["To continue watching uninterrupted, please"," ",O.jsxs("a",{href:`https://${s}/products`,className:"underline",children:["upgrade your ",r," license"]})," ","to a full Pro license."]})]}),O.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[o,O.jsxs("div",{children:[O.jsx(Ln,{to:`https://${s}/products`,className:"underline",children:"Upgrade"})," for transcripts"]})]})]}):c.statusCode===401?O.jsxs("div",{children:[O.jsx(Ea,{url:i,title:t}),O.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[o,u]})]}):c.statusCode===403?O.jsxs("div",{children:[O.jsx(Ea,{url:i,title:t}),O.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[o,O.jsxs("div",{children:[O.jsx(Ln,{to:`https://${s}/products`,className:"underline",children:"Upgrade"})," for transcripts"]})]})]}):c.statusCode===404?O.jsxs("div",{children:[O.jsx(Ea,{url:i,title:t}),O.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[o,O.jsx("div",{children:"Transcripts not found"})]})]}):(console.error(c),O.jsxs("div",{children:[O.jsx(Ea,{url:i,title:t}),O.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[o,O.jsx("div",{className:"text-foreground-destructive",children:"Unknown error (check console)"})]})]}))}})})})}function pN({url:i,title:e=C_(i),muxPlaybackId:t,transcript:s,duration:r,durationEstimate:n}){const a=Se.useRef(null),o=Se.useRef(null),l=Kv(),d=k_(),u=Gv(),c=cN(u.preferences?.offlineVideo?.downloadResolution),[h,f]=Se.useState(0),m=hN(t,h),p=m.available,g=Bv(),v=g.state!=="idle",[b,E]=Se.useState(void 0),T=v&&!m.available,A=O_(`/resources/offline-video-progress/${encodeURIComponent(t)}`,{enabled:T});Se.useEffect(()=>{if(A)try{const N=JSON.parse(A);if(N.status==="complete"||N.status==="error"){E(void 0);return}if(N.totalBytes&&N.totalBytes>0){const W=N.bytesDownloaded/N.totalBytes*100;E(W)}else E(void 0)}catch{}},[A]),Se.useEffect(()=>{T||E(void 0)},[T]);const x=`${t}:currentTime`,[S,L]=Se.useState(null),R=/(\d+:\d+)/g,I=[];let M,B=0;for(;M=R.exec(s);){const N=M[1];if(!R.lastIndex||!N||M.index==null)break;const W=M.index,U=R.lastIndex;let $=s.slice(B,W);$.endsWith("[")&&($=$.slice(0,-1)),$&&I.push(O.jsx("span",{children:$},`span-${W}`)),I.push(O.jsx("button",{className:"underline",onClick:re=>{const he=o.current??a.current;if(he){he.currentTime=gN(N);try{he.play().catch(()=>{})}catch{}he.scrollIntoView({behavior:"smooth",inline:"center",block:"start"}),re.currentTarget.blur()}},children:N},`button-${W}`)),B=U,s.charAt(B)==="]"&&(B+=1)}const q=s.slice(B);q&&I.push(O.jsx("span",{children:q},s.length)),Se.useEffect(()=>{o.current&&(typeof d?.playbackRate=="number"&&(o.current.playbackRate=d.playbackRate),typeof d?.volumeRate=="number"&&(o.current.volume=d.volumeRate))},[d?.playbackRate,d?.volumeRate,p]),Se.useEffect(()=>{if(!p||typeof document>"u")return;const N=sessionStorage.getItem(x);if(!N){L(null);return}try{const W=JSON.parse(N),U=W.expiresAt?new Date(W.expiresAt).getTime():0;if(typeof W.time!="number"||Number.isNaN(W.time)||!U||U<Date.now())throw new Error("Time expired");L(W.time)}catch{sessionStorage.removeItem(x),L(null)}},[x,p]),Se.useEffect(()=>{if(!p)return;const N=o.current;if(!N||S==null)return;const W=()=>{const U=Number.isFinite(N.duration)?N.duration:0,$=U?Math.min(S,Math.max(U-1,0)):S;$>0&&(N.currentTime=$)};if(N.readyState>=1){W();return}return N.addEventListener("loadedmetadata",W),()=>{N.removeEventListener("loadedmetadata",W)}},[S,p]);const z=Se.useCallback(()=>{if(typeof document>"u")return;const N=o.current;if(!N)return;const W=Number.isFinite(N.duration)?N.duration:0;if(W&&W-N.currentTime<=1){sessionStorage.removeItem(x);return}sessionStorage.setItem(x,JSON.stringify({time:N.currentTime,expiresAt:new Date(Date.now()+1e3*60*30).toISOString()}))},[x]);Se.useEffect(()=>{g.state==="idle"&&g.data?.status&&f(N=>N+1)},[g.state,g.data]),Se.useEffect(()=>{if(g.state!=="idle")return;const N=g.data;if(!N||N.action!=="download"||N.status!=="error")return;const W=N.message??"Offline video download failed. Check the terminal logs.";$p.error("Offline video download failed",{description:W})},[g.state,g.data]);const K=Se.useCallback(()=>{$p.success(`Download of ${e} has started (${c} quality).`,{description:O.jsxs("span",{children:["Go to"," ",O.jsx(Ln,{className:"underline",to:"/preferences",children:"Preferences"})," ","to download all workshop videos at once."]})}),g.submit({intent:"download-video",playbackId:t,title:e,url:i},{method:"post",action:"/resources/offline-videos"})},[t,g,e,i,c]),H=Se.useCallback(()=>{g.submit({intent:"delete-video",playbackId:t},{method:"post",action:"/resources/offline-videos"})},[t,g]),j=Se.useCallback(N=>{N&&N.setAttribute("seekoffset","10")},[]),G=O.jsx(uN,{isAvailable:m.available,isBusy:v,downloadProgress:b,onDownload:K,onDelete:H});return O.jsxs("div",{children:[O.jsx("div",{className:"shadow-lg",children:p?O.jsx("div",{className:"flex aspect-video w-full items-center justify-center bg-black",children:O.jsxs(gI,{tabIndex:0,"aria-label":`${e} video player`,onPointerDown:N=>{N.currentTarget.focus()},className:"focus-visible:ring-ring flex h-full w-full flex-col justify-end outline-none focus-visible:ring-2 focus-visible:ring-offset-2",style:{"--media-primary-color":"hsl(var(--background))","--media-text-color":"hsl(var(--background))","--media-secondary-color":"transparent","--media-control-background":"transparent","--media-control-hover-background":"hsl(var(--background) / 0.18)","--media-control-height":"18px","--media-range-padding":"2px","--media-time-range-hover-height":"18px","--media-time-range-hover-bottom":"-4px","--media-range-track-height":"3px","--media-range-thumb-height":"8px","--media-range-thumb-width":"8px","--media-range-track-background":"hsl(var(--background) / 0.35)","--media-range-track-pointer-background":"hsl(var(--background) / 0.85)"},children:[O.jsx("video",{ref:o,slot:"media","aria-label":e,className:"h-full w-full",playsInline:!0,preload:"metadata",src:m.offlineUrl,onTimeUpdate:z}),O.jsxs("div",{className:"bg-foreground/40 text-background w-full space-y-1 px-3 pt-1 pb-1.5 text-sm leading-none backdrop-blur select-none",children:[O.jsx(xI,{className:"w-full"}),O.jsxs(vI,{className:"w-full items-center gap-3",children:[O.jsxs("div",{className:"flex items-center gap-3",children:[O.jsx(_I,{}),O.jsx(AI,{ref:j,seekOffset:10}),O.jsx(SI,{ref:j,seekOffset:10}),O.jsx(II,{showDuration:!0,className:"text-background text-xs tabular-nums"}),O.jsx(yI,{}),O.jsx(LI,{className:"w-24"})]}),O.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[O.jsx(TI,{className:"text-background text-xs",rates:[.5,.75,.8,.9,1,1.25,1.5,1.75,2,2.5,3,3.5,4]}),O.jsx(bI,{}),O.jsx(EI,{})]})]})]})]})}):!l&&m.checked?O.jsx(fN,{}):l?O.jsx(rN,{playbackId:t,muxPlayerRef:a,title:e}):O.jsx("div",{className:"flex aspect-video w-full items-center justify-center",children:O.jsx(yu,{children:"Checking offline videos..."})})}),O.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[O.jsx(w_,{url:i,title:e,duration:r,durationEstimate:n,actions:G}),O.jsxs("details",{children:[O.jsx("summary",{children:"Transcript"}),O.jsx("div",{className:"bg-accent text-accent-foreground rounded-md p-2 whitespace-pre-line",children:I})]})]})]})}function gN(i){const e=i.split(":");let t=0,s=1;for(;e.length>0;)t+=s*parseInt(e.pop()??"0",10),s*=60;return t}function Fv(i){const e=Math.floor(i/3600),t=Math.floor(i%3600/60),s=Math.floor(i%60);return e>0?`${e}:${t.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`:`${t}:${s.toString().padStart(2,"0")}`}function Ea({url:i,title:e}){const t=Hv();let s=new URL("https://epicweb.dev");try{s=new URL(i)}catch(r){return console.error(r),O.jsxs("div",{children:['Invalid URL: "',i,'"']})}return s.pathname=s.pathname.endsWith("/")?`${s.pathname}embed`:`${s.pathname}/embed`,s.searchParams.set("theme",t),s.host==="www.epicai.pro"&&!s.pathname.startsWith("/workshops/")&&(s.pathname=`/posts/${s.pathname}`),O.jsx(mN,{url:s.toString(),title:e,loadingContent:O.jsx(yu,{children:O.jsxs("span",{children:['Loading "',O.jsx("a",{className:"underline",href:i,children:e}),'"']})})})}export{a3 as D,n3 as E,mN as V};
|
|
3386
|
+
//# sourceMappingURL=epic-video-CBv5iEXI.js.map
|