@maveio/components 0.0.150 → 0.0.151

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.
Files changed (37) hide show
  1. package/dist/{chunk-3GACH56T.js → chunk-2EYY6N7K.js} +1 -1
  2. package/dist/{chunk-VRW6KUQP.js → chunk-AEGY4JNC.js} +1 -1
  3. package/dist/{chunk-NENQOWTM.cjs → chunk-APKCPW3V.cjs} +2 -2
  4. package/dist/{chunk-XSYWRQWB.js → chunk-DH5I55F5.js} +1 -1
  5. package/dist/{chunk-O4SVRXZ6.cjs → chunk-F2VMRZFU.cjs} +1 -1
  6. package/dist/{chunk-6AXROGQC.js → chunk-FDSTNWZP.js} +1 -1
  7. package/dist/{chunk-KDE6VE72.js → chunk-GMEHYYP4.js} +1 -1
  8. package/dist/{chunk-5UMTSGHI.cjs → chunk-LOR3PIH5.cjs} +1 -1
  9. package/dist/{chunk-ABWSEIH3.js → chunk-LX6MMRGQ.js} +1 -1
  10. package/dist/{chunk-3GVDBAOP.cjs → chunk-QJHVSRHC.cjs} +1 -1
  11. package/dist/{chunk-JZVU4QZ4.cjs → chunk-VGWLQHAV.cjs} +2 -2
  12. package/dist/{chunk-DOR5AD7J.js → chunk-WFWUIIE6.js} +1 -1
  13. package/dist/{chunk-P4RYGSTU.cjs → chunk-X3IY737A.cjs} +1 -1
  14. package/dist/{chunk-I6LB6U7R.cjs → chunk-XSVNMS3S.cjs} +1 -1
  15. package/dist/{chunk-KCZRQ4AS.cjs → chunk-Y7NYUH3P.cjs} +1 -1
  16. package/dist/{chunk-GO5AXJUO.js → chunk-ZWTODZDA.js} +1 -1
  17. package/dist/components/clip.cjs +1 -1
  18. package/dist/components/clip.js +1 -1
  19. package/dist/components/files.cjs +1 -1
  20. package/dist/components/files.js +1 -1
  21. package/dist/components/list.cjs +1 -1
  22. package/dist/components/list.js +1 -1
  23. package/dist/components/player.cjs +1 -1
  24. package/dist/components/player.js +1 -1
  25. package/dist/components/pop.cjs +1 -1
  26. package/dist/components/pop.js +1 -1
  27. package/dist/components/text.cjs +1 -1
  28. package/dist/components/text.js +1 -1
  29. package/dist/embed/caption.cjs +1 -1
  30. package/dist/embed/caption.js +1 -1
  31. package/dist/embed/controller.cjs +1 -1
  32. package/dist/embed/controller.js +1 -1
  33. package/dist/index.cjs +1 -1
  34. package/dist/index.js +1 -1
  35. package/dist/react.cjs +1 -1
  36. package/dist/react.js +1 -1
  37. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkKTP5LV2E_cjs=require('./chunk-KTP5LV2E.cjs'),chunkQ22T22LT_cjs=require('./chunk-Q22T22LT.cjs'),chunk5KQJTT3P_cjs=require('./chunk-5KQJTT3P.cjs'),chunkSDKTBB4N_cjs=require('./chunk-SDKTBB4N.cjs'),chunkKCZRQ4AS_cjs=require('./chunk-KCZRQ4AS.cjs'),chunkVW7IKXVI_cjs=require('./chunk-VW7IKXVI.cjs'),chunkFUBUUA7Y_cjs=require('./chunk-FUBUUA7Y.cjs'),chunk5NSCV6C2_cjs=require('./chunk-5NSCV6C2.cjs'),chunk5STN56TL_cjs=require('./chunk-5STN56TL.cjs'),chunkIPA5Q26W_cjs=require('./chunk-IPA5Q26W.cjs');var $={MEDIA_PLAY_REQUEST:"mediaplayrequest",MEDIA_PAUSE_REQUEST:"mediapauserequest",MEDIA_MUTE_REQUEST:"mediamuterequest",MEDIA_UNMUTE_REQUEST:"mediaunmuterequest",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"},Y={MEDIA_CHROME_ATTRIBUTES:"mediachromeattributes",MEDIA_CONTROLLER:"mediacontroller"},ei={MEDIA_AIRPLAY_UNAVAILABLE:"mediaAirplayUnavailable",MEDIA_FULLSCREEN_UNAVAILABLE:"mediaFullscreenUnavailable",MEDIA_PIP_UNAVAILABLE:"mediaPipUnavailable",MEDIA_CAST_UNAVAILABLE:"mediaCastUnavailable",MEDIA_RENDITION_UNAVAILABLE:"mediaRenditionUnavailable",MEDIA_AUDIO_TRACK_UNAVAILABLE:"mediaAudioTrackUnavailable",MEDIA_PAUSED:"mediaPaused",MEDIA_HAS_PLAYED:"mediaHasPlayed",MEDIA_ENDED:"mediaEnded",MEDIA_MUTED:"mediaMuted",MEDIA_VOLUME_LEVEL:"mediaVolumeLevel",MEDIA_VOLUME:"mediaVolume",MEDIA_VOLUME_UNAVAILABLE:"mediaVolumeUnavailable",MEDIA_IS_PIP:"mediaIsPip",MEDIA_IS_CASTING:"mediaIsCasting",MEDIA_IS_AIRPLAYING:"mediaIsAirplaying",MEDIA_SUBTITLES_LIST:"mediaSubtitlesList",MEDIA_SUBTITLES_SHOWING:"mediaSubtitlesShowing",MEDIA_IS_FULLSCREEN:"mediaIsFullscreen",MEDIA_PLAYBACK_RATE:"mediaPlaybackRate",MEDIA_CURRENT_TIME:"mediaCurrentTime",MEDIA_DURATION:"mediaDuration",MEDIA_SEEKABLE:"mediaSeekable",MEDIA_PREVIEW_TIME:"mediaPreviewTime",MEDIA_PREVIEW_IMAGE:"mediaPreviewImage",MEDIA_PREVIEW_COORDS:"mediaPreviewCoords",MEDIA_PREVIEW_CHAPTER:"mediaPreviewChapter",MEDIA_LOADING:"mediaLoading",MEDIA_BUFFERED:"mediaBuffered",MEDIA_STREAM_TYPE:"mediaStreamType",MEDIA_TARGET_LIVE_WINDOW:"mediaTargetLiveWindow",MEDIA_TIME_IS_LIVE:"mediaTimeIsLive",MEDIA_RENDITION_LIST:"mediaRenditionList",MEDIA_RENDITION_SELECTED:"mediaRenditionSelected",MEDIA_AUDIO_TRACK_LIST:"mediaAudioTrackList",MEDIA_AUDIO_TRACK_ENABLED:"mediaAudioTrackEnabled",MEDIA_CHAPTERS_CUES:"mediaChaptersCues"},Yd=Object.entries(ei),T=Yd.reduce((s,[e,t])=>(s[e]=`${t.toLowerCase()}`,s),{}),ti=Yd.reduce((s,[e,t])=>(s[e]=`${t.toLowerCase()}`,s),{USER_INACTIVE:"userinactivechange",BREAKPOINTS_CHANGE:"breakpointchange",BREAKPOINTS_COMPUTED:"breakpointscomputed"});Object.entries(ti).reduce((s,[e,t])=>{let i=T[e];return i&&(s[t]=i),s},{userinactivechange:"userinactive"});var qd=Object.entries(T).reduce((s,[e,t])=>{let i=ti[e];return i&&(s[t]=i),s},{userinactive:"userinactivechange"}),Et={SUBTITLES:"subtitles",CAPTIONS:"captions",CHAPTERS:"chapters",METADATA:"metadata"},ii={DISABLED:"disabled",SHOWING:"showing"};var fa={MOUSE:"mouse",TOUCH:"touch"},je={UNAVAILABLE:"unavailable",UNSUPPORTED:"unsupported"},rt={LIVE:"live",ON_DEMAND:"on-demand",UNKNOWN:"unknown"};var Be={AUDIO_PLAYER:()=>"audio player",VIDEO_PLAYER:()=>"video player",VOLUME:()=>"volume",SEEK:()=>"seek",CLOSED_CAPTIONS:()=>"closed captions",PLAYBACK_RATE:({playbackRate:s=1}={})=>`current playback rate ${s}`,PLAYBACK_TIME:()=>"playback time",MEDIA_LOADING:()=>"media loading",SETTINGS:()=>"settings",AUDIO_TRACKS:()=>"audio tracks",QUALITY:()=>"quality"},le={PLAY:()=>"play",PAUSE:()=>"pause",MUTE:()=>"mute",UNMUTE:()=>"unmute",ENTER_AIRPLAY:()=>"start airplay",EXIT_AIRPLAY:()=>"stop airplay",ENTER_CAST:()=>"start casting",EXIT_CAST:()=>"stop casting",ENTER_FULLSCREEN:()=>"enter fullscreen mode",EXIT_FULLSCREEN:()=>"exit fullscreen mode",ENTER_PIP:()=>"enter picture in picture mode",EXIT_PIP:()=>"exit picture in picture mode",SEEK_FORWARD_N_SECS:({seekOffset:s=30}={})=>`seek forward ${s} seconds`,SEEK_BACK_N_SECS:({seekOffset:s=30}={})=>`seek back ${s} seconds`,SEEK_LIVE:()=>"seek to live",PLAYING_LIVE:()=>"playing live"};function zd(s){return s?.map(nm).join(" ")}function nm(s){if(s){let{id:e,width:t,height:i}=s;return [e,t,i].filter(r=>r!=null).join(":")}}function Xd(s){return s?.map(am).join(" ")}function am(s){if(s){let{id:e,kind:t,language:i,label:r}=s;return [e,t,i,r].filter(n=>n!=null).join(":")}}function Qs(s,e=false){return s.split("_").map(function(t,i){return (i||e?t[0].toUpperCase():t[0].toLowerCase())+t.slice(1).toLowerCase()}).join("")}function jd(s){return typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s)}var Zs=s=>new Promise(e=>setTimeout(e,s));var Qd=[{singular:"hour",plural:"hours"},{singular:"minute",plural:"minutes"},{singular:"second",plural:"seconds"}],om=(s,e)=>{let t=s===1?Qd[e].singular:Qd[e].plural;return `${s} ${t}`},si=s=>{if(!jd(s))return "";let e=Math.abs(s),t=e!==s,i=new Date(0,0,0,0,0,e,0);return `${[i.getHours(),i.getMinutes(),i.getSeconds()].map((o,l)=>o&&om(o,l)).filter(o=>o).join(", ")}${t?" remaining":""}`};function vt(s,e){let t=false;s<0&&(t=true,s=0-s),s=s<0?0:s;let i=Math.floor(s%60),r=Math.floor(s/60%60),n=Math.floor(s/3600),a=Math.floor(e/60%60),o=Math.floor(e/3600);return (isNaN(s)||s===1/0)&&(n=r=i="0"),n=n>0||o>0?n+":":"",r=((n||a>=10)&&r<10?"0"+r:r)+":",i=i<10?"0"+i:i,(t?"-":"")+n+r+i}var Js=(s,e,t=".value")=>{let i=s.querySelector(t);i&&(i.textContent=e);},dm=(s,e)=>{let t=`slot[name="${e}"]`,i=s.shadowRoot.querySelector(t);return i?i.children:[]},er=(s,e)=>dm(s,e)[0],Vt=(s,e)=>!s||!e?false:s.contains(e)?true:Vt(s,e.getRootNode().host),Kt=(s,e)=>{if(!s)return null;let t=s.closest(e);return t||Kt(s.getRootNode().host,e)};function ga(s=document){var e;let t=s?.activeElement;return t?(e=ga(t.shadowRoot))!=null?e:t:null}function Zd(s){var e;let t=(e=s?.getRootNode)==null?void 0:e.call(s);return t instanceof ShadowRoot||t instanceof Document?t:null}function Jd(s,e=3){if(s.checkVisibility)return s.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});let t=s;for(;t&&e>0;){let i=getComputedStyle(t);if(i.opacity==="0"||i.visibility==="hidden"||i.display==="none")return false;t=t.parentElement,e--;}return true}function ec(s,e,t,i){let r=ma(t,i),n=ma(t,{x:s,y:e}),a=ma(i,{x:s,y:e});return n>r||a>r?n>a?1:0:n/r}function ma(s,e){return Math.sqrt(Math.pow(e.x-s.x,2)+Math.pow(e.y-s.y,2))}function ce(s,e){let t=cm(s,i=>i===e);return t||pa(s,e)}function cm(s,e){var t;let i;for(i of s.querySelectorAll("style")){let r;try{r=(t=i.sheet)==null?void 0:t.cssRules;}catch{continue}for(let n of r??[])if(e(n.selectorText))return n}}function pa(s,e){var t,i;let r=(t=s.querySelectorAll("style"))!=null?t:[],n=r?.[r.length-1];return n?.sheet?(n?.sheet.insertRule(`${e}{}`,n.sheet.cssRules.length),(i=n.sheet.cssRules)==null?void 0:i[n.sheet.cssRules.length-1]):(console.warn("Media Chrome: No style sheet found on style tag of",s),{style:{setProperty:()=>{},removeProperty:()=>"",getPropertyValue:()=>""}})}function oe(s,e,t=Number.NaN){let i=s.getAttribute(e);return i!=null?+i:t}function me(s,e,t){let i=+t;if(t==null||Number.isNaN(i)){s.hasAttribute(e)&&s.removeAttribute(e);return}oe(s,e,void 0)!==i&&s.setAttribute(e,`${i}`);}function re(s,e){return s.hasAttribute(e)}function ie(s,e,t){if(t==null){s.hasAttribute(e)&&s.removeAttribute(e);return}re(s,e)!=t&&s.toggleAttribute(e,t);}function Ae(s,e,t=null){var i;return (i=s.getAttribute(e))!=null?i:t}function ge(s,e,t){if(t==null){s.hasAttribute(e)&&s.removeAttribute(e);return}let i=`${t}`;Ae(s,e,void 0)!==i&&s.setAttribute(e,i);}var tr=class{addEventListener(){}removeEventListener(){}dispatchEvent(){return true}},Ea=class{observe(){}unobserve(){}disconnect(){}},tc={createElement:function(){return new ir.HTMLElement},createElementNS:function(){return new ir.HTMLElement},addEventListener(){},removeEventListener(){}},ir={ResizeObserver:Ea,document:tc,HTMLElement:class extends tr{},DocumentFragment:class extends tr{},customElements:{get:function(){},define:function(){},whenDefined:function(){}},CustomEvent:function(){},getComputedStyle:function(){},navigator:{languages:[],get userAgent(){return ""}},matchMedia(s){return {matches:false,media:s}}},ic=typeof window>"u"||typeof window.customElements>"u",sc=Object.keys(ir).every(s=>s in globalThis),_=ic&&!sc?ir:globalThis,M=ic&&!sc?tc:globalThis.document;var hm=Object.defineProperty,um=(s,e,t)=>e in s?hm(s,e,{enumerable:true,configurable:true,writable:true,value:t}):s[e]=t,fm=(s,e,t)=>(um(s,e+"",t),t),rc=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},et=(s,e,t)=>(rc(s,e,"read from private field"),t?t.call(s):e.get(s)),sr=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},rr=(s,e,t,i)=>(rc(s,e,"write to private field"),e.set(s,t),t),Tt,nr,bi,ar,nc=M.createElement("template");nc.innerHTML=`
1
+ 'use strict';var chunkKTP5LV2E_cjs=require('./chunk-KTP5LV2E.cjs'),chunkQ22T22LT_cjs=require('./chunk-Q22T22LT.cjs'),chunk5KQJTT3P_cjs=require('./chunk-5KQJTT3P.cjs'),chunkSDKTBB4N_cjs=require('./chunk-SDKTBB4N.cjs'),chunkY7NYUH3P_cjs=require('./chunk-Y7NYUH3P.cjs'),chunkVW7IKXVI_cjs=require('./chunk-VW7IKXVI.cjs'),chunkFUBUUA7Y_cjs=require('./chunk-FUBUUA7Y.cjs'),chunk5NSCV6C2_cjs=require('./chunk-5NSCV6C2.cjs'),chunk5STN56TL_cjs=require('./chunk-5STN56TL.cjs'),chunkIPA5Q26W_cjs=require('./chunk-IPA5Q26W.cjs');var $={MEDIA_PLAY_REQUEST:"mediaplayrequest",MEDIA_PAUSE_REQUEST:"mediapauserequest",MEDIA_MUTE_REQUEST:"mediamuterequest",MEDIA_UNMUTE_REQUEST:"mediaunmuterequest",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"},Y={MEDIA_CHROME_ATTRIBUTES:"mediachromeattributes",MEDIA_CONTROLLER:"mediacontroller"},ei={MEDIA_AIRPLAY_UNAVAILABLE:"mediaAirplayUnavailable",MEDIA_FULLSCREEN_UNAVAILABLE:"mediaFullscreenUnavailable",MEDIA_PIP_UNAVAILABLE:"mediaPipUnavailable",MEDIA_CAST_UNAVAILABLE:"mediaCastUnavailable",MEDIA_RENDITION_UNAVAILABLE:"mediaRenditionUnavailable",MEDIA_AUDIO_TRACK_UNAVAILABLE:"mediaAudioTrackUnavailable",MEDIA_PAUSED:"mediaPaused",MEDIA_HAS_PLAYED:"mediaHasPlayed",MEDIA_ENDED:"mediaEnded",MEDIA_MUTED:"mediaMuted",MEDIA_VOLUME_LEVEL:"mediaVolumeLevel",MEDIA_VOLUME:"mediaVolume",MEDIA_VOLUME_UNAVAILABLE:"mediaVolumeUnavailable",MEDIA_IS_PIP:"mediaIsPip",MEDIA_IS_CASTING:"mediaIsCasting",MEDIA_IS_AIRPLAYING:"mediaIsAirplaying",MEDIA_SUBTITLES_LIST:"mediaSubtitlesList",MEDIA_SUBTITLES_SHOWING:"mediaSubtitlesShowing",MEDIA_IS_FULLSCREEN:"mediaIsFullscreen",MEDIA_PLAYBACK_RATE:"mediaPlaybackRate",MEDIA_CURRENT_TIME:"mediaCurrentTime",MEDIA_DURATION:"mediaDuration",MEDIA_SEEKABLE:"mediaSeekable",MEDIA_PREVIEW_TIME:"mediaPreviewTime",MEDIA_PREVIEW_IMAGE:"mediaPreviewImage",MEDIA_PREVIEW_COORDS:"mediaPreviewCoords",MEDIA_PREVIEW_CHAPTER:"mediaPreviewChapter",MEDIA_LOADING:"mediaLoading",MEDIA_BUFFERED:"mediaBuffered",MEDIA_STREAM_TYPE:"mediaStreamType",MEDIA_TARGET_LIVE_WINDOW:"mediaTargetLiveWindow",MEDIA_TIME_IS_LIVE:"mediaTimeIsLive",MEDIA_RENDITION_LIST:"mediaRenditionList",MEDIA_RENDITION_SELECTED:"mediaRenditionSelected",MEDIA_AUDIO_TRACK_LIST:"mediaAudioTrackList",MEDIA_AUDIO_TRACK_ENABLED:"mediaAudioTrackEnabled",MEDIA_CHAPTERS_CUES:"mediaChaptersCues"},Yd=Object.entries(ei),T=Yd.reduce((s,[e,t])=>(s[e]=`${t.toLowerCase()}`,s),{}),ti=Yd.reduce((s,[e,t])=>(s[e]=`${t.toLowerCase()}`,s),{USER_INACTIVE:"userinactivechange",BREAKPOINTS_CHANGE:"breakpointchange",BREAKPOINTS_COMPUTED:"breakpointscomputed"});Object.entries(ti).reduce((s,[e,t])=>{let i=T[e];return i&&(s[t]=i),s},{userinactivechange:"userinactive"});var qd=Object.entries(T).reduce((s,[e,t])=>{let i=ti[e];return i&&(s[t]=i),s},{userinactive:"userinactivechange"}),Et={SUBTITLES:"subtitles",CAPTIONS:"captions",CHAPTERS:"chapters",METADATA:"metadata"},ii={DISABLED:"disabled",SHOWING:"showing"};var fa={MOUSE:"mouse",TOUCH:"touch"},je={UNAVAILABLE:"unavailable",UNSUPPORTED:"unsupported"},rt={LIVE:"live",ON_DEMAND:"on-demand",UNKNOWN:"unknown"};var Be={AUDIO_PLAYER:()=>"audio player",VIDEO_PLAYER:()=>"video player",VOLUME:()=>"volume",SEEK:()=>"seek",CLOSED_CAPTIONS:()=>"closed captions",PLAYBACK_RATE:({playbackRate:s=1}={})=>`current playback rate ${s}`,PLAYBACK_TIME:()=>"playback time",MEDIA_LOADING:()=>"media loading",SETTINGS:()=>"settings",AUDIO_TRACKS:()=>"audio tracks",QUALITY:()=>"quality"},le={PLAY:()=>"play",PAUSE:()=>"pause",MUTE:()=>"mute",UNMUTE:()=>"unmute",ENTER_AIRPLAY:()=>"start airplay",EXIT_AIRPLAY:()=>"stop airplay",ENTER_CAST:()=>"start casting",EXIT_CAST:()=>"stop casting",ENTER_FULLSCREEN:()=>"enter fullscreen mode",EXIT_FULLSCREEN:()=>"exit fullscreen mode",ENTER_PIP:()=>"enter picture in picture mode",EXIT_PIP:()=>"exit picture in picture mode",SEEK_FORWARD_N_SECS:({seekOffset:s=30}={})=>`seek forward ${s} seconds`,SEEK_BACK_N_SECS:({seekOffset:s=30}={})=>`seek back ${s} seconds`,SEEK_LIVE:()=>"seek to live",PLAYING_LIVE:()=>"playing live"};function zd(s){return s?.map(nm).join(" ")}function nm(s){if(s){let{id:e,width:t,height:i}=s;return [e,t,i].filter(r=>r!=null).join(":")}}function Xd(s){return s?.map(am).join(" ")}function am(s){if(s){let{id:e,kind:t,language:i,label:r}=s;return [e,t,i,r].filter(n=>n!=null).join(":")}}function Qs(s,e=false){return s.split("_").map(function(t,i){return (i||e?t[0].toUpperCase():t[0].toLowerCase())+t.slice(1).toLowerCase()}).join("")}function jd(s){return typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s)}var Zs=s=>new Promise(e=>setTimeout(e,s));var Qd=[{singular:"hour",plural:"hours"},{singular:"minute",plural:"minutes"},{singular:"second",plural:"seconds"}],om=(s,e)=>{let t=s===1?Qd[e].singular:Qd[e].plural;return `${s} ${t}`},si=s=>{if(!jd(s))return "";let e=Math.abs(s),t=e!==s,i=new Date(0,0,0,0,0,e,0);return `${[i.getHours(),i.getMinutes(),i.getSeconds()].map((o,l)=>o&&om(o,l)).filter(o=>o).join(", ")}${t?" remaining":""}`};function vt(s,e){let t=false;s<0&&(t=true,s=0-s),s=s<0?0:s;let i=Math.floor(s%60),r=Math.floor(s/60%60),n=Math.floor(s/3600),a=Math.floor(e/60%60),o=Math.floor(e/3600);return (isNaN(s)||s===1/0)&&(n=r=i="0"),n=n>0||o>0?n+":":"",r=((n||a>=10)&&r<10?"0"+r:r)+":",i=i<10?"0"+i:i,(t?"-":"")+n+r+i}var Js=(s,e,t=".value")=>{let i=s.querySelector(t);i&&(i.textContent=e);},dm=(s,e)=>{let t=`slot[name="${e}"]`,i=s.shadowRoot.querySelector(t);return i?i.children:[]},er=(s,e)=>dm(s,e)[0],Vt=(s,e)=>!s||!e?false:s.contains(e)?true:Vt(s,e.getRootNode().host),Kt=(s,e)=>{if(!s)return null;let t=s.closest(e);return t||Kt(s.getRootNode().host,e)};function ga(s=document){var e;let t=s?.activeElement;return t?(e=ga(t.shadowRoot))!=null?e:t:null}function Zd(s){var e;let t=(e=s?.getRootNode)==null?void 0:e.call(s);return t instanceof ShadowRoot||t instanceof Document?t:null}function Jd(s,e=3){if(s.checkVisibility)return s.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});let t=s;for(;t&&e>0;){let i=getComputedStyle(t);if(i.opacity==="0"||i.visibility==="hidden"||i.display==="none")return false;t=t.parentElement,e--;}return true}function ec(s,e,t,i){let r=ma(t,i),n=ma(t,{x:s,y:e}),a=ma(i,{x:s,y:e});return n>r||a>r?n>a?1:0:n/r}function ma(s,e){return Math.sqrt(Math.pow(e.x-s.x,2)+Math.pow(e.y-s.y,2))}function ce(s,e){let t=cm(s,i=>i===e);return t||pa(s,e)}function cm(s,e){var t;let i;for(i of s.querySelectorAll("style")){let r;try{r=(t=i.sheet)==null?void 0:t.cssRules;}catch{continue}for(let n of r??[])if(e(n.selectorText))return n}}function pa(s,e){var t,i;let r=(t=s.querySelectorAll("style"))!=null?t:[],n=r?.[r.length-1];return n?.sheet?(n?.sheet.insertRule(`${e}{}`,n.sheet.cssRules.length),(i=n.sheet.cssRules)==null?void 0:i[n.sheet.cssRules.length-1]):(console.warn("Media Chrome: No style sheet found on style tag of",s),{style:{setProperty:()=>{},removeProperty:()=>"",getPropertyValue:()=>""}})}function oe(s,e,t=Number.NaN){let i=s.getAttribute(e);return i!=null?+i:t}function me(s,e,t){let i=+t;if(t==null||Number.isNaN(i)){s.hasAttribute(e)&&s.removeAttribute(e);return}oe(s,e,void 0)!==i&&s.setAttribute(e,`${i}`);}function re(s,e){return s.hasAttribute(e)}function ie(s,e,t){if(t==null){s.hasAttribute(e)&&s.removeAttribute(e);return}re(s,e)!=t&&s.toggleAttribute(e,t);}function Ae(s,e,t=null){var i;return (i=s.getAttribute(e))!=null?i:t}function ge(s,e,t){if(t==null){s.hasAttribute(e)&&s.removeAttribute(e);return}let i=`${t}`;Ae(s,e,void 0)!==i&&s.setAttribute(e,i);}var tr=class{addEventListener(){}removeEventListener(){}dispatchEvent(){return true}},Ea=class{observe(){}unobserve(){}disconnect(){}},tc={createElement:function(){return new ir.HTMLElement},createElementNS:function(){return new ir.HTMLElement},addEventListener(){},removeEventListener(){}},ir={ResizeObserver:Ea,document:tc,HTMLElement:class extends tr{},DocumentFragment:class extends tr{},customElements:{get:function(){},define:function(){},whenDefined:function(){}},CustomEvent:function(){},getComputedStyle:function(){},navigator:{languages:[],get userAgent(){return ""}},matchMedia(s){return {matches:false,media:s}}},ic=typeof window>"u"||typeof window.customElements>"u",sc=Object.keys(ir).every(s=>s in globalThis),_=ic&&!sc?ir:globalThis,M=ic&&!sc?tc:globalThis.document;var hm=Object.defineProperty,um=(s,e,t)=>e in s?hm(s,e,{enumerable:true,configurable:true,writable:true,value:t}):s[e]=t,fm=(s,e,t)=>(um(s,e+"",t),t),rc=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},et=(s,e,t)=>(rc(s,e,"read from private field"),t?t.call(s):e.get(s)),sr=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},rr=(s,e,t,i)=>(rc(s,e,"write to private field"),e.set(s,t),t),Tt,nr,bi,ar,nc=M.createElement("template");nc.innerHTML=`
2
2
  <style>
3
3
  :host {
4
4
  font: var(--media-font,
@@ -1126,7 +1126,7 @@ svg, img, ::slotted(svg), ::slotted(img) {
1126
1126
  `),d=[],c=e?w0(e.baseTime,e.timescale):0,h="00:00.000",u=0,f=0,m,g=true;o.oncue=function(E){let v=t[i],A=t.ccOffset,b=(u-c)/9e4;if(v!=null&&v.new&&(f!==void 0?A=t.ccOffset=v.start:Z0(t,i,b)),b){if(!e){m=new Error("Missing initPTS for VTT MPEGTS");return}A=b-t.presentationOffset;}let L=E.endTime-E.startTime,y=it((E.startTime+A-f)*9e4,r*9e4)/9e4;E.startTime=Math.max(y,0),E.endTime=Math.max(y+L,0);let D=E.text.trim();E.text=decodeURIComponent(encodeURIComponent(D)),E.id||(E.id=Dd(E.startTime,E.endTime,D)),E.endTime>0&&d.push(E);},o.onparsingerror=function(E){m=E;},o.onflush=function(){if(m){a(m);return}n(d);},l.forEach(E=>{if(g)if(sl(E,"X-TIMESTAMP-MAP=")){g=false,E.slice(16).split(",").forEach(v=>{sl(v,"LOCAL:")?h=v.slice(6):sl(v,"MPEGTS:")&&(u=parseInt(v.slice(7)));});try{f=Q0(h)/1e3;}catch(v){m=v;}return}else E===""&&(g=false);o.parse(E+`
1127
1127
  `);}),o.flush();}var nl="stpp.ttml.im1t",Cf=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,kf=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,eE={left:"start",center:"center",right:"end",start:"start",end:"end"};function Cu(s,e,t,i){let r=j(new Uint8Array(s),["mdat"]);if(r.length===0){i(new Error("Could not parse IMSC1 mdat"));return}let n=r.map(o=>Ft(o)),a=k0(e.baseTime,1,e.timescale);try{n.forEach(o=>t(tE(o,a)));}catch(o){i(o);}}function tE(s,e){let r=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");let n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((h,u)=>(h[u]=r.getAttribute(`ttp:${u}`)||n[u],h),{}),o=r.getAttribute("xml:space")!=="preserve",l=ku(al(r,"styling","style")),d=ku(al(r,"layout","region")),c=al(r,"body","[begin]");return [].map.call(c,h=>{let u=wf(h,o);if(!u||!h.hasAttribute("begin"))return null;let f=ll(h.getAttribute("begin"),a),m=ll(h.getAttribute("dur"),a),g=ll(h.getAttribute("end"),a);if(f===null)throw wu(h);if(g===null){if(m===null)throw wu(h);g=f+m;}let E=new Rd(f-e,g-e,u);E.id=Dd(E.startTime,E.endTime,E.text);let v=d[h.getAttribute("region")],A=l[h.getAttribute("style")],b=iE(v,A,l),{textAlign:L}=b;if(L){let y=eE[L];y&&(E.lineAlign=y),E.align=L;}return _e(E,b),E}).filter(h=>h!==null)}function al(s,e,t){let i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function ku(s){return s.reduce((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function wf(s,e){return [].slice.call(s.childNodes).reduce((t,i,r)=>{var n;return i.nodeName==="br"&&r?t+`
1128
1128
  `:(n=i.childNodes)!=null&&n.length?wf(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function iE(s,e,t){let i="http://www.w3.org/ns/ttml#styling",r=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(r=t[a]),n.reduce((o,l)=>{let d=ol(e,i,l)||ol(s,i,l)||ol(r,i,l);return d&&(o[l]=d),o},{})}function ol(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function wu(s){return new Error(`Could not parse ttml timestamp ${s}`)}function ll(s,e){if(!s)return null;let t=Lf(s);return t===null&&(Cf.test(s)?t=sE(s,e):kf.test(s)&&(t=rE(s,e))),t}function sE(s,e){let t=Cf.exec(s),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return (t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function rE(s,e){let t=kf.exec(s),i=Number(t[1]);switch(t[2]){case "h":return i*3600;case "m":return i*60;case "ms":return i*1e3;case "f":return i/e.frameRate;case "t":return i/e.tickRate}return i}var nd=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=true,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=Pu(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this);}destroy(){let{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0;}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){let e=new Zi(this,"textTrack1"),t=new Zi(this,"textTrack2"),i=new Zi(this,"textTrack3"),r=new Zi(this,"textTrack4");this.cea608Parser1=new ta(1,e,t),this.cea608Parser2=new ta(3,i,r);}}addCues(e,t,i,r,n){let a=false;for(let o=n.length;o--;){let l=n[o],d=nE(l[0],l[1],t,i);if(d>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),a=true,d/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){let o=this.captionsTracks[e];this.Cues.newCue(o,t,i,r);}else {let o=this.Cues.newCue(null,t,i,r);this.hls.trigger(p.CUES_PARSED,{type:"captions",cues:o,track:e});}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:n}){let{unparsedVttFrags:a}=this;i==="main"&&(this.initPTS[t.cc]={baseTime:r,timescale:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(p.FRAG_LOADED,o);}));}getExistingTrack(e,t){let{media:i}=this;if(i)for(let r=0;r<i.textTracks.length;r++){let n=i.textTracks[r];if(Mu(n,{name:e,lang:t}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e);}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:i,media:r}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)i[e]=o,Qi(i[e]),ef(i[e],r);else {let l=this.createTextTrack("captions",n,a);l&&(l[e]=true,i[e]=l);}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i=t.label,r={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:false,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]});}createTextTrack(e,t,i){let r=this.media;if(r)return r.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks();}onMediaDetaching(){let{captionsTracks:e}=this;Object.keys(e).forEach(t=>{Qi(e[t]),delete e[t];}),this.nonNativeCaptionsTracks={};}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Pu(),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(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let i=0;i<t.length;i++)Qi(t[i]);}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[],r=i.some(n=>n.textCodec===nl);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(xf(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let a=this.media,o=a?In(a.textTracks):null;if(this.tracks.forEach((l,d)=>{let c;if(o){let h=null;for(let u=0;u<o.length;u++)if(o[u]&&Mu(o[u],l)){h=o[u],o[u]=null;break}h&&(c=h);}if(c)Qi(c);else {let h=Mf(l);c=this.createTextTrack(h,l.name,l.lang),c&&(c.mode="disabled");}c&&this.textTracks.push(c);}),o!=null&&o.length){let l=o.filter(d=>d!==null).map(d=>d.label);l.length&&S.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`);}}else if(this.tracks.length){let a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a});}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{let r=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!r)return;let n=`textTrack${r[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i);});}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===H.MAIN){var i,r;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:d}=t.frag,c=(i=(r=t.part)==null?void 0:r.index)!=null?i:-1;n&&a&&(d!==o+1||d===o&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=d,this.lastPartIndex=c;}}onFragLoaded(e,t){let{frag:i,payload:r}=t;if(i.type===H.SUBTITLE)if(r.byteLength){let n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){let o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:true},this.prevCC=i.cc),o&&o.textCodec===nl?this._parseIMSC1(i,r):this._parseVTTs(t);}}else this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:false,frag:i,error:new Error("Empty subtitle payload")});}_parseIMSC1(e,t){let i=this.hls;Cu(t,this.initPTS[e.cc],r=>{this._appendCues(r,e.level),i.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:true,frag:e});},r=>{S.log(`Failed to parse IMSC1: ${r}`),i.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:false,frag:e,error:r});});}_parseVTTs(e){var t;let{frag:i,payload:r}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[i.cc]&&o===-1){a.push(e);return}let l=this.hls,d=(t=i.initSegment)!=null&&t.data?st(i.initSegment.data,new Uint8Array(r)):r;J0(d,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,c=>{this._appendCues(c,i.level),l.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:true,frag:i});},c=>{let h=c.message==="Missing initPTS for VTT MPEGTS";h?a.push(e):this._fallbackToIMSC1(i,r),S.log(`Failed to parse VTT cue: ${c}`),!(h&&o>i.cc)&&l.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:false,frag:i,error:c});});}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||Cu(t,this.initPTS[e.cc],()=>{i.textCodec=nl,this._parseIMSC1(e,t);},()=>{i.textCodec="wvtt";});}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){let r=this.textTracks[t];if(!r||r.mode==="disabled")return;e.forEach(n=>tf(r,n));}else {let r=this.tracks[t];if(!r)return;let n=r.default?"default":"subtitles"+t;i.trigger(p.CUES_PARSED,{type:"subtitles",cues:e,track:n});}}onFragDecrypted(e,t){let{frag:i}=t;i.type===H.SUBTITLE&&this.onFragLoaded(p.FRAG_LOADED,t);}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={};}onFragParsingUserdata(e,t){this.initCea608Parsers();let{cea608Parser1:i,cea608Parser2:r}=this;if(!this.enabled||!i||!r)return;let{frag:n,samples:a}=t;if(!(n.type===H.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let o=0;o<a.length;o++){let l=a[o].bytes;if(l){let d=this.extractCea608Data(l);i.addData(a[o].pts,d[0]),r.addData(a[o].pts,d[1]);}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:r,type:n}){let{media:a}=this;if(!(!a||a.currentTime<i)){if(!n||n==="video"){let{captionsTracks:o}=this;Object.keys(o).forEach(l=>pl(o[l],t,i));}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){let{textTracks:o}=this;Object.keys(o).forEach(l=>pl(o[l],t,r));}}}extractCea608Data(e){let t=[[],[]],i=e[0]&31,r=2;for(let n=0;n<i;n++){let a=e[r++],o=127&e[r++],l=127&e[r++];if(o===0&&l===0)continue;if((4&a)!==0){let c=3&a;(c===0||c===1)&&(t[c].push(o),t[c].push(l));}}return t}};function Mf(s){return s.characteristics&&/transcribes-spoken-dialog/gi.test(s.characteristics)&&/describes-music-and-sound/gi.test(s.characteristics)?"captions":"subtitles"}function Mu(s,e){return !!s&&s.kind===Mf(e)&&Kl(e,s)}function nE(s,e,t,i){return Math.min(e,i)-Math.max(s,t)}function Pu(){return {ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:true}}}var ad=class s{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(){let{hls:e}=this;e.on(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this);}unregisterListener(){let{hls:e}=this;e.off(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this);}onFpsDropLevelCapping(e,t){let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width});}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize();}onManifestParsed(e,t){let i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping();}onLevelsUpdated(e,t){this.timer&&F(this.autoLevelCapping)&&this.detectPlayerSize();}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping();}onMediaDetaching(){this.stopCapping();}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}let e=this.hls.levels;if(e.length){let t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&S.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping;}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return -1;let i=t.filter((r,n)=>this.isLevelAllowed(r)&&n<=e);return this.clientRect=null,s.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize());}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0);}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0);}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio;}catch{}return e}isLevelAllowed(e){return !this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return -1;let r=(o,l)=>l?o.width!==l.width||o.height!==l.height:true,n=e.length-1,a=Math.max(t,i);for(let o=0;o<e.length;o+=1){let l=e[o];if((l.width>=a||l.height>=a)&&r(l,e[o+1])){n=o;break}}return n}},od=class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=false,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners();}setStreamController(e){this.streamController=e;}registerListeners(){this.hls.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this);}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this);}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=false,this.media=null;}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&typeof r.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=true),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod);}}checkFPS(e,t,i){let r=performance.now();if(t){if(this.lastTime){let n=r-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,d=this.hls;if(d.trigger(p.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>d.config.fpsDroppedMonitoringThreshold*o){let c=d.currentLevel;S.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=c)&&(c=c-1,d.trigger(p.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:d.currentLevel}),d.autoLevelCapping=c,this.streamController.nextLevelSwitch());}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t;}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames);}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount);}},_n="[eme]",ia=class s{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=s.CDMCleanupPromise?[s.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=S.debug.bind(S,_n),this.log=S.log.bind(S,_n),this.warn=S.warn.bind(S,_n),this.error=S.error.bind(S,_n),this.hls=e,this.config=e.config,this.registerListeners();}destroy(){this.unregisterListeners(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null;}registerListeners(){this.hls.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.MANIFEST_LOADED,this.onManifestLoaded,this);}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.MANIFEST_LOADED,this.onManifestLoaded,this);}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t[e];if(r)return r.licenseUrl;if(e===de.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){let{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`);}attemptKeySystemAccess(e){let t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,r=t.map(a=>a.audioCodec).filter(i),n=t.map(a=>a.videoCodec).filter(i);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{let l=d=>{let c=d.shift();this.getMediaKeysPromise(c,r,n).then(h=>a({keySystem:c,mediaKeys:h})).catch(h=>{d.length?l(d):h instanceof ze?o(h):o(new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_ACCESS,error:h,fatal:true},h.message));});};l(e);})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Gu===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return i(e,t)}getMediaKeysPromise(e,t,i){let r=zg(e,t,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[e],a=n?.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(r)}`),a=this.requestMediaKeySystemAccess(e,r);let o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`);}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);let d=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=l.createMediaKeys().then(c=>(this.log(`Media-keys created for "${e}"`),d.then(h=>h?this.setMediaKeysServerCertificate(c,e,h):c))),o.mediaKeys.catch(c=>{this.error(`Failed to create media-keys for "${e}"}: ${c}`);}),o.mediaKeys})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${Pt.hexDump(e.keyId||[])}`);let r=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let i=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,n,t.pssh,"expired");}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e);}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return Pt.hexDump(e.keyId)}updateKeySession(e,t){var i;let r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${Pt.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])}
1129
- } (data length: ${t&&t.byteLength})`),r.update(t)}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,i)=>{let r=Wo(this.config),n=e.map(qh).filter(a=>!!a&&r.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:a})=>{let o=Xh(a);o?t(o):i(new Error(`Unable to find format for key-system "${a}"`));}).catch(i)})}loadKey(e){let t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let n=this.keyIdToKeySessionPromise[i];return n||(n=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();let l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:t});return this.generateRequestWithPreferredKeySession(l,"cenc",t.pssh,"playlist-key")}))),n.catch(a=>this.handleError(a))),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof ze?this.hls.trigger(p.ERROR,e.data):this.hls.trigger(p.ERROR,{type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_KEYS,error:e,fatal:true}));}getKeySystemForKeyPromise(e){let t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){let r=qh(e.keyFormat),n=r?[r]:Wo(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Wo(this.config)),e.length===0)throw new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:true},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){let{initDataType:t,initData:i}=e,r=`"${e.type}" event: init data type: "${t}"`;if(this.debug(r),i===null)return;let n,a;if(t==="sinf"&&this.config.drmSystems[de.FAIRPLAY]){let h=xe(new Uint8Array(i));try{let u=Ad(JSON.parse(h).sinf),f=Xu(new Uint8Array(u));if(!f)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");n=f.subarray(8,24),a=de.FAIRPLAY;}catch(u){this.warn(`${r} Failed to parse sinf: ${u}`);return}}else {let h=Tp(i),u=h.filter(f=>f.systemId===Fs.WIDEVINE)[0];if(!u){h.length===0||h.some(f=>!f.systemId)?this.warn(`${r} contains incomplete or invalid pssh data`):this.log(`ignoring ${r} for ${h.map(f=>zh(f.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(a=zh(u.systemId),u.version===0&&u.data){let f=u.data.length-22;n=u.data.subarray(f,f+16);}}if(!a||!n)return;let o=Pt.hexDump(n),{keyIdToKeySessionPromise:l,mediaKeySessions:d}=this,c=l[o];for(let h=0;h<d.length;h++){let u=d[h],f=u.decryptdata;if(!f.keyId)continue;let m=Pt.hexDump(f.keyId);if(o===m||f.uri.replace(/-/g,"").indexOf(o)!==-1){if(c=l[m],f.pssh)break;delete l[m],f.pssh=new Uint8Array(i),f.keyId=n,c=l[o]=c.then(()=>this.generateRequestWithPreferredKeySession(u,t,i,"encrypted-event-key-match"));break}}c||(c=l[o]=this.getKeySystemSelectionPromise([a]).then(({keySystem:h,mediaKeys:u})=>{var f;this.throwIfDestroyed();let m=new Hs("ISO-23001-7",o,(f=Xh(h))!=null?f:"");return m.pssh=new Uint8Array(i),m.keyId=n,this.attemptSetMediaKeys(h,u).then(()=>{this.throwIfDestroyed();let g=this.createMediaKeySessionContext({decryptdata:m,keySystem:h,mediaKeys:u});return this.generateRequestWithPreferredKeySession(g,t,i,"encrypted-event-no-match")})})),c.catch(h=>this.handleError(h));}_onWaitingForKey(e){this.log(`"${e.type}" event`);}attemptSetMediaKeys(e,t){let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1);})}generateRequestWithPreferredKeySession(e,t,i,r){var n,a;let o=(n=this.config.drmSystems)==null||(a=n[e.keySystem])==null?void 0:a.generateRequest;if(o)try{let m=o.call(this.hls,t,i,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,i=e.decryptdata.pssh=m.initData?new Uint8Array(m.initData):null;}catch(m){var l;if(this.warn(m.message),(l=this.hls)!=null&&l.config.debug)throw m}if(i===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let d=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${d} (init data type: ${t} length: ${i?i.byteLength:null})`);let c=new Ld,h=e._onmessage=m=>{let g=e.mediaKeysSession;if(!g){c.emit("error",new Error("invalid state"));return}let{messageType:E,message:v}=m;this.log(`"${E}" message event for session "${g.sessionId}" message size: ${v.byteLength}`),E==="license-request"||E==="license-renewal"?this.renewLicense(e,v).catch(A=>{this.handleError(A),c.emit("error",A);}):E==="license-release"?e.keySystem===de.FAIRPLAY&&(this.updateKeySession(e,fl("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${E}"`);},u=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){c.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);let E=e.keyStatus;c.emit("keyStatus",E),E==="expired"&&(this.warn(`${e.keySystem} expired for key ${d}`),this.renewKeySession(e));};e.mediaKeysSession.addEventListener("message",h),e.mediaKeysSession.addEventListener("keystatuseschange",u);let f=new Promise((m,g)=>{c.on("error",g),c.on("keyStatus",E=>{E.startsWith("usable")?m():E==="output-restricted"?g(new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:false},"HDCP level output restricted")):E==="internal-error"?g(new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:true},`key status changed to "${E}"`)):E==="expired"?g(new Error("key expired while generating request")):this.warn(`unhandled key status change "${E}"`);});});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var m;this.log(`Request generated for key-session "${(m=e.mediaKeysSession)==null?void 0:m.sessionId}" keyId: ${d}`);}).catch(m=>{throw new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_SESSION,error:m,fatal:false},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>{throw c.removeAllListeners(),this.removeSession(e),m}).then(()=>(c.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${Pt.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${Pt.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t;});}fetchServerCertificate(e){let t=this.config,i=t.loader,r=new i(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{let l={responseType:"arraybuffer",url:n},d=t.certLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,f,m,g)=>{a(u.data);},onError:(u,f,m,g)=>{o(new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:true,networkDetails:m,response:Oe({url:l.url,data:void 0},u)},`"${e}" certificate request failed (${n}). Status: ${u.code} (${u.text})`));},onTimeout:(u,f,m)=>{o(new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:true,networkDetails:m,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`));},onAbort:(u,f,m)=>{o(new Error("aborted"));}};r.load(l,c,h);})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((r,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i?.byteLength}) on "${t}"`),r(e);}).catch(a=>{n(new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:true},a.message));});})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(r=>{throw new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:r,fatal:true},r.message)}))}unpackPlayReadyKeyMessage(e,t){let i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let r=new DOMParser().parseFromString(i,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let c;for(let h=0,u=n.length;h<u;h++){var a,o;c=n[h];let f=(a=c.querySelector("name"))==null?void 0:a.textContent,m=(o=c.querySelector("value"))==null?void 0:o.textContent;f&&m&&e.setRequestHeader(f,m);}}let l=r.querySelector("Challenge"),d=l?.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return fl(atob(d))}setupLicenseXHR(e,t,i,r){let n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,r)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,true),n.call(this.hls,e,t,i,r)}).then(a=>(e.readyState||e.open("POST",t,true),{xhr:e,licenseChallenge:a||r})):(e.open("POST",t,true),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{let a=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${a}`);let 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}`);let d=this.config.licenseResponseCallback;if(d)try{l=d.call(this.hls,o,a,e);}catch(c){this.error(c);}r(l);}else {let l=i.errorRetry,d=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)n(new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:true,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 {let c=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${c} 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==de.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(l,d)),l.send(d);});})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey);}onMediaDetached(){let e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Hs.clearKeyUriToKeyIdMap();let i=t.length;s.CDMCleanupPromise=Promise.all(t.map(r=>this.removeSession(r)).concat(e?.setMediaKeys(null).catch(r=>{this.log(`Could not clear media keys: ${r}`);}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0);}).catch(r=>{this.log(`Could not close sessions and clear media keys: ${r}`);});}onManifestLoading(){this.keyFormatPromise=null;}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let i=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i);}}removeSession(e){let{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch(n=>{this.log(`Could not remove session: ${n}`);}).then(()=>t.close()).catch(n=>{this.log(`Could not close session: ${n}`);})}}};ia.CDMCleanupPromise=void 0;var ze=class 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;}},He;(function(s){s.MANIFEST="m",s.AUDIO="a",s.VIDEO="v",s.MUXED="av",s.INIT="i",s.CAPTION="c",s.TIMED_TEXT="tt",s.KEY="k",s.OTHER="o";})(He||(He={}));var ld;(function(s){s.DASH="d",s.HLS="h",s.SMOOTH="s",s.OTHER="o";})(ld||(ld={}));var Ei;(function(s){s.OBJECT="CMCD-Object",s.REQUEST="CMCD-Request",s.SESSION="CMCD-Session",s.STATUS="CMCD-Status";})(Ei||(Ei={}));var aE={[Ei.OBJECT]:["br","d","ot","tb"],[Ei.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Ei.SESSION]:["cid","pr","sf","sid","st","v"],[Ei.STATUS]:["bs","rtp"]},Xs=class s{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(i=>i instanceof s?i:new s(i))),this.value=e,this.params=t;}},sa=class{constructor(e){this.description=void 0,this.description=e;}},oE="Dict";function lE(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function dE(s,e,t,i){return new Error(`failed to ${s} "${lE(e)}" as ${t}`,{cause:i})}var Ou="Bare Item",cE="Boolean",hE="Byte Sequence",uE="Decimal",fE="Integer";function mE(s){return s<-999999999999999||999999999999999<s}var gE=/[\x00-\x1f\x7f]+/,pE="Token",EE="Key";function Ut(s,e,t){return dE("serialize",s,e,t)}function vE(s){if(typeof s!="boolean")throw Ut(s,cE);return s?"?1":"?0"}function TE(s){return btoa(String.fromCharCode(...s))}function AE(s){if(ArrayBuffer.isView(s)===false)throw Ut(s,hE);return `:${TE(s)}:`}function Pf(s){if(mE(s))throw Ut(s,fE);return s.toString()}function bE(s){return `@${Pf(s.getTime()/1e3)}`}function Of(s,e){if(s<0)return -Of(-s,e);let t=Math.pow(10,e);if(Math.abs(s*t%1-.5)<Number.EPSILON){let r=Math.floor(s*t);return (r%2===0?r:r+1)/t}else return Math.round(s*t)/t}function yE(s){let e=Of(s,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Ut(s,uE);let t=e.toString();return t.includes(".")?t:`${t}.0`}var SE="String";function _E(s){if(gE.test(s))throw Ut(s,SE);return `"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function xE(s){return s.description||s.toString().slice(7,-1)}function Nu(s){let e=xE(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===false)throw Ut(e,pE);return e}function dd(s){switch(typeof s){case "number":if(!F(s))throw Ut(s,Ou);return Number.isInteger(s)?Pf(s):yE(s);case "string":return _E(s);case "symbol":return Nu(s);case "boolean":return vE(s);case "object":if(s instanceof Date)return bE(s);if(s instanceof Uint8Array)return AE(s);if(s instanceof sa)return Nu(s);default:throw Ut(s,Ou)}}function cd(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===false)throw Ut(s,EE);return s}function Cd(s){return s==null?"":Object.entries(s).map(([e,t])=>t===true?`;${cd(e)}`:`;${cd(e)}=${dd(t)}`).join("")}function Nf(s){return s instanceof Xs?`${dd(s.value)}${Cd(s.params)}`:dd(s)}function IE(s){return `(${s.value.map(Nf).join(" ")})${Cd(s.params)}`}function LE(s,e={whitespace:true}){if(typeof s!="object")throw Ut(s,oE);let t=s instanceof Map?s.entries():Object.entries(s),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof Xs||(n=new Xs(n));let a=cd(r);return n.value===true?a+=Cd(n.params):(a+="=",Array.isArray(n.value)?a+=IE(n):a+=Nf(n)),a}).join(`,${i}`)}function RE(s,e){return LE(s,e)}var DE=s=>s==="ot"||s==="sf"||s==="st",CE=s=>typeof s=="number"?F(s):s!=null&&s!==""&&s!==false;function kE(s,e){let t=new URL(s),i=new URL(e);if(t.origin!==i.origin)return s;let r=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")}function wE(){try{return crypto.randomUUID()}catch{try{let 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=>{let n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(r=="x"?n:n&3|8).toString(16)})}}}var kn=s=>Math.round(s),ME=(s,e)=>(e!=null&&e.baseUrl&&(s=kE(s,e.baseUrl)),encodeURIComponent(s)),xn=s=>kn(s/100)*100,PE={br:kn,d:kn,bl:xn,dl:xn,mtp:xn,nor:ME,rtp:xn,tb:kn};function OE(s,e){let t={};if(s==null||typeof s!="object")return t;let i=Object.keys(s).sort(),r=_e({},PE,e?.formatters),n=e?.filter;return i.forEach(a=>{if(n!=null&&n(a))return;let o=s[a],l=r[a];l&&(o=l(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||CE(o)&&(DE(a)&&typeof o=="string"&&(o=new sa(o)),t[a]=o));}),t}function Ff(s,e={}){return s?RE(OE(s,e),_e({whitespace:false},e)):""}function NE(s,e={}){if(!s)return {};let t=Object.entries(s),i=Object.entries(aE).concat(Object.entries(e?.customHeaderMap||{})),r=t.reduce((n,a)=>{var o;let[d,c]=a,h=((o=i.find(u=>u[1].includes(d)))==null?void 0:o[0])||Ei.REQUEST;return (n[h])!=null||(n[h]={}),n[h][d]=c,n},{});return Object.entries(r).reduce((n,[a,o])=>(n[a]=Ff(o,e),n),{})}function FE(s,e,t){return _e(s,NE(e,t))}var UE="CMCD";function BE(s,e={}){if(!s)return "";let t=Ff(s,e);return `${UE}=${encodeURIComponent(t)}`}var Fu=/CMCD=[^&#]+/;function $E(s,e,t){let i=BE(e,t);if(!i)return s;if(Fu.test(s))return s.replace(Fu,i);let r=s.includes("?")?"&":"?";return `${s}${r}${i}`}var hd=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=false,this.includeKeys=void 0,this.initialized=false,this.starved=false,this.buffering=true,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=true),this.buffering=true;},this.onPlaying=()=>{this.initialized||(this.initialized=true),this.buffering=false;},this.applyPlaylistData=r=>{try{this.apply(r,{ot:He.MANIFEST,su:!this.initialized});}catch(n){S.warn("Could not generate manifest CMCD data.",n);}},this.applyFragmentData=r=>{try{let n=r.frag,a=this.hls.levels[n.level],o=this.getObjectType(n),l={d:n.duration*1e3,ot:o};(o===He.VIDEO||o===He.AUDIO||o==He.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(r,l);}catch(n){S.warn("Could not generate segment CMCD data.",n);}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||wE(),this.cid=i.contentId,this.useHeaders=i.useHeaders===true,this.includeKeys=i.includeKeys,this.registerListeners());}registerListeners(){let e=this.hls;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this);}unregisterListeners(){let e=this.hls;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this);}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null;}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying);}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null);}onBufferCreated(e,t){var i,r;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(r=t.tracks.video)==null?void 0:r.buffer;}createData(){var e;return {v:1,sf:ld.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){_e(t,this.createData());let i=t.ot===He.INIT||t.ot===He.VIDEO||t.ot===He.MUXED;this.starved&&i&&(t.bs=true,t.su=true,this.starved=false),t.su==null&&(t.su=this.buffering);let{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((n,a)=>(r.includes(a)&&(n[a]=t[a]),n),{})),this.useHeaders?(e.headers||(e.headers={}),FE(e.headers,t)):e.url=$E(e.url,t);}getObjectType(e){let{type:t}=e;if(t==="subtitle")return He.TIMED_TEXT;if(e.sn==="initSegment")return He.INIT;if(t==="audio")return He.AUDIO;if(t==="main")return this.hls.audioTracks.length?He.VIDEO:He.MUXED}getTopBandwidth(e){let t=0,i,r=this.hls;if(e===He.AUDIO)i=r.audioTracks;else {let n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;i=r.levels.slice(0,a);}for(let n of i)n.bitrate>t&&(t=n.bitrate);return t>0?t:NaN}getBufferLength(e){let t=this.hls.media,i=e===He.AUDIO?this.audioBuffer:this.videoBuffer;return !i||!t?NaN:ue.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n);}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy();}abort(){this.loader.abort();}load(n,a,o){t(n),this.loader.load(n,a,o);}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n);}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy();}abort(){this.loader.abort();}load(n,a,o){t(n),this.loader.load(n,a,o);}}}},GE=3e5,ud=class{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=false,this.enabled=true,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=S.log.bind(S,"[content-steering]:"),this.registerListeners();}registerListeners(){let e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this);}unregisterListeners(){let e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this));}startLoad(){if(this.started=true,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri);}}stopLoad(){this.started=false,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){let t=this.levels;t&&(this.levels=t.filter(i=>i!==e));}onManifestLoading(){this.stopLoad(),this.enabled=true,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null;}onManifestLoaded(e,t){let{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad());}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks;}onError(e,t){let{errorAction:i}=t;if(i?.action===Me.SendAlternateToPenaltyBox&&i.flags===ut.MoveAllAlternatesMatchingHost){let r=this.levels,n=this.pathwayPriority,a=this.pathwayId;if(t.context){let{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=r.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),i.resolved||S.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${r&&r.length} priorities: ${JSON.stringify(n)} penalized: ${JSON.stringify(this.penalizedPathways)}`);}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i;}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t,i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(n=>{r-i[n]>GE&&delete i[n];});for(let n=0;n<e.length;n++){let a=e[n];if(a in i)continue;if(a===this.pathwayId)return;let 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,af(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});let 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,i){let r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===Z.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===Z.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return i}clonePathways(e){let t=this.levels;if(!t)return;let i={},r={};e.forEach(n=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(c=>c.pathwayId===a))return;let d=this.getLevelsForPathway(o).map(c=>{let h=new Ee(c.attrs);h["PATHWAY-ID"]=a;let u=h.AUDIO&&`${h.AUDIO}_clone_${a}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;u&&(i[h.AUDIO]=u,h.AUDIO=u),f&&(r[h.SUBTITLES]=f,h.SUBTITLES=f);let m=Uf(c.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new Jt({attrs:h,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:m,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(let E=1;E<c.audioGroups.length;E++)g.addGroupId("audio",`${c.audioGroups[E]}_clone_${a}`);if(c.subtitleGroups)for(let E=1;E<c.subtitleGroups.length;E++)g.addGroupId("text",`${c.subtitleGroups[E]}_clone_${a}`);return g});t.push(...d),Uu(this.audioTracks,i,l,a),Uu(this.subtitleTracks,r,l,a);});}loadSteeringManifest(e){let t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let r;try{r=new self.URL(e);}catch{this.enabled=false,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){let c=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+c);}let 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:(c,h,u,f)=>{this.log(`Loaded steering manifest: "${r}"`);let m=c.data;if(m.VERSION!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;let{"RELOAD-URI":g,"PATHWAY-CLONES":E,"PATHWAY-PRIORITY":v}=m;if(g)try{this.uri=new self.URL(g,r).href;}catch{this.enabled=false,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||u.url),E&&this.clonePathways(E);let A={steeringManifest:m,url:r.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,A),v&&this.updatePathwayPriority(v);},onError:(c,h,u,f)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${h.url})`),this.stopLoad(),c.code===410){this.enabled=false,this.log(`Steering manifest ${h.url} no longer available`);return}let m=this.timeToLoad*1e3;if(c.code===429){let g=this.loader;if(typeof g?.getResponseHeader=="function"){let E=g.getResponseHeader("Retry-After");E&&(m=parseFloat(E)*1e3);}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,m);},onTimeout:(c,h,u)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url);}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,l,d);}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;let r=(i=this.hls)==null?void 0:i.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3);},t);}};function Uu(s,e,t,i){s&&Object.keys(e).forEach(r=>{let n=s.filter(a=>a.groupId===r).map(a=>{let o=_e({},a);return o.details=void 0,o.attrs=new Ee(o.attrs),o.url=o.attrs.URI=Uf(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=i,o});s.push(...n);});}function Uf(s,e,t,i){let{HOST:r,PARAMS:n,[t]:a}=i,o;e&&(o=a?.[e],o&&(s=o));let l=new self.URL(s);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(d=>{d&&l.searchParams.set(d,n[d]);}),l.href}var HE=/^age:\s*[\d.]+\s*$/im,ra=class{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 ts,this.retryDelay=0;}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null;}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=true,e.abort()));}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader);}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal();}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=false;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n(i,t.url)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,true),n(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e);}).catch(a=>{this.callbacks.onError({code:i.status,text:a.message},t,i,r);}):this.openAndSendXhr(i,t,e);}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,true);let r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(r)for(let o in r)e.setRequestHeader(o,r[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&F(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send();}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let r=t.readyState,n=this.config;if(!i.aborted&&r>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let a=t.status,o=t.responseType!=="text";if(a>=200&&a<300&&(o&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);let l=o?t.response:t.responseText,d=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=d,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;let c=this.callbacks.onProgress;if(c&&c(i,e,l,t),!this.callbacks)return;let h={url:t.responseURL,data:l,code:a};this.callbacks.onSuccess(h,i,e,t);}else {let l=n.loadPolicy.errorRetry,d=i.retry,c={url:e.url,data:void 0,code:a};Hn(l,d,false,c)?this.retry(l):(S.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:t.statusText},e,t,i));}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Hn(e,t,true))this.retry(e);else {var i;S.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);let r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader));}}retry(e){let{context:t,stats:i}=this;this.retryDelay=Sd(e,i.retry),i.retry++,S.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay);}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total);}getCacheAge(){let e=null;if(this.loader&&HE.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null;}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}};function VE(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return false}var KE=/(\d+)-(\d+)\/(\d+)/,na=class{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||zE,this.controller=new self.AbortController,this.stats=new ts;}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=true,this.controller.abort());}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response);}load(e,t,i){let r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();let n=WE(e,this.controller.signal),a=i.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:d,maxLoadTimeMs:c}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=d&&F(d)?d:c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response);},t.timeout),self.fetch(this.request).then(h=>{this.response=this.loader=h;let u=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response);},c-(u-r.loading.start)),!h.ok){let{status:f,statusText:m}=h;throw new fd(m||"fetch, bad network response",f,h)}return r.loading.first=u,r.total=qE(h.headers)||r.total,a&&F(t.highWaterMark)?this.loadProgressively(h,r,e,t.highWaterMark,a):o?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{let u=this.response;if(!u)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let f=h[l];f&&(r.loaded=r.total=f);let m={url:u.url,data:h,code:u.status};a&&!F(t.highWaterMark)&&a(r,e,h,u),i.onSuccess(m,r,e,u);}).catch(h=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;let u=h&&h.code||0,f=h?h.message:null;i.onError({code:u,text:f},e,h?h.details:null,r);});}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null;}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,n){let a=new Wn,o=e.body.getReader(),l=()=>o.read().then(d=>{if(d.done)return a.dataLength&&n(t,i,a.flush(),e),Promise.resolve(new ArrayBuffer(0));let c=d.value,h=c.length;return t.loaded+=h,h<r||a.dataLength?(a.push(c),a.dataLength>=r&&n(t,i,a.flush(),e)):n(t,i,c,e),l()}).catch(()=>Promise.reject());return l()}};function WE(s,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(_e({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function YE(s){let e=KE.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function qE(s){let e=s.get("Content-Range");if(e){let i=YE(e);if(F(i))return i}let t=s.get("Content-Length");if(t)return parseInt(t)}function zE(s,e){return new self.Request(s.url,e)}var fd=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i;}},XE=/\s/,jE={newCue(s,e,t,i){let r=[],n,a,o,l,d,c=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=true,l=0,d="",!n.isEmpty()){var h;for(let g=0;g<n.chars.length;g++)XE.test(n.chars[g].uchar)&&o?l++:(d+=n.chars[g].uchar,o=false);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=Df(d.trim()),m=Dd(e,t,f);s!=null&&(h=s.cues)!=null&&h.getCueById(m)||(a=new c(e,t,f),a.id=m,a.line=u+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a));}return s&&r.length&&(r.sort((u,f)=>u.line==="auto"||f.line==="auto"?0:u.line>8&&f.line>8?f.line-u.line:u.line-f.line),r.forEach(u=>tf(s,u))),r}},QE={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Bf=Oe(Oe({autoStartLoad:true,startPosition:-1,defaultAudioCodec:void 0,debug:false,capLevelOnFPSDrop:false,capLevelToPlayerSize:false,ignoreDevicePixelRatio:false,preferManagedMediaSource:true,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:false,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:true,workerPath:null,enableSoftwareAES:true,startLevel:void 0,startFragPrefetch:false,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:ra,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:xl,bufferController:Ql,capLevelController:ad,errorController:Sl,fpsController:od,stretchShortVideoTrack:false,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:true,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:false,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:false,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Gu,testBandwidth:true,progressive:false,lowLatencyMode:true,cmcd:void 0,enableDateRangeMetadataCues:true,enableEmsgMetadataCues:true,enableID3MetadataCues:true,useMediaCapabilities:true,certLoadPolicy:{default:QE},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},ZE()),{},{subtitleStreamController:ql,subtitleTrackController:Xl,timelineController:nd,audioStreamController:Wl,audioTrackController:Yl,emeController:ia,cmcdController:hd,contentSteeringController:ud});function ZE(){return {cueHandler:jE,enableWebVTT:true,enableIMSC1:true,enableCEA708Captions:true,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:true}}function JE(s,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let t=md(s),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{let a=`${n==="level"?"playlist":n}LoadPolicy`,o=e[a]===void 0,l=[];r.forEach(d=>{let c=`${n}Loading${d}`,h=e[c];if(h!==void 0&&o){l.push(c);let u=t[a].default;switch(e[a]={default:u},d){case "TimeOut":u.maxLoadTimeMs=h,u.maxTimeToFirstByteMs=h;break;case "MaxRetry":u.errorRetry.maxNumRetry=h,u.timeoutRetry.maxNumRetry=h;break;case "RetryDelay":u.errorRetry.retryDelayMs=h,u.timeoutRetry.retryDelayMs=h;break;case "MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=h,u.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&S.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`);}),Oe(Oe({},t),e)}function md(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(md):Object.keys(s).reduce((e,t)=>(e[t]=md(s[t]),e),{}):s}function ev(s){let e=s.loader;e!==na&&e!==ra?(S.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=false):VE()&&(s.loader=na,s.progressive=true,s.enableSoftwareAES=true,S.log("[config]: Progressive streaming enabled, using FetchLoader"));}var dl,gd=class extends Ks{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(){let{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this);}_unregisterListeners(){let{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.ERROR,this.onError,this);}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy();}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0;}),super.stopLoad();}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1;}onManifestLoading(e,t){this.resetLevels();}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,r=[],n={},a={},o=false,l=false,d=false;t.levels.forEach(c=>{var h,u;let f=c.attrs,{audioCodec:m,videoCodec:g}=c;((h=m)==null?void 0:h.indexOf("mp4a.40.34"))!==-1&&(dl||(dl=/chrome|firefox/i.test(navigator.userAgent)),dl&&(c.audioCodec=m=void 0)),m&&(c.audioCodec=m=Un(m,i)),((u=g)==null?void 0:u.indexOf("avc1"))===0&&(g=c.videoCodec=Lp(g));let{width:E,height:v,unknownCodecs:A}=c;if(o||(o=!!(E&&v)),l||(l=!!g),d||(d=!!m),A!=null&&A.length||m&&!Xo(m,"audio",i)||g&&!Xo(g,"video",i))return;let{CODECS:b,"FRAME-RATE":L,"HDCP-LEVEL":y,"PATHWAY-ID":D,RESOLUTION:I,"VIDEO-RANGE":k}=f,R=`${`${D||"."}-`}${c.bitrate}-${I}-${L}-${b}-${k}-${y}`;if(n[R])if(n[R].uri!==c.url&&!c.attrs["PATHWAY-ID"]){let w=a[R]+=1;c.attrs["PATHWAY-ID"]=new Array(w+1).join(".");let X=new Jt(c);n[R]=X,r.push(X);}else n[R].addGroupId("audio",f.AUDIO),n[R].addGroupId("text",f.SUBTITLES);else {let w=new Jt(c);n[R]=w,a[R]=1,r.push(w);}}),this.filterAndSortMediaOptions(r,t,o,l,d);}filterAndSortMediaOptions(e,t,i,r,n){let a=[],o=[],l=e;if((i||r)&&n&&(l=l.filter(({videoCodec:m,videoRange:g,width:E,height:v})=>(!!m||!!(E&&v))&&Fp(g))),l.length===0){Promise.resolve().then(()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);let m=new Error("no level with compatible codecs found in manifest");this.hls.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:x.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:true,url:t.url,error:m,reason:m.message});}});return}if(t.audioTracks){let{preferManagedMediaSource:m}=this.hls.config;a=t.audioTracks.filter(g=>!g.audioCodec||Xo(g.audioCodec,"audio",m)),Bu(a);}t.subtitles&&(o=t.subtitles,Bu(o));let d=l.slice(0);l.sort((m,g)=>{if(m.attrs["HDCP-LEVEL"]!==g.attrs["HDCP-LEVEL"])return (m.attrs["HDCP-LEVEL"]||"")>(g.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&m.height!==g.height)return m.height-g.height;if(m.frameRate!==g.frameRate)return m.frameRate-g.frameRate;if(m.videoRange!==g.videoRange)return Bn.indexOf(m.videoRange)-Bn.indexOf(g.videoRange);if(m.videoCodec!==g.videoCodec){let E=eu(m.videoCodec),v=eu(g.videoCodec);if(E!==v)return v-E}if(m.uri===g.uri&&m.codecSet!==g.codecSet){let E=Fn(m.codecSet),v=Fn(g.codecSet);if(E!==v)return v-E}return m.averageBitrate!==g.averageBitrate?m.averageBitrate-g.averageBitrate:0});let c=d[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==d.length)){for(let m=0;m<d.length;m++)if(d[m].pathwayId===l[0].pathwayId){c=d[m];break}}this._levels=l;for(let m=0;m<l.length;m++)if(l[m]===c){var h;this._firstLevel=m;let g=c.bitrate,E=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${g}`),((h=this.hls.userConfig)==null?void 0:h.abrEwmaDefaultEstimate)===void 0){let v=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);v>E&&E===Bf.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=v);}break}let u=n&&!r,f={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:!u&&a.some(m=>!!m.url)};this.hls.trigger(p.MANIFEST_PARSED,f),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition);}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let c=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(p.ERROR,{type:K.OTHER_ERROR,details:x.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:c,reason:c.message}),h)return;e=Math.min(e,t.length-1);}let i=this.currentLevelIndex,r=this.currentLevel,n=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&a.details&&r&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);let l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(p.LEVEL_SWITCHING,l);let d=a.details;if(!d||d.live){let c=this.switchParams(a.uri,r?.details,d);this.loadPlaylist(c);}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e);}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e;}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e;}onError(e,t){t.fatal||!t.context||t.context.type===Z.LEVEL&&t.context.level===this.level&&this.checkRetry(t);}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===H.MAIN){let i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;let r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0);}}onLevelLoaded(e,t){var i;let{level:r,details:n}=t,a=this._levels[r];if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=true);return}r===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(r,t,a.details)):(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=true);}loadPlaylist(e){super.loadPlaylist();let t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let r=i.uri;if(e)try{r=e.addDirectives(r);}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`);}let n=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${e?.msn!==void 0?" at sn "+e.msn+" part "+e.part:""} with${n?" Pathway "+n:""} ${r}`),this.clearTimer(),this.hls.trigger(p.LEVEL_LOADING,{url:r,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null});}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e);}removeLevel(e){var t;let i=this._levels.filter((r,n)=>n!==e?true:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(a=>a.level=-1)),false));af(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(p.LEVELS_UPDATED,{levels:i});}onLevelsUpdated(e,{levels:t}){this._levels=t;}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}));}};function Bu(s){let e={};s.forEach(t=>{let i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++;});}var pd=class{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e;}abort(e){for(let i in this.keyUriToKeyInfo){let r=this.keyUriToKeyInfo[i].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort();}}}detach(){for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e];}}destroy(){this.detach();for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e].loader;t&&t.destroy();}this.keyUriToKeyInfo={};}createKeyLoadError(e,t=x.KEY_LOAD_ERROR,i,r,n){return new mt({type:K.NETWORK_ERROR,details:t,fatal:false,frag:e,response:n,error:i,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){let{sn:i,cc:r}=e;for(let n=0;n<t.length;n++){let a=t[n];if(r<=a.cc&&(i==="initSegment"||a.sn==="initSegment"||i<a.sn)){this.emeController.selectKeySystemFormat(a).then(o=>{a.setKeyFormat(o);});break}}}}load(e){return !e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);let n=e.decryptdata;if(!n){let d=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,x.KEY_LOAD_ERROR,d))}let a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,x.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return n.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((r=o)!=null&&r.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case "status-pending":case "usable":case "usable-in-future":return o.keyLoadPromise.then(d=>(n.key=d.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case "ISO-23001-7":case "SAMPLE-AES":case "SAMPLE-AES-CENC":case "SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case "AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,x.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){let i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){let r=this.emeController.loadKey(i);if(r)return (e.keyLoadPromise=r.then(n=>(e.mediaKeySessionContext=n,i))).catch(n=>{throw e.keyLoadPromise=null,n})}return Promise.resolve(i)}loadKeyHTTP(e,t){let i=this.config,r=i.loader,n=new r(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{let l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=i.keyLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,f,m,g)=>{let{frag:E,keyInfo:v,url:A}=m;if(!E.decryptdata||v!==this.keyUriToKeyInfo[A])return o(this.createKeyLoadError(E,x.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));v.decryptdata.key=E.decryptdata.key=new Uint8Array(u.data),E.keyLoader=null,v.loader=null,a({frag:E,keyInfo:v});},onError:(u,f,m,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,x.KEY_LOAD_ERROR,new Error(`HTTP Error ${u.code} loading key ${u.text}`),m,Oe({url:l.url,data:void 0},u)));},onTimeout:(u,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,x.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m));},onAbort:(u,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,x.INTERNAL_ABORTED,new Error("key loading aborted"),m));}};n.load(l,c,h);})}resetLoader(e){let{frag:t,keyInfo:i,url:r}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],n&&n.destroy();}};function $f(){return self.SourceBuffer||self.WebKitSourceBuffer}function Gf(){if(!Ti())return false;let e=$f();return !e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function tv(){if(!Gf())return false;let s=Ti();return typeof s?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(Vs(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(Vs(e,"audio"))))}function iv(){var s;let e=$f();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}var sv=250,wn=2,rv=.1,nv=.05,Ed=class{constructor(e,t,i,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=false,this.stalled=null,this.moved=false,this.seeking=false,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=r;}destroy(){this.media=null,this.hls=this.fragmentTracker=null;}poll(e,t){let{config:i,media:r,stalled:n}=this;if(r===null)return;let{currentTime:a,seeking:o}=r,l=this.seeking&&!o,d=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=true,o||(this.nudgeRetry=0),n!==null){if(this.stallReported){let E=self.performance.now()-n;S.warn(`playback not stuck anymore @${a}, after ${Math.round(E)}ms`),this.stallReported=false;}this.stalled=null;}return}if(d||l){this.stalled=null;return}if(r.paused&&!o||r.ended||r.playbackRate===0||!ue.getBuffered(r).length){this.nudgeRetry=0;return}let c=ue.bufferInfo(r,a,0),h=c.nextStart||0;if(o){let E=c.len>wn,v=!h||t&&t.start<=a||h-a>wn&&!this.fragmentTracker.getPartialFragment(a);if(E||v)return;this.moved=false;}if(!this.moved&&this.stalled!==null){var u;if(!(c.len>0)&&!h)return;let v=Math.max(h,c.start||0)-a,A=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,L=(A==null||(u=A.details)==null?void 0:u.live)?A.details.targetduration*2:wn,y=this.fragmentTracker.getPartialFragment(a);if(v>0&&(v<=L||y)){r.paused||this._trySkipBufferHole(y);return}}let f=self.performance.now();if(n===null){this.stalled=f;return}let m=f-n;if(!o&&m>=sv&&(this._reportStall(c),!this.media))return;let g=ue.bufferInfo(r,a,i.maxBufferHole);this._tryFixBufferStall(g,m);}_tryFixBufferStall(e,t){let{config:i,fragmentTracker:r,media:n}=this;if(n===null)return;let a=n.currentTime,o=r.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-a<i.maxBufferHole)&&t>i.highBufferWatchdogPeriod*1e3&&(S.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer());}_reportStall(e){let{hls:t,media:i,stallReported:r}=this;if(!r&&i){this.stallReported=true;let n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);S.warn(n.message),t.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:x.BUFFER_STALLED_ERROR,fatal:false,error:n,buffer:e.len});}}_trySkipBufferHole(e){let{config:t,hls:i,media:r}=this;if(r===null)return 0;let n=r.currentTime,a=ue.bufferInfo(r,n,0),o=n<a.start?a.start:a.nextStart;if(o){let l=a.len<=t.maxBufferHole,d=a.len>0&&a.len<1&&r.readyState<3,c=o-n;if(c>0&&(l||d)){if(c>t.maxBufferHole){let{fragmentTracker:u}=this,f=false;if(n===0){let m=u.getAppendedFrag(0,H.MAIN);m&&o<m.end&&(f=true);}if(!f){let m=e||u.getAppendedFrag(n,H.MAIN);if(m){let g=false,E=m.end;for(;E<o;){let v=u.getPartialFragment(E);if(v)E+=v.duration;else {g=true;break}}if(g)return 0}}}let h=Math.max(o+nv,n+rv);if(S.warn(`skipping hole, adjusting currentTime from ${n} to ${h}`),this.moved=true,this.stalled=null,r.currentTime=h,e&&!e.gap){let u=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${h}`);i.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:x.BUFFER_SEEK_OVER_HOLE,fatal:false,error:u,reason:u.message,frag:e});}return h}}return 0}_tryNudgeBuffer(){let{config:e,hls:t,media:i,nudgeRetry:r}=this;if(i===null)return;let n=i.currentTime;if(this.nudgeRetry++,r<e.nudgeMaxRetry){let a=n+(r+1)*e.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);S.warn(o.message),i.currentTime=a,t.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:x.BUFFER_NUDGE_ON_STALL,error:o,fatal:false});}else {let a=new Error(`Playhead still not moving while enough data buffered @${n} after ${e.nudgeMaxRetry} nudges`);S.error(a.message),t.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:x.BUFFER_STALLED_ERROR,error:a,fatal:true});}}},av=100,vd=class extends qs{constructor(e,t,i){super(e,t,i,"[stream-controller]",H.MAIN),this.audioCodecSwap=false,this.gapController=null,this.level=-1,this._forceStartLoad=false,this.altAudio=false,this.audioOnly=false,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=false,this.backtrackFragment=null,this.audioCodecSwitch=false,this.videoBuffer=null,this._registerListeners();}_registerListeners(){let{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(p.ERROR,this.onError,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this);}_unregisterListeners(){let{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(p.ERROR,this.onError,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this);}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying();}startLoad(e){if(this.levels){let{lastCurrentTime:t,hls:i}=this;if(this.stopLoad(),this.setInterval(av),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=true):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this.loadedmetadata=false;}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=C.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick();}else this._forceStartLoad=true,this.state=C.STOPPED;}stopLoad(){this._forceStartLoad=false,super.stopLoad();}doTick(){switch(this.state){case C.WAITING_LEVEL:{let{levels:t,level:i}=this,r=t?.[i],n=r?.details;if(n&&(!n.live||this.levelLastLoaded===r)){if(this.waitForCdnTuneIn(n))break;this.state=C.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=C.IDLE;break}break}case C.FRAG_LOADING_WAITING_RETRY:{var e;let t=self.performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){let{levels:r,level:n}=this,a=r?.[n];this.resetStartWhenNotLoaded(a||null),this.state=C.IDLE;}}break}this.state===C.IDLE&&this.doTickIdle(),this.onTickEnd();}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged();}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(t===null||!r&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=e.nextLoadLevel;if(!(i!=null&&i[n]))return;let a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let g={};this.altAudio&&(g.type="video"),this.hls.trigger(p.BUFFER_EOS,g),this.state=C.ENDED;return}e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;let d=a.details;if(!d||this.state===C.WAITING_LEVEL||d.live&&this.levelLastLoaded!==a){this.level=n,this.state=C.WAITING_LEVEL;return}let c=o.len,h=this.getMaxBufferLength(a.maxBitrate);if(c>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);let u=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(u,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&f.sn!=="initSegment"&&this.fragmentTracker.getState(f)!==Pe.OK){var m;let E=((m=this.backtrackFragment)!=null?m:f).sn-d.startSN,v=d.fragments[E-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,u)){if(!f.gap){let E=this.audioOnly&&!this.altAudio?ne.AUDIO:ne.VIDEO,v=(E===ne.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,E,H.MAIN);}f=this.getNextFragmentLoopLoading(f,d,o,H.MAIN,h);}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,u));}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);this.fragCurrent=e,r===Pe.NOT_LOADED||r===Pe.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=true,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e);}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,H.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY);}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let n=this.getLevelDetails();if(n!=null&&n.live){let o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){let o=this.hls.nextLoadLevel,l=e[o],d=this.fragLastKbps;d&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*d)+1:i=0;}else i=0;let a=this.getBufferedFrag(t.currentTime+i);if(a){let o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();let l=o.maxStartPTS?o.maxStartPTS:o.start,d=o.duration,c=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(c,Number.POSITIVE_INFINITY);}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case C.KEY_LOADING:case C.FRAG_LOADING:case C.FRAG_LOADING_WAITING_RETRY:case C.PARSING:case C.PARSED:this.state=C.IDLE;break}this.nextLoadPosition=this.getLoadPosition();}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null);}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Ed(this.config,i,this.fragmentTracker,this.hls);}onMediaDetaching(){let{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching();}onMediaPlaying(){this.tick();}onMediaSeeked(){let e=this.media,t=e?e.currentTime:null;F(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);let i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick();}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(p.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=false,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=false;}onManifestParsed(e,t){let i=false,r=false;t.levels.forEach(n=>{let a=n.audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1);}),this.audioCodecSwitch=i&&r&&!iv(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=false;}onLevelLoading(e,t){let{levels:i}=this;if(!i||this.state!==C.IDLE)return;let r=i[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(r.details))&&(this.state=C.WAITING_LEVEL);}onLevelLoaded(e,t){var i;let{levels:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!r){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);let l=r[n],d=this.fragCurrent;d&&(this.state===C.FRAG_LOADING||this.state===C.FRAG_LOADING_WAITING_RETRY)&&d.level!==t.level&&d.loader&&this.abortCurrentFrag();let c=0;if(a.live||(i=l.details)!=null&&i.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details);}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(p.LEVEL_UPDATED,{details:a,level:n}),this.state===C.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=C.IDLE;}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,c),this.tick();}_handleFragmentLoadProgress(e){var t;let{frag:i,part:r,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let o=a[i.level],l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}let d=o.videoCodec,c=l.PTSKnown||!l.live,h=(t=i.initSegment)==null?void 0:t.data,u=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Zn(this.hls,H.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=r?r.index:-1,g=m!==-1,E=new Ws(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,g),v=this.initPTS[i.cc];f.push(n,h,u,d,i,r,l.totalduration,c,E,v);}onAudioTrackSwitching(e,t){let i=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let 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();let n=this.hls;i&&(n.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),n.trigger(p.AUDIO_TRACK_SWITCHED,t);}}onAudioTrackSwitched(e,t){let i=t.id,r=!!this.hls.audioTracks[i].url;if(r){let n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n);}this.altAudio=r,this.tick();}onBufferCreated(e,t){let i=t.tracks,r,n,a=false;for(let o in i){let l=i[o];if(l.id==="main"){if(n=o,r=l,o==="video"){let d=i[o];d&&(this.videoBuffer=d.buffer);}}else a=true;}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){let{frag:i,part:r}=t;if(i&&i.type!==H.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===C.PARSED&&(this.state=C.IDLE);return}let n=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,r);}onError(e,t){var i;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case x.FRAG_GAP:case x.FRAG_PARSING_ERROR:case x.FRAG_DECRYPT_ERROR:case x.FRAG_LOAD_ERROR:case x.FRAG_LOAD_TIMEOUT:case x.KEY_LOAD_ERROR:case x.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.MAIN,t);break;case x.LEVEL_LOAD_ERROR:case x.LEVEL_LOAD_TIMEOUT:case x.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===Z.LEVEL&&(this.state=C.IDLE);break;case x.BUFFER_APPEND_ERROR:case x.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===x.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case x.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){let{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!ue.getBuffered(e).length){let i=this.state!==C.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i);}this.lastCurrentTime=e.currentTime;}}onFragLoadEmergencyAborted(){this.state=C.IDLE,this.loadedmetadata||(this.startFragRequested=false,this.nextLoadPosition=this.startPosition),this.tickImmediate();}onBufferFlushed(e,{type:t}){if(t!==ne.AUDIO||this.audioOnly&&!this.altAudio){let i=(t===ne.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,H.MAIN),this.tick();}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels;}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap;}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}let r=ue.getBuffered(e),a=(r.length?r.start(0):0)-i;a>0&&(a<this.config.maxBufferHole||a<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${a} to match buffer start`),i+=a,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${t}`),e.currentTime=i;}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=true,this._doFragLoad(e,t).then(i=>{let{hls:r}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=C.IDLE,this.startFragRequested=false,this.bitrateTest=false;let n=e.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),r.trigger(p.FRAG_LOADED,i),e.bitrateTest=false;});}_handleTransmuxComplete(e){var t;let i="main",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:d,level:c}=o,{video:h,text:u,id3:f,initSegment:m}=n,{details:g}=c,E=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=C.PARSING,m){if(m!=null&&m.tracks){let b=l.initSegment||l;this._bufferInitSegment(c,m.tracks,b,a),r.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:b,id:i,tracks:m.tracks});}let v=m.initPTS,A=m.timescale;F(v)&&(this.initPTS[l.cc]={baseTime:v,timescale:A},r.trigger(p.INIT_PTS_FOUND,{frag:l,id:i,initPTS:v,timescale:A}));}if(h&&g&&l.sn!=="initSegment"){let v=g.fragments[l.sn-1-g.startSN],A=l.sn===g.startSN,b=!v||l.cc>v.cc;if(n.independent!==false){let{startPTS:L,endPTS:y,startDTS:D,endDTS:I}=h;if(d)d.elementaryStreams[h.type]={startPTS:L,endPTS:y,startDTS:D,endDTS:I};else if(h.firstKeyFrame&&h.independent&&a.id===1&&!b&&(this.couldBacktrack=true),h.dropped&&h.independent){let k=this.getMainFwdBufferInfo(),P=(k?k.end:this.getLoadPosition())+this.config.maxBufferHole,R=h.firstKeyFramePTS?h.firstKeyFramePTS:L;if(!A&&P<R-this.config.maxBufferHole&&!b){this.backtrack(l);return}else b&&(l.gap=true);l.setElementaryStreamInfo(h.type,l.start,y,l.start,I,true);}else A&&L>wn&&(l.gap=true);l.setElementaryStreamInfo(h.type,L,y,D,I),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(h,l,d,a,A||b);}else if(A||b)l.gap=true;else {this.backtrack(l);return}}if(E){let{startPTS:v,endPTS:A,startDTS:b,endDTS:L}=E;d&&(d.elementaryStreams[ne.AUDIO]={startPTS:v,endPTS:A,startDTS:b,endDTS:L}),l.setElementaryStreamInfo(ne.AUDIO,v,A,b,L),this.bufferFragmentData(E,l,d,a);}if(g&&f!=null&&(t=f.samples)!=null&&t.length){let v={id:i,frag:l,details:g,samples:f.samples};r.trigger(p.FRAG_PARSING_METADATA,v);}if(g&&u){let v={id:i,frag:l,details:g,samples:u.samples};r.trigger(p.FRAG_PARSING_USERDATA,v);}}_bufferInitSegment(e,t,i,r){if(this.state!==C.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;let{audio:n,video:a,audiovideo:o}=t;if(n){let l=e.audioCodec,d=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5");let c=n.metadata;c&&"channelCount"in c&&(c.channelCount||1)!==1&&d.indexOf("firefox")===-1&&(l="mp4a.40.5");}l&&l.indexOf("mp4a.40.5")!==-1&&d.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),n.levelCodec=l,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${n.codec}]`);}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(p.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{let c=t[l].initSegment;c!=null&&c.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:l,data:c,frag:i,part:null,chunkMeta:r,parent:i.type});}),this.tickImmediate();}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,H.MAIN)}backtrack(e){this.couldBacktrack=true,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=C.IDLE;}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===false){let i=e.currentTime;if(ue.isBuffered(e,i)?t=this.getAppendedFrag(i):ue.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;let r=this.fragPlaying,n=t.level;(!r||t.sn!==r.sn||r.level!==n)&&(this.fragPlaying=t,this.hls.trigger(p.FRAG_CHANGED,{frag:t}),(!r||r.level!==n)&&this.hls.trigger(p.LEVEL_SWITCHED,{level:n}));}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){let e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){let e=this.media;if(e){let t=e.currentTime,i=this.currentFrag;if(i&&F(t)&&F(i.programDateTime)){let r=i.programDateTime+(t-i.start)*1e3;return new Date(r)}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},rs=class s{static get version(){return "1.5.15"}static isMSESupported(){return Gf()}static isSupported(){return tv()}static getMediaSource(){return Ti()}static get Events(){return p}static get ErrorTypes(){return K}static get ErrorDetails(){return x}static get DefaultConfig(){return s.defaultConfig?s.defaultConfig:Bf}static set DefaultConfig(e){s.defaultConfig=e;}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=false,this._emitter=new Ld,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,$g(e.debug||false,"Hls instance");let t=this.config=JE(s.DefaultConfig,e);this.userConfig=e,t.progressive&&ev(t);let{abrController:i,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=t,l=new a(this),d=this.abrController=new i(this),c=this.bufferController=new r(this),h=this.capLevelController=new n(this),u=new o(this),f=new gl(this),m=new vl(this),g=t.contentSteeringController,E=g?new g(this):null,v=this.levelController=new gd(this,E),A=new Ll(this),b=new pd(this.config),L=this.streamController=new vd(this,A,b);h.setStreamController(L),u.setStreamController(L);let y=[f,v,L];E&&y.splice(1,0,E),this.networkControllers=y;let D=[d,c,h,u,m,A];this.audioTrackController=this.createController(t.audioTrackController,y);let I=t.audioStreamController;I&&y.push(new I(this,A,b)),this.subtitleTrackController=this.createController(t.subtitleTrackController,y);let k=t.subtitleStreamController;k&&y.push(new k(this,A,b)),this.createController(t.timelineController,D),b.emeController=this.emeController=this.createController(t.emeController,D),this.cmcdController=this.createController(t.cmcdController,D),this.latencyController=this.createController(Tl,D),this.coreComponents=D,y.push(l);let P=l.onErrorOut;typeof P=="function"&&this.on(p.ERROR,P,l);}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i);}once(e,t,i=this){this._emitter.once(e,t,i);}removeAllListeners(e){this._emitter.removeAllListeners(e);}off(e,t,i=this,r){this._emitter.off(e,t,i,r);}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(S.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=true;let r=e===p.ERROR;this.trigger(p.ERROR,{type:K.OTHER_ERROR,details:x.INTERNAL_EXCEPTION,fatal:r,event:e,error:i}),this.triggeringException=false;}}return false}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){S.log("destroy"),this.trigger(p.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null;}attachMedia(e){S.log("attachMedia"),this._media=e,this.trigger(p.MEDIA_ATTACHING,{media:e});}detachMedia(){S.log("detachMedia"),this.trigger(p.MEDIA_DETACHING,void 0),this._media=null;}loadSource(e){this.stopLoad();let t=this.media,i=this.url,r=this.url=Td.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:true});this._autoLevelCapping=-1,this._maxHdcpLevel=null,S.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(p.MANIFEST_LOADING,{url:e});}startLoad(e=-1){S.log(`startLoad(${e})`),this.started=true,this.networkControllers.forEach(t=>{t.startLoad(e);});}stopLoad(){S.log("stopLoad"),this.started=false,this.networkControllers.forEach(e=>{e.stopLoad();});}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1);});}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.stopLoad();});}swapAudioCodec(){S.log("swapAudioCodec"),this.streamController.swapAudioCodec();}recoverMediaError(){S.log("recoverMediaError");let e=this._media;this.detachMedia(),e&&this.attachMedia(e);}removeLevel(e){this.levelController.removeLevel(e);}get levels(){let e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){S.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch();}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){S.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch();}get loadLevel(){return this.levelController.level}set loadLevel(e){S.log(`set loadLevel:${e}`),this.levelController.manualLevel=e;}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e;}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){S.log(`set firstLevel:${e}`),this.levelController.firstLevel=e;}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){S.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e;}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let 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(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e);}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(S.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated());}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Np(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(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this,r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,i)for(let n=r;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e;}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var t;return (t=this.audioTrackController)==null?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return (t=this.subtitleTrackController)==null||t.setSubtitleOption(e),null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e);}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e);}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:false}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e);}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e;}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}};rs.defaultConfig=void 0;var Vf=Symbol.for(""),ov=s=>{if(s?.r===Vf)return s?._$litStatic$},kd=s=>({_$litStatic$:s,r:Vf});var Hf=new Map,Kf=s=>(e,...t)=>{let i=t.length,r,n,a=[],o=[],l,d=0,c=false;for(;d<i;){for(l=e[d];d<i&&(n=t[d],(r=ov(n))!==void 0);)l+=r+e[++d],c=true;d!==i&&o.push(n),a.push(l),d++;}if(d===i&&a.push(e[i]),c){let h=a.join("$$lit$$");(e=Hf.get(h))===void 0&&(a.raw=a,Hf.set(h,e=a)),t=o;}return s(e,...t)},Wf=Kf(chunk5NSCV6C2_cjs.c);var W,Yf,qf,oa,zf,Xf,jf,Qf,wd,Md,Pd,la,Zf,Od,ns,Nd,Jf,em,fe=class extends chunkVW7IKXVI_cjs.a{constructor(){super(...arguments);chunkIPA5Q26W_cjs.e(this,W);this._controls=["play","time","seek","volume","fullscreen","subtitles"];this.popped=false;this._startedPlaying=false;this._intersectionObserver=new chunk5KQJTT3P_cjs.a(this,{callback:chunkIPA5Q26W_cjs.f(this,W,jf).bind(this)});this.embedController=new chunkKCZRQ4AS_cjs.b(this);this._intersected=false;this._queue=[];}get embed(){return this._embedId}set embed(t){this._embedId!=t&&(this._embedId=t,this.embedController.embed=this.embed,this.updateStylePoster(),this.loadTheme());}get token(){return this._token}set token(t){this._token!=t&&(this._token=t,this.requestUpdate("token"),this.embedController.token=this._token);}set loop(t){this._loop=(t===""||t=="true"||t==true)??false;}get loop(){return this._loop}get controls(){return this._controls}set controls(t){typeof t=="string"?this._controls=t.split(" "):this._controls=t;}get cache(){return this._cache}set cache(t){this._cache!=t&&(typeof t=="string"?this._cache=t==="true"||t==="":this._cache=false,this.requestUpdate("caching"),this.embedController.caching=this._cache);}get quality(){return this._quality}set quality(t){this._quality!=t&&(this._quality=t);}get theme(){return this._theme||"default"}set theme(t){this._theme!=t&&(this._theme=t,this.requestUpdate("theme"),this.loadTheme());}get poster(){return !this.embed||!this._embedObj?"":this._poster&&this._poster=="custom"?this.embedController.embedFile(chunkIPA5Q26W_cjs.f(this,W,oa).call(this,"custom_thumbnail")):this._poster&&(!Number.isNaN(parseFloat(this._poster))||!Number.isNaN(parseInt(this._poster)))?this._embedObj.poster&&this._embedObj.poster.renditions&&this._embedObj.poster.renditions.find(t=>t.type=="custom_thumbnail")?this.embedController.embedFile(chunkIPA5Q26W_cjs.f(this,W,oa).call(this,"custom_thumbnail")):`https://image.mave.io/${this.embedController.spaceId}${this.embedController.embedId}.jpg?time=${this._poster}`:this._poster?this._poster:this.embedController.embedFile(chunkIPA5Q26W_cjs.f(this,W,oa).call(this,"thumbnail"))}set poster(t){t&&(this._poster=t,this.requestUpdate("poster"));}pop(){this.popped=true;}close(){this.popped=false;}set muted(t){let i=(t===""||t=="true"||t==true)??false;this._videoElement?this._videoElement.muted=i:this._queue.push(()=>this._videoElement.muted=i);}get muted(){return this._videoElement?.muted||false}set currentTime(t){this._videoElement?this._videoElement.currentTime=t:this._queue.push(()=>this._videoElement.currentTime=t);}get currentTime(){return this._videoElement?this._videoElement?.currentTime:0}get duration(){return new Promise((t,i)=>{if(this._videoElement&&!isNaN(this._videoElement.duration))return t(this._videoElement.duration);let r=()=>{this._videoElement?.addEventListener("loadedmetadata",()=>{this._videoElement&&t(this._videoElement.duration);}),this._videoElement?.addEventListener("error",()=>{i(new Error("Failed to load video metadata."));});};this._videoElement?r():this.addEventListener("mave:video_element_ready",()=>{r();});})}get paused(){return this._videoElement?this._videoElement.paused:true}play(){this._videoElement&&!this.embedController.loading?chunkIPA5Q26W_cjs.f(this,W,la).call(this):this._queue.push(()=>chunkIPA5Q26W_cjs.f(this,W,la).call(this));}restart(){this._videoElement&&(this.pause(),this._videoElement.currentTime=0,this.play());}pause(){this._videoElement?this._videoElement.pause():this._queue.push(()=>this._videoElement?.pause());}updateStylePoster(){this.style.setProperty("background",`center / contain no-repeat url(${this.poster})`);}connectedCallback(){super.connectedCallback(),this.loadTheme(),chunkIPA5Q26W_cjs.f(this,W,qf).call(this);}disconnectedCallback(){super.disconnectedCallback(),this._metricsInstance?.demonitor();}loadTheme(){this.embed&&this._themeLoaded!=this.theme&&(chunkKTP5LV2E_cjs.a.get(this.theme,`${this.embedController.cdnRoot}/themes/player`),this._themeLoaded=this.theme);}updateEmbed(t){this._embedObj=t,this.updateStylePoster(),this.poster=this._embedObj.settings.poster,this.attributes.getNamedItem("color")||(this.color=this._embedObj.settings.color),this.attributes.getNamedItem("opacity")||(this.opacity=this._embedObj.settings.opacity?this._embedObj.settings.opacity:void 0),this.attributes.getNamedItem("aspect-ratio")||(this.aspect_ratio=this._embedObj.settings.aspect_ratio),this.attributes.getNamedItem("width")||(this.width=this._embedObj.settings.width),this.attributes.getNamedItem("height")||(this.height=this._embedObj.settings.height),this.attributes.getNamedItem("autoplay")||(this.autoplay=this._embedObj.settings.autoplay=="on_show"?"lazy":this._embedObj.settings.autoplay),this.attributes.getNamedItem("controls")||(this.controls=this._embedObj.settings.controls),this.attributes.getNamedItem("loop")||(this.loop=this._embedObj.settings.loop);}get styles(){let t={};return (this.color||this._embedObj?.settings.color)&&(t["--primary-color"]=`${this.color||this._embedObj?.settings.color}${this.opacity||this._embedObj?.settings.opacity?this._embedObj?.settings.opacity:""}`),this.aspect_ratio=="auto"||this._embedObj?.settings.aspect_ratio=="auto"&&!this.aspect_ratio?t["--aspect-ratio"]=this._embedObj?.video.aspect_ratio:t["--aspect-ratio"]=this.aspect_ratio||this._embedObj?.settings.aspect_ratio,(this.width||this._embedObj?.settings.width)&&(t["--width"]=this.width||this._embedObj?.settings.width),(this.height||this._embedObj?.settings.height)&&(t["--height"]=this.height||this._embedObj?.settings.height),!this.controls.includes("full")&&!this.controls.includes("big")&&!this.controls.includes("none")&&(t["--play-display"]=this.controls.includes("play")?"flex":"none",t["--time-display"]=this.controls.includes("time")?"flex":"none",t["--seek-bar-visibility"]=this.controls.includes("seek")?"visible":"hidden",t["--volume-display"]=this.controls.includes("volume")?"flex":"none",t["--fullscreen-display"]=this.controls.includes("fullscreen")?"flex":"none",t["--captions-display"]=this.controls.includes("subtitles")?"flex":"none"),t["--playbackrate-display"]=this.controls.includes("rate")?"flex":"none",((this.subtitles=="none"||this.subtitles=="off"||this._embedObj?.subtitles.length==0)&&!this.active_subtitle||this._embedObj?.created_at<1740674988&&!this.subtitles&&!this.active_subtitle)&&(t["--captions-display"]="none"),this.controls.includes("full")||this._embedObj?.settings.controls=="full"&&!this.controls.includes("big")&&!this.controls.includes("none")?t["--media-control-bar-display"]="flex":t["--media-control-bar-display"]="none",this.controls.includes("big")||this._embedObj?.settings.controls=="big"&&!this.controls.includes("full")&&!this.controls.includes("none")?t["--big-button-display"]="flex":t["--big-button-display"]="none",this._embedObj?.video.audio===false?t["--media-volume-display"]="none":t["--media-volume-display"]="inline-flex",chunkQ22T22LT_cjs.a(t)}render(){if(!this.embed)return;let t=this.querySelector('[slot="start-screen"]');return chunk5NSCV6C2_cjs.c`
1129
+ } (data length: ${t&&t.byteLength})`),r.update(t)}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,i)=>{let r=Wo(this.config),n=e.map(qh).filter(a=>!!a&&r.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:a})=>{let o=Xh(a);o?t(o):i(new Error(`Unable to find format for key-system "${a}"`));}).catch(i)})}loadKey(e){let t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let n=this.keyIdToKeySessionPromise[i];return n||(n=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();let l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:t});return this.generateRequestWithPreferredKeySession(l,"cenc",t.pssh,"playlist-key")}))),n.catch(a=>this.handleError(a))),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof ze?this.hls.trigger(p.ERROR,e.data):this.hls.trigger(p.ERROR,{type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_KEYS,error:e,fatal:true}));}getKeySystemForKeyPromise(e){let t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){let r=qh(e.keyFormat),n=r?[r]:Wo(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Wo(this.config)),e.length===0)throw new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:true},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){let{initDataType:t,initData:i}=e,r=`"${e.type}" event: init data type: "${t}"`;if(this.debug(r),i===null)return;let n,a;if(t==="sinf"&&this.config.drmSystems[de.FAIRPLAY]){let h=xe(new Uint8Array(i));try{let u=Ad(JSON.parse(h).sinf),f=Xu(new Uint8Array(u));if(!f)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");n=f.subarray(8,24),a=de.FAIRPLAY;}catch(u){this.warn(`${r} Failed to parse sinf: ${u}`);return}}else {let h=Tp(i),u=h.filter(f=>f.systemId===Fs.WIDEVINE)[0];if(!u){h.length===0||h.some(f=>!f.systemId)?this.warn(`${r} contains incomplete or invalid pssh data`):this.log(`ignoring ${r} for ${h.map(f=>zh(f.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(a=zh(u.systemId),u.version===0&&u.data){let f=u.data.length-22;n=u.data.subarray(f,f+16);}}if(!a||!n)return;let o=Pt.hexDump(n),{keyIdToKeySessionPromise:l,mediaKeySessions:d}=this,c=l[o];for(let h=0;h<d.length;h++){let u=d[h],f=u.decryptdata;if(!f.keyId)continue;let m=Pt.hexDump(f.keyId);if(o===m||f.uri.replace(/-/g,"").indexOf(o)!==-1){if(c=l[m],f.pssh)break;delete l[m],f.pssh=new Uint8Array(i),f.keyId=n,c=l[o]=c.then(()=>this.generateRequestWithPreferredKeySession(u,t,i,"encrypted-event-key-match"));break}}c||(c=l[o]=this.getKeySystemSelectionPromise([a]).then(({keySystem:h,mediaKeys:u})=>{var f;this.throwIfDestroyed();let m=new Hs("ISO-23001-7",o,(f=Xh(h))!=null?f:"");return m.pssh=new Uint8Array(i),m.keyId=n,this.attemptSetMediaKeys(h,u).then(()=>{this.throwIfDestroyed();let g=this.createMediaKeySessionContext({decryptdata:m,keySystem:h,mediaKeys:u});return this.generateRequestWithPreferredKeySession(g,t,i,"encrypted-event-no-match")})})),c.catch(h=>this.handleError(h));}_onWaitingForKey(e){this.log(`"${e.type}" event`);}attemptSetMediaKeys(e,t){let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1);})}generateRequestWithPreferredKeySession(e,t,i,r){var n,a;let o=(n=this.config.drmSystems)==null||(a=n[e.keySystem])==null?void 0:a.generateRequest;if(o)try{let m=o.call(this.hls,t,i,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,i=e.decryptdata.pssh=m.initData?new Uint8Array(m.initData):null;}catch(m){var l;if(this.warn(m.message),(l=this.hls)!=null&&l.config.debug)throw m}if(i===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let d=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${d} (init data type: ${t} length: ${i?i.byteLength:null})`);let c=new Ld,h=e._onmessage=m=>{let g=e.mediaKeysSession;if(!g){c.emit("error",new Error("invalid state"));return}let{messageType:E,message:v}=m;this.log(`"${E}" message event for session "${g.sessionId}" message size: ${v.byteLength}`),E==="license-request"||E==="license-renewal"?this.renewLicense(e,v).catch(A=>{this.handleError(A),c.emit("error",A);}):E==="license-release"?e.keySystem===de.FAIRPLAY&&(this.updateKeySession(e,fl("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${E}"`);},u=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){c.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);let E=e.keyStatus;c.emit("keyStatus",E),E==="expired"&&(this.warn(`${e.keySystem} expired for key ${d}`),this.renewKeySession(e));};e.mediaKeysSession.addEventListener("message",h),e.mediaKeysSession.addEventListener("keystatuseschange",u);let f=new Promise((m,g)=>{c.on("error",g),c.on("keyStatus",E=>{E.startsWith("usable")?m():E==="output-restricted"?g(new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:false},"HDCP level output restricted")):E==="internal-error"?g(new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:true},`key status changed to "${E}"`)):E==="expired"?g(new Error("key expired while generating request")):this.warn(`unhandled key status change "${E}"`);});});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var m;this.log(`Request generated for key-session "${(m=e.mediaKeysSession)==null?void 0:m.sessionId}" keyId: ${d}`);}).catch(m=>{throw new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_SESSION,error:m,fatal:false},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>{throw c.removeAllListeners(),this.removeSession(e),m}).then(()=>(c.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${Pt.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${Pt.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t;});}fetchServerCertificate(e){let t=this.config,i=t.loader,r=new i(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{let l={responseType:"arraybuffer",url:n},d=t.certLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,f,m,g)=>{a(u.data);},onError:(u,f,m,g)=>{o(new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:true,networkDetails:m,response:Oe({url:l.url,data:void 0},u)},`"${e}" certificate request failed (${n}). Status: ${u.code} (${u.text})`));},onTimeout:(u,f,m)=>{o(new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:true,networkDetails:m,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`));},onAbort:(u,f,m)=>{o(new Error("aborted"));}};r.load(l,c,h);})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((r,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i?.byteLength}) on "${t}"`),r(e);}).catch(a=>{n(new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:true},a.message));});})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(r=>{throw new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:r,fatal:true},r.message)}))}unpackPlayReadyKeyMessage(e,t){let i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let r=new DOMParser().parseFromString(i,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let c;for(let h=0,u=n.length;h<u;h++){var a,o;c=n[h];let f=(a=c.querySelector("name"))==null?void 0:a.textContent,m=(o=c.querySelector("value"))==null?void 0:o.textContent;f&&m&&e.setRequestHeader(f,m);}}let l=r.querySelector("Challenge"),d=l?.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return fl(atob(d))}setupLicenseXHR(e,t,i,r){let n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,r)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,true),n.call(this.hls,e,t,i,r)}).then(a=>(e.readyState||e.open("POST",t,true),{xhr:e,licenseChallenge:a||r})):(e.open("POST",t,true),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{let a=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${a}`);let 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}`);let d=this.config.licenseResponseCallback;if(d)try{l=d.call(this.hls,o,a,e);}catch(c){this.error(c);}r(l);}else {let l=i.errorRetry,d=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)n(new ze({type:K.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:true,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 {let c=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${c} 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==de.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(l,d)),l.send(d);});})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey);}onMediaDetached(){let e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Hs.clearKeyUriToKeyIdMap();let i=t.length;s.CDMCleanupPromise=Promise.all(t.map(r=>this.removeSession(r)).concat(e?.setMediaKeys(null).catch(r=>{this.log(`Could not clear media keys: ${r}`);}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0);}).catch(r=>{this.log(`Could not close sessions and clear media keys: ${r}`);});}onManifestLoading(){this.keyFormatPromise=null;}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let i=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i);}}removeSession(e){let{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch(n=>{this.log(`Could not remove session: ${n}`);}).then(()=>t.close()).catch(n=>{this.log(`Could not close session: ${n}`);})}}};ia.CDMCleanupPromise=void 0;var ze=class 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;}},He;(function(s){s.MANIFEST="m",s.AUDIO="a",s.VIDEO="v",s.MUXED="av",s.INIT="i",s.CAPTION="c",s.TIMED_TEXT="tt",s.KEY="k",s.OTHER="o";})(He||(He={}));var ld;(function(s){s.DASH="d",s.HLS="h",s.SMOOTH="s",s.OTHER="o";})(ld||(ld={}));var Ei;(function(s){s.OBJECT="CMCD-Object",s.REQUEST="CMCD-Request",s.SESSION="CMCD-Session",s.STATUS="CMCD-Status";})(Ei||(Ei={}));var aE={[Ei.OBJECT]:["br","d","ot","tb"],[Ei.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Ei.SESSION]:["cid","pr","sf","sid","st","v"],[Ei.STATUS]:["bs","rtp"]},Xs=class s{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(i=>i instanceof s?i:new s(i))),this.value=e,this.params=t;}},sa=class{constructor(e){this.description=void 0,this.description=e;}},oE="Dict";function lE(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function dE(s,e,t,i){return new Error(`failed to ${s} "${lE(e)}" as ${t}`,{cause:i})}var Ou="Bare Item",cE="Boolean",hE="Byte Sequence",uE="Decimal",fE="Integer";function mE(s){return s<-999999999999999||999999999999999<s}var gE=/[\x00-\x1f\x7f]+/,pE="Token",EE="Key";function Ut(s,e,t){return dE("serialize",s,e,t)}function vE(s){if(typeof s!="boolean")throw Ut(s,cE);return s?"?1":"?0"}function TE(s){return btoa(String.fromCharCode(...s))}function AE(s){if(ArrayBuffer.isView(s)===false)throw Ut(s,hE);return `:${TE(s)}:`}function Pf(s){if(mE(s))throw Ut(s,fE);return s.toString()}function bE(s){return `@${Pf(s.getTime()/1e3)}`}function Of(s,e){if(s<0)return -Of(-s,e);let t=Math.pow(10,e);if(Math.abs(s*t%1-.5)<Number.EPSILON){let r=Math.floor(s*t);return (r%2===0?r:r+1)/t}else return Math.round(s*t)/t}function yE(s){let e=Of(s,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Ut(s,uE);let t=e.toString();return t.includes(".")?t:`${t}.0`}var SE="String";function _E(s){if(gE.test(s))throw Ut(s,SE);return `"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function xE(s){return s.description||s.toString().slice(7,-1)}function Nu(s){let e=xE(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===false)throw Ut(e,pE);return e}function dd(s){switch(typeof s){case "number":if(!F(s))throw Ut(s,Ou);return Number.isInteger(s)?Pf(s):yE(s);case "string":return _E(s);case "symbol":return Nu(s);case "boolean":return vE(s);case "object":if(s instanceof Date)return bE(s);if(s instanceof Uint8Array)return AE(s);if(s instanceof sa)return Nu(s);default:throw Ut(s,Ou)}}function cd(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===false)throw Ut(s,EE);return s}function Cd(s){return s==null?"":Object.entries(s).map(([e,t])=>t===true?`;${cd(e)}`:`;${cd(e)}=${dd(t)}`).join("")}function Nf(s){return s instanceof Xs?`${dd(s.value)}${Cd(s.params)}`:dd(s)}function IE(s){return `(${s.value.map(Nf).join(" ")})${Cd(s.params)}`}function LE(s,e={whitespace:true}){if(typeof s!="object")throw Ut(s,oE);let t=s instanceof Map?s.entries():Object.entries(s),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof Xs||(n=new Xs(n));let a=cd(r);return n.value===true?a+=Cd(n.params):(a+="=",Array.isArray(n.value)?a+=IE(n):a+=Nf(n)),a}).join(`,${i}`)}function RE(s,e){return LE(s,e)}var DE=s=>s==="ot"||s==="sf"||s==="st",CE=s=>typeof s=="number"?F(s):s!=null&&s!==""&&s!==false;function kE(s,e){let t=new URL(s),i=new URL(e);if(t.origin!==i.origin)return s;let r=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")}function wE(){try{return crypto.randomUUID()}catch{try{let 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=>{let n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(r=="x"?n:n&3|8).toString(16)})}}}var kn=s=>Math.round(s),ME=(s,e)=>(e!=null&&e.baseUrl&&(s=kE(s,e.baseUrl)),encodeURIComponent(s)),xn=s=>kn(s/100)*100,PE={br:kn,d:kn,bl:xn,dl:xn,mtp:xn,nor:ME,rtp:xn,tb:kn};function OE(s,e){let t={};if(s==null||typeof s!="object")return t;let i=Object.keys(s).sort(),r=_e({},PE,e?.formatters),n=e?.filter;return i.forEach(a=>{if(n!=null&&n(a))return;let o=s[a],l=r[a];l&&(o=l(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||CE(o)&&(DE(a)&&typeof o=="string"&&(o=new sa(o)),t[a]=o));}),t}function Ff(s,e={}){return s?RE(OE(s,e),_e({whitespace:false},e)):""}function NE(s,e={}){if(!s)return {};let t=Object.entries(s),i=Object.entries(aE).concat(Object.entries(e?.customHeaderMap||{})),r=t.reduce((n,a)=>{var o;let[d,c]=a,h=((o=i.find(u=>u[1].includes(d)))==null?void 0:o[0])||Ei.REQUEST;return (n[h])!=null||(n[h]={}),n[h][d]=c,n},{});return Object.entries(r).reduce((n,[a,o])=>(n[a]=Ff(o,e),n),{})}function FE(s,e,t){return _e(s,NE(e,t))}var UE="CMCD";function BE(s,e={}){if(!s)return "";let t=Ff(s,e);return `${UE}=${encodeURIComponent(t)}`}var Fu=/CMCD=[^&#]+/;function $E(s,e,t){let i=BE(e,t);if(!i)return s;if(Fu.test(s))return s.replace(Fu,i);let r=s.includes("?")?"&":"?";return `${s}${r}${i}`}var hd=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=false,this.includeKeys=void 0,this.initialized=false,this.starved=false,this.buffering=true,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=true),this.buffering=true;},this.onPlaying=()=>{this.initialized||(this.initialized=true),this.buffering=false;},this.applyPlaylistData=r=>{try{this.apply(r,{ot:He.MANIFEST,su:!this.initialized});}catch(n){S.warn("Could not generate manifest CMCD data.",n);}},this.applyFragmentData=r=>{try{let n=r.frag,a=this.hls.levels[n.level],o=this.getObjectType(n),l={d:n.duration*1e3,ot:o};(o===He.VIDEO||o===He.AUDIO||o==He.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(r,l);}catch(n){S.warn("Could not generate segment CMCD data.",n);}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||wE(),this.cid=i.contentId,this.useHeaders=i.useHeaders===true,this.includeKeys=i.includeKeys,this.registerListeners());}registerListeners(){let e=this.hls;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this);}unregisterListeners(){let e=this.hls;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this);}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null;}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying);}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null);}onBufferCreated(e,t){var i,r;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(r=t.tracks.video)==null?void 0:r.buffer;}createData(){var e;return {v:1,sf:ld.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){_e(t,this.createData());let i=t.ot===He.INIT||t.ot===He.VIDEO||t.ot===He.MUXED;this.starved&&i&&(t.bs=true,t.su=true,this.starved=false),t.su==null&&(t.su=this.buffering);let{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((n,a)=>(r.includes(a)&&(n[a]=t[a]),n),{})),this.useHeaders?(e.headers||(e.headers={}),FE(e.headers,t)):e.url=$E(e.url,t);}getObjectType(e){let{type:t}=e;if(t==="subtitle")return He.TIMED_TEXT;if(e.sn==="initSegment")return He.INIT;if(t==="audio")return He.AUDIO;if(t==="main")return this.hls.audioTracks.length?He.VIDEO:He.MUXED}getTopBandwidth(e){let t=0,i,r=this.hls;if(e===He.AUDIO)i=r.audioTracks;else {let n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;i=r.levels.slice(0,a);}for(let n of i)n.bitrate>t&&(t=n.bitrate);return t>0?t:NaN}getBufferLength(e){let t=this.hls.media,i=e===He.AUDIO?this.audioBuffer:this.videoBuffer;return !i||!t?NaN:ue.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n);}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy();}abort(){this.loader.abort();}load(n,a,o){t(n),this.loader.load(n,a,o);}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n);}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy();}abort(){this.loader.abort();}load(n,a,o){t(n),this.loader.load(n,a,o);}}}},GE=3e5,ud=class{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=false,this.enabled=true,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=S.log.bind(S,"[content-steering]:"),this.registerListeners();}registerListeners(){let e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this);}unregisterListeners(){let e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this));}startLoad(){if(this.started=true,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri);}}stopLoad(){this.started=false,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){let t=this.levels;t&&(this.levels=t.filter(i=>i!==e));}onManifestLoading(){this.stopLoad(),this.enabled=true,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null;}onManifestLoaded(e,t){let{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad());}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks;}onError(e,t){let{errorAction:i}=t;if(i?.action===Me.SendAlternateToPenaltyBox&&i.flags===ut.MoveAllAlternatesMatchingHost){let r=this.levels,n=this.pathwayPriority,a=this.pathwayId;if(t.context){let{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=r.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),i.resolved||S.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${r&&r.length} priorities: ${JSON.stringify(n)} penalized: ${JSON.stringify(this.penalizedPathways)}`);}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i;}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t,i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(n=>{r-i[n]>GE&&delete i[n];});for(let n=0;n<e.length;n++){let a=e[n];if(a in i)continue;if(a===this.pathwayId)return;let 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,af(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});let 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,i){let r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===Z.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===Z.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return i}clonePathways(e){let t=this.levels;if(!t)return;let i={},r={};e.forEach(n=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(c=>c.pathwayId===a))return;let d=this.getLevelsForPathway(o).map(c=>{let h=new Ee(c.attrs);h["PATHWAY-ID"]=a;let u=h.AUDIO&&`${h.AUDIO}_clone_${a}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;u&&(i[h.AUDIO]=u,h.AUDIO=u),f&&(r[h.SUBTITLES]=f,h.SUBTITLES=f);let m=Uf(c.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new Jt({attrs:h,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:m,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(let E=1;E<c.audioGroups.length;E++)g.addGroupId("audio",`${c.audioGroups[E]}_clone_${a}`);if(c.subtitleGroups)for(let E=1;E<c.subtitleGroups.length;E++)g.addGroupId("text",`${c.subtitleGroups[E]}_clone_${a}`);return g});t.push(...d),Uu(this.audioTracks,i,l,a),Uu(this.subtitleTracks,r,l,a);});}loadSteeringManifest(e){let t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let r;try{r=new self.URL(e);}catch{this.enabled=false,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){let c=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+c);}let 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:(c,h,u,f)=>{this.log(`Loaded steering manifest: "${r}"`);let m=c.data;if(m.VERSION!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;let{"RELOAD-URI":g,"PATHWAY-CLONES":E,"PATHWAY-PRIORITY":v}=m;if(g)try{this.uri=new self.URL(g,r).href;}catch{this.enabled=false,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||u.url),E&&this.clonePathways(E);let A={steeringManifest:m,url:r.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,A),v&&this.updatePathwayPriority(v);},onError:(c,h,u,f)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${h.url})`),this.stopLoad(),c.code===410){this.enabled=false,this.log(`Steering manifest ${h.url} no longer available`);return}let m=this.timeToLoad*1e3;if(c.code===429){let g=this.loader;if(typeof g?.getResponseHeader=="function"){let E=g.getResponseHeader("Retry-After");E&&(m=parseFloat(E)*1e3);}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,m);},onTimeout:(c,h,u)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url);}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,l,d);}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;let r=(i=this.hls)==null?void 0:i.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3);},t);}};function Uu(s,e,t,i){s&&Object.keys(e).forEach(r=>{let n=s.filter(a=>a.groupId===r).map(a=>{let o=_e({},a);return o.details=void 0,o.attrs=new Ee(o.attrs),o.url=o.attrs.URI=Uf(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=i,o});s.push(...n);});}function Uf(s,e,t,i){let{HOST:r,PARAMS:n,[t]:a}=i,o;e&&(o=a?.[e],o&&(s=o));let l=new self.URL(s);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(d=>{d&&l.searchParams.set(d,n[d]);}),l.href}var HE=/^age:\s*[\d.]+\s*$/im,ra=class{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 ts,this.retryDelay=0;}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null;}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=true,e.abort()));}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader);}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal();}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=false;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n(i,t.url)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,true),n(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e);}).catch(a=>{this.callbacks.onError({code:i.status,text:a.message},t,i,r);}):this.openAndSendXhr(i,t,e);}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,true);let r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(r)for(let o in r)e.setRequestHeader(o,r[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&F(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send();}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let r=t.readyState,n=this.config;if(!i.aborted&&r>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let a=t.status,o=t.responseType!=="text";if(a>=200&&a<300&&(o&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);let l=o?t.response:t.responseText,d=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=d,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;let c=this.callbacks.onProgress;if(c&&c(i,e,l,t),!this.callbacks)return;let h={url:t.responseURL,data:l,code:a};this.callbacks.onSuccess(h,i,e,t);}else {let l=n.loadPolicy.errorRetry,d=i.retry,c={url:e.url,data:void 0,code:a};Hn(l,d,false,c)?this.retry(l):(S.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:t.statusText},e,t,i));}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Hn(e,t,true))this.retry(e);else {var i;S.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);let r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader));}}retry(e){let{context:t,stats:i}=this;this.retryDelay=Sd(e,i.retry),i.retry++,S.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay);}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total);}getCacheAge(){let e=null;if(this.loader&&HE.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null;}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}};function VE(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return false}var KE=/(\d+)-(\d+)\/(\d+)/,na=class{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||zE,this.controller=new self.AbortController,this.stats=new ts;}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=true,this.controller.abort());}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response);}load(e,t,i){let r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();let n=WE(e,this.controller.signal),a=i.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:d,maxLoadTimeMs:c}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=d&&F(d)?d:c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response);},t.timeout),self.fetch(this.request).then(h=>{this.response=this.loader=h;let u=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response);},c-(u-r.loading.start)),!h.ok){let{status:f,statusText:m}=h;throw new fd(m||"fetch, bad network response",f,h)}return r.loading.first=u,r.total=qE(h.headers)||r.total,a&&F(t.highWaterMark)?this.loadProgressively(h,r,e,t.highWaterMark,a):o?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{let u=this.response;if(!u)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let f=h[l];f&&(r.loaded=r.total=f);let m={url:u.url,data:h,code:u.status};a&&!F(t.highWaterMark)&&a(r,e,h,u),i.onSuccess(m,r,e,u);}).catch(h=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;let u=h&&h.code||0,f=h?h.message:null;i.onError({code:u,text:f},e,h?h.details:null,r);});}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null;}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,n){let a=new Wn,o=e.body.getReader(),l=()=>o.read().then(d=>{if(d.done)return a.dataLength&&n(t,i,a.flush(),e),Promise.resolve(new ArrayBuffer(0));let c=d.value,h=c.length;return t.loaded+=h,h<r||a.dataLength?(a.push(c),a.dataLength>=r&&n(t,i,a.flush(),e)):n(t,i,c,e),l()}).catch(()=>Promise.reject());return l()}};function WE(s,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(_e({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function YE(s){let e=KE.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function qE(s){let e=s.get("Content-Range");if(e){let i=YE(e);if(F(i))return i}let t=s.get("Content-Length");if(t)return parseInt(t)}function zE(s,e){return new self.Request(s.url,e)}var fd=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i;}},XE=/\s/,jE={newCue(s,e,t,i){let r=[],n,a,o,l,d,c=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=true,l=0,d="",!n.isEmpty()){var h;for(let g=0;g<n.chars.length;g++)XE.test(n.chars[g].uchar)&&o?l++:(d+=n.chars[g].uchar,o=false);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=Df(d.trim()),m=Dd(e,t,f);s!=null&&(h=s.cues)!=null&&h.getCueById(m)||(a=new c(e,t,f),a.id=m,a.line=u+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a));}return s&&r.length&&(r.sort((u,f)=>u.line==="auto"||f.line==="auto"?0:u.line>8&&f.line>8?f.line-u.line:u.line-f.line),r.forEach(u=>tf(s,u))),r}},QE={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Bf=Oe(Oe({autoStartLoad:true,startPosition:-1,defaultAudioCodec:void 0,debug:false,capLevelOnFPSDrop:false,capLevelToPlayerSize:false,ignoreDevicePixelRatio:false,preferManagedMediaSource:true,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:false,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:true,workerPath:null,enableSoftwareAES:true,startLevel:void 0,startFragPrefetch:false,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:ra,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:xl,bufferController:Ql,capLevelController:ad,errorController:Sl,fpsController:od,stretchShortVideoTrack:false,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:true,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:false,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:false,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Gu,testBandwidth:true,progressive:false,lowLatencyMode:true,cmcd:void 0,enableDateRangeMetadataCues:true,enableEmsgMetadataCues:true,enableID3MetadataCues:true,useMediaCapabilities:true,certLoadPolicy:{default:QE},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},ZE()),{},{subtitleStreamController:ql,subtitleTrackController:Xl,timelineController:nd,audioStreamController:Wl,audioTrackController:Yl,emeController:ia,cmcdController:hd,contentSteeringController:ud});function ZE(){return {cueHandler:jE,enableWebVTT:true,enableIMSC1:true,enableCEA708Captions:true,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:true}}function JE(s,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let t=md(s),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{let a=`${n==="level"?"playlist":n}LoadPolicy`,o=e[a]===void 0,l=[];r.forEach(d=>{let c=`${n}Loading${d}`,h=e[c];if(h!==void 0&&o){l.push(c);let u=t[a].default;switch(e[a]={default:u},d){case "TimeOut":u.maxLoadTimeMs=h,u.maxTimeToFirstByteMs=h;break;case "MaxRetry":u.errorRetry.maxNumRetry=h,u.timeoutRetry.maxNumRetry=h;break;case "RetryDelay":u.errorRetry.retryDelayMs=h,u.timeoutRetry.retryDelayMs=h;break;case "MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=h,u.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&S.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`);}),Oe(Oe({},t),e)}function md(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(md):Object.keys(s).reduce((e,t)=>(e[t]=md(s[t]),e),{}):s}function ev(s){let e=s.loader;e!==na&&e!==ra?(S.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=false):VE()&&(s.loader=na,s.progressive=true,s.enableSoftwareAES=true,S.log("[config]: Progressive streaming enabled, using FetchLoader"));}var dl,gd=class extends Ks{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(){let{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this);}_unregisterListeners(){let{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.ERROR,this.onError,this);}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy();}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0;}),super.stopLoad();}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1;}onManifestLoading(e,t){this.resetLevels();}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,r=[],n={},a={},o=false,l=false,d=false;t.levels.forEach(c=>{var h,u;let f=c.attrs,{audioCodec:m,videoCodec:g}=c;((h=m)==null?void 0:h.indexOf("mp4a.40.34"))!==-1&&(dl||(dl=/chrome|firefox/i.test(navigator.userAgent)),dl&&(c.audioCodec=m=void 0)),m&&(c.audioCodec=m=Un(m,i)),((u=g)==null?void 0:u.indexOf("avc1"))===0&&(g=c.videoCodec=Lp(g));let{width:E,height:v,unknownCodecs:A}=c;if(o||(o=!!(E&&v)),l||(l=!!g),d||(d=!!m),A!=null&&A.length||m&&!Xo(m,"audio",i)||g&&!Xo(g,"video",i))return;let{CODECS:b,"FRAME-RATE":L,"HDCP-LEVEL":y,"PATHWAY-ID":D,RESOLUTION:I,"VIDEO-RANGE":k}=f,R=`${`${D||"."}-`}${c.bitrate}-${I}-${L}-${b}-${k}-${y}`;if(n[R])if(n[R].uri!==c.url&&!c.attrs["PATHWAY-ID"]){let w=a[R]+=1;c.attrs["PATHWAY-ID"]=new Array(w+1).join(".");let X=new Jt(c);n[R]=X,r.push(X);}else n[R].addGroupId("audio",f.AUDIO),n[R].addGroupId("text",f.SUBTITLES);else {let w=new Jt(c);n[R]=w,a[R]=1,r.push(w);}}),this.filterAndSortMediaOptions(r,t,o,l,d);}filterAndSortMediaOptions(e,t,i,r,n){let a=[],o=[],l=e;if((i||r)&&n&&(l=l.filter(({videoCodec:m,videoRange:g,width:E,height:v})=>(!!m||!!(E&&v))&&Fp(g))),l.length===0){Promise.resolve().then(()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);let m=new Error("no level with compatible codecs found in manifest");this.hls.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:x.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:true,url:t.url,error:m,reason:m.message});}});return}if(t.audioTracks){let{preferManagedMediaSource:m}=this.hls.config;a=t.audioTracks.filter(g=>!g.audioCodec||Xo(g.audioCodec,"audio",m)),Bu(a);}t.subtitles&&(o=t.subtitles,Bu(o));let d=l.slice(0);l.sort((m,g)=>{if(m.attrs["HDCP-LEVEL"]!==g.attrs["HDCP-LEVEL"])return (m.attrs["HDCP-LEVEL"]||"")>(g.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&m.height!==g.height)return m.height-g.height;if(m.frameRate!==g.frameRate)return m.frameRate-g.frameRate;if(m.videoRange!==g.videoRange)return Bn.indexOf(m.videoRange)-Bn.indexOf(g.videoRange);if(m.videoCodec!==g.videoCodec){let E=eu(m.videoCodec),v=eu(g.videoCodec);if(E!==v)return v-E}if(m.uri===g.uri&&m.codecSet!==g.codecSet){let E=Fn(m.codecSet),v=Fn(g.codecSet);if(E!==v)return v-E}return m.averageBitrate!==g.averageBitrate?m.averageBitrate-g.averageBitrate:0});let c=d[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==d.length)){for(let m=0;m<d.length;m++)if(d[m].pathwayId===l[0].pathwayId){c=d[m];break}}this._levels=l;for(let m=0;m<l.length;m++)if(l[m]===c){var h;this._firstLevel=m;let g=c.bitrate,E=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${g}`),((h=this.hls.userConfig)==null?void 0:h.abrEwmaDefaultEstimate)===void 0){let v=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);v>E&&E===Bf.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=v);}break}let u=n&&!r,f={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:!u&&a.some(m=>!!m.url)};this.hls.trigger(p.MANIFEST_PARSED,f),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition);}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let c=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(p.ERROR,{type:K.OTHER_ERROR,details:x.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:c,reason:c.message}),h)return;e=Math.min(e,t.length-1);}let i=this.currentLevelIndex,r=this.currentLevel,n=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&a.details&&r&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);let l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(p.LEVEL_SWITCHING,l);let d=a.details;if(!d||d.live){let c=this.switchParams(a.uri,r?.details,d);this.loadPlaylist(c);}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e);}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e;}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e;}onError(e,t){t.fatal||!t.context||t.context.type===Z.LEVEL&&t.context.level===this.level&&this.checkRetry(t);}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===H.MAIN){let i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;let r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0);}}onLevelLoaded(e,t){var i;let{level:r,details:n}=t,a=this._levels[r];if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=true);return}r===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(r,t,a.details)):(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=true);}loadPlaylist(e){super.loadPlaylist();let t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let r=i.uri;if(e)try{r=e.addDirectives(r);}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`);}let n=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${e?.msn!==void 0?" at sn "+e.msn+" part "+e.part:""} with${n?" Pathway "+n:""} ${r}`),this.clearTimer(),this.hls.trigger(p.LEVEL_LOADING,{url:r,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null});}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e);}removeLevel(e){var t;let i=this._levels.filter((r,n)=>n!==e?true:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(a=>a.level=-1)),false));af(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(p.LEVELS_UPDATED,{levels:i});}onLevelsUpdated(e,{levels:t}){this._levels=t;}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}));}};function Bu(s){let e={};s.forEach(t=>{let i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++;});}var pd=class{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e;}abort(e){for(let i in this.keyUriToKeyInfo){let r=this.keyUriToKeyInfo[i].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort();}}}detach(){for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e];}}destroy(){this.detach();for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e].loader;t&&t.destroy();}this.keyUriToKeyInfo={};}createKeyLoadError(e,t=x.KEY_LOAD_ERROR,i,r,n){return new mt({type:K.NETWORK_ERROR,details:t,fatal:false,frag:e,response:n,error:i,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){let{sn:i,cc:r}=e;for(let n=0;n<t.length;n++){let a=t[n];if(r<=a.cc&&(i==="initSegment"||a.sn==="initSegment"||i<a.sn)){this.emeController.selectKeySystemFormat(a).then(o=>{a.setKeyFormat(o);});break}}}}load(e){return !e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);let n=e.decryptdata;if(!n){let d=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,x.KEY_LOAD_ERROR,d))}let a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,x.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return n.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((r=o)!=null&&r.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case "status-pending":case "usable":case "usable-in-future":return o.keyLoadPromise.then(d=>(n.key=d.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case "ISO-23001-7":case "SAMPLE-AES":case "SAMPLE-AES-CENC":case "SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case "AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,x.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){let i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){let r=this.emeController.loadKey(i);if(r)return (e.keyLoadPromise=r.then(n=>(e.mediaKeySessionContext=n,i))).catch(n=>{throw e.keyLoadPromise=null,n})}return Promise.resolve(i)}loadKeyHTTP(e,t){let i=this.config,r=i.loader,n=new r(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{let l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=i.keyLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,f,m,g)=>{let{frag:E,keyInfo:v,url:A}=m;if(!E.decryptdata||v!==this.keyUriToKeyInfo[A])return o(this.createKeyLoadError(E,x.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));v.decryptdata.key=E.decryptdata.key=new Uint8Array(u.data),E.keyLoader=null,v.loader=null,a({frag:E,keyInfo:v});},onError:(u,f,m,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,x.KEY_LOAD_ERROR,new Error(`HTTP Error ${u.code} loading key ${u.text}`),m,Oe({url:l.url,data:void 0},u)));},onTimeout:(u,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,x.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m));},onAbort:(u,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,x.INTERNAL_ABORTED,new Error("key loading aborted"),m));}};n.load(l,c,h);})}resetLoader(e){let{frag:t,keyInfo:i,url:r}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],n&&n.destroy();}};function $f(){return self.SourceBuffer||self.WebKitSourceBuffer}function Gf(){if(!Ti())return false;let e=$f();return !e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function tv(){if(!Gf())return false;let s=Ti();return typeof s?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(Vs(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(Vs(e,"audio"))))}function iv(){var s;let e=$f();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}var sv=250,wn=2,rv=.1,nv=.05,Ed=class{constructor(e,t,i,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=false,this.stalled=null,this.moved=false,this.seeking=false,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=r;}destroy(){this.media=null,this.hls=this.fragmentTracker=null;}poll(e,t){let{config:i,media:r,stalled:n}=this;if(r===null)return;let{currentTime:a,seeking:o}=r,l=this.seeking&&!o,d=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=true,o||(this.nudgeRetry=0),n!==null){if(this.stallReported){let E=self.performance.now()-n;S.warn(`playback not stuck anymore @${a}, after ${Math.round(E)}ms`),this.stallReported=false;}this.stalled=null;}return}if(d||l){this.stalled=null;return}if(r.paused&&!o||r.ended||r.playbackRate===0||!ue.getBuffered(r).length){this.nudgeRetry=0;return}let c=ue.bufferInfo(r,a,0),h=c.nextStart||0;if(o){let E=c.len>wn,v=!h||t&&t.start<=a||h-a>wn&&!this.fragmentTracker.getPartialFragment(a);if(E||v)return;this.moved=false;}if(!this.moved&&this.stalled!==null){var u;if(!(c.len>0)&&!h)return;let v=Math.max(h,c.start||0)-a,A=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,L=(A==null||(u=A.details)==null?void 0:u.live)?A.details.targetduration*2:wn,y=this.fragmentTracker.getPartialFragment(a);if(v>0&&(v<=L||y)){r.paused||this._trySkipBufferHole(y);return}}let f=self.performance.now();if(n===null){this.stalled=f;return}let m=f-n;if(!o&&m>=sv&&(this._reportStall(c),!this.media))return;let g=ue.bufferInfo(r,a,i.maxBufferHole);this._tryFixBufferStall(g,m);}_tryFixBufferStall(e,t){let{config:i,fragmentTracker:r,media:n}=this;if(n===null)return;let a=n.currentTime,o=r.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-a<i.maxBufferHole)&&t>i.highBufferWatchdogPeriod*1e3&&(S.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer());}_reportStall(e){let{hls:t,media:i,stallReported:r}=this;if(!r&&i){this.stallReported=true;let n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);S.warn(n.message),t.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:x.BUFFER_STALLED_ERROR,fatal:false,error:n,buffer:e.len});}}_trySkipBufferHole(e){let{config:t,hls:i,media:r}=this;if(r===null)return 0;let n=r.currentTime,a=ue.bufferInfo(r,n,0),o=n<a.start?a.start:a.nextStart;if(o){let l=a.len<=t.maxBufferHole,d=a.len>0&&a.len<1&&r.readyState<3,c=o-n;if(c>0&&(l||d)){if(c>t.maxBufferHole){let{fragmentTracker:u}=this,f=false;if(n===0){let m=u.getAppendedFrag(0,H.MAIN);m&&o<m.end&&(f=true);}if(!f){let m=e||u.getAppendedFrag(n,H.MAIN);if(m){let g=false,E=m.end;for(;E<o;){let v=u.getPartialFragment(E);if(v)E+=v.duration;else {g=true;break}}if(g)return 0}}}let h=Math.max(o+nv,n+rv);if(S.warn(`skipping hole, adjusting currentTime from ${n} to ${h}`),this.moved=true,this.stalled=null,r.currentTime=h,e&&!e.gap){let u=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${h}`);i.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:x.BUFFER_SEEK_OVER_HOLE,fatal:false,error:u,reason:u.message,frag:e});}return h}}return 0}_tryNudgeBuffer(){let{config:e,hls:t,media:i,nudgeRetry:r}=this;if(i===null)return;let n=i.currentTime;if(this.nudgeRetry++,r<e.nudgeMaxRetry){let a=n+(r+1)*e.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);S.warn(o.message),i.currentTime=a,t.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:x.BUFFER_NUDGE_ON_STALL,error:o,fatal:false});}else {let a=new Error(`Playhead still not moving while enough data buffered @${n} after ${e.nudgeMaxRetry} nudges`);S.error(a.message),t.trigger(p.ERROR,{type:K.MEDIA_ERROR,details:x.BUFFER_STALLED_ERROR,error:a,fatal:true});}}},av=100,vd=class extends qs{constructor(e,t,i){super(e,t,i,"[stream-controller]",H.MAIN),this.audioCodecSwap=false,this.gapController=null,this.level=-1,this._forceStartLoad=false,this.altAudio=false,this.audioOnly=false,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=false,this.backtrackFragment=null,this.audioCodecSwitch=false,this.videoBuffer=null,this._registerListeners();}_registerListeners(){let{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(p.ERROR,this.onError,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this);}_unregisterListeners(){let{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(p.ERROR,this.onError,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this);}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying();}startLoad(e){if(this.levels){let{lastCurrentTime:t,hls:i}=this;if(this.stopLoad(),this.setInterval(av),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=true):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this.loadedmetadata=false;}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=C.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick();}else this._forceStartLoad=true,this.state=C.STOPPED;}stopLoad(){this._forceStartLoad=false,super.stopLoad();}doTick(){switch(this.state){case C.WAITING_LEVEL:{let{levels:t,level:i}=this,r=t?.[i],n=r?.details;if(n&&(!n.live||this.levelLastLoaded===r)){if(this.waitForCdnTuneIn(n))break;this.state=C.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=C.IDLE;break}break}case C.FRAG_LOADING_WAITING_RETRY:{var e;let t=self.performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){let{levels:r,level:n}=this,a=r?.[n];this.resetStartWhenNotLoaded(a||null),this.state=C.IDLE;}}break}this.state===C.IDLE&&this.doTickIdle(),this.onTickEnd();}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged();}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(t===null||!r&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=e.nextLoadLevel;if(!(i!=null&&i[n]))return;let a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let g={};this.altAudio&&(g.type="video"),this.hls.trigger(p.BUFFER_EOS,g),this.state=C.ENDED;return}e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;let d=a.details;if(!d||this.state===C.WAITING_LEVEL||d.live&&this.levelLastLoaded!==a){this.level=n,this.state=C.WAITING_LEVEL;return}let c=o.len,h=this.getMaxBufferLength(a.maxBitrate);if(c>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);let u=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(u,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&f.sn!=="initSegment"&&this.fragmentTracker.getState(f)!==Pe.OK){var m;let E=((m=this.backtrackFragment)!=null?m:f).sn-d.startSN,v=d.fragments[E-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,u)){if(!f.gap){let E=this.audioOnly&&!this.altAudio?ne.AUDIO:ne.VIDEO,v=(E===ne.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,E,H.MAIN);}f=this.getNextFragmentLoopLoading(f,d,o,H.MAIN,h);}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,u));}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);this.fragCurrent=e,r===Pe.NOT_LOADED||r===Pe.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=true,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e);}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,H.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY);}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let n=this.getLevelDetails();if(n!=null&&n.live){let o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){let o=this.hls.nextLoadLevel,l=e[o],d=this.fragLastKbps;d&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*d)+1:i=0;}else i=0;let a=this.getBufferedFrag(t.currentTime+i);if(a){let o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();let l=o.maxStartPTS?o.maxStartPTS:o.start,d=o.duration,c=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(c,Number.POSITIVE_INFINITY);}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case C.KEY_LOADING:case C.FRAG_LOADING:case C.FRAG_LOADING_WAITING_RETRY:case C.PARSING:case C.PARSED:this.state=C.IDLE;break}this.nextLoadPosition=this.getLoadPosition();}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null);}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Ed(this.config,i,this.fragmentTracker,this.hls);}onMediaDetaching(){let{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching();}onMediaPlaying(){this.tick();}onMediaSeeked(){let e=this.media,t=e?e.currentTime:null;F(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);let i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick();}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(p.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=false,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=false;}onManifestParsed(e,t){let i=false,r=false;t.levels.forEach(n=>{let a=n.audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1);}),this.audioCodecSwitch=i&&r&&!iv(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=false;}onLevelLoading(e,t){let{levels:i}=this;if(!i||this.state!==C.IDLE)return;let r=i[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(r.details))&&(this.state=C.WAITING_LEVEL);}onLevelLoaded(e,t){var i;let{levels:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!r){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);let l=r[n],d=this.fragCurrent;d&&(this.state===C.FRAG_LOADING||this.state===C.FRAG_LOADING_WAITING_RETRY)&&d.level!==t.level&&d.loader&&this.abortCurrentFrag();let c=0;if(a.live||(i=l.details)!=null&&i.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details);}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(p.LEVEL_UPDATED,{details:a,level:n}),this.state===C.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=C.IDLE;}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,c),this.tick();}_handleFragmentLoadProgress(e){var t;let{frag:i,part:r,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let o=a[i.level],l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}let d=o.videoCodec,c=l.PTSKnown||!l.live,h=(t=i.initSegment)==null?void 0:t.data,u=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Zn(this.hls,H.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=r?r.index:-1,g=m!==-1,E=new Ws(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,g),v=this.initPTS[i.cc];f.push(n,h,u,d,i,r,l.totalduration,c,E,v);}onAudioTrackSwitching(e,t){let i=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let 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();let n=this.hls;i&&(n.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),n.trigger(p.AUDIO_TRACK_SWITCHED,t);}}onAudioTrackSwitched(e,t){let i=t.id,r=!!this.hls.audioTracks[i].url;if(r){let n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n);}this.altAudio=r,this.tick();}onBufferCreated(e,t){let i=t.tracks,r,n,a=false;for(let o in i){let l=i[o];if(l.id==="main"){if(n=o,r=l,o==="video"){let d=i[o];d&&(this.videoBuffer=d.buffer);}}else a=true;}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){let{frag:i,part:r}=t;if(i&&i.type!==H.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===C.PARSED&&(this.state=C.IDLE);return}let n=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,r);}onError(e,t){var i;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case x.FRAG_GAP:case x.FRAG_PARSING_ERROR:case x.FRAG_DECRYPT_ERROR:case x.FRAG_LOAD_ERROR:case x.FRAG_LOAD_TIMEOUT:case x.KEY_LOAD_ERROR:case x.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.MAIN,t);break;case x.LEVEL_LOAD_ERROR:case x.LEVEL_LOAD_TIMEOUT:case x.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===Z.LEVEL&&(this.state=C.IDLE);break;case x.BUFFER_APPEND_ERROR:case x.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===x.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case x.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){let{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!ue.getBuffered(e).length){let i=this.state!==C.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i);}this.lastCurrentTime=e.currentTime;}}onFragLoadEmergencyAborted(){this.state=C.IDLE,this.loadedmetadata||(this.startFragRequested=false,this.nextLoadPosition=this.startPosition),this.tickImmediate();}onBufferFlushed(e,{type:t}){if(t!==ne.AUDIO||this.audioOnly&&!this.altAudio){let i=(t===ne.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,H.MAIN),this.tick();}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels;}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap;}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}let r=ue.getBuffered(e),a=(r.length?r.start(0):0)-i;a>0&&(a<this.config.maxBufferHole||a<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${a} to match buffer start`),i+=a,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${t}`),e.currentTime=i;}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=true,this._doFragLoad(e,t).then(i=>{let{hls:r}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=C.IDLE,this.startFragRequested=false,this.bitrateTest=false;let n=e.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),r.trigger(p.FRAG_LOADED,i),e.bitrateTest=false;});}_handleTransmuxComplete(e){var t;let i="main",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:d,level:c}=o,{video:h,text:u,id3:f,initSegment:m}=n,{details:g}=c,E=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=C.PARSING,m){if(m!=null&&m.tracks){let b=l.initSegment||l;this._bufferInitSegment(c,m.tracks,b,a),r.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:b,id:i,tracks:m.tracks});}let v=m.initPTS,A=m.timescale;F(v)&&(this.initPTS[l.cc]={baseTime:v,timescale:A},r.trigger(p.INIT_PTS_FOUND,{frag:l,id:i,initPTS:v,timescale:A}));}if(h&&g&&l.sn!=="initSegment"){let v=g.fragments[l.sn-1-g.startSN],A=l.sn===g.startSN,b=!v||l.cc>v.cc;if(n.independent!==false){let{startPTS:L,endPTS:y,startDTS:D,endDTS:I}=h;if(d)d.elementaryStreams[h.type]={startPTS:L,endPTS:y,startDTS:D,endDTS:I};else if(h.firstKeyFrame&&h.independent&&a.id===1&&!b&&(this.couldBacktrack=true),h.dropped&&h.independent){let k=this.getMainFwdBufferInfo(),P=(k?k.end:this.getLoadPosition())+this.config.maxBufferHole,R=h.firstKeyFramePTS?h.firstKeyFramePTS:L;if(!A&&P<R-this.config.maxBufferHole&&!b){this.backtrack(l);return}else b&&(l.gap=true);l.setElementaryStreamInfo(h.type,l.start,y,l.start,I,true);}else A&&L>wn&&(l.gap=true);l.setElementaryStreamInfo(h.type,L,y,D,I),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(h,l,d,a,A||b);}else if(A||b)l.gap=true;else {this.backtrack(l);return}}if(E){let{startPTS:v,endPTS:A,startDTS:b,endDTS:L}=E;d&&(d.elementaryStreams[ne.AUDIO]={startPTS:v,endPTS:A,startDTS:b,endDTS:L}),l.setElementaryStreamInfo(ne.AUDIO,v,A,b,L),this.bufferFragmentData(E,l,d,a);}if(g&&f!=null&&(t=f.samples)!=null&&t.length){let v={id:i,frag:l,details:g,samples:f.samples};r.trigger(p.FRAG_PARSING_METADATA,v);}if(g&&u){let v={id:i,frag:l,details:g,samples:u.samples};r.trigger(p.FRAG_PARSING_USERDATA,v);}}_bufferInitSegment(e,t,i,r){if(this.state!==C.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;let{audio:n,video:a,audiovideo:o}=t;if(n){let l=e.audioCodec,d=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5");let c=n.metadata;c&&"channelCount"in c&&(c.channelCount||1)!==1&&d.indexOf("firefox")===-1&&(l="mp4a.40.5");}l&&l.indexOf("mp4a.40.5")!==-1&&d.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),n.levelCodec=l,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${n.codec}]`);}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(p.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{let c=t[l].initSegment;c!=null&&c.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:l,data:c,frag:i,part:null,chunkMeta:r,parent:i.type});}),this.tickImmediate();}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,H.MAIN)}backtrack(e){this.couldBacktrack=true,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=C.IDLE;}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===false){let i=e.currentTime;if(ue.isBuffered(e,i)?t=this.getAppendedFrag(i):ue.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;let r=this.fragPlaying,n=t.level;(!r||t.sn!==r.sn||r.level!==n)&&(this.fragPlaying=t,this.hls.trigger(p.FRAG_CHANGED,{frag:t}),(!r||r.level!==n)&&this.hls.trigger(p.LEVEL_SWITCHED,{level:n}));}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){let e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){let e=this.media;if(e){let t=e.currentTime,i=this.currentFrag;if(i&&F(t)&&F(i.programDateTime)){let r=i.programDateTime+(t-i.start)*1e3;return new Date(r)}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},rs=class s{static get version(){return "1.5.15"}static isMSESupported(){return Gf()}static isSupported(){return tv()}static getMediaSource(){return Ti()}static get Events(){return p}static get ErrorTypes(){return K}static get ErrorDetails(){return x}static get DefaultConfig(){return s.defaultConfig?s.defaultConfig:Bf}static set DefaultConfig(e){s.defaultConfig=e;}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=false,this._emitter=new Ld,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,$g(e.debug||false,"Hls instance");let t=this.config=JE(s.DefaultConfig,e);this.userConfig=e,t.progressive&&ev(t);let{abrController:i,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=t,l=new a(this),d=this.abrController=new i(this),c=this.bufferController=new r(this),h=this.capLevelController=new n(this),u=new o(this),f=new gl(this),m=new vl(this),g=t.contentSteeringController,E=g?new g(this):null,v=this.levelController=new gd(this,E),A=new Ll(this),b=new pd(this.config),L=this.streamController=new vd(this,A,b);h.setStreamController(L),u.setStreamController(L);let y=[f,v,L];E&&y.splice(1,0,E),this.networkControllers=y;let D=[d,c,h,u,m,A];this.audioTrackController=this.createController(t.audioTrackController,y);let I=t.audioStreamController;I&&y.push(new I(this,A,b)),this.subtitleTrackController=this.createController(t.subtitleTrackController,y);let k=t.subtitleStreamController;k&&y.push(new k(this,A,b)),this.createController(t.timelineController,D),b.emeController=this.emeController=this.createController(t.emeController,D),this.cmcdController=this.createController(t.cmcdController,D),this.latencyController=this.createController(Tl,D),this.coreComponents=D,y.push(l);let P=l.onErrorOut;typeof P=="function"&&this.on(p.ERROR,P,l);}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i);}once(e,t,i=this){this._emitter.once(e,t,i);}removeAllListeners(e){this._emitter.removeAllListeners(e);}off(e,t,i=this,r){this._emitter.off(e,t,i,r);}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(S.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=true;let r=e===p.ERROR;this.trigger(p.ERROR,{type:K.OTHER_ERROR,details:x.INTERNAL_EXCEPTION,fatal:r,event:e,error:i}),this.triggeringException=false;}}return false}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){S.log("destroy"),this.trigger(p.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null;}attachMedia(e){S.log("attachMedia"),this._media=e,this.trigger(p.MEDIA_ATTACHING,{media:e});}detachMedia(){S.log("detachMedia"),this.trigger(p.MEDIA_DETACHING,void 0),this._media=null;}loadSource(e){this.stopLoad();let t=this.media,i=this.url,r=this.url=Td.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:true});this._autoLevelCapping=-1,this._maxHdcpLevel=null,S.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(p.MANIFEST_LOADING,{url:e});}startLoad(e=-1){S.log(`startLoad(${e})`),this.started=true,this.networkControllers.forEach(t=>{t.startLoad(e);});}stopLoad(){S.log("stopLoad"),this.started=false,this.networkControllers.forEach(e=>{e.stopLoad();});}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1);});}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.stopLoad();});}swapAudioCodec(){S.log("swapAudioCodec"),this.streamController.swapAudioCodec();}recoverMediaError(){S.log("recoverMediaError");let e=this._media;this.detachMedia(),e&&this.attachMedia(e);}removeLevel(e){this.levelController.removeLevel(e);}get levels(){let e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){S.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch();}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){S.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch();}get loadLevel(){return this.levelController.level}set loadLevel(e){S.log(`set loadLevel:${e}`),this.levelController.manualLevel=e;}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e;}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){S.log(`set firstLevel:${e}`),this.levelController.firstLevel=e;}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){S.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e;}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let 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(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e);}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(S.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated());}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Np(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(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this,r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,i)for(let n=r;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e;}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var t;return (t=this.audioTrackController)==null?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return (t=this.subtitleTrackController)==null||t.setSubtitleOption(e),null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e);}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e);}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:false}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e);}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e;}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}};rs.defaultConfig=void 0;var Vf=Symbol.for(""),ov=s=>{if(s?.r===Vf)return s?._$litStatic$},kd=s=>({_$litStatic$:s,r:Vf});var Hf=new Map,Kf=s=>(e,...t)=>{let i=t.length,r,n,a=[],o=[],l,d=0,c=false;for(;d<i;){for(l=e[d];d<i&&(n=t[d],(r=ov(n))!==void 0);)l+=r+e[++d],c=true;d!==i&&o.push(n),a.push(l),d++;}if(d===i&&a.push(e[i]),c){let h=a.join("$$lit$$");(e=Hf.get(h))===void 0&&(a.raw=a,Hf.set(h,e=a)),t=o;}return s(e,...t)},Wf=Kf(chunk5NSCV6C2_cjs.c);var W,Yf,qf,oa,zf,Xf,jf,Qf,wd,Md,Pd,la,Zf,Od,ns,Nd,Jf,em,fe=class extends chunkVW7IKXVI_cjs.a{constructor(){super(...arguments);chunkIPA5Q26W_cjs.e(this,W);this._controls=["play","time","seek","volume","fullscreen","subtitles"];this.popped=false;this._startedPlaying=false;this._intersectionObserver=new chunk5KQJTT3P_cjs.a(this,{callback:chunkIPA5Q26W_cjs.f(this,W,jf).bind(this)});this.embedController=new chunkY7NYUH3P_cjs.b(this);this._intersected=false;this._queue=[];}get embed(){return this._embedId}set embed(t){this._embedId!=t&&(this._embedId=t,this.embedController.embed=this.embed,this.updateStylePoster(),this.loadTheme());}get token(){return this._token}set token(t){this._token!=t&&(this._token=t,this.requestUpdate("token"),this.embedController.token=this._token);}set loop(t){this._loop=(t===""||t=="true"||t==true)??false;}get loop(){return this._loop}get controls(){return this._controls}set controls(t){typeof t=="string"?this._controls=t.split(" "):this._controls=t;}get cache(){return this._cache}set cache(t){this._cache!=t&&(typeof t=="string"?this._cache=t==="true"||t==="":this._cache=false,this.requestUpdate("caching"),this.embedController.caching=this._cache);}get quality(){return this._quality}set quality(t){this._quality!=t&&(this._quality=t);}get theme(){return this._theme||"default"}set theme(t){this._theme!=t&&(this._theme=t,this.requestUpdate("theme"),this.loadTheme());}get poster(){return !this.embed||!this._embedObj?"":this._poster&&this._poster=="custom"?this.embedController.embedFile(chunkIPA5Q26W_cjs.f(this,W,oa).call(this,"custom_thumbnail")):this._poster&&(!Number.isNaN(parseFloat(this._poster))||!Number.isNaN(parseInt(this._poster)))?this._embedObj.poster&&this._embedObj.poster.renditions&&this._embedObj.poster.renditions.find(t=>t.type=="custom_thumbnail")?this.embedController.embedFile(chunkIPA5Q26W_cjs.f(this,W,oa).call(this,"custom_thumbnail")):`https://image.mave.io/${this.embedController.spaceId}${this.embedController.embedId}.jpg?time=${this._poster}`:this._poster?this._poster:this.embedController.embedFile(chunkIPA5Q26W_cjs.f(this,W,oa).call(this,"thumbnail"))}set poster(t){t&&(this._poster=t,this.requestUpdate("poster"));}pop(){this.popped=true;}close(){this.popped=false;}set muted(t){let i=(t===""||t=="true"||t==true)??false;this._videoElement?this._videoElement.muted=i:this._queue.push(()=>this._videoElement.muted=i);}get muted(){return this._videoElement?.muted||false}set currentTime(t){this._videoElement?this._videoElement.currentTime=t:this._queue.push(()=>this._videoElement.currentTime=t);}get currentTime(){return this._videoElement?this._videoElement?.currentTime:0}get duration(){return new Promise((t,i)=>{if(this._videoElement&&!isNaN(this._videoElement.duration))return t(this._videoElement.duration);let r=()=>{this._videoElement?.addEventListener("loadedmetadata",()=>{this._videoElement&&t(this._videoElement.duration);}),this._videoElement?.addEventListener("error",()=>{i(new Error("Failed to load video metadata."));});};this._videoElement?r():this.addEventListener("mave:video_element_ready",()=>{r();});})}get paused(){return this._videoElement?this._videoElement.paused:true}play(){this._videoElement&&!this.embedController.loading?chunkIPA5Q26W_cjs.f(this,W,la).call(this):this._queue.push(()=>chunkIPA5Q26W_cjs.f(this,W,la).call(this));}restart(){this._videoElement&&(this.pause(),this._videoElement.currentTime=0,this.play());}pause(){this._videoElement?this._videoElement.pause():this._queue.push(()=>this._videoElement?.pause());}updateStylePoster(){this.style.setProperty("background",`center / contain no-repeat url(${this.poster})`);}connectedCallback(){super.connectedCallback(),this.loadTheme(),chunkIPA5Q26W_cjs.f(this,W,qf).call(this);}disconnectedCallback(){super.disconnectedCallback(),this._metricsInstance?.demonitor();}loadTheme(){this.embed&&this._themeLoaded!=this.theme&&(chunkKTP5LV2E_cjs.a.get(this.theme,`${this.embedController.cdnRoot}/themes/player`),this._themeLoaded=this.theme);}updateEmbed(t){this._embedObj=t,this.updateStylePoster(),this.poster=this._embedObj.settings.poster,this.attributes.getNamedItem("color")||(this.color=this._embedObj.settings.color),this.attributes.getNamedItem("opacity")||(this.opacity=this._embedObj.settings.opacity?this._embedObj.settings.opacity:void 0),this.attributes.getNamedItem("aspect-ratio")||(this.aspect_ratio=this._embedObj.settings.aspect_ratio),this.attributes.getNamedItem("width")||(this.width=this._embedObj.settings.width),this.attributes.getNamedItem("height")||(this.height=this._embedObj.settings.height),this.attributes.getNamedItem("autoplay")||(this.autoplay=this._embedObj.settings.autoplay=="on_show"?"lazy":this._embedObj.settings.autoplay),this.attributes.getNamedItem("controls")||(this.controls=this._embedObj.settings.controls),this.attributes.getNamedItem("loop")||(this.loop=this._embedObj.settings.loop);}get styles(){let t={};return (this.color||this._embedObj?.settings.color)&&(t["--primary-color"]=`${this.color||this._embedObj?.settings.color}${this.opacity||this._embedObj?.settings.opacity?this._embedObj?.settings.opacity:""}`),this.aspect_ratio=="auto"||this._embedObj?.settings.aspect_ratio=="auto"&&!this.aspect_ratio?t["--aspect-ratio"]=this._embedObj?.video.aspect_ratio:t["--aspect-ratio"]=this.aspect_ratio||this._embedObj?.settings.aspect_ratio,(this.width||this._embedObj?.settings.width)&&(t["--width"]=this.width||this._embedObj?.settings.width),(this.height||this._embedObj?.settings.height)&&(t["--height"]=this.height||this._embedObj?.settings.height),!this.controls.includes("full")&&!this.controls.includes("big")&&!this.controls.includes("none")&&(t["--play-display"]=this.controls.includes("play")?"flex":"none",t["--time-display"]=this.controls.includes("time")?"flex":"none",t["--seek-bar-visibility"]=this.controls.includes("seek")?"visible":"hidden",t["--volume-display"]=this.controls.includes("volume")?"flex":"none",t["--fullscreen-display"]=this.controls.includes("fullscreen")?"flex":"none",t["--captions-display"]=this.controls.includes("subtitles")?"flex":"none"),t["--playbackrate-display"]=this.controls.includes("rate")?"flex":"none",((this.subtitles=="none"||this.subtitles=="off"||this._embedObj?.subtitles.length==0)&&!this.active_subtitle||this._embedObj?.created_at<1740674988&&!this.subtitles&&!this.active_subtitle)&&(t["--captions-display"]="none"),this.controls.includes("full")||this._embedObj?.settings.controls=="full"&&!this.controls.includes("big")&&!this.controls.includes("none")?t["--media-control-bar-display"]="flex":t["--media-control-bar-display"]="none",this.controls.includes("big")||this._embedObj?.settings.controls=="big"&&!this.controls.includes("full")&&!this.controls.includes("none")?t["--big-button-display"]="flex":t["--big-button-display"]="none",this._embedObj?.video.audio===false?t["--media-volume-display"]="none":t["--media-volume-display"]="inline-flex",chunkQ22T22LT_cjs.a(t)}render(){if(!this.embed)return;let t=this.querySelector('[slot="start-screen"]');return chunk5NSCV6C2_cjs.c`
1130
1130
  <slot
1131
1131
  name="video"
1132
1132
  style=${chunkQ22T22LT_cjs.a({display:t&&!this._startedPlaying?"none":"block"})}