import{r as y,e as El,d as vl,an as Se,T as Nt,aF as xl,aG as yl,ao as $i,aD as gt,aE as wa,aH as vi,aI as Da,aJ as Tl,z as ne,j as O,F as J,c as ka,K as Zs,D as _a,a1 as Ie,W as oi,G as Sl,Q as bl,az as Gi,aK as Ll,aA as Al,aL as Cl,x as Vi,U as Rl,ap as Il,aM as Pa,aN as os,aO as wl,o as Oa,g as kt,aP as Dl,aQ as kl}from"./vendor-CT-JknSv.chunk.js";import{cQ as _l,R as ls,cR as Pl,u as cs,cK as mi,cS as qn,a6 as li,cT as ys,b as Ol,bI as us,aA as Fl,cL as Fa,cU as Ml,Z as Nl,_ as Bl,$ as Ul,j as V,r as be,v as ti,a0 as Re,aP as Ge,cs as nt,cV as Ma,cW as $l,B as Gl,b8 as ci,bk as Vl,l as Hi,bm as zn,a$ as Hl,aD as Xn,az as Ne,w as ii,i as He,f as hs,bZ as Kl,cX as Na,cY as Wl,aU as ds,aT as Ba,cZ as Yl,ac as Ua,c7 as ql,c_ as zl,Q as Xl,a5 as jn,c$ as jl,J as $a,d0 as Zl,bb as yn,H as Ql,O as Jl,aF as ec,aW as tc,bA as ic,cP as sc,y as nc,d1 as rc}from"./index-DDZqnj79.js";import{H as ac}from"./Header-CcAYibhJ.chunk.js";import{d as oc,e as pt,f as Ga,a as lc,b as cc,s as uc,c as Zn,h as Qn,i as hc,T as dc}from"./preferences-BqZcwQYn.chunk.js";function fc({enabled:n=!0}){const[e,t]=y.useState(window==null?void 0:window.innerWidth),[i,s]=y.useState(window==null?void 0:window.innerHeight);return y.useEffect(()=>{if(!n)return;function r(){t(window.innerWidth),s(window.innerHeight)}return r(),window.addEventListener("resize",r),window.addEventListener("orientationchange",r),()=>{window.removeEventListener("resize",r,!1),window.removeEventListener("orientationchange",r,!1)}},[n]),{viewportWidth:n?e:void 0,viewportHeight:n?i:void 0}}const gc={manifest:({jwt:n,type:e,id:t})=>["streaming",n,"manifest",{type:e,id:t}]},mc={manifest:({jwt:n,type:e,id:t})=>n&&t&&e?(e==="video_episode"?`video_episodes/${t}/manifest.m3u8?`:`lessons/${t}/manifest.m3u8?`)+new URLSearchParams({token:n,app_version:Pl(),platform:"web"}).toString():""},Jn=3*60*60*1e3,er=30*1e3;function pc({id:n,type:e,enabled:t}){const{jwt:i}=_l(),s=mc.manifest({id:n,type:e,jwt:i});return El(gc.manifest({id:n,type:e,jwt:i}),async({signal:r})=>{const a=await vl.get(s,{baseURL:ls.NEBULA_API_CONTENT_BASE_URL,signal:r}),o=a.headers["x-manifest-expires-at"],l=o&&!isNaN(parseInt(o))?parseInt(o):void 0;return{url:a.request.responseURL,expiresAt:l}},{enabled:!!s&&t,refetchInterval(r){if(!(r!=null&&r.expiresAt))return Jn;const a=r.expiresAt*1e3;return Math.max(a-er-Date.now(),0)},refetchOnWindowFocus(r){const{data:a,dataUpdatedAt:o,errorUpdatedAt:l}=r.state,c=a!=null&&a.expiresAt?a.expiresAt*1e3:(o||l||0)+Jn;return Date.now()>c-er?"always":!1}})}function Ec({store:n,reportProgress:e}){const t=cs(),i=mi(),s=Se(n,o=>o.chromecastConnected),a=t&&!s&&!i?e:void 0;y.useEffect(()=>{if(!a)return;const o=Nt(d=>{a(d)},qn),l=Nt(()=>{o.flush()},qn/2),c=n.subscribe(d=>Math.floor(d.currentTime),d=>{o(d)}),u=n.subscribe(d=>d.isPlaying,()=>{l()}),h=n.subscribe(d=>d.hasEnded,d=>{d&&o.flush()});return()=>{c(),u(),h(),l.cancel(),o.flush()}},[n,a])}const vc=.1;function Ki(n,e){return Math.abs(n-e)<vc}const Qs=[.5,.75,1,1.25,1.5,1.75,2],jg=["k"," "],xc="/static/nebula-text-only-white@2x-D3AMcu2n.png",yc="/static/nebula-text-only@2x-7Q__aWCe.png";function Zg({mediaId:n,startPosition:e,autoplayEnabled:t}){const i={mediaId:n,mediaTitle:"",chromecastQueue:null,mediaSessionMetadata:null,src:"",duration:0,currentTime:e,wasEverPlayed:!1,currentLanguage:"",isPlaying:!1,hasEnded:!1,autoplayEnabled:t,isEndScreenShowing:!1,airPlayConnected:!1,chromecastConnected:!1,isFullScreen:!!(document!=null&&document.fullscreenElement||document!=null&&document.webkitFullscreenElement),muxData:null,deviceSupportsVideoCodecs:!0,mediaType:void 0},s={isMuted:!1,isBuffering:!1,isSeeking:!1,isScrubbing:!1,playbackSpeed:1,volume:1,subtitles:[],showNativeCues:!1,aspectRatio:1/li,isInitialized:!1,qualityLevels:[],quality:"auto",currentAutoLevel:null,chromecastDeviceName:null,buffered:[],chromecastAvailable:!1,airPlayAvailable:!1,fullScreenAvailable:!1,pictureInPictureAvailable:!1,autoplayAvailable:!1,volumeChangeAvailable:!0,muteChangeAvailable:!0};return xl()(yl(r=>({...i,...s,set(a){r(a)},resetTech(){r(s)}})))}function Tc({playerHandlers:n,isPlaying:e,duration:t}){const i=!!(n.previousFrame&&n.nextFrame);ys({codes:i?["Comma","Period"]:[],callback:r=>{var a,o;e||(r==="Comma"&&((a=n.previousFrame)==null||a.call(n)),r==="Period"&&((o=n.nextFrame)==null||o.call(n)))}});const s=!!(n.lowerPlaybackSpeed&&n.raisePlaybackSpeed);ys({codes:s?["Comma","Period"]:[],shift:!0,callback:r=>{var a,o;r==="Comma"&&((a=n.lowerPlaybackSpeed)==null||a.call(n)),r==="Period"&&((o=n.raisePlaybackSpeed)==null||o.call(n))}}),ys({codes:["Digit0","Digit1","Digit2","Digit3","Digit4","Digit5","Digit6","Digit7","Digit8","Digit9"],callback:r=>{if(t===0)return;const l=Number(r.replace("Digit",""))*10/100*t;n.setCurrentTime(l)}})}function Qg(n,e){const[t]=Ol("t"),i=Sc(t);return i!==void 0?{startTime:i}:n==null||e===void 0||e===null?{startTime:void 0}:n>e||Ki(n,e)?{startTime:0}:{startTime:n}}function Sc(n){if(n)try{if(n.match(/^\d+$/))return parseInt(n);const e=n.match(/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/);if(e)return(e[1]?parseInt(e[1])*3600:0)+(e[2]?parseInt(e[2])*60:0)+(e[3]?parseInt(e[3]):0)}catch(e){us.warn(`Could not parse provided timestamp "${n}", error ${e}`);return}}const tr=ls.MUX_ENV_KEY,bc=({mediaElement:n,initTime:e,data:t})=>{!n||!tr||Ml()||$i.monitor(n,{debug:!1,data:{env_key:tr,player_init_time:e!=null?e:$i.utils.now(),player_name:"Nebula Website",player_version:ls.VERSION,...t}})};function Lc(n){return Nl(n)?"Original":Bl(n)?"Plus":Ul(n)?"First":"None"}function Ac(n,e){!(n!=null&&n.mux)||!e||$i.emit(n,"videochange",e)}function Cc(n){var o;const{user:e,isInitialLoading:t}=Fl(),[i]=Fa("freeVideoFriendlySlug"),s=(o=e==null?void 0:e.pk)==null?void 0:o.toString(),r=t?!1:e?!!e.collect_video_analytics:!0;return y.useMemo(()=>{if(!r)return null;const l={viewer_user_id:s,video_id:n.id,video_title:n.title,video_duration:n.duration*1e3};if(n.type==="lesson"&&(l.class_id=n.class_id),n.type==="video_episode"){const c=i===n.slug,u=Lc(n);l.sub_property_id=c?"Free Sample":void 0,l.channel_id=n.channel_id,l.video_producer=n.channel_title,l.video_series=n.channel_title,l.custom_1=u}return n.type==="podcast_episode"&&(l.channel_id=n.channel_id,l.video_producer=n.channel_title,l.video_series=n.channel_title,l.custom_1="None"),l.video_content_type=n.type,l},[n,i,s,r])}function Rc(n,e){return n.classList?!!e&&n.classList.contains(e):(" "+(n.className.baseVal||n.className)+" ").indexOf(" "+e+" ")!==-1}function Ic(n,e){n.classList?n.classList.add(e):Rc(n,e)||(typeof n.className=="string"?n.className=n.className+" "+e:n.setAttribute("class",(n.className&&n.className.baseVal||"")+" "+e))}function ir(n,e){return n.replace(new RegExp("(^|\\s)"+e+"(?:\\s|$)","g"),"$1").replace(/\s+/g," ").replace(/^\s*|\s*$/g,"")}function wc(n,e){n.classList?n.classList.remove(e):typeof n.className=="string"?n.className=ir(n.className,e):n.setAttribute("class",ir(n.className&&n.className.baseVal||"",e))}const sr={disabled:!1},Va=gt.createContext(null);var Ha=function(e){return e.scrollTop},jt="unmounted",ut="exited",ht="entering",Dt="entered",Js="exiting",tt=function(n){wa(e,n);function e(i,s){var r;r=n.call(this,i,s)||this;var a=s,o=a&&!a.isMounting?i.enter:i.appear,l;return r.appearStatus=null,i.in?o?(l=ut,r.appearStatus=ht):l=Dt:i.unmountOnExit||i.mountOnEnter?l=jt:l=ut,r.state={status:l},r.nextCallback=null,r}e.getDerivedStateFromProps=function(s,r){var a=s.in;return a&&r.status===jt?{status:ut}:null};var t=e.prototype;return t.componentDidMount=function(){this.updateStatus(!0,this.appearStatus)},t.componentDidUpdate=function(s){var r=null;if(s!==this.props){var a=this.state.status;this.props.in?a!==ht&&a!==Dt&&(r=ht):(a===ht||a===Dt)&&(r=Js)}this.updateStatus(!1,r)},t.componentWillUnmount=function(){this.cancelNextCallback()},t.getTimeouts=function(){var s=this.props.timeout,r,a,o;return r=a=o=s,s!=null&&typeof s!="number"&&(r=s.exit,a=s.enter,o=s.appear!==void 0?s.appear:a),{exit:r,enter:a,appear:o}},t.updateStatus=function(s,r){if(s===void 0&&(s=!1),r!==null)if(this.cancelNextCallback(),r===ht){if(this.props.unmountOnExit||this.props.mountOnEnter){var a=this.props.nodeRef?this.props.nodeRef.current:vi.findDOMNode(this);a&&Ha(a)}this.performEnter(s)}else this.performExit();else this.props.unmountOnExit&&this.state.status===ut&&this.setState({status:jt})},t.performEnter=function(s){var r=this,a=this.props.enter,o=this.context?this.context.isMounting:s,l=this.props.nodeRef?[o]:[vi.findDOMNode(this),o],c=l[0],u=l[1],h=this.getTimeouts(),d=o?h.appear:h.enter;if(!s&&!a||sr.disabled){this.safeSetState({status:Dt},function(){r.props.onEntered(c)});return}this.props.onEnter(c,u),this.safeSetState({status:ht},function(){r.props.onEntering(c,u),r.onTransitionEnd(d,function(){r.safeSetState({status:Dt},function(){r.props.onEntered(c,u)})})})},t.performExit=function(){var s=this,r=this.props.exit,a=this.getTimeouts(),o=this.props.nodeRef?void 0:vi.findDOMNode(this);if(!r||sr.disabled){this.safeSetState({status:ut},function(){s.props.onExited(o)});return}this.props.onExit(o),this.safeSetState({status:Js},function(){s.props.onExiting(o),s.onTransitionEnd(a.exit,function(){s.safeSetState({status:ut},function(){s.props.onExited(o)})})})},t.cancelNextCallback=function(){this.nextCallback!==null&&(this.nextCallback.cancel(),this.nextCallback=null)},t.safeSetState=function(s,r){r=this.setNextCallback(r),this.setState(s,r)},t.setNextCallback=function(s){var r=this,a=!0;return this.nextCallback=function(o){a&&(a=!1,r.nextCallback=null,s(o))},this.nextCallback.cancel=function(){a=!1},this.nextCallback},t.onTransitionEnd=function(s,r){this.setNextCallback(r);var a=this.props.nodeRef?this.props.nodeRef.current:vi.findDOMNode(this),o=s==null&&!this.props.addEndListener;if(!a||o){setTimeout(this.nextCallback,0);return}if(this.props.addEndListener){var l=this.props.nodeRef?[this.nextCallback]:[a,this.nextCallback],c=l[0],u=l[1];this.props.addEndListener(c,u)}s!=null&&setTimeout(this.nextCallback,s)},t.render=function(){var s=this.state.status;if(s===jt)return null;var r=this.props,a=r.children;r.in,r.mountOnEnter,r.unmountOnExit,r.appear,r.enter,r.exit,r.timeout,r.addEndListener,r.onEnter,r.onEntering,r.onEntered,r.onExit,r.onExiting,r.onExited,r.nodeRef;var o=Da(r,["children","in","mountOnEnter","unmountOnExit","appear","enter","exit","timeout","addEndListener","onEnter","onEntering","onEntered","onExit","onExiting","onExited","nodeRef"]);return gt.createElement(Va.Provider,{value:null},typeof a=="function"?a(s,o):gt.cloneElement(gt.Children.only(a),o))},e}(gt.Component);tt.contextType=Va;tt.propTypes={};function bt(){}tt.defaultProps={in:!1,mountOnEnter:!1,unmountOnExit:!1,appear:!1,enter:!0,exit:!0,onEnter:bt,onEntering:bt,onEntered:bt,onExit:bt,onExiting:bt,onExited:bt};tt.UNMOUNTED=jt;tt.EXITED=ut;tt.ENTERING=ht;tt.ENTERED=Dt;tt.EXITING=Js;var Dc=function(e,t){return e&&t&&t.split(" ").forEach(function(i){return Ic(e,i)})},Ts=function(e,t){return e&&t&&t.split(" ").forEach(function(i){return wc(e,i)})},Tn=function(n){wa(e,n);function e(){for(var i,s=arguments.length,r=new Array(s),a=0;a<s;a++)r[a]=arguments[a];return i=n.call.apply(n,[this].concat(r))||this,i.appliedClasses={appear:{},enter:{},exit:{}},i.onEnter=function(o,l){var c=i.resolveArguments(o,l),u=c[0],h=c[1];i.removeClasses(u,"exit"),i.addClass(u,h?"appear":"enter","base"),i.props.onEnter&&i.props.onEnter(o,l)},i.onEntering=function(o,l){var c=i.resolveArguments(o,l),u=c[0],h=c[1],d=h?"appear":"enter";i.addClass(u,d,"active"),i.props.onEntering&&i.props.onEntering(o,l)},i.onEntered=function(o,l){var c=i.resolveArguments(o,l),u=c[0],h=c[1],d=h?"appear":"enter";i.removeClasses(u,d),i.addClass(u,d,"done"),i.props.onEntered&&i.props.onEntered(o,l)},i.onExit=function(o){var l=i.resolveArguments(o),c=l[0];i.removeClasses(c,"appear"),i.removeClasses(c,"enter"),i.addClass(c,"exit","base"),i.props.onExit&&i.props.onExit(o)},i.onExiting=function(o){var l=i.resolveArguments(o),c=l[0];i.addClass(c,"exit","active"),i.props.onExiting&&i.props.onExiting(o)},i.onExited=function(o){var l=i.resolveArguments(o),c=l[0];i.removeClasses(c,"exit"),i.addClass(c,"exit","done"),i.props.onExited&&i.props.onExited(o)},i.resolveArguments=function(o,l){return i.props.nodeRef?[i.props.nodeRef.current,o]:[o,l]},i.getClassNames=function(o){var l=i.props.classNames,c=typeof l=="string",u=c&&l?l+"-":"",h=c?""+u+o:l[o],d=c?h+"-active":l[o+"Active"],f=c?h+"-done":l[o+"Done"];return{baseClassName:h,activeClassName:d,doneClassName:f}},i}var t=e.prototype;return t.addClass=function(s,r,a){var o=this.getClassNames(r)[a+"ClassName"],l=this.getClassNames("enter"),c=l.doneClassName;r==="appear"&&a==="done"&&c&&(o+=" "+c),a==="active"&&s&&Ha(s),o&&(this.appliedClasses[r][a]=o,Dc(s,o))},t.removeClasses=function(s,r){var a=this.appliedClasses[r],o=a.base,l=a.active,c=a.done;this.appliedClasses[r]={},o&&Ts(s,o),l&&Ts(s,l),c&&Ts(s,c)},t.render=function(){var s=this.props;s.classNames;var r=Da(s,["classNames"]);return gt.createElement(tt,Tl({},r,{onEnter:this.onEnter,onEntered:this.onEntered,onEntering:this.onEntering,onExit:this.onExit,onExiting:this.onExiting,onExited:this.onExited}))},e}(gt.Component);Tn.defaultProps={classNames:""};Tn.propTypes={};function kc({onSliding:n,percentage:e,onMouseDown:t,onMouseUp:i}){const s=a=>{const{value:o}=a.target;n(Number(o))},r=y.useCallback(a=>{const o=()=>{a.preventDefault(),n(Math.max(0,e-10))},l=()=>{a.preventDefault(),n(Math.min(100,e+10))};(a.key==="ArrowLeft"||a.key==="ArrowDown")&&o(),(a.key==="ArrowUp"||a.key==="ArrowRight")&&l()},[n,e]);return O("div",{css:Pc.slider,style:{[Ka]:`${e}%`},children:O("input",{type:"range",tabIndex:-1,value:e,min:0,max:100,onMouseDown:t,onMouseUp:i,onChange:s,onKeyDown:r})})}const Ss={WebkitAppearance:"none",height:12,width:12,background:V.neutral0,borderRadius:"50%",marginTop:-4,cursor:"pointer",border:"none",zIndex:20},_c={display:"flex",alignItems:"center",justifyContent:"center",height:"100%","input[type=range]":{WebkitAppearance:"none",width:"100%",background:"transparent"},"input[type=range]::-webkit-slider-thumb":{WebkitAppearance:"none"},"input[type=range]::-ms-track":{width:"100%",cursor:"pointer",background:"transparent",borderColor:"transparent",color:"transparent"}},Ka="--slider-percentage",nr=`var(${Ka})`,bs={width:"100%",height:4,borderRadius:4,cursor:"pointer",background:`linear-gradient(to right, ${V.blue400} 0%, ${V.blue400} ${nr}, ${V.neutral600} ${nr}, ${V.neutral600} 100%)`},Pc={slider:ne([_c,{"input[type=range]::-webkit-slider-thumb":Ss,"input[type=range]::-moz-range-thumb":Ss,"input[type=range]::-ms-thumb":Ss,"input[type=range]::-webkit-slider-runnable-track":bs,"input[type=range]::-moz-range-track":bs,"input[type=range]::-ms-track":bs}])},Oc=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("path",{d:"M11 13L16 8V24L11 19H7V13H11ZM20 16C19.9958 15.3019 19.809 14.6171 19.4581 14.0137C19.1072 13.4102 18.6046 12.909 18 12.56V19.44C18.6046 19.091 19.1072 18.5898 19.4581 17.9863C19.809 17.3829 19.9958 16.6981 20 16V16ZM18 8.26V10.35C19.1651 10.7664 20.173 11.5328 20.8856 12.5443C21.5982 13.5557 21.9807 14.7627 21.9807 16C21.9807 17.2373 21.5982 18.4443 20.8856 19.4557C20.173 20.4672 19.1651 21.2336 18 21.65V23.74C19.712 23.2925 21.2273 22.2901 22.3088 20.8896C23.3904 19.4891 23.977 17.7695 23.977 16C23.977 14.2305 23.3904 12.5109 22.3088 11.1104C21.2273 9.70989 19.712 8.70746 18 8.26V8.26Z",fill:"currentColor"}),y.createElement("defs",null,y.createElement("clipPath",{id:"clip0_1301_10281"},y.createElement("rect",{width:32,height:32,fill:"currentColor"})))),Fc=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("path",{d:"M11 13L16 8V24L11 19H7V13H11ZM20 16C19.9958 15.3019 19.809 14.6171 19.4581 14.0137C19.1072 13.4102 18.6046 12.909 18 12.56V19.44C18.6046 19.091 19.1072 18.5898 19.4581 17.9863C19.809 17.3829 19.9958 16.6981 20 16V16Z",fill:"currentColor"}),y.createElement("defs",null,y.createElement("clipPath",{id:"clip0_1301_10265"},y.createElement("rect",{width:32,height:32,fill:"currentColor"})))),Mc=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("path",{d:"M11 13L16 8V24L11 19H7V13H11Z",fill:"currentColor"}),y.createElement("path",{d:"M24.03 14.03L22.97 12.97L21 14.94L19.03 12.97L17.97 14.03L19.94 16L17.97 17.97L19.03 19.03L21 17.06L22.97 19.03L24.03 17.97L22.06 16L24.03 14.03Z",fill:"currentColor"}),y.createElement("defs",null,y.createElement("clipPath",{id:"clip0_1301_10273"},y.createElement("rect",{width:32,height:32,fill:"currentColor"})))),Lt=33,rr=120;function Nc({onSliding:n,isMuted:e,percentage:t,onToggleMute:i,lowerVolume:s,raiseVolume:r,buttonCss:a,hideIconForMobile:o=!0,muteChangeAvailable:l=!0,volumeChangeAvailable:c,appendToId:u,...h}){const d=e||t===0?Mc:t<50&&c?Fc:Oc,[f,g]=y.useState(!1),[m,p]=y.useState(!1),v=f||m;return l?J("div",{css:[{alignItems:"center",flexDirection:"row",gridArea:"volume",height:"100%",justifyContent:"center",overflow:"hidden",position:"relative",transition:"all ease-in-out 0.2s",width:Lt,outline:"none",[be]:{display:o?"none":"flex"},[ti]:{display:o?"none":"flex"}},c?{[Re]:{":hover":{width:rr,".volume-slider-container":{opacity:1}},width:v?rr:Lt,".volume-slider-container":{opacity:v?1:0},[be]:{width:Lt,":hover":{width:Lt}},[ti]:{width:Lt,":hover":{width:Lt}}}}:null],...h,children:[O(Ge,{keyboardShortcuts:["m"],"data-shortcuts":["ArrowLeft","ArrowRight"," ","Enter"],label:e||t===0?"Unmute":"Mute",onKeyDown:x=>{x.key==="ArrowLeft"&&(x.preventDefault(),s==null||s()),x.key==="ArrowRight"&&(x.preventDefault(),r==null||r())},onFocus:()=>{g(!0)},onBlur:()=>{g(!1)},css:{position:"absolute",top:0,left:0,width:"36px",outline:"none",...a},onClick:i,appendToId:u,children:O(d,{})}),c?O("div",{className:"volume-slider-container",css:{position:"absolute",height:"100%",left:48,marginRight:4,opacity:0,transition:"opacity ease-in-out 0.4s",transitionDelay:"0.1s",[be]:{display:"none"},[ti]:{display:"none"}},children:O(kc,{onSliding:n,percentage:e?0:t,onMouseDown:()=>{p(!0)},onMouseUp:()=>{p(!1)}})}):null]}):null}const Bc={".tippy-box":{backgroundColor:nt.modalSecondaryBackground,fontSize:"0.8em",fontWeight:500,lineHeight:1.1,borderRadius:"4px",".tippy-content":{color:nt.label,padding:"8px",".tooltip-key":{color:nt.label400}}},".tippy-arrow":{color:nt.modalSecondaryBackground}},Vt=0,Uc=Vt+1,$c=Vt+2,Gc=Vt+3,Vc=Vt+4,Sn=Vt+5,ar=navigator!=null&&navigator.webdriver?0:10;function Hc({store:n}){var d;const e=ka(),t=Se(n,f=>f.autoplayEnabled),[i,s]=y.useState(ar),r=Ma(),a=(r==null?void 0:r.type)==="video_episode"?`/videos/${r.slug}`:(r==null?void 0:r.type)==="lesson"?`/${r.class_slug}/${r.slug}`:"",o=$l({enabled:(r==null?void 0:r.type)==="video_episode",pathname:a});y.useEffect(()=>{s(ar)},[r==null?void 0:r.id]);const{data:l}=Gl(r);(r==null?void 0:r.type)==="lesson"&&(o.state={...o.state,isContinuingPlayback:!0});const c=y.useCallback(()=>{o.pathname&&(ci(),e.push(o))},[e,o]);if(y.useEffect(()=>{if(!(!t||!r)){if(i===0)c();else if(i>0){const f=setTimeout(()=>s(g=>g-1),1e3);return()=>clearTimeout(f)}}},[t,c,i,r]),!r)return null;const u=r.title,h=r.type==="lesson"?(d=r.class)==null?void 0:d.title:r.channel_title;return J(Zs,{children:[O("div",{css:{position:"absolute",zIndex:$c,width:"100%",height:"100%",background:V.neutral1000_80}}),J("div",{css:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:Vc,display:"flex",flexDirection:"column",width:"100%",maxWidth:600,padding:24},children:[J("div",{css:{display:"flex",width:"100%",marginBottom:16},children:[O("div",{css:{width:"calc(50% - 8px)",marginRight:8},children:O(Vl,{item:r,engagement:l})}),J("div",{css:{width:"calc(50% - 8px)",display:"flex",flexDirection:"column",marginLeft:8,...Hi.callout},children:[O("h3",{css:{marginBottom:8,color:V.neutral0,fontWeight:Hi.weight.medium,fontSize:17,...zn({lineHeight:"22px",maxLineCount:4}),[be]:{fontSize:12,lineHeight:"16px"}},children:u}),J("div",{css:{display:"flex",alignItems:"center"},children:[r.type==="video_episode"?O(Hl,{item:r,css:{alignSelf:"center",[be]:{display:"none"}}}):null,O("p",{css:{color:V.neutral0,...zn({lineHeight:"16px",maxLineCount:2})},children:h})]})]})]}),J("div",{css:{display:"flex"},children:[O(Xn,{css:{flex:1,marginRight:8},theme:"secondary",onClick:()=>{n.getState().set({isEndScreenShowing:!1})},onKeyDown:f=>{f.code==="Space"&&(f.preventDefault(),n.getState().set({isEndScreenShowing:!1}))},children:"Cancel"}),O(Xn,{css:{flex:1,marginLeft:8},onKeyDown:f=>{f.code==="Space"&&(f.preventDefault(),c())},onClick:()=>{ci()},to:o,children:t?`Playing in ${i}`:"Play next"})]})]})]})}const Wi=n=>{const e=Math.floor(n/3600),t=Math.floor((n-e*(60*60))/60),i=Math.floor(n-e*60*60-t*60);return e>0?`${e}:${t.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}`:`${t.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}`},Wa="data-hover-trigger",_t=`[${Wa}]:hover &`,Ya="data-focus-trigger",en=`[${Ya}]:focus-visible &`,qa="data-is-scrubbing",si=`[${qa}="true"] &`;function Kc({store:n,showBufferingProgress:e,playerHandlers:t,isPlaying:i,onFocus:s,areControlsVisible:r,type:a,...o}){const l=Se(n,D=>D.isScrubbing),c=y.useCallback(D=>{n.getState().set({isScrubbing:D})},[n]),u=y.useRef(null),h=y.useRef(null),d=y.useRef(null),f=y.useRef(null),g=y.useRef(null),m=y.useRef(null),p=y.useRef(!1),{matches:v}=hs(`screen and ${Kl}`),x=Se(n,D=>D.duration),S=y.useCallback(D=>{if(!u.current)return;u.current.innerHTML="";const{currentTime:I}=n.getState();let k=[0,0];for(let Q=0;Q<D.length;Q++){const[,$]=D[Q];if($>I){k=D[Q];break}}const[M,_]=k;if(_<I)return;const N=(I-M)/100<2?I:M,B=document.createElement("div");let G=(_-N)/x*100;const X=N/x*100;B.style.left=`${X}%`,X+G>100&&(G=100-X),B.style.width=`${G}%`,u.current.replaceChildren(B)},[x,n]);y.useEffect(()=>{const D=Nt(S,200),I=M=>{D(M)},k=n.subscribe(M=>M.buffered,I,{equalityFn:_a});return()=>{D.cancel(),k()}},[S,n]);const b=y.useCallback(D=>{if(!h.current||!d.current||x===0)return;const I=D/x*100;h.current.style.width=Ie(I,0,100)+"%",d.current.style.left=Ie(I,0,100)+"%"},[x]);y.useEffect(()=>{if(l)return;const D=Nt(b,500),I=M=>{D(M)};b(n.getState().currentTime);const k=n.subscribe(M=>M.currentTime,I);return()=>{D.cancel(),k()}},[l,n,b]),y.useEffect(()=>{const D=()=>t.back5(),I=()=>t.forward5(),k=()=>t.back15(),M=()=>t.forward15(),_=N=>{if(N.ctrlKey||N.metaKey||N.shiftKey)return;const B=N.target,G=({key:X,callback:Q,event:$})=>{Na({element:B,event:$})||!Wl($,X)||(Q(),r||s==null||s())};G({key:"ArrowLeft",callback:D,event:N}),G({key:"ArrowRight",callback:I,event:N}),G({key:"j",callback:k,event:N}),G({key:"l",callback:M,event:N})};return document.addEventListener("keydown",_),()=>{document.removeEventListener("keydown",_)}},[r,s,t]);const T=y.useCallback(D=>{if(!m.current)return;if("buttons"in D&&D.buttons===0){c(!1),p.current&&(t.play(),p.current=!1),document.removeEventListener("mousemove",T),document.removeEventListener("touchmove",T);return}D.preventDefault();const I=m.current.getBoundingClientRect(),k=I.left,M=I.width,_="touches"in D?D.touches[0].clientX:D.clientX;if(typeof _!="number")return;const N=Ie((_-k)/M*x,0,x);if(t.setCurrentTime(N),!g.current)return;const B=g.current.getBoundingClientRect().width;g.current.style.left=Ie(_-k,B/2,M-B/2)-B/2+"px",g.current.innerHTML=Wi(N)},[x,c,t]),L=y.useCallback(D=>{var N;if(c(!1),p.current&&(t.play(),p.current=!1),document.removeEventListener("mousemove",T),document.removeEventListener("touchmove",T),!m.current)return;const I=m.current.getBoundingClientRect(),k=I.left,M=I.width,_="changedTouches"in D?(N=D.changedTouches[0])==null?void 0:N.clientX:D.clientX;if(typeof _=="number"){const B=Ie((_-k)/M*x,0,x);t.setCurrentTime(B)}},[x,T,c,t]),A=y.useCallback(()=>{c(!0),i&&(p.current=!0,t.pause()),v?(document.addEventListener("touchmove",T,{passive:!1}),document.addEventListener("touchend",L,{once:!0})):(document.addEventListener("mousemove",T,{passive:!1}),document.addEventListener("mouseup",L,{once:!0}))},[i,v,T,L,c,t]);y.useEffect(()=>{if(!m.current)return;const D=m.current;return v?D.addEventListener("touchstart",A):D.addEventListener("mousedown",A),()=>{v?D.removeEventListener("touchstart",A):D.removeEventListener("mousedown",A)}},[v,A]),y.useEffect(()=>{const D=m.current;if(!D)return;const I=M=>{if(!m.current)return;const _=m.current.getBoundingClientRect(),N=_.left,B=_.width,G=(M.clientX-N)/B*x;t.setCurrentTime(G)},k=M=>{if(!m.current||!f.current)return;const _=m.current.getBoundingClientRect(),N=_.left,B=_.width,G=Ie((M.clientX-N)/B*x,0,x);if(f.current.style.left=M.clientX-N+"px",!g.current)return;const X=g.current.getBoundingClientRect().width;g.current.style.left=Ie(M.clientX-N,X/2,B-X/2)-X/2+"px",g.current.innerHTML=Wi(G)};return D.addEventListener("click",I),D.addEventListener("mousemove",k),s&&D.addEventListener("focus",s),()=>{D.removeEventListener("click",I),D.removeEventListener("mousemove",k),s&&D.removeEventListener("focus",s)}},[x,s,t]);const P=a==="video"?Wc:Yc;return O("div",{"aria-label":"scrubber",tabIndex:0,css:P.wrapper,ref:m,...o,[Wa]:"",[qa]:l,[Ya]:"",children:J("div",{css:P.focusOutline,className:ja,children:[O("div",{css:P.timeTooltip,ref:g,children:"0:00"}),J("div",{css:P.barsWrapper,children:[O("div",{css:P.videoScrubberOverlay}),O("div",{style:{opacity:e?1:0},css:P.bufferBar,ref:u}),O("div",{ref:h,style:{transitionDuration:l?"0s":"0.2s"},css:P.progressBar}),O("div",{ref:f,className:za,css:P.marker})]}),O("div",{style:{transitionDuration:l?"0s":"0.2s"},ref:d,css:P.playhead})]})})}const za="scrubber-current-time-pointer",Xa=`.${za}`,ja="focus-outline",Yi=`.${ja}`,Wc={wrapper:ne({position:"relative",margin:"0 12px",height:"12px",top:"2px",userSelect:"none",cursor:"pointer",borderRadius:"4px",[Ne]:{outline:0,[Yi]:{boxShadow:`0px 0px 0px 1px ${V.blue400} inset`}},[Re]:{transition:"padding 0.2s ease-in-out","&:hover":{[Yi]:{padding:"1px 2px"},[Xa]:{opacity:1}}}}),videoScrubberOverlay:ne({width:"100%",position:"absolute",background:V.neutral600,opacity:.5,height:"100%"}),focusOutline:ne({height:"8px",top:"4px",width:"100%",position:"relative",borderRadius:"6px",padding:"2px",boxSizing:"border-box",transition:"padding 0.2s ease-in-out"}),barsWrapper:ne({position:"relative",top:0,left:0,width:"100%",margin:"0 auto",height:"100%",transition:"all 0.2s ease-in-out",borderRadius:"4px",overflow:"hidden"}),bufferBar:ne({width:"100%",height:"100%",position:"absolute",">div":{position:"absolute",height:"100%",backgroundColor:V.neutral300,bottom:0}}),progressBar:ne({left:"0",width:"0%",height:"100%",position:"absolute",transitionTimingFunction:"ease-in-out",transitionProperty:"all",background:V.blue400}),timeTooltip:ne({color:nt.label,background:nt.modalSecondaryBackground,position:"absolute",bottom:"15px",borderRadius:"4px",fontSize:"12px",fontWeight:500,padding:"4px 8px",fontFamily:ii,fontFeatureSettings:'"tnum"',letterSpacing:"0.06px",display:"none",[_t]:{[Re]:{display:"block"}},[si]:{display:"block"}}),playhead:ne({position:"absolute",left:0,top:"-4px",borderRadius:"8px",backgroundColor:V.neutral0,width:"16px",height:"16px",transitionTimingFunction:"ease-in-out",transitionProperty:"all",transform:"scale(0)",marginLeft:"-6px",opacity:1,[_t]:{transformOrigin:"center",transform:"scale(1)"},[en]:{transformOrigin:"center",transform:"scale(1)"},[si]:{transformOrigin:"center",transform:"scale(1)"}}),marker:ne({width:"1px",height:"100%",background:V.neutral1000,left:0,position:"absolute",opacity:0})},Yc={wrapper:ne({position:"relative",height:"18px",userSelect:"none",cursor:"pointer",borderRadius:"4px",[Ne]:{outline:0,[Yi]:{boxShadow:`0px 0px 0px 1px ${V.blue400} inset`}},[Re]:{"&:hover":{[Yi]:{padding:"2px"},[Xa]:{opacity:1}}}}),videoScrubberOverlay:ne({display:"none"}),focusOutline:ne({top:"4px",width:"100%",position:"relative",borderRadius:"6px",padding:"2px",boxSizing:"border-box",transition:"padding 0.2s ease-in-out"}),barsWrapper:ne({display:"flex",alignItems:"center",flexDirection:"column",justifyContent:"center",flex:1,height:6,borderRadius:6,width:"100%",position:"relative",transition:"height 0.1s",overflow:"hidden",background:He.podcastTrack}),bufferBar:ne({width:"100%",height:"100%",position:"absolute",">div":{position:"absolute",height:"100%",background:He.podcastTrackBuffer,bottom:0}}),progressBar:ne({left:"0",width:"0%",height:"100%",position:"absolute",transitionTimingFunction:"ease-in-out",transitionProperty:"all",background:He.primaryButton,[_t]:{background:He.primaryButtonHover},[en]:{background:He.primaryButtonHover},[si]:{background:He.primaryButtonHover}}),timeTooltip:ne({color:nt.label,background:nt.modalSecondaryBackground,position:"absolute",bottom:"15px",borderRadius:"4px",fontSize:"12px",fontWeight:500,padding:"4px 8px",fontFamily:ii,fontFeatureSettings:'"tnum"',letterSpacing:"0.06px",display:"none",[_t]:{[Re]:{display:"block"}},[si]:{display:"block"}}),playhead:ne({boxShadow:"0 0 4px 0 rgba(0, 0, 0, 0.5)",position:"absolute",left:0,top:"-3px",borderRadius:"8px",backgroundColor:V.neutral0,width:"16px",height:"16px",transitionTimingFunction:"ease-in-out",transitionProperty:"all",transform:"scale(0)",marginLeft:"-8px",[_t]:{transformOrigin:"center",transform:"scale(1)"},[en]:{transformOrigin:"center",transform:"scale(1)"},[si]:{transformOrigin:"center",transform:"scale(1)"}}),marker:ne({opacity:0,position:"absolute",bottom:0,left:-1,width:1,height:"6px",background:"rgba(0, 0, 0, 0.3)",transition:"opacity ease-in-out 0.1s",[_t]:{[Re]:{opacity:1}}})},qc=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("g",{opacity:1,clipPath:"url(#clip0_1301_10396)"},y.createElement("path",{d:"M22.12 20.5L20.62 19H22.88C22.9614 19 23.042 18.984 23.1173 18.9528C23.1925 18.9216 23.2608 18.876 23.3184 18.8184C23.376 18.7608 23.4216 18.6925 23.4528 18.6173C23.484 18.542 23.5 18.4614 23.5 18.38V10.62C23.5 10.4556 23.4347 10.2979 23.3184 10.1816C23.2021 10.0653 23.0444 10 22.88 10H9.12C8.95557 10 8.79787 10.0653 8.68159 10.1816C8.56532 10.2979 8.5 10.4556 8.5 10.62V18.38C8.5 18.4614 8.51604 18.542 8.54719 18.6173C8.57835 18.6925 8.62402 18.7608 8.68159 18.8184C8.73917 18.876 8.80751 18.9216 8.88274 18.9528C8.95796 18.984 9.03858 19 9.12 19H11.38L9.88 20.5H9.12C8.55774 20.5 8.01851 20.2766 7.62093 19.8791C7.22336 19.4815 7 18.9423 7 18.38V10.62C7 10.0577 7.22336 9.51851 7.62093 9.12093C8.01851 8.72336 8.55774 8.5 9.12 8.5H22.88C23.4423 8.5 23.9815 8.72336 24.3791 9.12093C24.7766 9.51851 25 10.0577 25 10.62V18.38C25 18.9423 24.7766 19.4815 24.3791 19.8791C23.9815 20.2766 23.4423 20.5 22.88 20.5H22.12ZM10.21 23.5C10.1113 23.5006 10.0146 23.4719 9.93215 23.4177C9.8497 23.3634 9.78515 23.2859 9.74665 23.195C9.70816 23.1041 9.69743 23.0038 9.71582 22.9069C9.73421 22.8099 9.7809 22.7205 9.85 22.65L15.65 16.85C15.7435 16.7584 15.8691 16.7071 16 16.7071C16.1309 16.7071 16.2565 16.7584 16.35 16.85L22.15 22.65C22.2191 22.7205 22.2658 22.8099 22.2842 22.9069C22.3026 23.0038 22.2918 23.1041 22.2533 23.195C22.2148 23.2859 22.1503 23.3634 22.0678 23.4177C21.9854 23.4719 21.8887 23.5006 21.79 23.5H10.21Z",fill:"currentColor"})),y.createElement("defs",null,y.createElement("clipPath",{id:"clip0_1301_10396"},y.createElement("rect",{width:32,height:32,fill:"currentColor"})))),zc=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("path",{id:"Vector",d:"M11.0449 20C8.9206 20 7.20001 18.21 7.20001 16C7.20001 13.79 8.9206 12 11.0449 12C15.8318 12 16.1682 20 20.9551 20C23.0794 20 24.8 18.21 24.8 16C24.8 13.79 23.0794 12 20.9551 12C16.1682 12 15.8318 20 11.0449 20Z",stroke:"currentColor",strokeWidth:1.5,strokeMiterlimit:10})),Xc=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7 8C4.79086 8 3 9.79086 3 12V20C3 22.2091 4.79086 24 7 24H25C27.2091 24 29 22.2091 29 20V12C29 9.79086 27.2091 8 25 8H7ZM8.2 16C8.2 14.3046 9.50978 13 11.0449 13C11.9192 13 12.6014 13.3501 13.2463 13.9706C13.8026 14.5058 14.291 15.202 14.8105 16C14.291 16.798 13.8026 17.4942 13.2463 18.0294C12.6014 18.6499 11.9192 19 11.0449 19C9.50978 19 8.2 17.6954 8.2 16ZM14.633 12.5294C15.1414 13.0185 15.5907 13.5946 16 14.1819C16.4093 13.5946 16.8586 13.0185 17.367 12.5294C18.2811 11.6499 19.436 11 20.9551 11C23.6686 11 25.8 13.2754 25.8 16C25.8 18.7246 23.6686 21 20.9551 21C19.436 21 18.2811 20.3501 17.367 19.4706C16.8586 18.9815 16.4093 18.4054 16 17.8181C15.5907 18.4054 15.1414 18.9815 14.633 19.4706C13.7189 20.3501 12.564 21 11.0449 21C8.3314 21 6.2 18.7246 6.2 16C6.2 13.2754 8.3314 11 11.0449 11C12.564 11 13.7189 11.6499 14.633 12.5294ZM18.7537 18.0294C18.1974 17.4942 17.709 16.798 17.1895 16C17.709 15.202 18.1974 14.5058 18.7537 13.9706C19.3986 13.3501 20.0808 13 20.9551 13C22.4902 13 23.8 14.3046 23.8 16C23.8 17.6954 22.4902 19 20.9551 19C20.0808 19 19.3986 18.6499 18.7537 18.0294Z",fill:"currentColor"})),jc=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("g",{opacity:1},y.createElement("path",{d:"M6.75 12.1333V10.25C6.75 9.42157 7.42157 8.75 8.25 8.75L23.75 8.75C24.5784 8.75 25.25 9.42157 25.25 10.25V21.75C25.25 22.5784 24.5784 23.25 23.75 23.25H17.9474",stroke:"currentColor",strokeWidth:1.5}),y.createElement("mask",{id:"mask0_1301_10405",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:6,y:19,width:5,height:5},y.createElement("rect",{x:6,y:19,width:5,height:5,fill:"#D9D9D9"})),y.createElement("g",{mask:"url(#mask0_1301_10405)"},y.createElement("circle",{cx:6,cy:24,r:2,fill:"currentColor",stroke:"currentColor",strokeWidth:1.5})),y.createElement("path",{d:"M11.5 24C11.5 20.9624 9.03757 18.5 6 18.5",stroke:"currentColor",strokeWidth:1.5}),y.createElement("path",{d:"M15 24C15 19.0294 10.9706 15 6 15",stroke:"currentColor",strokeWidth:1.5}))),or=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("g",{opacity:1,clipPath:"url(#clip0_1301_10402)"},y.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M23 11H9V12.627C12.9624 13.907 16.093 17.0376 17.373 21H23V11Z",fill:"currentColor"}),y.createElement("path",{d:"M6.75 12.1333V10.25C6.75 9.42157 7.42157 8.75 8.25 8.75L23.75 8.75C24.5784 8.75 25.25 9.42157 25.25 10.25V21.75C25.25 22.5784 24.5784 23.25 23.75 23.25H17.9474",stroke:"currentColor",strokeWidth:1.5}),y.createElement("mask",{id:"mask0_1301_10402",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:6,y:19,width:5,height:5},y.createElement("rect",{x:6,y:19,width:5,height:5,fill:"#D9D9D9"})),y.createElement("g",{mask:"url(#mask0_1301_10402)"},y.createElement("circle",{cx:6,cy:24,r:2,fill:"currentColor",stroke:"currentColor",strokeWidth:1.5})),y.createElement("path",{d:"M11.5 24C11.5 20.9624 9.03757 18.5 6 18.5",stroke:"currentColor",strokeWidth:1.5}),y.createElement("path",{d:"M15 24C15 19.0294 10.9706 15 6 15",stroke:"currentColor",strokeWidth:1.5})),y.createElement("defs",null,y.createElement("clipPath",{id:"clip0_1301_10402"},y.createElement("rect",{width:32,height:32,fill:"currentColor"})))),Zc=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("g",{className:"topRight"},y.createElement("path",{d:"M24.75 13.75H18.75V7.25H20.75V11.75H24.75V13.75Z",fill:"currentColor"})),y.createElement("g",{className:"topLeft"},y.createElement("path",{d:"M13.25 13.75H7.25V11.75H11.25V7.25H13.25V13.75Z",fill:"currentColor"})),y.createElement("g",{className:"bottomLeft"},y.createElement("path",{d:"M13.25 24.75H11.25V20.25H7.25V18.25H13.25V24.75Z",fill:"currentColor"})),y.createElement("g",{className:"bottomRight"},y.createElement("path",{d:"M20.75 24.75H18.75V18.25H24.75V20.25H20.75V24.75Z",fill:"currentColor"})),y.createElement("defs",null,y.createElement("clipPath",{id:"clip0_1301_10206"},y.createElement("rect",{width:32,height:32,fill:"currentColor"})))),Qc=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("g",{className:"topRight"},y.createElement("path",{d:"M25 13.5H23V9H19V7H25V13.5Z",fill:"currentColor"})),y.createElement("g",{className:"topLeft"},y.createElement("path",{d:"M9 13.5H7V7H13V9H9V13.5Z",fill:"currentColor"})),y.createElement("g",{className:"bottomRight"},y.createElement("path",{d:"M25 25H19V23H23V18.5H25V25Z",fill:"currentColor"})),y.createElement("g",{className:"bottomLeft"},y.createElement("path",{d:"M13 25H7V18.5H9V23H13V25Z",fill:"currentColor"})),y.createElement("defs",null,y.createElement("clipPath",{id:"clip0_1301_10220"},y.createElement("rect",{width:32,height:32,fill:"currentColor"})))),Jc=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("path",{d:"M10.5 23C10.3674 23 10.2402 22.9473 10.1464 22.8536C10.0527 22.7598 10 22.6326 10 22.5V9.5C10 9.36739 10.0527 9.24021 10.1464 9.14645C10.2402 9.05268 10.3674 9 10.5 9H13.5C13.6326 9 13.7598 9.05268 13.8536 9.14645C13.9473 9.24021 14 9.36739 14 9.5V22.5C14 22.6326 13.9473 22.7598 13.8536 22.8536C13.7598 22.9473 13.6326 23 13.5 23H10.5ZM18.5 23C18.3674 23 18.2402 22.9473 18.1464 22.8536C18.0527 22.7598 18 22.6326 18 22.5V9.5C18 9.36739 18.0527 9.24021 18.1464 9.14645C18.2402 9.05268 18.3674 9 18.5 9H21.5C21.6326 9 21.7598 9.05268 21.8536 9.14645C21.9473 9.24021 22 9.36739 22 9.5V22.5C22 22.6326 21.9473 22.7598 21.8536 22.8536C21.7598 22.9473 21.6326 23 21.5 23H18.5Z",fill:"currentColor"})),eu=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("g",{clipPath:"url(#clip0_453_1870)"},y.createElement("path",{d:"M23 9.5C23.663 9.5 24.2989 9.76339 24.7678 10.2322C25.2366 10.7011 25.5 11.337 25.5 12V20C25.5 20.663 25.2366 21.2989 24.7678 21.7678C24.2989 22.2366 23.663 22.5 23 22.5H9C8.33696 22.5 7.70107 22.2366 7.23223 21.7678C6.76339 21.2989 6.5 20.663 6.5 20V12C6.5 11.337 6.76339 10.7011 7.23223 10.2322C7.70107 9.76339 8.33696 9.5 9 9.5H23ZM23 8H9C7.93913 8 6.92172 8.42143 6.17157 9.17157C5.42143 9.92172 5 10.9391 5 12V20C5 21.0609 5.42143 22.0783 6.17157 22.8284C6.92172 23.5786 7.93913 24 9 24H23C24.0609 24 25.0783 23.5786 25.8284 22.8284C26.5786 22.0783 27 21.0609 27 20V12C27 10.9391 26.5786 9.92172 25.8284 9.17157C25.0783 8.42143 24.0609 8 23 8Z",fill:"currentColor"}),y.createElement("g",{className:"bottomRect"},y.createElement("path",{d:"M27.75 19H20.25C19.5596 19 19 19.5223 19 20.1667V24.8333C19 25.4777 19.5596 26 20.25 26H27.75C28.4404 26 29 25.4777 29 24.8333V20.1667C29 19.5223 28.4404 19 27.75 19Z",fill:"currentColor"}))),y.createElement("defs",null,y.createElement("clipPath",{id:"clip0_453_1870"},y.createElement("rect",{width:32,height:32,fill:"currentColor"})))),tu=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("path",{d:"m21.75 15.57-11-6.5a.5.5 0 0 0-.75.43v13a.49.49 0 0 0 .25.43.45.45 0 0 0 .25.07.43.43 0 0 0 .25-.07l11-6.5a.49.49 0 0 0 0-.86z",fill:"currentColor"})),iu=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("g",{opacity:1,clipPath:"url(#clip0_1301_10301)"},y.createElement("path",{d:"M0 16C0 7.16344 7.16344 0 16 0C24.8366 0 32 7.16344 32 16C32 24.8366 24.8366 32 16 32C7.16344 32 0 24.8366 0 16Z",fill:"#131619",fillOpacity:.5}),y.createElement("path",{d:"M23.75 15.57L12.75 9.07001C12.6742 9.02625 12.5883 9.00315 12.5008 9.00302C12.4132 9.00289 12.3272 9.02573 12.2513 9.06926C12.1754 9.11278 12.1122 9.17548 12.0681 9.25107C12.024 9.32666 12.0005 9.4125 12 9.50001V22.5C11.9995 22.5875 12.0224 22.6735 12.0664 22.7491C12.1104 22.8247 12.1738 22.8872 12.25 22.93C12.3247 22.9774 12.4116 23.0017 12.5 23C12.5886 23.003 12.6759 22.9785 12.75 22.93L23.75 16.43C23.8272 16.3878 23.8916 16.3256 23.9365 16.25C23.9814 16.1743 24.0051 16.088 24.0051 16C24.0051 15.912 23.9814 15.8257 23.9365 15.75C23.8916 15.6744 23.8272 15.6122 23.75 15.57Z",fill:"currentColor"})),y.createElement("defs",null,y.createElement("clipPath",{id:"clip0_1301_10301"},y.createElement("rect",{width:32,height:32,fill:"currentColor"})))),su=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("g",{opacity:1},y.createElement("g",{clipPath:"url(#clip0_1301_10304)"},y.createElement("path",{d:"M24.25 16C24.2531 17.0851 24.0408 18.1601 23.6254 19.1626C23.21 20.1651 22.5997 21.0751 21.83 21.84C21.0645 22.6054 20.1555 23.2122 19.1551 23.6258C18.1547 24.0393 17.0825 24.2514 16 24.25C14.9175 24.2514 13.8453 24.0393 12.8449 23.6258C11.8445 23.2122 10.9355 22.6054 10.17 21.84C9.40028 21.0751 8.79002 20.1651 8.37461 19.1626C7.9592 18.1601 7.7469 17.0851 7.75 16C7.74767 14.9165 7.96036 13.8432 8.37577 12.8425C8.79117 11.8417 9.40103 10.9334 10.17 10.17C10.3106 10.0296 10.5012 9.95066 10.7 9.95066C10.8988 9.95066 11.0894 10.0296 11.23 10.17C11.3705 10.3106 11.4493 10.5013 11.4493 10.7C11.4493 10.8988 11.3705 11.0894 11.23 11.23C10.5963 11.8522 10.093 12.5945 9.7496 13.4136C9.40619 14.2326 9.22955 15.1119 9.23001 16C9.23044 16.8895 9.40745 17.77 9.75077 18.5905C10.0941 19.411 10.5969 20.1553 11.23 20.78C11.8532 21.4124 12.5958 21.9148 13.4146 22.2581C14.2334 22.6014 15.1121 22.7788 16 22.78C16.8879 22.7788 17.7667 22.6014 18.5855 22.2581C19.4043 21.9148 20.1468 21.4124 20.77 20.78C21.4031 20.1553 21.9059 19.411 22.2492 18.5905C22.5926 17.77 22.7696 16.8895 22.77 16C22.7705 15.1119 22.5938 14.2326 22.2504 13.4136C21.907 12.5945 21.4037 11.8522 20.77 11.23C19.8728 10.33 18.739 9.7025 17.5 9.42V10.54C17.5013 10.6302 17.4778 10.719 17.4319 10.7966C17.386 10.8742 17.3196 10.9377 17.24 10.98C17.1659 11.0187 17.0836 11.0392 17 11.04C16.9013 11.038 16.8048 11.0105 16.72 10.96L13.72 8.96C13.6514 8.91367 13.5955 8.85104 13.5571 8.77774C13.5187 8.70443 13.4991 8.62275 13.5 8.54C13.4989 8.45861 13.5185 8.37828 13.557 8.30656C13.5955 8.23484 13.6516 8.17408 13.72 8.13L16.72 6.13C16.7979 6.08121 16.888 6.05533 16.98 6.05533C17.072 6.05533 17.1621 6.08121 17.24 6.13C17.314 6.17135 17.3765 6.23049 17.4219 6.30208C17.4673 6.37366 17.4942 6.45544 17.5 6.54V7.89C19.1426 8.18912 20.6539 8.98492 21.83 10.17C22.599 10.9334 23.2088 11.8417 23.6242 12.8425C24.0396 13.8432 24.2523 14.9165 24.25 16Z",fill:"currentColor"}))),y.createElement("defs",null,y.createElement("clipPath",{id:"clip0_1301_10304"},y.createElement("rect",{width:28,height:28,fill:"currentColor",transform:"translate(2 2)"})))),nu=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("path",{d:"M23.62 18.1C23.699 18.1577 23.7528 18.2437 23.77 18.34C23.7849 18.4331 23.7672 18.5284 23.72 18.61L22.12 21.39C22.0725 21.4699 21.998 21.5302 21.91 21.56C21.8199 21.5947 21.7201 21.5947 21.63 21.56L19.63 20.76C19.2153 21.0769 18.7616 21.339 18.28 21.54L18 23.66C17.9863 23.7551 17.9361 23.8412 17.86 23.9C17.8258 23.9336 17.7851 23.9598 17.7404 23.977C17.6957 23.9942 17.6479 24.002 17.6 24H14.4C14.3521 24.002 14.3043 23.9942 14.2596 23.977C14.2149 23.9598 14.1742 23.9336 14.14 23.9C14.0639 23.8412 14.0137 23.7551 14 23.66L13.7 21.54C13.2206 21.3346 12.7674 21.0727 12.35 20.76L10.35 21.56C10.2599 21.5947 10.1601 21.5947 10.07 21.56C9.98198 21.5302 9.90751 21.4699 9.86 21.39L8.26 18.61C8.22497 18.5234 8.22497 18.4266 8.26 18.34C8.26448 18.2922 8.27933 18.246 8.30351 18.2045C8.32769 18.1631 8.36062 18.1274 8.4 18.1L10.08 16.78C10.08 16.48 10.03 16.22 10.03 16C10.03 15.78 10.03 15.52 10.08 15.22L8.37 13.9C8.33062 13.8726 8.29769 13.8369 8.27351 13.7954C8.24933 13.754 8.23448 13.7078 8.23 13.66C8.19497 13.5734 8.19497 13.4766 8.23 13.39L9.83 10.61C9.87751 10.5301 9.95198 10.4698 10.04 10.44C10.1301 10.4053 10.2299 10.4053 10.32 10.44L12.32 11.24C12.7347 10.9231 13.1884 10.661 13.67 10.46L14 8.34C14.0137 8.24485 14.0639 8.15877 14.14 8.1C14.1742 8.06642 14.2149 8.04022 14.2596 8.02302C14.3043 8.00582 14.3521 7.99798 14.4 8H17.59C17.6379 7.99798 17.6857 8.00582 17.7304 8.02302C17.7751 8.04022 17.8158 8.06642 17.85 8.1C17.929 8.1577 17.9828 8.24367 18 8.34L18.3 10.46C18.7794 10.6654 19.2326 10.9273 19.65 11.24L21.65 10.44C21.7366 10.405 21.8334 10.405 21.92 10.44C22.008 10.4698 22.0825 10.5301 22.13 10.61L23.74 13.39C23.775 13.4766 23.775 13.5734 23.74 13.66C23.7219 13.7536 23.6725 13.8382 23.6 13.9L21.91 15.22C21.9767 15.7379 21.9767 16.2621 21.91 16.78L23.62 18.1ZM17.4 18.42C17.8142 18.1788 18.1588 17.8342 18.4 17.42C18.6429 16.9934 18.7705 16.5109 18.7705 16.02C18.7705 15.5291 18.6429 15.0466 18.4 14.62C18.1556 14.1941 17.8032 13.8402 17.3783 13.5941C16.9534 13.348 16.471 13.2184 15.98 13.2184C15.489 13.2184 15.0066 13.348 14.5817 13.5941C14.1568 13.8402 13.8044 14.1941 13.56 14.62C13.1908 15.2603 13.0887 16.0202 13.2759 16.7353C13.4631 17.4503 13.9244 18.0627 14.56 18.44C14.9865 18.6886 15.4713 18.8196 15.965 18.8196C16.4587 18.8196 16.9435 18.6886 17.37 18.44L17.4 18.42Z",fill:"currentColor"}),y.createElement("defs",null,y.createElement("clipPath",{id:"clip0_1301_10389"},y.createElement("rect",{width:32,height:32,fill:"currentColor"})))),lr=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M23 9.5C23.663 9.5 24.2989 9.76339 24.7678 10.2322C25.2366 10.7011 25.5 11.337 25.5 12V20C25.5 20.663 25.2366 21.2989 24.7678 21.7678C24.2989 22.2366 23.663 22.5 23 22.5H9C8.33696 22.5 7.70107 22.2366 7.23223 21.7678C6.76339 21.2989 6.5 20.663 6.5 20V12C6.5 11.337 6.76339 10.7011 7.23223 10.2322C7.70107 9.76339 8.33696 9.5 9 9.5H23ZM23 8H9C7.93913 8 6.92172 8.42143 6.17157 9.17157C5.42143 9.92172 5 10.9391 5 12V20C5 21.0609 5.42143 22.0783 6.17157 22.8284C6.92172 23.5786 7.93913 24 9 24H23C24.0609 24 25.0783 23.5786 25.8284 22.8284C26.5786 22.0783 27 21.0609 27 20V12C27 10.9391 26.5786 9.92172 25.8284 9.17157C25.0783 8.42143 24.0609 8 23 8ZM8.15 17.7153C8.15 17.4029 8.40323 17.1497 8.7156 17.1497H12.5178C12.8301 17.1497 13.0834 17.4029 13.0834 17.7153C13.0834 18.0277 12.8301 18.2809 12.5178 18.2809H8.7156C8.40323 18.2809 8.15 18.0277 8.15 17.7153ZM19.4856 19.464C19.1732 19.464 18.92 19.7172 18.92 20.0296C18.92 20.342 19.1732 20.5952 19.4856 20.5952H23.2878C23.6001 20.5952 23.8534 20.342 23.8534 20.0296C23.8534 19.7172 23.6001 19.464 23.2878 19.464H19.4856ZM14.5 17.7153C14.5 17.4029 14.7532 17.1497 15.0656 17.1497H23.2809C23.5932 17.1497 23.8465 17.4029 23.8465 17.7153C23.8465 18.0277 23.5932 18.2809 23.2809 18.2809H15.0656C14.7532 18.2809 14.5 18.0277 14.5 17.7153ZM8.7156 19.464C8.40323 19.464 8.15 19.7172 8.15 20.0296C8.15 20.342 8.40323 20.5952 8.7156 20.5952H16.9309C17.2432 20.5952 17.4965 20.342 17.4965 20.0296C17.4965 19.7172 17.2432 19.464 16.9309 19.464H8.7156Z",fill:"currentColor"}),y.createElement("defs",null,y.createElement("clipPath",{id:"clip0_1301_10164"},y.createElement("rect",{width:32,height:32,fill:"currentColor"})))),cr=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("g",{clipPath:"url(#clip0_2624_8039)"},y.createElement("path",{d:"M23.7 8H8.3C7.42479 8 6.58542 8.36122 5.96655 9.0042C5.34768 9.64719 5 10.5193 5 11.4286V20.5714C5 21.4807 5.34768 22.3528 5.96655 22.9958C6.58542 23.6388 7.42479 24 8.3 24H23.7C24.5752 24 25.4146 23.6388 26.0335 22.9958C26.6523 22.3528 27 21.4807 27 20.5714V11.4286C27 10.5193 26.6523 9.64719 26.0335 9.0042C25.4146 8.36122 24.5752 8 23.7 8ZM8.3 17.1429H12.15C12.2959 17.1429 12.4358 17.2031 12.5389 17.3102C12.6421 17.4174 12.7 17.5627 12.7 17.7143C12.7 17.8658 12.6421 18.0112 12.5389 18.1183C12.4358 18.2255 12.2959 18.2857 12.15 18.2857H8.3C8.15413 18.2857 8.01424 18.2255 7.91109 18.1183C7.80795 18.0112 7.75 17.8658 7.75 17.7143C7.75 17.5627 7.80795 17.4174 7.91109 17.3102C8.01424 17.2031 8.15413 17.1429 8.3 17.1429ZM16.55 21.7143H8.3C8.15413 21.7143 8.01424 21.6541 7.91109 21.5469C7.80795 21.4398 7.75 21.2944 7.75 21.1429C7.75 20.9913 7.80795 20.846 7.91109 20.7388C8.01424 20.6316 8.15413 20.5714 8.3 20.5714H16.55C16.6959 20.5714 16.8358 20.6316 16.9389 20.7388C17.0421 20.846 17.1 20.9913 17.1 21.1429C17.1 21.2944 17.0421 21.4398 16.9389 21.5469C16.8358 21.6541 16.6959 21.7143 16.55 21.7143ZM23.7 21.7143H19.85C19.7041 21.7143 19.5642 21.6541 19.4611 21.5469C19.3579 21.4398 19.3 21.2944 19.3 21.1429C19.3 20.9913 19.3579 20.846 19.4611 20.7388C19.5642 20.6316 19.7041 20.5714 19.85 20.5714H23.7C23.8459 20.5714 23.9858 20.6316 24.0889 20.7388C24.1921 20.846 24.25 20.9913 24.25 21.1429C24.25 21.2944 24.1921 21.4398 24.0889 21.5469C23.9858 21.6541 23.8459 21.7143 23.7 21.7143ZM23.7 18.2857H15.45C15.3041 18.2857 15.1642 18.2255 15.0611 18.1183C14.9579 18.0112 14.9 17.8658 14.9 17.7143C14.9 17.5627 14.9579 17.4174 15.0611 17.3102C15.1642 17.2031 15.3041 17.1429 15.45 17.1429H23.7C23.8459 17.1429 23.9858 17.2031 24.0889 17.3102C24.1921 17.4174 24.25 17.5627 24.25 17.7143C24.25 17.8658 24.1921 18.0112 24.0889 18.1183C23.9858 18.2255 23.8459 18.2857 23.7 18.2857Z",fill:"currentColor"})),y.createElement("defs",null,y.createElement("clipPath",{id:"clip0_2624_8039"},y.createElement("rect",{width:32,height:32,fill:"currentColor"})))),ru=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("g",{className:"arrow-left"},y.createElement("path",{d:"M11 19.56L9.94 18.5L12.44 16L9.94 13.5L11 12.44L14.56 16L11 19.56Z",fill:"currentColor"})),y.createElement("g",{className:"arrow-right"},y.createElement("path",{d:"M21 19.56L17.44 16L21 12.44L22.06 13.5L19.56 16L22.06 18.5L21 19.56Z",fill:"currentColor"})),y.createElement("path",{d:"M23 9.5C23.663 9.5 24.2989 9.76339 24.7678 10.2322C25.2366 10.7011 25.5 11.337 25.5 12V20C25.5 20.663 25.2366 21.2989 24.7678 21.7678C24.2989 22.2366 23.663 22.5 23 22.5H9C8.33696 22.5 7.70107 22.2366 7.23223 21.7678C6.76339 21.2989 6.5 20.663 6.5 20V12C6.5 11.337 6.76339 10.7011 7.23223 10.2322C7.70107 9.76339 8.33696 9.5 9 9.5H23ZM23 8H9C7.93913 8 6.92172 8.42143 6.17157 9.17157C5.42143 9.92172 5 10.9391 5 12V20C5 21.0609 5.42143 22.0783 6.17157 22.8284C6.92172 23.5786 7.93913 24 9 24H23C24.0609 24 25.0783 23.5786 25.8284 22.8284C26.5786 22.0783 27 21.0609 27 20V12C27 10.9391 26.5786 9.92172 25.8284 9.17157C25.0783 8.42143 24.0609 8 23 8V8Z",fill:"currentColor"}),y.createElement("defs",null,y.createElement("clipPath",{id:"clip0_1301_10243"},y.createElement("rect",{width:32,height:32,fill:"currentColor"})))),au=n=>y.createElement("svg",{width:32,height:32,viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("g",{className:"arrow-left"},y.createElement("path",{d:"M13.5 19.56L9.94 16L13.5 12.44L14.56 13.5L12.06 16L14.56 18.5L13.5 19.56Z",fill:"currentColor"})),y.createElement("g",{className:"arrow-right"},y.createElement("path",{d:"M18.5 19.56L17.44 18.5L19.94 16L17.44 13.5L18.5 12.44L22.06 16L18.5 19.56Z",fill:"currentColor"})),y.createElement("path",{d:"M23 9.5C23.663 9.5 24.2989 9.76339 24.7678 10.2322C25.2366 10.7011 25.5 11.337 25.5 12V20C25.5 20.663 25.2366 21.2989 24.7678 21.7678C24.2989 22.2366 23.663 22.5 23 22.5H9C8.33696 22.5 7.70107 22.2366 7.23223 21.7678C6.76339 21.2989 6.5 20.663 6.5 20V12C6.5 11.337 6.76339 10.7011 7.23223 10.2322C7.70107 9.76339 8.33696 9.5 9 9.5H23ZM23 8H9C7.93913 8 6.92172 8.42143 6.17157 9.17157C5.42143 9.92172 5 10.9391 5 12V20C5 21.0609 5.42143 22.0783 6.17157 22.8284C6.92172 23.5786 7.93913 24 9 24H23C24.0609 24 25.0783 23.5786 25.8284 22.8284C26.5786 22.0783 27 21.0609 27 20V12C27 10.9391 26.5786 9.92172 25.8284 9.17157C25.0783 8.42143 24.0609 8 23 8V8Z",fill:"currentColor"}),y.createElement("defs",null,y.createElement("clipPath",{id:"clip0_1301_10255"},y.createElement("rect",{width:32,height:32,fill:"currentColor"})))),ou=n=>y.createElement("svg",{width:12,height:12,viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},y.createElement("path",{d:"M9.15 3.15L4.5 7.8L2.85 6.15C2.65 5.95 2.35 5.95 2.15 6.15C1.95 6.35 1.95 6.65 2.15 6.85L4.15 8.85C4.25 8.95 4.35 9 4.5 9C4.65 9 4.75 8.95 4.85 8.85L9.85 3.85C10.05 3.65 10.05 3.35 9.85 3.15C9.65 2.95 9.35 2.95 9.15 3.15Z",fill:"currentColor"}));function lu({className:n,onFocus:e,store:t}){const i=Se(t,s=>s.autoplayEnabled);return O(Ge,{className:n,label:i?"Autoplay is on":"Autoplay is off",onClick:()=>{oc(!i,"video"),t.getState().set({autoplayEnabled:!i})},onFocus:e,role:"switch","aria-checked":i,children:i?O(Xc,{}):O(zc,{})})}function cu({checked:n,onCheckedChange:e,...t}){const i={width:32,height:20,border:"none",backgroundColor:n?V.blue400:He.label100,borderRadius:9999,cursor:"pointer",padding:"2px 2px"},s={display:"flex",alignItems:"center",justifyContent:"center",width:16,height:16,backgroundColor:V.neutral0,borderRadius:"100%",transform:n?"translate(12px, 0px)":"translate(0px, 0px)",transition:"transform 100ms ease-in-out",svg:{color:V.neutral1000,height:"100%",width:"100%"}};return O("button",{type:"button",role:"checkbox",css:i,onClick:()=>{e(!n)},"aria-checked":n,...t,children:O("div",{css:s})})}function ni({active:n,activeColor:e}){return O(ou,{css:{marginRight:"6px",color:n?e!=null?e:V.neutral25:"rgba(0,0,0,0)"}})}function Ue(n){return O(ds.OptionButton,{forceDarkTheme:!0,css:Za,...n})}function tn(n){return O(ds.OptionLabel,{forceDarkTheme:!0,css:Za,...n})}const Za={color:V.neutral0,padding:"13px",width:"216px",height:"42px",fontWeight:400,[Ne]:{boxShadow:`0px 0px 0px 1px ${V.blue400} inset`}},uu={1634:2160,1088:1440,816:1080,544:720,408:540,272:360};function Ls(n){const e=uu[n];return e||n}const hu={label:"Settings",id:"settings-button",boundaryId:"video-player",appendToId:"video-controls"};function du({quality:n,playbackSpeed:e,qualityLevels:t,autoplayEnabled:i,controlsRef:s,playerHandlers:r,videoPlayerRef:a,label:o,autoQualityLevel:l,onToggle:c,...u}){const h=mi(),d=y.useRef(null),f=y.useRef(null),g=cs(),[m,p]=y.useState("settings"),v=Ba(),x=t&&t.length>0,S=!!r.setPlaybackSpeed;y.useEffect(()=>{var L,A,P,D;if(m){const I=(D=(P=(L=f.current)==null?void 0:L.querySelector("[data-active=true]"))!=null?P:(A=f.current)==null?void 0:A.querySelector(Yl))!=null?D:null;I&&I.focus()}},[m]);const{matches:b}=hs(Ua),T=t==null?void 0:t.find(L=>L.height===n);return J(ds,{rootElement:O(nu,{}),tooltipConfig:hu,keyboardShortcut:"s",portalTargetElementRef:s,showOnHover:!1,closeRef:d,direction:"top",forceDarkTheme:!0,listRef:f,contextMenuHeightLimiterRef:a,label:o,onToggle:c,fixedPosition:!0,ignoreSpaceKeypress:v,dropdownCss:{bottom:"35px",right:"10px","> button:first-child, > a:first-child":{borderRadius:"12px 12px 0 0"},"> button:last-child, > a:last-child":{borderRadius:"0 0 12px 12px"}},css:{height:"100%",button:{transition:"0.25s ease-in-out",position:"relative",background:"none",border:"none",cursor:"pointer",height:"100%",display:"flex",justifyContent:"center",alignItems:"center",color:"rgba(255,255,255,0.9)","&[aria-pressed=true]":{color:V.neutral0},outline:"none",[Ne]:{svg:{boxShadow:`0px 0px 0px 1px ${V.blue400} inset`,borderRadius:"4px"}},"&:hover":{color:V.neutral0},"&:active":{svg:{transform:"scale(0.9)"}}}},...u,children:[m==="settings"?J(y.Fragment,{children:[O(tn,{css:{fontWeight:500},children:"Settings"}),S?J(Ue,{onClick:()=>{p("speed")},children:["Playback speed",O("div",{css:{marginLeft:"auto",color:V.neutral300},children:e===1?"Normal":e+"x"})]}):J(Ue,{css:{fontWeight:500,color:V.neutral300},disabled:!0,children:[O("span",{children:"Playback speed"}),O("span",{css:{marginLeft:"auto"},children:e===1?"Normal":e+"x"})]}),x?J(Ue,{onClick:()=>{p("quality")},css:{[`&:hover, ${Ne}`]:{"> div":{color:V.neutral25}}},children:["Quality",O("div",{css:{marginLeft:"auto",color:V.neutral300},children:T?J(Zs,{children:[Ls(T.height),"p"]}):l!=null&&l.height?J(Zs,{children:[O("span",{css:{color:V.neutral25},children:"Auto  "}),J("span",{children:[Ls(l.height),"p"]})]}):"Auto"})]}):J(tn,{css:{fontWeight:500,color:V.neutral300},disabled:!0,children:[O("span",{children:"Quality"}),O("span",{css:{marginLeft:"auto"},children:"Auto"})]}),g&&b&&!h?J("li",{css:{padding:13,alignItems:"center",justifyContent:"space-between",color:V.neutral0,display:"flex"},children:[O("span",{children:"Autoplay"}),O(cu,{checked:i,onCheckedChange:()=>{var L;(L=r.setAutoplayEnabled)==null||L.call(r,!i)}})]}):null]}):null,m==="quality"?J(y.Fragment,{children:[J(Ue,{onClick:()=>{p("settings")},children:[O(ur,{})," Quality"]}),t?J(y.Fragment,{children:[J(Ue,{onClick:L=>{r.setQualityLevel&&(r.setQualityLevel(),d.current&&(setTimeout(()=>{p("settings")},0),d.current({resetFocus:L.type==="keypress"})))},"data-active":n==="auto",css:{[Re]:{"&:hover":{svg:{color:n==="auto"?V.neutral25:V.neutral600}}},[Ne]:{svg:{color:n==="auto"?V.neutral25:V.neutral600}}},children:[O(ni,{active:n==="auto"}),"Auto"]}),[...t].sort((L,A)=>L.height<A.height?1:L.height===A.height?0:-1).map(L=>J(Ue,{"data-active":T,onClick:A=>{r.setQualityLevel&&(r.setQualityLevel(L.height),d.current&&(setTimeout(()=>{p("settings")},0),d.current({resetFocus:A.type==="keypress"})))},css:{[Re]:{"&:hover":{svg:{color:(T==null?void 0:T.height)===L.height?V.neutral25:V.neutral600}}},[Ne]:{svg:{color:(T==null?void 0:T.height)===L.height?V.neutral25:V.neutral600}}},children:[O(ni,{active:(T==null?void 0:T.height)===L.height}),Ls(L.height),"p"]},L.height))]}):null]}):null,m==="speed"?J(y.Fragment,{children:[J(Ue,{onClick:()=>{p("settings")},children:[O(ur,{})," Playback Speed"]}),Qs.map(L=>J(Ue,{"data-active":e===L,onClick:A=>{r.setPlaybackSpeed&&(r.setPlaybackSpeed(L),d.current&&(setTimeout(()=>{p("settings")},0),d.current({resetFocus:A.type==="keypress"})))},css:{[Re]:{"&:hover":{svg:{color:e===L?V.neutral25:V.neutral600}}},[Ne]:{svg:{color:e===L?V.neutral25:V.neutral600}}},children:[O(ni,{active:e===L}),L===1?"Normal":L+"x"]},L))]}):null]})}function ur(){return O(ql,{css:{height:"16px",width:"16px",position:"relative",marginRight:"5px"}})}const fu={label:"Subtitles",id:"subtitles-button",boundaryId:"video-player",appendToId:"video-controls"},hr="c";function gu({subtitles:n,currentLanguage:e,playerHandlers:t,controlsRef:i,label:s,onToggle:r,onFocus:a,...o}){const l=y.useRef(null),c=y.useRef(null),u=Ba();return n.length===0?null:n.length===1?O(Ge,{label:s,keyboardShortcuts:[hr],onFocus:a,onClick:()=>{var d;const h=e?"":n[0].label;pt(h),(d=t.changeLanguage)==null||d.call(t,h)},children:e===""?O(lr,{}):O(cr,{})}):O(ds,{rootElement:e===""?O(lr,{}):O(cr,{}),tooltipConfig:fu,keyboardShortcut:hr,portalTargetElementRef:i,showOnHover:!1,closeRef:l,direction:"top",listRef:c,forceDarkTheme:!0,label:s,onToggle:r,fixedPosition:!0,ignoreSpaceKeypress:u,onFocus:a,css:{height:"100%",button:{transition:"0.25s ease-in-out",position:"relative",background:"none",border:"none",cursor:"pointer",height:"100%",display:"flex",justifyContent:"center",alignItems:"center",color:"rgba(255,255,255,0.9)","&:hover":{color:V.neutral0},'&[aria-pressed="true"]':{color:V.neutral0},outline:"none",[Ne]:{svg:{boxShadow:`0px 0px 0px 1px ${V.blue400} inset`,borderRadius:"4px"}},"&:active":{svg:{transform:"scale(0.9)"}}}},dropdownCss:{borderRadius:"8px",bottom:"35px",right:"10px","> button:first-child, > a:first-child":{borderRadius:"12px 12px 0 0"},"> button:last-child, > a:last-child":{borderRadius:"0 0 12px 12px"}},...o,children:n?J(y.Fragment,{children:[O(tn,{css:{fontWeight:500},children:"Subtitles"}),J(Ue,{"data-active":e==="",css:{[Re]:{"&:hover":{svg:{color:e===""?V.neutral0:V.neutral600}}},[Ne]:{svg:{color:e===""?V.neutral0:V.neutral600}}},onClick:h=>{var d;pt(""),t.changeLanguage&&t.changeLanguage(""),(d=l.current)==null||d.call(l,{resetFocus:h.type==="keypress"})},children:[O(ni,{active:e===""}),"Off"]},"off"),n.map(h=>J(Ue,{"data-active":e===h.label,css:{[Re]:{"&:hover":{svg:{color:e===h.label?V.neutral25:V.neutral600}}},[Ne]:{svg:{color:e===h.label?V.neutral25:V.neutral600}}},onClick:d=>{var f;pt(h.label),t.changeLanguage&&t.changeLanguage(h.label),(f=l.current)==null||f.call(l,{resetFocus:d.type==="keypress"})},children:[O(ni,{active:e===h.label}),h.label]},h.label))]}):null})}const dr=["k"," "],mu=["t"],pu=["f"],Eu=["i"];function vu({playerHandlers:n,setTheaterMode:e,videoStore:t,videoElement:i,isTheaterMode:s,videoPlayerRef:r,onFocus:a,onBlur:o,subtitlesMenuOnToggle:l,settingsMenuOnToggle:c,areControlsVisible:u,isEndScreenOnMobile:h,title:d,wasEverPlayed:f,...g}){const m=mi(),p=cs(),{airPlayConnected:v,airPlayAvailable:x,pictureInPictureAvailable:S,isFullScreen:b,chromecastAvailable:T,fullScreenAvailable:L,volumeChangeAvailable:A,muteChangeAvailable:P}=Se(t,Y=>({airPlayConnected:Y.airPlayConnected,airPlayAvailable:Y.airPlayAvailable,pictureInPictureAvailable:Y.pictureInPictureAvailable,isFullScreen:Y.isFullScreen,chromecastAvailable:Y.chromecastAvailable,fullScreenAvailable:Y.fullScreenAvailable,volumeChangeAvailable:Y.volumeChangeAvailable,muteChangeAvailable:Y.muteChangeAvailable}),oi),D=y.useRef(null),I=y.useRef(null),[k,M]=y.useState(!1),{isPlaying:_,isMuted:N,subtitles:B,currentLanguage:G,hasEnded:X,qualityLevels:Q,quality:$,currentAutoLevel:U,playbackSpeed:ee,volume:Z,duration:te,isBuffering:oe,isSeeking:ue,isInitialized:he,autoplayEnabled:xe,chromecastConnected:De,chromecastDeviceName:rt,isEndScreenShowing:Es}=Se(t,Y=>({isPlaying:Y.isPlaying,isMuted:Y.isMuted,subtitles:Y.subtitles,currentLanguage:Y.currentLanguage,hasEnded:Y.hasEnded,qualityLevels:Y.qualityLevels,quality:Y.quality,currentAutoLevel:Y.currentAutoLevel,playbackSpeed:Y.playbackSpeed,volume:Y.volume,duration:Y.duration,isBuffering:Y.isBuffering,isSeeking:Y.isSeeking,isInitialized:Y.isInitialized,autoplayEnabled:Y.autoplayEnabled,chromecastConnected:Y.chromecastConnected,chromecastDeviceName:Y.chromecastDeviceName,isEndScreenShowing:Y.isEndScreenShowing}),oi),vs=y.useMemo(()=>Sl(Q,Y=>Y.height),[Q]);y.useEffect(()=>{const Y=Te=>{D.current&&(D.current.innerHTML=Wi(Te))};return Y(t.getState().currentTime),t.subscribe(Te=>Te.currentTime,Y)},[t]);const yt=he&&!(oe||ue);y.useEffect(()=>{k&&yt&&(n.play(),M(!1))},[k,n,yt]);const Kt=y.useCallback(()=>{if(!yt){M(!0);return}n.play()},[yt,n]),Wt=y.useCallback(()=>{M(!1),n.pause()},[n]),at=()=>{n.mute()},ot=()=>{n.unmute()},Tt=y.useCallback(()=>{if(_||k){Wt();return}Kt()},[Wt,Kt,_,k]),lt=_||k,xs=!f&&yt&&!_;return Tc({playerHandlers:n,isPlaying:_,duration:te}),y.useEffect(()=>()=>{document.pictureInPictureElement&&document.exitPictureInPicture()},[]),J("div",{id:"video-player-controls-wrapper",className:"video-player-controls-wrapper",css:{userSelect:"none",position:"absolute",bottom:0,left:0,height:"100%",width:"100%",overflow:"hidden",display:he?"block":"none",zIndex:Gc,transition:` opacity 0.2s ease-in-out 0s, border-radius 0.3s ease-in-out 0s `},children:[O("div",{css:{backgroundImage:`linear-gradient(to top, hsl(0, 0%, 0%) 0%, hsla(0, 0%, 0%, 0.738) 19%, hsla(0, 0%, 0%, 0.541) 34%, hsla(0, 0%, 0%, 0.382) 47%, hsla(0, 0%, 0%, 0.278) 56.5%, hsla(0, 0%, 0%, 0.194) 65%, hsla(0, 0%, 0%, 0.126) 73%, hsla(0, 0%, 0%, 0.075) 80.2%, hsla(0, 0%, 0%, 0.042) 86.1%, hsla(0, 0%, 0%, 0.021) 91%, hsla(0, 0%, 0%, 0.008) 95.2%, hsla(0, 0%, 0%, 0.002) 98.2%, hsla(0, 0%, 0%, 0) 100% )`,position:"absolute",left:0,bottom:0,width:"100%",height:"33%",pointerEvents:"none"}}),Es?O(Hc,{store:t}):null,De?J("div",{css:{position:"absolute",left:"10px",bottom:"60px",background:V.neutral1000_80,borderRadius:"8px",padding:"8px 16px",display:"flex",justifyContent:"center",alignItems:"center",color:V.neutral0},children:[O(or,{css:{marginRight:"5px"}}),"Casting on: ",rt]}):null,O("div",{css:{position:"absolute",top:0,left:0,width:"100%",color:V.neutral25,padding:"24px",height:"auto",pointerEvents:"none",fontSize:"24px",background:zl,display:b?"block":"none",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",opacity:b?1:0,transitionDuration:b?"0s":"1s",transitionTimingFunction:"ease",transitionProperty:"all"},children:d}),O("div",{css:{height:"100% ",width:"100%",position:"absolute",top:0,left:0,display:"flex",justifyContent:"center",alignItems:"center",color:V.neutral0},onPointerUp:Y=>{var Te;if(Y.isPrimary){if((Te=r.current)==null||Te.focus(),f||ci(),!f||Y.pointerType==="mouse"){Tt();return}if(u){o();return}a()}},onDoubleClick:()=>{var Y,Te;document.fullscreenElement||document.webkitFullscreenElement?(Y=n.exitFullScreen)==null||Y.call(n):(Te=n.requestFullScreen)==null||Te.call(n)},children:xs?O(iu,{"aria-label":"play video",css:{width:"90px",height:"90px",cursor:"pointer",zIndex:1,[ti]:{width:"84px",height:"84px",maxHeight:"50%"},[be]:{width:"84px",height:"84px",maxHeight:"50%"}}}):null}),O("div",{onClick:()=>{a()},css:{position:"absolute",bottom:0,width:"100%",height:"48px",zIndex:Sn,visibility:h?"hidden":"visible"},...g,children:J("div",{ref:I,css:xu.videoControls,id:"video-controls",children:[O(Kc,{store:t,showBufferingProgress:!De,playerHandlers:n,isPlaying:_,areControlsVisible:u,onFocus:a,type:"video"}),J("div",{css:{width:"100%",padding:"0 24px",height:"48px",display:"flex",flexAlign:"center",justifyContent:"flex-start",color:V.neutral0,[be]:{padding:"0 4px"},".icon-spacing":{gap:"12px",[be]:{gap:"4px"}}},children:[J("div",{css:{display:"flex",height:"100%",justifyContent:"flex-start",flexAlign:"center"},className:"icon-spacing",children:[X?O(Ge,{label:"Replay",onClick:()=>{n.replay()},onFocus:a,keyboardShortcuts:dr,children:O(su,{})}):O(Ge,{css:{height:"auto"},label:lt?"Pause":"Play",onClick:()=>{!f&<&&ci(),lt?Wt():Kt()},keyboardShortcuts:dr,onFocus:a,children:lt?O(Jc,{}):O(tu,{})}),O(Nc,{onToggleMute:()=>{N?ot():at(),u||a()},isMuted:N,percentage:Z*100,muteChangeAvailable:P,volumeChangeAvailable:A,lowerVolume:A?()=>{n.lowerVolume(),u||a()}:void 0,raiseVolume:A?()=>{n.raiseVolume(),u||a()}:void 0,onFocus:a,onSliding:Y=>{ot(),n.setVolume(Y/100),u||a()},hideIconForMobile:!m}),J("div",{css:{display:"flex",alignItems:"center",fontSize:"12px",fontFamily:ii,fontFeatureSettings:'"tnum"',letterSpacing:"0.06px"},children:[O("div",{css:[{minWidth:"3em",textAlign:"right",fontFamily:ii,fontFeatureSettings:'"tnum"'},m&&!f?{[be]:{display:"none"}}:null],ref:D,children:"0:00"}),O("div",{css:[{fontFamily:ii,fontFeatureSettings:'"tnum"'},m?{[be]:{display:"none"}}:null],children:" / "}),O("div",{css:m&&f?{[be]:{display:"none"}}:null,children:Wi(te)})]})]}),J("div",{css:{marginLeft:"auto",marginRight:"0",display:"flex"},className:"icon-spacing",children:[p&&!m?O(lu,{store:t,onFocus:a,css:{[be]:{display:"none"}}}):null,B!=null&&B.length&&!v?O(gu,{subtitles:B,currentLanguage:G,playerHandlers:n,controlsRef:I,onFocus:a,onToggle:l,label:"Subtitles"}):null,O(du,{quality:$,controlsRef:I,qualityLevels:vs,playerHandlers:n,playbackSpeed:ee,videoPlayerRef:r,onFocus:a,onToggle:c,label:"Settings",autoplayEnabled:xe,autoQualityLevel:U!=null?U:void 0}),x&&!m?O(Ge,{label:"AirPlay",onClick:()=>{var Y;(Y=n.airPlay)==null||Y.call(n)},onFocus:a,children:O(qc,{})}):null,T&&!m?O(Ge,{label:`Chromecast${De?" (active)":""}`,onClick:()=>{var Y;(Y=n.cast)==null||Y.call(n)},onFocus:a,children:De?O(or,{}):O(jc,{})}):null,S&&!m?O(Ge,{label:"Picture in Picture",css:{g:{transitionDuration:"0.1s",transitionTimingFunction:"ease-out",transitionProperty:"transform",transformOrigin:"center center"},".bottomRect":{transform:"translateX(-8%) translateY(-11%) scaleX(0.8) scaleY(0.85)"},[Re]:{"&:hover":{".bottomRect":{transform:"translateX(0) translateY(0) scale(1)"}}}},onFocus:a,onClick:()=>{document.pictureInPictureElement?document==null||document.exitPictureInPicture():i==null||i.requestPictureInPicture()},keyboardShortcuts:Eu,children:O(eu,{})}):null,m?null:O(Ge,{label:"Theater mode",keyboardShortcuts:mu,onClick:()=>{e(!s)},css:{[be]:{display:"none"},[ti]:{display:"none"},[Xl]:{display:"none"}},onFocus:a,children:s?O(ru,{css:{g:{transitionDuration:"0.1s",transitionTimingFunction:"ease-out",transitionProperty:"transform"},"&:hover":{".arrow-left":{transform:"translateX(2%)"},".arrow-right":{transform:"translateX(-2%)"}}}}):O(au,{css:{g:{transitionDuration:"0.1s",transitionTimingFunction:"ease-out",transitionProperty:"transform"},"&:hover":{".arrow-left":{transform:"translateX(-3%)"},".arrow-right":{transform:"translateX(3%)"}}}})}),L?O(Ge,{label:"Full screen",keyboardShortcuts:pu,onFocus:a,onClick:()=>{var Y,Te;b?n.exitFullScreen&&((Y=n.exitFullScreen)==null||Y.call(n)):n.requestFullScreen&&((Te=n.requestFullScreen)==null||Te.call(n))},children:b?O(Zc,{css:{g:{transitionDuration:"0.1s",transitionTimingFunction:"ease-out",transitionProperty:"transform"},[Re]:{"&:hover":{".topRight":{transform:"translateX(-2%) translateY(2%)"},".topLeft":{transform:"translateX(2%) translateY(2%)"},".bottomRight":{transform:"translateX(-2%) translateY(-2%)"},".bottomLeft":{transform:"translateX(2%) translateY(-2%)"}}}}}):O(Qc,{css:{g:{transitionDuration:"0.1s",transitionTimingFunction:"ease-out",transitionProperty:"transform"},[Re]:{"&:hover":{".topRight":{transform:"translateX(2%) translateY(-2%)"},".topLeft":{transform:"translateX(-2%) translateY(-2%)"},".bottomRight":{transform:"translateX(2%) translateY(2%)"},".bottomLeft":{transform:"translateX(-2%) translateY(2%)"}}}}})}):null]})]})]})})]})}const xu={videoControls:ne([{position:"absolute",bottom:0,width:"100%"},Bc])};function yu({show:n}){return O("div",{"aria-label":"video loading spinner",css:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",display:n?"flex":"none",opacity:n?1:0,transition:"opacity 0.2s ease-in-out",justifyContent:"center",alignItems:"center",width:"100%",zIndex:Sn},children:O("div",{css:{width:"62px",height:"62px",position:"relative",borderRadius:"100px",animationName:bl({"0%":{transform:"rotate(0deg)"},"100%":{transform:"rotate(360deg)"}}),animationTimingFunction:"cubic-bezier(0.55, 0.22, 0.07, 0.75)",animationIterationCount:"infinite",animationDuration:"1.05s","&:before":{content:'" "',width:"100%",borderRadius:"100px",height:"100%",position:"absolute",top:0,left:0,border:`4px solid ${V.neutral900_50}`,opacity:.8},"&:after":{width:"100%",height:"100%",borderRadius:"100px",position:"absolute",top:0,left:0,content:'" "',borderWidth:"4px",borderStyle:"solid",borderColor:`${V.neutral0} rgba(0,0,0,0) rgba(0,0,0,0) rgba(0,0,0,0)`}}})})}function Tu({className:n,style:e}){return O("div",{"data-subtitles-container":!0,className:n,style:e,css:Su.main})}const Su={main:ne({position:"absolute",top:0,left:0,right:0,height:"calc(100% - 1em)",marginTop:"0",width:"100%",alignItems:"center",zIndex:Sn,userSelect:"none",pointerEvents:"none"})};function Qa({show:n,image:e,videoTitle:t}){return O("div",{className:"video-poster",css:{position:"absolute",top:0,left:0,display:n?"flex":"none",height:"100%",width:"100%",alignItems:"center",justifyContent:"center",zIndex:Uc,background:V.neutral1000,overflow:"hidden"},children:O(jn,{name:`${t} thumbnail`,image:e,widthDefinition:"100vw",css:{height:"100%",width:"100%",display:"flex",justifyContent:"center",alignItems:"center",[jn.fallbackSelector]:{objectFit:"contain",maxHeight:"100%",maxWidth:"100%"}}})})}function bu(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Ja={exports:{}};(function(n,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,c,u){if(u=u||{},l=l.trim(),c=c.trim(),!c){if(!u.alwaysNormalize)return l;var h=o.parseURL(l);if(!h)throw new Error("Error trying to parse base URL.");return h.path=o.normalizePath(h.path),o.buildURLFromParts(h)}var d=o.parseURL(c);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return u.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):c;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=s.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var m={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(m.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)m.path=f.path,d.params||(m.params=f.params,d.query||(m.query=f.query));else{var p=f.path,v=p.substring(0,p.lastIndexOf("/")+1)+d.path;m.path=o.normalizePath(v)}return m.path===null&&(m.path=u.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(m)},parseURL:function(l){var c=i.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(r,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};n.exports=o})()})(Ja);var bn=Ja.exports;function fr(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(n);e&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(n,s).enumerable})),t.push.apply(t,i)}return t}function Ee(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?fr(Object(t),!0).forEach(function(i){Cu(n,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):fr(Object(t)).forEach(function(i){Object.defineProperty(n,i,Object.getOwnPropertyDescriptor(t,i))})}return n}function Lu(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var i=t.call(n,e||"default");if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function Au(n){var e=Lu(n,"string");return typeof e=="symbol"?e:String(e)}function Cu(n,e,t){return e=Au(e),e in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function de(){return de=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[i]=t[i])}return n},de.apply(this,arguments)}const H=Number.isFinite||function(n){return typeof n=="number"&&isFinite(n)},Ru=Number.isSafeInteger||function(n){return typeof n=="number"&&Math.abs(n)<=Iu},Iu=Number.MAX_SAFE_INTEGER||9007199254740991;let E=function(n){return n.MEDIA_ATTACHING="hlsMediaAttaching",n.MEDIA_ATTACHED="hlsMediaAttached",n.MEDIA_DETACHING="hlsMediaDetaching",n.MEDIA_DETACHED="hlsMediaDetached",n.BUFFER_RESET="hlsBufferReset",n.BUFFER_CODECS="hlsBufferCodecs",n.BUFFER_CREATED="hlsBufferCreated",n.BUFFER_APPENDING="hlsBufferAppending",n.BUFFER_APPENDED="hlsBufferAppended",n.BUFFER_EOS="hlsBufferEos",n.BUFFER_FLUSHING="hlsBufferFlushing",n.BUFFER_FLUSHED="hlsBufferFlushed",n.MANIFEST_LOADING="hlsManifestLoading",n.MANIFEST_LOADED="hlsManifestLoaded",n.MANIFEST_PARSED="hlsManifestParsed",n.LEVEL_SWITCHING="hlsLevelSwitching",n.LEVEL_SWITCHED="hlsLevelSwitched",n.LEVEL_LOADING="hlsLevelLoading",n.LEVEL_LOADED="hlsLevelLoaded",n.LEVEL_UPDATED="hlsLevelUpdated",n.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",n.LEVELS_UPDATED="hlsLevelsUpdated",n.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",n.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",n.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",n.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",n.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",n.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",n.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",n.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",n.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",n.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",n.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",n.CUES_PARSED="hlsCuesParsed",n.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",n.INIT_PTS_FOUND="hlsInitPtsFound",n.FRAG_LOADING="hlsFragLoading",n.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",n.FRAG_LOADED="hlsFragLoaded",n.FRAG_DECRYPTED="hlsFragDecrypted",n.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",n.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",n.FRAG_PARSING_METADATA="hlsFragParsingMetadata",n.FRAG_PARSED="hlsFragParsed",n.FRAG_BUFFERED="hlsFragBuffered",n.FRAG_CHANGED="hlsFragChanged",n.FPS_DROP="hlsFpsDrop",n.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",n.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",n.ERROR="hlsError",n.DESTROYING="hlsDestroying",n.KEY_LOADING="hlsKeyLoading",n.KEY_LOADED="hlsKeyLoaded",n.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",n.BACK_BUFFER_REACHED="hlsBackBufferReached",n.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",n}({}),z=function(n){return n.NETWORK_ERROR="networkError",n.MEDIA_ERROR="mediaError",n.KEY_SYSTEM_ERROR="keySystemError",n.MUX_ERROR="muxError",n.OTHER_ERROR="otherError",n}({}),w=function(n){return n.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",n.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",n.KEY_SYSTEM_NO_SESSION="keySystemNoSession",n.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",n.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",n.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",n.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",n.MANIFEST_LOAD_ERROR="manifestLoadError",n.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",n.MANIFEST_PARSING_ERROR="manifestParsingError",n.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",n.LEVEL_EMPTY_ERROR="levelEmptyError",n.LEVEL_LOAD_ERROR="levelLoadError",n.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",n.LEVEL_PARSING_ERROR="levelParsingError",n.LEVEL_SWITCH_ERROR="levelSwitchError",n.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",n.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",n.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",n.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",n.FRAG_LOAD_ERROR="fragLoadError",n.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",n.FRAG_DECRYPT_ERROR="fragDecryptError",n.FRAG_PARSING_ERROR="fragParsingError",n.FRAG_GAP="fragGap",n.REMUX_ALLOC_ERROR="remuxAllocError",n.KEY_LOAD_ERROR="keyLoadError",n.KEY_LOAD_TIMEOUT="keyLoadTimeOut",n.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",n.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",n.BUFFER_APPEND_ERROR="bufferAppendError",n.BUFFER_APPENDING_ERROR="bufferAppendingError",n.BUFFER_STALLED_ERROR="bufferStalledError",n.BUFFER_FULL_ERROR="bufferFullError",n.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",n.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",n.INTERNAL_EXCEPTION="internalException",n.INTERNAL_ABORTED="aborted",n.UNKNOWN="unknown",n}({});const dt=function(){},sn={trace:dt,debug:dt,log:dt,warn:dt,info:dt,error:dt};let ri=sn;function wu(n){const e=self.console[n];return e?e.bind(self.console,`[${n}] >`):dt}function Du(n,...e){e.forEach(function(t){ri[t]=n[t]?n[t].bind(n):wu(t)})}function ku(n,e){if(typeof console=="object"&&n===!0||typeof n=="object"){Du(n,"debug","log","info","warn","error");try{ri.log(`Debug logs enabled for "${e}" in hls.js version 1.5.16`)}catch{ri=sn}}else ri=sn}const C=ri,_u=/^(\d+)x(\d+)$/,gr=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ce{constructor(e){typeof e=="string"&&(e=ce.parseAttrList(e)),de(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const i=new Uint8Array(t.length/2);for(let s=0;s<t.length/2;s++)i[s]=parseInt(t.slice(s*2,s*2+2),16);return i}else return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}bool(e){return this[e]==="YES"}decimalResolution(e){const t=_u.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const i={},s='"';for(gr.lastIndex=0;(t=gr.exec(e))!==null;){let r=t[2];r.indexOf(s)===0&&r.lastIndexOf(s)===r.length-1&&(r=r.slice(1,-1));const a=t[1].trim();i[a]=r}return i}}function Pu(n){return n!=="ID"&&n!=="CLASS"&&n!=="START-DATE"&&n!=="DURATION"&&n!=="END-DATE"&&n!=="END-ON-NEXT"}function Ou(n){return n==="SCTE35-OUT"||n==="SCTE35-IN"}class eo{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const i=t.attr;for(const s in i)if(Object.prototype.hasOwnProperty.call(e,s)&&e[s]!==i[s]){C.warn(`DATERANGE tag attribute: "${s}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=s;break}e=de(new ce({}),i,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const i=new Date(this.attr["END-DATE"]);H(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return e!==null?new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(H(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&H(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class fs{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var se={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class to{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[se.AUDIO]:null,[se.VIDEO]:null,[se.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,t){const i=e.split("@",2);let s;i.length===1?s=(t==null?void 0:t.byteRangeEndOffset)||0:s=parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=bn.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class As extends to{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new fs,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const i=Object.keys(this.levelkeys);if(i.length===1)return this._decryptdata=this.levelkeys[i[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!H(this.programDateTime))return null;const e=H(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),i=t.length;if(i>1||i===1&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,s,r,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:r,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,s),l.endDTS=Math.max(l.endDTS,r)}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[se.AUDIO]=null,e[se.VIDEO]=null,e[se.AUDIOVIDEO]=null}}class Fu extends to{constructor(e,t,i,s,r){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new fs,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}const Mu=10;class Nu{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?H(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Mu}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function Ln(n){return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}function Bu(n){const e=nn(n).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Uu(n){const e=function(i,s,r){const a=i[s];i[s]=i[r],i[r]=a};e(n,0,3),e(n,1,2),e(n,4,5),e(n,6,7)}function $u(n){const e=n.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),s=i[i.length-1].split(",");if(s.length===2){const r=s[0]==="base64",a=s[1];r?(i.splice(-1,1),t=Ln(a)):t=Bu(a)}}return t}function nn(n){return Uint8Array.from(unescape(encodeURIComponent(n)),e=>e.charCodeAt(0))}const Bt=typeof self<"u"?self:void 0;var ae={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ce={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function mr(n){switch(n){case Ce.FAIRPLAY:return ae.FAIRPLAY;case Ce.PLAYREADY:return ae.PLAYREADY;case Ce.WIDEVINE:return ae.WIDEVINE;case Ce.CLEARKEY:return ae.CLEARKEY}}var Zt={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",FAIRPLAY:"94ce86fb07ff4f43adb893d2fa968ca2",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function pr(n){if(n===Zt.WIDEVINE)return ae.WIDEVINE;if(n===Zt.PLAYREADY)return ae.PLAYREADY;if(n===Zt.CENC||n===Zt.CLEARKEY)return ae.CLEARKEY}function Er(n){switch(n){case ae.FAIRPLAY:return Ce.FAIRPLAY;case ae.PLAYREADY:return Ce.PLAYREADY;case ae.WIDEVINE:return Ce.WIDEVINE;case ae.CLEARKEY:return Ce.CLEARKEY}}function Cs(n){const{drmSystems:e,widevineLicenseUrl:t}=n,i=e?[ae.FAIRPLAY,ae.WIDEVINE,ae.PLAYREADY,ae.CLEARKEY].filter(s=>!!e[s]):[];return!i[ae.WIDEVINE]&&t&&i.push(ae.WIDEVINE),i}const io=function(n){return Bt!=null&&(n=Bt.navigator)!=null&&n.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Gu(n,e,t,i){let s;switch(n){case ae.FAIRPLAY:s=["cenc","sinf"];break;case ae.WIDEVINE:case ae.PLAYREADY:s=["cenc"];break;case ae.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${n}`)}return Vu(s,e,t,i)}function Vu(n,e,t,i){return[{initDataTypes:n,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs="${r}"`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs="${r}"`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function Et(n,e,t){return Uint8Array.prototype.slice?n.slice(e,t):new Uint8Array(Array.prototype.slice.call(n,e,t))}const An=(n,e)=>e+10<=n.length&&n[e]===73&&n[e+1]===68&&n[e+2]===51&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128,so=(n,e)=>e+10<=n.length&&n[e]===51&&n[e+1]===68&&n[e+2]===73&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128,ui=(n,e)=>{const t=e;let i=0;for(;An(n,e);){i+=10;const s=gs(n,e+6);i+=s,so(n,e+10)&&(i+=10),e+=i}if(i>0)return n.subarray(t,t+i)},gs=(n,e)=>{let t=0;return t=(n[e]&127)<<21,t|=(n[e+1]&127)<<14,t|=(n[e+2]&127)<<7,t|=n[e+3]&127,t},Hu=(n,e)=>An(n,e)&&gs(n,e+6)+10<=n.length-e,Cn=n=>{const e=ro(n);for(let t=0;t<e.length;t++){const i=e[t];if(no(i))return Xu(i)}},no=n=>n&&n.key==="PRIV"&&n.info==="com.apple.streaming.transportStreamTimestamp",Ku=n=>{const e=String.fromCharCode(n[0],n[1],n[2],n[3]),t=gs(n,4),i=10;return{type:e,size:t,data:n.subarray(i,i+t)}},ro=n=>{let e=0;const t=[];for(;An(n,e);){const i=gs(n,e+6);e+=10;const s=e+i;for(;e+8<s;){const r=Ku(n.subarray(e)),a=Wu(r);a&&t.push(a),e+=r.size+10}so(n,e)&&(e+=10)}return t},Wu=n=>n.type==="PRIV"?Yu(n):n.type[0]==="W"?zu(n):qu(n),Yu=n=>{if(n.size<2)return;const e=ze(n.data,!0),t=new Uint8Array(n.data.subarray(e.length+1));return{key:n.type,info:e,data:t.buffer}},qu=n=>{if(n.size<2)return;if(n.type==="TXXX"){let t=1;const i=ze(n.data.subarray(t),!0);t+=i.length+1;const s=ze(n.data.subarray(t));return{key:n.type,info:i,data:s}}const e=ze(n.data.subarray(1));return{key:n.type,data:e}},zu=n=>{if(n.type==="WXXX"){if(n.size<2)return;let t=1;const i=ze(n.data.subarray(t),!0);t+=i.length+1;const s=ze(n.data.subarray(t));return{key:n.type,info:i,data:s}}const e=ze(n.data);return{key:n.type,data:e}},Xu=n=>{if(n.data.byteLength===8){const e=new Uint8Array(n.data),t=e[3]&1;let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}},ze=(n,e=!1)=>{const t=ju();if(t){const c=t.decode(n);if(e){const u=c.indexOf("\0");return u!==-1?c.substring(0,u):c}return c.replace(/\0/g,"")}const i=n.length;let s,r,a,o="",l=0;for(;l<i;){if(s=n[l++],s===0&&e)return o;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(s);break;case 12:case 13:r=n[l++],o+=String.fromCharCode((s&31)<<6|r&63);break;case 14:r=n[l++],a=n[l++],o+=String.fromCharCode((s&15)<<12|(r&63)<<6|(a&63)<<0);break}}return o};let Rs;function ju(){if(!navigator.userAgent.includes("PlayStation 4"))return!Rs&&typeof self.TextDecoder<"u"&&(Rs=new self.TextDecoder("utf-8")),Rs}const Ve={hexDump:function(n){let e="";for(let t=0;t<n.length;t++){let i=n[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}},qi=Math.pow(2,32)-1,Zu=[].push,ao={video:1,audio:2,id3:3,text:4};function fe(n){return String.fromCharCode.apply(null,n)}function oo(n,e){const t=n[e]<<8|n[e+1];return t<0?65536+t:t}function K(n,e){const t=lo(n,e);return t<0?4294967296+t:t}function vr(n,e){let t=K(n,e);return t*=Math.pow(2,32),t+=K(n,e+4),t}function lo(n,e){return n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3]}function Is(n,e,t){n[e]=t>>24,n[e+1]=t>>16&255,n[e+2]=t>>8&255,n[e+3]=t&255}function Qu(n){const e=n.byteLength;for(let t=0;t<e;){const i=K(n,t);if(i>8&&n[t+4]===109&&n[t+5]===111&&n[t+6]===111&&n[t+7]===102)return!0;t=i>1?t+i:e}return!1}function j(n,e){const t=[];if(!e.length)return t;const i=n.byteLength;for(let s=0;s<i;){const r=K(n,s),a=fe(n.subarray(s+4,s+8)),o=r>1?s+r:i;if(a===e[0])if(e.length===1)t.push(n.subarray(s+8,o));else{const l=j(n.subarray(s+8,o),e.slice(1));l.length&&Zu.apply(t,l)}s=o}return t}function Ju(n){const e=[],t=n[0];let i=8;const s=K(n,i);i+=4;let r=0,a=0;t===0?(r=K(n,i),a=K(n,i+4),i+=8):(r=vr(n,i),a=vr(n,i+8),i+=16),i+=2;let o=n.length+a;const l=oo(n,i);i+=2;for(let c=0;c<l;c++){let u=i;const h=K(n,u);u+=4;const d=h&2147483647;if((h&2147483648)>>>31===1)return C.warn("SIDX has hierarchical references (not supported)"),null;const g=K(n,u);u+=4,e.push({referenceSize:d,subsegmentDuration:g,info:{duration:g/s,start:o,end:o+d-1}}),o+=d,u+=4,i=u}return{earliestPresentationTime:r,timescale:s,version:t,referencesCount:l,references:e}}function co(n){const e=[],t=j(n,["moov","trak"]);for(let s=0;s<t.length;s++){const r=t[s],a=j(r,["tkhd"])[0];if(a){let o=a[0];const l=K(a,o===0?12:20),c=j(r,["mdia","mdhd"])[0];if(c){o=c[0];const u=K(c,o===0?12:20),h=j(r,["mdia","hdlr"])[0];if(h){const d=fe(h.subarray(8,12)),f={soun:se.AUDIO,vide:se.VIDEO}[d];if(f){const g=j(r,["mdia","minf","stbl","stsd"])[0],m=eh(g);e[l]={timescale:u,type:f},e[f]=Ee({timescale:u,id:l},m)}}}}}return j(n,["moov","mvex","trex"]).forEach(s=>{const r=K(s,4),a=e[r];a&&(a.default={duration:K(s,12),flags:K(s,20)})}),e}function eh(n){const e=n.subarray(8),t=e.subarray(86),i=fe(e.subarray(4,8));let s=i;const r=i==="enca"||i==="encv";if(r){const o=j(e,[i])[0].subarray(i==="enca"?28:78);j(o,["sinf"]).forEach(c=>{const u=j(c,["schm"])[0];if(u){const h=fe(u.subarray(4,8));if(h==="cbcs"||h==="cenc"){const d=j(c,["frma"])[0];d&&(s=fe(d))}}})}switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const a=j(t,["avcC"])[0];s+="."+xi(a[1])+xi(a[2])+xi(a[3]);break}case"mp4a":{const a=j(e,[i])[0],o=j(a.subarray(28),["esds"])[0];if(o&&o.length>12){let l=4;if(o[l++]!==3)break;l=ws(o,l),l+=2;const c=o[l++];if(c&128&&(l+=2),c&64&&(l+=o[l++]),o[l++]!==4)break;l=ws(o,l);const u=o[l++];if(u===64)s+="."+xi(u);else break;if(l+=12,o[l++]!==5)break;l=ws(o,l);const h=o[l++];let d=(h&248)>>3;d===31&&(d+=1+((h&7)<<3)+((o[l]&224)>>5)),s+="."+d}break}case"hvc1":case"hev1":{const a=j(t,["hvcC"])[0],o=a[1],l=["","A","B","C"][o>>6],c=o&31,u=K(a,2),h=(o&32)>>5?"H":"L",d=a[12],f=a.subarray(6,12);s+="."+l+c,s+="."+u.toString(16).toUpperCase(),s+="."+h+d;let g="";for(let m=f.length;m--;){const p=f[m];(p||g)&&(g="."+p.toString(16).toUpperCase()+g)}s+=g;break}case"dvh1":case"dvhe":{const a=j(t,["dvcC"])[0],o=a[2]>>1&127,l=a[2]<<5&32|a[3]>>3&31;s+="."+Be(o)+"."+Be(l);break}case"vp09":{const a=j(t,["vpcC"])[0],o=a[4],l=a[5],c=a[6]>>4&15;s+="."+Be(o)+"."+Be(l)+"."+Be(c);break}case"av01":{const a=j(t,["av1C"])[0],o=a[1]>>>5,l=a[1]&31,c=a[2]>>>7?"H":"M",u=(a[2]&64)>>6,h=(a[2]&32)>>5,d=o===2&&u?h?12:10:u?10:8,f=(a[2]&16)>>4,g=(a[2]&8)>>3,m=(a[2]&4)>>2,p=a[2]&3;s+="."+o+"."+Be(l)+c+"."+Be(d)+"."+f+"."+g+m+p+"."+Be(1)+"."+Be(1)+"."+Be(1)+"."+0;break}}return{codec:s,encrypted:r}}function ws(n,e){const t=e+5;for(;n[e++]&128&&e<t;);return e}function xi(n){return("0"+n.toString(16).toUpperCase()).slice(-2)}function Be(n){return(n<10?"0":"")+n}function th(n,e){if(!n||!e)return n;const t=e.keyId;return t&&e.isCommonEncryption&&j(n,["moov","trak"]).forEach(s=>{const a=j(s,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=j(a,["enca"]);const l=o.length>0;l||(o=j(a,["encv"])),o.forEach(c=>{const u=l?c.subarray(28):c.subarray(78);j(u,["sinf"]).forEach(d=>{const f=uo(d);if(f){const g=f.subarray(8,24);g.some(m=>m!==0)||(C.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${Ve.hexDump(g)} -> ${Ve.hexDump(t)}`),f.set(t,8))}})})}),n}function uo(n){const e=j(n,["schm"])[0];if(e){const t=fe(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return j(n,["schi","tenc"])[0]}return null}function ih(n,e){return j(e,["moof","traf"]).reduce((t,i)=>{const s=j(i,["tfdt"])[0],r=s[0],a=j(i,["tfhd"]).reduce((o,l)=>{const c=K(l,4),u=n[c];if(u){let h=K(s,4);if(r===1){if(h===qi)return C.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;h*=qi+1,h+=K(s,8)}const d=u.timescale||9e4,f=h/d;if(H(f)&&(o===null||f<o))return f}return o},null);return a!==null&&H(a)&&(t===null||a<t)?a:t},null)}function sh(n,e){let t=0,i=0,s=0;const r=j(n,["moof","traf"]);for(let a=0;a<r.length;a++){const o=r[a],l=j(o,["tfhd"])[0],c=K(l,4),u=e[c];if(!u)continue;const h=u.default,d=K(l,0)|(h==null?void 0:h.flags);let f=h==null?void 0:h.duration;d&8&&(d&2?f=K(l,12):f=K(l,8));const g=u.timescale||9e4,m=j(o,["trun"]);for(let p=0;p<m.length;p++){if(t=nh(m[p]),!t&&f){const v=K(m[p],4);t=f*v}u.type===se.VIDEO?i+=t/g:u.type===se.AUDIO&&(s+=t/g)}}if(i===0&&s===0){let a=1/0,o=0,l=0;const c=j(n,["sidx"]);for(let u=0;u<c.length;u++){const h=Ju(c[u]);if(h!=null&&h.references){a=Math.min(a,h.earliestPresentationTime/h.timescale);const d=h.references.reduce((f,g)=>f+g.info.duration||0,0);o=Math.max(o,d+h.earliestPresentationTime/h.timescale),l=o-a}}if(l&&H(l))return l}return i||s}function nh(n){const e=K(n,0);let t=8;e&1&&(t+=4),e&4&&(t+=4);let i=0;const s=K(n,4);for(let r=0;r<s;r++){if(e&256){const a=K(n,t);i+=a,t+=4}e&512&&(t+=4),e&1024&&(t+=4),e&2048&&(t+=4)}return i}function rh(n,e,t){j(e,["moof","traf"]).forEach(i=>{j(i,["tfhd"]).forEach(s=>{const r=K(s,4),a=n[r];if(!a)return;const o=a.timescale||9e4;j(i,["tfdt"]).forEach(l=>{const c=l[0],u=t*o;if(u){let h=K(l,4);if(c===0)h-=u,h=Math.max(h,0),Is(l,4,h);else{h*=Math.pow(2,32),h+=K(l,8),h-=u,h=Math.max(h,0);const d=Math.floor(h/(qi+1)),f=Math.floor(h%(qi+1));Is(l,4,d),Is(l,8,f)}}})})})}function ah(n){const e={valid:null,remainder:null},t=j(n,["moof"]);if(t.length<2)return e.remainder=n,e;const i=t[t.length-1];return e.valid=Et(n,0,i.byteOffset-8),e.remainder=Et(n,i.byteOffset-8),e}function Pe(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function xr(n,e){const t=[],i=e.samples,s=e.timescale,r=e.id;let a=!1;return j(i,["moof"]).map(l=>{const c=l.byteOffset-8;j(l,["traf"]).map(h=>{const d=j(h,["tfdt"]).map(f=>{const g=f[0];let m=K(f,4);return g===1&&(m*=Math.pow(2,32),m+=K(f,8)),m/s})[0];return d!==void 0&&(n=d),j(h,["tfhd"]).map(f=>{const g=K(f,4),m=K(f,0)&16777215,p=(m&1)!==0,v=(m&2)!==0,x=(m&8)!==0;let S=0;const b=(m&16)!==0;let T=0;const L=(m&32)!==0;let A=8;g===r&&(p&&(A+=8),v&&(A+=4),x&&(S=K(f,A),A+=4),b&&(T=K(f,A),A+=4),L&&(A+=4),e.type==="video"&&(a=oh(e.codec)),j(h,["trun"]).map(P=>{const D=P[0],I=K(P,0)&16777215,k=(I&1)!==0;let M=0;const _=(I&4)!==0,N=(I&256)!==0;let B=0;const G=(I&512)!==0;let X=0;const Q=(I&1024)!==0,$=(I&2048)!==0;let U=0;const ee=K(P,4);let Z=8;k&&(M=K(P,Z),Z+=4),_&&(Z+=4);let te=M+c;for(let oe=0;oe<ee;oe++){if(N?(B=K(P,Z),Z+=4):B=S,G?(X=K(P,Z),Z+=4):X=T,Q&&(Z+=4),$&&(D===0?U=K(P,Z):U=lo(P,Z),Z+=4),e.type===se.VIDEO){let ue=0;for(;ue<X;){const he=K(i,te);if(te+=4,lh(a,i[te])){const xe=i.subarray(te,te+he);ho(xe,a?2:1,n+U/s,t)}te+=he,ue+=he+4}}n+=B/s}}))})})}),t}function oh(n){if(!n)return!1;const e=n.indexOf("."),t=e<0?n:n.substring(0,e);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function lh(n,e){if(n){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function ho(n,e,t,i){const s=fo(n);let r=0;r+=e;let a=0,o=0,l=0;for(;r<s.length;){a=0;do{if(r>=s.length)break;l=s[r++],a+=l}while(l===255);o=0;do{if(r>=s.length)break;l=s[r++],o+=l}while(l===255);const c=s.length-r;let u=r;if(o<c)r+=o;else if(o>c){C.error(`Malformed SEI payload. ${o} is too small, only ${c} bytes left to parse.`);break}if(a===4){if(s[u++]===181){const d=oo(s,u);if(u+=2,d===49){const f=K(s,u);if(u+=4,f===1195456820){const g=s[u++];if(g===3){const m=s[u++],p=31&m,v=64&m,x=v?2+p*3:0,S=new Uint8Array(x);if(v){S[0]=m;for(let b=1;b<x;b++)S[b]=s[u++]}i.push({type:g,payloadType:a,pts:t,bytes:S})}}}}}else if(a===5&&o>16){const h=[];for(let g=0;g<16;g++){const m=s[u++].toString(16);h.push(m.length==1?"0"+m:m),(g===3||g===5||g===7||g===9)&&h.push("-")}const d=o-16,f=new Uint8Array(d);for(let g=0;g<d;g++)f[g]=s[u++];i.push({payloadType:a,pts:t,uuid:h.join(""),userData:ze(f),userDataBytes:f})}}}function fo(n){const e=n.byteLength,t=[];let i=1;for(;i<e-2;)n[i]===0&&n[i+1]===0&&n[i+2]===3?(t.push(i+2),i+=2):i++;if(t.length===0)return n;const s=e-t.length,r=new Uint8Array(s);let a=0;for(i=0;i<s;a++,i++)a===t[0]&&(a++,t.shift()),r[i]=n[a];return r}function ch(n){const e=n[0];let t="",i="",s=0,r=0,a=0,o=0,l=0,c=0;if(e===0){for(;fe(n.subarray(c,c+1))!=="\0";)t+=fe(n.subarray(c,c+1)),c+=1;for(t+=fe(n.subarray(c,c+1)),c+=1;fe(n.subarray(c,c+1))!=="\0";)i+=fe(n.subarray(c,c+1)),c+=1;i+=fe(n.subarray(c,c+1)),c+=1,s=K(n,12),r=K(n,16),o=K(n,20),l=K(n,24),c=28}else if(e===1){c+=4,s=K(n,c),c+=4;const h=K(n,c);c+=4;const d=K(n,c);for(c+=4,a=2**32*h+d,Ru(a)||(a=Number.MAX_SAFE_INTEGER,C.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=K(n,c),c+=4,l=K(n,c),c+=4;fe(n.subarray(c,c+1))!=="\0";)t+=fe(n.subarray(c,c+1)),c+=1;for(t+=fe(n.subarray(c,c+1)),c+=1;fe(n.subarray(c,c+1))!=="\0";)i+=fe(n.subarray(c,c+1)),c+=1;i+=fe(n.subarray(c,c+1)),c+=1}const u=n.subarray(c,n.byteLength);return{schemeIdUri:t,value:i,timeScale:s,presentationTime:a,presentationTimeDelta:r,eventDuration:o,id:l,payload:u}}function uh(n,...e){const t=e.length;let i=8,s=t;for(;s--;)i+=e[s].byteLength;const r=new Uint8Array(i);for(r[0]=i>>24&255,r[1]=i>>16&255,r[2]=i>>8&255,r[3]=i&255,r.set(n,4),s=0,i=8;s<t;s++)r.set(e[s],i),i+=e[s].byteLength;return r}function hh(n,e,t){if(n.byteLength!==16)throw new RangeError("Invalid system id");let i,s;i=0,s=new Uint8Array;let r;i>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const a=new Uint8Array(4);return t&&t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),uh([112,115,115,104],new Uint8Array([i,0,0,0]),n,r,s,a,t||new Uint8Array)}function dh(n){const e=[];if(n instanceof ArrayBuffer){const t=n.byteLength;let i=0;for(;i+32<t;){const s=new DataView(n,i),r=fh(s);e.push(r),i+=r.size}}return e}function fh(n){const e=n.getUint32(0),t=n.byteOffset,i=n.byteLength;if(i<e)return{offset:t,size:i};if(n.getUint32(4)!==1886614376)return{offset:t,size:e};const r=n.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const a=n.buffer,o=Ve.hexDump(new Uint8Array(a,t+12,16)),l=n.getUint32(28);let c=null,u=null;if(r===0){if(e-32<l||l<22)return{offset:t,size:e};u=new Uint8Array(a,t+32,l)}else if(r===1){if(!l||i<t+32+l*16+16)return{offset:t,size:e};c=[];for(let h=0;h<l;h++)c.push(new Uint8Array(a,t+32+h*16,16))}return{version:r,systemId:o,kids:c,data:u,offset:t,size:e}}let yi={};class hi{static clearKeyUriToKeyIdMap(){yi={}}constructor(e,t,i,s=[1],r=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=s,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&e!=="AES-128"}isSupported(){if(this.method){if(this.method==="AES-128"||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Ce.FAIRPLAY:case Ce.WIDEVINE:case Ce.PLAYREADY:case Ce.CLEARKEY:return["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(this.method==="AES-128"&&this.uri&&!this.iv){typeof e!="number"&&(this.method==="AES-128"&&!this.iv&&C.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const i=gh(e);return new hi(this.method,this.uri,"identity",this.keyFormatVersions,i)}const t=$u(this.uri);if(t)switch(this.keyFormat){case Ce.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Ce.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=hh(i,null,t);const s=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),r=String.fromCharCode.apply(null,Array.from(s)),a=r.substring(r.indexOf("<"),r.length),c=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("KID")[0];if(c){const u=c.childNodes[0]?c.childNodes[0].nodeValue:c.getAttribute("VALUE");if(u){const h=Ln(u).subarray(0,16);Uu(h),this.keyId=h}}break}default:{let i=t.subarray(0,16);if(i.length!==16){const s=new Uint8Array(16);s.set(i,16-i.length),i=s}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=yi[this.uri];if(!i){const s=Object.keys(yi).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,s),yi[this.uri]=i}this.keyId=i}return this}}function gh(n){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=n>>8*(15-t)&255;return e}const go=/\{\$([a-zA-Z0-9-_]+)\}/g;function yr(n){return go.test(n)}function Ae(n,e,t){if(n.variableList!==null||n.hasVariableRefs)for(let i=t.length;i--;){const s=t[i],r=e[s];r&&(e[s]=rn(n,r))}}function rn(n,e){if(n.variableList!==null||n.hasVariableRefs){const t=n.variableList;return e.replace(go,i=>{const s=i.substring(2,i.length-1),r=t==null?void 0:t[s];return r===void 0?(n.playlistParsingError||(n.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),i):r})}return e}function Tr(n,e,t){let i=n.variableList;i||(n.variableList=i={});let s,r;if("QUERYPARAM"in e){s=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(s))r=a.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${t}"`)}catch(a){n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else s=e.NAME,r=e.VALUE;s in i?n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):i[s]=r||""}function mh(n,e,t){const i=e.IMPORT;if(t&&i in t){let s=n.variableList;s||(n.variableList=s={}),s[i]=t[i]}else n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function vt(n=!0){return typeof self>"u"?void 0:(n||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ph(n){return typeof self<"u"&&n===self.ManagedMediaSource}const zi={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Eh(n,e){const t=zi[e];return!!t&&!!t[n.slice(0,4)]}function Ds(n,e,t=!0){return!n.split(",").some(i=>!mo(i,e,t))}function mo(n,e,t=!0){var i;const s=vt(t);return(i=s==null?void 0:s.isTypeSupported(di(n,e)))!=null?i:!1}function di(n,e){return`${e}/mp4;codecs="${n}"`}function Sr(n){if(n){const e=n.substring(0,4);return zi.video[e]}return 2}function Xi(n){return n.split(",").reduce((e,t)=>{const i=zi.video[t];return i?(i*2+e)/(e?3:2):(zi.audio[t]+e)/(e?2:1)},0)}const ks={};function vh(n,e=!0){if(ks[n])return ks[n];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[n];for(let i=0;i<t.length;i++)if(mo(t[i],"audio",e))return ks[n]=t[i],t[i];return n}const xh=/flac|opus/i;function ji(n,e=!0){return n.replace(xh,t=>vh(t.toLowerCase(),e))}function br(n,e){return n&&n!=="mp4a"?n:e&&e.split(",")[0]}function yh(n){const e=n.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");if(i.length>2){let s=i.shift()+".";s+=parseInt(i.shift()).toString(16),s+=("000"+parseInt(i.shift()).toString(16)).slice(-4),e[t]=s}}return e.join(",")}const Lr=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Ar=/#EXT-X-MEDIA:(.*)/g,Th=/^#EXT(?:INF|-X-TARGETDURATION):/m,Cr=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Sh=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class We{static findGroup(e,t){for(let i=0;i<e.length;i++){const s=e[i];if(s.id===t)return s}}static resolve(e,t){return bn.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Th.test(e)}static parseMasterPlaylist(e,t){const i=yr(e),s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},r=[];Lr.lastIndex=0;let a;for(;(a=Lr.exec(e))!=null;)if(a[1]){var o;const c=new ce(a[1]);Ae(s,c,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const u=rn(s,a[2]),h={attrs:c,bitrate:c.decimalInteger("BANDWIDTH")||c.decimalInteger("AVERAGE-BANDWIDTH"),name:c.NAME,url:We.resolve(u,t)},d=c.decimalResolution("RESOLUTION");d&&(h.width=d.width,h.height=d.height),bh(c.CODECS,h),(o=h.unknownCodecs)!=null&&o.length||r.push(h),s.levels.push(h)}else if(a[3]){const c=a[3],u=a[4];switch(c){case"SESSION-DATA":{const h=new ce(u);Ae(s,h,["DATA-ID","LANGUAGE","VALUE","URI"]);const d=h["DATA-ID"];d&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[d]=h);break}case"SESSION-KEY":{const h=Rr(u,t,s);h.encrypted&&h.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(h)):C.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const h=new ce(u);Ae(s,h,["NAME","VALUE","QUERYPARAM"]),Tr(s,h,t)}break}case"CONTENT-STEERING":{const h=new ce(u);Ae(s,h,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:We.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=Ir(u);break}}}const l=r.length>0&&r.length<s.levels.length;return s.levels=l?r:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,i){let s;const r={},a=i.levels,o={AUDIO:a.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:a.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Ar.lastIndex=0;(s=Ar.exec(e))!==null;){const c=new ce(s[1]),u=c.TYPE;if(u){const h=o[u],d=r[u]||[];r[u]=d,Ae(i,c,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const f=c.LANGUAGE,g=c["ASSOC-LANGUAGE"],m=c.CHANNELS,p=c.CHARACTERISTICS,v=c["INSTREAM-ID"],x={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",name:c.NAME||f||"",type:u,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:f,url:c.URI?We.resolve(c.URI,t):""};if(g&&(x.assocLang=g),m&&(x.channels=m),p&&(x.characteristics=p),v&&(x.instreamId=v),h!=null&&h.length){const S=We.findGroup(h,x.groupId)||h[0];wr(x,S,"audioCodec"),wr(x,S,"textCodec")}d.push(x)}}return r}static parseLevelPlaylist(e,t,i,s,r,a){const o=new Nu(t),l=o.fragments;let c=null,u=0,h=0,d=0,f=0,g=null,m=new As(s,t),p,v,x,S=-1,b=!1,T=null;for(Cr.lastIndex=0,o.m3u8=e,o.hasVariableRefs=yr(e);(p=Cr.exec(e))!==null;){b&&(b=!1,m=new As(s,t),m.start=d,m.sn=u,m.cc=f,m.level=i,c&&(m.initSegment=c,m.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null,T&&(m.setByteRange(T),T=null)));const D=p[1];if(D){m.duration=parseFloat(D);const I=(" "+p[2]).slice(1);m.title=I||null,m.tagList.push(I?["INF",D,I]:["INF",D])}else if(p[3]){if(H(m.duration)){m.start=d,x&&_r(m,x,o),m.sn=u,m.level=i,m.cc=f,l.push(m);const I=(" "+p[3]).slice(1);m.relurl=rn(o,I),Dr(m,g),g=m,d+=m.duration,u++,h=0,b=!0}}else if(p[4]){const I=(" "+p[4]).slice(1);g?m.setByteRange(I,g):m.setByteRange(I)}else if(p[5])m.rawProgramDateTime=(" "+p[5]).slice(1),m.tagList.push(["PROGRAM-DATE-TIME",m.rawProgramDateTime]),S===-1&&(S=l.length);else{if(p=p[0].match(Sh),!p){C.warn("No matches on slow regex match for level playlist!");continue}for(v=1;v<p.length&&!(typeof p[v]<"u");v++);const I=(" "+p[v]).slice(1),k=(" "+p[v+1]).slice(1),M=p[v+2]?(" "+p[v+2]).slice(1):"";switch(I){case"PLAYLIST-TYPE":o.type=k.toUpperCase();break;case"MEDIA-SEQUENCE":u=o.startSN=parseInt(k);break;case"SKIP":{const _=new ce(k);Ae(o,_,["RECENTLY-REMOVED-DATERANGES"]);const N=_.decimalInteger("SKIPPED-SEGMENTS");if(H(N)){o.skippedSegments=N;for(let G=N;G--;)l.unshift(null);u+=N}const B=_.enumeratedString("RECENTLY-REMOVED-DATERANGES");B&&(o.recentlyRemovedDateranges=B.split(" "));break}case"TARGETDURATION":o.targetduration=Math.max(parseInt(k),1);break;case"VERSION":o.version=parseInt(k);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":o.live=!1;break;case"#":(k||M)&&m.tagList.push(M?[k,M]:[k]);break;case"DISCONTINUITY":f++,m.tagList.push(["DIS"]);break;case"GAP":m.gap=!0,m.tagList.push([I]);break;case"BITRATE":m.tagList.push([I,k]);break;case"DATERANGE":{const _=new ce(k);Ae(o,_,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),Ae(o,_,_.clientAttrs);const N=new eo(_,o.dateRanges[_.ID]);N.isValid||o.skippedSegments?o.dateRanges[N.id]=N:C.warn(`Ignoring invalid DATERANGE tag: "${k}"`),m.tagList.push(["EXT-X-DATERANGE",k]);break}case"DEFINE":{{const _=new ce(k);Ae(o,_,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in _?mh(o,_,a):Tr(o,_,t)}break}case"DISCONTINUITY-SEQUENCE":f=parseInt(k);break;case"KEY":{const _=Rr(k,t,o);if(_.isSupported()){if(_.method==="NONE"){x=void 0;break}x||(x={}),x[_.keyFormat]&&(x=de({},x)),x[_.keyFormat]=_}else C.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${k}"`);break}case"START":o.startTimeOffset=Ir(k);break;case"MAP":{const _=new ce(k);if(Ae(o,_,["BYTERANGE","URI"]),m.duration){const N=new As(s,t);kr(N,_,i,x),c=N,m.initSegment=c,c.rawProgramDateTime&&!m.rawProgramDateTime&&(m.rawProgramDateTime=c.rawProgramDateTime)}else{const N=m.byteRangeEndOffset;if(N){const B=m.byteRangeStartOffset;T=`${N-B}@${B}`}else T=null;kr(m,_,i,x),c=m,b=!0}break}case"SERVER-CONTROL":{const _=new ce(k);o.canBlockReload=_.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=_.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&_.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=_.optionalFloat("PART-HOLD-BACK",0),o.holdBack=_.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const _=new ce(k);o.partTarget=_.decimalFloatingPoint("PART-TARGET");break}case"PART":{let _=o.partList;_||(_=o.partList=[]);const N=h>0?_[_.length-1]:void 0,B=h++,G=new ce(k);Ae(o,G,["BYTERANGE","URI"]);const X=new Fu(G,m,t,B,N);_.push(X),m.duration+=X.duration;break}case"PRELOAD-HINT":{const _=new ce(k);Ae(o,_,["URI"]),o.preloadHint=_;break}case"RENDITION-REPORT":{const _=new ce(k);Ae(o,_,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(_);break}default:C.warn(`line parsed but not handled: ${p}`);break}}}g&&!g.relurl?(l.pop(),d-=g.duration,o.partList&&(o.fragmentHint=g)):o.partList&&(Dr(m,g),m.cc=f,o.fragmentHint=m,x&&_r(m,x,o));const L=l.length,A=l[0],P=l[L-1];if(d+=o.skippedSegments*o.targetduration,d>0&&L&&P){o.averagetargetduration=d/L;const D=P.sn;o.endSN=D!=="initSegment"?D:0,o.live||(P.endList=!0),A&&(o.startCC=A.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(d+=o.fragmentHint.duration),o.totalduration=d,o.endCC=f,S>0&&Lh(l,S),o}}function Rr(n,e,t){var i,s;const r=new ce(n);Ae(t,r,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=(i=r.METHOD)!=null?i:"",o=r.URI,l=r.hexadecimalInteger("IV"),c=r.KEYFORMATVERSIONS,u=(s=r.KEYFORMAT)!=null?s:"identity";o&&r.IV&&!l&&C.error(`Invalid IV: ${r.IV}`);const h=o?We.resolve(o,e):"",d=(c||"1").split("/").map(Number).filter(Number.isFinite);return new hi(a,h,u,d,l)}function Ir(n){const t=new ce(n).decimalFloatingPoint("TIME-OFFSET");return H(t)?t:null}function bh(n,e){let t=(n||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const s=t.filter(r=>Eh(r,i));s.length&&(e[`${i}Codec`]=s.join(","),t=t.filter(r=>s.indexOf(r)===-1))}),e.unknownCodecs=t}function wr(n,e,t){const i=e[t];i&&(n[t]=i)}function Lh(n,e){let t=n[e];for(let i=e;i--;){const s=n[i];if(!s)return;s.programDateTime=t.programDateTime-s.duration*1e3,t=s}}function Dr(n,e){n.rawProgramDateTime?n.programDateTime=Date.parse(n.rawProgramDateTime):e!=null&&e.programDateTime&&(n.programDateTime=e.endProgramDateTime),H(n.programDateTime)||(n.programDateTime=null,n.rawProgramDateTime=null)}function kr(n,e,t,i){n.relurl=e.URI,e.BYTERANGE&&n.setByteRange(e.BYTERANGE),n.level=t,n.sn="initSegment",i&&(n.levelkeys=i),n.initSegment=null}function _r(n,e,t){n.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(s=>e[s].isCommonEncryption)&&i.push(n)}var ie={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},W={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function Pr(n){const{type:e}=n;switch(e){case ie.AUDIO_TRACK:return W.AUDIO;case ie.SUBTITLE_TRACK:return W.SUBTITLE;default:return W.MAIN}}function _s(n,e){let t=n.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Ah{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,r=i||s,a=new r(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ie.MANIFEST,url:i,deliveryDirectives:null})}onLevelLoading(e,t){const{id:i,level:s,pathwayId:r,url:a,deliveryDirectives:o}=t;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:ie.LEVEL,url:a,deliveryDirectives:o})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:ie.AUDIO_TRACK,url:r,deliveryDirectives:a})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:ie.SUBTITLE_TRACK,url:r,deliveryDirectives:a})}load(e){var t;const i=this.hls.config;let s=this.getInternalLoader(e);if(s){const c=s.context;if(c&&c.url===e.url&&c.level===e.level){C.trace("[playlist-loader]: playlist request ongoing");return}C.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let r;if(e.type===ie.MANIFEST?r=i.manifestLoadPolicy.default:r=de({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),H((t=e.deliveryDirectives)==null?void 0:t.part)){let c;if(e.type===ie.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===ie.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===ie.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const u=c.partTarget,h=c.targetduration;if(u&&h){const d=Math.max(u*3,h*.8)*1e3;r=de({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(c,u,h,d)=>{const f=this.getInternalLoader(h);this.resetInternalLoader(h.type);const g=c.data;if(g.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(c,h,new Error("no EXTM3U delimiter"),d||null,u);return}u.parsing.start=performance.now(),We.isMediaPlaylist(g)?this.handleTrackOrLevelPlaylist(c,u,h,d||null,f):this.handleMasterPlaylist(c,u,h,d)},onError:(c,u,h,d)=>{this.handleNetworkError(u,h,!1,c,d)},onTimeout:(c,u,h)=>{this.handleNetworkError(u,h,!0,void 0,c)}};s.load(e,o,l)}handleMasterPlaylist(e,t,i,s){const r=this.hls,a=e.data,o=_s(e,i),l=We.parseMasterPlaylist(a,o);if(l.playlistParsingError){this.handleManifestParsingError(e,i,l.playlistParsingError,s,t);return}const{contentSteering:c,levels:u,sessionData:h,sessionKeys:d,startTimeOffset:f,variableList:g}=l;this.variableList=g;const{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":v}=We.parseMasterPlaylistMedia(a,o,l);m.length&&!m.some(S=>!S.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(C.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ce({}),bitrate:0,url:""})),r.trigger(E.MANIFEST_LOADED,{levels:u,audioTracks:m,subtitles:p,captions:v,contentSteering:c,url:o,stats:t,networkDetails:s,sessionData:h,sessionKeys:d,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,i,s,r){const a=this.hls,{id:o,level:l,type:c}=i,u=_s(e,i),h=0,d=H(l)?l:H(o)?o:0,f=Pr(i),g=We.parseLevelPlaylist(e.data,u,d,f,h,this.variableList);if(c===ie.MANIFEST){const m={attrs:new ce({}),bitrate:0,details:g,name:"",url:u};a.trigger(E.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:u,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=g,this.handlePlaylistLoaded(g,e,t,i,s,r)}handleManifestParsingError(e,t,i,s,r){this.hls.trigger(E.ERROR,{type:z.NETWORK_ERROR,details:w.MANIFEST_PARSING_ERROR,fatal:t.type===ie.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:r})}handleNetworkError(e,t,i=!1,s,r){let a=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===ie.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===ie.AUDIO_TRACK||e.type===ie.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);C.warn(`[playlist-loader]: ${a}`);let l=w.UNKNOWN,c=!1;const u=this.getInternalLoader(e);switch(e.type){case ie.MANIFEST:l=i?w.MANIFEST_LOAD_TIMEOUT:w.MANIFEST_LOAD_ERROR,c=!0;break;case ie.LEVEL:l=i?w.LEVEL_LOAD_TIMEOUT:w.LEVEL_LOAD_ERROR,c=!1;break;case ie.AUDIO_TRACK:l=i?w.AUDIO_TRACK_LOAD_TIMEOUT:w.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case ie.SUBTITLE_TRACK:l=i?w.SUBTITLE_TRACK_LOAD_TIMEOUT:w.SUBTITLE_LOAD_ERROR,c=!1;break}u&&this.resetInternalLoader(e.type);const h={type:z.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:r};if(s){const d=(t==null?void 0:t.url)||e.url;h.response=Ee({url:d,data:void 0},s)}this.hls.trigger(E.ERROR,h)}handlePlaylistLoaded(e,t,i,s,r,a){const o=this.hls,{type:l,level:c,id:u,groupId:h,deliveryDirectives:d}=s,f=_s(t,s),g=Pr(s),m=typeof s.level=="number"&&g===W.MAIN?c:void 0;if(!e.fragments.length){const v=new Error("No Segments found in Playlist");o.trigger(E.ERROR,{type:z.NETWORK_ERROR,details:w.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:s,level:m,parent:g,networkDetails:r,stats:i});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const p=e.playlistParsingError;if(p){o.trigger(E.ERROR,{type:z.NETWORK_ERROR,details:w.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:s,level:m,parent:g,networkDetails:r,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case ie.MANIFEST:case ie.LEVEL:o.trigger(E.LEVEL_LOADED,{details:e,level:m||0,id:u||0,stats:i,networkDetails:r,deliveryDirectives:d});break;case ie.AUDIO_TRACK:o.trigger(E.AUDIO_TRACK_LOADED,{details:e,id:u||0,groupId:h||"",stats:i,networkDetails:r,deliveryDirectives:d});break;case ie.SUBTITLE_TRACK:o.trigger(E.SUBTITLE_TRACK_LOADED,{details:e,id:u||0,groupId:h||"",stats:i,networkDetails:r,deliveryDirectives:d});break}}}function po(n,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=n,e.dispatchEvent(t)}function Eo(n,e){const t=n.mode;if(t==="disabled"&&(n.mode="hidden"),n.cues&&!n.cues.getCueById(e.id))try{if(n.addCue(e),!n.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){C.debug(`[texttrack-utils]: ${i}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,n.addCue(s)}catch(s){C.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}t==="disabled"&&(n.mode=t)}function Pt(n){const e=n.mode;if(e==="disabled"&&(n.mode="hidden"),n.cues)for(let t=n.cues.length;t--;)n.removeCue(n.cues[t]);e==="disabled"&&(n.mode=e)}function an(n,e,t,i){const s=n.mode;if(s==="disabled"&&(n.mode="hidden"),n.cues&&n.cues.length>0){const r=Rh(n.cues,e,t);for(let a=0;a<r.length;a++)(!i||i(r[a]))&&n.removeCue(r[a])}s==="disabled"&&(n.mode=s)}function Ch(n,e){if(e<n[0].startTime)return 0;const t=n.length-1;if(e>n[t].endTime)return-1;let i=0,s=t;for(;i<=s;){const r=Math.floor((s+i)/2);if(e<n[r].startTime)s=r-1;else if(e>n[r].startTime&&i<t)i=r+1;else return r}return n[i].startTime-e<e-n[s].startTime?i:s}function Rh(n,e,t){const i=[],s=Ch(n,e);if(s>-1)for(let r=s,a=n.length;r<a;r++){const o=n[r];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}function ki(n){const e=[];for(let t=0;t<n.length;t++){const i=n[t];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&e.push(n[t])}return e}var Me={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const Ih=.25;function on(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Or(n,e,t,i,s){let r=new n(e,t,"");try{r.value=i,s&&(r.type=s)}catch{r=new n(e,t,JSON.stringify(s?Ee({type:s},i):i))}return r}const Ti=(()=>{const n=on();try{n&&new n(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Ps(n,e){return n.getTime()/1e3-e}function wh(n){return Uint8Array.from(n.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class Dh{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(Pt(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const i=e[t];if(i.kind==="metadata"&&i.label==="id3")return po(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:s}}}=this;if(!i&&!s)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=on();if(a)for(let o=0;o<r.length;o++){const l=r[o].type;if(l===Me.emsg&&!i||!s)continue;const c=ro(r[o].data);if(c){const u=r[o].pts;let h=u+r[o].duration;h>Ti&&(h=Ti),h-u<=0&&(h=u+Ih);for(let f=0;f<c.length;f++){const g=c[f];if(!no(g)){this.updateId3CueEnds(u,l);const m=Or(a,u,h,g,l);m&&this.id3Track.addCue(m)}}}}}updateId3CueEnds(e,t){var i;const s=(i=this.id3Track)==null?void 0:i.cues;if(s)for(let r=s.length;r--;){const a=s[r];a.type===t&&a.startTime<e&&a.endTime===Ti&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){const{id3Track:r,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(r&&(o||l)){let c;s==="audio"?c=u=>u.type===Me.audioId3&&l:s==="video"?c=u=>u.type===Me.emsg&&o:c=u=>u.type===Me.audioId3&&l||u.type===Me.emsg&&o,an(r,t,i,c)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:s}=this,{dateRanges:r}=t,a=Object.keys(r);if(s){const u=Object.keys(i).filter(h=>!a.includes(h));for(let h=u.length;h--;){const d=u[h];Object.keys(i[d].cues).forEach(f=>{s.removeCue(i[d].cues[f])}),delete i[d]}}const o=t.fragments[t.fragments.length-1];if(a.length===0||!H(o==null?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,c=on();for(let u=0;u<a.length;u++){const h=a[u],d=r[h],f=Ps(d.startDate,l),g=i[h],m=(g==null?void 0:g.cues)||{};let p=(g==null?void 0:g.durationKnown)||!1,v=Ti;const x=d.endDate;if(x)v=Ps(x,l),p=!0;else if(d.endOnNext&&!p){const b=a.reduce((T,L)=>{if(L!==d.id){const A=r[L];if(A.class===d.class&&A.startDate>d.startDate&&(!T||d.startDate<T.startDate))return A}return T},null);b&&(v=Ps(b.startDate,l),p=!0)}const S=Object.keys(d.attr);for(let b=0;b<S.length;b++){const T=S[b];if(!Pu(T))continue;const L=m[T];if(L)p&&!g.durationKnown&&(L.endTime=v);else if(c){let A=d.attr[T];Ou(T)&&(A=wh(A));const P=Or(c,f,v,{key:T,data:A},Me.dateRange);P&&(P.id=h,this.id3Track.addCue(P),m[T]=P)}}i[h]={cues:m,dateRange:d,durationKnown:p}}}}class kh{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(e===null)return null;const{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:r,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let c=o&&i||t;(l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=r!==void 0?r:a*s);const u=s;return c+Math.min(this.stallCount*1,u)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,i=this.levelDetails;if(e===null||t===null||i===null)return null;const s=i.edge,r=e-t-this.edgeStalled,a=s-i.totalduration,o=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,r),o)}get drift(){const{levelDetails:e}=this;return e===null?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(E.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(E.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var i;t.details===w.BUFFER_STALLED_ERROR&&(this.stallCount++,(i=this.levelDetails)!=null&&i.live&&C.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:r}=this.config;if(!s||r===1||!t.live)return;const a=this.targetLatency;if(a===null)return;const o=i-a,l=Math.min(this.maxLatency,a+t.targetduration);if(o<l&&o>.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,r)),h=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(u,Math.max(1,h))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const ln=["NONE","TYPE-0","TYPE-1",null];function _h(n){return ln.indexOf(n)>-1}const Zi=["SDR","PQ","HLG"];function Ph(n){return!!n&&Zi.indexOf(n)>-1}var _i={No:"",Yes:"YES",v2:"v2"};function Fr(n){const{canSkipUntil:e,canSkipDateRanges:t,age:i}=n,s=i<e/2;return e&&s?t?_i.v2:_i.Yes:_i.No}class Mr{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Ut{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Nr(this._audioGroups,e)}hasSubtitleGroup(e){return Nr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Nr(n,e){return!e||!n?!1:n.indexOf(e)!==-1}function Os(n,e){const t=e.startPTS;if(H(t)){let i=0,s;e.sn>n.sn?(i=t-n.start,s=n):(i=n.start-t,s=e),s.duration!==i&&(s.duration=i)}else e.sn>n.sn?n.cc===e.cc&&n.minEndPTS?e.start=n.start+(n.minEndPTS-n.start):e.start=n.start+n.duration:e.start=Math.max(n.start-e.duration,0)}function vo(n,e,t,i,s,r){i-t<=0&&(C.warn("Fragment should have a positive duration",e),i=t+e.duration,r=s+e.duration);let o=t,l=i;const c=e.startPTS,u=e.endPTS;if(H(c)){const p=Math.abs(c-t);H(e.deltaPTS)?e.deltaPTS=Math.max(p,e.deltaPTS):e.deltaPTS=p,o=Math.max(t,c),t=Math.min(t,c),s=Math.min(s,e.startDTS),l=Math.min(i,u),i=Math.max(i,u),r=Math.max(r,e.endDTS)}const h=t-e.start;e.start!==0&&(e.start=t),e.duration=i-e.start,e.startPTS=t,e.maxStartPTS=o,e.startDTS=s,e.endPTS=i,e.minEndPTS=l,e.endDTS=r;const d=e.sn;if(!n||d<n.startSN||d>n.endSN)return 0;let f;const g=d-n.startSN,m=n.fragments;for(m[g]=e,f=g;f>0;f--)Os(m[f],m[f-1]);for(f=g;f<m.length-1;f++)Os(m[f],m[f+1]);return n.fragmentHint&&Os(m[m.length-1],n.fragmentHint),n.PTSKnown=n.alignedSliding=!0,h}function Oh(n,e){let t=null;const i=n.fragments;for(let l=i.length-1;l>=0;l--){const c=i[l].initSegment;if(c){t=c;break}}n.fragmentHint&&delete n.fragmentHint.endPTS;let s=0,r;if(Nh(n,e,(l,c)=>{l.relurl&&(s=l.cc-c.cc),H(l.startPTS)&&H(l.endPTS)&&(c.start=c.startPTS=l.startPTS,c.startDTS=l.startDTS,c.maxStartPTS=l.maxStartPTS,c.endPTS=l.endPTS,c.endDTS=l.endDTS,c.minEndPTS=l.minEndPTS,c.duration=l.endPTS-l.startPTS,c.duration&&(r=c),e.PTSKnown=e.alignedSliding=!0),c.elementaryStreams=l.elementaryStreams,c.loader=l.loader,c.stats=l.stats,l.initSegment&&(c.initSegment=l.initSegment,t=l.initSegment)}),t&&(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(c=>{var u;c&&(!c.initSegment||c.initSegment.relurl===((u=t)==null?void 0:u.relurl))&&(c.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some(l=>!l),e.deltaUpdateFailed){C.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=Fh(n.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(s){C.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l<a.length;l++)a[l].cc+=s}e.skippedSegments&&(e.startCC=e.fragments[0].cc),Mh(n.partList,e.partList,(l,c)=>{c.elementaryStreams=l.elementaryStreams,c.stats=l.stats}),r?vo(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):xo(n,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=n.driftStartTime,e.driftStart=n.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const l=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=l),e.driftEndTime=o,e.driftEnd=l}else e.driftEndTime=n.driftEndTime,e.driftEnd=n.driftEnd,e.advancedDateTime=n.advancedDateTime}function Fh(n,e,t){const i=de({},n);return t&&t.forEach(s=>{delete i[s]}),Object.keys(e).forEach(s=>{const r=new eo(e[s].attr,i[s]);r.isValid?i[s]=r:C.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[s].attr)}"`)}),i}function Mh(n,e,t){if(n&&e){let i=0;for(let s=0,r=n.length;s<=r;s++){const a=n[s],o=e[s+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--}}}function Nh(n,e,t){const i=e.skippedSegments,s=Math.max(n.startSN,e.startSN)-e.startSN,r=(n.fragmentHint?1:0)+(i?e.endSN:Math.min(n.endSN,e.endSN))-e.startSN,a=e.startSN-n.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=n.fragmentHint?n.fragments.concat(n.fragmentHint):n.fragments;for(let c=s;c<=r;c++){const u=l[a+c];let h=o[c];i&&!h&&c<i&&(h=e.fragments[c]=u),u&&h&&t(u,h)}}function xo(n,e){const t=e.startSN+e.skippedSegments-n.startSN,i=n.fragments;t<0||t>=i.length||cn(e,i[t].start)}function cn(n,e){if(e){const t=n.fragments;for(let i=n.skippedSegments;i<t.length;i++)t[i].start+=e;n.fragmentHint&&(n.fragmentHint.start+=e)}}function Bh(n,e=1/0){let t=1e3*n.targetduration;if(n.updated){const i=n.fragments;if(i.length&&t*4>e){const r=i[i.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function Uh(n,e,t){if(!(n!=null&&n.details))return null;const i=n.details;let s=i.fragments[e-i.startSN];return s||(s=i.fragmentHint,s&&s.sn===e)?s:e<i.startSN&&t&&t.sn===e?t:null}function Br(n,e,t){var i;return n!=null&&n.details?yo((i=n.details)==null?void 0:i.partList,e,t):null}function yo(n,e,t){if(n)for(let i=n.length;i--;){const s=n[i];if(s.index===t&&s.fragment.sn===e)return s}return null}function To(n){n.forEach((e,t)=>{const{details:i}=e;i!=null&&i.fragments&&i.fragments.forEach(s=>{s.level=t})})}function Qi(n){switch(n.details){case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_TIMEOUT:case w.LEVEL_LOAD_TIMEOUT:case w.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Ur(n,e){const t=Qi(e);return n.default[`${t?"timeout":"error"}Retry`]}function Rn(n,e){const t=n.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*n.retryDelayMs,n.maxRetryDelayMs)}function $r(n){return Ee(Ee({},n),{errorRetry:null,timeoutRetry:null})}function Ji(n,e,t,i){if(!n)return!1;const s=i==null?void 0:i.code,r=e<n.maxNumRetry&&($h(s)||!!t);return n.shouldRetry?n.shouldRetry(n,e,t,i,r):r}function $h(n){return n===0&&navigator.onLine===!1||!!n&&(n<400||n>499)}const So={search:function(n,e){let t=0,i=n.length-1,s=null,r=null;for(;t<=i;){s=(t+i)/2|0,r=n[s];const a=e(r);if(a>0)t=s+1;else if(a<0)i=s-1;else return r}return null}};function Gh(n,e,t){if(e===null||!Array.isArray(n)||!n.length||!H(e))return null;const i=n[0].programDateTime;if(e<(i||0))return null;const s=n[n.length-1].endProgramDateTime;if(e>=(s||0))return null;t=t||0;for(let r=0;r<n.length;++r){const a=n[r];if(Hh(e,t,a))return a}return null}function es(n,e,t=0,i=0,s=.005){let r=null;if(n){r=e[n.sn-e[0].sn+1]||null;const o=n.endDTS-t;o>0&&o<15e-7&&(t+=15e-7)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!n||n.level===r.level)&&un(t,i,r)===0||Vh(r,n,Math.min(s,i))))return r;const a=So.search(e,un.bind(null,t,i));return a&&(a!==n||!r)?a:r}function Vh(n,e,t){if(e&&e.start===0&&e.level<n.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((s,r)=>(r[0]==="INF"&&(s+=parseFloat(r[1])),s),t);return n.start<=i}return!1}function un(n=0,e=0,t){if(t.start<=n&&t.start+t.duration>n)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=n?1:t.start-i>n&&t.start?-1:0}function Hh(n,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>n}function Kh(n,e){return So.search(n,t=>t.cc<e?1:t.cc>e?-1:0)}var ve={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Oe={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class Wh{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=C.log.bind(C,"[info]:"),this.warn=C.warn.bind(C,"[warning]:"),this.error=C.error.bind(C,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(E.ERROR,this.onError,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(E.ERROR,this.onError,this),e.off(E.ERROR,this.onErrorOut,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===W.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,s;if(t.fatal)return;const r=this.hls,a=t.context;switch(t.details){case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case w.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction={action:ve.DoNothing,flags:Oe.None};return}case w.FRAG_GAP:case w.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ve.SendAlternateToPenaltyBox;return}case w.LEVEL_EMPTY_ERROR:case w.LEVEL_PARSING_ERROR:{var o,l;const c=t.parent===W.MAIN?t.level:r.loadLevel;t.details===w.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(l=o.levelDetails)!=null&&l.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case w.LEVEL_LOAD_ERROR:case w.LEVEL_LOAD_TIMEOUT:typeof(a==null?void 0:a.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a.level));return;case w.AUDIO_TRACK_LOAD_ERROR:case w.AUDIO_TRACK_LOAD_TIMEOUT:case w.SUBTITLE_LOAD_ERROR:case w.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const c=r.levels[r.loadLevel];if(c&&(a.type===ie.AUDIO_TRACK&&c.hasAudioGroup(a.groupId)||a.type===ie.SUBTITLE_TRACK&&c.hasSubtitleGroup(a.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=ve.SendAlternateToPenaltyBox,t.errorAction.flags=Oe.MoveAllAlternatesMatchingHost;return}}return;case w.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const c=r.levels[r.loadLevel],u=c==null?void 0:c.attrs["HDCP-LEVEL"];u?t.errorAction={action:ve.SendAlternateToPenaltyBox,flags:Oe.MoveAllAlternatesMatchingHDCP,hdcpLevel:u}:this.keySystemError(t)}return;case w.BUFFER_ADD_CODEC_ERROR:case w.REMUX_ALLOC_ERROR:case w.BUFFER_APPEND_ERROR:t.errorAction=this.getLevelSwitchAction(t,(s=t.level)!=null?s:r.loadLevel);return;case w.INTERNAL_EXCEPTION:case w.BUFFER_APPENDING_ERROR:case w.BUFFER_FULL_ERROR:case w.LEVEL_SWITCH_ERROR:case w.BUFFER_STALLED_ERROR:case w.BUFFER_SEEK_OVER_HOLE:case w.BUFFER_NUDGE_ON_STALL:t.errorAction={action:ve.DoNothing,flags:Oe.None};return}t.type===z.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,s=Ur(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(Ji(s,r,Qi(e),e.response))return{action:ve.RetryRequest,flags:Oe.None,retryConfig:s,retryCount:r};const o=this.getLevelSwitchAction(e,t);return s&&(o.retryConfig=s,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:a}=t.config,o=Ur(e.details.startsWith("key")?a:r,e),l=t.levels.reduce((u,h)=>u+h.fragmentError,0);if(s&&(e.details!==w.FRAG_GAP&&s.fragmentError++,Ji(o,l,Qi(e),e.response)))return{action:ve.RetryRequest,flags:Oe.None,retryConfig:o,retryCount:l};const c=this.getLevelSwitchAction(e,i);return o&&(c.retryConfig=o,c.retryCount=l),c}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const s=this.hls.levels[t];if(s){var r,a;const c=e.details;s.loadError++,c===w.BUFFER_APPEND_ERROR&&s.fragmentError++;let u=-1;const{levels:h,loadLevel:d,minAutoLevel:f,maxAutoLevel:g}=i;i.autoLevelEnabled||(i.loadLevel=-1);const m=(r=e.frag)==null?void 0:r.type,v=(m===W.AUDIO&&c===w.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(c===w.BUFFER_ADD_CODEC_ERROR||c===w.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:L})=>s.audioCodec!==L),S=e.sourceBufferName==="video"&&(c===w.BUFFER_ADD_CODEC_ERROR||c===w.BUFFER_APPEND_ERROR)&&h.some(({codecSet:L,audioCodec:A})=>s.codecSet!==L&&s.audioCodec===A),{type:b,groupId:T}=(a=e.context)!=null?a:{};for(let L=h.length;L--;){const A=(L+d)%h.length;if(A!==d&&A>=f&&A<=g&&h[A].loadError===0){var o,l;const P=h[A];if(c===w.FRAG_GAP&&m===W.MAIN&&e.frag){const D=h[A].details;if(D){const I=es(e.frag,D.fragments,e.frag.start);if(I!=null&&I.gap)continue}}else{if(b===ie.AUDIO_TRACK&&P.hasAudioGroup(T)||b===ie.SUBTITLE_TRACK&&P.hasSubtitleGroup(T))continue;if(m===W.AUDIO&&(o=s.audioGroups)!=null&&o.some(D=>P.hasAudioGroup(D))||m===W.SUBTITLE&&(l=s.subtitleGroups)!=null&&l.some(D=>P.hasSubtitleGroup(D))||v&&s.audioCodec===P.audioCodec||!v&&s.audioCodec!==P.audioCodec||S&&s.codecSet===P.codecSet)continue}u=A;break}}if(u>-1&&i.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:ve.SendAlternateToPenaltyBox,flags:Oe.None,nextAutoLevel:u}}return{action:ve.SendAlternateToPenaltyBox,flags:Oe.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case ve.DoNothing:break;case ve.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==w.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:s,hdcpLevel:r,nextAutoLevel:a}=i;switch(s){case Oe.None:this.switchLevel(e,a);break;case Oe.MoveAllAlternatesMatchingHDCP:r&&(t.maxHdcpLevel=ln[ln.indexOf(r)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(e,a)}switchLevel(e,t){t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}}class In{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=C.log.bind(C,`${t}:`),this.warn=C.warn.bind(C,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const s=t==null?void 0:t.renditionReports;if(s){let r=-1;for(let a=0;a<s.length;a++){const o=s[a];let l;try{l=new self.URL(o.URI,t.url).href}catch(c){C.warn(`Could not construct new URL for Rendition Report: ${c}`),l=o.URI||""}if(l===e){r=a;break}else l===e.substring(0,l.length)&&(r=a)}if(r!==-1){const a=s[r],o=parseInt(a["LAST-MSN"])||(t==null?void 0:t.lastPartSn);let l=parseInt(a["LAST-PART"])||(t==null?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const u=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&u>t.partTarget&&(l+=1)}const c=i&&Fr(i);return new Mr(o,l>=0?l:void 0,c)}}}loadPlaylist(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,i){const{details:s,stats:r}=t,a=self.performance.now(),o=r.loading.first?Math.max(0,a-r.loading.first):0;if(s.advancedDateTime=Date.now()-o,s.live||i!=null&&i.live){if(s.reloaded(i),i&&this.log(`live playlist ${e} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),i&&s.fragments.length>0&&Oh(i,s),!this.canLoad||!s.live)return;let l,c,u;if(s.canBlockReload&&s.endSN&&s.advanced){const p=this.hls.config.lowLatencyMode,v=s.lastPartSn,x=s.endSN,S=s.lastPartIndex,b=S!==-1,T=v===x,L=p?0:S;b?(c=T?x+1:v,u=T?L:S+1):c=x+1;const A=s.age,P=A+s.ageHeader;let D=Math.min(P-s.partTarget,s.targetduration*1.5);if(D>0){if(i&&D>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${D} with playlist age: ${s.age}`),D=0;else{const I=Math.floor(D/s.targetduration);if(c+=I,u!==void 0){const k=Math.round(D%s.targetduration/s.partTarget);u+=k}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${A.toFixed(2)}s goal: ${D} skip sn ${I} to part ${u}`)}s.tuneInGoal=D}if(l=this.getDeliveryDirectives(s,t.deliveryDirectives,c,u),p||!T){this.loadPlaylist(l);return}}else(s.canBlockReload||s.canSkipUntil)&&(l=this.getDeliveryDirectives(s,t.deliveryDirectives,c,u));const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,f=(s.edge-d)*1e3,g=Bh(s,f);s.updated&&a>this.requestScheduled+g&&(this.requestScheduled=r.loading.start),c!==void 0&&s.canBlockReload?this.requestScheduled=r.loading.first+g-(s.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+g<a?this.requestScheduled=a:this.requestScheduled-a<=0&&(this.requestScheduled+=g);let m=this.requestScheduled-a;m=Math.max(0,m),this.log(`reload live playlist ${e} in ${Math.round(m)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(l),m)}else this.clearTimer()}getDeliveryDirectives(e,t,i,s){let r=Fr(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,r=_i.No),new Mr(i,s,r)}checkRetry(e){const t=e.details,i=Qi(e),s=e.errorAction,{action:r,retryCount:a=0,retryConfig:o}=s||{},l=!!s&&!!o&&(r===ve.RetryRequest||!s.resolved&&r===ve.SendAlternateToPenaltyBox);if(l){var c;if(this.requestScheduled=-1,a>=o.maxNumRetry)return!1;if(i&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const u=Rn(o,a);this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${u}ms`)}e.levelRetry=!0,s.resolved=!0}return l}}class At{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class Yh{constructor(e,t,i,s=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new At(e),this.fast_=new At(t),this.defaultTTFB_=s,this.ttfb_=new At(e)}update(e,t){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new At(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new At(t,s.getEstimate(),s.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new At(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,s=e/1e3,r=i/s;this.fast_.sample(s,r),this.slow_.sample(s,r)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}const bo={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Gr={};function qh(n,e,t,i,s,r){const a=n.audioCodec?n.audioGroups:null,o=r==null?void 0:r.audioCodec,l=r==null?void 0:r.channels,c=l?parseInt(l):o?1/0:2;let u=null;if(a!=null&&a.length)try{a.length===1&&a[0]?u=e.groups[a[0]].channels:u=a.reduce((h,d)=>{if(d){const f=e.groups[d];if(!f)throw new Error(`Audio track group ${d} not found`);Object.keys(f.channels).forEach(g=>{h[g]=(h[g]||0)+f.channels[g]})}return h},{2:0})}catch{return!0}return n.videoCodec!==void 0&&(n.width>1920&&n.height>1088||n.height>1920&&n.width>1088||n.frameRate>Math.max(i,30)||n.videoRange!=="SDR"&&n.videoRange!==t||n.bitrate>Math.max(s,8e6))||!!u&&H(c)&&Object.keys(u).some(h=>parseInt(h)>c)}function zh(n,e,t){const i=n.videoCodec,s=n.audioCodec;if(!i||!s||!t)return Promise.resolve(bo);const r={width:n.width,height:n.height,bitrate:Math.ceil(Math.max(n.bitrate*.9,n.averageBitrate)),framerate:n.frameRate||30},a=n.videoRange;a!=="SDR"&&(r.transferFunction=a.toLowerCase());const o=i.split(",").map(l=>({type:"media-source",video:Ee(Ee({},r),{},{contentType:di(l,"video")})}));return s&&n.audioGroups&&n.audioGroups.forEach(l=>{var c;l&&((c=e.groups[l])==null||c.tracks.forEach(u=>{if(u.groupId===l){const h=u.channels||"",d=parseFloat(h);H(d)&&d>2&&o.push.apply(o,s.split(",").map(f=>({type:"media-source",audio:{contentType:di(f,"audio"),channels:""+d}})))}}))}),Promise.all(o.map(l=>{const c=Xh(l);return Gr[c]||(Gr[c]=t.decodingInfo(l))})).then(l=>({supported:!l.some(c=>!c.supported),configurations:o,decodingInfoResults:l})).catch(l=>({supported:!1,configurations:o,decodingInfoResults:[],error:l}))}function Xh(n){const{audio:e,video:t}=n,i=t||e;if(i){const s=i.contentType.split('"')[1];if(t)return`r${t.height}x${t.width}f${Math.ceil(t.framerate)}${t.transferFunction||"sd"}_${s}_${Math.ceil(t.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${s}`}return""}function jh(){if(typeof matchMedia=="function"){const n=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(n.media!==e.media)return n.matches===!0}return!1}function Zh(n,e){let t=!1,i=[];return n&&(t=n!=="SDR",i=[n]),e&&(i=e.allowedVideoRanges||Zi.slice(0),t=e.preferHDR!==void 0?e.preferHDR:jh(),t?i=i.filter(s=>s!=="SDR"):i=["SDR"]),{preferHDR:t,allowedVideoRanges:i}}function Qh(n,e,t,i,s){const r=Object.keys(n),a=i==null?void 0:i.channels,o=i==null?void 0:i.audioCodec,l=a&&parseInt(a)===2;let c=!0,u=!1,h=1/0,d=1/0,f=1/0,g=0,m=[];const{preferHDR:p,allowedVideoRanges:v}=Zh(e,s);for(let T=r.length;T--;){const L=n[r[T]];c=L.channels[2]>0,h=Math.min(h,L.minHeight),d=Math.min(d,L.minFramerate),f=Math.min(f,L.minBitrate);const A=v.filter(P=>L.videoRanges[P]>0);A.length>0&&(u=!0,m=A)}h=H(h)?h:0,d=H(d)?d:0;const x=Math.max(1080,h),S=Math.max(30,d);return f=H(f)?f:t,t=Math.max(f,t),u||(e=void 0,m=[]),{codecSet:r.reduce((T,L)=>{const A=n[L];if(L===T)return T;if(A.minBitrate>t)return je(L,`min bitrate of ${A.minBitrate} > current estimate of ${t}`),T;if(!A.hasDefaultAudio)return je(L,"no renditions with default or auto-select sound found"),T;if(o&&L.indexOf(o.substring(0,4))%5!==0)return je(L,`audio codec preference "${o}" not found`),T;if(a&&!l){if(!A.channels[a])return je(L,`no renditions with ${a} channel sound found (channels options: ${Object.keys(A.channels)})`),T}else if((!o||l)&&c&&A.channels[2]===0)return je(L,"no renditions with stereo sound found"),T;return A.minHeight>x?(je(L,`min resolution of ${A.minHeight} > maximum of ${x}`),T):A.minFramerate>S?(je(L,`min framerate of ${A.minFramerate} > maximum of ${S}`),T):m.some(P=>A.videoRanges[P]>0)?A.maxScore<g?(je(L,`max score of ${A.maxScore} < selected max of ${g}`),T):T&&(Xi(L)>=Xi(T)||A.fragmentError>n[T].fragmentError)?T:(g=A.maxScore,L):(je(L,`no variants with VIDEO-RANGE of ${JSON.stringify(m)} found`),T)},void 0),videoRanges:m,preferHDR:p,minFramerate:d,minBitrate:f}}function je(n,e){C.log(`[abr] start candidates with "${n}" ignored because ${e}`)}function Jh(n){return n.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const s=t.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function ed(n,e,t,i){return n.slice(t,i+1).reduce((s,r)=>{if(!r.codecSet)return s;const a=r.audioGroups;let o=s[r.codecSet];o||(s[r.codecSet]=o={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!a,fragmentError:0}),o.minBitrate=Math.min(o.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return o.minHeight=Math.min(o.minHeight,l),o.minFramerate=Math.min(o.minFramerate,r.frameRate),o.maxScore=Math.max(o.maxScore,r.score),o.fragmentError+=r.fragmentError,o.videoRanges[r.videoRange]=(o.videoRanges[r.videoRange]||0)+1,a&&a.forEach(c=>{if(!c)return;const u=e.groups[c];u&&(o.hasDefaultAudio=o.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(h=>{o.channels[h]=(o.channels[h]||0)+u.channels[h]}))}),s},{})}function Ye(n,e,t){if("attrs"in n){const i=e.indexOf(n);if(i!==-1)return i}for(let i=0;i<e.length;i++){const s=e[i];if(Ot(n,s,t))return i}return-1}function Ot(n,e,t){const{groupId:i,name:s,lang:r,assocLang:a,characteristics:o,default:l}=n,c=n.forced;return(i===void 0||e.groupId===i)&&(s===void 0||e.name===s)&&(r===void 0||e.lang===r)&&(r===void 0||e.assocLang===a)&&(l===void 0||e.default===l)&&(c===void 0||e.forced===c)&&(o===void 0||td(o,e.characteristics))&&(t===void 0||t(n,e))}function td(n,e=""){const t=n.split(","),i=e.split(",");return t.length===i.length&&!t.some(s=>i.indexOf(s)===-1)}function Ct(n,e){const{audioCodec:t,channels:i}=n;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function id(n,e,t,i,s){const r=e[i],o=e.reduce((d,f,g)=>{const m=f.uri;return(d[m]||(d[m]=[])).push(g),d},{})[r.uri];o.length>1&&(i=Math.max.apply(Math,o));const l=r.videoRange,c=r.frameRate,u=r.codecSet.substring(0,4),h=Vr(e,i,d=>{if(d.videoRange!==l||d.frameRate!==c||d.codecSet.substring(0,4)!==u)return!1;const f=d.audioGroups,g=t.filter(m=>!f||f.indexOf(m.groupId)!==-1);return Ye(n,g,s)>-1});return h>-1?h:Vr(e,i,d=>{const f=d.audioGroups,g=t.filter(m=>!f||f.indexOf(m.groupId)!==-1);return Ye(n,g,s)>-1})}function Vr(n,e,t){for(let i=e;i;i--)if(t(n[i]))return i;for(let i=e+1;i<n.length;i++)if(t(n[i]))return i;return-1}class sd{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:t,partCurrent:i,hls:s}=this,{autoLevelEnabled:r,media:a}=s;if(!t||!a)return;const o=performance.now(),l=i?i.stats:t.stats,c=i?i.duration:t.duration,u=o-l.loading.start,h=s.minAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||t.level<=h){this.clearTimer(),this._nextAutoLevel=-1;return}if(!r||a.paused||!a.playbackRate||!a.readyState)return;const d=s.mainForwardBufferInfo;if(d===null)return;const f=this.bwEstimator.getEstimateTTFB(),g=Math.abs(a.playbackRate);if(u<=Math.max(f,1e3*(c/(g*2))))return;const m=d.len/g,p=l.loading.first?l.loading.first-l.loading.start:-1,v=l.loaded&&p>-1,x=this.getBwEstimate(),S=s.levels,b=S[t.level],T=l.total||Math.max(l.loaded,Math.round(c*b.averageBitrate/8));let L=v?u-p:u;L<1&&v&&(L=Math.min(u,l.loaded*8/x));const A=v?l.loaded*1e3/L:0,P=A?(T-l.loaded)/A:T*8/x+f/1e3;if(P<=m)return;const D=A?A*8:x;let I=Number.POSITIVE_INFINITY,k;for(k=t.level-1;k>h;k--){const _=S[k].maxBitrate;if(I=this.getTimeToLoadFrag(f/1e3,D,c*_,!S[k].details),I<m)break}if(I>=P||I>c*10)return;s.nextLoadLevel=s.nextAutoLevel=k,v?this.bwEstimator.sample(u-Math.min(f,p),l.loaded):this.bwEstimator.sampleTTFB(u);const M=S[k].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>M&&this.resetEstimator(M),this.clearTimer(),C.warn(`[abr] Fragment ${t.sn}${i?" part "+i.index:""} of level ${t.level} is loading too slowly; Time to underbuffer: ${m.toFixed(3)} s Estimated load time for current fragment: ${P.toFixed(3)} s Estimated load time for down switch fragment: ${I.toFixed(3)} s TTFB estimate: ${p|0} ms Current BW estimate: ${H(x)?x|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${k} @ ${M|0} bps`),s.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:i,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(C.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new Yh(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(E.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var s;this.fragCurrent=i,this.partCurrent=(s=t.part)!=null?s:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case w.BUFFER_ADD_CODEC_ERROR:case w.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case w.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:s,partCurrent:r}=this;if(i&&s&&i.sn===s.sn&&i.level===s.level){const a=performance.now(),o=r?r.stats:i.stats,l=a-o.loading.start,c=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&c>-1){const h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(h,c),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,s){const r=e+i/t,a=s?this.lastLevelLoadSec:0;return r+a}onLevelLoaded(e,t){const i=this.hls.config,{loading:s}=t.stats,r=s.end-s.start;H(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}onFragLoaded(e,{frag:t,part:i}){const s=i?i.stats:t.stats;if(t.type===W.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=i?i.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+s.loaded,l=(a.loaded?a.loaded.duration:0)+r;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){const r={stats:s,frag:t,part:i,id:t.type};this.onFragBuffered(E.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:s}=t,r=s!=null&&s.stats.loaded?s.stats:i.stats;if(r.aborted||this.ignoreFragment(i))return;const a=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==W.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,t,e,0,s,1,1);if(r>-1)return r;const a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return C.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,r)&&a[e].loadError<=a[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this,{maxAutoLevel:s,config:r,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let u=r.abrBandWidthFactor,h=r.abrBandWidthUpFactor;if(c){const p=this.findBestLevel(l,a,s,c,0,u,h);if(p>=0)return p}let d=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!c){const p=this.bitrateTestDelay;p&&(d=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-p,C.info(`[abr] bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),u=h=1)}const f=this.findBestLevel(l,a,s,c,d,u,h);if(C.info(`[abr] ${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`),f>-1)return f;const g=i.levels[a],m=i.levels[i.loadLevel];return(g==null?void 0:g.bitrate)<(m==null?void 0:m.bitrate)?a:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,s,r,a,o){var l;const c=s+r,u=this.lastLoadedFragLevel,h=u===-1?this.hls.firstLevel:u,{fragCurrent:d,partCurrent:f}=this,{levels:g,allAudioTracks:m,loadLevel:p,config:v}=this.hls;if(g.length===1)return 0;const x=g[h],S=!!(x!=null&&(l=x.details)!=null&&l.live),b=p===-1||u===-1;let T,L="SDR",A=(x==null?void 0:x.frameRate)||0;const{audioPreference:P,videoPreference:D}=v,I=this.audioTracksByGroup||(this.audioTracksByGroup=Jh(m));if(b){if(this.firstSelection!==-1)return this.firstSelection;const B=this.codecTiers||(this.codecTiers=ed(g,I,t,i)),G=Qh(B,L,e,P,D),{codecSet:X,videoRanges:Q,minFramerate:$,minBitrate:U,preferHDR:ee}=G;T=X,L=ee?Q[Q.length-1]:Q[0],A=$,e=Math.max(e,U),C.log(`[abr] picked start tier ${JSON.stringify(G)}`)}else T=x==null?void 0:x.codecSet,L=x==null?void 0:x.videoRange;const k=f?f.duration:d?d.duration:0,M=this.bwEstimator.getEstimateTTFB()/1e3,_=[];for(let B=i;B>=t;B--){var N;const G=g[B],X=B>h;if(!G)continue;if(v.useMediaCapabilities&&!G.supportedResult&&!G.supportedPromise){const oe=navigator.mediaCapabilities;typeof(oe==null?void 0:oe.decodingInfo)=="function"&&qh(G,I,L,A,e,P)?(G.supportedPromise=zh(G,I,oe),G.supportedPromise.then(ue=>{if(!this.hls)return;G.supportedResult=ue;const he=this.hls.levels,xe=he.indexOf(G);ue.error?C.warn(`[abr] MediaCapabilities decodingInfo error: "${ue.error}" for level ${xe} ${JSON.stringify(ue)}`):ue.supported||(C.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${xe} ${JSON.stringify(ue)}`),xe>-1&&he.length>1&&(C.log(`[abr] Removing unsupported level ${xe}`),this.hls.removeLevel(xe)))})):G.supportedResult=bo}if(T&&G.codecSet!==T||L&&G.videoRange!==L||X&&A>G.frameRate||!X&&A>0&&A<G.frameRate||G.supportedResult&&!((N=G.supportedResult.decodingInfoResults)!=null&&N[0].smooth)){_.push(B);continue}const Q=G.details,$=(f?Q==null?void 0:Q.partTarget:Q==null?void 0:Q.averagetargetduration)||k;let U;X?U=o*e:U=a*e;const ee=k&&s>=k*2&&r===0?g[B].averageBitrate:g[B].maxBitrate,Z=this.getTimeToLoadFrag(M,U,ee*$,Q===void 0);if(U>=ee&&(B===u||G.loadError===0&&G.fragmentError===0)&&(Z<=M||!H(Z)||S&&!this.bitrateTestDelay||Z<c)){const oe=this.forcedAutoLevel;return B!==p&&(oe===-1||oe!==p)&&(_.length&&C.trace(`[abr] Skipped level(s) ${_.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${g[_[0]].codecs}" ${g[_[0]].videoRange}; not compatible with "${x.codecs}" ${L}`),C.info(`[abr] switch candidate:${h}->${B} adjustedbw(${Math.round(U)})-bitrate=${Math.round(U-ee)} ttfb:${M.toFixed(1)} avgDuration:${$.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${Z.toFixed(1)} firstSelection:${b} codecSet:${T} videoRange:${L} hls.loadLevel:${p}`)),b&&(this.firstSelection=B),B}}return-1}set nextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls,s=Math.min(Math.max(e,i),t);this._nextAutoLevel!==s&&(this.nextAutoLevelKey="",this._nextAutoLevel=s)}}class nd{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}var pe={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class rd{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let s=i.length;s--;){const r=i[s];if(!r)break;const a=r.end;if(r.start<=e&&a!==null&&e<=a)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:i}=this,s=Object.keys(i);for(let r=s.length;r--;){const a=i[s[r]];if((a==null?void 0:a.body.type)===t&&a.buffered){const o=a.body;if(o.start<=e&&e<=o.end)return o}}return null}detectEvictedFragments(e,t,i,s){this.timeRanges&&(this.timeRanges[e]=t);const r=(s==null?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o||r>=o.body.sn)return;if(!o.buffered&&!o.loaded){o.body.type===i&&this.removeFragment(o.body);return}const l=o.range[e];l&&l.time.some(c=>{const u=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return u&&this.removeFragment(o.body),u})})}detectPartialFragments(e){const t=this.timeRanges,{frag:i,part:s}=e;if(!t||i.sn==="initSegment")return;const r=Rt(i),a=this.fragments[r];if(!a||a.buffered&&i.gap)return;const o=!i.relurl;Object.keys(t).forEach(l=>{const c=i.elementaryStreams[l];if(!c)return;const u=t[l],h=o||c.partial===!0;a.range[l]=this.getBufferedTimes(i,s,h,u)}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=i.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),Si(a)||this.removeParts(i.sn-1,i.type)):this.removeFragment(a.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=i.filter(s=>s.fragment.sn>=e))}fragBuffered(e,t){const i=Rt(e);let s=this.fragments[i];!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)}getBufferedTimes(e,t,i,s){const r={time:[],partial:i},a=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||a;for(let u=0;u<s.length;u++){const h=s.start(u)-this.bufferPadding,d=s.end(u)+this.bufferPadding;if(c>=h&&l<=d){r.time.push({startPTS:Math.max(a,s.start(u)),endPTS:Math.min(o,s.end(u))});break}else if(a<d&&o>h){const f=Math.max(a,s.start(u)),g=Math.min(o,s.end(u));g>f&&(r.partial=!0,r.time.push({startPTS:f,endPTS:g}))}else if(o<=h)break}return r}getPartialFragment(e){let t=null,i,s,r,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{const u=l[c];u&&Si(u)&&(s=u.body.start-o,r=u.body.end+o,e>=s&&e<=r&&(i=Math.min(e-s,r-e),a<=i&&(t=u.body,a=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Si(t))}getState(e){const t=Rt(e),i=this.fragments[t];return i?i.buffered?Si(i)?pe.PARTIAL:pe.OK:pe.APPENDING:pe.NOT_LOADED}isTimeBuffered(e,t,i){let s,r;for(let a=0;a<i.length;a++){if(s=i.start(a)-this.bufferPadding,r=i.end(a)+this.bufferPadding,e>=s&&t<=r)return!0;if(t<=s)return!1}return!1}onFragLoaded(e,t){const{frag:i,part:s}=t;if(i.sn==="initSegment"||i.bitrateTest)return;const r=s?null:t,a=Rt(i);this.fragments[a]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:s,timeRanges:r}=t;if(i.sn==="initSegment")return;const a=i.type;if(s){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(s)}this.timeRanges=r,Object.keys(r).forEach(o=>{const l=r[o];this.detectEvictedFragments(o,l,a,s)})}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Rt(e);return!!this.fragments[t]}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,s,r){s&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==i||s&&!l.gap||l.start<t&&l.end>e&&(o.buffered||r)&&this.removeFragment(l)})}removeFragment(e){const t=Rt(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const s=e.sn;this.activePartLists[e.type]=i.filter(r=>r.fragment.sn!==s)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function Si(n){var e,t,i;return n.buffered&&(n.body.gap||((e=n.range.video)==null?void 0:e.partial)||((t=n.range.audio)==null?void 0:t.partial)||((i=n.range.audiovideo)==null?void 0:i.partial))}function Rt(n){return`${n.type}_${n.level}_${n.sn}`}const ad={length:0,start:()=>0,end:()=>0};class re{static isBuffered(e,t){try{if(e){const i=re.getBuffered(e);for(let s=0;s<i.length;s++)if(t>=i.start(s)&&t<=i.end(s))return!0}}catch{}return!1}static bufferInfo(e,t,i){try{if(e){const s=re.getBuffered(e),r=[];let a;for(a=0;a<s.length;a++)r.push({start:s.start(a),end:s.end(a)});return this.bufferedInfo(r,t,i)}}catch{}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.sort(function(c,u){const h=c.start-u.start;return h||u.end-c.end});let s=[];if(i)for(let c=0;c<e.length;c++){const u=s.length;if(u){const h=s[u-1].end;e[c].start-h<i?e[c].end>h&&(s[u-1].end=e[c].end):s.push(e[c])}else s.push(e[c])}else s=e;let r=0,a,o=t,l=t;for(let c=0;c<s.length;c++){const u=s[c].start,h=s[c].end;if(t+i>=u&&t<h)o=u,l=h,r=l-t;else if(t+i<u){a=u;break}}return{len:r,start:o||0,end:l||0,nextStart:a}}static getBuffered(e){try{return e.buffered}catch(t){return C.log("failed to get media.buffered",t),ad}}}class wn{constructor(e,t,i,s=0,r=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=bi(),this.buffering={audio:bi(),video:bi(),audiovideo:bi()},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=r,this.partial=a}}function bi(){return{start:0,executeStart:0,executeEnd:0,end:0}}function Pi(n,e){for(let i=0,s=n.length;i<s;i++){var t;if(((t=n[i])==null?void 0:t.cc)===e)return n[i]}return null}function od(n,e,t){return!!(e&&(t.endCC>t.startCC||n&&n.cc<t.startCC))}function ld(n,e){const t=n.fragments,i=e.fragments;if(!i.length||!t.length){C.log("No fragments to align");return}const s=Pi(t,i[0].cc);if(!s||s&&!s.startPTS){C.log("No frag in previous level to align on");return}return s}function Hr(n,e){if(n){const t=n.start+e;n.start=n.startPTS=t,n.endPTS=t+n.duration}}function Lo(n,e){const t=e.fragments;for(let i=0,s=t.length;i<s;i++)Hr(t[i],n);e.fragmentHint&&Hr(e.fragmentHint,n),e.alignedSliding=!0}function cd(n,e,t){e&&(ud(n,t,e),!t.alignedSliding&&e&&ts(t,e),!t.alignedSliding&&e&&!t.skippedSegments&&xo(e,t))}function ud(n,e,t){if(od(n,t,e)){const i=ld(t,e);i&&H(i.start)&&(C.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),Lo(i.start,e))}}function ts(n,e){if(!n.hasProgramDateTime||!e.hasProgramDateTime)return;const t=n.fragments,i=e.fragments;if(!t.length||!i.length)return;let s,r;const a=Math.min(e.endCC,n.endCC);e.startCC<a&&n.startCC<a&&(s=Pi(i,a),r=Pi(t,a)),(!s||!r)&&(s=i[Math.floor(i.length/2)],r=Pi(t,s.cc)||t[Math.floor(t.length/2)]);const o=s.programDateTime,l=r.programDateTime;if(!o||!l)return;const c=(l-o)/1e3-(r.start-s.start);Lo(c,n)}const Kr=Math.pow(2,17);class hd{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new Qe({type:z.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const s=this.config,r=s.fLoader,a=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){l(Yr(e));return}else e.gap=!1;const c=this.loader=e.loader=r?new r(s):new a(s),u=Wr(e),h=$r(s.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Kr};e.stats=c.stats,c.load(u,d,{onSuccess:(f,g,m,p)=>{this.resetLoader(e,c);let v=f.data;m.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),o({frag:e,part:null,payload:v,networkDetails:p})},onError:(f,g,m,p)=>{this.resetLoader(e,c),l(new Qe({type:z.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Ee({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:m,stats:p}))},onAbort:(f,g,m)=>{this.resetLoader(e,c),l(new Qe({type:z.NETWORK_ERROR,details:w.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:m,stats:f}))},onTimeout:(f,g,m)=>{this.resetLoader(e,c),l(new Qe({type:z.NETWORK_ERROR,details:w.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:m,stats:f}))},onProgress:(f,g,m,p)=>{t&&t({frag:e,part:null,payload:m,networkDetails:p})}})})}loadPart(e,t,i){this.abort();const s=this.config,r=s.fLoader,a=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Yr(e,t));return}const c=this.loader=e.loader=r?new r(s):new a(s),u=Wr(e,t),h=$r(s.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Kr};t.stats=c.stats,c.load(u,d,{onSuccess:(f,g,m,p)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:f.data,networkDetails:p};i(v),o(v)},onError:(f,g,m,p)=>{this.resetLoader(e,c),l(new Qe({type:z.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Ee({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:m,stats:p}))},onAbort:(f,g,m)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new Qe({type:z.NETWORK_ERROR,details:w.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:m,stats:f}))},onTimeout:(f,g,m)=>{this.resetLoader(e,c),l(new Qe({type:z.NETWORK_ERROR,details:w.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:m,stats:f}))}})})}updateStatsFromPart(e,t){const i=e.stats,s=t.stats,r=s.total;if(i.loaded+=s.loaded,r){const l=Math.round(e.duration/t.duration),c=Math.min(Math.round(i.loaded/r),l),h=(l-c)*Math.round(i.loaded/c);i.total=i.loaded+h}else i.total=Math.max(i.loaded,i.total);const a=i.loading,o=s.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Wr(n,e=null){const t=e||n,i={frag:n,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},s=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(H(s)&&H(r)){var a;let o=s,l=r;if(n.sn==="initSegment"&&((a=n.decryptdata)==null?void 0:a.method)==="AES-128"){const c=r-s;c%16&&(l=r+(16-c%16)),s!==0&&(i.resetIV=!0,o=s-16)}i.rangeStart=o,i.rangeEnd=l}return i}function Yr(n,e){const t=new Error(`GAP ${n.gap?"tag":"attribute"} found`),i={type:z.MEDIA_ERROR,details:w.FRAG_GAP,fatal:!1,frag:n,error:t,networkDetails:null};return e&&(i.part=e),(e||n).stats.aborted=!0,new Qe(i)}class Qe extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class dd{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class fd{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function gd(n){const e=n.byteLength,t=e&&new DataView(n.buffer).getUint8(e-1);return t?Et(n,0,e-t):n}class md{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=t.getUint32(s*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],r=i[1],a=i[2],o=i[3],l=this.invSubMix,c=l[0],u=l[1],h=l[2],d=l[3],f=new Uint32Array(256);let g=0,m=0,p=0;for(p=0;p<256;p++)p<128?f[p]=p<<1:f[p]=p<<1^283;for(p=0;p<256;p++){let v=m^m<<1^m<<2^m<<3^m<<4;v=v>>>8^v&255^99,e[g]=v,t[v]=g;const x=f[g],S=f[x],b=f[S];let T=f[v]*257^v*16843008;s[g]=T<<24|T>>>8,r[g]=T<<16|T>>>16,a[g]=T<<8|T>>>24,o[g]=T,T=b*16843009^S*65537^x*257^g*16843008,c[v]=T<<24|T>>>8,u[v]=T<<16|T>>>16,h[v]=T<<8|T>>>24,d[v]=T,g?(g=x^f[f[f[b^x]]],m^=f[f[m]]):g=m=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,s=0;for(;s<t.length&&i;)i=t[s]===this.key[s],s++;if(i)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const a=this.ksRows=(r+6+1)*4;let o,l;const c=this.keySchedule=new Uint32Array(a),u=this.invKeySchedule=new Uint32Array(a),h=this.sBox,d=this.rcon,f=this.invSubMix,g=f[0],m=f[1],p=f[2],v=f[3];let x,S;for(o=0;o<a;o++){if(o<r){x=c[o]=t[o];continue}S=x,o%r===0?(S=S<<8|S>>>24,S=h[S>>>24]<<24|h[S>>>16&255]<<16|h[S>>>8&255]<<8|h[S&255],S^=d[o/r|0]<<24):r>6&&o%r===4&&(S=h[S>>>24]<<24|h[S>>>16&255]<<16|h[S>>>8&255]<<8|h[S&255]),c[o]=x=(c[o-r]^S)>>>0}for(l=0;l<a;l++)o=a-l,l&3?S=c[o]:S=c[o-4],l<4||o<=4?u[l]=S:u[l]=g[h[S>>>24]]^m[h[S>>>16&255]]^p[h[S>>>8&255]]^v[h[S&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const s=this.keySize+6,r=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],c=o[1],u=o[2],h=o[3],d=this.uint8ArrayToUint32Array_(i);let f=d[0],g=d[1],m=d[2],p=d[3];const v=new Int32Array(e),x=new Int32Array(v.length);let S,b,T,L,A,P,D,I,k,M,_,N,B,G;const X=this.networkToHostOrderSwap;for(;t<v.length;){for(k=X(v[t]),M=X(v[t+1]),_=X(v[t+2]),N=X(v[t+3]),A=k^r[0],P=N^r[1],D=_^r[2],I=M^r[3],B=4,G=1;G<s;G++)S=l[A>>>24]^c[P>>16&255]^u[D>>8&255]^h[I&255]^r[B],b=l[P>>>24]^c[D>>16&255]^u[I>>8&255]^h[A&255]^r[B+1],T=l[D>>>24]^c[I>>16&255]^u[A>>8&255]^h[P&255]^r[B+2],L=l[I>>>24]^c[A>>16&255]^u[P>>8&255]^h[D&255]^r[B+3],A=S,P=b,D=T,I=L,B=B+4;S=a[A>>>24]<<24^a[P>>16&255]<<16^a[D>>8&255]<<8^a[I&255]^r[B],b=a[P>>>24]<<24^a[D>>16&255]<<16^a[I>>8&255]<<8^a[A&255]^r[B+1],T=a[D>>>24]<<24^a[I>>16&255]<<16^a[A>>8&255]<<8^a[P&255]^r[B+2],L=a[I>>>24]<<24^a[A>>16&255]<<16^a[P>>8&255]<<8^a[D&255]^r[B+3],x[t]=X(S^f),x[t+1]=X(L^g),x[t+2]=X(T^m),x[t+3]=X(b^p),f=k,g=M,m=_,p=N,t=t+4}return x.buffer}}const pd=16;class Dn{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?gd(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i){return this.useSoftware?new Promise((s,r)=>{this.softwareDecrypt(new Uint8Array(e),t,i);const a=this.flush();a?s(a.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i)}softwareDecrypt(e,t,i){const{currentIV:s,currentResult:r,remainderData:a}=this;this.logOnce("JS AES decrypt"),a&&(e=Pe(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;s&&(i=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new md),l.expandKey(t);const c=r;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=Et(o,-16).buffer,c||null}webCryptoDecrypt(e,t,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i));this.key=t,this.fastAesKey=new fd(this.subtle,t)}return this.fastAesKey.expandKey().then(s=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new dd(this.subtle,new Uint8Array(i)).decrypt(e.buffer,s)):Promise.reject(new Error("web crypto not initialized"))).catch(s=>(C.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(e,t,i)))}onWebCryptoError(e,t,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i);const s=this.flush();if(s)return s.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%pd;return i!==e.length&&(t=Et(e,0,i),this.remainderData=Et(e,i)),t}logOnce(e){this.logEnabled&&(C.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Ed={toString:function(n){let e="";const t=n.length;for(let i=0;i<t;i++)e+=`[${n.start(i).toFixed(3)}-${n.end(i).toFixed(3)}]`;return e}},F={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class kn extends nd{constructor(e,t,i,s,r){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=F.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=r,this.logPrefix=s,this.log=C.log.bind(C,`${s}:`),this.warn=C.warn.bind(C,`${s}:`),this.hls=e,this.fragmentLoader=new hd(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Dn(e.config),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=F.STOPPED}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;const i=t.partList;if(i!=null&&i.length){const r=i[i.length-1];return re.isBuffered(this.media,r.start+r.duration/2)}const s=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(s)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levelLastLoaded)==null?void 0:e.details}}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),i.addEventListener("seeking",this.onvseeking),i.addEventListener("ended",this.onvended);const s=this.config;this.levels&&s.autoStartLoad&&this.state===F.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(){const e=this.media;e!=null&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:t,media:i,mediaBuffer:s,state:r}=this,a=i?i.currentTime:0,o=re.bufferInfo(s||i,a,e.maxBufferHole);if(this.log(`media seeking to ${H(a)?a.toFixed(3):a}, state: ${r}`),this.state===F.ENDED)this.resetLoadingState();else if(t){const l=e.maxFragLookUpTolerance,c=t.start-l,u=t.start+t.duration+l;if(!o.len||u<o.start||c>o.end){const h=a>u;(a<c||h)&&(h&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}i&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),this.lastCurrentTime=a),!this.loadedmetadata&&!o.len&&(this.nextLoadPosition=this.startPosition=a),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=F.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const s=r=>{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${r.part?" p: "+r.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,s).then(r=>{if(!r)return;const a=this.state;if(this.fragContextChanged(e)){(a===F.FRAG_LOADING||!this.fragCurrent&&a===F.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=F.IDLE);return}"payload"in r&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(E.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===F.STOPPED||this.state===F.ERROR||(this.warn(`Frag error: ${(r==null?void 0:r.message)||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===pe.APPENDING){const r=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===pe.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const s={startOffset:e,endOffset:t,type:i};this.hls.trigger(E.BUFFER_FLUSHING,s)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{if(!i||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:s}=this,{payload:r}=i,a=e.decryptdata;if(r&&r.byteLength>0&&a!=null&&a.key&&a.iv&&a.method==="AES-128"){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer).catch(l=>{throw s.trigger(E.ERROR,{type:z.MEDIA_ERROR,details:w.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:e}),l}).then(l=>{const c=self.performance.now();return s.trigger(E.FRAG_DECRYPTED,{frag:e,payload:l,stats:{tstart:o,tdecrypt:c}}),i.payload=l,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===F.STOPPED||this.state===F.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state=F.IDLE,e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){var i,s,r,a;const o=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===W.MAIN?"level":"track"} ${e.level} (frag:[${((i=e.startPTS)!=null?i:NaN).toFixed(3)}-${((s=e.endPTS)!=null?s:NaN).toFixed(3)}] > buffer:${o?Ed.toString(re.getBuffered(o)):"(detached)"})`),e.sn!=="initSegment"){var l;if(e.type!==W.SUBTITLE){const u=e.elementaryStreams;if(!Object.keys(u).some(h=>!!u[h])){this.state=F.IDLE;return}}const c=(l=this.levels)==null?void 0:l[e.level];c!=null&&c.fragmentError&&(this.log(`Resetting level fragment error count of ${c.fragmentError} on frag buffered`),c.fragmentError=0)}this.state=F.IDLE,o&&(!this.loadedmetadata&&e.type==W.MAIN&&o.buffered.length&&((r=this.fragCurrent)==null?void 0:r.sn)===((a=this.fragPrevious)==null?void 0:a.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:s,partsLoaded:r}=e,a=!r||r.length===0||r.some(l=>!l),o=new wn(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,s){var r;const a=t==null?void 0:t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)?(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${e.level}`),this.state=F.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(u=>{if(!this.fragContextChanged(u.frag))return this.hls.trigger(E.KEY_LOADED,u),this.state===F.KEY_LOADING&&(this.state=F.IDLE),u}),this.hls.trigger(E.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(e,a.encryptedFragments),i=Math.max(e.start,i||0),this.config.lowLatencyMode&&e.sn!=="initSegment"){const u=a.partList;if(u&&s){i>e.end&&a.fragmentHint&&(e=a.fragmentHint);const h=this.getNextPart(u,e,i);if(h>-1){const d=u[h];this.log(`Loading part sn: ${e.sn} p: ${d.index} cc: ${e.cc} of playlist [${a.startSN}-${a.endSN}] parts [0-${h}-${u.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=d.start+d.duration,this.state=F.FRAG_LOADING;let f;return o?f=o.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,d,t,s)).catch(g=>this.handleFragLoadError(g)):f=this.doFragPartsLoad(e,d,t,s).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(E.FRAG_LOADING,{frag:e,part:d,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!e.url||this.loadedEndOfParts(u,i))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${a?"of ["+a.startSN+"-"+a.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),H(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=F.FRAG_LOADING;const l=this.config.progressive;let c;return l&&o?c=o.then(u=>!u||this.fragContextChanged(u==null?void 0:u.frag)?null:this.fragmentLoader.load(e,s)).catch(u=>this.handleFragLoadError(u)):c=Promise.all([this.fragmentLoader.load(e,l?s:void 0),o]).then(([u])=>(!l&&u&&s&&s(u),u)).catch(u=>this.handleFragLoadError(u)),this.hls.trigger(E.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,i,s){return new Promise((r,a)=>{var o;const l=[],c=(o=i.details)==null?void 0:o.partList,u=h=>{this.fragmentLoader.loadPart(e,h,s).then(d=>{l[h.index]=d;const f=d.part;this.hls.trigger(E.FRAG_LOADED,d);const g=Br(i,e.sn,h.index+1)||yo(c,e.sn,h.index+1);if(g)u(g);else return r({frag:e,part:f,partsLoaded:l})}).catch(a)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===w.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(E.ERROR,t)}else this.hls.trigger(E.ERROR,{type:z.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==F.PARSING){!this.fragCurrent&&this.state!==F.STOPPED&&this.state!==F.ERROR&&(this.state=F.IDLE);return}const{frag:i,part:s,level:r}=t,a=self.performance.now();i.stats.parsing.end=a,s&&(s.stats.parsing.end=a),this.updateLevelTiming(i,s,r,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:s,sn:r,part:a}=e;if(!(t!=null&&t[s]))return this.warn(`Levels object was unset while buffering fragment ${r} of level ${s}. The current chunk will not be buffered.`),null;const o=t[s],l=a>-1?Br(o,r,a):null,c=l?l.fragment:Uh(o,r,i);return c?(i&&i!==c&&(c.stats=i.stats),{frag:c,part:l,level:o}):null}bufferFragmentData(e,t,i,s,r){var a;if(!e||this.state!==F.PARSING)return;const{data1:o,data2:l}=e;let c=o;if(o&&l&&(c=Pe(o,l)),!((a=c)!=null&&a.length))return;const u={type:e.type,frag:t,part:i,chunkMeta:s,parent:t.type,data:c};if(this.hls.trigger(E.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!re.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,s=re.bufferInfo(t,i,0),r=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-a,s.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){const i=this.getLoadPosition();return H(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){const{config:{maxBufferHole:s}}=this,r=re.bufferInfo(e,t,s);if(r.len===0&&r.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&r.nextStart<a.end)return re.bufferInfo(e,t,Math.max(r.nextStart,s))}return r}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t),r=Math.max(e-t*3,i.maxMaxBufferLength/2,s);return r>=s?(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=W.MAIN){const i=this.fragmentTracker.getAppendedFrag(e,W.MAIN);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,s=i.length;if(!s)return null;const{config:r}=this,a=i[0].start;let o;if(t.live){const l=r.initialLiveManifestSize;if(s<l)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${l})`),null;(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a)&&(o=this.getInitialLiveFragment(t,i),this.startPosition=this.nextLoadPosition=o?this.hls.liveSyncPosition||o.start:e)}else e<=a&&(o=i[0]);if(!o){const l=r.lowLatencyMode?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,l,t)}return this.mapToInitFragWhenRequired(o)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===pe.OK||i===pe.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,s,r){const a=e.gap,o=this.getNextFragment(this.nextLoadPosition,t);if(o===null)return o;if(e=o,a&&e&&!e.gap&&i.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s);if(l!==null&&i.len+l.len>=r)return this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let s=-1,r=!1,a=!0;for(let o=0,l=e.length;o<l;o++){const c=e[o];if(a=a&&!c.independent,s>-1&&i<c.start)break;const u=c.loaded;u?s=-1:(r||c.independent||a)&&c.fragment===t&&(s=o),r=u}return s}loadedEndOfParts(e,t){const i=e[e.length-1];return i&&t>i.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let s=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=Gh(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const a=t[r-e.startSN];i.cc===a.cc&&(s=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=Kh(t,i.cc),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(s=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){const{config:s}=this;let{fragPrevious:r}=this,{fragments:a,endSN:o}=i;const{fragmentHint:l}=i,{maxFragLookUpTolerance:c}=s,u=i.partList,h=!!(s.lowLatencyMode&&u!=null&&u.length&&l);h&&l&&!this.bitrateTest&&(a=a.concat(l),o=l.sn);let d;if(e<t){const f=e>t-c?0:c;d=es(r,a,e,f)}else d=a[a.length-1];if(d){const f=d.sn-i.startSN,g=this.fragmentTracker.getState(d);if((g===pe.OK||g===pe.PARTIAL&&d.gap)&&(r=d),r&&d.sn===r.sn&&(!h||u[0].fragment.sn>d.sn)&&r&&d.level===r.level){const p=a[f+1];d.sn<o&&this.fragmentTracker.getState(p)!==pe.OK?d=p:d=null}}return d}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=i.currentTime,a=e.fragments[0].start,o=e.edge,l=r>=a-t.maxFragLookUpTolerance&&r<=o;if(s!==null&&i.duration>s&&(r<s||!l)){const c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!l&&i.readyState<4||r<o-c)&&(this.loadedmetadata||(this.nextLoadPosition=s),i.readyState&&(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s.toFixed(3)}`),i.currentTime=s))}}alignPlaylists(e,t,i){const s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const r=e.fragments[0].start,a=!t,o=e.alignedSliding&&H(r);if(a||!o&&!r){const{fragPrevious:l}=this;cd(l,i,e);const c=e.fragments[0].start;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${l?l.sn:"na"} fragments: ${s}`),c}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;if(i<t&&(i=-1),i===-1||this.lastCurrentTime===-1){const s=this.startTimeOffset!==null,r=s?this.startTimeOffset:e.startTimeOffset;r!==null&&H(r)?(i=t+r,r<0&&(i+=e.totalduration),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Start time offset ${r} found in ${s?"multivariant":"media"} playlist, adjust startPosition to ${i}`),this.startPosition=i):e.live?i=this.hls.liveSyncPosition||t:this.startPosition=i=0,this.lastCurrentTime=i}this.nextLoadPosition=i}getLoadPosition(){const{media:e}=this;let t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&e.sn!=="initSegment"&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==F.FRAG_LOADING_WAITING_RETRY)&&(this.state=F.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const u=this.getCurrentContext(t.chunkMeta);u&&(t.frag=u.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var s;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(s=this.fragCurrent)==null?void 0:s.url}`);return}const r=t.details===w.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(i,!0);const a=t.errorAction,{action:o,retryCount:l=0,retryConfig:c}=a||{};if(a&&o===ve.RetryRequest&&c){this.resetStartWhenNotLoaded(this.levelLastLoaded);const u=Rn(c,l);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${l+1}/${c.maxNumRetry} in ${u}ms`),a.resolved=!0,this.retryDate=self.performance.now()+u,this.state=F.FRAG_LOADING_WAITING_RETRY}else if(c&&a)if(this.resetFragmentErrors(e),l<c.maxNumRetry)!r&&o!==ve.RemoveAlternatePermanently&&(a.resolved=!0);else{C.warn(`${t.details} reached or exceeded max retry (${l})`);return}else(a==null?void 0:a.action)===ve.SendAlternateToPenaltyBox?this.state=F.WAITING_LEVEL:this.state=F.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===F.PARSING||this.state===F.PARSED){const t=e.frag,i=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len,(t==null?void 0:t.duration)||10);const a=!r;return a&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===W.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==F.STOPPED&&(this.state=F.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const s=re.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,i),this.state===F.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=F.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=e?e.details:null;t!=null&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){var r;const a=i.details;if(!a){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,c)=>{const u=e.elementaryStreams[c];if(u){const h=u.endPTS-u.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${h})`),l||!1;const d=s?0:vo(a,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS);return this.hls.trigger(E.LEVEL_PTS_UPDATED,{details:a,level:i,drift:d,type:c,frag:e,start:u.startPTS,end:u.endPTS}),!0}return l},!1)&&((r=this.transmuxer)==null?void 0:r.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(i.fragmentError===0&&(i.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(l.message),this.hls.trigger(E.ERROR,{type:z.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=F.PARSED,this.hls.trigger(E.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}class Ao{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=vd(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function vd(n,e){const t=new Uint8Array(e);let i=0;for(let s=0;s<n.length;s++){const r=n[s];t.set(r,i),i+=r.length}return t}function xd(){return typeof __HLS_WORKER_BUNDLE__=="function"}function yd(){const n=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(n);return{worker:new self.Worker(e),objectURL:e}}function Td(n){const e=new self.URL(n,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}function Ke(n="",e=9e4){return{type:n,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class _n{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=Pe(this.cachedData,e),this.cachedData=null);let i=ui(e,0),s=i?i.length:0,r;const a=this._audioTrack,o=this._id3Track,l=i?Cn(i):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&H(l))&&(this.basePTS=Sd(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Me.audioId3,duration:Number.POSITIVE_INFINITY});s<c;){if(this.canParse(e,s)){const u=this.appendFrame(a,e,s);u?(this.frameIndex++,this.lastPTS=u.sample.pts,s+=u.length,r=s):s=c}else Hu(e,s)?(i=ui(e,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Me.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,r=s):s++;if(s===c&&r!==c){const u=Et(e,r);this.cachedData?this.cachedData=Pe(this.cachedData,u):this.cachedData=u}}return{audioTrack:a,videoTrack:Ke(),id3Track:o,textTrack:Ke()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Ke(),id3Track:this._id3Track,textTrack:Ke()}}destroy(){}}const Sd=(n,e,t)=>{if(H(n))return n*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};function bd(n,e,t,i){let s,r,a,o;const l=navigator.userAgent.toLowerCase(),c=i,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=((e[t+2]&192)>>>6)+1;const h=(e[t+2]&60)>>>2;if(h>u.length-1){const d=new Error(`invalid ADTS sampling index:${h}`);n.emit(E.ERROR,E.ERROR,{type:z.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!0,error:d,reason:d.message});return}return a=(e[t+2]&1)<<2,a|=(e[t+3]&192)>>>6,C.log(`manifest codec:${i}, ADTS type:${s}, samplingIndex:${h}`),/firefox/i.test(l)?h>=6?(s=5,o=new Array(4),r=h-3):(s=2,o=new Array(2),r=h):l.indexOf("android")!==-1?(s=2,o=new Array(2),r=h):(s=5,o=new Array(4),i&&(i.indexOf("mp4a.40.29")!==-1||i.indexOf("mp4a.40.5")!==-1)||!i&&h>=6?r=h-3:((i&&i.indexOf("mp4a.40.2")!==-1&&(h>=6&&a===1||/vivaldi/i.test(l))||!i&&a===1)&&(s=2,o=new Array(2)),r=h)),o[0]=s<<3,o[0]|=(h&14)>>1,o[1]|=(h&1)<<7,o[1]|=a<<3,s===5&&(o[1]|=(r&14)>>1,o[2]=(r&1)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:u[h],channelCount:a,codec:"mp4a.40."+s,manifestCodec:c}}function Co(n,e){return n[e]===255&&(n[e+1]&246)===240}function Ro(n,e){return n[e+1]&1?7:9}function Pn(n,e){return(n[e+3]&3)<<11|n[e+4]<<3|(n[e+5]&224)>>>5}function Ld(n,e){return e+5<n.length}function is(n,e){return e+1<n.length&&Co(n,e)}function Ad(n,e){return Ld(n,e)&&Co(n,e)&&Pn(n,e)<=n.length-e}function Cd(n,e){if(is(n,e)){const t=Ro(n,e);if(e+t>=n.length)return!1;const i=Pn(n,e);if(i<=t)return!1;const s=e+i;return s===n.length||is(n,s)}return!1}function Io(n,e,t,i,s){if(!n.samplerate){const r=bd(e,t,i,s);if(!r)return;n.config=r.config,n.samplerate=r.samplerate,n.channelCount=r.channelCount,n.codec=r.codec,n.manifestCodec=r.manifestCodec,C.log(`parsed codec:${n.codec}, rate:${r.samplerate}, channels:${r.channelCount}`)}}function wo(n){return 1024*9e4/n}function Rd(n,e){const t=Ro(n,e);if(e+t<=n.length){const i=Pn(n,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function Do(n,e,t,i,s){const r=wo(n.samplerate),a=i+s*r,o=Rd(e,t);let l;if(o){const{frameLength:h,headerLength:d}=o,f=d+h,g=Math.max(0,t+f-e.length);g?(l=new Uint8Array(f-d),l.set(e.subarray(t+d,e.length),0)):l=e.subarray(t+d,t+f);const m={unit:l,pts:a};return g||n.samples.push(m),{sample:m,length:f,missing:g}}const c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:c,missing:-1}}let Li=null;const Id=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],wd=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Dd=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],kd=[0,1,1,4];function ko(n,e,t,i,s){if(t+24>e.length)return;const r=_o(e,t);if(r&&t+r.frameLength<=e.length){const a=r.samplesPerFrame*9e4/r.sampleRate,o=i+s*a,l={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return n.config=[],n.channelCount=r.channelCount,n.samplerate=r.sampleRate,n.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function _o(n,e){const t=n[e+1]>>3&3,i=n[e+1]>>1&3,s=n[e+2]>>4&15,r=n[e+2]>>2&3;if(t!==1&&s!==0&&s!==15&&r!==3){const a=n[e+2]>>1&1,o=n[e+3]>>6,l=t===3?3-i:i===3?3:4,c=Id[l*14+s-1]*1e3,h=wd[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,f=Dd[t][i],g=kd[i],m=f*8*g,p=Math.floor(f*c/h+a)*g;if(Li===null){const S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Li=S?parseInt(S[1]):0}return!!Li&&Li<=87&&i===2&&c>=224e3&&o===0&&(n[e+3]=n[e+3]|128),{sampleRate:h,channelCount:d,frameLength:p,samplesPerFrame:m}}}function On(n,e){return n[e]===255&&(n[e+1]&224)===224&&(n[e+1]&6)!==0}function Po(n,e){return e+1<n.length&&On(n,e)}function _d(n,e){return On(n,e)&&4<=n.length-e}function Oo(n,e){if(e+1<n.length&&On(n,e)){const i=_o(n,e);let s=4;i!=null&&i.frameLength&&(s=i.frameLength);const r=e+s;return r===n.length||Po(n,r)}return!1}class Pd extends _n{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=ui(e,0);let i=(t==null?void 0:t.length)||0;if(Oo(e,i))return!1;for(let s=e.length;i<s;i++)if(Cd(e,i))return C.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Ad(e,t)}appendFrame(e,t,i){Io(e,this.observer,t,i,e.manifestCodec);const s=Do(e,t,i,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}}const Od=/\/emsg[-/]ID3/i;class Fd{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,s){const r=this.videoTrack=Ke("video",1),a=this.audioTrack=Ke("audio",1),o=this.txtTrack=Ke("text",1);if(this.id3Track=Ke("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=co(e);if(l.video){const{id:c,timescale:u,codec:h}=l.video;r.id=c,r.timescale=o.timescale=u,r.codec=h}if(l.audio){const{id:c,timescale:u,codec:h}=l.audio;a.id=c,a.timescale=u,a.codec=h}o.id=ao.text,r.sampleDuration=0,r.duration=a.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return Qu(e)}demux(e,t){this.timeOffset=t;let i=e;const s=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Pe(this.remainderData,e));const o=ah(i);this.remainderData=o.remainder,s.samples=o.valid||new Uint8Array}else s.samples=i;const a=this.extractID3Track(s,t);return r.samples=xr(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(t,this.timeOffset);return i.samples=xr(e,t),{videoTrack:t,audioTrack:Ke(),id3Track:s,textTrack:Ke()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const s=j(e.samples,["emsg"]);s&&s.forEach(r=>{const a=ch(r);if(Od.test(a.schemeIdUri)){const o=H(a.presentationTime)?a.presentationTime/a.timeScale:t+a.presentationTimeDelta/a.timeScale;let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=a.payload;i.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:Me.emsg,duration:l})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}const Fo=(n,e)=>{let t=0,i=5;e+=i;const s=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=n[e];const o=Math.min(i,8),l=8-o;r[0]=4278190080>>>24+l<<l,s[0]=(a[0]&r[0])>>l,t=t?t<<o|s[0]:s[0],e+=1,i-=o}return t};class Md extends _n{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const s=Mo(e,t,i,this.basePTS,this.frameIndex);if(s!==-1)return{sample:e.samples[e.samples.length-1],length:s,missing:0}}static probe(e){if(!e)return!1;const t=ui(e,0);if(!t)return!1;const i=t.length;return e[i]===11&&e[i+1]===119&&Cn(t)!==void 0&&Fo(e,i)<16}}function Mo(n,e,t,i,s){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],l=e[t+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+r]*2;if(t+u>e.length)return-1;const h=e[t+6]>>5;let d=0;h===2?d+=2:(h&1&&h!==1&&(d+=2),h&4&&(d+=2));const f=(e[t+6]<<8|e[t+7])>>12-d&1,m=[2,1,2,3,3,4,4,5][h]+f,p=e[t+5]>>3,v=e[t+5]&7,x=new Uint8Array([r<<6|p<<1|v>>2,(v&3)<<6|h<<3|f<<2|l>>4,l<<4&224]),S=1536/o*9e4,b=i+s*S,T=e.subarray(t,t+u);return n.config=x,n.channelCount=m,n.samplerate=o,n.samples.push({unit:T,pts:b}),u}class Nd{constructor(){this.VideoSample=null}createVideoSample(e,t,i,s){return{key:e,frame:!1,pts:t,dts:i,units:[],debug:s,length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,s;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const r=i.units;s=r[r.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,s=i.length;if(s){const r=i[s-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}e.debug.length&&C.log(e.pts+"/"+e.dts+":"+e.debug)}}class qr{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,s=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");s.set(e.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&C.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t=8,i=8,s;for(let r=0;r<e;r++)i!==0&&(s=this.readEG(),i=(t+s+256)%256),t=i===0?t:i}readSPS(){let e=0,t=0,i=0,s=0,r,a,o;const l=this.readUByte.bind(this),c=this.readBits.bind(this),u=this.readUEG.bind(this),h=this.readBoolean.bind(this),d=this.skipBits.bind(this),f=this.skipEG.bind(this),g=this.skipUEG.bind(this),m=this.skipScalingList.bind(this);l();const p=l();if(c(5),d(3),l(),g(),p===100||p===110||p===122||p===244||p===44||p===83||p===86||p===118||p===128){const L=u();if(L===3&&d(1),g(),g(),d(1),h())for(a=L!==3?8:12,o=0;o<a;o++)h()&&(o<6?m(16):m(64))}g();const v=u();if(v===0)u();else if(v===1)for(d(1),f(),f(),r=u(),o=0;o<r;o++)f();g(),d(1);const x=u(),S=u(),b=c(1);b===0&&d(1),d(1),h()&&(e=u(),t=u(),i=u(),s=u());let T=[1,1];if(h()&&h())switch(l()){case 1:T=[1,1];break;case 2:T=[12,11];break;case 3:T=[10,11];break;case 4:T=[16,11];break;case 5:T=[40,33];break;case 6:T=[24,11];break;case 7:T=[20,11];break;case 8:T=[32,11];break;case 9:T=[80,33];break;case 10:T=[18,11];break;case 11:T=[15,11];break;case 12:T=[64,33];break;case 13:T=[160,99];break;case 14:T=[4,3];break;case 15:T=[3,2];break;case 16:T=[2,1];break;case 255:{T=[l()<<8|l(),l()<<8|l()];break}}return{width:Math.ceil((x+1)*16-e*2-t*2),height:(2-b)*(S+1)*16-(b?2:4)*(i+s),pixelRatio:T}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class Bd extends Nd{parseAVCPES(e,t,i,s,r){const a=this.parseAVCNALu(e,i.data);let o=this.VideoSample,l,c=!1;i.data=null,o&&a.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"")),a.forEach(u=>{var h;switch(u.type){case 1:{let m=!1;l=!0;const p=u.data;if(c&&p.length>4){const v=new qr(p).readSliceType();(v===2||v===4||v===7||v===9)&&(m=!0)}if(m){var d;(d=o)!=null&&d.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.frame=!0,o.key=m;break}case 5:l=!0,(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.key=!0,o.frame=!0;break;case 6:{l=!0,ho(u.data,1,i.pts,t.samples);break}case 7:{var f,g;l=!0,c=!0;const m=u.data,v=new qr(m).readSPS();if(!e.sps||e.width!==v.width||e.height!==v.height||((f=e.pixelRatio)==null?void 0:f[0])!==v.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[1])!==v.pixelRatio[1]){e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.sps=[m],e.duration=r;const x=m.subarray(1,4);let S="avc1.";for(let b=0;b<3;b++){let T=x[b].toString(16);T.length<2&&(T="0"+T),S+=T}e.codec=S}break}case 8:l=!0,e.pps=[u.data];break;case 9:l=!0,e.audFound=!0,o&&this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"");break;case 12:l=!0;break;default:l=!1,o&&(o.debug+="unknown NAL "+u.type+" ");break}o&&l&&o.units.push(u)}),s&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}parseAVCNALu(e,t){const i=t.byteLength;let s=e.naluState||0;const r=s,a=[];let o=0,l,c,u,h=-1,d=0;for(s===-1&&(h=0,d=t[0]&31,s=0,o=1);o<i;){if(l=t[o++],!s){s=l?0:1;continue}if(s===1){s=l?0:2;continue}if(!l)s=3;else if(l===1){if(c=o-s-1,h>=0){const f={data:t.subarray(h,c),type:d};a.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(r&&o<=4-r&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-r)),c>0&&(f.data=Pe(f.data,t.subarray(0,c)),f.state=0))}o<i?(u=t[o]&31,h=o,d=u,s=0):s=-1}else s=0}if(h>=0&&s>=0){const f={data:t.subarray(h,i),type:d,state:s};a.push(f)}if(a.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=Pe(f.data,t))}return e.naluState=s,a}}class Ud{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Dn(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,i){const s=e[t].unit;if(s.length<=16)return;const r=s.subarray(16,s.length-s.length%16),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);s.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)})}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let s=0;for(let r=32;r<e.length-16;r+=160,s+=16)i.set(e.subarray(r,r+16),s);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let s=0;for(let r=32;r<e.length-16;r+=160,s+=16)e.set(i.subarray(s,s+16),r);return e}decryptAvcSample(e,t,i,s,r){const a=fo(r.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{r.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,s)})}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){s();return}const r=e[t].units;for(;!(i>=r.length);i++){const a=r[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,s,a),!this.decrypter.isSync()))return}}}}const ge=188;class st{constructor(e,t,i){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.videoParser=new Bd}static probe(e){const t=st.syncOffset(e);return t>0&&C.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),t!==-1}static syncOffset(e){const t=e.length;let i=Math.min(ge*5,t-ge)+1,s=0;for(;s<i;){let r=!1,a=-1,o=0;for(let l=s;l<t;l+=ge)if(e[l]===71&&(t-l===ge||e[l+ge]===71)){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+ge*99,e.length-ge)+1)),r||(r=hn(e,l)===0),r&&o>1&&(a===0&&o>2||l+ge>i))return a}else{if(o)return-1;break}s++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:ao[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=st.createTrack("video"),this._audioTrack=st.createTrack("audio",s),this._id3Track=st.createTrack("id3"),this._txtTrack=st.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,this._duration=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,s=!1){i||(this.sampleAes=null);let r;const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,c=this._txtTrack;let u=a.pid,h=a.pesData,d=o.pid,f=l.pid,g=o.pesData,m=l.pesData,p=null,v=this.pmtParsed,x=this._pmtId,S=e.length;if(this.remainderData&&(e=Pe(this.remainderData,e),S=e.length,this.remainderData=null),S<ge&&!s)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};const b=Math.max(0,st.syncOffset(e));S-=(S-b)%ge,S<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,S,e.buffer.byteLength-S));let T=0;for(let A=b;A<S;A+=ge)if(e[A]===71){const P=!!(e[A+1]&64),D=hn(e,A),I=(e[A+3]&48)>>4;let k;if(I>1){if(k=A+5+e[A+4],k===A+ge)continue}else k=A+4;switch(D){case u:P&&(h&&(r=It(h))&&this.videoParser.parseAVCPES(a,c,r,!1,this._duration),h={data:[],size:0}),h&&(h.data.push(e.subarray(k,A+ge)),h.size+=A+ge-k);break;case d:if(P){if(g&&(r=It(g)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}g={data:[],size:0}}g&&(g.data.push(e.subarray(k,A+ge)),g.size+=A+ge-k);break;case f:P&&(m&&(r=It(m))&&this.parseID3PES(l,r),m={data:[],size:0}),m&&(m.data.push(e.subarray(k,A+ge)),m.size+=A+ge-k);break;case 0:P&&(k+=e[k]+1),x=this._pmtId=$d(e,k);break;case x:{P&&(k+=e[k]+1);const M=Gd(e,k,this.typeSupported,i,this.observer);u=M.videoPid,u>0&&(a.pid=u,a.segmentCodec=M.segmentVideoCodec),d=M.audioPid,d>0&&(o.pid=d,o.segmentCodec=M.segmentAudioCodec),f=M.id3Pid,f>0&&(l.pid=f),p!==null&&!v&&(C.warn(`MPEG-TS PMT found at ${A} after unknown PID '${p}'. Backtracking to sync byte @${b} to parse all TS packets.`),p=null,A=b-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=D;break}}else T++;T>0&&ss(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`)),a.pesData=h,o.pesData=g,l.pesData=m;const L={audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};return s&&this.extractRemainingSamples(L),L}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:s,textTrack:r}=e,a=i.pesData,o=t.pesData,l=s.pesData;let c;if(a&&(c=It(a))?(this.videoParser.parseAVCPES(i,r,c,!0,this._duration),i.pesData=null):i.pesData=a,o&&(c=It(o))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,c);break;case"mp3":this.parseMPEGPES(t,c);break;case"ac3":this.parseAC3PES(t,c);break}t.pesData=null}else o!=null&&o.size&&C.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(c=It(l))?(this.parseID3PES(s,c),s.pesData=null):s.pesData=l}demuxSampleAes(e,t,i){const s=this.demux(e,i,!0,!this.config.progressive),r=this.sampleAes=new Ud(this.observer,this.config,t);return this.decrypt(s,r)}decrypt(e,t){return new Promise(i=>{const{audioTrack:s,videoTrack:r}=e;s.samples&&s.segmentCodec==="aac"?t.decryptAacSamples(s.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{i(e)}):i(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{i(e)})})}destroy(){this._duration=0}parseAACPES(e,t){let i=0;const s=this.aacOverFlow;let r=t.data;if(s){this.aacOverFlow=null;const h=s.missing,d=s.sample.unit.byteLength;if(h===-1)r=Pe(s.sample.unit,r);else{const f=d-h;s.sample.unit.set(r.subarray(0,h),f),e.samples.push(s.sample),i=s.missing}}let a,o;for(a=i,o=r.length;a<o-1&&!is(r,a);a++);if(a!==i){let h;const d=a<o-1;if(d?h=`AAC PES did not start with ADTS header,offset:${a}`:h="No ADTS header found in AAC PES",ss(this.observer,new Error(h),d),!d)return}Io(e,this.observer,r,a,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(s){const h=wo(e.samplerate);l=s.sample.pts+h}else{C.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,u;for(;a<o;)if(u=Do(e,r,a,l,c),a+=u.length,u.missing){this.aacOverFlow=u;break}else for(c++;a<o-1&&!is(r,a);a++);}parseMPEGPES(e,t){const i=t.data,s=i.length;let r=0,a=0;const o=t.pts;if(o===void 0){C.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<s;)if(Po(i,a)){const l=ko(e,i,a,o,r);if(l)a+=l.length,r++;else break}else a++}parseAC3PES(e,t){{const i=t.data,s=t.pts;if(s===void 0){C.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=i.length;let a=0,o=0,l;for(;o<r&&(l=Mo(e,i,o,s,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){C.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=de({},t,{type:this._videoTrack?Me.emsg:Me.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function hn(n,e){return((n[e+1]&31)<<8)+n[e+2]}function $d(n,e){return(n[e+10]&31)<<8|n[e+11]}function Gd(n,e,t,i,s){const r={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=(n[e+1]&15)<<8|n[e+2],o=e+3+a-4,l=(n[e+10]&15)<<8|n[e+11];for(e+=12+l;e<o;){const c=hn(n,e),u=(n[e+3]&15)<<8|n[e+4];switch(n[e]){case 207:if(!i){Fs("ADTS AAC");break}case 15:r.audioPid===-1&&(r.audioPid=c);break;case 21:r.id3Pid===-1&&(r.id3Pid=c);break;case 219:if(!i){Fs("H.264");break}case 27:r.videoPid===-1&&(r.videoPid=c,r.segmentVideoCodec="avc");break;case 3:case 4:!t.mpeg&&!t.mp3?C.log("MPEG audio found, not supported in this browser"):r.audioPid===-1&&(r.audioPid=c,r.segmentAudioCodec="mp3");break;case 193:if(!i){Fs("AC-3");break}case 129:t.ac3?r.audioPid===-1&&(r.audioPid=c,r.segmentAudioCodec="ac3"):C.log("AC-3 audio found, not supported in this browser");break;case 6:if(r.audioPid===-1&&u>0){let h=e+5,d=u;for(;d>2;){switch(n[h]){case 106:t.ac3!==!0?C.log("AC-3 audio found, not supported in this browser for now"):(r.audioPid=c,r.segmentAudioCodec="ac3");break}const g=n[h+1]+2;h+=g,d-=g}}break;case 194:case 135:return ss(s,new Error("Unsupported EC-3 in M2TS found")),r;case 36:return ss(s,new Error("Unsupported HEVC in M2TS found")),r}e+=u+5}return r}function ss(n,e,t){C.warn(`parsing error: ${e.message}`),n.emit(E.ERROR,E.ERROR,{type:z.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Fs(n){C.log(`${n} with AES-128-CBC encryption found in unencrypted stream`)}function It(n){let e=0,t,i,s,r,a;const o=n.data;if(!n||n.size===0)return null;for(;o[0].length<19&&o.length>1;)o[0]=Pe(o[0],o[1]),o.splice(1,1);if(t=o[0],(t[0]<<16)+(t[1]<<8)+t[2]===1){if(i=(t[4]<<8)+t[5],i&&i>n.size-6)return null;const c=t[7];c&192&&(r=(t[9]&14)*536870912+(t[10]&255)*4194304+(t[11]&254)*16384+(t[12]&255)*128+(t[13]&254)/2,c&64?(a=(t[14]&14)*536870912+(t[15]&255)*4194304+(t[16]&254)*16384+(t[17]&255)*128+(t[18]&254)/2,r-a>60*9e4&&(C.warn(`${Math.round((r-a)/9e4)}s delta between PTS and DTS, align them`),r=a)):a=r),s=t[8];let u=s+9;if(n.size<=u)return null;n.size-=u;const h=new Uint8Array(n.size);for(let d=0,f=o.length;d<f;d++){t=o[d];let g=t.byteLength;if(u)if(u>g){u-=g;continue}else t=t.subarray(u),g-=u,u=0;h.set(t,e),e+=g}return i&&(i-=s+3),{data:h,pts:r,dts:a,len:i}}return null}class Vd extends _n{resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=ui(e,0);let i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&Cn(t)!==void 0&&Fo(e,i)<=16)return!1;for(let s=e.length;i<s;i++)if(Oo(e,i))return C.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return _d(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return ko(e,t,i,this.basePTS,this.frameIndex)}}class zr{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const it=Math.pow(2,32)-1;class R{static init(){R.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in R.types)R.types.hasOwnProperty(e)&&(R.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);R.HDLR_TYPES={video:t,audio:i};const s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);R.STTS=R.STSC=R.STCO=r,R.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),R.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),R.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),R.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);R.FTYP=R.box(R.types.ftyp,a,l,a,o),R.DINF=R.box(R.types.dinf,R.box(R.types.dref,s))}static box(e,...t){let i=8,s=t.length;const r=s;for(;s--;)i+=t[s].byteLength;const a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.set(e,4),s=0,i=8;s<r;s++)a.set(t[s],i),i+=t[s].byteLength;return a}static hdlr(e){return R.box(R.types.hdlr,R.HDLR_TYPES[e])}static mdat(e){return R.box(R.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(it+1)),s=Math.floor(t%(it+1));return R.box(R.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(e){return R.box(R.types.mdia,R.mdhd(e.timescale,e.duration),R.hdlr(e.type),R.minf(e))}static mfhd(e){return R.box(R.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?R.box(R.types.minf,R.box(R.types.smhd,R.SMHD),R.DINF,R.stbl(e)):R.box(R.types.minf,R.box(R.types.vmhd,R.VMHD),R.DINF,R.stbl(e))}static moof(e,t,i){return R.box(R.types.moof,R.mfhd(e),R.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=R.trak(e[t]);return R.box.apply(null,[R.types.moov,R.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(R.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=R.trex(e[t]);return R.box.apply(null,[R.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(it+1)),s=Math.floor(t%(it+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return R.box(R.types.mvhd,r)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let s,r;for(s=0;s<t.length;s++)r=t[s].flags,i[s+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return R.box(R.types.sdtp,i)}static stbl(e){return R.box(R.types.stbl,R.stsd(e),R.box(R.types.stts,R.STTS),R.box(R.types.stsc,R.STSC),R.box(R.types.stsz,R.STSZ),R.box(R.types.stco,R.STCO))}static avc1(e){let t=[],i=[],s,r,a;for(s=0;s<e.sps.length;s++)r=e.sps[s],a=r.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(r));for(s=0;s<e.pps.length;s++)r=e.pps[s],a=r.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(r));const o=R.box(R.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,c=e.height,u=e.pixelRatio[0],h=e.pixelRatio[1];return R.box(R.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static audioStsd(e){const t=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return R.box(R.types.mp4a,R.audioStsd(e),R.box(R.types.esds,R.esds(e)))}static mp3(e){return R.box(R.types[".mp3"],R.audioStsd(e))}static ac3(e){return R.box(R.types["ac-3"],R.audioStsd(e),R.box(R.types.dac3,e.config))}static stsd(e){return e.type==="audio"?e.segmentCodec==="mp3"&&e.codec==="mp3"?R.box(R.types.stsd,R.STSD,R.mp3(e)):e.segmentCodec==="ac3"?R.box(R.types.stsd,R.STSD,R.ac3(e)):R.box(R.types.stsd,R.STSD,R.mp4a(e)):R.box(R.types.stsd,R.STSD,R.avc1(e))}static tkhd(e){const t=e.id,i=e.duration*e.timescale,s=e.width,r=e.height,a=Math.floor(i/(it+1)),o=Math.floor(i%(it+1));return R.box(R.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,s&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const i=R.sdtp(e),s=e.id,r=Math.floor(t/(it+1)),a=Math.floor(t%(it+1));return R.box(R.types.traf,R.box(R.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),R.box(R.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),R.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,R.box(R.types.trak,R.tkhd(e),R.mdia(e))}static trex(e){const t=e.id;return R.box(R.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],s=i.length,r=12+16*s,a=new Uint8Array(r);let o,l,c,u,h,d;for(t+=8+r,a.set([e.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<s;o++)l=i[o],c=l.duration,u=l.size,h=l.flags,d=l.cts,a.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return R.box(R.types.trun,a)}static initSegment(e){R.types||R.init();const t=R.moov(e);return Pe(R.FTYP,t)}}R.types=void 0;R.HDLR_TYPES=void 0;R.STTS=void 0;R.STSC=void 0;R.STCO=void 0;R.STSZ=void 0;R.VMHD=void 0;R.SMHD=void 0;R.STSD=void 0;R.FTYP=void 0;R.DINF=void 0;const No=9e4;function Fn(n,e,t=1,i=!1){const s=n*e*t;return i?Math.round(s):s}function Hd(n,e,t=1,i=!1){return Fn(n,e,1/t,i)}function Yt(n,e=!1){return Fn(n,1e3,1/No,e)}function Kd(n,e=1){return Fn(n,No,1/e)}const Wd=10*1e3,Xr=1024,Yd=1152,qd=1536;let wt=null,Ms=null;class Oi{constructor(e,t,i,s=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,wt===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);wt=a?parseInt(a[1]):0}if(Ms===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);Ms=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){C.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){C.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){C.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e.reduce((s,r)=>{const a=r.pts-s;return a<-4294967296?(t=!0,_e(s,r.pts)):a>0?s:r.pts},e[0].pts);return t&&C.debug("PTS rollover detected"),i}remux(e,t,i,s,r,a,o,l){let c,u,h,d,f,g,m=r,p=r;const v=e.pid>-1,x=t.pid>-1,S=t.samples.length,b=e.samples.length>0,T=o&&S>0||S>1;if((!v||b)&&(!x||T)||this.ISGenerated||o){if(this.ISGenerated){var A,P,D,I;const N=this.videoTrackConfig;N&&(t.width!==N.width||t.height!==N.height||((A=t.pixelRatio)==null?void 0:A[0])!==((P=N.pixelRatio)==null?void 0:P[0])||((D=t.pixelRatio)==null?void 0:D[1])!==((I=N.pixelRatio)==null?void 0:I[1]))&&this.resetInitSegment()}else h=this.generateIS(e,t,r,a);const k=this.isVideoContiguous;let M=-1,_;if(T&&(M=zd(t.samples),!k&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,M>0){C.warn(`[mp4-remuxer]: Dropped ${M} out of ${S} video samples due to a missing keyframe`);const N=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(M),t.dropped+=M,p+=(t.samples[0].pts-N)/t.inputTimeScale,_=p}else M===-1&&(C.warn(`[mp4-remuxer]: No keyframe found out of ${S} video samples`),g=!1);if(this.ISGenerated){if(b&&T){const N=this.getVideoStartPts(t.samples),G=(_e(e.samples[0].pts,N)-N)/t.inputTimeScale;m+=Math.max(0,G),p+=Math.max(0,-G)}if(b){if(e.samplerate||(C.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),h=this.generateIS(e,t,r,a)),u=this.remuxAudio(e,m,this.isAudioContiguous,a,x||T||l===W.AUDIO?p:void 0),T){const N=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(C.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),h=this.generateIS(e,t,r,a)),c=this.remuxVideo(t,p,k,N)}}else T&&(c=this.remuxVideo(t,p,k,0));c&&(c.firstKeyFrame=M,c.independent=M!==-1,c.firstKeyFramePTS=_)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=Bo(i,r,this._initPTS,this._initDTS)),s.samples.length&&(d=Uo(s,r,this._initPTS))),{audio:u,video:c,initSegment:h,independent:g,text:d,id3:f}}generateIS(e,t,i,s){const r=e.samples,a=t.samples,o=this.typeSupported,l={},c=this._initPTS;let u=!c||s,h="audio/mp4",d,f,g;if(u&&(d=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(h="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):R.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(g=e.inputTimeScale,!c||g!==c.timescale?d=f=r[0].pts-Math.round(g*i):u=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:R.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(g=t.inputTimeScale,!c||g!==c.timescale){const m=this.getVideoStartPts(a),p=Math.round(g*i);f=Math.min(f,_e(a[0].dts,m)-p),d=Math.min(d,m-p)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:d,timescale:g},this._initDTS={baseTime:f,timescale:g}):d=g=void 0,{tracks:l,initPTS:d,timescale:g}}remuxVideo(e,t,i,s){const r=e.inputTimeScale,a=e.samples,o=[],l=a.length,c=this._initPTS;let u=this.nextAvcDts,h=8,d=this.videoSampleDuration,f,g,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!i||u===null){const $=t*r,U=a[0].pts-_e(a[0].dts,a[0].pts);wt&&u!==null&&Math.abs($-U-u)<15e3?i=!0:u=$-U}const x=c.baseTime*r/c.timescale;for(let $=0;$<l;$++){const U=a[$];U.pts=_e(U.pts-x,u),U.dts=_e(U.dts-x,u),U.dts<a[$>0?$-1:$].dts&&(v=!0)}v&&a.sort(function($,U){const ee=$.dts-U.dts,Z=$.pts-U.pts;return ee||Z}),f=a[0].dts,g=a[a.length-1].dts;const S=g-f,b=S?Math.round(S/(l-1)):d||e.inputTimeScale/30;if(i){const $=f-u,U=$>b,ee=$<-1;if((U||ee)&&(U?C.warn(`AVC: ${Yt($,!0)} ms (${$}dts) hole between fragments detected at ${t.toFixed(3)}`):C.warn(`AVC: ${Yt(-$,!0)} ms (${$}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!ee||u>=a[0].pts||wt)){f=u;const Z=a[0].pts-$;if(U)a[0].dts=f,a[0].pts=Z;else for(let te=0;te<a.length&&!(a[te].dts>Z);te++)a[te].dts-=$,a[te].pts-=$;C.log(`Video: Initial PTS/DTS adjusted: ${Yt(Z,!0)}/${Yt(f,!0)}, delta: ${Yt($,!0)} ms`)}}f=Math.max(0,f);let T=0,L=0,A=f;for(let $=0;$<l;$++){const U=a[$],ee=U.units,Z=ee.length;let te=0;for(let oe=0;oe<Z;oe++)te+=ee[oe].data.length;L+=te,T+=Z,U.length=te,U.dts<A?(U.dts=A,A+=b/4|0||1):A=U.dts,m=Math.min(U.pts,m),p=Math.max(U.pts,p)}g=a[l-1].dts;const P=L+4*T+8;let D;try{D=new Uint8Array(P)}catch($){this.observer.emit(E.ERROR,E.ERROR,{type:z.MUX_ERROR,details:w.REMUX_ALLOC_ERROR,fatal:!1,error:$,bytes:P,reason:`fail allocating video mdat ${P}`});return}const I=new DataView(D.buffer);I.setUint32(0,P),D.set(R.types.mdat,4);let k=!1,M=Number.POSITIVE_INFINITY,_=Number.POSITIVE_INFINITY,N=Number.NEGATIVE_INFINITY,B=Number.NEGATIVE_INFINITY;for(let $=0;$<l;$++){const U=a[$],ee=U.units;let Z=0;for(let ue=0,he=ee.length;ue<he;ue++){const xe=ee[ue],De=xe.data,rt=xe.data.byteLength;I.setUint32(h,rt),h+=4,D.set(De,h),h+=rt,Z+=4+rt}let te;if($<l-1)d=a[$+1].dts-U.dts,te=a[$+1].pts-U.pts;else{const ue=this.config,he=$>0?U.dts-a[$-1].dts:b;if(te=$>0?U.pts-a[$-1].pts:b,ue.stretchShortVideoTrack&&this.nextAudioPts!==null){const xe=Math.floor(ue.maxBufferHole*r),De=(s?m+s*r:this.nextAudioPts)-U.pts;De>xe?(d=De-he,d<0?d=he:k=!0,C.log(`[mp4-remuxer]: It is approximately ${De/90} ms to the next segment; using duration ${d/90} ms for the last video frame.`)):d=he}else d=he}const oe=Math.round(U.pts-U.dts);M=Math.min(M,d),N=Math.max(N,d),_=Math.min(_,te),B=Math.max(B,te),o.push(new jr(U.key,d,Z,oe))}if(o.length){if(wt){if(wt<70){const $=o[0].flags;$.dependsOn=2,$.isNonSync=0}}else if(Ms&&B-_<N-M&&b/N<.025&&o[0].cts===0){C.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let $=f;for(let U=0,ee=o.length;U<ee;U++){const Z=$+o[U].duration,te=$+o[U].cts;if(U<ee-1){const oe=Z+o[U+1].cts;o[U].duration=oe-te}else o[U].duration=U?o[U-1].duration:b;o[U].cts=0,$=Z}}}d=k||!d?b:d,this.nextAvcDts=u=g+d,this.videoSampleDuration=d,this.isVideoContiguous=!0;const Q={data1:R.moof(e.sequenceNumber++,f,de({},e,{samples:o})),data2:D,startPTS:m/r,endPTS:(p+d)/r,startDTS:f/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Q}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Yd;case"ac3":return qd;default:return Xr}}remuxAudio(e,t,i,s,r){const a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,l=a/o,c=this.getSamplesPerFrame(e),u=c*l,h=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=r!==void 0;let m=e.samples,p=d?0:8,v=this.nextAudioPts||-1;const x=t*a,S=h.baseTime*a/h.timescale;if(this.isAudioContiguous=i=i||m.length&&v>0&&(s&&Math.abs(x-v)<9e3||Math.abs(_e(m[0].pts-S,x)-v)<20*u),m.forEach(function(G){G.pts=_e(G.pts-S,x)}),!i||v<0){if(m=m.filter(G=>G.pts>=0),!m.length)return;r===0?v=0:s&&!g?v=Math.max(0,x):v=m[0].pts}if(e.segmentCodec==="aac"){const G=this.config.maxAudioFramesDrift;for(let X=0,Q=v;X<m.length;X++){const $=m[X],U=$.pts,ee=U-Q,Z=Math.abs(1e3*ee/a);if(ee<=-G*u&&g)X===0&&(C.warn(`Audio frame @ ${(U/a).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*ee/a)} ms.`),this.nextAudioPts=v=Q=U);else if(ee>=G*u&&Z<Wd&&g){let te=Math.round(ee/u);Q=U-te*u,Q<0&&(te--,Q+=u),X===0&&(this.nextAudioPts=v=Q),C.warn(`[mp4-remuxer]: Injecting ${te} audio frame @ ${(Q/a).toFixed(3)}s due to ${Math.round(1e3*ee/a)} ms gap.`);for(let oe=0;oe<te;oe++){const ue=Math.max(Q,0);let he=zr.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);he||(C.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),he=$.unit.subarray()),m.splice(X,0,{unit:he,pts:ue}),Q+=u,X++}}$.pts=Q,Q+=u}}let b=null,T=null,L,A=0,P=m.length;for(;P--;)A+=m[P].unit.byteLength;for(let G=0,X=m.length;G<X;G++){const Q=m[G],$=Q.unit;let U=Q.pts;if(T!==null){const Z=f[G-1];Z.duration=Math.round((U-T)/l)}else if(i&&e.segmentCodec==="aac"&&(U=v),b=U,A>0){A+=p;try{L=new Uint8Array(A)}catch(Z){this.observer.emit(E.ERROR,E.ERROR,{type:z.MUX_ERROR,details:w.REMUX_ALLOC_ERROR,fatal:!1,error:Z,bytes:A,reason:`fail allocating audio mdat ${A}`});return}d||(new DataView(L.buffer).setUint32(0,A),L.set(R.types.mdat,4))}else return;L.set($,p);const ee=$.byteLength;p+=ee,f.push(new jr(!0,c,ee,0)),T=U}const D=f.length;if(!D)return;const I=f[f.length-1];this.nextAudioPts=v=T+l*I.duration;const k=d?new Uint8Array(0):R.moof(e.sequenceNumber++,b/l,de({},e,{samples:f}));e.samples=[];const M=b/a,_=v/a,B={data1:k,data2:L,startPTS:M,endPTS:_,startDTS:M,endDTS:_,type:"audio",hasAudio:!0,hasVideo:!1,nb:D};return this.isAudioContiguous=!0,B}remuxEmptyAudio(e,t,i,s){const r=e.inputTimeScale,a=e.samplerate?e.samplerate:r,o=r/a,l=this.nextAudioPts,c=this._initDTS,u=c.baseTime*9e4/c.timescale,h=(l!==null?l:s.startDTS*r)+u,d=s.endDTS*r+u,f=o*Xr,g=Math.ceil((d-h)/f),m=zr.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(C.warn("[mp4-remuxer]: remux empty Audio"),!m){C.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const p=[];for(let v=0;v<g;v++){const x=h+v*f;p.push({unit:m,pts:x,dts:x})}return e.samples=p,this.remuxAudio(e,t,i,!1)}}function _e(n,e){let t;if(e===null)return n;for(e<n?t=-8589934592:t=8589934592;Math.abs(n-e)>4294967296;)n+=t;return n}function zd(n){for(let e=0;e<n.length;e++)if(n[e].key)return e;return-1}function Bo(n,e,t,i){const s=n.samples.length;if(!s)return;const r=n.inputTimeScale;for(let o=0;o<s;o++){const l=n.samples[o];l.pts=_e(l.pts-t.baseTime*r/t.timescale,e*r)/r,l.dts=_e(l.dts-i.baseTime*r/i.timescale,e*r)/r}const a=n.samples;return n.samples=[],{samples:a}}function Uo(n,e,t){const i=n.samples.length;if(!i)return;const s=n.inputTimeScale;for(let a=0;a<i;a++){const o=n.samples[a];o.pts=_e(o.pts-t.baseTime*s/t.timescale,e*s)/s}n.samples.sort((a,o)=>a.pts-o.pts);const r=n.samples;return n.samples=[],{samples:r}}class jr{constructor(e,t,i,s){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=i,this.cts=s,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class Xd{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(th(e,s)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const s=this.initData=co(e);s.audio&&(t=Zr(s.audio,se.AUDIO)),s.video&&(i=Zr(s.video,se.VIDEO));const r={};s.audio&&s.video?r.audiovideo={container:"video/mp4",codec:t+","+i,initSegment:e,id:"main"}:s.audio?r.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:s.video?r.video={container:"video/mp4",codec:i,initSegment:e,id:"main"}:C.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(e,t,i,s,r,a){var o,l;let{initPTS:c,lastEndTime:u}=this;const h={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};H(u)||(u=this.lastEndTime=r||0);const d=t.samples;if(!(d!=null&&d.length))return h;const f={initPTS:void 0,timescale:1};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(d),g=this.initData),!((l=g)!=null&&l.length))return C.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),h;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const m=sh(d,g),p=ih(g,d),v=p===null?r:p;(jd(c,v,r,m)||f.timescale!==c.timescale&&a)&&(f.initPTS=v-r,c&&c.timescale===1&&C.warn(`Adjusting initPTS by ${f.initPTS-c.baseTime}`),this.initPTS=c={baseTime:f.initPTS,timescale:1});const x=e?v-c.baseTime/c.timescale:u,S=x+m;rh(g,d,c.baseTime/c.timescale),m>0?this.lastEndTime=S:(C.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const b=!!g.audio,T=!!g.video;let L="";b&&(L+="audio"),T&&(L+="video");const A={data1:d,startPTS:x,startDTS:x,endPTS:S,endDTS:S,type:L,hasAudio:b,hasVideo:T,nb:1,dropped:0};return h.audio=A.type==="audio"?A:void 0,h.video=A.type!=="audio"?A:void 0,h.initSegment=f,h.id3=Bo(i,r,c,c),s.samples.length&&(h.text=Uo(s,r,c)),h}}function jd(n,e,t,i){if(n===null)return!0;const s=Math.max(i,1),r=e-n.baseTime/n.timescale;return Math.abs(r-t)>s}function Zr(n,e){const t=n==null?void 0:n.codec;if(t&&t.length>4)return t;if(e===se.AUDIO){if(t==="ec-3"||t==="ac-3"||t==="alac")return t;if(t==="fLaC"||t==="Opus")return ji(t,!1);const i="mp4a.40.5";return C.info(`Parsed audio codec "${t}" or audio object type not handled. Using "${i}"`),i}return C.warn(`Unhandled video codec "${t}"`),t==="hvc1"||t==="hev1"?"hvc1.1.6.L120.90":t==="av01"?"av01.0.04M.08":"avc1.42e01e"}let Je;try{Je=self.performance.now.bind(self.performance)}catch{C.debug("Unable to use Performance API on this environment"),Je=Bt==null?void 0:Bt.Date.now}const Fi=[{demux:Fd,remux:Xd},{demux:st,remux:Oi},{demux:Pd,remux:Oi},{demux:Vd,remux:Oi}];Fi.splice(2,0,{demux:Md,remux:Oi});class Qr{constructor(e,t,i,s,r){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.vendor=s,this.id=r}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){const r=i.transmuxing;r.executeStart=Je();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;s&&(this.currentTransmuxState=s);const{contiguous:c,discontinuity:u,trackSwitch:h,accurateTimeOffset:d,timeOffset:f,initSegmentChange:g}=s||o,{audioCodec:m,videoCodec:p,defaultInitPts:v,duration:x,initSegmentData:S}=l,b=Zd(a,t);if(b&&b.method==="AES-128"){const P=this.getDecrypter();if(P.isSync()){let D=P.softwareDecrypt(a,b.key.buffer,b.iv.buffer);if(i.part>-1&&(D=P.flush()),!D)return r.executeEnd=Je(),Ns(i);a=new Uint8Array(D)}else return this.decryptionPromise=P.webCryptoDecrypt(a,b.key.buffer,b.iv.buffer).then(D=>{const I=this.push(D,null,i);return this.decryptionPromise=null,I}),this.decryptionPromise}const T=this.needsProbing(u,h);if(T){const P=this.configureTransmuxer(a);if(P)return C.warn(`[transmuxer] ${P.message}`),this.observer.emit(E.ERROR,E.ERROR,{type:z.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,error:P,reason:P.message}),r.executeEnd=Je(),Ns(i)}(u||h||g||T)&&this.resetInitSegment(S,m,p,x,t),(u||g||T)&&this.resetInitialTimestamp(v),c||this.resetContiguity();const L=this.transmux(a,b,f,d,i),A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=Je(),L}flush(e){const t=e.transmuxing;t.executeStart=Je();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return r.then(()=>this.flush(e));const a=[],{timeOffset:o}=s;if(i){const h=i.flush();h&&a.push(this.push(h,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c)return t.executeEnd=Je(),[Ns(e)];const u=l.flush(o);return Mi(u)?u.then(h=>(this.flushRemux(a,h,e),a)):(this.flushRemux(a,u,e),a)}flushRemux(e,t,i){const{audioTrack:s,videoTrack:r,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;C.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const u=this.remuxer.remux(s,r,a,o,c,l,!0,this.id);e.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=Je()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,s,r){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,i,s),o.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,s,r){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,s,r):a=this.transmuxUnencrypted(e,i,s,r),a}transmuxUnencrypted(e,t,i,s){const{audioTrack:r,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,a,o,l,t,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,i,s,r){return this.demuxer.demuxSampleAes(e,t,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,s,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:s,vendor:r}=this;let a;for(let d=0,f=Fi.length;d<f;d++){var o;if((o=Fi[d].demux)!=null&&o.probe(e)){a=Fi[d];break}}if(!a)return new Error("Failed to find demuxer by probing fragment data");const l=this.demuxer,c=this.remuxer,u=a.remux,h=a.demux;(!c||!(c instanceof u))&&(this.remuxer=new u(i,t,s,r)),(!l||!(l instanceof h))&&(this.demuxer=new h(i,t,s),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Dn(this.config)),e}}function Zd(n,e){let t=null;return n.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Ns=n=>({remuxResult:{},chunkMeta:n});function Mi(n){return"then"in n&&n.then instanceof Function}class Qd{constructor(e,t,i,s,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}}class Jd{constructor(e,t,i,s,r,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=a}}var $o={exports:{}};(function(n){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function r(l,c,u,h,d){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new s(u,h||l,d),g=t?t+c:c;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function a(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,h;if(this._eventsCount===0)return c;for(h in u=this._events)e.call(u,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var d=0,f=h.length,g=new Array(f);d<f;d++)g[d]=h[d].fn;return g},o.prototype.listenerCount=function(c){var u=t?t+c:c,h=this._events[u];return h?h.fn?1:h.length:0},o.prototype.emit=function(c,u,h,d,f,g){var m=t?t+c:c;if(!this._events[m])return!1;var p=this._events[m],v=arguments.length,x,S;if(p.fn){switch(p.once&&this.removeListener(c,p.fn,void 0,!0),v){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,u),!0;case 3:return p.fn.call(p.context,u,h),!0;case 4:return p.fn.call(p.context,u,h,d),!0;case 5:return p.fn.call(p.context,u,h,d,f),!0;case 6:return p.fn.call(p.context,u,h,d,f,g),!0}for(S=1,x=new Array(v-1);S<v;S++)x[S-1]=arguments[S];p.fn.apply(p.context,x)}else{var b=p.length,T;for(S=0;S<b;S++)switch(p[S].once&&this.removeListener(c,p[S].fn,void 0,!0),v){case 1:p[S].fn.call(p[S].context);break;case 2:p[S].fn.call(p[S].context,u);break;case 3:p[S].fn.call(p[S].context,u,h);break;case 4:p[S].fn.call(p[S].context,u,h,d);break;default:if(!x)for(T=1,x=new Array(v-1);T<v;T++)x[T-1]=arguments[T];p[S].fn.apply(p[S].context,x)}}return!0},o.prototype.on=function(c,u,h){return r(this,c,u,h,!1)},o.prototype.once=function(c,u,h){return r(this,c,u,h,!0)},o.prototype.removeListener=function(c,u,h,d){var f=t?t+c:c;if(!this._events[f])return this;if(!u)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===u&&(!d||g.once)&&(!h||g.context===h)&&a(this,f);else{for(var m=0,p=[],v=g.length;m<v;m++)(g[m].fn!==u||d&&!g[m].once||h&&g[m].context!==h)&&p.push(g[m]);p.length?this._events[f]=p.length===1?p[0]:p:a(this,f)}return this},o.prototype.removeAllListeners=function(c){var u;return c?(u=t?t+c:c,this._events[u]&&a(this,u)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,n.exports=o})($o);var ef=$o.exports,Mn=bu(ef);class Go{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const a=(c,u)=>{u=u||{},u.frag=this.frag,u.id=this.id,c===E.ERROR&&(this.error=u.error),this.hls.trigger(c,u)};this.observer=new Mn,this.observer.on(E.FRAG_DECRYPTED,a),this.observer.on(E.ERROR,a);const o=vt(r.preferManagedMediaSource)||{isTypeSupported:()=>!1},l={mpeg:o.isTypeSupported("audio/mpeg"),mp3:o.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:o.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&typeof Worker<"u"&&(r.workerPath||xd())){try{r.workerPath?(C.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=Td(r.workerPath)):(C.log(`injecting Web Worker for "${t}"`),this.workerContext=yd()),this.onwmsg=h=>this.onWorkerMessage(h);const{worker:u}=this.workerContext;u.addEventListener("message",this.onwmsg),u.onerror=h=>{const d=new Error(`${h.message} (${h.filename}:${h.lineno})`);r.enableWorker=!1,C.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(E.ERROR,{type:z.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})},u.postMessage({cmd:"init",typeSupported:l,vendor:"",id:t,config:JSON.stringify(r)})}catch(u){C.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.resetWorker(),this.error=null,this.transmuxer=new Qr(this.observer,l,r,"",t)}return}this.transmuxer=new Qr(this.observer,l,r,"",t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,i,s,r,a,o,l,c,u){var h,d;c.transmuxing.start=self.performance.now();const{transmuxer:f}=this,g=a?a.start:r.start,m=r.decryptdata,p=this.frag,v=!(p&&r.cc===p.cc),x=!(p&&c.level===p.level),S=p?c.sn-p.sn:-1,b=this.part?c.part-this.part.index:-1,T=S===0&&c.id>1&&c.id===(p==null?void 0:p.stats.chunkCount),L=!x&&(S===1||S===0&&(b===1||T&&b<=0)),A=self.performance.now();(x||S||r.stats.parsing.start===0)&&(r.stats.parsing.start=A),a&&(b||!L)&&(a.stats.parsing.start=A);const P=!(p&&((h=r.initSegment)==null?void 0:h.url)===((d=p.initSegment)==null?void 0:d.url)),D=new Jd(v,L,l,x,g,P);if(!L||v||P){C.log(`[transmuxer-interface, ${r.type}]: Starting new transmux session for sn: ${c.sn} p: ${c.part} level: ${c.level} id: ${c.id} discontinuity: ${v} trackSwitch: ${x} contiguous: ${L} accurateTimeOffset: ${l} timeOffset: ${g} initSegmentChange: ${P}`);const I=new Qd(i,s,t,o,u);this.configureTransmuxer(I)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:m,chunkMeta:c,state:D},e instanceof ArrayBuffer?[e]:[]);else if(f){const I=f.push(e,m,c,D);Mi(I)?(f.async=!0,I.then(k=>{this.handleTransmuxComplete(k)}).catch(k=>{this.transmuxerError(k,c,"transmuxer-interface push error")})):(f.async=!1,this.handleTransmuxComplete(I))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let i=t.flush(e);Mi(i)||t.async?(Mi(i)||(i=Promise.resolve(i)),i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")})):this.handleFlushResult(i,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(E.ERROR,{type:z.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}onWorkerMessage(e){const t=e.data;if(!(t!=null&&t.event)){C.warn(`worker message received with no ${t?"event name":"data"}`);return}const i=this.hls;if(this.hls)switch(t.event){case"init":{var s;const r=(s=this.workerContext)==null?void 0:s.objectURL;r&&self.URL.revokeObjectURL(r);break}case"transmuxComplete":{this.handleTransmuxComplete(t.data);break}case"flush":{this.onFlush(t.data);break}case"workerLog":C[t.data.logType]&&C[t.data.logType](t.data.message);break;default:{t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,i.trigger(t.event,t.data);break}}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}function Vo(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(!$t(n[t].attrs,e[t].attrs))return!1;return!0}function $t(n,e,t){const i=n["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>n[s]!==e[s])}function dn(n,e){return e.label.toLowerCase()===n.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(n.lang||"").toLowerCase())}const Jr=100;class tf extends kn{constructor(e,t,i){super(e,t,i,"[audio-stream-controller]",W.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.ERROR,this.onError,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.ERROR,this.onError,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:r}){if(i==="main"){const a=t.cc;this.initPTS[t.cc]={baseTime:s,timescale:r},this.log(`InitPTS for cc: ${a} found from main: ${s}`),this.videoTrackCC=a,this.state===F.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=F.STOPPED;return}const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(Jr),t>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=F.IDLE):(this.loadedmetadata=!1,this.state=F.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case F.IDLE:this.doTickIdle();break;case F.WAITING_TRACK:{var e;const{levels:i,trackId:s}=this,r=i==null||(e=i[s])==null?void 0:e.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=F.WAITING_INIT_PTS}break}case F.FRAG_LOADING_WAITING_RETRY:{var t;const i=performance.now(),s=this.retryDate;if(!s||i>=s||(t=this.media)!=null&&t.seeking){const{levels:r,trackId:a}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((r==null?void 0:r[a])||null),this.state=F.IDLE}break}case F.WAITING_INIT_PTS:{const i=this.waitingData;if(i){const{frag:s,part:r,cache:a,complete:o}=i;if(this.initPTS[s.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=F.FRAG_LOADING;const l=a.flush(),c={frag:s,part:r,payload:l,networkDetails:null};this._handleFragmentLoadProgress(c),o&&super._handleFragmentLoadComplete(c)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${s.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),c=re.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);un(c.end,this.config.maxFragLookUpTolerance,s)<0&&(this.log(`Waiting fragment cc (${s.cc}) @ ${s.start} cancelled because another fragment at ${c.end} is needed`),this.clearWaitingFragment())}}else this.state=F.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=F.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:i,trackId:s}=this,r=e.config;if(!i&&(this.startFragRequested||!r.startFragPrefetch)||!(t!=null&&t[s]))return;const a=t[s],o=a.details;if(!o||o.live&&this.levelLastLoaded!==a||this.waitForCdnTuneIn(o)){this.state=F.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,se.AUDIO,W.AUDIO));const c=this.getFwdBufferInfo(l,W.AUDIO);if(c===null)return;const{bufferedTrack:u,switchingTrack:h}=this;if(!h&&this._streamEnded(c,o)){e.trigger(E.BUFFER_EOS,{type:"audio"}),this.state=F.ENDED;return}const d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,W.MAIN),f=c.len,g=this.getMaxBufferLength(d==null?void 0:d.len),m=o.fragments,p=m[0].start;let v=this.flushing?this.getLoadPosition():c.end;if(h&&i){const T=this.getLoadPosition();u&&!$t(h.attrs,u.attrs)&&(v=T),o.PTSKnown&&T<p&&(c.end>p||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=p+.05)}if(f>=g&&!h&&v<m[m.length-1].start)return;let x=this.getNextFragment(v,o),S=!1;if(x&&this.isLoopLoading(x,v)&&(S=!!x.gap,x=this.getNextFragmentLoopLoading(x,o,c,W.MAIN,g)),!x){this.bufferFlushed=!0;return}const b=d&&x.start>d.end+o.targetduration;if(b||!(d!=null&&d.len)&&c.len){const T=this.getAppendedFrag(x.start,W.MAIN);if(T===null||(S||(S=!!T.gap||!!b&&d.len===0),b&&!S||S&&c.nextStart&&c.nextStart<T.end))return}this.loadFragment(x,a,v)}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new Ut(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?this.setInterval(Jr):this.resetTransmuxer(),i?(this.switchingTrack=t,this.state=F.IDLE,this.flushAudioIfNeeded(t)):(this.switchingTrack=null,this.bufferedTrack=t,this.state=F.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(E.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var i;if(this.mainDetails==null){this.cachedTrackLoadedData=t;return}const{levels:s}=this,{details:r,id:a}=t;if(!s){this.warn(`Audio tracks were reset while loading level ${a}`);return}this.log(`Audio track ${a} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const o=s[a];let l=0;if(r.live||(i=o.details)!=null&&i.live){this.checkLiveUpdate(r);const u=this.mainDetails;if(r.deltaUpdateFailed||!u)return;if(!o.details&&r.hasProgramDateTime&&u.hasProgramDateTime)ts(r,u),l=r.fragments[0].start;else{var c;l=this.alignPlaylists(r,o.details,(c=this.levelLastLoaded)==null?void 0:c.details)}}o.details=r,this.levelLastLoaded=o,!this.startFragRequested&&(this.mainDetails||!r.live)&&this.setStartPosition(this.mainDetails||r,l),this.state===F.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=F.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:s,payload:r}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const c=l[o];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const u=c.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const h=a.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new Go(this.hls,W.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[i.cc],g=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){const p=s?s.index:-1,v=p!==-1,x=new wn(i.level,i.sn,i.stats.chunkCount,r.byteLength,p,v);d.push(r,g,h,"",i,s,u.totalduration,!1,x,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:m}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Ao,complete:!1};m.push(new Uint8Array(r)),this.waitingVideoCC=this.videoTrackCC,this.state=F.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i.type!==W.AUDIO){if(!this.loadedmetadata&&i.type===W.MAIN){const r=this.videoBuffer||this.media;r&&re.getBuffered(r).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(i.sn!=="initSegment"){this.fragPrevious=i;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(E.AUDIO_TRACK_SWITCHED,Ee({},r)))}this.fragBufferedComplete(i,s)}onError(e,t){var i;if(t.fatal){this.state=F.ERROR;return}switch(t.details){case w.FRAG_GAP:case w.FRAG_PARSING_ERROR:case w.FRAG_DECRYPT_ERROR:case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(W.AUDIO,t);break;case w.AUDIO_TRACK_LOAD_ERROR:case w.AUDIO_TRACK_LOAD_TIMEOUT:case w.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===F.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===ie.AUDIO_TRACK&&(this.state=F.IDLE);break;case w.BUFFER_APPEND_ERROR:case w.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="audio")return;if(t.details===w.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case w.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==se.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==se.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===F.ENDED&&(this.state=F.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,W.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:u}=o,{details:h}=u,{audio:d,text:f,id3:g,initSegment:m}=r;if(this.fragContextChanged(l)||!h){this.fragmentTracker.removeFragment(l);return}if(this.state=F.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),m!=null&&m.tracks){const p=l.initSegment||l;this._bufferInitSegment(u,m.tracks,p,a),s.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:i,tracks:m.tracks})}if(d){const{startPTS:p,endPTS:v,startDTS:x,endDTS:S}=d;c&&(c.elementaryStreams[se.AUDIO]={startPTS:p,endPTS:v,startDTS:x,endDTS:S}),l.setElementaryStreamInfo(se.AUDIO,p,v,x,S),this.bufferFragmentData(d,l,c,a)}if(g!=null&&(t=g.samples)!=null&&t.length){const p=de({id:i,frag:l,details:h},g);s.trigger(E.FRAG_PARSING_METADATA,p)}if(f){const p=de({id:i,frag:l,details:h},f);s.trigger(E.FRAG_PARSING_USERDATA,p)}}_bufferInitSegment(e,t,i,s){if(this.state!==F.PARSING)return;t.video&&delete t.video;const r=t.audio;if(!r)return;r.id="audio";const a=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a&&a.split(",").length===1&&(r.levelCodec=a),this.hls.trigger(E.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:o};this.hls.trigger(E.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||s===pe.NOT_LOADED||s===pe.PARTIAL){var r;if(e.sn==="initSegment")this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=F.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragments[0].start!==t.details.fragments[0].start&&ts(t.details,a)}else this.startFragRequested=!0,super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){const{media:t,bufferedTrack:i}=this,s=i==null?void 0:i.attrs,r=e.attrs;t&&s&&(s.CHANNELS!==r.CHANNELS||i.name!==e.name||i.lang!==e.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(E.AUDIO_TRACK_SWITCHED,Ee({},e))}}class sf extends In{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:s,details:r}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Audio track with id:${i} and group:${s} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||(s==null?void 0:s.length)!==(i==null?void 0:i.length)||i!=null&&i.some(o=>(s==null?void 0:s.indexOf(o))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!i||i.indexOf(d.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,f)=>{d.id=f});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!r&&l){const d=Ye(l,o,Ct);if(d>-1)r=o[d];else{const f=Ye(l,this.tracks);r=this.tracks[f]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(E.AUDIO_TRACKS_UPDATED,u);const h=this.trackId;if(c!==-1&&h===-1)this.setAudioTrack(c);else if(o.length&&h===-1){var a;const d=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(E.ERROR,{type:z.MEDIA_ERROR,details:w.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}else this.shouldReloadPlaylist(r)&&this.setAudioTrack(this.trackId)}onError(e,t){t.fatal||!t.context||t.context.type===ie.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&(this.requestScheduled=-1,this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&Ot(e,s,Ct))return s;const r=Ye(e,this.tracksInGroup,Ct);if(r>-1){const a=this.tracksInGroup[r];return this.setAudioTrack(r),a}else if(s){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=id(e,t.levels,i,a,Ct);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=Ye(e,i);if(a>-1)return i[a]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e],r=s.details&&!s.details.live;if(e===this.trackId&&s===i&&r||(this.log(`Switching to audio-track ${e} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=e,this.currentTrack=s,this.hls.trigger(E.AUDIO_TRACK_SWITCHING,Ee({},s)),r))return;const a=this.switchParams(s.url,i==null?void 0:i.details,s.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if(!(this.selectDefaultTrack&&!s.default)&&(!e||Ot(e,s,Ct)))return i}if(e){const{name:i,lang:s,assocLang:r,characteristics:a,audioCodec:o,channels:l}=e;for(let c=0;c<t.length;c++){const u=t[c];if(Ot({name:i,lang:s,assocLang:r,characteristics:a,audioCodec:o,channels:l},u,Ct))return c}for(let c=0;c<t.length;c++){const u=t[c];if($t(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<t.length;c++){const u=t[c];if($t(e.attrs,u.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(e){const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){super.loadPlaylist();const i=t.id,s=t.groupId;let r=t.url;if(e)try{r=e.addDirectives(r)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`loading audio-track playlist ${i} "${t.name}" lang:${t.lang} group:${s}`),this.clearTimer(),this.hls.trigger(E.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:e||null})}}}const ea=500;class nf extends kn{constructor(e,t,i){super(e,t,i,"[subtitle-stream-controller]",W.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.ERROR,this.onError,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.ERROR,this.onError,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=F.IDLE,this.setInterval(ea),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:s}=t;if(this.fragPrevious=i,this.state=F.IDLE,!s)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let a;const o=i.start;for(let c=0;c<r.length;c++)if(o>=r[c].start&&o<=r[c].end){a=r[c];break}const l=i.start+i.duration;a?a.end=l:(a={start:o,end:l},r.push(a)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null)}onBufferFlushing(e,t){const{startOffset:i,endOffset:s}=t;if(i===0&&s!==Number.POSITIVE_INFINITY){const r=s-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=r){a.shift();continue}else if(a[o].start<r)a[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(i,r,W.SUBTITLE)}}onFragBuffered(e,t){if(!this.loadedmetadata&&t.frag.type===W.MAIN){var i;(i=this.media)!=null&&i.buffered.length&&(this.loadedmetadata=!0)}}onError(e,t){const i=t.frag;(i==null?void 0:i.type)===W.SUBTITLE&&(t.details===w.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==F.STOPPED&&(this.state=F.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Vo(this.levels,t)){this.levels=t.map(i=>new Ut(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const s=new Ut(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,W.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}const s=this.levels[this.currentTrackId];s!=null&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.setInterval(ea)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:s,levels:r}=this,{details:a,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=r[o];if(o>=r.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(a.live||(i=l.details)!=null&&i.live){const h=this.mainDetails;if(a.deltaUpdateFailed||!h)return;const d=h.fragments[0];if(!l.details)a.hasProgramDateTime&&h.hasProgramDateTime?(ts(a,h),c=a.fragments[0].start):d&&(c=d.start,cn(a,c));else{var u;c=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details),c===0&&d&&(c=d.start,cn(a,c))}}l.details=a,this.levelLastLoaded=l,o===s&&(!this.startFragRequested&&(this.mainDetails||!a.live)&&this.setStartPosition(this.mainDetails||a,c),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===F.IDLE&&(es(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,s=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&s!=null&&s.key&&s.iv&&s.method==="AES-128"){const a=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer).catch(o=>{throw r.trigger(E.ERROR,{type:z.MEDIA_ERROR,details:w.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const l=performance.now();r.trigger(E.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=F.IDLE})}}doTick(){if(!this.media){this.state=F.IDLE;return}if(this.state===F.IDLE){const{currentTrackId:e,levels:t}=this,i=t==null?void 0:t[e];if(!i||!t.length||!i.details)return;const{config:s}=this,r=this.getLoadPosition(),a=re.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,s.maxBufferHole),{end:o,len:l}=a,c=this.getFwdBufferInfo(this.media,W.MAIN),u=i.details,h=this.getMaxBufferLength(c==null?void 0:c.len)+u.levelTargetDuration;if(l>h)return;const d=u.fragments,f=d.length,g=u.edge;let m=null;const p=this.fragPrevious;if(o<g){const v=s.maxFragLookUpTolerance,x=o>g-v?0:v;m=es(p,d,Math.max(d[0].start,o),x),!m&&p&&p.start<d[0].start&&(m=d[0])}else m=d[f-1];if(!m)return;if(m=this.mapToInitFragWhenRequired(m),m.sn!=="initSegment"){const v=m.sn-u.startSN,x=d[v-1];x&&x.cc===m.cc&&this.fragmentTracker.getState(x)===pe.NOT_LOADED&&(m=x)}this.fragmentTracker.getState(m)===pe.NOT_LOADED&&this.loadFragment(m,i,o)}}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,i){this.fragCurrent=e,e.sn==="initSegment"?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,i))}get mediaBufferTimeRanges(){return new rf(this.tracksBuffered[this.currentTrackId]||[])}}class rf{constructor(e){this.buffered=void 0;const t=(i,s,r)=>{if(s=s>>>0,s>r-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${r})`);return e[s][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}class af extends In{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=ki(this.media.textTracks);for(let r=0;r<i.length;r++)if(i[r].mode==="hidden")t=i[r];else if(i[r].mode==="showing"){t=i[r];break}const s=this.findTrackForTextTrack(t);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),ki(this.media.textTracks).forEach(t=>{Pt(t)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:s,details:r}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||(s==null?void 0:s.length)!==(i==null?void 0:i.length)||i!=null&&i.some(a=>(s==null?void 0:s.indexOf(a))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(u=>!i||i.indexOf(u.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(u=>u.default)&&(this.selectDefaultTrack=!1),a.forEach((u,h)=>{u.id=h});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const u=Ye(o,a);if(u>-1)r=a[u];else{const h=Ye(o,this.tracks);r=this.tracks[h]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const c={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i==null?void 0:i.join(",")}" group-id`),this.hls.trigger(E.SUBTITLE_TRACKS_UPDATED,c),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId)}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<t.length;s++){const r=t[s];if(!(i&&!r.default||!i&&!e)&&(!e||Ot(r,e)))return s}if(e){for(let s=0;s<t.length;s++){const r=t[s];if($t(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const r=t[s];if($t(e.attrs,r.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if(dn(s,e))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===ie.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&Ot(e,i))return i;const s=Ye(e,this.tracksInGroup);if(s>-1){const r=this.tracksInGroup[s];return this.setSubtitleTrack(s),r}else{if(i)return null;{const r=Ye(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){const i=t.id,s=t.groupId;let r=t.url;if(e)try{r=e.addDirectives(r)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(E.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:e||null})}}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=ki(e.textTracks),i=this.currentTrack;let s;if(i&&(s=t.filter(r=>dn(i,r))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==s&&(r.mode="disabled")}),s){const r=this.subtitleDisplay?"showing":"hidden";s.mode!==r&&(s.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!H(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e]||null;if(this.trackId=e,this.currentTrack=s,this.toggleTrackModes(),!s){this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!s.details&&!s.details.live;if(e===this.trackId&&s===i&&r)return;this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:a,groupId:o="",name:l,type:c,url:u}=s;this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:c,url:u});const h=this.switchParams(s.url,i==null?void 0:i.details,s.details);this.loadPlaylist(h)}}class of{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t,i){const s=this.queues[t];s.push(e),s.length===1&&!i&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const i=new Promise(r=>{t=r}),s={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(s,e),i}executeNext(e){const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(s){C.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${s}`),i.onError(s);const r=this.buffers[e];r!=null&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const ta=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;class lf{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=i=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:i,mediaSource:s}=this;this.log("Media source opened"),i&&(i.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(E.MEDIA_ATTACHED,{media:i,mediaSource:s})),s&&s.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:s}=this;i!==s&&C.error(`Media element src was set while attaching MediaSource (${s} > ${i})`)},this.hls=e;const t="[buffer-controller]";this.appendSource=ph(vt(e.config.preferManagedMediaSource)),this.log=C.log.bind(C,t),this.warn=C.warn.bind(C,t),this.error=C.error.bind(C,t),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_APPENDING,this.onBufferAppending,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.BUFFER_EOS,this.onBufferEos,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.FRAG_PARSED,this.onFragParsed,this),e.on(E.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_APPENDING,this.onBufferAppending,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_EOS,this.onBufferEos,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.FRAG_PARSED,this.onFragParsed,this),e.off(E.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new of(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const i=this.media=t.media,s=vt(this.appendSource);if(i&&s){var r;const a=this.mediaSource=new s;this.log(`created media source: ${(r=a.constructor)==null?void 0:r.name}`),a.addEventListener("sourceopen",this._onMediaSourceOpen),a.addEventListener("sourceended",this._onMediaSourceEnded),a.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(a.addEventListener("startstreaming",this._onStartStreaming),a.addEventListener("endstreaming",this._onEndStreaming));const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");const l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&a instanceof l,ia(i),cf(i,o),i.load()}catch{i.src=o}else i.src=o;i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:i}=this;if(t){if(this.log("media source detaching"),t.readyState==="open")try{t.endOfStream()}catch(s){this.warn(`onMediaDetaching: ${s.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.removeEventListener("startstreaming",this._onStartStreaming),t.removeEventListener("endstreaming",this._onEndStreaming)),e&&(e.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(e.removeAttribute("src"),this.appendSource&&ia(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(E.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{this.resetBuffer(e)}),this._initSourceBuffer()}resetBuffer(e){const t=this.sourceBuffer[e];try{if(t){var i;this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}}catch(s){this.warn(`onBufferReset ${e}`,s)}}onBufferCodecs(e,t){const i=this.getSourceBufferTypes().length,s=Object.keys(t);if(s.forEach(a=>{if(i){const l=this.tracks[a];if(l&&typeof l.buffer.changeType=="function"){var o;const{id:c,codec:u,levelCodec:h,container:d,metadata:f}=t[a],g=br(l.codec,l.levelCodec),m=g==null?void 0:g.replace(ta,"$1");let p=br(u,h);const v=(o=p)==null?void 0:o.replace(ta,"$1");if(p&&m!==v){a.slice(0,5)==="audio"&&(p=ji(p,this.appendSource));const x=`${d};codecs=${p}`;this.appendChangeType(a,x),this.log(`switching codec ${g} to ${p}`),this.tracks[a]={buffer:l.buffer,codec:u,container:d,levelCodec:h,metadata:f,id:c}}}}else this.pendingTracks[a]=t[a]}),i)return;const r=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==r&&(this.log(`${r} bufferCodec event(s) expected ${s.join(",")}`),this.bufferCodecEventsExpected=r),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks()}appendChangeType(e,t){const{operationQueue:i}=this,s={execute:()=>{const r=this.sourceBuffer[e];r&&(this.log(`changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),i.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:r=>{this.warn(`Failed to change ${e} SourceBuffer type`,r)}};i.append(s,e,!!this.pendingTracks[e])}onBufferAppending(e,t){const{hls:i,operationQueue:s,tracks:r}=this,{data:a,type:o,frag:l,part:c,chunkMeta:u}=t,h=u.buffering[o],d=self.performance.now();h.start=d;const f=l.stats.buffering,g=c?c.stats.buffering:null;f.start===0&&(f.start=d),g&&g.start===0&&(g.start=d);const m=r.audio;let p=!1;o==="audio"&&(m==null?void 0:m.container)==="audio/mpeg"&&(p=!this.lastMpegAudioChunk||u.id===1||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);const v=l.start,x={execute:()=>{if(h.executeStart=self.performance.now(),p){const S=this.sourceBuffer[o];if(S){const b=v-S.timestampOffset;Math.abs(b)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${v} (delta: ${b}) sn: ${l.sn})`),S.timestampOffset=v)}}this.appendExecutor(a,o)},onStart:()=>{},onComplete:()=>{const S=self.performance.now();h.executeEnd=h.end=S,f.first===0&&(f.first=S),g&&g.first===0&&(g.first=S);const{sourceBuffer:b}=this,T={};for(const L in b)T[L]=re.getBuffered(b[L]);this.appendErrors[o]=0,o==="audio"||o==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(E.BUFFER_APPENDED,{type:o,frag:l,part:c,chunkMeta:u,parent:l.type,timeRanges:T})},onError:S=>{const b={type:z.MEDIA_ERROR,parent:l.type,details:w.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:l,part:c,chunkMeta:u,error:S,err:S,fatal:!1};if(S.code===DOMException.QUOTA_EXCEEDED_ERR)b.details=w.BUFFER_FULL_ERROR;else{const T=++this.appendErrors[o];b.details=w.BUFFER_APPEND_ERROR,this.warn(`Failed ${T}/${i.config.appendErrorMaxRetry} times to append segment in "${o}" sourceBuffer`),T>=i.config.appendErrorMaxRetry&&(b.fatal=!0)}i.trigger(E.ERROR,b)}};s.append(x,o,!!this.pendingTracks[o])}onBufferFlushing(e,t){const{operationQueue:i}=this,s=r=>({execute:this.removeExecutor.bind(this,r,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(E.BUFFER_FLUSHED,{type:r})},onError:a=>{this.warn(`Failed to remove from ${r} SourceBuffer`,a)}});t.type?i.append(s(t.type),t.type):this.getSourceBufferTypes().forEach(r=>{i.append(s(r),r)})}onFragParsed(e,t){const{frag:i,part:s}=t,r=[],a=s?s.elementaryStreams:i.elementaryStreams;a[se.AUDIOVIDEO]?r.push("audiovideo"):(a[se.AUDIO]&&r.push("audio"),a[se.VIDEO]&&r.push("video"));const o=()=>{const l=self.performance.now();i.stats.buffering.end=l,s&&(s.stats.buffering.end=l);const c=s?s.stats:i.stats;this.hls.trigger(E.FRAG_BUFFERED,{frag:i,part:s,stats:c,id:i.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,r)}onFragChanged(e,t){this.trimBuffers()}onBufferEos(e,t){this.getSourceBufferTypes().reduce((s,r)=>{const a=this.sourceBuffer[r];return a&&(!t.type||t.type===r)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${r} sourceBuffer now EOS`))),s&&!!(!a||a.ended)},!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(r=>{const a=this.sourceBuffer[r];a&&(a.ending=!1)});const{mediaSource:s}=this;if(!s||s.readyState!=="open"){s&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${s.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),s.endOfStream()}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.getSourceBufferTypes().length)return;const r=e.config,a=i.currentTime,o=t.levelTargetDuration,l=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(H(l)&&l>0){const c=Math.max(l,o),u=Math.floor(a/o)*o-c;this.flushBackBuffer(a,o,u)}if(H(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const c=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),u=Math.max(c,o),h=Math.floor(a/o)*o+u;this.flushFrontBuffer(a,o,h)}}flushBackBuffer(e,t,i){const{details:s,sourceBuffer:r}=this;this.getSourceBufferTypes().forEach(o=>{const l=r[o];if(l){const c=re.getBuffered(l);if(c.length>0&&i>c.start(0)){if(this.hls.trigger(E.BACK_BUFFER_REACHED,{bufferEnd:i}),s!=null&&s.live)this.hls.trigger(E.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l.ended&&c.end(c.length-1)-e<t*2){this.log(`Cannot flush ${o} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:o})}}})}flushFrontBuffer(e,t,i){const{sourceBuffer:s}=this;this.getSourceBufferTypes().forEach(a=>{const o=s[a];if(o){const l=re.getBuffered(o),c=l.length;if(c<2)return;const u=l.start(c-1),h=l.end(c-1);if(i>u||e>=u&&e<=h)return;if(o.ended&&e-h<2*t){this.log(`Cannot flush ${a} front buffer while SourceBuffer is in ended state`);return}this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:a})}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:e,hls:t,media:i,mediaSource:s}=this,r=e.fragments[0].start+e.totalduration,a=i.duration,o=H(s.duration)?s.duration:0;e.live&&t.config.liveDurationInfinity?(s.duration=1/0,this.updateSeekableRange(e)):(r>o&&r>a||!H(a))&&(this.log(`Updating Media Source duration to ${r.toFixed(3)}`),s.duration=r)}updateSeekableRange(e){const t=this.mediaSource,i=e.fragments;if(i.length&&e.live&&t!=null&&t.setLiveSeekableRange){const r=Math.max(0,i[0].start),a=Math.max(r,r+e.totalduration);this.log(`Media Source duration is set to ${t.duration}. Setting seekable range to ${r}-${a}.`),t.setLiveSeekableRange(r,a)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:i}=this,s=Object.keys(i).length;if(s&&(!e||s===2||"audiovideo"in i)){this.createSourceBuffers(i),this.pendingTracks={};const r=this.getSourceBufferTypes();if(r.length)this.hls.trigger(E.BUFFER_CREATED,{tracks:this.tracks}),r.forEach(a=>{t.executeNext(a)});else{const a=new Error("could not create source buffer for media codec(s)");this.hls.trigger(E.ERROR,{type:z.MEDIA_ERROR,details:w.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:a,reason:a.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const r in e)if(!t[r]){var s;const a=e[r];if(!a)throw Error(`source buffer exists for track ${r}, however track does not`);let o=((s=a.levelCodec)==null?void 0:s.indexOf(","))===-1?a.levelCodec:a.codec;o&&r.slice(0,5)==="audio"&&(o=ji(o,this.appendSource));const l=`${a.container};codecs=${o}`;this.log(`creating sourceBuffer(${l})`);try{const c=t[r]=i.addSourceBuffer(l),u=r;this.addBufferListener(u,"updatestart",this._onSBUpdateStart),this.addBufferListener(u,"updateend",this._onSBUpdateEnd),this.addBufferListener(u,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(u,"bufferedchange",(h,d)=>{const f=d.removedRanges;f!=null&&f.length&&this.hls.trigger(E.BUFFER_FLUSHED,{type:r})}),this.tracks[r]={buffer:c,codec:o,container:a.container,levelCodec:a.levelCodec,metadata:a.metadata,id:a.id}}catch(c){this.error(`error while trying to add sourceBuffer: ${c.message}`),this.hls.trigger(E.ERROR,{type:z.MEDIA_ERROR,details:w.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:c,sourceBufferName:r,mimeType:l})}}}get mediaSrc(){var e,t;const i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i==null?void 0:i.src}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const{operationQueue:i}=this;i.current(e).onComplete(),i.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){var i;const s=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${s}`,t),this.hls.trigger(E.ERROR,{type:z.MEDIA_ERROR,details:w.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});const r=this.operationQueue.current(e);r&&r.onError(s)}removeExecutor(e,t,i){const{media:s,mediaSource:r,operationQueue:a,sourceBuffer:o}=this,l=o[e];if(!s||!r||!l){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),a.shiftAndExecuteNext(e);return}const c=H(s.duration)?s.duration:1/0,u=H(r.duration)?r.duration:1/0,h=Math.max(0,t),d=Math.min(i,c,u);d>h&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${h},${d}] from the ${e} SourceBuffer`),l.remove(h,d)):a.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.sourceBuffer[t];if(!i){if(!this.pendingTracks[t])throw new Error(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);return}i.ended=!1,i.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length){this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}const{operationQueue:i}=this,s=t.map(r=>i.appendBlocker(r));Promise.all(s).then(()=>{e(),t.forEach(r=>{const a=this.sourceBuffer[r];a!=null&&a.updating||i.shiftAndExecuteNext(r)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,i){const s=this.sourceBuffer[e];if(!s)return;const r=i.bind(this,e);this.listeners[e].push({event:t,listener:r}),s.addEventListener(t,r)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach(i=>{t.removeEventListener(i.event,i.listener)})}}function ia(n){const e=n.querySelectorAll("source");[].slice.call(e).forEach(t=>{n.removeChild(t)})}function cf(n,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,n.appendChild(t)}const uf={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Ho=n=>String.fromCharCode(uf[n]||n),Fe=15,Ze=100,hf={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},df={17:2,18:4,21:6,22:8,23:10,19:13,20:15},ff={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},gf={25:2,26:4,29:6,30:8,31:10,27:13,28:15},mf=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class pf{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;C.log(`${this.time} [${e}] ${i}`)}}}const ct=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class Ko{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){const s=t[i];e.hasOwnProperty(s)&&(this[s]=e[s])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Ef{constructor(){this.uchar=" ",this.penState=new Ko}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class vf{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Ko,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ze;t++)this.chars.push(new Ef);this.logger=e}equals(e){for(let t=0;t<Ze;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Ze;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Ze;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Ze&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ze)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Ho(e);if(this.pos>=Ze){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Ze;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let i=0;i<Ze;i++){const s=this.chars[i].uchar;s!==" "&&(t=!1),e.push(s)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class Bs{constructor(e){this.rows=[],this.currRow=Fe-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Fe;t++)this.rows.push(new vf(e));this.logger=e}reset(){for(let e=0;e<Fe;e++)this.rows[e].clear();this.currRow=Fe-1}equals(e){let t=!0;for(let i=0;i<Fe;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<Fe;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Fe;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+JSON.stringify(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<Fe;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[r].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(a.rows[r+c])}}this.currRow=t;const i=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,a=Math.max(r-1,0);i.setCursor(e.indent),e.color=i.chars[a].penState.foreground}const s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+JSON.stringify(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",s=-1;for(let r=0;r<Fe;r++){const a=this.rows[r].getTextString();a&&(s=r+1,e?t.push("Row "+s+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(` `)),i}getTextAndFormat(){return this.rows}}class sa{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Bs(i),this.nonDisplayedMemory=new Bs(i),this.lastOutputScreen=new Bs(i),this.currRollUpRow=this.displayedMemory.rows[Fe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Fe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=s[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class na{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=yf(),this.logger=void 0;const s=this.logger=new pf;this.channels=[null,new sa(e,t,s),new sa(e+1,i,s)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){const s=t[i]&127,r=t[i+1]&127;let a=!1,o=null;if(s===0&&r===0)continue;this.logger.log(3,()=>"["+ct([t[i],t[i+1]])+"] -> ("+ct([s,r])+")");const l=this.cmdHistory;if(s>=16&&s<=31){if(xf(s,r,l)){Ai(null,null,l),this.logger.log(3,()=>"Repeated command ("+ct([s,r])+") is dropped");continue}Ai(s,r,this.cmdHistory),a=this.parseCmd(s,r),a||(a=this.parseMidrow(s,r)),a||(a=this.parsePAC(s,r)),a||(a=this.parseBackgroundAttributes(s,r))}else Ai(null,null,l);if(!a&&(o=this.parseChars(s,r),o)){const u=this.currentChannel;u&&u>0?this.channels[u].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+ct([s,r])+" orig: "+ct([t[i],t[i+1]]))}}parseCmd(e,t){const i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=33&&t<=35;if(!(i||s))return!1;const r=e===20||e===21||e===23?1:2,a=this.channels[r];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[i];return s?(s.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+ct([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const s=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(s||r))return!1;const a=e<=23?1:2;t>=64&&t<=95?i=a===1?hf[e]:ff[e]:i=a===1?df[e]:gf[e];const o=this.channels[a];return o?(o.setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!0):!1}interpretPAC(e,t){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,s.underline=(i&1)===1,i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=Math.floor((i-16)/2)*4,s}parseChars(e,t){let i,s=null,r=null;if(e>=25?(i=2,r=e-8):(i=1,r=e),r>=17&&r<=19){let a;r===17?a=t+80:r===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+Ho(a)+"' in channel "+i),s=[a]}else e>=32&&e<=127&&(s=t===0?[e]:[e,t]);return s&&this.logger.log(3,()=>"Char codes = "+ct(s).join(",")),s}parseBackgroundAttributes(e,t){const i=(e===16||e===24)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=45&&t<=47;if(!(i||s))return!1;let r;const a={};e===16||e===24?(r=Math.floor((t-32)/2),a.background=mf[r],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Ai(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const i=this.channels[t];i&&i.cueSplitAtTime(e)}}}function Ai(n,e,t){t.a=n,t.b=e}function xf(n,e,t){return t.a===n&&t.b===e}function yf(){return{a:null,b:null}}class Ci{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Nn=function(){if(Bt!=null&&Bt.VTTCue)return self.VTTCue;const n=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const c=l.toLowerCase();return~o.indexOf(c)?c:!1}function i(o){return t(n,o)}function s(o){return t(e,o)}function r(o,...l){let c=1;for(;c<arguments.length;c++){const u=arguments[c];for(const h in u)o[h]=u[h]}return o}function a(o,l,c){const u=this,h={enumerable:!0};u.hasBeenReset=!1;let d="",f=!1,g=o,m=l,p=c,v=null,x="",S=!0,b="auto",T="start",L=50,A="middle",P=50,D="middle";Object.defineProperty(u,"id",r({},h,{get:function(){return d},set:function(I){d=""+I}})),Object.defineProperty(u,"pauseOnExit",r({},h,{get:function(){return f},set:function(I){f=!!I}})),Object.defineProperty(u,"startTime",r({},h,{get:function(){return g},set:function(I){if(typeof I!="number")throw new TypeError("Start time must be set to a number.");g=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",r({},h,{get:function(){return m},set:function(I){if(typeof I!="number")throw new TypeError("End time must be set to a number.");m=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",r({},h,{get:function(){return p},set:function(I){p=""+I,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",r({},h,{get:function(){return v},set:function(I){v=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",r({},h,{get:function(){return x},set:function(I){const k=i(I);if(k===!1)throw new SyntaxError("An invalid or illegal string was specified.");x=k,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",r({},h,{get:function(){return S},set:function(I){S=!!I,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",r({},h,{get:function(){return b},set:function(I){if(typeof I!="number"&&I!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");b=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",r({},h,{get:function(){return T},set:function(I){const k=s(I);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");T=k,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",r({},h,{get:function(){return L},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");L=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",r({},h,{get:function(){return A},set:function(I){const k=s(I);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");A=k,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",r({},h,{get:function(){return P},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");P=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",r({},h,{get:function(){return D},set:function(I){const k=s(I);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");D=k,this.hasBeenReset=!0}})),u.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class Tf{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Wo(n){function e(i,s,r,a){return(i|0)*3600+(s|0)*60+(r|0)+parseFloat(a||0)}const t=n.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}let Sf=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let s=0;s<i.length;++s)if(t===i[s]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}};function Yo(n,e,t,i){const s=i?n.split(i):[n];for(const r in s){if(typeof s[r]!="string")continue;const a=s[r].split(t);if(a.length!==2)continue;const o=a[0],l=a[1];e(o,l)}}const fn=new Nn(0,0,""),Ri=fn.align==="middle"?"middle":"center";function bf(n,e,t){const i=n;function s(){const o=Wo(n);if(o===null)throw new Error("Malformed timestamp: "+i);return n=n.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,l){const c=new Sf;Yo(o,function(d,f){let g;switch(d){case"region":for(let m=t.length-1;m>=0;m--)if(t[m].id===f){c.set(d,t[m].region);break}break;case"vertical":c.alt(d,f,["rl","lr"]);break;case"line":g=f.split(","),c.integer(d,g[0]),c.percent(d,g[0])&&c.set("snapToLines",!1),c.alt(d,g[0],["auto"]),g.length===2&&c.alt("lineAlign",g[1],["start",Ri,"end"]);break;case"position":g=f.split(","),c.percent(d,g[0]),g.length===2&&c.alt("positionAlign",g[1],["start",Ri,"end","line-left","line-right","auto"]);break;case"size":c.percent(d,f);break;case"align":c.alt(d,f,["start",Ri,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let u=c.get("line","auto");u==="auto"&&fn.line===-1&&(u=-1),l.line=u,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",Ri);let h=c.get("position","auto");h==="auto"&&fn.position===50&&(h=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=h}function a(){n=n.replace(/^\s+/,"")}if(a(),e.startTime=s(),a(),n.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);n=n.slice(3),a(),e.endTime=s(),a(),r(n,e)}function qo(n){return n.replace(/<br(?: \/)?>/gi,` `)}class Lf{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Tf,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let r=t.buffer,a=0;for(r=qo(r);a<r.length&&r[a]!=="\r"&&r[a]!==` `;)++a;const o=r.slice(0,a);return r[a]==="\r"&&++a,r[a]===` `&&++a,t.buffer=r.slice(a),o}function s(r){Yo(r,function(a,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=i();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:r=i(),t.state){case"HEADER":/:/.test(r)?s(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new Nn(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{bf(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=` `),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=` `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const Af=/\r\n|\n\r|\n|\r/g,Us=function(e,t,i=0){return e.slice(i,i+t.length)===t},Cf=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!H(t)||!H(i)||!H(s)||!H(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*s,t+=60*60*1e3*r,t},$s=function(e){let t=5381,i=e.length;for(;i;)t=t*33^e.charCodeAt(--i);return(t>>>0).toString()};function Bn(n,e,t){return $s(n.toString())+$s(e.toString())+$s(t)}const Rf=function(e,t,i){let s=e[t],r=e[s.prevCC];if(!r||!r.new&&s.new){e.ccOffset=e.presentationOffset=s.start,s.new=!1;return}for(;(a=r)!=null&&a.new;){var a;e.ccOffset+=s.start-r.start,s.new=!1,s=r,r=e[s.prevCC]}e.presentationOffset=i};function If(n,e,t,i,s,r,a){const o=new Lf,l=ze(new Uint8Array(n)).trim().replace(Af,` `).split(` `),c=[],u=e?Kd(e.baseTime,e.timescale):0;let h="00:00.000",d=0,f=0,g,m=!0;o.oncue=function(p){const v=t[i];let x=t.ccOffset;const S=(d-u)/9e4;if(v!=null&&v.new&&(f!==void 0?x=t.ccOffset=v.start:Rf(t,i,S)),S){if(!e){g=new Error("Missing initPTS for VTT MPEGTS");return}x=S-t.presentationOffset}const b=p.endTime-p.startTime,T=_e((p.startTime+x-f)*9e4,s*9e4)/9e4;p.startTime=Math.max(T,0),p.endTime=Math.max(T+b,0);const L=p.text.trim();p.text=decodeURIComponent(encodeURIComponent(L)),p.id||(p.id=Bn(p.startTime,p.endTime,L)),p.endTime>0&&c.push(p)},o.onparsingerror=function(p){g=p},o.onflush=function(){if(g){a(g);return}r(c)},l.forEach(p=>{if(m)if(Us(p,"X-TIMESTAMP-MAP=")){m=!1,p.slice(16).split(",").forEach(v=>{Us(v,"LOCAL:")?h=v.slice(6):Us(v,"MPEGTS:")&&(d=parseInt(v.slice(7)))});try{f=Cf(h)/1e3}catch(v){g=v}return}else p===""&&(m=!1);o.parse(p+` `)}),o.flush()}const Gs="stpp.ttml.im1t",zo=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Xo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,wf={left:"start",center:"center",right:"end",start:"start",end:"end"};function ra(n,e,t,i){const s=j(new Uint8Array(n),["mdat"]);if(s.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const r=s.map(o=>ze(o)),a=Hd(e.baseTime,1,e.timescale);try{r.forEach(o=>t(Df(o,a)))}catch(o){i(o)}}function Df(n,e){const s=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(r).reduce((h,d)=>(h[d]=s.getAttribute(`ttp:${d}`)||r[d],h),{}),o=s.getAttribute("xml:space")!=="preserve",l=aa(Vs(s,"styling","style")),c=aa(Vs(s,"layout","region")),u=Vs(s,"body","[begin]");return[].map.call(u,h=>{const d=jo(h,o);if(!d||!h.hasAttribute("begin"))return null;const f=Ks(h.getAttribute("begin"),a),g=Ks(h.getAttribute("dur"),a);let m=Ks(h.getAttribute("end"),a);if(f===null)throw oa(h);if(m===null){if(g===null)throw oa(h);m=f+g}const p=new Nn(f-e,m-e,d);p.id=Bn(p.startTime,p.endTime,p.text);const v=c[h.getAttribute("region")],x=l[h.getAttribute("style")],S=kf(v,x,l),{textAlign:b}=S;if(b){const T=wf[b];T&&(p.lineAlign=T),p.align=b}return de(p,S),p}).filter(h=>h!==null)}function Vs(n,e,t){const i=n.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function aa(n){return n.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function jo(n,e){return[].slice.call(n.childNodes).reduce((t,i,s)=>{var r;return i.nodeName==="br"&&s?t+` `:(r=i.childNodes)!=null&&r.length?jo(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function kf(n,e,t){const i="http://www.w3.org/ns/ttml#styling";let s=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=n!=null&&n.hasAttribute("style")?n.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(s=t[a]),r.reduce((o,l)=>{const c=Hs(e,i,l)||Hs(n,i,l)||Hs(s,i,l);return c&&(o[l]=c),o},{})}function Hs(n,e,t){return n&&n.hasAttributeNS(e,t)?n.getAttributeNS(e,t):null}function oa(n){return new Error(`Could not parse ttml timestamp ${n}`)}function Ks(n,e){if(!n)return null;let t=Wo(n);return t===null&&(zo.test(n)?t=_f(n,e):Xo.test(n)&&(t=Pf(n,e))),t}function _f(n,e){const t=zo.exec(n),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 Pf(n,e){const t=Xo.exec(n),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}class Of{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ca(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const e=new Ci(this,"textTrack1"),t=new Ci(this,"textTrack2"),i=new Ci(this,"textTrack3"),s=new Ci(this,"textTrack4");this.cea608Parser1=new na(1,e,t),this.cea608Parser2=new na(3,i,s)}}addCues(e,t,i,s,r){let a=!1;for(let o=r.length;o--;){const l=r[o],c=Ff(l[0],l[1],t,i);if(c>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),a=!0,c/(i-t)>.5))return}if(a||r.push([t,i]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,i,s)}else{const o=this.Cues.newCue(null,t,i,s);this.hls.trigger(E.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:r}){const{unparsedVttFrags:a}=this;i==="main"&&(this.initPTS[t.cc]={baseTime:s,timescale:r}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(E.FRAG_LOADED,o)}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){const r=i.textTracks[s];if(la(r,{name:e,lang:t,attrs:{}}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:s}=this,{label:r,languageCode:a}=t[e],o=this.getExistingTrack(r,a);if(o)i[e]=o,Pt(i[e]),po(i[e],s);else{const l=this.createTextTrack("captions",r,a);l&&(l[e]=!0,i[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i=t.label,s={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,t,i){const s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach(t=>{Pt(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ca(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let i=0;i<t.length;i++)Pt(t[i])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],s=i.some(r=>r.textCodec===Gs);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Vo(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const a=this.media,o=a?ki(a.textTracks):null;if(this.tracks.forEach((l,c)=>{let u;if(o){let h=null;for(let d=0;d<o.length;d++)if(o[d]&&la(o[d],l)){h=o[d],o[d]=null;break}h&&(u=h)}if(u)Pt(u);else{const h=Zo(l);u=this.createTextTrack(h,l.name,l.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),o!=null&&o.length){const l=o.filter(c=>c!==null).map(c=>c.label);l.length&&C.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;const r=`textTrack${s[1]}`,a=this.captionsProperties[r];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===W.MAIN){var i,s;const{cea608Parser1:r,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:c}=t.frag,u=(i=(s=t.part)==null?void 0:s.index)!=null?i:-1;r&&a&&(c!==o+1||c===o&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=u}}onFragLoaded(e,t){const{frag:i,payload:s}=t;if(i.type===W.SUBTITLE)if(s.byteLength){const r=i.decryptdata,a="stats"in t;if(r==null||!r.encrypted||a){const o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===Gs?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;ra(t,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),i.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{C.log(`Failed to parse IMSC1: ${s}`),i.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:s})})}_parseVTTs(e){var t;const{frag:i,payload:s}=e,{initPTS:r,unparsedVttFrags:a}=this,o=r.length-1;if(!r[i.cc]&&o===-1){a.push(e);return}const l=this.hls,c=(t=i.initSegment)!=null&&t.data?Pe(i.initSegment.data,new Uint8Array(s)):s;If(c,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,u=>{this._appendCues(u,i.level),l.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},u=>{const h=u.message==="Missing initPTS for VTT MPEGTS";h?a.push(e):this._fallbackToIMSC1(i,s),C.log(`Failed to parse VTT cue: ${u}`),!(h&&o>i.cc)&&l.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:u})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||ra(t,this.initPTS[e.cc],()=>{i.textCodec=Gs,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[t];if(!s||s.mode==="disabled")return;e.forEach(r=>Eo(s,r))}else{const s=this.tracks[t];if(!s)return;const r=s.default?"default":"subtitles"+t;i.trigger(E.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===W.SUBTITLE&&this.onFragLoaded(E.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){this.initCea608Parsers();const{cea608Parser1:i,cea608Parser2:s}=this;if(!this.enabled||!i||!s)return;const{frag:r,samples:a}=t;if(!(r.type===W.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let o=0;o<a.length;o++){const l=a[o].bytes;if(l){const c=this.extractCea608Data(l);i.addData(a[o].pts,c[0]),s.addData(a[o].pts,c[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:s,type:r}){const{media:a}=this;if(!(!a||a.currentTime<i)){if(!r||r==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>an(o[l],t,i))}if(this.config.renderTextTracksNatively&&t===0&&s!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>an(o[l],t,s))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let s=2;for(let r=0;r<i;r++){const a=e[s++],o=127&e[s++],l=127&e[s++];if(o===0&&l===0)continue;if((4&a)!==0){const u=3&a;(u===0||u===1)&&(t[u].push(o),t[u].push(l))}}return t}}function Zo(n){return n.characteristics&&/transcribes-spoken-dialog/gi.test(n.characteristics)&&/describes-music-and-sound/gi.test(n.characteristics)?"captions":"subtitles"}function la(n,e){return!!n&&n.kind===Zo(e)&&dn(e,n)}function Ff(n,e,t,i){return Math.min(e,i)-Math.max(n,t)}function ca(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class Un{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&H(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&C.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((s,r)=>this.isLevelAllowed(s)&&r<=e);return this.clientRect=null,Un.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return e}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const s=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let r=e.length-1;const a=Math.max(t,i);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=a||l.height>=a)&&s(l,e[o+1])){r=o;break}}return r}}class Mf{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const s=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){const s=performance.now();if(t){if(this.lastTime){const r=s-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/r,c=this.hls;if(c.trigger(E.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>c.config.fpsDroppedMonitoringThreshold*o){let u=c.currentLevel;C.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=u)&&(u=u-1,c.trigger(E.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:c.currentLevel}),c.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}const Ii="[eme]";class Ft{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=Ft.CDMCleanupPromise?[Ft.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=C.debug.bind(C,Ii),this.log=C.log.bind(C,Ii),this.warn=C.warn.bind(C,Ii),this.error=C.error.bind(C,Ii),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(E.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(E.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,s=t[e];if(s)return s.licenseUrl;if(e===ae.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,s=t.map(a=>a.audioCodec).filter(i),r=t.map(a=>a.videoCodec).filter(i);return s.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,o)=>{const l=c=>{const u=c.shift();this.getMediaKeysPromise(u,s,r).then(h=>a({keySystem:u,mediaKeys:h})).catch(h=>{c.length?l(c):h instanceof ke?o(h):o(new ke({type:z.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return io===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return i(e,t)}getMediaKeysPromise(e,t,i){const s=Gu(e,t,i,this.config.drmSystemOptions),r=this.keySystemAccessPromises[e];let a=r==null?void 0:r.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(s)}`),a=this.requestMediaKeySystemAccess(e,s);const o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const c=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=l.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),c.then(h=>h?this.setMediaKeysServerCertificate(u,e,h):u))),o.mediaKeys.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),o.mediaKeys})}return a.then(()=>r.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${Ve.hexDump(e.keyId||[])}`);const s=i.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),s=this.getKeyIdString(t),r="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,r,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 Ve.hexDump(e.keyId)}updateKeySession(e,t){var i;const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyID ${Ve.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])} } (data length: ${t&&t.byteLength})`),s.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,i)=>{const s=Cs(this.config),r=e.map(mr).filter(a=>!!a&&s.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(r).then(({keySystem:a})=>{const o=Er(a);o?t(o):i(new Error(`Unable to find format for key-system "${a}"`))}).catch(i)})}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),s=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${s}`);let r=this.keyIdToKeySessionPromise[i];return r||(r=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 ${s}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:t});return this.generateRequestWithPreferredKeySession(l,"cenc",t.pssh,"playlist-key")}))),r.catch(a=>this.handleError(a))),r}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof ke?this.hls.trigger(E.ERROR,e.data):this.hls.trigger(E.ERROR,{type:z.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const s=mr(e.keyFormat),r=s?[s]:Cs(this.config);return this.attemptKeySystemAccess(r)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Cs(this.config)),e.length===0)throw new ke({type:z.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:i}=e,s=`"${e.type}" event: init data type: "${t}"`;if(this.debug(s),i===null)return;let r,a;if(t==="sinf"&&this.config.drmSystems[ae.FAIRPLAY]){const h=fe(new Uint8Array(i));try{const d=Ln(JSON.parse(h).sinf),f=uo(new Uint8Array(d));if(!f)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");r=f.subarray(8,24),a=ae.FAIRPLAY}catch(d){this.warn(`${s} Failed to parse sinf: ${d}`);return}}else{const h=dh(i),d=h.filter(f=>f.systemId===Zt.WIDEVINE)[0];if(!d){h.length===0||h.some(f=>!f.systemId)?this.warn(`${s} contains incomplete or invalid pssh data`):this.log(`ignoring ${s} for ${h.map(f=>pr(f.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(a=pr(d.systemId),d.version===0&&d.data){const f=d.data.length-22;r=d.data.subarray(f,f+16)}}if(!a||!r)return;const o=Ve.hexDump(r),{keyIdToKeySessionPromise:l,mediaKeySessions:c}=this;let u=l[o];for(let h=0;h<c.length;h++){const d=c[h],f=d.decryptdata;if(!f.keyId)continue;const g=Ve.hexDump(f.keyId);if(o===g||f.uri.replace(/-/g,"").indexOf(o)!==-1){if(u=l[g],f.pssh)break;delete l[g],f.pssh=new Uint8Array(i),f.keyId=r,u=l[o]=u.then(()=>this.generateRequestWithPreferredKeySession(d,t,i,"encrypted-event-key-match"));break}}u||(u=l[o]=this.getKeySystemSelectionPromise([a]).then(({keySystem:h,mediaKeys:d})=>{var f;this.throwIfDestroyed();const g=new hi("ISO-23001-7",o,(f=Er(h))!=null?f:"");return g.pssh=new Uint8Array(i),g.keyId=r,this.attemptSetMediaKeys(h,d).then(()=>{this.throwIfDestroyed();const m=this.createMediaKeySessionContext({decryptdata:g,keySystem:h,mediaKeys:d});return this.generateRequestWithPreferredKeySession(m,t,i,"encrypted-event-no-match")})})),u.catch(h=>this.handleError(h))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const s=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(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>i.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,i,s){var r,a;const o=(r=this.config.drmSystems)==null||(a=r[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const g=o.call(this.hls,t,i,e);if(!g)throw new Error("Invalid response from configured generateRequest filter");t=g.initDataType,i=e.decryptdata.pssh=g.initData?new Uint8Array(g.initData):null}catch(g){var l;if(this.warn(g.message),(l=this.hls)!=null&&l.config.debug)throw g}if(i===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);const c=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${s}": ${c} (init data type: ${t} length: ${i?i.byteLength:null})`);const u=new Mn,h=e._onmessage=g=>{const m=e.mediaKeysSession;if(!m){u.emit("error",new Error("invalid state"));return}const{messageType:p,message:v}=g;this.log(`"${p}" message event for session "${m.sessionId}" message size: ${v.byteLength}`),p==="license-request"||p==="license-renewal"?this.renewLicense(e,v).catch(x=>{this.handleError(x),u.emit("error",x)}):p==="license-release"?e.keySystem===ae.FAIRPLAY&&(this.updateKeySession(e,nn("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${p}"`)},d=e._onkeystatuseschange=g=>{if(!e.mediaKeysSession){u.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const p=e.keyStatus;u.emit("keyStatus",p),p==="expired"&&(this.warn(`${e.keySystem} expired for key ${c}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",h),e.mediaKeysSession.addEventListener("keystatuseschange",d);const f=new Promise((g,m)=>{u.on("error",m),u.on("keyStatus",p=>{p.startsWith("usable")?g():p==="output-restricted"?m(new ke({type:z.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):p==="internal-error"?m(new ke({type:z.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${p}"`)):p==="expired"?m(new Error("key expired while generating request")):this.warn(`unhandled key status change "${p}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var g;this.log(`Request generated for key-session "${(g=e.mediaKeysSession)==null?void 0:g.sessionId}" keyId: ${c}`)}).catch(g=>{throw new ke({type:z.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_SESSION,error:g,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>{throw u.removeAllListeners(),this.removeSession(e),g}).then(()=>(u.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${Ve.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${Ve.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,i=t.loader,s=new i(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:r},c=t.certLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,f,g,m)=>{a(d.data)},onError:(d,f,g,m)=>{o(new ke({type:z.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:Ee({url:l.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,g)=>{o(new ke({type:z.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,f,g)=>{o(new Error("aborted"))}};s.load(l,u,h)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((s,r)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),s(e)}).catch(a=>{r(new ke({type:z.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(s=>{throw new ke({type:z.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:s,fatal:!0},s.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const s=new DOMParser().parseFromString(i,"application/xml"),r=s.querySelectorAll("HttpHeader");if(r.length>0){let u;for(let h=0,d=r.length;h<d;h++){var a,o;u=r[h];const f=(a=u.querySelector("name"))==null?void 0:a.textContent,g=(o=u.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}const l=s.querySelector("Challenge"),c=l==null?void 0:l.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return nn(atob(c))}setupLicenseXHR(e,t,i,s){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,i,s)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),r.call(this.hls,e,t,i,s)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||s})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((s,r)=>{const a=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,a,e)}catch(u){this.error(u)}s(l)}else{const l=i.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)r(new ke({type:z.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const u=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(s,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:c})=>{e.keySystem==ae.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(l,c)),l.send(c)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},hi.clearKeyUriToKeyIdMap();const i=t.length;Ft.CDMCleanupPromise=Promise.all(t.map(s=>this.removeSession(s)).concat(e==null?void 0:e.setMediaKeys(null).catch(s=>{this.log(`Could not clear media keys: ${s}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(s=>{this.log(`Could not close sessions and clear media keys: ${s}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((s,r)=>(s.indexOf(r.keyFormat)===-1&&s.push(r.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const s=this.mediaKeySessions.indexOf(e);return s>-1&&this.mediaKeySessions.splice(s,1),t.remove().catch(r=>{this.log(`Could not remove session: ${r}`)}).then(()=>t.close()).catch(r=>{this.log(`Could not close session: ${r}`)})}}}Ft.CDMCleanupPromise=void 0;class ke extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}var ye;(function(n){n.MANIFEST="m",n.AUDIO="a",n.VIDEO="v",n.MUXED="av",n.INIT="i",n.CAPTION="c",n.TIMED_TEXT="tt",n.KEY="k",n.OTHER="o"})(ye||(ye={}));var gn;(function(n){n.DASH="d",n.HLS="h",n.SMOOTH="s",n.OTHER="o"})(gn||(gn={}));var mt;(function(n){n.OBJECT="CMCD-Object",n.REQUEST="CMCD-Request",n.SESSION="CMCD-Session",n.STATUS="CMCD-Status"})(mt||(mt={}));const Nf={[mt.OBJECT]:["br","d","ot","tb"],[mt.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[mt.SESSION]:["cid","pr","sf","sid","st","v"],[mt.STATUS]:["bs","rtp"]};class Gt{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(i=>i instanceof Gt?i:new Gt(i))),this.value=e,this.params=t}}class Qo{constructor(e){this.description=void 0,this.description=e}}const Bf="Dict";function Uf(n){return Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":typeof n=="object"?JSON.stringify(n):String(n)}function $f(n,e,t,i){return new Error(`failed to ${n} "${Uf(e)}" as ${t}`,{cause:i})}const ua="Bare Item",Gf="Boolean",Vf="Byte Sequence",Hf="Decimal",Kf="Integer";function Wf(n){return n<-999999999999999||999999999999999<n}const Yf=/[\x00-\x1f\x7f]+/,qf="Token",zf="Key";function Xe(n,e,t){return $f("serialize",n,e,t)}function Xf(n){if(typeof n!="boolean")throw Xe(n,Gf);return n?"?1":"?0"}function jf(n){return btoa(String.fromCharCode(...n))}function Zf(n){if(ArrayBuffer.isView(n)===!1)throw Xe(n,Vf);return`:${jf(n)}:`}function Jo(n){if(Wf(n))throw Xe(n,Kf);return n.toString()}function Qf(n){return`@${Jo(n.getTime()/1e3)}`}function el(n,e){if(n<0)return-el(-n,e);const t=Math.pow(10,e);if(Math.abs(n*t%1-.5)<Number.EPSILON){const s=Math.floor(n*t);return(s%2===0?s:s+1)/t}else return Math.round(n*t)/t}function Jf(n){const e=el(n,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Xe(n,Hf);const t=e.toString();return t.includes(".")?t:`${t}.0`}const e0="String";function t0(n){if(Yf.test(n))throw Xe(n,e0);return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function i0(n){return n.description||n.toString().slice(7,-1)}function ha(n){const e=i0(n);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Xe(e,qf);return e}function mn(n){switch(typeof n){case"number":if(!H(n))throw Xe(n,ua);return Number.isInteger(n)?Jo(n):Jf(n);case"string":return t0(n);case"symbol":return ha(n);case"boolean":return Xf(n);case"object":if(n instanceof Date)return Qf(n);if(n instanceof Uint8Array)return Zf(n);if(n instanceof Qo)return ha(n);default:throw Xe(n,ua)}}function pn(n){if(/^[a-z*][a-z0-9\-_.*]*$/.test(n)===!1)throw Xe(n,zf);return n}function $n(n){return n==null?"":Object.entries(n).map(([e,t])=>t===!0?`;${pn(e)}`:`;${pn(e)}=${mn(t)}`).join("")}function tl(n){return n instanceof Gt?`${mn(n.value)}${$n(n.params)}`:mn(n)}function s0(n){return`(${n.value.map(tl).join(" ")})${$n(n.params)}`}function n0(n,e={whitespace:!0}){if(typeof n!="object")throw Xe(n,Bf);const t=n instanceof Map?n.entries():Object.entries(n),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([s,r])=>{r instanceof Gt||(r=new Gt(r));let a=pn(s);return r.value===!0?a+=$n(r.params):(a+="=",Array.isArray(r.value)?a+=s0(r):a+=tl(r)),a}).join(`,${i}`)}function r0(n,e){return n0(n,e)}const a0=n=>n==="ot"||n==="sf"||n==="st",o0=n=>typeof n=="number"?H(n):n!=null&&n!==""&&n!==!1;function l0(n,e){const t=new URL(n),i=new URL(e);if(t.origin!==i.origin)return n;const s=t.pathname.split("/").slice(1),r=i.pathname.split("/").slice(1,-1);for(;s[0]===r[0];)s.shift(),r.shift();for(;r.length;)r.shift(),s.unshift("..");return s.join("/")}function c0(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(s=="x"?r:r&3|8).toString(16)})}}}const Ni=n=>Math.round(n),u0=(n,e)=>(e!=null&&e.baseUrl&&(n=l0(n,e.baseUrl)),encodeURIComponent(n)),wi=n=>Ni(n/100)*100,h0={br:Ni,d:Ni,bl:wi,dl:wi,mtp:wi,nor:u0,rtp:wi,tb:Ni};function d0(n,e){const t={};if(n==null||typeof n!="object")return t;const i=Object.keys(n).sort(),s=de({},h0,e==null?void 0:e.formatters),r=e==null?void 0:e.filter;return i.forEach(a=>{if(r!=null&&r(a))return;let o=n[a];const l=s[a];l&&(o=l(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||o0(o)&&(a0(a)&&typeof o=="string"&&(o=new Qo(o)),t[a]=o))}),t}function il(n,e={}){return n?r0(d0(n,e),de({whitespace:!1},e)):""}function f0(n,e={}){if(!n)return{};const t=Object.entries(n),i=Object.entries(Nf).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),s=t.reduce((r,a)=>{var o,l;const[c,u]=a,h=((o=i.find(d=>d[1].includes(c)))==null?void 0:o[0])||mt.REQUEST;return(l=r[h])!=null||(r[h]={}),r[h][c]=u,r},{});return Object.entries(s).reduce((r,[a,o])=>(r[a]=il(o,e),r),{})}function g0(n,e,t){return de(n,f0(e,t))}const m0="CMCD";function p0(n,e={}){if(!n)return"";const t=il(n,e);return`${m0}=${encodeURIComponent(t)}`}const da=/CMCD=[^&#]+/;function E0(n,e,t){const i=p0(e,t);if(!i)return n;if(da.test(n))return n.replace(da,i);const s=n.includes("?")?"&":"?";return`${n}${s}${i}`}class v0{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=s=>{try{this.apply(s,{ot:ye.MANIFEST,su:!this.initialized})}catch(r){C.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=s=>{try{const r=s.frag,a=this.hls.levels[r.level],o=this.getObjectType(r),l={d:r.duration*1e3,ot:o};(o===ye.VIDEO||o===ye.AUDIO||o==ye.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(s,l)}catch(r){C.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||c0(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHED,this.onMediaDetached,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHED,this.onMediaDetached,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=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,s;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(s=t.tracks.video)==null?void 0:s.buffer}createData(){var e;return{v:1,sf:gn.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){de(t,this.createData());const i=t.ot===ye.INIT||t.ot===ye.VIDEO||t.ot===ye.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:s}=this;s&&(t=Object.keys(t).reduce((r,a)=>(s.includes(a)&&(r[a]=t[a]),r),{})),this.useHeaders?(e.headers||(e.headers={}),g0(e.headers,t)):e.url=E0(e.url,t)}getObjectType(e){const{type:t}=e;if(t==="subtitle")return ye.TIMED_TEXT;if(e.sn==="initSegment")return ye.INIT;if(t==="audio")return ye.AUDIO;if(t==="main")return this.hls.audioTracks.length?ye.VIDEO:ye.MUXED}getTopBandwidth(e){let t=0,i;const s=this.hls;if(e===ye.AUDIO)i=s.audioTracks;else{const r=s.maxAutoLevel,a=r>-1?r+1:s.levels.length;i=s.levels.slice(0,a)}for(const r of i)r.bitrate>t&&(t=r.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.hls.media,i=e===ye.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:re.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}}const x0=3e5;class y0{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=C.log.bind(C,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((i==null?void 0:i.action)===ve.SendAlternateToPenaltyBox&&i.flags===Oe.MoveAllAlternatesMatchingHost){const s=this.levels;let r=this.pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:c}=t.context;o&&s?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&s&&(r=s.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==a),i.resolved||C.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${s&&s.length} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(r=>{s-i[r]>x0&&delete i[r]});for(let r=0;r<e.length;r++){const a=e[r];if(a in i)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,To(t),this.hls.trigger(E.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let r=0;r<s.length;r++)if(t===ie.AUDIO_TRACK&&s[r].hasAudioGroup(e)||t===ie.SUBTITLE_TRACK&&s[r].hasSubtitleGroup(e))return s[r].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},s={};e.forEach(r=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(t.some(u=>u.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(u=>{const h=new ce(u.attrs);h["PATHWAY-ID"]=a;const d=h.AUDIO&&`${h.AUDIO}_clone_${a}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;d&&(i[h.AUDIO]=d,h.AUDIO=d),f&&(s[h.SUBTITLES]=f,h.SUBTITLES=f);const g=sl(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new Ut({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:g,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let p=1;p<u.audioGroups.length;p++)m.addGroupId("audio",`${u.audioGroups[p]}_clone_${a}`);if(u.subtitleGroups)for(let p=1;p<u.subtitleGroups.length;p++)m.addGroupId("text",`${u.subtitleGroups[p]}_clone_${a}`);return m});t.push(...c),fa(this.audioTracks,i,l,a),fa(this.subtitleTracks,s,l,a)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let s;try{s=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+u)}const r={responseType:"json",url:s.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(u,h,d,f)=>{this.log(`Loaded steering manifest: "${s}"`);const g=u.data;if(g.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":m,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":v}=g;if(m)try{this.uri=new self.URL(m,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||d.url),p&&this.clonePathways(p);const x={steeringManifest:g,url:s.toString()};this.hls.trigger(E.STEERING_MANIFEST_LOADED,x),v&&this.updatePathwayPriority(v)},onError:(u,h,d,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${h.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let g=this.timeToLoad*1e3;if(u.code===429){const m=this.loader;if(typeof(m==null?void 0:m.getResponseHeader)=="function"){const p=m.getResponseHeader("Retry-After");p&&(g=parseFloat(p)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},onTimeout:(u,h,d)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const s=(i=this.hls)==null?void 0:i.media;if(s&&!s.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function fa(n,e,t,i){n&&Object.keys(e).forEach(s=>{const r=n.filter(a=>a.groupId===s).map(a=>{const o=de({},a);return o.details=void 0,o.attrs=new ce(o.attrs),o.url=o.attrs.URI=sl(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[s],o.attrs["PATHWAY-ID"]=i,o});n.push(...r)})}function sl(n,e,t,i){const{HOST:s,PARAMS:r,[t]:a}=i;let o;e&&(o=a==null?void 0:a[e],o&&(n=o));const l=new self.URL(n);return s&&!o&&(l.host=s),r&&Object.keys(r).sort().forEach(c=>{c&&l.searchParams.set(c,r[c])}),l.href}const T0=/^age:\s*[\d.]+\s*$/im;class nl{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 fs,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return r(i,t.url)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),r(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,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const s=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=i.loadPolicy;if(s)for(const o in s)e.setRequestHeader(o,s[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=r&&H(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const s=t.readyState,r=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const a=t.status,o=t.responseType!=="text";if(a>=200&&a<300&&(o&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=o?t.response:t.responseText,c=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=c,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;const u=this.callbacks.onProgress;if(u&&u(i,e,l,t),!this.callbacks)return;const h={url:t.responseURL,data:l,code:a};this.callbacks.onSuccess(h,i,e,t)}else{const l=r.loadPolicy.errorRetry,c=i.retry,u={url:e.url,data:void 0,code:a};Ji(l,c,!1,u)?this.retry(l):(C.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:t.statusText},e,t,i))}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Ji(e,t,!0))this.retry(e);else{var i;C.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Rn(e,i.retry),i.retry++,C.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&T0.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}function S0(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const b0=/(\d+)-(\d+)\/(\d+)/;class ga{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||R0,this.controller=new self.AbortController,this.stats=new fs}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const r=L0(e,this.controller.signal),a=i.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:u}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&H(c)?c:u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,e,this.response)},t.timeout),self.fetch(this.request).then(h=>{this.response=this.loader=h;const d=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,e,this.response)},u-(d-s.loading.start)),!h.ok){const{status:f,statusText:g}=h;throw new I0(g||"fetch, bad network response",f,h)}return s.loading.first=d,s.total=C0(h.headers)||s.total,a&&H(t.highWaterMark)?this.loadProgressively(h,s,e,t.highWaterMark,a):o?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{const d=this.response;if(!d)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const f=h[l];f&&(s.loaded=s.total=f);const g={url:d.url,data:h,code:d.status};a&&!H(t.highWaterMark)&&a(s,e,h,d),i.onSuccess(g,s,e,d)}).catch(h=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const d=h&&h.code||0,f=h?h.message:null;i.onError({code:d,text:f},e,h?h.details:null,s)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,s=0,r){const a=new Ao,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&r(t,i,a.flush(),e),Promise.resolve(new ArrayBuffer(0));const u=c.value,h=u.length;return t.loaded+=h,h<s||a.dataLength?(a.push(u),a.dataLength>=s&&r(t,i,a.flush(),e)):r(t,i,u,e),l()}).catch(()=>Promise.reject());return l()}}function L0(n,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(de({},n.headers))};return n.rangeEnd&&t.headers.set("Range","bytes="+n.rangeStart+"-"+String(n.rangeEnd-1)),t}function A0(n){const e=b0.exec(n);if(e)return parseInt(e[2])-parseInt(e[1])+1}function C0(n){const e=n.get("Content-Range");if(e){const i=A0(e);if(H(i))return i}const t=n.get("Content-Length");if(t)return parseInt(t)}function R0(n,e){return new self.Request(n.url,e)}class I0 extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const w0=/\s/,D0={newCue(n,e,t,i){const s=[];let r,a,o,l,c;const u=self.VTTCue||self.TextTrackCue;for(let d=0;d<i.rows.length;d++)if(r=i.rows[d],o=!0,l=0,c="",!r.isEmpty()){var h;for(let m=0;m<r.chars.length;m++)w0.test(r.chars[m].uchar)&&o?l++:(c+=r.chars[m].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=qo(c.trim()),g=Bn(e,t,f);n!=null&&(h=n.cues)!=null&&h.getCueById(g)||(a=new u(e,t,f),a.id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(a))}return n&&s.length&&(s.sort((d,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),s.forEach(d=>Eo(n,d))),s}},k0={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},rl=Ee(Ee({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:nl,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:sd,bufferController:lf,capLevelController:Un,errorController:Wh,fpsController:Mf,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:io,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:k0},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},_0()),{},{subtitleStreamController:nf,subtitleTrackController:af,timelineController:Of,audioStreamController:tf,audioTrackController:sf,emeController:Ft,cmcdController:v0,contentSteeringController:y0});function _0(){return{cueHandler:D0,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function P0(n,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const t=En(n),i=["manifest","level","frag"],s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(r=>{const a=`${r==="level"?"playlist":r}LoadPolicy`,o=e[a]===void 0,l=[];s.forEach(c=>{const u=`${r}Loading${c}`,h=e[u];if(h!==void 0&&o){l.push(u);const d=t[a].default;switch(e[a]={default:d},c){case"TimeOut":d.maxLoadTimeMs=h,d.maxTimeToFirstByteMs=h;break;case"MaxRetry":d.errorRetry.maxNumRetry=h,d.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":d.errorRetry.retryDelayMs=h,d.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":d.errorRetry.maxRetryDelayMs=h,d.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&C.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`)}),Ee(Ee({},t),e)}function En(n){return n&&typeof n=="object"?Array.isArray(n)?n.map(En):Object.keys(n).reduce((e,t)=>(e[t]=En(n[t]),e),{}):n}function O0(n){const e=n.loader;e!==ga&&e!==nl?(C.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):S0()&&(n.loader=ga,n.progressive=!0,n.enableSoftwareAES=!0,C.log("[config]: Progressive streaming enabled, using FetchLoader"))}let Ws;class F0 extends In{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,s=[],r={},a={};let o=!1,l=!1,c=!1;t.levels.forEach(u=>{var h,d;const f=u.attrs;let{audioCodec:g,videoCodec:m}=u;((h=g)==null?void 0:h.indexOf("mp4a.40.34"))!==-1&&(Ws||(Ws=/chrome|firefox/i.test(navigator.userAgent)),Ws&&(u.audioCodec=g=void 0)),g&&(u.audioCodec=g=ji(g,i)),((d=m)==null?void 0:d.indexOf("avc1"))===0&&(m=u.videoCodec=yh(m));const{width:p,height:v,unknownCodecs:x}=u;if(o||(o=!!(p&&v)),l||(l=!!m),c||(c=!!g),x!=null&&x.length||g&&!Ds(g,"audio",i)||m&&!Ds(m,"video",i))return;const{CODECS:S,"FRAME-RATE":b,"HDCP-LEVEL":T,"PATHWAY-ID":L,RESOLUTION:A,"VIDEO-RANGE":P}=f,I=`${`${L||"."}-`}${u.bitrate}-${A}-${b}-${S}-${P}-${T}`;if(r[I])if(r[I].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const k=a[I]+=1;u.attrs["PATHWAY-ID"]=new Array(k+1).join(".");const M=new Ut(u);r[I]=M,s.push(M)}else r[I].addGroupId("audio",f.AUDIO),r[I].addGroupId("text",f.SUBTITLES);else{const k=new Ut(u);r[I]=k,a[I]=1,s.push(k)}}),this.filterAndSortMediaOptions(s,t,o,l,c)}filterAndSortMediaOptions(e,t,i,s,r){let a=[],o=[],l=e;if((i||s)&&r&&(l=l.filter(({videoCodec:g,videoRange:m,width:p,height:v})=>(!!g||!!(p&&v))&&Ph(m))),l.length===0){Promise.resolve().then(()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);const g=new Error("no level with compatible codecs found in manifest");this.hls.trigger(E.ERROR,{type:z.MEDIA_ERROR,details:w.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:g,reason:g.message})}});return}if(t.audioTracks){const{preferManagedMediaSource:g}=this.hls.config;a=t.audioTracks.filter(m=>!m.audioCodec||Ds(m.audioCodec,"audio",g)),ma(a)}t.subtitles&&(o=t.subtitles,ma(o));const c=l.slice(0);l.sort((g,m)=>{if(g.attrs["HDCP-LEVEL"]!==m.attrs["HDCP-LEVEL"])return(g.attrs["HDCP-LEVEL"]||"")>(m.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&g.height!==m.height)return g.height-m.height;if(g.frameRate!==m.frameRate)return g.frameRate-m.frameRate;if(g.videoRange!==m.videoRange)return Zi.indexOf(g.videoRange)-Zi.indexOf(m.videoRange);if(g.videoCodec!==m.videoCodec){const p=Sr(g.videoCodec),v=Sr(m.videoCodec);if(p!==v)return v-p}if(g.uri===m.uri&&g.codecSet!==m.codecSet){const p=Xi(g.codecSet),v=Xi(m.codecSet);if(p!==v)return v-p}return g.averageBitrate!==m.averageBitrate?g.averageBitrate-m.averageBitrate:0});let u=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let g=0;g<c.length;g++)if(c[g].pathwayId===l[0].pathwayId){u=c[g];break}}this._levels=l;for(let g=0;g<l.length;g++)if(l[g]===u){var h;this._firstLevel=g;const m=u.bitrate,p=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${m}`),((h=this.hls.userConfig)==null?void 0:h.abrEwmaDefaultEstimate)===void 0){const v=Math.min(m,this.hls.config.abrEwmaDefaultEstimateMax);v>p&&p===rl.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=v)}break}const d=r&&!s,f={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:s,altAudio:!d&&a.some(g=>!!g.url)};this.hls.trigger(E.MANIFEST_PARSED,f),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const u=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(E.ERROR,{type:z.OTHER_ERROR,details:w.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:u,reason:u.message}),h)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&a.details&&s&&r===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${r?" with Pathway "+r:""}`);const l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(E.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const u=this.switchParams(a.uri,s==null?void 0:s.details,c);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===ie.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===W.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(r=>!!i[r]))return;const s=this._levels[t.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var i;const{level:s,details:r}=t,a=this._levels[s];if(!a){var o;this.warn(`Invalid level index ${s}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}s===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(s,t,a.details)):(i=t.deliveryDirectives)!=null&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let s=i.uri;if(e)try{s=e.addDirectives(s)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}const r=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${r?" Pathway "+r:""} ${s}`),this.clearTimer(),this.hls.trigger(E.LEVEL_LOADING,{url:s,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;const i=this._levels.filter((s,r)=>r!==e?!0:(this.steering&&this.steering.removeLevel(s),s===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,s.details&&s.details.fragments.forEach(a=>a.level=-1)),!1));To(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(E.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function ma(n){const e={};n.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}class M0{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyUriToKeyInfo){const s=this.keyUriToKeyInfo[i].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=w.KEY_LOAD_ERROR,i,s,r){return new Qe({type:z.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:s})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:s}=e;for(let r=0;r<t.length;r++){const a=t[r];if(s<=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,s;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,c))}const a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((s=o)!=null&&s.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(c=>(r.key=c.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const s=this.emeController.loadKey(i);if(s)return(e.keyLoadPromise=s.then(r=>(e.mediaKeySessionContext=r,i))).catch(r=>{throw e.keyLoadPromise=null,r})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,s=i.loader,r=new s(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=i.keyLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,f,g,m)=>{const{frag:p,keyInfo:v,url:x}=g;if(!p.decryptdata||v!==this.keyUriToKeyInfo[x])return o(this.createKeyLoadError(p,w.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),m));v.decryptdata.key=p.decryptdata.key=new Uint8Array(d.data),p.keyLoader=null,v.loader=null,a({frag:p,keyInfo:v})},onError:(d,f,g,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),g,Ee({url:l.url,data:void 0},d)))},onTimeout:(d,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(d,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};r.load(l,u,h)})}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[s],r&&r.destroy()}}function al(){return self.SourceBuffer||self.WebKitSourceBuffer}function ol(){if(!vt())return!1;const e=al();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function N0(){if(!ol())return!1;const n=vt();return typeof(n==null?void 0:n.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>n.isTypeSupported(di(e,"video")))||["mp4a.40.2","fLaC"].some(e=>n.isTypeSupported(di(e,"audio"))))}function B0(){var n;const e=al();return typeof(e==null||(n=e.prototype)==null?void 0:n.changeType)=="function"}const U0=250,Bi=2,$0=.1,G0=.05;class V0{constructor(e,t,i,s){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=s}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:i,media:s,stalled:r}=this;if(s===null)return;const{currentTime:a,seeking:o}=s,l=this.seeking&&!o,c=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,o||(this.nudgeRetry=0),r!==null){if(this.stallReported){const p=self.performance.now()-r;C.warn(`playback not stuck anymore @${a}, after ${Math.round(p)}ms`),this.stallReported=!1}this.stalled=null}return}if(c||l){this.stalled=null;return}if(s.paused&&!o||s.ended||s.playbackRate===0||!re.getBuffered(s).length){this.nudgeRetry=0;return}const u=re.bufferInfo(s,a,0),h=u.nextStart||0;if(o){const p=u.len>Bi,v=!h||t&&t.start<=a||h-a>Bi&&!this.fragmentTracker.getPartialFragment(a);if(p||v)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var d;if(!(u.len>0)&&!h)return;const v=Math.max(h,u.start||0)-a,x=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,b=(x==null||(d=x.details)==null?void 0:d.live)?x.details.targetduration*2:Bi,T=this.fragmentTracker.getPartialFragment(a);if(v>0&&(v<=b||T)){s.paused||this._trySkipBufferHole(T);return}}const f=self.performance.now();if(r===null){this.stalled=f;return}const g=f-r;if(!o&&g>=U0&&(this._reportStall(u),!this.media))return;const m=re.bufferInfo(s,a,i.maxBufferHole);this._tryFixBufferStall(m,g)}_tryFixBufferStall(e,t){const{config:i,fragmentTracker:s,media:r}=this;if(r===null)return;const a=r.currentTime,o=s.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-a<i.maxBufferHole)&&t>i.highBufferWatchdogPeriod*1e3&&(C.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:i,stallReported:s}=this;if(!s&&i){this.stallReported=!0;const r=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);C.warn(r.message),t.trigger(E.ERROR,{type:z.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:i,media:s}=this;if(s===null)return 0;const r=s.currentTime,a=re.bufferInfo(s,r,0),o=r<a.start?a.start:a.nextStart;if(o){const l=a.len<=t.maxBufferHole,c=a.len>0&&a.len<1&&s.readyState<3,u=o-r;if(u>0&&(l||c)){if(u>t.maxBufferHole){const{fragmentTracker:d}=this;let f=!1;if(r===0){const g=d.getAppendedFrag(0,W.MAIN);g&&o<g.end&&(f=!0)}if(!f){const g=e||d.getAppendedFrag(r,W.MAIN);if(g){let m=!1,p=g.end;for(;p<o;){const v=d.getPartialFragment(p);if(v)p+=v.duration;else{m=!0;break}}if(m)return 0}}}const h=Math.max(o+G0,r+$0);if(C.warn(`skipping hole, adjusting currentTime from ${r} to ${h}`),this.moved=!0,this.stalled=null,s.currentTime=h,e&&!e.gap){const d=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${h}`);i.trigger(E.ERROR,{type:z.MEDIA_ERROR,details:w.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:e})}return h}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:i,nudgeRetry:s}=this;if(i===null)return;const r=i.currentTime;if(this.nudgeRetry++,s<e.nudgeMaxRetry){const a=r+(s+1)*e.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${r} to ${a}`);C.warn(o.message),i.currentTime=a,t.trigger(E.ERROR,{type:z.MEDIA_ERROR,details:w.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const a=new Error(`Playhead still not moving while enough data buffered @${r} after ${e.nudgeMaxRetry} nudges`);C.error(a.message),t.trigger(E.ERROR,{type:z.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,error:a,fatal:!0})}}}const H0=100;class K0 extends kn{constructor(e,t,i){super(e,t,i,"[stream-controller]",W.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(E.ERROR,this.onError,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(E.ERROR,this.onError,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:i}=this;if(this.stopLoad(),this.setInterval(H0),this.level=-1,!this.startFragRequested){let s=i.startLevel;s===-1&&(i.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=i.firstAutoLevel),i.nextLoadLevel=s,this.level=i.loadLevel,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=F.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=F.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case F.WAITING_LEVEL:{const{levels:t,level:i}=this,s=t==null?void 0:t[i],r=s==null?void 0:s.details;if(r&&(!r.live||this.levelLastLoaded===s)){if(this.waitForCdnTuneIn(r))break;this.state=F.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=F.IDLE;break}break}case F.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){const{levels:s,level:r}=this,a=s==null?void 0:s[r];this.resetStartWhenNotLoaded(a||null),this.state=F.IDLE}}break}this.state===F.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(t===null||!s&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=e.nextLoadLevel;if(!(i!=null&&i[r]))return;const a=i[r],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const m={};this.altAudio&&(m.type="video"),this.hls.trigger(E.BUFFER_EOS,m),this.state=F.ENDED;return}e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const c=a.details;if(!c||this.state===F.WAITING_LEVEL||c.live&&this.levelLastLoaded!==a){this.level=r,this.state=F.WAITING_LEVEL;return}const u=o.len,h=this.getMaxBufferLength(a.maxBitrate);if(u>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(d,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&f.sn!=="initSegment"&&this.fragmentTracker.getState(f)!==pe.OK){var g;const p=((g=this.backtrackFragment)!=null?g:f).sn-c.startSN,v=c.fragments[p-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,d)){if(!f.gap){const p=this.audioOnly&&!this.altAudio?se.AUDIO:se.VIDEO,v=(p===se.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,p,W.MAIN)}f=this.getNextFragmentLoopLoading(f,c,o,W.MAIN,h)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,d))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);this.fragCurrent=e,s===pe.NOT_LOADED||s===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=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,W.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let i;const s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,l=e[o],c=this.fragLastKbps;c&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:i=0}else i=0;const a=this.getBufferedFrag(t.currentTime+i);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,c=o.duration,u=Math.max(a.end,l+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*(this.couldBacktrack?.5:.125)),c*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(u,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case F.KEY_LOADING:case F.FRAG_LOADING:case F.FRAG_LOADING_WAITING_RETRY:case F.PARSING:case F.PARSED:this.state=F.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new V0(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;H(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(E.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let i=!1,s=!1;t.levels.forEach(r=>{const a=r.audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=i&&s&&!B0(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==F.IDLE)return;const s=i[t.level];(!s.details||s.details.live&&this.levelLastLoaded!==s||this.waitForCdnTuneIn(s.details))&&(this.state=F.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:s}=this,r=t.level,a=t.details,o=a.totalduration;if(!s){this.warn(`Levels were reset while loading level ${r}`);return}this.log(`Level ${r} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=s[r],c=this.fragCurrent;c&&(this.state===F.FRAG_LOADING||this.state===F.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let u=0;if(a.live||(i=l.details)!=null&&i.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(E.LEVEL_UPDATED,{details:a,level:r}),this.state===F.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=F.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,u),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:s,payload:r}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=a[i.level],l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const c=o.videoCodec,u=l.PTSKnown||!l.live,h=(t=i.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Go(this.hls,W.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=s?s.index:-1,m=g!==-1,p=new wn(i.level,i.sn,i.stats.chunkCount,r.byteLength,g,m),v=this.initPTS[i.cc];f.push(r,h,d,c,i,s,l.totalduration,u,p,v)}onAudioTrackSwitching(e,t){const i=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const r=this.hls;i&&(r.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),r.trigger(E.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=t.id,s=!!this.hls.audioTracks[i].url;if(s){const r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=s,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,r,a=!1;for(const o in i){const l=i[o];if(l.id==="main"){if(r=o,s=l,o==="video"){const c=i[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&s?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i&&i.type!==W.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===F.PARSED&&(this.state=F.IDLE);return}const r=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*r.total/(r.buffering.end-r.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}onError(e,t){var i;if(t.fatal){this.state=F.ERROR;return}switch(t.details){case w.FRAG_GAP:case w.FRAG_PARSING_ERROR:case w.FRAG_DECRYPT_ERROR:case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(W.MAIN,t);break;case w.LEVEL_LOAD_ERROR:case w.LEVEL_LOAD_TIMEOUT:case w.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===F.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===ie.LEVEL&&(this.state=F.IDLE);break;case w.BUFFER_APPEND_ERROR:case w.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===w.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case w.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){const{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!re.getBuffered(e).length){const i=this.state!==F.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=F.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==se.AUDIO||this.audioOnly&&!this.altAudio){const i=(t===se.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,W.MAIN),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const s=re.getBuffered(e),a=(s.length?s.start(0):0)-i;a>0&&(a<this.config.maxBufferHole||a<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${a} to match buffer start`),i+=a,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${t}`),e.currentTime=i}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{const{hls:s}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=F.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=e.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger(E.FRAG_LOADED,i),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const i="main",{hls:s}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:u}=o,{video:h,text:d,id3:f,initSegment:g}=r,{details:m}=u,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=F.PARSING,g){if(g!=null&&g.tracks){const S=l.initSegment||l;this._bufferInitSegment(u,g.tracks,S,a),s.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:i,tracks:g.tracks})}const v=g.initPTS,x=g.timescale;H(v)&&(this.initPTS[l.cc]={baseTime:v,timescale:x},s.trigger(E.INIT_PTS_FOUND,{frag:l,id:i,initPTS:v,timescale:x}))}if(h&&m&&l.sn!=="initSegment"){const v=m.fragments[l.sn-1-m.startSN],x=l.sn===m.startSN,S=!v||l.cc>v.cc;if(r.independent!==!1){const{startPTS:b,endPTS:T,startDTS:L,endDTS:A}=h;if(c)c.elementaryStreams[h.type]={startPTS:b,endPTS:T,startDTS:L,endDTS:A};else if(h.firstKeyFrame&&h.independent&&a.id===1&&!S&&(this.couldBacktrack=!0),h.dropped&&h.independent){const P=this.getMainFwdBufferInfo(),D=(P?P.end:this.getLoadPosition())+this.config.maxBufferHole,I=h.firstKeyFramePTS?h.firstKeyFramePTS:b;if(!x&&D<I-this.config.maxBufferHole&&!S){this.backtrack(l);return}else S&&(l.gap=!0);l.setElementaryStreamInfo(h.type,l.start,T,l.start,A,!0)}else x&&b>Bi&&(l.gap=!0);l.setElementaryStreamInfo(h.type,b,T,L,A),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(h,l,c,a,x||S)}else if(x||S)l.gap=!0;else{this.backtrack(l);return}}if(p){const{startPTS:v,endPTS:x,startDTS:S,endDTS:b}=p;c&&(c.elementaryStreams[se.AUDIO]={startPTS:v,endPTS:x,startDTS:S,endDTS:b}),l.setElementaryStreamInfo(se.AUDIO,v,x,S,b),this.bufferFragmentData(p,l,c,a)}if(m&&f!=null&&(t=f.samples)!=null&&t.length){const v={id:i,frag:l,details:m,samples:f.samples};s.trigger(E.FRAG_PARSING_METADATA,v)}if(m&&d){const v={id:i,frag:l,details:m,samples:d.samples};s.trigger(E.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(e,t,i,s){if(this.state!==F.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:r,video:a,audiovideo:o}=t;if(r){let l=e.audioCodec;const c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5");const u=r.metadata;u&&"channelCount"in u&&(u.channelCount||1)!==1&&c.indexOf("firefox")===-1&&(l="mp4a.40.5")}l&&l.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),r.levelCodec=l,r.id="main",this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${r.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(E.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{const u=t[l].initSegment;u!=null&&u.byteLength&&this.hls.trigger(E.BUFFER_APPENDING,{type:l,data:u,frag:i,part:null,chunkMeta:s,parent:i.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,W.MAIN)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=F.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(re.isBuffered(e,i)?t=this.getAppendedFrag(i):re.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const s=this.fragPlaying,r=t.level;(!s||t.sn!==s.sn||s.level!==r)&&(this.fragPlaying=t,this.hls.trigger(E.FRAG_CHANGED,{frag:t}),(!s||s.level!==r)&&this.hls.trigger(E.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,i=this.currentFrag;if(i&&H(t)&&H(i.programDateTime)){const s=i.programDateTime+(t-i.start)*1e3;return new Date(s)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class le{static get version(){return"1.5.16"}static isMSESupported(){return ol()}static isSupported(){return N0()}static getMediaSource(){return vt()}static get Events(){return E}static get ErrorTypes(){return z}static get ErrorDetails(){return w}static get DefaultConfig(){return le.defaultConfig?le.defaultConfig:rl}static set DefaultConfig(e){le.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new Mn,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,ku(e.debug||!1,"Hls instance");const t=this.config=P0(le.DefaultConfig,e);this.userConfig=e,t.progressive&&O0(t);const{abrController:i,bufferController:s,capLevelController:r,errorController:a,fpsController:o}=t,l=new a(this),c=this.abrController=new i(this),u=this.bufferController=new s(this),h=this.capLevelController=new r(this),d=new o(this),f=new Ah(this),g=new Dh(this),m=t.contentSteeringController,p=m?new m(this):null,v=this.levelController=new F0(this,p),x=new rd(this),S=new M0(this.config),b=this.streamController=new K0(this,x,S);h.setStreamController(b),d.setStreamController(b);const T=[f,v,b];p&&T.splice(1,0,p),this.networkControllers=T;const L=[c,u,h,d,g,x];this.audioTrackController=this.createController(t.audioTrackController,T);const A=t.audioStreamController;A&&T.push(new A(this,x,S)),this.subtitleTrackController=this.createController(t.subtitleTrackController,T);const P=t.subtitleStreamController;P&&T.push(new P(this,x,S)),this.createController(t.timelineController,L),S.emeController=this.emeController=this.createController(t.emeController,L),this.cmcdController=this.createController(t.cmcdController,L),this.latencyController=this.createController(kh,L),this.coreComponents=L,T.push(l);const D=l.onErrorOut;typeof D=="function"&&this.on(E.ERROR,D,l)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,s){this._emitter.off(e,t,i,s)}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(C.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const s=e===E.ERROR;this.trigger(E.ERROR,{type:z.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,fatal:s,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){C.log("destroy"),this.trigger(E.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){C.log("attachMedia"),this._media=e,this.trigger(E.MEDIA_ATTACHING,{media:e})}detachMedia(){C.log("detachMedia"),this.trigger(E.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,i=this.url,s=this.url=bn.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,C.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(E.MANIFEST_LOADING,{url:e})}startLoad(e=-1){C.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){C.log("stopLoad"),this.started=!1,this.networkControllers.forEach(e=>{e.stopLoad()})}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1)})}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.stopLoad()})}swapAudioCodec(){C.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){C.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){C.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){C.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){C.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){C.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){C.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(C.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){_h(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let s=0;s<i;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let s;if(t===-1&&e!=null&&e.length?s=e.length-1:s=t,i)for(let r=s;r--;){const a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=i)return r}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var t;return(t=this.audioTrackController)==null?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return(t=this.subtitleTrackController)==null||t.setSubtitleOption(e),null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}le.defaultConfig=void 0;const ll="avc1,mp4a";var cl={exports:{}},Qt;typeof window<"u"?Qt=window:typeof Gi<"u"?Qt=Gi:typeof self<"u"?Qt=self:Qt={};var W0=Qt;const Y0={},q0=Object.freeze(Object.defineProperty({__proto__:null,default:Y0},Symbol.toStringTag,{value:"Module"})),z0=Ll(q0);var pa=typeof Gi<"u"?Gi:typeof window<"u"?window:{},X0=z0,Jt;typeof document<"u"?Jt=document:(Jt=pa["__GLOBAL_DOCUMENT_CACHE@4"],Jt||(Jt=pa["__GLOBAL_DOCUMENT_CACHE@4"]=X0));var j0=Jt,Ea=j0,Gn=Object.create||function(){function n(){}return function(e){if(arguments.length!==1)throw new Error("Object.create shim only accepts one parameter.");return n.prototype=e,new n}}();function we(n,e){this.name="ParsingError",this.code=n.code,this.message=e||n.message}we.prototype=Gn(Error.prototype);we.prototype.constructor=we;we.Errors={BadSignature:{code:0,message:"Malformed WebVTT signature."},BadTimeStamp:{code:1,message:"Malformed time stamp."}};function Vn(n){function e(i,s,r,a){return(i|0)*3600+(s|0)*60+(r|0)+(a|0)/1e3}var t=n.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);return t?t[3]?e(t[1],t[2],t[3].replace(":",""),t[4]):t[1]>59?e(t[1],t[2],0,t[4]):e(0,t[1],t[2],t[4]):null}function ai(){this.values=Gn(null)}ai.prototype={set:function(n,e){!this.get(n)&&e!==""&&(this.values[n]=e)},get:function(n,e,t){return t?this.has(n)?this.values[n]:e[t]:this.has(n)?this.values[n]:e},has:function(n){return n in this.values},alt:function(n,e,t){for(var i=0;i<t.length;++i)if(e===t[i]){this.set(n,e);break}},integer:function(n,e){/^-?\d+$/.test(e)&&this.set(n,parseInt(e,10))},percent:function(n,e){return e.match(/^([\d]{1,3})(\.[\d]*)?%$/)&&(e=parseFloat(e),e>=0&&e<=100)?(this.set(n,e),!0):!1}};function ei(n,e,t,i){var s=i?n.split(i):[n];for(var r in s)if(typeof s[r]=="string"){var a=s[r].split(t);if(a.length===2){var o=a[0].trim(),l=a[1].trim();e(o,l)}}}function Z0(n,e,t){var i=n;function s(){var o=Vn(n);if(o===null)throw new we(we.Errors.BadTimeStamp,"Malformed timestamp: "+i);return n=n.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,l){var c=new ai;ei(o,function(u,h){switch(u){case"region":for(var d=t.length-1;d>=0;d--)if(t[d].id===h){c.set(u,t[d].region);break}break;case"vertical":c.alt(u,h,["rl","lr"]);break;case"line":var f=h.split(","),g=f[0];c.integer(u,g),c.percent(u,g)&&c.set("snapToLines",!1),c.alt(u,g,["auto"]),f.length===2&&c.alt("lineAlign",f[1],["start","center","end"]);break;case"position":f=h.split(","),c.percent(u,f[0]),f.length===2&&c.alt("positionAlign",f[1],["start","center","end"]);break;case"size":c.percent(u,h);break;case"align":c.alt(u,h,["start","center","end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");try{l.line=c.get("line","auto")}catch{}l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100);try{l.align=c.get("align","center")}catch{l.align=c.get("align","middle")}try{l.position=c.get("position","auto")}catch{l.position=c.get("position",{start:0,left:0,center:50,middle:50,end:100,right:100},l.align)}l.positionAlign=c.get("positionAlign",{start:"start",left:"start",center:"center",middle:"center",end:"end",right:"end"},l.align)}function a(){n=n.replace(/^\s+/,"")}if(a(),e.startTime=s(),a(),n.substr(0,3)!=="-->")throw new we(we.Errors.BadTimeStamp,"Malformed time stamp (time stamps must be separated by '-->'): "+i);n=n.substr(3),a(),e.endTime=s(),a(),r(n,e)}var Ys=Ea.createElement&&Ea.createElement("textarea"),Q0={c:"span",i:"i",b:"b",u:"u",ruby:"ruby",rt:"rt",v:"span",lang:"span"},va={white:"rgba(255,255,255,1)",lime:"rgba(0,255,0,1)",cyan:"rgba(0,255,255,1)",red:"rgba(255,0,0,1)",yellow:"rgba(255,255,0,1)",magenta:"rgba(255,0,255,1)",blue:"rgba(0,0,255,1)",black:"rgba(0,0,0,1)"},J0={v:"title",lang:"lang"},xa={rt:"ruby"};function ul(n,e){function t(){if(!e)return null;function g(p){return e=e.substr(p.length),p}var m=e.match(/^([^<]*)(<[^>]*>?)?/);return g(m[1]?m[1]:m[2])}function i(g){return Ys.innerHTML=g,g=Ys.textContent,Ys.textContent="",g}function s(g,m){return!xa[m.localName]||xa[m.localName]===g.localName}function r(g,m){var p=Q0[g];if(!p)return null;var v=n.document.createElement(p),x=J0[g];return x&&m&&(v[x]=m.trim()),v}for(var a=n.document.createElement("div"),o=a,l,c=[];(l=t())!==null;){if(l[0]==="<"){if(l[1]==="/"){c.length&&c[c.length-1]===l.substr(2).replace(">","")&&(c.pop(),o=o.parentNode);continue}var u=Vn(l.substr(1,l.length-2)),h;if(u){h=n.document.createProcessingInstruction("timestamp",u),o.appendChild(h);continue}var d=l.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);if(!d||(h=r(d[1],d[3]),!h)||!s(o,h))continue;if(d[2]){var f=d[2].split(".");f.forEach(function(g){var m=/^bg_/.test(g),p=m?g.slice(3):g;if(va.hasOwnProperty(p)){var v=m?"background-color":"color",x=va[p];h.style[v]=x}}),h.className=f.join(" ")}c.push(d[1]),o.appendChild(h),o=h;continue}o.appendChild(n.document.createTextNode(i(l)))}return a}var ya=[[1470,1470],[1472,1472],[1475,1475],[1478,1478],[1488,1514],[1520,1524],[1544,1544],[1547,1547],[1549,1549],[1563,1563],[1566,1610],[1645,1647],[1649,1749],[1765,1766],[1774,1775],[1786,1805],[1807,1808],[1810,1839],[1869,1957],[1969,1969],[1984,2026],[2036,2037],[2042,2042],[2048,2069],[2074,2074],[2084,2084],[2088,2088],[2096,2110],[2112,2136],[2142,2142],[2208,2208],[2210,2220],[8207,8207],[64285,64285],[64287,64296],[64298,64310],[64312,64316],[64318,64318],[64320,64321],[64323,64324],[64326,64449],[64467,64829],[64848,64911],[64914,64967],[65008,65020],[65136,65140],[65142,65276],[67584,67589],[67592,67592],[67594,67637],[67639,67640],[67644,67644],[67647,67669],[67671,67679],[67840,67867],[67872,67897],[67903,67903],[67968,68023],[68030,68031],[68096,68096],[68112,68115],[68117,68119],[68121,68147],[68160,68167],[68176,68184],[68192,68223],[68352,68405],[68416,68437],[68440,68466],[68472,68479],[68608,68680],[126464,126467],[126469,126495],[126497,126498],[126500,126500],[126503,126503],[126505,126514],[126516,126519],[126521,126521],[126523,126523],[126530,126530],[126535,126535],[126537,126537],[126539,126539],[126541,126543],[126545,126546],[126548,126548],[126551,126551],[126553,126553],[126555,126555],[126557,126557],[126559,126559],[126561,126562],[126564,126564],[126567,126570],[126572,126578],[126580,126583],[126585,126588],[126590,126590],[126592,126601],[126603,126619],[126625,126627],[126629,126633],[126635,126651],[1114109,1114109]];function eg(n){for(var e=0;e<ya.length;e++){var t=ya[e];if(n>=t[0]&&n<=t[1])return!0}return!1}function tg(n){var e=[],t="",i;if(!n||!n.childNodes)return"ltr";function s(o,l){for(var c=l.childNodes.length-1;c>=0;c--)o.push(l.childNodes[c])}function r(o){if(!o||!o.length)return null;var l=o.pop(),c=l.textContent||l.innerText;if(c){var u=c.match(/^.*(\n|\r)/);return u?(o.length=0,u[0]):c}if(l.tagName==="ruby")return r(o);if(l.childNodes)return s(o,l),r(o)}for(s(e,n);t=r(e);)for(var a=0;a<t.length;a++)if(i=t.charCodeAt(a),eg(i))return"rtl";return"ltr"}function ig(n){if(typeof n.line=="number"&&(n.snapToLines||n.line>=0&&n.line<=100))return n.line;if(!n.track||!n.track.textTrackList||!n.track.textTrackList.mediaElement)return-1;for(var e=n.track,t=e.textTrackList,i=0,s=0;s<t.length&&t[s]!==e;s++)t[s].mode==="showing"&&i++;return++i*-1}function ms(){}ms.prototype.applyStyles=function(n,e){e=e||this.div;for(var t in n)n.hasOwnProperty(t)&&(e.style[t]=n[t])};ms.prototype.formatStyle=function(n,e){return n===0?0:n+e};function ns(n,e,t){ms.call(this),this.cue=e,this.cueDiv=ul(n,e.text);var i={color:"rgba(255, 255, 255, 1)",backgroundColor:"rgba(0, 0, 0, 0.8)",position:"relative",left:0,right:0,top:0,bottom:0,display:"inline",writingMode:e.vertical===""?"horizontal-tb":e.vertical==="lr"?"vertical-lr":"vertical-rl",unicodeBidi:"plaintext"};this.applyStyles(i,this.cueDiv),this.div=n.document.createElement("div"),i={direction:tg(this.cueDiv),writingMode:e.vertical===""?"horizontal-tb":e.vertical==="lr"?"vertical-lr":"vertical-rl",unicodeBidi:"plaintext",textAlign:e.align==="middle"?"center":e.align,font:t.font,whiteSpace:"pre-line",position:"absolute"},this.applyStyles(i),this.div.appendChild(this.cueDiv);var s=0;switch(e.positionAlign){case"start":s=e.position;break;case"center":s=e.position-e.size/2;break;case"end":s=e.position-e.size;break}e.vertical===""?this.applyStyles({left:this.formatStyle(s,"%"),width:this.formatStyle(e.size,"%")}):this.applyStyles({top:this.formatStyle(s,"%"),height:this.formatStyle(e.size,"%")}),this.move=function(r){this.applyStyles({top:this.formatStyle(r.top,"px"),bottom:this.formatStyle(r.bottom,"px"),left:this.formatStyle(r.left,"px"),right:this.formatStyle(r.right,"px"),height:this.formatStyle(r.height,"px"),width:this.formatStyle(r.width,"px")})}}ns.prototype=Gn(ms.prototype);ns.prototype.constructor=ns;function Le(n){var e,t,i,s;if(n.div){t=n.div.offsetHeight,i=n.div.offsetWidth,s=n.div.offsetTop;var r=(r=n.div.childNodes)&&(r=r[0])&&r.getClientRects&&r.getClientRects();n=n.div.getBoundingClientRect(),e=r?Math.max(r[0]&&r[0].height||0,n.height/r.length):0}this.left=n.left,this.right=n.right,this.top=n.top||s,this.height=n.height||t,this.bottom=n.bottom||s+(n.height||t),this.width=n.width||i,this.lineHeight=e!==void 0?e:n.lineHeight}Le.prototype.move=function(n,e){switch(e=e!==void 0?e:this.lineHeight,n){case"+x":this.left+=e,this.right+=e;break;case"-x":this.left-=e,this.right-=e;break;case"+y":this.top+=e,this.bottom+=e;break;case"-y":this.top-=e,this.bottom-=e;break}};Le.prototype.overlaps=function(n){return this.left<n.right&&this.right>n.left&&this.top<n.bottom&&this.bottom>n.top};Le.prototype.overlapsAny=function(n){for(var e=0;e<n.length;e++)if(this.overlaps(n[e]))return!0;return!1};Le.prototype.within=function(n){return this.top>=n.top&&this.bottom<=n.bottom&&this.left>=n.left&&this.right<=n.right};Le.prototype.overlapsOppositeAxis=function(n,e){switch(e){case"+x":return this.left<n.left;case"-x":return this.right>n.right;case"+y":return this.top<n.top;case"-y":return this.bottom>n.bottom}};Le.prototype.intersectPercentage=function(n){var e=Math.max(0,Math.min(this.right,n.right)-Math.max(this.left,n.left)),t=Math.max(0,Math.min(this.bottom,n.bottom)-Math.max(this.top,n.top)),i=e*t;return i/(this.height*this.width)};Le.prototype.toCSSCompatValues=function(n){return{top:this.top-n.top,bottom:n.bottom-this.bottom,left:this.left-n.left,right:n.right-this.right,height:this.height,width:this.width}};Le.getSimpleBoxPosition=function(n){var e=n.div?n.div.offsetHeight:n.tagName?n.offsetHeight:0,t=n.div?n.div.offsetWidth:n.tagName?n.offsetWidth:0,i=n.div?n.div.offsetTop:n.tagName?n.offsetTop:0;n=n.div?n.div.getBoundingClientRect():n.tagName?n.getBoundingClientRect():n;var s={left:n.left,right:n.right,top:n.top||i,height:n.height||e,bottom:n.bottom||i+(n.height||e),width:n.width||t};return s};function sg(n,e,t,i){function s(p,v){for(var x,S=new Le(p),b=1,T=0;T<v.length;T++){for(;p.overlapsOppositeAxis(t,v[T])||p.within(t)&&p.overlapsAny(i);)p.move(v[T]);if(p.within(t))return p;var L=p.intersectPercentage(t);b>L&&(x=new Le(p),b=L),p=new Le(S)}return x||S}var r=new Le(e),a=e.cue,o=ig(a),l=[];if(a.snapToLines){var c;switch(a.vertical){case"":l=["+y","-y"],c="height";break;case"rl":l=["+x","-x"],c="width";break;case"lr":l=["-x","+x"],c="width";break}var u=r.lineHeight,h=u*Math.round(o),d=t[c]+u,f=l[0];Math.abs(h)>d&&(h=h<0?-1:1,h*=Math.ceil(d/u)*u),o<0&&(h+=a.vertical===""?t.height:t.width,l=l.reverse()),r.move(f,h)}else{var g=r.lineHeight/t.height*100;switch(a.lineAlign){case"center":o-=g/2;break;case"end":o-=g;break}switch(a.vertical){case"":e.applyStyles({top:e.formatStyle(o,"%")});break;case"rl":e.applyStyles({left:e.formatStyle(o,"%")});break;case"lr":e.applyStyles({right:e.formatStyle(o,"%")});break}l=["+y","-x","+x","-y"],r=new Le(e)}var m=s(r,l);e.move(m.toCSSCompatValues(t))}function Ht(){}Ht.StringDecoder=function(){return{decode:function(n){if(!n)return"";if(typeof n!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(n))}}};Ht.convertCueToDOMTree=function(n,e){return!n||!e?null:ul(n,e)};var ng=.05,rg="sans-serif",ag="1.5%";Ht.processCues=function(n,e,t){if(!n||!e||!t)return null;for(;t.firstChild;)t.removeChild(t.firstChild);var i=n.document.createElement("div");i.style.position="absolute",i.style.left="0",i.style.right="0",i.style.top="0",i.style.bottom="0",i.style.margin=ag,t.appendChild(i);function s(u){for(var h=0;h<u.length;h++)if(u[h].hasBeenReset||!u[h].displayState)return!0;return!1}if(!s(e)){for(var r=0;r<e.length;r++)i.appendChild(e[r].displayState);return}var a=[],o=Le.getSimpleBoxPosition(i),l=Math.round(o.height*ng*100)/100,c={font:l+"px "+rg};(function(){for(var u,h,d=0;d<e.length;d++)h=e[d],u=new ns(n,h,c),i.appendChild(u.div),sg(n,u,o,a),h.displayState=u.div,a.push(Le.getSimpleBoxPosition(u))})()};Ht.Parser=function(n,e,t){t||(t=e,e={}),e||(e={}),this.window=n,this.vttjs=e,this.state="INITIAL",this.buffer="",this.decoder=t||new TextDecoder("utf8"),this.regionList=[]};Ht.Parser.prototype={reportOrThrowError:function(n){if(n instanceof we)this.onparsingerror&&this.onparsingerror(n);else throw n},parse:function(n){var e=this;n&&(e.buffer+=e.decoder.decode(n,{stream:!0}));function t(){for(var u=e.buffer,h=0;h<u.length&&u[h]!=="\r"&&u[h]!==` `;)++h;var d=u.substr(0,h);return u[h]==="\r"&&++h,u[h]===` `&&++h,e.buffer=u.substr(h),d}function i(u){var h=new ai;if(ei(u,function(f,g){switch(f){case"id":h.set(f,g);break;case"width":h.percent(f,g);break;case"lines":h.integer(f,g);break;case"regionanchor":case"viewportanchor":var m=g.split(",");if(m.length!==2)break;var p=new ai;if(p.percent("x",m[0]),p.percent("y",m[1]),!p.has("x")||!p.has("y"))break;h.set(f+"X",p.get("x")),h.set(f+"Y",p.get("y"));break;case"scroll":h.alt(f,g,["up"]);break}},/=/,/\s/),h.has("id")){var d=new(e.vttjs.VTTRegion||e.window.VTTRegion);d.width=h.get("width",100),d.lines=h.get("lines",3),d.regionAnchorX=h.get("regionanchorX",0),d.regionAnchorY=h.get("regionanchorY",100),d.viewportAnchorX=h.get("viewportanchorX",0),d.viewportAnchorY=h.get("viewportanchorY",100),d.scroll=h.get("scroll",""),e.onregion&&e.onregion(d),e.regionList.push({id:h.get("id"),region:d})}}function s(u){var h=new ai;ei(u,function(d,f){switch(d){case"MPEGT":h.integer(d+"S",f);break;case"LOCA":h.set(d+"L",Vn(f));break}},/[^\d]:/,/,/),e.ontimestampmap&&e.ontimestampmap({MPEGTS:h.get("MPEGTS"),LOCAL:h.get("LOCAL")})}function r(u){u.match(/X-TIMESTAMP-MAP/)?ei(u,function(h,d){switch(h){case"X-TIMESTAMP-MAP":s(d);break}},/=/):ei(u,function(h,d){switch(h){case"Region":i(d);break}},/:/)}try{var a;if(e.state==="INITIAL"){if(!/\r\n|\n/.test(e.buffer))return this;a=t();var o=a.match(/^WEBVTT([ \t].*)?$/);if(!o||!o[0])throw new we(we.Errors.BadSignature);e.state="HEADER"}for(var l=!1;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(l?l=!1:a=t(),e.state){case"HEADER":/:/.test(a)?r(a):a||(e.state="ID");continue;case"NOTE":a||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(a)){e.state="NOTE";break}if(!a)continue;e.cue=new(e.vttjs.VTTCue||e.window.VTTCue)(0,0,"");try{e.cue.align="center"}catch{e.cue.align="middle"}if(e.state="CUE",a.indexOf("-->")===-1){e.cue.id=a;continue}case"CUE":try{Z0(a,e.cue,e.regionList)}catch(u){e.reportOrThrowError(u),e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":var c=a.indexOf("-->")!==-1;if(!a||c&&(l=!0)){e.oncue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}e.cue.text&&(e.cue.text+=` `),e.cue.text+=a.replace(/\u2028/g,` `).replace(/u2029/g,` `);continue;case"BADCUE":a||(e.state="ID");continue}}}catch(u){e.reportOrThrowError(u),e.state==="CUETEXT"&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state=e.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this},flush:function(){var n=this;try{if(n.buffer+=n.decoder.decode(),(n.cue||n.state==="HEADER")&&(n.buffer+=` `,n.parse()),n.state==="INITIAL")throw new we(we.Errors.BadSignature)}catch(e){n.reportOrThrowError(e)}return n.onflush&&n.onflush(),this}};var og=Ht,lg="auto",cg={"":1,lr:1,rl:1},ug={start:1,center:1,end:1,left:1,right:1,auto:1,"line-left":1,"line-right":1};function hg(n){if(typeof n!="string")return!1;var e=cg[n.toLowerCase()];return e?n.toLowerCase():!1}function qs(n){if(typeof n!="string")return!1;var e=ug[n.toLowerCase()];return e?n.toLowerCase():!1}function hl(n,e,t){this.hasBeenReset=!1;var i="",s=!1,r=n,a=e,o=t,l=null,c="",u=!0,h="auto",d="start",f="auto",g="auto",m=100,p="center";Object.defineProperties(this,{id:{enumerable:!0,get:function(){return i},set:function(v){i=""+v}},pauseOnExit:{enumerable:!0,get:function(){return s},set:function(v){s=!!v}},startTime:{enumerable:!0,get:function(){return r},set:function(v){if(typeof v!="number")throw new TypeError("Start time must be set to a number.");r=v,this.hasBeenReset=!0}},endTime:{enumerable:!0,get:function(){return a},set:function(v){if(typeof v!="number")throw new TypeError("End time must be set to a number.");a=v,this.hasBeenReset=!0}},text:{enumerable:!0,get:function(){return o},set:function(v){o=""+v,this.hasBeenReset=!0}},region:{enumerable:!0,get:function(){return l},set:function(v){l=v,this.hasBeenReset=!0}},vertical:{enumerable:!0,get:function(){return c},set:function(v){var x=hg(v);if(x===!1)throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");c=x,this.hasBeenReset=!0}},snapToLines:{enumerable:!0,get:function(){return u},set:function(v){u=!!v,this.hasBeenReset=!0}},line:{enumerable:!0,get:function(){return h},set:function(v){if(typeof v!="number"&&v!==lg)throw new SyntaxError("Line: an invalid number or illegal string was specified.");h=v,this.hasBeenReset=!0}},lineAlign:{enumerable:!0,get:function(){return d},set:function(v){var x=qs(v);x?(d=x,this.hasBeenReset=!0):console.warn("lineAlign: an invalid or illegal string was specified.")}},position:{enumerable:!0,get:function(){return f},set:function(v){if(v<0||v>100)throw new Error("Position must be between 0 and 100.");f=v,this.hasBeenReset=!0}},positionAlign:{enumerable:!0,get:function(){return g},set:function(v){var x=qs(v);x?(g=x,this.hasBeenReset=!0):console.warn("positionAlign: an invalid or illegal string was specified.")}},size:{enumerable:!0,get:function(){return m},set:function(v){if(v<0||v>100)throw new Error("Size must be between 0 and 100.");m=v,this.hasBeenReset=!0}},align:{enumerable:!0,get:function(){return p},set:function(v){var x=qs(v);if(!x)throw new SyntaxError("align: an invalid or illegal alignment string was specified.");p=x,this.hasBeenReset=!0}}}),this.displayState=void 0}hl.prototype.getCueAsHTML=function(){return WebVTT.convertCueToDOMTree(window,this.text)};var dg=hl,fg={"":!0,up:!0};function gg(n){if(typeof n!="string")return!1;var e=fg[n.toLowerCase()];return e?n.toLowerCase():!1}function qt(n){return typeof n=="number"&&n>=0&&n<=100}function mg(){var n=100,e=3,t=0,i=100,s=0,r=100,a="";Object.defineProperties(this,{width:{enumerable:!0,get:function(){return n},set:function(o){if(!qt(o))throw new Error("Width must be between 0 and 100.");n=o}},lines:{enumerable:!0,get:function(){return e},set:function(o){if(typeof o!="number")throw new TypeError("Lines must be set to a number.");e=o}},regionAnchorY:{enumerable:!0,get:function(){return i},set:function(o){if(!qt(o))throw new Error("RegionAnchorX must be between 0 and 100.");i=o}},regionAnchorX:{enumerable:!0,get:function(){return t},set:function(o){if(!qt(o))throw new Error("RegionAnchorY must be between 0 and 100.");t=o}},viewportAnchorY:{enumerable:!0,get:function(){return r},set:function(o){if(!qt(o))throw new Error("ViewportAnchorY must be between 0 and 100.");r=o}},viewportAnchorX:{enumerable:!0,get:function(){return s},set:function(o){if(!qt(o))throw new Error("ViewportAnchorX must be between 0 and 100.");s=o}},scroll:{enumerable:!0,get:function(){return a},set:function(o){var l=gg(o);l===!1?console.warn("Scroll: an invalid or illegal string was specified."):a=l}}})}var pg=mg,et=W0,xt=cl.exports={WebVTT:og,VTTCue:dg,VTTRegion:pg};et.vttjs=xt;et.WebVTT=xt.WebVTT;var Eg=xt.VTTCue,vg=xt.VTTRegion,xg=et.VTTCue,yg=et.VTTRegion;xt.shim=function(){et.VTTCue=Eg,et.VTTRegion=vg};xt.restore=function(){et.VTTCue=xg,et.VTTRegion=yg};et.VTTCue||xt.shim();var Tg=cl.exports;const Sg=Al(Tg);class dl{constructor(){this.disableCallbacks=[],this.disposeCallbacks=[],this.eventListeners={}}onDisable(e){this.disableCallbacks.push(e)}disable(){for(;this.disableCallbacks.length;){const e=this.disableCallbacks.pop();e==null||e()}}onDispose(e){this.disposeCallbacks.push(e)}dispose(){for(;this.disposeCallbacks.length;){const e=this.disposeCallbacks.pop();e==null||e()}}isAvailable(){throw new Error("Not implemented")}enable(e){throw new Error("Not implemented")}get handlers(){throw new Error("Not implemented")}addEventListener(e,t){if(!t)return;let i=this.eventListeners[e];i||(i=this.eventListeners[e]=[]),i.push(t)}removeEventListener(e,t){if(!t)return;const i=this.eventListeners[e];if(!i)return;const s=i.findIndex(r=>r===t);s!==-1&&i.splice(s,1),i.length||(this.eventListeners[e]=void 0)}dispatchEvent(e){const t=this.eventListeners[e.type];if(!t)return!0;for(const i of t)"handleEvent"in i?i.handleEvent(e):i(e);return e.cancelable!==!1||!e.defaultPrevented}}function bg(n){const e=n.closest("[data-video-player-root]");e&&(e.requestFullscreen?e.requestFullscreen().catch():e.webkitRequestFullscreen?e.webkitRequestFullscreen():n.webkitEnterFullscreen&&n.webkitEnterFullscreen())}function Hn(){(document.fullscreenElement||document.webkitFullscreenElement)&&(document.exitFullscreen?document.exitFullscreen().catch():document.webkitExitFullscreen&&document.webkitExitFullscreen())}let $e=null,Ui=null;class Lg{}const Ag=(window==null?void 0:window.CustomEvent)||Lg,as=class as extends Ag{constructor(e){super(as.type,{detail:{entityId:e}})}};as.type="videoChange";let fi=as;class gi extends dl{constructor(e,t){super(),this.store=e,this.mediaElement=t,this._handlers=null,this._apiToken=null;const i=$e,s=Ui;if(!i||!s)return;i.isConnected&&this.store.getState().set({chromecastConnected:i.isConnected});const r=()=>{this.store.getState().set({chromecastConnected:i.isConnected})};s.addEventListener(cast.framework.RemotePlayerEventType.IS_CONNECTED_CHANGED,r),this.onDispose(()=>{s.removeEventListener(cast.framework.RemotePlayerEventType.IS_CONNECTED_CHANGED,r)}),this._handlers=new Cg(this.store,i,s,()=>{this.store.getState().set({currentTime:0,hasEnded:!1}),this.loadMedia()}),this.onDispose(()=>{this._handlers=null})}static isAvailable(){return!!($e&&Ui)}isAvailable(){return gi.isAvailable()}requestSession(){if(!this.isAvailable())throw new Error("Can't request cast session (browser doesn't have Cast APIs)");Kn().requestSession()}enable(){var m,p,v,x,S,b;const e=$e,t=Ui;if(!e||!t)throw new Error("ChromecastTech is not available in this browser");const{RemotePlayerEventType:i}=cast.framework,s=this.getActiveTextTrack();document.pictureInPictureElement&&document.exitPictureInPicture(),(m=this.mediaElement.mux)!=null&&m.deleted||((p=this.mediaElement.mux)==null||p.destroy(),this.mediaElement.mux=void 0),Hn(),this.store.getState().set({isFullScreen:!1}),this.store.getState().set({isInitialized:!0,chromecastAvailable:!0,chromecastConnected:e.isConnected,chromecastDeviceName:(S=Cl((x=(v=cast.framework.CastContext.getInstance())==null?void 0:v.getCurrentSession())==null?void 0:x.getCastDevice().friendlyName))!=null?S:"",isPlaying:!e.isPaused,isMuted:e.isMuted,volume:e.volumeLevel,subtitles:Ta((b=e.mediaInfo)==null?void 0:b.tracks),showNativeCues:!1,currentLanguage:s?rs(s):"",isBuffering:!1,isSeeking:!1,isScrubbing:!1,playbackSpeed:1,aspectRatio:1/li,qualityLevels:[],quality:"auto",currentAutoLevel:null,buffered:[],airPlayAvailable:!1,fullScreenAvailable:!1,pictureInPictureAvailable:!1,autoplayAvailable:!0,volumeChangeAvailable:e.canControlVolume,muteChangeAvailable:e.canControlVolume,duration:e.duration});const{mediaId:r}=this.store.getState(),a=()=>{var T;((T=e.mediaInfo)==null?void 0:T.contentId)===r&&e.isMediaLoaded&&this.store.getState().set({currentTime:e.currentTime})};t.addEventListener(i.CURRENT_TIME_CHANGED,a),this.onDisable(()=>{t.removeEventListener(i.CURRENT_TIME_CHANGED,a)});const o=()=>{var T;((T=e.mediaInfo)==null?void 0:T.contentId)===r&&e.isMediaLoaded&&this.store.getState().set({duration:e.duration})};t.addEventListener(i.DURATION_CHANGED,o),this.onDisable(()=>{t.removeEventListener(i.DURATION_CHANGED,o)});const l=()=>{this.store.getState().set({volume:e.volumeLevel})};t.addEventListener(i.VOLUME_LEVEL_CHANGED,l),this.onDisable(()=>{t.removeEventListener(i.VOLUME_LEVEL_CHANGED,l)});const c=()=>{this.store.getState().set({isMuted:e.isMuted})};t.addEventListener(i.IS_MUTED_CHANGED,c),this.onDisable(()=>{t.removeEventListener(i.IS_MUTED_CHANGED,c)});const u=()=>{this.store.getState().set({isPlaying:!e.isPaused})};t.addEventListener(i.IS_PAUSED_CHANGED,u),this.onDisable(()=>{t.removeEventListener(i.IS_PAUSED_CHANGED,u)});const h=()=>{var T;((T=e.mediaInfo)==null?void 0:T.contentId)===r&&this.store.getState().set({hasEnded:!e.isMediaLoaded})};t.addEventListener(i.IS_MEDIA_LOADED_CHANGED,h),this.onDisable(()=>{t.removeEventListener(i.IS_MEDIA_LOADED_CHANGED,h)});const d=()=>{var A;const T=this.store.getState().subtitles,L=Ta((A=e.mediaInfo)==null?void 0:A.tracks);_a(T,L)||this.store.getState().set({subtitles:L})};t.addEventListener(i.MEDIA_INFO_CHANGED,d),this.onDisable(()=>{t.removeEventListener(i.MEDIA_INFO_CHANGED,d)});const f=Vi(()=>{const T=this.getActiveTextTrack();this.store.getState().set({currentLanguage:T?rs(T):""})},0);t.addEventListener(i.MEDIA_INFO_CHANGED,f),this.onDisable(()=>{t.removeEventListener(i.MEDIA_INFO_CHANGED,f)});const g=T=>{var L;(L=T.value)!=null&&L.entity&&(this.store.getState().mediaId!==T.value.entity&&this.dispatchEvent(new fi(T.value.entity)),this.store.getState().set({hasEnded:!1}))};t.addEventListener(i.MEDIA_INFO_CHANGED,g),this.onDisable(()=>{t.removeEventListener(i.MEDIA_INFO_CHANGED,g)}),this.loadMedia()}disable(){super.disable(),this.store.getState().resetTech()}dispose(){super.dispose()}get handlers(){return this._handlers}setApiToken(e){this._apiToken=e}isActive(){var e;return(e=$e==null?void 0:$e.isConnected)!=null?e:!1}getActiveTextTrack(){var s,r;const e=$e,t=vn();if(!((s=t==null?void 0:t.activeTrackIds)!=null&&s.length)||!(e!=null&&e.isMediaLoaded))return;const i=new Set(t.activeTrackIds);return(r=e.mediaInfo)==null?void 0:r.tracks.find(a=>a.type==="TEXT"&&i.has(a.trackId))}loadMedia(){var d,f,g;const e=this.handlers;if(!e)throw new Error("Can't loadMedia before handlers are defined");const{mediaId:t,mediaTitle:i,currentTime:s,src:r,chromecastQueue:a,mediaType:o}=this.store.getState(),l=vn();if((d=l==null?void 0:l.media)!=null&&d.contentId&&((f=l==null?void 0:l.media)==null?void 0:f.contentId)===t)return;const c=new chrome.cast.media.MediaInfo(t,o!=null?o:"video/mp4");c.contentId=t,c.contentUrl=r,c.entity=t,c.metadata=new chrome.cast.media.GenericMediaMetadata,c.metadata.title=i;const u=new chrome.cast.media.LoadRequest(c);if(u.credentials=(g=this._apiToken)!=null?g:"",u.credentialsType="web",u.currentTime=s,a){const m=a.map(x=>{const S=new chrome.cast.media.MediaInfo(x.entity,x.type);return S.entity=x.entity,S.metadata=new chrome.cast.media.GenericMediaMetadata,S.metadata.title=x.title,S.metadata.subtitle=x.subtitle,S.tracks=[],new chrome.cast.media.QueueItem(S)}),p=chrome.cast.media.QueueData,v=a.findIndex(x=>x.entity===t);u.queueData=new p(void 0,void 0,void 0,void 0,m,v===-1?0:v,s)}const h=fl();if(!h)throw new Error("Can't loadMedia without a cast session");this.store.getState().set({isBuffering:!0}),h.loadMedia(u).then(()=>{const m=Ga();m&&e.changeLanguage(m);const p=$e;this.store.getState().set({isBuffering:!1,isPlaying:!(p!=null&&p.isPaused)})},m=>{us.error(m)})}addEventListener(e,t){return super.addEventListener(e,t)}removeEventListener(e,t){return super.removeEventListener(e,t)}}class Cg{constructor(e,t,i,s){this.store=e,this.remotePlayer=t,this.remotePlayerController=i,this.reloadMedia=s,this.relativeSeek=Nt(function(r){const a=Ie(this.remotePlayer.currentTime+r,0,this.remotePlayer.duration);this.remotePlayer.currentTime=a,this.remotePlayerController.seek()},150,{trailing:!1})}play(){this.remotePlayer.isPaused&&this.remotePlayerController.playOrPause()}pause(){this.remotePlayer.isPaused||this.remotePlayerController.playOrPause()}setCurrentTime(e){this.remotePlayer.currentTime=e,this.remotePlayerController.seek()}back5(){this.relativeSeek(-5)}back15(){this.relativeSeek(-15)}back30(){this.relativeSeek(-30)}forward5(){this.relativeSeek(5)}forward15(){this.relativeSeek(15)}forward30(){this.relativeSeek(30)}mute(){this.remotePlayer.isMuted||this.remotePlayerController.muteOrUnmute()}unmute(){this.remotePlayer.isMuted&&this.remotePlayerController.muteOrUnmute()}replay(){this.reloadMedia()}setVolume(e){this.remotePlayer.volumeLevel=e,this.remotePlayerController.setVolumeLevel()}raiseVolume(){const e=Ie(this.remotePlayer.volumeLevel+.1,0,1);this.remotePlayer.isMuted&&this.remotePlayerController.muteOrUnmute(),this.remotePlayer.volumeLevel=e,this.remotePlayerController.setVolumeLevel()}lowerVolume(){const e=Ie(this.remotePlayer.volumeLevel-.1,0,1);this.remotePlayer.volumeLevel=e,this.remotePlayerController.setVolumeLevel()}changeLanguage(e){var r;const t=vn();if(!t)return;const i=(r=this.remotePlayer.mediaInfo)==null?void 0:r.tracks.filter(a=>a.type!=="TEXT"?!0:e?rs(a)===e:!1).map(a=>a.trackId),s=new chrome.cast.media.EditTracksInfoRequest(i);t.editTracksInfo(s,()=>null,()=>null),pt(e||"")}cast(){Kn().requestSession()}setAutoplayEnabled(e){this.store.getState().autoplayAvailable&&this.store.getState().set({autoplayEnabled:e})}}function fl(){return Kn().getCurrentSession()}function vn(){const n=fl(),e=n==null?void 0:n.getMediaSession();return e!=null?e:null}function Kn(){return cast.framework.CastContext.getInstance()}function Ta(n){return!n||!n.length?[]:n.filter(e=>e.type.toUpperCase()==="TEXT").map(e=>({language:e.language,label:rs(e),trackId:e.trackId}))}function rs(n){let e=n.name;return e||(e=n.language==="en"?"English":n.language),e}if(typeof chrome<"u"){window.__onGCastApiAvailable=n=>{var e;n&&typeof cast<"u"&&(cast.framework.CastContext.getInstance().setOptions({receiverApplicationId:ls.CHROMECAST_RECEIVER_ID,autoJoinPolicy:(e=chrome.cast)==null?void 0:e.AutoJoinPolicy.TAB_AND_ORIGIN_SCOPED}),$e=new cast.framework.RemotePlayer,Ui=new cast.framework.RemotePlayerController($e))};{const n=document.createElement("script");n.src="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1",document.body.appendChild(n)}}class qe extends dl{constructor(e,t){super(),this.store=e,this.videoElement=t,this._handlers=null,this.constructor===qe&&(this._handlers=new gl(this.store,this.videoElement),this.onDispose(()=>{this._handlers=null}),this._addAirPlayListeners())}_addAirPlayListeners(){if(!qe.browserHasAirPlaySupport())return;const e=()=>{const{isInitialized:t,isPlaying:i}=this.store.getState(),s=this.videoElement.webkitCurrentPlaybackTargetIsWireless,r=!s,a=!s,o=Sa()&&!s;(s||t)&&(this.store.getState().set({airPlayConnected:s,volumeChangeAvailable:r,fullScreenAvailable:a,pictureInPictureAvailable:o}),Hn()),s&&t&&!i&&this.showFirstFrameWhenStartingToAirPlay()};this.videoElement.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",e),this.onDispose(()=>{this.videoElement.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",e)})}static isAvailable(e){return e||(e=document.createElement("video")),e.canPlayType('video/mp4; codecs="avc1.42E01E,mp4a.40.2"')!==""}isAvailable(){return qe.isAvailable(this.videoElement)}_initTechState(){var r,a;const{volume:e,mute:t}=(r=lc())!=null?r:{volume:1,mute:!1},i=(a=cc("video"))!=null?a:1,s=this.videoElement.webkitCurrentPlaybackTargetIsWireless;this.store.getState().set({isMuted:t,isBuffering:!1,isSeeking:!1,isScrubbing:!1,playbackSpeed:i,volume:e,subtitles:[],showNativeCues:!1,aspectRatio:1/li,isInitialized:!1,qualityLevels:[],quality:"auto",currentAutoLevel:null,airPlayConnected:s,airPlayAvailable:!1,pictureInPictureAvailable:Sa()&&!s,fullScreenAvailable:!s,autoplayAvailable:!0,buffered:[],chromecastDeviceName:"",chromecastAvailable:gi.isAvailable(),volumeChangeAvailable:!s,muteChangeAvailable:!0})}_connect(){const e=this.videoElement,{currentTime:t,volume:i,isMuted:s,src:r}=this.store.getState();e.volume=i,e.muted=s,r&&(e.src=r,e.preload="metadata",e.currentTime=t),this.onDisable(()=>{e.preload="none",e.removeAttribute("src")}),this.onDisable(this.store.subscribe(a=>a.src,a=>{if(!a)return;const{currentTime:o,isPlaying:l}=this.store.getState();e.src=a,e.currentTime=o,l&&e.play()}))}_analytics(e){const i=this.store.getState().muxData;i&&(!this.videoElement.mux||this.videoElement.mux.deleted?bc({mediaElement:this.videoElement,data:i,initTime:e}):Ac(this.videoElement,i))}_listen(e){const t=this.videoElement,i=this.store,s=()=>{i.getState().set({isPlaying:!t.paused,hasEnded:t.currentTime>t.duration||Ki(t.currentTime,t.duration),duration:t.duration,isMuted:t.muted,aspectRatio:t.videoWidth/t.videoHeight}),Zn({mute:t.muted,volume:t.volume})};t.addEventListener("loadedmetadata",s),this.onDisable(()=>t.removeEventListener("loadedmetadata",s));const r=()=>{i.getState().set({isBuffering:!0})};t.addEventListener("waiting",r),this.onDisable(()=>t.removeEventListener("waiting",r));const a=()=>{i.getState().set({isBuffering:!1})};t.addEventListener("playing",a),this.onDisable(()=>t.removeEventListener("playing",a));const o=()=>{i.getState().set({isMuted:t.muted,volume:t.volume}),Zn({mute:t.muted,volume:t.volume})};t.addEventListener("volumechange",o),this.onDisable(()=>t.removeEventListener("volumechange",o));const l=()=>{i.getState().set({isPlaying:!1})};t.addEventListener("pause",l),this.onDisable(()=>t.removeEventListener("pause",l));const c=()=>{i.getState().set({isSeeking:!0})};t.addEventListener("seeking",c),this.onDisable(()=>t.removeEventListener("seeking",c));const u=()=>{i.getState().set({isSeeking:!1})};t.addEventListener("seeked",u),this.onDisable(()=>t.removeEventListener("seeked",u));const h=()=>{i.getState().set({isPlaying:!0,hasEnded:!1})};t.addEventListener("play",h),this.onDisable(()=>t.removeEventListener("play",h));const d=()=>{i.getState().set({hasEnded:!0})};t.addEventListener("ended",d),this.onDisable(()=>t.removeEventListener("ended",d));const f=()=>{this.store.getState().isInitialized&&i.getState().set({playbackSpeed:t.playbackRate})};t.addEventListener("ratechange",f),this.onDisable(()=>t.removeEventListener("ratechange",f));const g=()=>{i.getState().set({isBuffering:!1})};t.addEventListener("canplay",g),this.onDisable(()=>t.removeEventListener("canplay",g));const m=()=>{var _,N;const M=(N=(_=[...t.textTracks].find(({mode:B})=>B==="showing"))==null?void 0:_.label)!=null?N:"";i.getState().set({currentLanguage:M})};t.textTracks.addEventListener("change",m),this.onDisable(()=>t.textTracks.removeEventListener("change",m));const p=()=>{const M=[...t.textTracks].filter(N=>!!(N.language||N.label)).map(N=>({label:N.label,language:N.language})),_=Ga();if(_)for(const N of t.textTracks)N.label===_?N.mode="showing":N.mode==="showing"&&(N.mode="disabled");i.getState().set({subtitles:M})};t.textTracks.addEventListener("addtrack",p),this.onDisable(()=>t.textTracks.removeEventListener("addtrack",p)),p();let v=Rg(t);this.onDisable(()=>{v&&(v.innerHTML="",v=null)});const x=()=>{Xs(t,v,!0)},S=()=>{Xs(t,v)},b=M=>{const _=M.track;_&&(_.addEventListener("cuechange",S),this.onDisable(()=>_.removeEventListener("cuechange",S)))};t.textTracks.addEventListener("addtrack",b),this.onDisable(()=>t.textTracks.removeEventListener("addtrack",b));const T=M=>{const _=M.track;_==null||_.removeEventListener("cuechange",S),Xs(t,v)};t.textTracks.addEventListener("removetrack",T),this.onDisable(()=>t.textTracks.removeEventListener("removetrack",T)),t.textTracks.addEventListener("change",x),this.onDisable(()=>t.textTracks.removeEventListener("change",x));const L=()=>{this.store.getState().set({showNativeCues:!0})};t.addEventListener("webkitbeginfullscreen",L),this.onDisable(()=>t.removeEventListener("webkitbeginfullscreen",L)),t.addEventListener("enterpictureinpicture",L),this.onDisable(()=>t.removeEventListener("enterpictureinpicture",L));const A=()=>{this.store.getState().set({showNativeCues:!1}),x()};if(t.addEventListener("webkitendfullscreen",A),this.onDisable(()=>t.removeEventListener("webkitendfullscreen",A)),t.addEventListener("leavepictureinpicture",A),this.onDisable(()=>t.removeEventListener("leavepictureinpicture",A)),v){const M=Vi(x,100),_=new ResizeObserver(N=>{Rl(N)&&M()});_.observe(v),this.onDisable(()=>{_.disconnect(),M.cancel()})}const P=()=>{const{playbackSpeed:M,wasEverPlayed:_,airPlayConnected:N}=this.store.getState();t.playbackRate=M;const B=()=>{i.getState().set({isInitialized:!0}),this.setupMediaSession()};if(!e||_||N){B();return}ci({isUserAction:!1}).then(async({result:G})=>{if(G)return t.play()}).finally(()=>{B()})};t.addEventListener("loadedmetadata",P),this.onDisable(()=>t.textTracks.removeEventListener("loadedmetadata",P));const D=()=>{const M=Ki(t.currentTime,t.duration);i.getState().set({hasEnded:M,currentTime:t.currentTime})};t.addEventListener("timeupdate",D),this.onDisable(()=>t.removeEventListener("timeupdate",D)),t.addEventListener("seeking",D),this.onDisable(()=>t.removeEventListener("seeking",D));const I=()=>{const M=[];for(let _=0;_<t.buffered.length;_++){const N=t.buffered.start(_),B=t.buffered.end(_);M.push([N,B])}this.store.getState().set({buffered:M})};t.addEventListener("progress",I),this.onDisable(()=>t.removeEventListener("progress",I));const k=()=>{const M=!!(document.fullscreenElement||document.webkitFullscreenElement);this.store.getState().set({isFullScreen:M})};document.addEventListener("webkitfullscreenchange",k),this.onDisable(()=>{document.removeEventListener("webkitfullscreenchange",k)}),document.addEventListener("fullscreenchange",k),this.onDisable(()=>{document.removeEventListener("fullscreenchange",k)})}enable(e){const t=$i.utils.now(),i=this.videoElement,s=this.store;if(!i)throw new Error("Can't enable NativeTech without a <video> element");jl().then(o=>{s.getState().set({deviceSupportsVideoCodecs:o})}),this._initTechState(),this._analytics(t),this._listen(e),this._connect(),qe.browserHasAirPlaySupport()&&(this.videoElement.disableRemotePlayback||this.videoElement.hasAttribute("disableremoteplayback")||this.setupAirplay());const{isPlaying:r,airPlayConnected:a}=s.getState();r?i.play():a&&this.showFirstFrameWhenStartingToAirPlay()}disable(){super.disable(),this.store.getState().resetTech()}dispose(){super.dispose()}get handlers(){return this._handlers}static browserHasAirPlaySupport(){return typeof WebKitPlaybackTargetAvailabilityEvent<"u"&&"remote"in HTMLVideoElement.prototype}setupAirplay(){const e=t=>{this.store.getState().set({airPlayAvailable:t})};this.videoElement.remote.watchAvailability(e).then(t=>{this.onDisable(()=>{this.videoElement.remote.cancelWatchAvailability(t)})})}showFirstFrameWhenStartingToAirPlay(){this.videoElement.play().then(()=>{this.videoElement.pause()})}setupMediaSession(){if(!("mediaSession"in navigator))return;const e=this.store,t=this.videoElement;this.onDisable(e.subscribe(a=>a.isPlaying,a=>{navigator.mediaSession.playbackState=a?"playing":"paused"}));const i=[256,480,960,1280,1920],s=a=>{if(!a){navigator.mediaSession.metadata=null;return}const{thumbnail:o,...l}=a;if(o){const c="jpeg";l.artwork=i.map(u=>({src:$a({image:o,format:c,width:u}),sizes:`${u}x${Math.floor(u*li)}`,type:`image/${c}`}))}else l.artwork=[];navigator.mediaSession.metadata=new MediaMetadata(l)},r=e.subscribe(a=>{var o;return(o=a.mediaSessionMetadata)!=null?o:void 0},s,{equalityFn:oi,fireImmediately:!0});if(this.onDisable(()=>{r(),navigator.mediaSession.metadata=null}),typeof navigator.mediaSession.setPositionState=="function"){const a=l=>({duration:l.duration,playbackRate:l.playbackSpeed,position:l.currentTime&&l.currentTime<l.duration?l.currentTime:0});navigator.mediaSession.setPositionState(a(e.getState()));const o=e.subscribe(a,l=>navigator.mediaSession.setPositionState(l),{equalityFn:oi});this.onDisable(()=>{navigator.mediaSession.setPositionState(void 0),o()})}if(navigator.mediaSession.setActionHandler("play",()=>void t.play()),this.onDisable(()=>navigator.mediaSession.setActionHandler("play",null)),navigator.mediaSession.setActionHandler("pause",()=>t.pause()),this.onDisable(()=>navigator.mediaSession.setActionHandler("pause",null)),navigator.mediaSession.setActionHandler("seekto",a=>{t.currentTime=Number(a.seekTime)}),this.onDisable(()=>navigator.mediaSession.setActionHandler("seekto",null)),navigator.mediaSession.setActionHandler("seekbackward",a=>{const o=-1*(a.seekOffset||30);t.currentTime=xn(t,o)}),this.onDisable(()=>navigator.mediaSession.setActionHandler("seekbackward",null)),navigator.mediaSession.setActionHandler("seekforward",a=>{const o=a.seekOffset||30;t.currentTime=xn(t,o)}),this.onDisable(()=>navigator.mediaSession.setActionHandler("seekforward",null)),navigator.mediaSession.coordinator){let a=function(){o.state==="waiting"&&o.join().then(async()=>{var l;if(((l=navigator.mediaSession.metadata)==null?void 0:l.trackIdentifier)!==void 0)return o.setTrack(navigator.mediaSession.metadata.trackIdentifier)})};const o=navigator.mediaSession.coordinator;a(),o.addEventListener("coordinatorstatechange",a),this.onDisable(()=>{o.removeEventListener("coordinatorstatechange",a)})}}}class gl{constructor(e,t){this.store=e,this.videoElement=t,this.relativeSeek=Nt(function(i){const s=xn(this.videoElement,i);this._setCurrentTime(s)},150,{trailing:!1})}play(){var e;zs()?(e=navigator.mediaSession.coordinator)==null||e.play():this.videoElement.play()}pause(){var e;zs()?(e=navigator.mediaSession.coordinator)==null||e.pause():this.videoElement.pause()}mute(){this.videoElement.muted=!0}unmute(){this.videoElement.volume===0&&(this.videoElement.volume=.1),this.videoElement.muted=!1}_setCurrentTime(e){var t;zs()?(t=navigator.mediaSession.coordinator)==null||t.seekTo(e):this.videoElement.currentTime=e}setCurrentTime(e){this.store.getState().isScrubbing||this._setCurrentTime(e)}setPlaybackSpeed(e){this.videoElement.playbackRate=e,uc(e,"video")}changeLanguage(e){pt(e||"");for(const t of this.videoElement.textTracks)t.label===e?t.mode="showing":t.mode==="showing"&&(t.mode="disabled")}replay(){this.videoElement.addEventListener("seeked",()=>{this.play()},{once:!0}),this._setCurrentTime(0)}setVolume(e){this.store.getState().volumeChangeAvailable&&(this.videoElement.volume=e)}raiseVolume(){const e=Ie(this.videoElement.volume+.1,0,1);this.setVolume(e),this.videoElement.muted=!1}lowerVolume(){const e=Ie(this.videoElement.volume-.1,0,1);this.setVolume(e)}forward30(){this.relativeSeek(30)}back30(){this.relativeSeek(-30)}forward5(){this.relativeSeek(5)}back5(){this.relativeSeek(-5)}forward15(){this.relativeSeek(15)}back15(){this.relativeSeek(-15)}nextFrame(){this.relativeSeek(1/24)}previousFrame(){this.relativeSeek(-1/24)}modifyPlaybackSpeed({modification:e}){const t=this.videoElement.playbackRate,i=e==="raise"?Qs.find(s=>s>t):Il(Qs,s=>s<t);typeof i=="number"&&this.setPlaybackSpeed(i)}raisePlaybackSpeed(){this.modifyPlaybackSpeed({modification:"raise"})}lowerPlaybackSpeed(){this.modifyPlaybackSpeed({modification:"lower"})}airPlay(){var e,t;this.store.getState().airPlayAvailable&&((t=(e=this.videoElement).webkitShowPlaybackTargetPicker)==null||t.call(e))}cast(){this.store.getState().chromecastAvailable&&cast.framework.CastContext.getInstance().requestSession()}requestFullScreen(){this.store.getState().fullScreenAvailable&&bg(this.videoElement)}exitFullScreen(){Hn()}setAutoplayEnabled(e){this.store.getState().autoplayAvailable&&this.store.getState().set({autoplayEnabled:e})}}function zs(){var n,e;return"mediaSession"in navigator&&((e=(n=navigator.mediaSession)==null?void 0:n.coordinator)==null?void 0:e.state)==="joined"}function xn(n,e){return Ie(n.currentTime+e,0,n.duration)}function Sa(){return!((navigator==null?void 0:navigator.standalone)&&/iphone|ipod|ipad/gi.test(navigator.platform)&&/Safari/i.test(navigator.appVersion))&&document.pictureInPictureEnabled}function Rg(n){var t;const e=n.closest("[data-video-player-root]");return(t=e==null?void 0:e.querySelector("[data-subtitles-container]"))!=null?t:null}function Xs(n,e,t=!1){if(!e)return;const i=[];for(const s of n.textTracks)s.mode==="showing"&&s.activeCues&&i.push(...s.activeCues);if(t){e.innerHTML="";for(const s of i)s.displayState=void 0}Sg.WebVTT.processCues(window,i,e)}function Ig(n){Pa("recoveryLimit",n)}function wg(n){Pa("mediaErrorRecoveryFailed",n)}function Dg({message:n,fatal:e,details:t}){os({category:"error_type",message:`message: ${n}, fatal: ${e}, details: ${t}`,level:"info"})}function kg({from:n,to:e}){os({category:"quality_level_change",message:`level changed from ${n}p to ${e}p`,level:"info"})}function _g(){os({category:"quality_level_change",message:"level changed to auto",level:"info"})}function Pg(n){os({category:"recovery_attempts",message:`${n}`,level:"info"})}function Og(n){wl("info",n)}const me={setRecoveryLimitTag:Ig,setMediaErrorRecoveryTag:wg,addErrorTypeBreadcrumb:Dg,addLevelChangeBreadcrumb:kg,addBreadCrumbAutoQualityRestored:_g,addRecoveryAttemptsBreadcrumb:Pg,setContext:Og},Fg=10;let ft=0;const Di=()=>ft>=Fg;class ps extends qe{constructor(e,t){super(e,t),this.store=e,this.videoElement=t,this.hls=null,this._handlers=null,this._reportHLSErrorOncePerType=Oa(function(i){me.setRecoveryLimitTag(Di()),me.setContext({message:i.details,code:i.type}),kt(new Error(js(i)))},js),this._handlers=new Mg(this.store,this.videoElement),this.onDispose(()=>{this._handlers=null})}_connect(){const e=this.videoElement,{src:t,playbackSpeed:i,volume:s,isMuted:r}=this.store.getState();e.volume=s,e.muted=r,e.playbackRate=i;const a=this.hls;if(!a)throw new Error("MediaSourceTech.hls isn't defined");if(t){const o=()=>{a.loadSource(t),this._appendAirplaySourceAlternative(t)};a.once(le.Events.MEDIA_ATTACHED,o),this.onDisable(()=>{a.off(le.Events.MEDIA_ATTACHED,o)})}this.onDisable(this.store.subscribe(o=>o.src,o=>{if(!o)return;const{currentTime:l,isPlaying:c}=this.store.getState();a.loadSource(o),this._appendAirplaySourceAlternative(o),e.currentTime=l,c&&e.play()})),a.attachMedia(this.videoElement),this.onDisable(()=>{a.detachMedia()})}_appendAirplaySourceAlternative(e){if(!qe.browserHasAirPlaySupport())return;const t=document.createElement("source");t.type="application/x-mpegURL",t.src=e,this.videoElement.appendChild(t),this.videoElement.disableRemotePlayback=!1,this.setupAirplay()}_analytics(e){super._analytics(e),!(!this.videoElement.mux||this.videoElement.mux.deleted||!this.hls)&&(this.videoElement.mux.addHLSJS({Hls:le,hlsjs:this.hls}),this.onDisable(()=>{var t;(t=this.videoElement.mux)==null||t.removeHLSJS()}))}static isAvailable(){var e;return!!((e=le.isSupported)!=null&&e.call(le))}isAvailable(){return!!this.videoElement&&ps.isAvailable()}_listen(e){super._listen(e);const t=this.hls;if(!t)throw new Error("MediaSourceTech.hls isn't defined");const i=this.store,s=()=>{var T;const m=hc(),v=window.innerWidth<=Zl?720:1080,x=m||v,S=t.levels.map(({height:L,codecSet:A},P)=>({index:P,height:L,codecSet:A})).filter(({height:L})=>L<=x),b=(T=Dl(S,[({height:L})=>L,({codecSet:L})=>L===ll?1:0],["desc","desc"])[0])==null?void 0:T.index;b!==void 0&&(t.startLevel=b,m&&(t.nextLevel=b)),i.getState().set({qualityLevels:t.levels,quality:t.nextLevel===-1?"auto":t.levels[t.nextLevel].height})};t.on(le.Events.MANIFEST_PARSED,s),this.onDisable(()=>t.off(le.Events.MANIFEST_PARSED,s));const r=()=>{i.getState().set({quality:t.manualLevel===-1?"auto":t.levels[t.manualLevel].height})};t.on(le.Events.LEVEL_SWITCHING,r),this.onDisable(()=>t.off(le.Events.LEVEL_SWITCHING,r));const a=()=>{i.getState().set({currentAutoLevel:t.levels[t.currentLevel]})};t.on(le.Events.LEVEL_SWITCHED,a),this.onDisable(()=>t.off(le.Events.LEVEL_SWITCHED,a));let o=!1,l,c;const u=(m,p)=>{var x;us.warn("Error",p,m);const v=this.videoElement;if(me.addErrorTypeBreadcrumb({message:(x=p.error)==null?void 0:x.message,fatal:p.fatal,details:p.details}),me.addRecoveryAttemptsBreadcrumb(ft),p.fatal){if(this._reportHLSErrorOncePerType(p),Di()){me.setMediaErrorRecoveryTag(!0),me.setRecoveryLimitTag(!0),me.setContext({message:p.details,code:p.type}),kt(new Error(js(p)));return}switch(p.type){case le.ErrorTypes.NETWORK_ERROR:o=!0,clearTimeout(c),c=setTimeout(()=>{t==null||t.startLoad()},2e3);break;case le.ErrorTypes.MEDIA_ERROR:if(p.details==="manifestIncompatibleCodecsError"){i.getState().set({deviceSupportsVideoCodecs:!1}),this.disable();break}const{currentTime:S,paused:b}=v,T=+new Date;l&&l<T?(l=void 0,t.swapAudioCodec()):l=T+2e3,t.config.startPosition=this.videoElement.currentTime,t.recoverMediaError(),typeof S=="number"&&(v.currentTime=S),b||v.play();break;default:this.disable();break}ft++,me.addErrorTypeBreadcrumb({message:p.error.message,fatal:p.fatal,details:p.details})}else p.type===le.ErrorTypes.MEDIA_ERROR&&p.details==="bufferStalledError"&&Ki(v.currentTime,v.duration)&&(v.currentTime=v.duration)};t.on(le.Events.ERROR,u),this.onDisable(()=>t.off(le.Events.ERROR,u)),this.onDisable(()=>{var m,p;return(p=(m=this._reportHLSErrorOncePerType.cache).clear)==null?void 0:p.call(m)});const h=()=>{o&&(o=!1,t.startLoad())},d=()=>{ft=0},f=()=>{var p,v,x,S;const m=(p=this.videoElement)==null?void 0:p.error;if(Di()){me.setRecoveryLimitTag(Di()),me.setContext({message:m==null?void 0:m.message,code:m==null?void 0:m.code,currentTime:(v=this.videoElement)==null?void 0:v.currentTime,loadLevel:(x=this.hls)==null?void 0:x.loadLevel}),kt(new Error("Media error: recovery limit exhausted"));return}if((m==null?void 0:m.code)===3){const b=this.hls;if(!b)return;const L=kl(b.levels,D=>-D.height).find(D=>D.bitrate<b.levels[b.loadLevel].bitrate),A=b.levels.findIndex(D=>D.height===(L==null?void 0:L.height)),P=b.autoLevelEnabled;if(me.addRecoveryAttemptsBreadcrumb(ft),A===-1){kt(new Error("Media error: reached lowest level"));return}me.addLevelChangeBreadcrumb({from:b.levels[b.loadLevel].height,to:b.levels[A].height}),b.currentLevel=A,b.nextLoadLevel=A,(P||zt)&&(clearTimeout(zt),zt=setTimeout(()=>{zt=void 0,b&&(me.addBreadCrumbAutoQualityRestored(),b.nextLevel=-1)},5e3)),b.config.startPosition=this.videoElement.currentTime,b.startLoad(),b.recoverMediaError(),ft++,me.addRecoveryAttemptsBreadcrumb(ft),this.store.getState().isPlaying&&((S=this.handlers)==null||S.play())}};this.videoElement.addEventListener("progress",d),this.onDisable(()=>{this.videoElement.removeEventListener("progress",d)}),this.videoElement.addEventListener("error",f),this.onDisable(()=>{this.videoElement.removeEventListener("error",f),clearTimeout(zt),clearTimeout(c)}),window.addEventListener("online",h),this.onDisable(()=>window.removeEventListener("online",h));const g=()=>{o=!0,t.stopLoad()};window.addEventListener("offline",g),this.onDisable(()=>{window.removeEventListener("offline",g)})}enable(e){var s;const{currentTime:t}=this.store.getState(),i=new le({startPosition:t,backBufferLength:60,lowLatencyMode:!1,capLevelToPlayerSize:!0,nudgeMaxRetry:6,maxBufferLength:60,maxMaxBufferLength:90,maxBufferSize:300*1e3*1e3});this.hls=i,(s=this._handlers)==null||s.setHls(i),this.onDisable(()=>{var r;(r=this._handlers)==null||r.setHls(null)}),super.enable(e)}}function js(n){var e,t;return`${n.type} ${n.details} ${(t=(e=n.err)==null?void 0:e.message)!=null?t:""}`}let zt;class Mg extends gl{constructor(e,t){super(e,t),this.store=e,this.videoElement=t,this.hls=null}setHls(e){this.hls=e}setCurrentTime(e){this._setCurrentTime(e)}setQualityLevel(e){const t=this.hls;if(!t)return;const i=t.levels.findIndex(r=>r.height===e&&r.codecSet===ll),s=t.levels.findIndex(r=>r.height===e);t.nextLevel=i>-1?i:s,e===void 0?Qn("auto"):Qn(e.toString()),setTimeout(()=>{this.store.getState().set({quality:t.manualLevel===-1?"auto":t.levels[t.manualLevel].height})},0)}changeLanguage(e){const t=this.hls;if(!t)return;const i=t.subtitleTracks.find(s=>s.name===e);i?(t.subtitleDisplay=!0,t.subtitleTrack=i.id,pt(e)):(t.subtitleDisplay=!1,t.subtitleTrack=-1,pt(""))}nextFrame(){const e=this.hls;if(!e)return;const t=e.levels[e.currentLevel],i=Number(t==null?void 0:t.attrs["FRAME-RATE"])||24;this.relativeSeek(1/i)}previousFrame(){const e=this.hls;if(!e)return;const t=e.levels[e.currentLevel],i=Number(t==null?void 0:t.attrs["FRAME-RATE"])||24;this.relativeSeek(-1/i)}}const Ng=16/9,ba=160,ml=90,Xt=18;function pl({ignoreTheaterMode:n}={}){const[e,t]=Fa(dc,{initialValue:!1,listen:!0}),i=mi(),s=n||i?!1:e,{viewportWidth:r,viewportHeight:a}=fc({enabled:s}),o=y.useContext(Ql),[l,c]=y.useState(!1),u=y.useCallback(g=>{t(g)},[t]),h=100/Ng,d=a?Math.max(ba,a-o-ml):ba,f=r?100*d/r:h;return y.useEffect(()=>{const g=()=>{document.fullscreenElement||document.webkitFullscreenElement?c(!0):c(!1)};return document.addEventListener("webkitfullscreenchange",g),document.addEventListener("fullscreenchange",g),()=>{document.removeEventListener("webkitfullscreenchange",g),document.removeEventListener("fullscreenchange",g)}},[]),{isTheaterMode:s,setTheaterMode:u,isFullscreen:l,paddingPercent:s?Math.min(h,f):h,videoSizeCSS:Bg({headerHeight:o,isTheaterMode:s,isFullscreen:l})}}const Bg=Oa(({headerHeight:n=0,isTheaterMode:e=!1,isFullscreen:t=!1})=>ne({margin:"0 auto",height:"fit-content",maxHeight:e?`calc(100vh - ${n}px - ${ml}px)`:`calc(100vh - ${n}px)`,width:"100%",borderRadius:0,overflow:"hidden",[yn]:{margin:e?"0 auto":"24px auto 0",borderRadius:e||t?0:Xt,maxWidth:e||t?"100%":960,".video-player-controls-wrapper":{borderBottomLeftRadius:e||t?0:Xt,borderBottomRightRadius:e||t?0:Xt},video:{borderRadius:e||t?0:Xt},".video-poster":{borderRadius:e||t?0:Xt}}}),({headerHeight:n=0,isTheaterMode:e=!1,isFullscreen:t=!1})=>`${n}${e}${t}`);function im(n){const e=y.useMemo(()=>qe.isAvailable()||ps.isAvailable(),[]),[t,i]=y.useState(!0);return y.useEffect(()=>{if(!n){i(!0);return}return n.subscribe(s=>s.deviceSupportsVideoCodecs,s=>{i(s)})},[n]),e&&t}function Ug({manifestURL:n,autoPlay:e=!1,video:t,chromecastQueue:i,chromecastEntityToUrlMap:s,mediaSessionMetadata:r,onProgress:a,className:o,store:l}){var Te,Wn,Yn;const c=cs(),u=mi(),h=Ma(),d=c&&!u&&!!h,f=Se(l,q=>d&&q.isEndScreenShowing);y.useEffect(()=>{if(d)return l.subscribe(q=>q.hasEnded,q=>{l.getState().set({isEndScreenShowing:d&&q})})},[l,d]);const g=y.useRef(null),m=y.useRef(null),p=Cc(t);y.useEffect(()=>{l.getState().set({muxData:p})},[l,p]),y.useEffect(()=>{l.getState().set({src:n!=null?n:""})},[l,n]),y.useEffect(()=>{l.getState().set({duration:t.duration})},[l,t.duration]),y.useEffect(()=>{l.getState().set({mediaTitle:t.title})},[l,t.title]),y.useEffect(()=>{l.getState().set({chromecastQueue:i})},[l,i]),y.useEffect(()=>{l.getState().set({mediaSessionMetadata:r})},[l,r]),y.useEffect(()=>{l.getState().set({mediaType:"video/mp4"})},[l]);const{currentTech:v}=Gg(l,g.current,{chromecastEntityToUrlMap:s,autoPlay:e}),x=(Te=v==null?void 0:v.handlers)!=null?Te:Vg,S=y.useContext(Jl);y.useEffect(()=>{S.current=x},[x,S]),y.useEffect(()=>()=>{S.current=null},[S]);const b=Se(l,q=>q.chromecastConnected),{trackEvent:T}=ic();y.useEffect(()=>{b&&T({category:"chromecast",action:"connected"})},[b,T]);const{isTheaterMode:L,setTheaterMode:A,videoSizeCSS:P}=pl(),{notify:D,dismiss:I}=ec(`${t.id}-video-player-error`),[k,M]=y.useState(!1),{matches:_}=hs(Ua),N=y.useCallback(()=>{var St;const q=g.current;q!=null&&q.error&&(D(`The media could not be loaded: ${q.error.code}`,{type:"error"}),me.setContext({message:q.error.message,code:q.error.code,recoverable:!1}),me.setMediaErrorRecoveryTag(!0),kt(new Error(`The media could not be loaded: ${(St=q.error)==null?void 0:St.code}`)))},[D]),B=2e3,G=y.useRef(Vi(N,B));y.useEffect(()=>(G.current=Vi(N,B),()=>{G.current.cancel()}),[N]),y.useEffect(()=>{const q=g.current;if(!q)return;const St=()=>{var Ei;I(),q.error&&(G.current(),us.error("message",q.error.message,q.error.code,q.error),me.setMediaErrorRecoveryTag(!1),me.setContext({message:q.error.message,code:q.error.code,recoverable:!0}),kt(new Error(`The media could not be loaded: ${(Ei=q.error)==null?void 0:Ei.code}`)))};return q.addEventListener("error",St),()=>{q.removeEventListener("error",St)}},[I]);const X=y.useRef(),Q=3e3,$=y.useCallback(()=>{clearTimeout(X.current),M(!0),X.current=setTimeout(()=>{M(!1)},Q)},[]);y.useEffect(()=>{clearTimeout(X.current)},[]);const[U,ee]=y.useState(!1),[Z,te]=y.useState(!1),oe=Se(l,q=>q.showNativeCues),ue=Se(l,q=>q.isScrubbing),{interacting:he,onPointerMove:xe,onPointerEnter:De,onPointerLeave:rt,onPointerCancel:Es}=$g(),vs=U||Z||ue||k,Kt=!Se(l,q=>q.isPlaying)||b,Wt=_&&f,at=Kt||he||vs,ot=Se(l,q=>q.wasEverPlayed);y.useEffect(()=>{if(ot)return;const q=()=>{l.getState().set({wasEverPlayed:!0})};return l.subscribe(Ei=>Ei.currentTime,q)},[ot,l]);const Tt=b||!ot,lt=Se(l,q=>q.aspectRatio),xs=Tt||!lt?(1/li).toString():lt.toString(),Y=Se(l,q=>!q.isInitialized||(q.isBuffering||q.isSeeking)&&!q.hasEnded);return Ec({store:l,reportProgress:a}),O(Tn,{nodeRef:m,in:L,classNames:{enter:"theater-mode-enter",exit:"theater-mode-exit"},timeout:300,children:J("div",{id:"video-player","data-video-player-root":!0,tabIndex:-1,onKeyDown:q=>{Na({element:q.target,event:q})||(q.key==="ArrowUp"&&(q.preventDefault(),x.raiseVolume(),at||$()),q.key==="ArrowDown"&&(q.preventDefault(),x.lowerVolume(),at||$()))},onPointerMove:xe,onPointerEnter:De,onPointerLeave:rt,onPointerCancel:Es,style:{cursor:f?"auto":void 0},"data-controls-visible":at,"data-is-theater-mode":L,css:[Ra.wrapper,P],className:o,ref:m,children:[O("video",{ref:g,playsInline:!0,style:{aspectRatio:xs,opacity:Tt?0:1},"data-show-native-cues":oe,css:Ra.videoElement,preload:"none",poster:$a({image:(Wn=t==null?void 0:t.images)==null?void 0:Wn.thumbnail,format:"jpeg",width:1920})}),(Yn=t.images)!=null&&Yn.thumbnail?O(Qa,{show:Tt,image:t.images.thumbnail,videoTitle:t.title}):null,O(yu,{show:Y}),O(Tu,{style:{marginTop:at?"-48px":"0",visibility:oe||Tt||f?"hidden":void 0}}),O(vu,{title:t.title,areControlsVisible:at,isEndScreenOnMobile:Wt,videoElement:g.current,videoPlayerRef:m,playerHandlers:x,videoStore:l,isTheaterMode:L,setTheaterMode:A,settingsMenuOnToggle:ee,subtitlesMenuOnToggle:te,wasEverPlayed:ot,onBlur:()=>{M(!1)},onFocus:$})]})})}const Mt=` padding 0.3s ease-in-out 0.3s, margin 0.3s ease-in-out 0s, border-radius 0.3s ease-in-out 0s `,La=` ${Mt}, width 0.3s ease-in-out 0s, max-width 0.3s ease-in-out 0s `,Aa=` ${Mt}, width 0.3s ease-in-out 0s, max-width 0.3s ease-in-out 0s, max-height 0s ease-in-out 0s `,Ca=` ${Mt}, width 0.3s ease-in-out 0s, max-width 0.3s ease-in-out 0s, max-height 0s ease-in-out 0.3s `,Ra={wrapper:ne([{display:"flex",justifyContent:"center",position:"relative",overflow:"hidden",outline:"none"},{transition:Mt,video:{transition:Mt},[yn]:{transition:La,video:{transition:La},'&[data-is-theater-mode="true"]':{transition:Mt},"&.theater-mode-enter":{transition:Aa,video:{transition:Aa}},"&.theater-mode-exit":{transition:Ca,video:{transition:Ca}}}},{cursor:"none",".video-player-controls-wrapper":{opacity:0,"#video-controls":{pointerEvents:"none"}},'&[data-controls-visible="true"]':{cursor:"auto",".video-player-controls-wrapper":{opacity:1,"#video-controls":{pointerEvents:"all"}}}}]),videoElement:ne({width:"100%",background:V.neutral1000,zIndex:Vt,maxHeight:"100%",height:"auto",'&[data-show-native-cues="false"]':{"::cue":{visibility:"hidden"},"::-webkit-media-text-track-container":{visibility:"hidden"}}})};function $g(){const[n,e]=y.useState(!1),t=y.useRef(void 0);y.useEffect(()=>()=>{clearTimeout(t.current)},[]);const i=y.useCallback(l=>{l.pointerType==="mouse"&&(clearTimeout(t.current),t.current=setTimeout(()=>{e(!1)},2e3),e(!0))},[]),s=y.useRef(!1),r=y.useCallback(l=>{l.isPrimary&&(s.current=!1)},[]),a=y.useCallback(l=>{l.isPrimary&&(s.current=!0)},[]),o=y.useCallback(l=>{if(l.isPrimary){if(s.current){s.current=!1;return}if(clearTimeout(t.current),l.pointerType==="mouse"){e(!1);return}e(c=>(c||(t.current=setTimeout(()=>{e(!1)},2e3)),!c))}},[]);return{interacting:n,onPointerMove:i,onPointerEnter:r,onPointerLeave:o,onPointerCancel:a}}function Gg(n,e,{chromecastEntityToUrlMap:t,autoPlay:i}){const s=ka(),[r,a]=y.useState(null),[o,l]=y.useState(null),[c,u]=y.useState(null),[h,d]=y.useState(null),f=y.useRef(i);f.current=i;const[g]=tc();return y.useEffect(()=>{if(!e)return;const m=new gi(n,e),p=new qe(n,e),v=new ps(n,e);return a(m),l(p),u(v),()=>{m.dispose(),p.dispose(),v.dispose()}},[n,e]),y.useEffect(()=>{!r||!g||r.setApiToken(g)},[r,g]),y.useEffect(()=>{if(!r||!t)return;const m=p=>{var S;const v=(S=p.detail)==null?void 0:S.entityId;if(!v)return;const x=t[v];x&&s.push(x)};return r.addEventListener(fi.type,m),()=>{r.removeEventListener(fi.type,m)}},[s,r,t]),y.useEffect(()=>{const m=b=>({hasSrc:!!b.src,airPlayConnected:b.airPlayConnected,chromecastConnected:b.chromecastConnected});function p(b){if(b.chromecastConnected&&(r!=null&&r.isAvailable()))return d(r);if(b.airPlayConnected&&(o!=null&&o.isAvailable()))return d(o);if(b.hasSrc&&(c!=null&&c.isAvailable()))return d(c);if(b.hasSrc&&(o!=null&&o.isAvailable()))return d(o)}const v=m(n.getState());p(v);const x=qe.browserHasAirPlaySupport()||gi.isAvailable()||!v.hasSrc;let S;return x&&(S=n.subscribe(m,p,{equalityFn:oi})),()=>{S==null||S()}},[n,o,c,r,e]),y.useEffect(()=>{if(h)return h.enable(f.current),()=>{h.disable()}},[h]),{currentTech:h,nativeTech:o,mediaSourceTech:c,chromecastTech:r}}const Vg={play:()=>null,pause:()=>null,setCurrentTime:()=>{},setQualityLevel:()=>{},mute:()=>null,unmute:()=>null,setPlaybackSpeed:()=>{},replay:()=>null,setVolume:()=>{},forward30:()=>null,back30:()=>null,forward5:()=>null,back5:()=>null,forward15:()=>null,back15:()=>null,previousFrame:()=>null,nextFrame:()=>null,raiseVolume:()=>null,lowerVolume:()=>null,raisePlaybackSpeed:()=>null,lowerPlaybackSpeed:()=>null,changeLanguage:()=>null,setAutoplayEnabled:()=>{},cast:()=>{},airPlay:()=>{},exitFullScreen:()=>{},requestFullScreen:()=>{}};function sm({isProxy:n,title:e,thumbnail:t,className:i}){const{videoSizeCSS:s,paddingPercent:r}=pl();return O("div",{className:i,css:[s,Ia.wrapper],children:O("div",{style:{paddingTop:n?void 0:`${r}%`},css:Ia.background,children:e&&t?O(Qa,{show:!0,image:t,videoTitle:e}):null})})}const Ia={wrapper:ne({margin:"0 auto",overflow:"hidden",position:"relative",zIndex:1}),background:ne({background:V.neutral1000,width:"100%",maxWidth:"100%",height:0,paddingTop:"56.25%"})},Hg={light:{logoImage:yc},dark:{logoImage:xc}},pi=y.createContext(!1);function nm({children:n,blurred:e}){const{matches:t}=hs(`(max-width: ${sc}px)`),i=e!=null?e:t;return O(pi.Provider,{value:i,children:O("div",{css:{position:"absolute",padding:32,top:0,right:0,bottom:0,left:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},style:i?{backdropFilter:"blur(3px)",background:V.neutral900_90,padding:0}:void 0,children:O("div",{css:{width:"100%",maxWidth:512,background:He.systemFill,borderRadius:12,boxShadow:"0px 0px 16px rgba(0,0,0,0.6)",padding:"24px 54px",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},style:i?{width:"auto",maxWidth:"100%",background:"none",borderRadius:"0",boxShadow:"none",padding:"10px 7.0vw"}:void 0,children:n})})})}function rm(){const{getThemeData:n}=nc(),e=n(Hg),t=y.useContext(pi);return O("img",{alt:"Nebula",src:e.logoImage,css:{width:280,margin:"0 auto"},style:t?{display:"none"}:void 0})}function am(){const n=y.useContext(pi);return O("div",{css:{height:26,flex:"0 0 26px"},style:n?{display:"none"}:void 0})}function om({children:n}){const e=y.useContext(pi);return O(ac,{as:"h2",css:{color:He.label,fontSize:15,[be]:{fontSize:13},fontWeight:Hi.weight.semibold,marginTop:0,marginBottom:0,textAlign:"center",letterSpacing:"0.1px"},style:e?{color:V.neutral0}:void 0,children:n})}function lm({children:n,className:e}){const t=y.useContext(pi);return O("p",{className:e,css:{fontSize:11,fontWeight:Hi.weight.medium,color:He.label400,textAlign:"center",marginTop:16,[be]:{fontSize:10,marginTop:10}},style:t?{color:V.neutral0}:void 0,children:n})}function Kg({id:n,type:e,enabled:t}){var r;const{data:i}=pc({id:n,type:e,enabled:t});return{manifestURL:(r=i==null?void 0:i.url)!=null?r:null}}function cm({cls:n,lesson:e,lessons:t,store:i}){const{manifestURL:s}=Kg({id:e.id,type:"lesson"}),{saveLessonProgress:r}=rc({id:e.id,classId:e.class_id}),a=y.useCallback(h=>{r({progress:h})},[r,e.id]),o=y.useMemo(()=>t.every(h=>h.entitled),[t]),l=y.useMemo(()=>{if(!(!n||!e))return{title:e.title,thumbnail:e.images.thumbnail,trackIdentifier:e.id,artist:n.creator,album:n.title}},[n,e]),c=y.useMemo(()=>{if(o)return t.map(h=>({entity:h.id,duration:h.duration,title:n.title,subtitle:h.title,type:"video/mp4"}))},[t,n.title,o]),u=y.useMemo(()=>c?t.reduce((d,f)=>(d[f.id]=`/${f.class_slug}/${f.slug}`,d),{}):void 0,[c,t]);return O(Ug,{manifestURL:s,store:i,autoPlay:!0,chromecastQueue:c,chromecastEntityToUrlMap:u,mediaSessionMetadata:l,video:e,onProgress:a,css:Wg})}const Wg=ne({[yn]:{marginTop:0}});export{dl as B,gi as C,om as H,rm as L,lm as M,cm as N,Qs as P,Kc as S,jg as T,sm as V,im as a,Ki as b,Zg as c,Ec as d,Ac as e,Wi as f,Tc as g,Cc as h,bc as i,ni as j,Xc as k,zc as l,or as m,Bc as n,jc as o,qc as p,pl as q,Kg as r,Ug as s,nm as t,Qg as u,am as v};