\n`)(t,(()=>{const{origin:e,protocol:t,hostname:i,port:s}=window.location;return e||`${t}//${i}${s?`:${s}`:""}`})());let r=Fe();try{r.src="about:blank",e.appendChild(r);const t=xe(r);if(!t)throw new TypeError("iframe content document is not a Document");t.write(n)}catch(t){e.removeChild(r),Be?(r=Fe(),r.src="about:srcdoc",r.srcdoc=n,e.appendChild(r)):s(t)}const o=({data:e})=>{e===`${t}_ready`&&(window.removeEventListener("message",o),i(r))};window.addEventListener("message",o,!1)})))(this.element,this[Ve].id),this[Ve].iframe=s,this.executionContext=s.contentWindow);const n=null===(i=xe(s))||void 0===i?void 0:i.body;return((e,{async:t=!1,defer:i=!1,type:s,placeholder:n}={})=>{if(!e)throw new TypeError('Missing required "src" parameter');return new Promise(((r,o)=>{const a=document.createElement("script");let l=n;a.type=null!=s?s:"text/javascript",a.async=t,a.defer=i,a.onerror=()=>o(new URIError(`The script ${e} is not accessible.`)),a.onload=()=>r(a),l||(l=document.currentScript?document.currentScript.parentNode:document.head),a.src=e,null==l||l.appendChild(a)}))})(e,Object.assign({placeholder:n},t))}addSlot(e,t){if(this.isDestroyed())throw new Error("VideoAdContainer has been destroyed");this.slotElement||(this.slotElement=((e,t,i)=>{const s=document.createElement("DIV");return Object.assign(s.style,{border:"0px",cursor:"pointer",height:`${i}px`,left:"0px",margin:"0px",padding:"0px",position:"absolute",top:"0px",width:`${t}px`}),e.appendChild(s),s})(this.element,e,t))}destroy(){const e=new Promise((e=>{setTimeout((()=>{var t;null===(t=this.element.parentNode)||void 0===t||t.removeChild(this.element),e()}),1e3)}));return this.element.style.zIndex="-9999",this[Ve].destroyed=!0,e}isDestroyed(){return this[Ve].destroyed}}Ue=Ve;const je={"3gp":"video/3gpp",avi:"video/x-msvideo",flv:"video/x-flv",m3u8:"application/x-mpegURL",m4v:"video/mp4",mov:"video/quicktime",mp4:"video/mp4",mpd:"application/dash+xml",ogv:"video/ogg",ts:"video/MP2T",webm:"video/webm",wmv:"video/x-ms-wmv"},Ke=(e,t)=>{const{src:i,type:s}=t;return e.canPlayType(s||(e=>{const t=e.match(/\.([^./?]+)(\?[^/]+)?$/i),i=t&&t[1];return i&&je[i]||`video/${i}`})(i||""))},He=e=>{const t=Number(e.width)||0,i=Number(e.height)||0;return{aspectRatio:i?Math.floor(t/i*10)/10:0,height:i,width:t}},Ye=(e,t)=>{const[i]=((e,t)=>{const i=He(t);return e.slice(0).sort(((e,t)=>{const s=He(e),n=He(t),r=Math.abs(i.width-s.width),o=Math.abs(i.width-n.width);return Math.abs(i.aspectRatio-s.aspectRatio)-Math.abs(i.aspectRatio-n.aspectRatio)||r-o}))})(e,t);return i},We=(e,t,{getMediaFile:i=Ye})=>{const{element:s,videoElement:n}=t,r=s.getBoundingClientRect(),o=be(e),a=null==o?void 0:o.filter((e=>Ke(n,e)));return a&&i(a,r)},ze=(e,t,i)=>{const s=(...n)=>(e.removeEventListener(t,s),i(...n));return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)}},{progress:qe}=F,Xe=(e,t)=>(...i)=>{try{e(...i)}catch(e){null==t||t.error(e)}},{fullscreen:Qe,exitFullscreen:Ze,playerCollapse:Je,playerExpand:et}=F,{pause:tt,resume:it}=F,{rewind:st}=F,{skip:nt}=F,rt=()=>{const e=document.createElement("button");return e.classList.add("mol-vast-skip-control"),e.type="button",e.innerHTML="skip",e.style.position="absolute",e.style.bottom="15px",e.style.right="15px",e},{error:ot}=F,at="volumeChanged",lt="finish",dt="adProgress",{complete:ct,firstQuartile:ht,midpoint:ut,start:ft,thirdQuartile:pt}=F,gt=(e,t)=>100*e/t,mt=(e,t)=>gt(e,t)>=99,{mute:vt,unmute:At}=F,Et=e=>e.muted||0===e.volume,{impression:yt,creativeView:Tt}=F,bt=(e,t)=>{let i=String(e);for(;i.length{const t=Math.floor(e/36e5),i=Math.floor(e/6e4%60),s=Math.floor(e/1e3%60),n=e%1e3;return`${bt(t,2)}:${bt(i,2)}:${bt(s,2)}.${bt(n,3)}`},{progress:_t}=F,Ct=e=>1e3*e,Rt=({offset:e,uri:t})=>{const i="number"==typeof e||Boolean(e&&(e=>/^\d+(\.\d+)?%$/g.test(e)&&!isNaN(parseFloat(e)))(e)),s="string"==typeof t&&t.length>0;return i&&s},Lt=(e,t)=>"number"==typeof e?e:parseFloat(e)/100*t,{clickThrough:It}=F,kt=()=>{const e=document.createElement("a");return e.classList.add("mol-vast-clickthrough"),e.style.width="100%",e.style.height="100%",e.style.position="absolute",e.style.left="0",e.style.top="0",e},wt=[({videoElement:e,element:t},i,{clickThroughUrl:s,pauseOnAdClick:n=!0,createClickControl:r=kt}={})=>{const o=t||e.parentNode,a=r(),l=!document.body.contains(a);return l&&o.appendChild(a),s&&a instanceof HTMLAnchorElement&&(a.href=s,a.target="_blank"),a.onclick=t=>{t.stopPropagation(),e.paused&&n?(t.preventDefault(),e.play()):(n&&e.pause(),i(It))},()=>{l&&o.removeChild(a)}},({videoElement:e},t)=>{const i=()=>{var i;const s=null!==(i=e.error)&&void 0!==i?i:void 0;s&&Object.defineProperty(s,"code",{get:()=>r.VAST_PROBLEM_DISPLAYING_MEDIA_FILE}),t(ot,s)};return e.addEventListener("error",i),()=>{e.removeEventListener("error",i)}},({videoElement:e},t)=>{const i=["webkitfullscreenchange","mozfullscreenchange","fullscreenchange","MSFullscreenChange"];let s=!1;const n=()=>{(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement||null)===e?(s=!0,t(et),t(Qe)):s&&(s=!1,t(Je),t(Ze))};for(const e of i)document.addEventListener(e,n);return()=>{for(const e of i)document.removeEventListener(e,n)}},({videoElement:e},t)=>{let i=!1;const s=()=>{const{currentTime:n}=e;!i&&n>0&&(i=!0,t(yt),t(Tt),e.removeEventListener("timeupdate",s))};return e.addEventListener("timeupdate",s),()=>{e.removeEventListener("timeupdate",s)}},({videoElement:e},t)=>{let i=!1,s=!0;const n=()=>{i?s&&(s=!1,t(it)):(i=!0,s=!1)},r=()=>{s||(s=!0,t(tt))};return e.addEventListener("play",n),e.addEventListener("pause",r),()=>{e.removeEventListener("play",n),e.removeEventListener("pause",r)}},({videoElement:e},t,{progressEvents:i=[]}={})=>{const{duration:s}=e,n=Ct(s);let r=0,o=Ct(e.currentTime),a=i.filter(Rt).map((({offset:e,uri:t})=>({offset:Lt(e,n),uri:t})));const l=()=>{const{currentTime:i}=e,s=Math.abs(i-o);r+=Ct(s),o=i;const{stillPending:n,toCall:d}=a.reduce(((e,t)=>{const{offset:i}=t;return"number"==typeof i&&r>=i?e.toCall.push(t):e.stillPending.push(t),e}),{stillPending:[],toCall:[]});a=n,d.forEach((({uri:e})=>{t(_t,{contentplayhead:St(r),progressUri:e})})),0===a.length&&e.removeEventListener("timeupdate",l)};return a.length>0&&e.addEventListener("timeupdate",l),()=>{e.removeEventListener("timeupdate",l)}},({videoElement:e},t)=>{let{currentTime:i}=e;const s=()=>{const s=e.currentTime-i;s<0&&Math.abs(s)>=1&&t(st),i=e.currentTime};return e.addEventListener("timeupdate",s),()=>{e.removeEventListener("timeupdate",s)}},(e,t,{skipoffset:i,createSkipControl:s=rt}={})=>{if(!i)return()=>null;let n;const{videoElement:r,element:o}=e,a=()=>{const e=1e3*r.currentTime;!n&&"number"==typeof i&&e>=i&&(n=s(),n.onclick=e=>{var i;return null===(i=e.stopPropagation)||void 0===i||i.call(e),t(nt),!1},o.appendChild(n),r.removeEventListener("timeupdate",a))};return r.addEventListener("timeupdate",a),()=>{r.removeEventListener("timeupdate",a),n&&o.removeChild(n)}},({videoElement:e},t)=>{let i=!1,s=!1,n=!1,r=!1,o=!1;const a={start:{isFired:e=>!i&&e>0,callback:()=>{i=!0,t(ft)}},firstQuartile:{isFired:(e,t)=>!s&&((e,t)=>gt(e,t)>=25)(e,t),callback:()=>{s=!0,t(ht)}},midpoint:{isFired:(e,t)=>!n&&((e,t)=>gt(e,t)>=50)(e,t),callback:()=>{n=!0,t(ut)}},thirdQuartile:{isFired:(e,t)=>!r&&((e,t)=>gt(e,t)>=75)(e,t),callback:()=>{r=!0,t(pt)}},complete:{isFired:(e,t)=>!o&&mt(e,t),callback:()=>{o=!0,t(ct)}}},l=()=>{const{duration:i}=e,{currentTime:s}=e;for(const e in a)if(a[e].isFired(s,i)){a[e].callback();break}t(dt)},d=()=>{const{duration:i}=e,{currentTime:s}=e;!o&&mt(s,i)&&(o=!0,t(ct)),e.removeEventListener("ended",d),e.removeEventListener("timeupdate",l)};return e.addEventListener("timeupdate",l),e.addEventListener("ended",d),()=>{e.removeEventListener("timeupdate",l),e.removeEventListener("ended",d)}},({videoElement:e},t)=>{let i=Et(e);const s=()=>{t(at),i&&!Et(e)?t(At):!i&&Et(e)&&t(vt),i=Et(e)};return e.addEventListener("volumechange",s),()=>{e.removeEventListener("volumechange",s)}}];class Pt extends Error{constructor(e){super(e),this.name="AdUnitError",Object.setPrototypeOf(this,Pt.prototype)}}var Ot=i(181),Dt=i.n(Ot);const Nt=window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver,Mt=()=>{},xt=["style","clientWidth","clientHeight"],Bt=Symbol("mutationHandlers"),Ft=Symbol("mutationObserver"),Ut=Symbol("resizeHandlers"),$t=Symbol("resizeElement"),Vt=(e,t,{threshold:i=20}={})=>{((e,t)=>{if(!(e instanceof Element))throw new TypeError("Target is not an Element node");if(!(t instanceof Function))throw new TypeError("Callback is not a function")})(e,t);const s=({style:e,clientHeight:t,clientWidth:i})=>[e.width,e.height,i,t].join(".");let n=s(e);const r=Dt()((()=>{const i=s(e);i!==n&&(n=i,t())}),i),o=Nt?((e,t)=>{var i;if(!e[Bt]){e[Bt]=[];const t=()=>{var t;null===(t=e[Bt])||void 0===t||t.forEach((e=>e()))};e[Ft]=((e,t)=>{const i=new Nt((e=>{for(let i=0;i{var i,s,n;e[Bt]=null===(i=e[Bt])||void 0===i?void 0:i.filter((e=>e!==t)),0===(null===(s=e[Bt])||void 0===s?void 0:s.length)&&(null===(n=e[Ft])||void 0===n||n.disconnect(),delete e[Bt],delete e[Ft])}})(e,r):Mt,a=((e,t)=>{var i;if(!e[Ut]){e[Ut]=[];const t=()=>{var t;null===(t=e[Ut])||void 0===t||t.forEach((e=>e()))};e[$t]=(e=>{const t=document.createElement("iframe");return t.setAttribute("style","display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; border: 0; overflow: hidden; pointer-events: none; z-index: -1;"),t.setAttribute("type","text/html"),t.setAttribute("loading","eager"),t.onload=()=>{t.contentWindow&&t.contentWindow.addEventListener("resize",e)},t.src="about:blank",t})(t),"static"===getComputedStyle(e).position&&(e.style.position="relative"),e.appendChild(e[$t])}return null===(i=e[Ut])||void 0===i||i.push(t),()=>{var i,s;e[Ut]=null===(i=e[Ut])||void 0===i?void 0:i.filter((e=>e!==t)),0===(null===(s=e[Ut])||void 0===s?void 0:s.length)&&(e.removeChild(e[$t]),delete e[Ut],delete e[$t])}})(e,r);return()=>{o(),a()}},{IntersectionObserver:Gt}=window,jt=()=>{},Kt=Symbol("intersectionHandlers"),Ht=Symbol("intersectionObserver");let Yt=[],Wt=[];const zt=(e,t,{threshold:i=100,viewabilityOffset:s=.4}={})=>{if(((e,t)=>{if(!(e instanceof Element))throw new TypeError("Target is not an Element node");if(!(t instanceof Function))throw new TypeError("Callback is not a function")})(e,t),!Gt)return t(void 0),jt;let n=!1;const r=Dt()((i=>{i.forEach((i=>{if(i.target===e){const e=!document.hidden&&i.intersectionRatio>s;e!==n&&(n=e,t(e))}})),Wt=i}),i),o=((e,t)=>{var i,s;if(!e[Kt]){e[Kt]=[];const t=(t,i)=>{var s;null===(s=e[Kt])||void 0===s||s.forEach((e=>e(t,i)))},s={root:null,rootMargin:"0px",threshold:[...new Array(11)].map(((e,t)=>t/10))};e[Ht]=new Gt(t,s),null===(i=e[Ht])||void 0===i||i.observe(e)}return null===(s=e[Kt])||void 0===s||s.push(t),()=>{var i,s,n;e[Kt]=null===(i=e[Kt])||void 0===i?void 0:i.filter((e=>e!==t)),0===(null===(s=e[Kt])||void 0===s?void 0:s.length)&&(null===(n=e[Ht])||void 0===n||n.disconnect(),delete e[Kt],delete e[Ht])}})(e,r),a=((e,t)=>{const i=()=>{Yt&&Yt.forEach((e=>e()))};return Yt.push(t),1===Yt.length&&document.addEventListener("visibilitychange",i),()=>{Yt=Yt.filter((e=>e!==t)),0===Yt.length&&document.removeEventListener("visibilitychange",i)}})(0,(()=>r(Wt)));return()=>{o(),a()}};class qt{constructor(e){this.events={},this.logger=e||console}on(e,t){const{events:i}=this;return(i[e]||(i[e]=[])).push(t),this}removeListener(e,t){const{events:i}=this,s=i[e]||(i[e]=[]);return i[e]=s.filter((e=>e!==t&&e._!==t)),this}removeAllListeners(e){return e?delete this.events[e]:this.events={},this}once(e,t){const i=(...s)=>{this.removeListener(e,i),t(...s)};return i._=t,this.on(e,i)}emit(e,...t){const{events:i}=this,s=i[e]||(i[e]=[]),n=s.length>0;return s.forEach((e=>{try{e(...t)}catch(e){e instanceof Error&&this.logger.error(e,e.stack)}})),n}}const Xt=({staticResource:e,htmlResource:t,iFrameResource:i}={})=>e||t||i||void 0,Qt="UNKNOWN",Zt=e=>1===e.length?e[0]:(e=>{const t=window.devicePixelRatio||0;return e.slice(0).sort(((e,i)=>Math.abs(t-(e.pxratio||0))-Math.abs(t-(i.pxratio||0))))})(e)[0],Jt=e=>{const t=e.map((({ad:e})=>e)).filter(Boolean).reduce(((e,t)=>[...e,...he(t)||[]]),[]);if(t.length>0){const e=(e=>((e,t)=>{const i={};return e.filter((e=>{const s=t(e);return!(!s||i.hasOwnProperty(s)||(i[s]=!0,0))}))})(e,Xt))(t);return(e=>{const t=(e=>e.reduce(((e,t)=>{var i,s;const n=null!==(i=t.program)&&void 0!==i?i:Qt;return null!==(s=e[n])&&void 0!==s||(e[n]=[]),e[n].push(t),e}),{}))(e);return Object.keys(t).reduce(((e,i)=>i===Qt?[...e,...t[Qt]]:[...e,Zt(t[i])]),[])})(e)}},ei=(e,t)=>{let i,s,n=!0;const r=new Promise(((e,t)=>{i=e,s=t})),o=ze(e,t,((...e)=>{n=!1,i(e)}));return{cancel:()=>{n&&(n=!1,o(),s(new Error("waitFor was canceled")))},promise:r}};class ti extends Error{constructor(e){super(e),this.name="FetchError",Object.setPrototypeOf(this,ti.prototype)}}const ii=document.createElement("div"),si=()=>{},ni=(e,{document:t,placeholder:i})=>new Promise(((s,n)=>{try{const r=((e,t)=>{const{staticResource:i,htmlResource:s,iFrameResource:n}=t;return i?((e,{document:t,data:i})=>{const{height:s,width:n}=i,r=t.createElement("img");return n&&(r.width=n),s&&(r.height=s),r.src=e,r})(i,{data:t,document:e}):s?((e,{document:t,data:i})=>{const{height:s,width:n}=i,r=t.createElement("div");return n&&(r.style.width=`${n}px`),s&&(r.style.height=`${s}px`),(async e=>{const t=await fetch(e),i=t.headers.get("Content-Type");if(t.status>=400){const e=new ti(t.statusText);throw e.response=t,e}if(!i||!(e=>{const t=e.toLowerCase();return["text/plain","text/html"].some((e=>t.includes(e)))})(i)){const e=new ti(`fetchHtml error, invalid Content-Type ${i}`);throw e.response=t,e}return t.text()})(e).then((e=>{r.innerHTML=e,r.dispatchEvent(new CustomEvent("load"))})).catch((()=>{r.dispatchEvent(new CustomEvent("error"))})),r})(s,{data:t,document:e}):n?((e,{document:t,data:i})=>{const{height:s,width:n}=i,r=t.createElement("iframe");return r.setAttribute("sandbox","allow-forms allow-popups allow-scripts"),r.setAttribute("loading","eager"),n&&(r.width=n.toString()),s&&(r.height=s.toString()),r.src=e,r.frameBorder="0",r.style.border="none",r})(n,{data:t,document:e}):ii})(t,e),o=ei(r,"error"),a=ei(r,"load"),l=()=>{i.contains(r)&&(i.removeChild(r),r.style.zIndex="0")};o.promise.then((()=>{a.cancel(),l(),n(new Error("Error loading resource"))})).catch(si),a.promise.then((()=>{o.cancel(),l(),s(r)})).catch(si),r.style.zIndex="-9999",i.appendChild(r)}catch(e){n(e)}})),ri=({height:e,width:t})=>e*t,oi=({left:e,width:t})=>e+t,ai=({left:e})=>e,li=({top:e})=>e,di=({top:e,height:t})=>e+t,ci=(e,t)=>{const i=((e,t)=>{const{drawnIcons:i,placeholder:s}=t,n=ri(s.getBoundingClientRect());return ri(e)+i.reduce(((e,t)=>{const{width:i,height:s}=t;return i&&s?e+ri({width:i,height:s}):e}),0)<=.35*n})(e,t),s=((e,{placeholder:t})=>{const i=t.getBoundingClientRect();return e.left>=0&&e.left+e.width<=i.width&&e.top>=0&&e.top+e.height<=i.height})(e,t),n=((e,{drawnIcons:t})=>!t.some((t=>((e,t)=>ai(e)<=oi(t)&&oi(e)>=ai(t)&&di(e)>=li(t)&&li(e)<=di(t))(e,t))))(e,t);return i&&s&&n},hi=()=>{},ui=async(e,{onIconClick:t,videoAdContainer:i,logger:s=console})=>{const{element:n,videoElement:r}=i,o=[],{iconsToShow:a,otherIcons:l}=e.reduce(((e,t)=>(((e,t)=>{const i=1e3*t.currentTime,s=1e3*t.duration,n="string"==typeof e.offset?parseInt(e.offset,10):e.offset||0,r=e.duration||s;return n<=i&&i-n<=r})(t,r)?e.iconsToShow.push(t):e.otherIcons.push(t),e)),{iconsToShow:[],otherIcons:[]});return l.forEach((({element:e})=>{var t;null===(t=null==e?void 0:e.parentNode)||void 0===t||t.removeChild(e)})),await a.reduce((async(e,i)=>{try{await e;const s=await(async(e,t)=>{var i;const{placeholder:s}=t,n=await(async(e,t)=>{if(!e.element){const i=await ni(e,t);(i instanceof HTMLIFrameElement||i instanceof HTMLImageElement)&&(i.width="100%",i.height="100%"),i.style.height="100%",i.style.width="100%",e.element=((e,t,{onIconClick:i=hi}={})=>{const s=document.createElement("a");return t.iconClickThrough&&(s.href=t.iconClickThrough,s.target="_blank"),t.iFrameResource&&(e.style.pointerEvents="none"),s.onclick=e=>{void 0!==Event.prototype.stopPropagation&&e.stopPropagation(),i(t)},s.appendChild(e),s})(i,e,t)}return e.element})(e,t),r=((e,t,{drawnIcons:i,placeholder:s})=>{const{signature:n}=e,r=t.getBoundingClientRect(),o=s.getBoundingClientRect(),a=e.width||r.width,l=e.height||r.height,d=e.xPosition||"right",c=e.yPosition||"top";let h,u;if((e=>!["left","right"].includes(String(e).toLowerCase()))(d))h=d;else{const e=i.filter((e=>e.xPosition===d&&e.yPosition===c));h=((e,t,i,s)=>{const n=i.reduce(((e,t)=>e+(t.width?t.width+1:0)),0);return"left"===e?n:s-n-t})(d,a,e,o.width)}var f,p,g;(e=>!["top","bottom"].includes(String(e).toLowerCase()))(c)?u=c:(f=c,p=l,g=o.height,u="top"===f?0:g-p);const m=`${h}-${u}_${a}x${l}`;return Object.assign(e,{height:l,left:h,signature:m,top:u,updated:n!==m,width:a})})(e,n,t);if(!ci(r,t))throw null===(i=n.parentNode)||void 0===i||i.removeChild(n),new Error("Icon can't be rendered");return n.parentNode&&!r.updated||s.appendChild(((e,t)=>{const{height:i,width:s,left:n,top:r,yPosition:o}=t;return e.style.position="absolute",e.style.left=`${n}px`,"bottom"===o?e.style.bottom="0":e.style.top=`${r}px`,e.style.height=`${i}px`,e.style.width=`${s}px`,e})(n,r)),r})(i,{document,drawnIcons:o,onIconClick:t,placeholder:n});o.push(s)}catch(e){s.log(e)}}),Promise.resolve()),o};const fi=Symbol("firstRenderPending"),pi=()=>{},gi=(e,t)=>{var{videoAdContainer:i,onIconView:s=pi,onIconClick:n=pi}=t,r=function(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);n{e[fi]=!0})),{drawIcons:async()=>{const t=await ui(e,Object.assign({onIconClick:n,videoAdContainer:i},r));a.dispatchEvent(new CustomEvent("iconsDrawn")),t.forEach((e=>{e[fi]&&(s(e),e[fi]=!1)}))},hasPendingIconRedraws:()=>((e,t)=>{const i=1e3*t.currentTime,s=1e3*t.duration,n=e.filter((e=>!e.offset||e.offsete.duration&&e.duration0||r.length>0})(e,o),removeIcons:()=>(e=>e.filter((({element:e})=>Boolean(null==e?void 0:e.parentNode))).forEach((({element:e})=>{var t;return null===(t=null==e?void 0:e.parentNode)||void 0===t?void 0:t.removeChild(e)})))(e)}},mi=(e,t)=>{const{screen:i}=window;return e+100>i.width&&t+100>i.height?"fullscreen":e<400?"thumbnail":"normal"};var vi,Ai;const{start:Ei,viewable:yi,notViewable:Ti,viewUndetermined:bi,iconClick:Si,iconView:_i}=F,Ci=Symbol("_private"),Ri=Symbol("_protected");class Li extends qt{constructor(e,t,{viewability:i=!1,responsive:s=!1,logger:n=console,pauseOnAdClick:r=!0}={}){super(n),this[vi]={addIcons:()=>{if(!this.icons)return;const{drawIcons:e,hasPendingIconRedraws:t,removeIcons:i}=gi(this.icons,{logger:this.logger,onIconClick:e=>this.emit(Si,{adUnit:this,data:e,type:Si}),onIconView:e=>this.emit(_i,{adUnit:this,data:e,type:_i}),videoAdContainer:this.videoAdContainer});this[Ri].drawIcons=e,this[Ri].removeIcons=i,this[Ri].hasPendingIconRedraws=t,this[Ri].onFinishCallbacks.push(i)},setupViewableImpression:()=>{let e;const t=zt(this.videoAdContainer.element,(t=>{this.isFinished()||this[Ri].viewable||("boolean"==typeof t?t?e=window.setTimeout(this[Ci].handleViewableImpression,2e3,yi):clearTimeout(e):this[Ci].handleViewableImpression(bi))}),{viewabilityOffset:.5});this[Ri].onFinishCallbacks.push((()=>{t(),clearTimeout(e),this[Ri].viewable||this[Ci].handleViewableImpression(Ti)}))},handleViewableImpression:e=>{this[Ri].viewable=Boolean(e),this.emit(e,{adUnit:this,type:e})},setupViewability:()=>{const e=zt(this.videoAdContainer.element,(e=>{this.isFinished()||"boolean"==typeof e&&(e?this.resume():this.pause())}));this[Ri].onFinishCallbacks.push(e)},setupResponsive:()=>{const{element:e}=this.videoAdContainer;this[Ri].size={height:e.clientHeight,viewmode:mi(e.clientWidth,e.clientHeight),width:e.clientWidth};const t=Vt(e,(()=>{if(this.isFinished())return;const t=this[Ri].size,i=e.clientHeight,s=e.clientWidth;i===(null==t?void 0:t.height)&&s===(null==t?void 0:t.width)||this.resize(s,i,mi(s,i))}));this[Ri].onFinishCallbacks.push(t)}},this[Ai]={finished:!1,started:!1,viewable:!1,onErrorCallbacks:[],onFinishCallbacks:[],finish:()=>{this.isFinished()||(this[Ri].finished=!0,this[Ri].onFinishCallbacks.forEach((e=>e())),this.emit(lt,{adUnit:this,type:lt}))},throwIfCalled:()=>{throw new Error("VideoAdUnit method must be implemented on child class")},throwIfFinished:()=>{if(this.isFinished())throw new Error("VideoAdUnit is finished")}},this.vastChain=e,this.videoAdContainer=t,this.icons=Jt(e),this.pauseOnAdClick=r,this[Ri].onFinishCallbacks.push((e=>{let t=0,i=0;const s=()=>{e.duration-t>3&&(e.pause(),e.play(),e.currentTime=t)},n=()=>{const{currentTime:s}=e;Math.abs(s-t)>3?(i+=1,i>=2&&e.pause(),e.currentTime=t):t=s};return e.addEventListener("timeupdate",n),e.addEventListener("ended",s),()=>{e.removeEventListener("timeupdate",n),e.removeEventListener("ended",s)}})(this.videoAdContainer.videoElement)),this[Ci].addIcons(),e.some((({ad:e})=>e&&Te(e)))&&this.once(Ei,this[Ci].setupViewableImpression),i&&this.once(Ei,this[Ci].setupViewability),s&&this.once(Ei,this[Ci].setupResponsive)}start(){this[Ri].throwIfCalled()}resume(){this[Ri].throwIfCalled()}pause(){this[Ri].throwIfCalled()}skip(){this[Ri].throwIfCalled()}setVolume(e){this[Ri].throwIfCalled()}getVolume(){this[Ri].throwIfCalled()}cancel(){this[Ri].throwIfCalled()}duration(){this[Ri].throwIfCalled()}paused(){this[Ri].throwIfCalled()}currentTime(){this[Ri].throwIfCalled()}onFinish(e){if("function"!=typeof e)throw new TypeError("Expected a callback function");this[Ri].onFinishCallbacks.push(Xe(e,this.logger))}onError(e){if("function"!=typeof e)throw new TypeError("Expected a callback function");this[Ri].onErrorCallbacks.push(Xe(e,this.logger))}isFinished(){return this[Ri].finished}isStarted(){return this[Ri].started}async resize(e,t,i){var s,n,r,o;this[Ri].size={height:t,viewmode:i,width:e},this.isStarted()&&!this.isFinished()&&this.icons&&(await(null===(n=(s=this[Ri]).removeIcons)||void 0===n?void 0:n.call(s)),await(null===(o=(r=this[Ri]).drawIcons)||void 0===o?void 0:o.call(r)))}}var Ii;vi=Ci,Ai=Ri;const{complete:ki,error:wi,skip:Pi}=F,Oi=Symbol("_private");class Di extends Li{constructor(e,t,i={}){super(e,t,i),this[Ii]={handleMetric:(e,t)=>{var i;switch(e){case ki:this[Ri].finish();break;case wi:t instanceof Error&&(this.error=t,this.errorCode=(null===(i=this.error)||void 0===i?void 0:i.code)&&h(this.error.code)?this.error.code:r.VAST_PROBLEM_DISPLAYING_MEDIA_FILE),this[Ri].onErrorCallbacks.forEach((e=>e(this.error,{adUnit:this,vastChain:this.vastChain}))),this[Ri].finish();break;case Pi:this.cancel()}this.emit(e,{adUnit:this,data:t,type:e})},drawIcons:async()=>{var e,t,i,s;if(!this.isFinished()&&(await(null===(t=(e=this[Ri]).drawIcons)||void 0===t?void 0:t.call(e)),(null===(s=(i=this[Ri]).hasPendingIconRedraws)||void 0===s?void 0:s.call(i))&&!this.isFinished())){const{videoElement:e}=this.videoAdContainer;ze(e,"timeupdate",this[Oi].drawIcons)}}},this.type="VAST";const{onFinishCallbacks:s}=this[Ri],{handleMetric:n}=this[Oi];this.hooks=i.hooks||{};const o=(({vastChain:e,videoAdContainer:t,hooks:i,pauseOnAdClick:s},n)=>{const[{ad:r}]=e,o=r&&Re(r),a=r&&Ce(r),l=(e=>e.map((({ad:e})=>e)).reduce(((e,t)=>[...e,...t&&le(t,qe)||[]]),[]).map((({offset:e,uri:t})=>({offset:e,uri:t}))))(e),d=Object.assign({clickThroughUrl:a,pauseOnAdClick:s,progressEvents:l,skipoffset:o},i),c=wt.map((e=>Xe(e(t,n,d))));return()=>c.forEach((e=>e()))})({hooks:this.hooks,pauseOnAdClick:this.pauseOnAdClick,vastChain:this.vastChain,videoAdContainer:this.videoAdContainer},n);s.push(o)}async start(){if(this[Ri].throwIfFinished(),this.isStarted())throw new Pt("VastAdUnit already started");const e=this.vastChain[0].ad,{videoElement:t}=this.videoAdContainer,i=e&&We(e,this.videoAdContainer,this.hooks);if(i)this.icons&&await this[Oi].drawIcons(),(null==i?void 0:i.src)&&(t.src=i.src,this.assetUri=i.src),t.play();else{const e=new Pt("Can't find a suitable media to play");e.code=r.VAST_LINEAR_ASSET_MISMATCH,this[Oi].handleMetric(wi,e)}this[Ri].started=!0}resume(){this.videoAdContainer.videoElement.play()}pause(){this.videoAdContainer.videoElement.pause()}skip(){const e=this.vastChain[0].ad,t=e&&Re(e),i=1e3*this.currentTime();"number"==typeof t&&i>=t&&this[Oi].handleMetric(Pi)}paused(){return this.videoAdContainer.videoElement.paused}setVolume(e){this.videoAdContainer.videoElement.volume=e}getVolume(){return this.videoAdContainer.videoElement.volume}cancel(){this[Ri].throwIfFinished(),this.videoAdContainer.videoElement.pause(),this[Ri].finish()}duration(){return this.isStarted()?this.videoAdContainer.videoElement.duration:0}currentTime(){return this.isStarted()?this.videoAdContainer.videoElement.currentTime:0}async resize(e,t,i){if(await super.resize(e,t,i),this.isStarted()&&!this.isFinished()){const e=this.vastChain[0].ad,{videoElement:t}=this.videoAdContainer,i=e&&We(e,this.videoAdContainer,this.hooks);i&&t.src!==i.src&&((e,t)=>{new Promise((i=>{const s={currentTime:e.currentTime,playing:!e.paused};s.playing&&e.pause(),t.src&&(e.src=t.src),e.load(),ze(e,"loadeddata",(()=>{e.currentTime=s.currentTime,s.playing&&e.play(),i()}))}))})(t,i)}}}Ii=Oi;const Ni=["text/javascript","text/javascript1.0","text/javascript1.2","text/javascript1.4","text/jscript","application/javascript","application/x-javascript","text/ecmascript","text/ecmascript1.0","text/ecmascript1.2","text/ecmascript1.4","text/livescript","application/ecmascript","application/x-ecmascript"],Mi=({type:e})=>Ni.some((t=>t===e)),xi="getAdIcons",Bi="AdLoaded",Fi="AdStarted",Ui="AdStopped",$i="AdSkipped",Vi="AdSizeChange",Gi="AdDurationChange",ji="AdRemainingTimeChange",Ki="AdVolumeChange",Hi="AdImpression",Yi="AdVideoStart",Wi="AdVideoFirstQuartile",zi="AdVideoMidpoint",qi="AdVideoThirdQuartile",Xi="AdVideoComplete",Qi="AdClickThru",Zi="AdUserAcceptInvitation",Ji="AdUserMinimize",es="AdUserClose",ts="AdPaused",is="AdPlaying",ss="AdError",ns=[Bi,Fi,Ui,$i,"AdSkippableStateChange",Vi,"AdLinearChange",Gi,"AdExpandedChange",ji,Ki,Hi,Yi,Wi,zi,qi,Xi,Qi,"AdInteraction",Zi,Ji,es,ts,is,"AdLog",ss],rs=(e,t,i)=>new Promise(((s,n)=>{let r;const o=()=>{"number"==typeof i&&window.clearTimeout(r),e.unsubscribe(o,t),s()};"number"==typeof i&&(r=window.setTimeout((()=>{e.unsubscribe(o,t),n(new Error(`Timeout waiting for event '${t}'`))}),i)),e.subscribe(o,t)})),os=(e,t,i,...s)=>{const n=rs(e,i,5e3),r=e[t];return null==r||r.apply(e,s),n},as=e=>{const t=e.split(".");return parseInt(t[0],10)};var ls;const{complete:ds,mute:cs,unmute:hs,skip:us,start:fs,firstQuartile:ps,pause:gs,resume:ms,impression:vs,midpoint:As,thirdQuartile:Es,clickThrough:ys,error:Ts,closeLinear:bs,creativeView:Ss}=F,_s=ns.filter((e=>e!==Bi)),Cs=Symbol("_private");class Rs extends Li{constructor(e,t,i={}){super(e,t,i),this[ls]={evtHandler:{[Qi]:(e,t,i)=>{i&&this[Cs].handleClickThrough(e),this.emit(ys,{adUnit:this,type:ys})},[Gi]:()=>{this.emit(dt,{adUnit:this,type:dt})},[ss]:e=>{this.error=(e=>{const t=e instanceof Error?e:new Pt("VPAID general error");return t.code&&h(t.code)||(t.code=r.VPAID_ERROR),t})(e),this.errorCode=this.error.code,this[Ri].onErrorCallbacks.forEach((e=>e(this.error,{adUnit:this,vastChain:this.vastChain}))),this[Ri].finish(),this.emit(Ts,{adUnit:this,type:Ts})},[Hi]:()=>{this[Cs].videoStart||this[Cs].handleVpaidEvent(Yi),this.emit(vs,{adUnit:this,type:vs})},[ts]:()=>{this[Cs].paused=!0,this.emit(gs,{adUnit:this,type:gs})},[is]:()=>{this[Cs].paused=!1,this.emit(ms,{adUnit:this,type:ms})},[ji]:()=>{this.emit(dt,{adUnit:this,type:dt})},[$i]:()=>{this.cancel(),this.emit(us,{adUnit:this,type:us})},[Fi]:()=>{this.emit(Ss,{adUnit:this,type:Ss})},[Ui]:()=>{this.emit(Ui,{adUnit:this,type:Ui}),this[Ri].finish()},[Zi]:()=>{this.emit(U,{adUnit:this,type:U})},[es]:()=>{this.emit(bs,{adUnit:this,type:bs}),this[Ri].finish()},[Ji]:()=>{this.emit(V,{adUnit:this,type:V})},[Xi]:()=>{this.emit(ds,{adUnit:this,type:ds})},[Wi]:()=>{this.emit(ps,{adUnit:this,type:ps})},[zi]:()=>{this.emit(As,{adUnit:this,type:As})},[Yi]:()=>{this[Cs].videoStart||(this[Cs].videoStart=!0,this[Cs].paused=!1,this.emit(fs,{adUnit:this,type:fs}))},[qi]:()=>{this.emit(Es,{adUnit:this,type:Es})},[Ki]:()=>{const e=this.getVolume();this.emit(at,{adUnit:this,type:at}),0!==e||this[Cs].muted||(this[Cs].muted=!0,this.emit(cs,{adUnit:this,type:cs})),e>0&&this[Cs].muted&&(this[Cs].muted=!1,this.emit(hs,{adUnit:this,type:hs}))}},handleVpaidEvent:(e,...t)=>{const i=this[Cs].evtHandler[e];i&&i(...t),this.emit(e,{adUnit:this,type:e})},handleClickThrough:e=>{if(this.paused()&&this.pauseOnAdClick)return void this.resume();const t=this.vastChain[0].ad,i="string"==typeof e&&e.length>0?e:t&&Ce(t);this.pauseOnAdClick&&this.pause(),i&&window.open(i,"_blank")},getIcons:()=>{var e;if(null===(e=this.creativeAd)||void 0===e?void 0:e[xi])try{this.creativeAd[xi]()||delete this.icons}catch(e){delete this.icons}},drawIcons:async()=>{var e,t,i,s;this.isFinished()||(await(null===(t=(e=this[Ri]).drawIcons)||void 0===t?void 0:t.call(e)),(null===(s=(i=this[Ri]).hasPendingIconRedraws)||void 0===s?void 0:s.call(i))&&!this.isFinished()&&setTimeout(this[Cs].drawIcons,500))},muted:!1,paused:!0},this.type="VPAID",this[Cs].loadCreativePromise=(async(e,t)=>{const i=(e[0].ad&&Se(e[0].ad)||[]).find(Mi);if(!i||!i.src)throw new TypeError("VastChain does not contain a supported vpaid creative");const{src:s,type:n}=i;return await t.addScript(s,{type:n}),t.executionContext.getVPAIDAd()})(e,t)}async start(){if(this[Ri].throwIfFinished(),this.isStarted())throw new Error("VpaidAdUnit already started");try{this.creativeAd=await this[Cs].loadCreativePromise;const e=rs(this.creativeAd,Bi);for(const e of _s)this.creativeAd.subscribe(this[Cs].handleVpaidEvent.bind(this,e),e);if(this[Cs].getIcons(),((e,t)=>{const i=e.handshakeVersion(t);if(!((e,t)=>{const i=as(t);return!(i<1)&&i<=as(e)})(t,i))throw new Error(`Creative Version '${i}' not supported`)})(this.creativeAd,"2.0"),((e,t,i)=>{const{width:s,height:n}=t.element.getBoundingClientRect(),r=mi(s,n),o=Le(i[0].XML);t.addSlot(s,n);const a={slot:t.slotElement,videoSlot:t.videoElement,videoSlotCanAutoPlay:t.isOriginalVideoElement};e.initAd(s,n,r,-1,o,a)})(this.creativeAd,this.videoAdContainer,this.vastChain),await e,this.videoAdContainer.isDestroyed())return;try{const{videoElement:e}=this.videoAdContainer;e.muted?(this[Cs].muted=!0,this.setVolume(0)):this.setVolume(e.volume),await os(this.creativeAd,"startAd",Fi),this.icons&&await this[Cs].drawIcons(),this[Ri].started=!0}catch(e){this.cancel()}}catch(e){throw this[Cs].handleVpaidEvent(ss,e),e}}resume(){var e;null===(e=this.creativeAd)||void 0===e||e.resumeAd()}pause(){var e;null===(e=this.creativeAd)||void 0===e||e.pauseAd()}skip(){var e;null===(e=this.creativeAd)||void 0===e||e.skipAd()}paused(){return this.isFinished()||this[Cs].paused}setVolume(e){var t;null===(t=this.creativeAd)||void 0===t||t.setAdVolume(e)}getVolume(){return this.creativeAd?this.creativeAd.getAdVolume():0}async cancel(){var e;this[Ri].throwIfFinished();try{const t=this.creativeAd&&rs(this.creativeAd,Ui,3e3);null===(e=this.creativeAd)||void 0===e||e.stopAd(),await t}catch(e){this[Ri].finish()}}duration(){if(!this.creativeAd)return 0;const e=this.creativeAd.getAdDuration();return e<0?0:e}currentTime(){if(!this.creativeAd)return 0;const e=this.creativeAd.getAdRemainingTime();return e<0?0:this.duration()-e}async resize(e,t,i){if(await super.resize(e,t,i),this.creativeAd){if(this.isStarted()&&!this.isFinished()){const i=this.videoAdContainer.slotElement;i&&(i.style.height=`${t}px`,i.style.width=`${e}px`)}return os(this.creativeAd,"resizeAd",Vi,e,t,i)}}}function Ls(e,t,i){const{tracker:s,type:n}=i,r="VPAID"===n?new Rs(e,t,i):new Di(e,t,i);return Object.values(F).forEach((t=>r.on(t,(t=>{const{type:i,data:n}=t,o={data:n,errorCode:r.errorCode,tracker:s};((e,t,{data:i,errorCode:s,tracker:n=Ie,logger:r=console})=>{const{[e]:o}=De;o?o(t,{data:Object.assign(Object.assign({},i),{errorCode:s}),errorCode:s,tracker:n}):r.error(`Event '${e}' cannot be tracked`)})(i,e,o)})))),Object.values(j).forEach((t=>r.on(t,(t=>{const i={data:t.data,tracker:s};((e,t,{data:i,tracker:s=Ie,logger:n=console})=>{const{[e]:r}=Me;r?r(t,{data:Object.assign({},i),tracker:s}):n.error(`Event '${e}' cannot be tracked`)})(t.type,e,i)})))),r}ls=Cs;class Is extends Error{constructor(e){super(e),this.name="VastError",Object.setPrototypeOf(this,Is.prototype)}}const ks=(e,{onAdReady:t})=>new Promise(((i,s)=>{const n=e=>()=>s(new Error(`Ad unit start rejected due to event '${e}'`));e.onError(s),e.on(P,(()=>i(e))),e.on(es,n(es)),e.on(x,n(x)),e.on(Ui,n(Ui)),t(e),e.start()})),ws=async(e,t,i)=>{((e,t)=>{if(!Array.isArray(e)||0===e.length)throw new TypeError("Invalid vastChain");if(!(t instanceof Ge))throw new TypeError("Invalid VideoAdContainer")})(e,t);try{return await((e,t,i)=>{const[{ad:s}]=e;if(!s||!Boolean(Se(s))){const e=new Is("No valid creative found in the passed VAST chain");throw e.code=r.VAST_MEDIA_FILE_NOT_FOUND,e}const n=Ls(e,t,Object.assign(Object.assign({},i),{type:"VPAID"}));return ks(n,i)})(e,t,i)}catch(s){const[{ad:n}]=e;if(n&&((e,t)=>{const i=be(e);return!!i&&i.some((e=>Ke(t,e)))})(n,t.videoElement))return((e,t,i)=>{const s=Ls(e,t,Object.assign(Object.assign({},i),{type:"VAST"}));return ks(s,i)})(e,t,i);throw s}};class Ps extends Error{constructor(e){super(e),this.name="FetchError",Object.setPrototypeOf(this,Ps.prototype)}}const Os=Symbol("requested"),Ds=e=>{e[Os]=!0},Ns=async(e,t,i=[])=>{var s;const n={requestTag:e};let o,a;try{const s=((e,t)=>{const[i]=e,s=Boolean(i)&&i.ad&&Ae(i.ad)&&i.ad?(e=>{const t=X(e,"Wrapper"),i={};if(t){const{allowMultipleAds:e,fallbackOnNoAd:s,followAdditionalWrappers:n}=ee(t);e&&(i.allowMultipleAds=ue(e)),s&&(i.fallbackOnNoAd=ue(s)),n&&(i.followAdditionalWrappers=ue(n))}return i})(i.ad):{};return Object.assign(Object.assign({},s),t)})(i,t);((e,{wrapperLimit:t=5})=>{if(e.length>t){const e=new Is("Wrapper Limit reached");throw e.code=r.VAST_TOO_MANY_REDIRECTS,e}})(i,s);let l=(async(e,t)=>{var i;let s;try{s=await(async(e,t={})=>{const i=Object.assign({credentials:"include"},t),s=await window.fetch(e,i);if(s.status>=400){const e=new Ps(s.statusText);throw e.response=s,e}return s})(e,t);const i=await s.text();return{response:s,XML:i}}catch(e){throw e.code=r.VAST_NONLINEAR_LOADING_FAILED,null!==(i=e.response)&&void 0!==i||(e.response=s),e}})(e,s);"number"==typeof s.timeout&&(a=s.timeout,o=Date.now(),l=Promise.race([l,new Promise(((e,t)=>{setTimeout((()=>{const e=new Is("RequestAd timeout");e.code=r.VAST_LOAD_TIMEOUT,t(e)}),a)}))]));const{response:d,XML:c}=await l;return n.response=d,n.XML=c,n.parsedXML=(e=>{try{return((e,t)=>{const i=e.parseFromString(t,"application/xml");return H.failOnParseError(i),z(i)})(ie,e)}catch(e){throw e.code=r.VAST_XML_PARSING_ERROR,e}})(n.XML),n.ad=(e=>{try{const t=(e=>{const t=pe(e);if(Array.isArray(t)&&t.length>0)return ve(e)?t.filter(me).sort(fe)[0]:t[0]})(e);if(t)return Ds(t),t;throw new Error("No Ad")}catch(e){throw e.code=r.VAST_NO_ADS_AFTER_WRAPPER,e}})(n.parsedXML),(({ad:e,parsedXML:t},{allowMultipleAds:i=!0,followAdditionalWrappers:s=!0})=>{if(!Ae(e)&&!Ee(e)){const e=new Is("Invalid VAST, ad contains neither Wrapper nor Inline");throw e.code=r.VAST_SCHEMA_VALIDATION_ERROR,e}if(ve(t)&&!i){const e=new Is("Multiple ads are not allowed");throw e.code=r.VAST_UNEXPECTED_MEDIA_FILE,e}if(Ae(e)&&!s){const e=new Is("To follow additional wrappers is not allowed");throw e.code=r.VAST_UNEXPECTED_AD_TYPE,e}})(n,s),Ae(n.ad)?(o&&a&&(a-=Date.now()-o),Ns(ye(n.ad),Object.assign(Object.assign({},s),{timeout:a}),[n,...i])):[n,...i]}catch(e){return h(e.code)||(e.code=r.UNKNOWN_ERROR),n.errorCode=e.code,n.error=e,null!==(s=n.response)&&void 0!==s||(n.response=e.response),[n,...i]}},Ms=(e,t)=>{(e=>{if(!Array.isArray(e))throw new TypeError("Invalid VAST chain");if(0===e.length)throw new Error("No next ad to request")})(e);const[i]=e,s=(({ad:e,parsedXML:t},{fallbackOnNoAd:i=!0,useAdBuffet:s=!1})=>{const n=pe(t).filter((e=>!(e=>Boolean(e[Os]))(e)));let r;if(ve(t))s&&(r=n.find((e=>!me(e)))),e&&!r&&(r=((e,t)=>{const i=(ge(e)||0)+1;return t.find((e=>ge(e)===i))})(e,n));else if(n.length>0&&i){const[e]=n;r=e}return r})(i,t);if(s){const n=[Object.assign(Object.assign({},i),{ad:s}),...e.slice(1)];return Ds(s),Ae(s)?Ns(ye(s),t,n):Promise.resolve(n)}return Ms(e.slice(1),t)};const xs=e=>(...t)=>{"function"==typeof e&&e(...t)},Bs=async(e,t,i)=>{var{isCanceled:s}=i,n=function(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);n{var i;if(!e||0===e.length)throw new Error("Invalid VastChain");const[s]=e;if(!t.vpaidEnabled&&(e=>Boolean(e[0].ad&&Se(e[0].ad)))(e)){const e=new Is("VPAID ads are not supported by the current player");e.code=r.VAST_UNEXPECTED_AD_TYPE,s.errorCode=r.VAST_UNEXPECTED_AD_TYPE,s.error=e}if(s.error)throw s.error;"function"==typeof(null===(i=t.hooks)||void 0===i?void 0:i.validateVastResponse)&&t.hooks.validateVastResponse(e)})(o,n),l=await(async(e,t,i)=>{let s;try{const{timeout:n}=i;s=((e,t)=>{if(!e)throw new TypeError("placeholder is required");return new Ge(e,t)})(t,i.videoElement);let o=ws(e,s,i);if("number"==typeof n){let t,s=!1;const n=new Promise(((n,o)=>{t=window.setTimeout((()=>{const{tracker:t}=i;ke(e,{errorCode:r.VAST_MEDIA_LOAD_TIMEOUT,tracker:t}),s=!0,o(new Error("Timeout while starting the ad"))}),i.timeout)})),a=async()=>{const e=await o;return s?e.isStarted()&&e.cancel():clearTimeout(t),e};o=Promise.race([a(),n])}const a=await o;return a.onFinish((()=>{null==s||s.destroy()})),a}catch(e){throw null==s||s.destroy(),e}})(((e,{hooks:t})=>"function"==typeof(null==t?void 0:t.transformVastResponse)?t.transformVastResponse(e):e)(o,n),t,Object.assign({},n)),s())return l.cancel(),void u();l.onError(c),l.onFinish(u),d(l)}catch(e){if(((e,t,i)=>{var s;let n=(null===(s=null==t?void 0:t[0])||void 0===s?void 0:s.errorCode)||(null==e?void 0:e.code);t&&n&&(h(n)||(n=r.UNKNOWN_ERROR),ke(t,{errorCode:n,tracker:i}))})(e,o,n.tracker),c(e,{adUnit:l,vastChain:o}),!o||s())return void u();if(n.timeout&&a&&(n.timeout-=Date.now()-a),a&&n.timeout&&n.timeout<=0)return void u();Bs((()=>Ms(o,n)),t,Object.assign(Object.assign({},n),{isCanceled:s}))}},Fs=(e,t)=>{const i=e&&X(e,t);return i&&J(i)},Us=e=>{const[{ad:t}]=e,i=t&&(e=>{const t=Z(e);return t&&X(t,"Pricing")})(t);return i?{pricing:J(i),pricingCurrency:te(i,"currency"),pricingModel:te(i,"model")}:e.length>1?Us(e.slice(1)):{}},$s=e=>{const t=(e=>e.map((({ad:e})=>e&&te(e,"id"))).filter(Boolean))(e),i=(e=>e.map((({ad:e})=>e&&(e=>{const t=Z(e),i=t&&X(t,"AdSystem");return i&&J(i)})(e))).filter(Boolean))(e),s=(e=>e.map((({ad:e})=>e&&oe(e))).filter(Boolean))(e),n=(e=>e.map((e=>e&&te(e,"id"))).filter(Boolean))(s),r=(e=>e.map((e=>e&&te(e,"adId"))).filter(Boolean))(s),[{ad:o,parsedXML:a,XML:l}]=e,{pricing:d,pricingCurrency:c,pricingModel:h}=Us(e),{category:u,categoryAuthority:f}=(e=>{const t=e&&X(e,"InLine"),i=t&&X(t,"Category");return i?{category:J(i),categoryAuthority:te(i,"authority")}:{}})(o),p=(e=>e&&Z(e))(o),g=(e=>e&&oe(e))(o),m=(e=>e&&X(e,"Linear"))(g),v=(e=>e&&Fs(e,"AdServingId"))(p),A=(e=>{const t=e&&X(e,"VAST");return t?te(t,"version"):"unknown"})(a),E=(e=>e&&Fs(e,"Advertiser"))(p),y=(e=>e&&Fs(e,"AdTitle"))(p),T=(e=>e&&Fs(e,"Description"))(p),b=(e=>e&&Fs(e,"Duration"))(m),S=(e=>e?se(e):void 0)(b);let _,C,R,L,I,k,w,P,O,D,N,M,x=[],B=[],F=[],U=[],$=[];if(Ee(o)){[_,...x]=t,[C,...B]=i,[R,...F]=n,[L,...U]=r,I=o&&Ce(o),k=l?Le(l):void 0;const e=(e=>e&&X(e,"UniversalAdId"))(g);w=e&&J(e),P=e&&te(e,"idRegistry"),$=o&&be(o)||[],O=Boolean(o&&Se(o)),N=m&&te(m,"skipoffset"),M=N?se(N):void 0,D=Boolean(N)}else Ae(e[0].ad)&&(x=t,B=i,F=n,U=r);return{adId:_,adServingId:v,adSystem:C,adTitle:y,advertiser:E,adWrapperCreativeAdIds:U,adWrapperCreativeIds:F,adWrapperIds:x,adWrapperSystems:B,category:u,categoryAuthority:f,clickThroughUrl:I,creativeAdId:L,creativeData:k,creativeId:R,description:T,duration:b,durationInMs:S,mediaFiles:$,pricing:d,pricingCurrency:c,pricingModel:h,skipOffset:N,skipOffsetInMs:M,skippable:D,universalAdId:w,universalAdIdRegistry:P,vastVersion:A,vpaid:O}},Vs=Object.assign(Object.assign({},r),{VAST_UNEXPECTED_AD_SOURCE:299});class Gs{constructor(e){var t;this.clickElement="container",Object.assign(this,null!==(t=Gs.CHANNELS[e])&&void 0!==t?t:Gs.CHANNELS.unknown)}}Gs.CHANNELS={uchannelrussia:{allowBlock:!0,showBlockNumber:!1,maxBlockLength:1/0,reloadFailedAdTag:!0,getNextAdBlockSources:!1},rvtest:{clickElement:o.Pw.isMobile?"button":"container"},championat:{middleRollStartTime:2,clickElement:o.Pw.isMobile?"button":"container"},unknown:{reloadFailedAdTag:!1}};var js=i(5542),Ks=i(377),Hs=i(2452);class Ys{static getDeviceName(){return o.Pw.isAndroid?"1":o.Pw.isiOS?"0":""}static getDeviceType(){var e,t;const{isMobile:i,userAgent:s,os:n}=o.Pw;return"iPhone"===n.name||"iPod"===n.name?"1":"iPad"===n.name?"2":"Android"===n.name&&(null===(e=window.screen)||void 0===e?void 0:e.width)<=1280?"3":"Android"===n.name?"4":"Windows Phone"===n.name?"5":~s.indexOf("tizen")&&(null===(t=window.screen)||void 0===t?void 0:t.width)<=1280?"7":~s.indexOf("tizen")?"8":i?"15":~s.indexOf("SmartTV")?~s.indexOf("NetCast")||~s.indexOf("LG")?"9":~s.indexOf("Samsung")||~s.indexOf("X11")?"10":~s.indexOf("Philips")?"11":~s.indexOf("Sony")?"12":"14":"16"}static getBrowserName(){const{isMobile:e,userAgent:t,data:i,os:s}=o.Pw;if(~t.indexOf("YaBrowser")&&(i.name="YaBrowser"),~t.indexOf("OPR")&&(i.name="Opera"),~t.indexOf("Edg")&&(i.name="Edge"),e){if("YaBrowser"===i.name)return"6";if("Edge"===i.group||"Edge"===i.name)return"22";if("Opera"===i.group||"Opera"===i.name)return"24";if("Chrome Mobile"===i.name||"Chrome"===i.group)return"7";if("Android Browser"===i.name)return"20";if("Explorer"===i.group)return"21";if("Firefox"===i.group)return"23";if("Safari"===i.group&&"iPad"===s.name)return"25";if("Safari"===i.group&&"iPhone"===s.name)return"26"}else{if("Explorer"===i.group)return"1";if("YaBrowser"===i.name)return"6";if("Edge"===i.group||"Edge"===i.name)return"2";if("Opera"===i.group||"Opera"===i.name)return"9";if("Firefox"===i.group)return"3";if("Netscape"===i.group)return"4";if("Safari"===i.group)return"5";if("Chrome"===i.group)return"7";if("Mozilla"===i.group)return"8"}return"27"}static getScreenSize({width:e=640,minWidth:t=0}){const i=e=1280?"3":"4"}}const Ws=(e,t)=>{var i;return e.url=t?null===(i=e.url)||void 0===i?void 0:i.replace(/puid3=\d+/g,`puid3=${t}`):e.url,e};let zs;const qs=(e,t)=>{if(!t.sspJparams)return e;try{const i=(0,Hs.al)(e),s=JSON.parse(i.jparams),n=t.sspJparams,{puid6:r}=n,o=function(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);n{var i;const s=qs(e.replace(/^\/\//,"https://"),t),{provider:n,sspUserId:r,sspUserIdScope:o}=t;zs||(zs=await(null===(i=null==n?void 0:n.getFingerPrintUserId)||void 0===i?void 0:i.call(n)));const a=Object.assign(Object.assign(Object.assign({videoplayer:"@rambler-vp/player",videoplayerver:"1.147.1",outstreamvideo:0},zs?{fpruid:zs}:{}),r?{publisher_uid:r}:{}),o?{publisher_uid_scope:o}:{});return(0,Hs.JT)(s,a)},Qs=480,Zs=(e,t=0)=>o.Pw.isMobile||Number(e.width)>=Qs||t>2?e:{width:Qs,height:Number(e.height)*Qs/Number(e.width)},Js=[{name:"ssp.rambler.ru",allowBlock:!1,reloadFailedAdTag:!0,showRemainingTimeToEnd:!0,addUrlParams:Xs,getSize:Zs},{name:"(ad.mail.ru|(adfox.ru|yandex.ru/ads/adfox)/378150)",allowBlock:void 0,showBlockNumber:!0,maxBlockLength:2,reloadFailedAdTag:!0,showRemainingTimeToEnd:!0,addUrlParams:qs,getSize:Zs,getNextAdBlockSources:Ws},{name:"(adfox.ru|yandex.ru/ads/adfox).*(eid1=6806|puid30=6806)",allowBlock:!0,showBlockNumber:!0,getSkipTime:e=>(e.skipTime2>=0&&(e.skipTime=e.skipTime2),e),getNextAdBlockSources(e,t){const i=Ws(e,t);return i.url=i.url.replace(/eid1=6806/g,"eid1=10620").replace(/puid6=1/g,"puid6=2").replace(/puid30=6806/g,"puid30=10620"),i}},{name:"(adfox.ru|yandex.ru/ads/adfox).*(eid1=11761|puid30=11761|puid6=2)",allowBlock:!0,showBlockNumber:!0,getSkipTime:e=>(e.skipTime2>=0&&(e.skipTime=e.skipTime2),e),getNextAdBlockSources(e,t){const i=Ws(e,t);return i.url=i.url.replace(/eid1=6806/g,"eid1=10620").replace(/puid6=1/g,"puid6=2").replace(/puid30=6806/g,"puid30=10620"),i}},{name:"(adfox.ru|yandex.ru/ads/adfox).*(eid1=6798|puid30=6798)",allowBlock:!0,showBlockNumber:!0,getSkipTime:e=>(e.skipTime2>=0&&(e.skipTime=e.skipTime2),e),getNextAdBlockSources(e,t){const i=Ws(e,t);return i.url=i.url.replace(/eid1=6806/g,"eid1=10620").replace(/puid6=1/g,"puid6=2").replace(/puid30=6806/g,"puid30=10620"),i}},{name:"(adfox.ru|yandex.ru/ads/adfox)",allowBlock:!1,showBlockNumber:!0,getSkipTime:e=>(e.skipTime2>=0&&(e.skipTime=e.skipTime2),e)},{name:"muz-tv.ru",allowBlock:!1,showBlockNumber:!0,getSkipTime:e=>(e.skipTime2>=0&&(e.skipTime=e.skipTime2),e)}];class en extends o.bI{static async preload(e){}static destroy(){}static canPlay(...e){return!0}static getAdPlaybackSources(e,t){const{referrer:i="",width:s}=t;if("VAST"===e.provider&&e.url){const t=new Date,n=i?(0,Hs.al)(i):{},r=encodeURIComponent(i.substring(0,en.MAX_REFERRER_LENGTH)),a=e.url.match(/(ssp\.rambler\.ru|ad\.mail)/)?Qs:0;e.url=e.url.replace(/\[pr\]/g,o.Aq.uniqueId("")).replace(/\[random\]/g,o.Aq.uniqueId("")).replace(/\[date\]/g,t.getDate().toString()).replace(/\[day\]/g,t.getDay().toString()).replace(/\[hours\]/g,t.getHours().toString()).replace(/\[device\]/g,Ys.getDeviceName()).replace(/\[all_device\]/g,Ys.getDeviceType()).replace(/\[gpmd_browser\]/g,Ys.getBrowserName()).replace(/\[dimensions\]/g,Ys.getScreenSize({width:s,minWidth:a})).replace(/\[referer\]/g,r).replace(/\[fullscreen\]/g,"1").replace(/\[arg_(.*?)\]/gi,((e,t)=>n[t]?`${t}=${n[t]}`:"")).replace(/\[var_(.*?)\]/gi,((e,t)=>n[t]?`${n[t]}`:""))}return e}get playerError(){return this.core.playerError}constructor(e,t){super(e),this.createError=o.yF.createError.bind(this),this.core=t}}en.MAX_REFERRER_LENGTH=250;class tn extends en{constructor(){super(...arguments),this.currentTime=0,this.onAdStarted=e=>{this.trigger(l.s.ADPLAYBACK_STARTED,this.sources)},this.onAdImpression=e=>{this.trigger(l.s.ADPLAYBACK_IMPRESSION,this.sources)},this.onAdPaused=e=>{this.trigger(l.s.ADPLAYBACK_PAUSED,this.sources)},this.onAdResumed=e=>{this.trigger(l.s.ADPLAYBACK_RESUMED,this.sources)},this.onAdComplete=e=>{this.trigger(l.s.ADPLAYBACK_COMPLETE,this.sources)},this.onAdUserClose=e=>{this.trigger(l.s.ADPLAYBACK_USER_CLOSE,this.sources)},this.onAdVolumeChange=e=>{this.trigger(l.s.ADPLAYBACK_VOLUME_CHANGE,this.sources)},this.onAdContentResumeRequested=e=>{this.trigger(l.s.ADPLAYBACK_CONTENT_RESUME_REQUESTED,this.sources)},this.onAdError=e=>{const t=e.getError(),i=t.getErrorCode(),s=i===this.ima.AdError.ErrorCode.VIDEO_PLAY_ERROR||i===this.ima.AdError.ErrorCode.FAILED_TO_REQUEST_ADS||i===this.ima.AdError.ErrorCode.VAST_ASSET_MISMATCH||i===this.ima.AdError.ErrorCode.VAST_LINEAR_ASSET_MISMATCH||i===this.ima.AdError.ErrorCode.VAST_NONLINEAR_ASSET_MISMATCH||i===this.ima.AdError.ErrorCode.VAST_ASSET_NOT_FOUND||i===this.ima.AdError.ErrorCode.NONLINEAR_DIMENSIONS_ERROR||i===this.ima.AdError.ErrorCode.COMPANION_REQUIRED_ERROR||i===this.ima.AdError.ErrorCode.UNKNOWN_ERROR||i===this.ima.AdError.ErrorCode.AUTOPLAY_DISALLOWED,n=this.createError({code:`${null!=i?i:c.n4}`,description:t.getMessage(),level:o.Mk.Levels.WARN,raw:Object.assign(Object.assign({},this.sources),{canRefetch:s,code:i})});this.trigger(l.s.ADPLAYBACK_ERROR,n)}}static canPlay(e){var t;return!!(null===(t=window.google)||void 0===t?void 0:t.ima)&&"VAST"===e.provider&&!!e.url}static async preload(e){var t,i;if(!(null===(t=window.google)||void 0===t?void 0:t.ima))return null!==(i=tn.preloadPromise)&&void 0!==i||(tn.preloadPromise=(async()=>{var e,t,i,s;try{await(0,js.k0)(`//imasdk.googleapis.com/js/sdkloader/${(0,Ks._o)()?"ima3_debug":"ima3"}.js`),null===(e=window.google)||void 0===e||e.ima.settings.setPlayerType("@rambler-vp/player"),null===(t=window.google)||void 0===t||t.ima.settings.setPlayerVersion("1.147.1"),null===(i=window.google)||void 0===i||i.ima.settings.setLocale(o.Aq.getBrowserLanguage()),null===(s=window.google)||void 0===s||s.ima.settings.setVpaidMode(window.google.ima.ImaSdkSettings.VpaidMode.INSECURE)}catch(e){delete tn.preloadPromise}})()),await tn.preloadPromise}static destroy(){var e;null===(e=tn.adDisplayContainer)||void 0===e||e.destroy(),delete tn.adDisplayContainer}get adDisplayContainer(){return tn.adDisplayContainer}set adDisplayContainer(e){tn.adDisplayContainer=e}get allowBlock(){return!1}get reloadFailedAdTag(){return!1}get name(){return"imaPlayback"}get ima(){var e;return null===(e=window.google)||void 0===e?void 0:e.ima}async load(e){var t;e.url=e.url.replace(/\[sessionid\]/g,o.Aq.uniqueId("")),e.url.match("ssp.rambler.ru")&&(e.url=null!==(t=await Xs(e.url,this.core.options))&&void 0!==t?t:e.url),this.sources=e,this.createAdDisplayContainer(),this.createAdsRequest(),await this.loadAdsManager(),this.initAdsManager()}createAdDisplayContainer(){if(!this.adDisplayContainer){const{containerElement:e,videoElement:t,clickTrackingElement:i}=this.options;this.adDisplayContainer=new this.ima.AdDisplayContainer(e,t,i),this.adDisplayContainer.initialize()}}createAdsRequest(){const{videoElement:e,muted:t}=this.options;this.adsRequest=new this.ima.AdsRequest,this.adsRequest.adTagUrl=this.sources.url,this.adsRequest.vastLoadTimeout=tn.VAST_LOAD_TIMEOUT,this.adsRequest.linearAdSlotWidth=e.offsetWidth,this.adsRequest.linearAdSlotHeight=e.offsetHeight,this.adsRequest.nonLinearAdSlotWidth=e.offsetWidth,this.adsRequest.nonLinearAdSlotHeight=e.offsetHeight,this.adsRequest.setAdWillAutoPlay(!0),this.adsRequest.setAdWillPlayMuted(t)}async loadAdsManager(){let e;try{this.adsLoader=new this.ima.AdsLoader(this.adDisplayContainer),e=await new Promise(((e,t)=>{this.adsLoader.addEventListener(this.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,e),this.adsLoader.addEventListener(this.ima.AdErrorEvent.Type.AD_ERROR,t),this.adsLoader.requestAds(this.adsRequest)}))}catch(e){return void this.onAdError(e)}const t=new this.ima.AdsRenderingSettings;t.loadVideoTimeout=tn.LOAD_VIDEO_TIMEOUT,t.restoreCustomPlaybackStateOnAdBreakComplete=!1,this.adsManager=e.getAdsManager(this.options.videoElement,t),this.adsManager.addEventListener(this.ima.AdEvent.Type.LOADED,(e=>this.onAdLoaded(e))),this.adsManager.addEventListener(this.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,this.onAdContentResumeRequested),this.adsManager.addEventListener(this.ima.AdErrorEvent.Type.AD_ERROR,this.onAdError),this.adsManager.addEventListener(this.ima.AdEvent.Type.STARTED,this.onAdStarted),this.adsManager.addEventListener(this.ima.AdEvent.Type.IMPRESSION,this.onAdImpression),this.adsManager.addEventListener(this.ima.AdEvent.Type.AD_PROGRESS,(e=>this.onAdProgress(e))),this.adsManager.addEventListener(this.ima.AdEvent.Type.VOLUME_CHANGED,this.onAdVolumeChange),this.adsManager.addEventListener(this.ima.AdEvent.Type.VOLUME_MUTED,this.onAdVolumeChange),this.adsManager.addEventListener(this.ima.AdEvent.Type.PAUSED,this.onAdPaused),this.adsManager.addEventListener(this.ima.AdEvent.Type.RESUMED,this.onAdResumed),this.adsManager.addEventListener(this.ima.AdEvent.Type.COMPLETED,this.onAdComplete),this.adsManager.addEventListener(this.ima.AdEvent.Type.USER_CLOSE,this.onAdUserClose),this.adsManager.addEventListener(this.ima.AdEvent.Type.CLICK,(e=>this.onAdClick(e))),this.adsManager.addEventListener(this.ima.AdEvent.Type.SKIPPED,(e=>this.onAdSkipped(e)))}initAdsManager(){if(this.adsManager){const{videoElement:e}=this.options;this.adsManager.init(e.offsetWidth,e.offsetHeight,this.ima.ViewMode.NORMAL),this.trigger(l.s.ADPLAYBACK_READY,this.sources)}}onAdLoaded(e){this.ad=e.getAd(),this.trigger(l.s.ADPLAYBACK_LOADED,this.sources),this.isLinear()||this.options.videoElement.play()}onAdProgress(e){const{duration:t=0,currentTime:i=0}=e.getAdData();this.currentTime=i,this.trigger(l.s.ADPLAYBACK_PROGRESS,Object.assign(Object.assign({},this.sources),{current:i,total:t}))}onAdClick(e){this.trigger(l.s.ADPLAYBACK_CLICK,this.sources)}onAdSkipped(e){this.trigger(l.s.ADPLAYBACK_SKIPPED,this.sources)}start(){var e;null===(e=this.adsManager)||void 0===e||e.start()}pause(){var e;null===(e=this.adsManager)||void 0===e||e.pause()}resume(){var e;null===(e=this.adsManager)||void 0===e||e.resume()}skip(){var e,t,i,s;(null===(e=this.adsManager)||void 0===e?void 0:e.getAdSkippableState())?null===(t=this.adsManager)||void 0===t||t.skip():(null===(i=this.adsManager)||void 0===i||i.addEventListener(this.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,(e=>this.onAdSkipped(e))),null===(s=this.adsManager)||void 0===s||s.stop())}setVolume(e){var t;null===(t=this.adsManager)||void 0===t||t.setVolume(e/100)}getVolume(){var e,t;return 100*(null!==(t=null===(e=this.adsManager)||void 0===e?void 0:e.getVolume())&&void 0!==t?t:0)}resize(e){var t;null===(t=this.adsManager)||void 0===t||t.resize(e.width,e.height,this.ima.ViewMode.NORMAL)}getDuration(){var e,t;return null!==(t=null===(e=this.ad)||void 0===e?void 0:e.getDuration())&&void 0!==t?t:0}getCurrentTime(){return this.currentTime}isLinear(){var e,t;return null===(t=null===(e=this.ad)||void 0===e?void 0:e.isLinear())||void 0===t||t}getAdSystem(){var e,t;return null!==(t=null===(e=this.ad)||void 0===e?void 0:e.getAdSystem())&&void 0!==t?t:c.n4}getAdType(){var e,t;const i=null===(t=null===(e=this.ad)||void 0===e?void 0:e.getApiFramework())||void 0===t?void 0:t.toLowerCase();return i?"vpaid"===i?"vpaid":"vast":"unknown"}destroy(){var e,t,i;null===(e=this.adsLoader)||void 0===e||e.contentComplete(),null===(t=this.adsLoader)||void 0===t||t.destroy(),null===(i=this.adsManager)||void 0===i||i.destroy()}}tn.VAST_LOAD_TIMEOUT=8e3,tn.LOAD_VIDEO_TIMEOUT=1e4,tn.adDisplayContainer=null;var sn=i(997),nn=i(6413),rn=i(5008);const on=(0,rn.L)((()=>i.e(5327).then(i.bind(i,5327)))),an=(0,rn.L)((()=>i.e(4929).then(i.bind(i,4929))));class ln extends en{constructor(){super(...arguments),this.currentTime=0,this.started=!1,this.destroyed=!1,this.isResizedAfter2s=!1,this.adSystem={},this.errors=[],this.extensions={startTime:0,skipTime:-1,skipTime2:-1,controls:!0,isClickable:!0,WOW:!1,Allowblock:!1,CustomTracking:{}},this.applyContainerClassNames=Dt()((()=>{var e,t;null===(t=null===(e=this.getContainerClassNames)||void 0===e?void 0:e.call(this,{height:this.core.el.offsetHeight}))||void 0===t||t.forEach((e=>{this.core.$el.toggleClass(...e)}))}),60),this.onAdLoaded=(e=[])=>(this.errors=[],this.vastChain=e,this.details=$s(e),this.parseExtensions(),this.parseSkipTimeOffset(),this.trigger(l.s.ADPLAYBACK_LOADED,Object.assign(Object.assign({},this.sources),{requestTags:e.map((e=>{var t;return null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.url}))})),this.trackURLs(this.customTracking.onVastLoad),this.hasMediaFiles||this.trackURLs(this.customTracking.onVastEmpty),this.subscribeOnSizeChanges(),e),this.onAdReady=e=>{var t;if(this.destroyed)return void(e.isFinished()||e.cancel());const{videoElement:i,muted:s}=this.options;null!=s&&(this.muted=i.muted,i.muted=s),this.muted&&(this.volume=i.volume,i.volume=0),this.ad=e,this.adSize&&this.adSize.width!==(null===(t=this.currentSize)||void 0===t?void 0:t.width)&&this.setAdElementsSize(this.adSize),this.ad.on("start",this.onAdStarted),this.ad.on("impression",this.onAdImpression),this.ad.on("volumeChanged",this.onAdVolumeChange),this.ad.on("pause",this.onAdPaused),this.ad.on("resume",this.onAdResumed),this.ad.on("closeLinear",this.onAdUserClose),this.ad.on("clickThrough",this.onAdClick),this.ad.on("skip",this.onAdSkipped),this.ad.on("complete",this.onAdComplete)},this.onAdStarted=()=>{this.adSize&&this.ad.resize(this.adSize.width,this.adSize.height,"normal"),this.started=!0,this.startAdProgressInterval(),this.trigger(l.s.ADPLAYBACK_STARTED,this.sources);const{$el:e,advertisement:t,controls:i,isWOW:s,isClickable:n,linkTxt:r,showRemainingTimeToEnd:o,skipTime2:a,i18n:d}=this;if((i||s)&&this.$panel.show(),!i||!t||!e)return;this.bindControlsEvents(),this.changeVolumeUI(this.getVolume()),this.$panelText.show(),this.$seekBar.show(),this.$volumeButton.show();const c=this.getDuration(),h=a>=0&&a{let t=null;"adlabel"===e?t=this.$acceptButton:"soundbtn"===e&&(t=this.$volumeButton),(null==t?void 0:t.length)&&t.toggle("0"!==i[e]&&"-1"!==i[e])}));const{allowBlock:f,blockCompleteCount:p,maxBlockLength:g,showBlockNumber:m}=t,v=f&&m&&p{var e,t,i;const s=(null===(e=this.mediaControl)||void 0===e?void 0:e.muted)?ln.VOLUME:0;this.setVolume(s),this.changeVolumeUI(s),null===(t=this.mediaControl)||void 0===t||t.toggleMute(),null===(i=this.notifier)||void 0===i||i.showMessage(this.i18n.t(s?"unmuted":"muted"),this.classNames.volumeMessage)},this.onAdImpression=()=>{this.trigger(l.s.ADPLAYBACK_IMPRESSION,this.sources)},this.onAdProgress=()=>{var e,t,i,s,n;const r=null!==(e=this.ad.duration())&&void 0!==e?e:0,o=this.getDuration();let a=this.ad.currentTime();if(null==a||Number.isNaN(a)){const e=null===(i=null===(t=this.ad.videoAdContainer)||void 0===t?void 0:t.videoElement)||void 0===i?void 0:i.currentTime;"number"!=typeof e||Number.isNaN(e)||(a=e)}if(null===(s=this.$el)||void 0===s||s.toggleClass(this.classNames.timerDisabled,null==a||Number.isNaN(a)),null==a||Number.isNaN(a)||a===this.currentTime)return;a<0&&0===r&&o>0&&(a+=o,a<0&&(a=0)),this.currentTime=a,this.trigger(l.s.ADPLAYBACK_PROGRESS,Object.assign(Object.assign({},this.sources),{current:a,total:o})),a>2&&this.adSystem.getSize&&this.adSize&&this.currentSize&&!this.isResizedAfter2s&&(this.adSize.width!==this.currentSize.width&&(this.restoreAdElementsSize(),this.resize(this.currentSize)),this.isResizedAfter2s=!0);const{advertisement:h,controls:u,isWOW:f,showRemainingTimeToEnd:p,skipTime2:g}=this;if(o<=0||!u||!h)return;const{blockCompleteCount:m,maxBlockLength:v}=h,A=Math.min(a,o),E=g>=0&&g<=o?g:null,y=null!=E&&E>A?Math.ceil(E-A):null,T=Math.ceil(o-A);let b;if(this.$seekBar.css("width",A/o*100+"%"),m0)if(null!=E||e){if(p){const t=e?T:(0,d.V1)(1e3*T);this.$panelText.html(`${t} сек.`)}}else b=T}if(null!=y?b=y:f?this.$panel.hide():null!=E&&this.$skipButton.removeClass("eagleplayer-advertisement-skip-button-disabled").show(),null!=b&&this.$skipButton.addClass("eagleplayer-advertisement-skip-button-disabled").show().find(".eagleplayer-advertisement-skip-timer").html(String(b)),null!=E||p){const e=null!=E?null!=y?y:0:T;this.$skipTime.find("span").html(String(e))}null===(n=this.$el)||void 0===n||n.toggleClass(this.classNames.skipActive,null!=E&&E{clearInterval(this.adProgressInterval),this.trigger(l.s.ADPLAYBACK_PAUSED,this.sources)},this.onAdResumed=()=>{this.startAdProgressInterval(),this.trigger(l.s.ADPLAYBACK_RESUMED,this.sources)},this.onAdUserClose=()=>{this.trigger(l.s.ADPLAYBACK_USER_CLOSE,this.sources)},this.onAdVolumeChange=()=>{this.trigger(l.s.ADPLAYBACK_VOLUME_CHANGE,this.sources)},this.onAdClick=()=>{this.trigger(l.s.ADPLAYBACK_CLICK,this.sources),this.trackURLs(this.addClick)},this.onAdSkipped=()=>{this.trigger(l.s.ADPLAYBACK_SKIPPED,this.sources)},this.onAdComplete=()=>{this.trigger(l.s.ADPLAYBACK_COMPLETE,this.sources)},this.onAdError=(e,t)=>{var i,s,n;const r=null!==(s=null===(i=t.vastChain)||void 0===i?void 0:i.map((e=>{var t;return null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.url})))&&void 0!==s?s:[],a=ln.REFETCH_ERRORS.includes(e.code),d=this.createError({code:`${null!==(n=e.code)&&void 0!==n?n:c.n4}`,description:e.message,level:o.Mk.Levels.WARN,raw:Object.assign(Object.assign({},this.sources),{requestTags:r,canRefetch:a,code:e.code})});"No next ad to request"!==e.message&&this.errors.unshift(d),this.trigger(l.s.ADPLAYBACK_WARNING,d)},this.onAdFinish=()=>{var e;if(this.destroyed)return;this.restoreDefaultVideoElement();const[t]=this.errors,i=!this.started&&ln.NOT_STARTED_ERRORS.includes(null===(e=null==t?void 0:t.raw)||void 0===e?void 0:e.code);if(this.vastChain&&i){const e=new Error("the vast ad was loaded but did not start"),i=this.vastChain.map((e=>{var t;return null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.url})),s={requestTags:i,XML:this.vastChain.slice(0,1).map((e=>null==e?void 0:e.XML))};if(t){const{raw:e}=t,i=function(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);n{const t=e.width||0,i=e.height||0;return{aspectRatio:i?Math.floor(t/i*10)/10:0,height:i,width:t}},this.getMediaFile=e=>{if(!this.embedSize)return;const t=this.getRectParams({width:Number(this.embedSize.width),height:Number(this.embedSize.height)});return e.slice(0).sort(((e,i)=>{const s=this.getRectParams({width:Number(e.width),height:Number(e.height)}),n=this.getRectParams({width:Number(i.width),height:Number(i.height)}),r=Math.abs(t.width-s.width),o=Math.abs(t.width-n.width);return Math.abs(t.aspectRatio-s.aspectRatio)-Math.abs(t.aspectRatio-n.aspectRatio)||r-o}))[0]},this.skip=()=>{var e,t;const{skipOffsetInMs:i}=this.details;this.trackURLs(this.skipAd),this.trackURLs(this.customTracking.onSkipAd),null!=i&&i>=0?null===(e=this.ad)||void 0===e||e.skip():null===(t=this.ad)||void 0===t||t.cancel()},this.setPreviewTimeout=()=>{this.clearPreviewTimeout(),this.previewTimeout=window.setTimeout(this.hidePreview.bind(this),ln.PREVIEW_DURATION)},this.clearPreviewTimeout=()=>{window.clearTimeout(this.previewTimeout)},this.showPreview=()=>{this.$preview.toggleClass(this.classNames.previewVisible,!0),this.setPreviewTimeout()},this.hidePreview=()=>{var e;null===(e=this.clearPreviewTimeout)||void 0===e||e.call(this),this.$preview.toggleClass(this.classNames.previewVisible,!1)}}static canPlay(e){return"VAST"===e.provider&&!!e.url&&!!Js.find((t=>{var i;return t.name&&(null===(i=e.url)||void 0===i?void 0:i.match(new RegExp(t.name)))}))}static async preload(e){var t,i;if(!e.advertisement)return;if(null!==(t=ln.loaded)&&void 0!==t||(ln.loaded=!0),ln.template)return;const n=null===(i=e.mediaControl)||void 0===i?void 0:i.skinName,r=n&&s[n]||on;if("function"!=typeof r)return;const{default:o,classNames:a,getContainerClassNames:l}=await r();o&&(ln.template=o),a&&(ln.classNames=a),ln.getContainerClassNames=l}get template(){return(0,o.vs)(ln.template)}get classNames(){return ln.classNames}get getContainerClassNames(){return ln.getContainerClassNames}get name(){return"vastPlayback"}get reloadFailedAdTag(){return this.adSystem.reloadFailedAdTag}get showRemainingTimeToEnd(){return Boolean(this.adSystem.showRemainingTimeToEnd)}get allowBlock(){var e;return null!==(e=this.adSystem.allowBlock)&&void 0!==e?e:!1===this.extensions.Allowblock&&this.extensions.Allowblock}get showBlockNumber(){return this.adSystem.showBlockNumber}get maxBlockLength(){return this.adSystem.maxBlockLength}get getNextAdBlockSources(){return this.adSystem.getNextAdBlockSources}get controls(){return this.extensions.controls}get isWOW(){return this.extensions.WOW}get isClickable(){return this.extensions.isClickable}get linkTxt(){var e;return null!==(e=this.extensions.linkTxt)&&void 0!==e?e:""}get skipTime(){return this.extensions.skipTime}get skipTime2(){return this.extensions.skipTime2}get customTracking(){return this.extensions.CustomTracking}get hasMediaFiles(){var e;return Boolean(null===(e=this.details.mediaFiles)||void 0===e?void 0:e.length)}get addClick(){var e;return null!==(e=this.extensions.addClick)&&void 0!==e?e:[]}get skipAd(){var e;return null!==(e=this.extensions.skipAd)&&void 0!==e?e:[]}get i18n(){return this.core.i18n}get mediaControl(){return this.core.getPlugin("mediaControl")}get notifier(){return this.core.getPlugin("notifier")}get advertisement(){return this.core.getPlugin("advertisement")}get docking(){return this.core.getPlugin("docking")}async load(e){var t,i,s,n,r,a,d,c,h;this.sources=Object.assign({},e),this.adSystem=null!==(t=Js.find((e=>e.name&&this.sources.url.match(new RegExp(e.name)))))&&void 0!==t?t:{},this.sources.url=e.url.replace(/\[sessionid\]/g,o.Aq.uniqueId("")),this.sources.url=null!==(n=await(null===(s=(i=this.adSystem).addUrlParams)||void 0===s?void 0:s.call(i,this.sources.url,this.core.options)))&&void 0!==n?n:this.sources.url,this.currentSize={width:this.options.videoElement.offsetWidth,height:this.options.videoElement.offsetHeight},this.adSize=null!==(d=null===(a=(r=this.adSystem).getSize)||void 0===a?void 0:a.call(r,this.currentSize))&&void 0!==d?d:this.currentSize,this.embedSize=null!==(h=null===(c=this.docking)||void 0===c?void 0:c.getEmbedSize())&&void 0!==h?h:this.currentSize,this.trigger(l.s.ADPLAYBACK_READY,this.sources)}bindControlsEvents(){var e,t,i,s,n;null===(e=this.$volumeButton)||void 0===e||e.on("click",this.toggleMute),null===(t=this.$skipButton)||void 0===t||t.on("click",this.skip),null===(i=this.$skip)||void 0===i||i.on("click",this.skip),null===(s=this.$showPreview)||void 0===s||s.on("click",this.showPreview),null===(n=this.$hidePreview)||void 0===n||n.on("click",this.hidePreview)}unbindControlsEvents(){var e,t,i,s,n;null===(e=this.$volumeButton)||void 0===e||e.off("click",this.toggleMute),null===(t=this.$skipButton)||void 0===t||t.off("click",this.skip),null===(i=this.$skip)||void 0===i||i.off("click",this.skip),null===(s=this.$showPreview)||void 0===s||s.off("click",this.showPreview),null===(n=this.$hidePreview)||void 0===n||n.off("click",this.hidePreview)}subscribeOnSizeChanges(){window.addEventListener("resize",this.applyContainerClassNames),window.addEventListener("orientationchange",this.applyContainerClassNames),this.applyContainerClassNames()}unsubscribeFromSizeChanges(){var e,t;window.removeEventListener("resize",this.applyContainerClassNames),window.removeEventListener("orientationchange",this.applyContainerClassNames),null===(t=null===(e=this.getContainerClassNames)||void 0===e?void 0:e.call(this,{height:this.core.el.offsetHeight}))||void 0===t||t.forEach((([e])=>{this.core.$el.toggleClass(e,!1)}))}changeVolumeUI(e){const{hasSound:t}=this.classNames;t?this.$volumeButton.toggleClass(t,e>0):(this.$volumeButton.find(".epvi-none").toggle(0===e),this.$volumeButton.find(".epvi-1").toggle(e>0),this.$volumeButton.find(".epvi-2").toggle(e>ln.VOLUME),this.$volumeButton.find(".epvi-3").toggle(e>2*ln.VOLUME))}startAdProgressInterval(){this.isLinear()&&(this.adProgressInterval=window.setInterval(this.onAdProgress,ln.PROGRESS_INTERVAL))}setAdElementsSize(e){var t;this.options.videoElement.style.width=`${e.width}px`,this.options.videoElement.style.height=`${e.height}px`,(null===(t=this.ad)||void 0===t?void 0:t.videoAdContainer)&&(this.ad.videoAdContainer.element.style.width=`${e.width}px`,this.ad.videoAdContainer.element.style.height=`${e.height}px`)}restoreAdElementsSize(){var e;this.restoreDefaultVideoElement(),(null===(e=this.ad)||void 0===e?void 0:e.videoAdContainer)&&(this.ad.videoAdContainer.element.style.width="100%",this.ad.videoAdContainer.element.style.height="100%")}restoreDefaultVideoElement(){var e,t;(null===(e=this.adSize)||void 0===e?void 0:e.width)!==(null===(t=this.currentSize)||void 0===t?void 0:t.width)&&(this.options.videoElement.style.width="100%",this.options.videoElement.style.height="100%"),null!=this.muted&&(this.options.videoElement.muted=this.muted),null!=this.volume&&(this.options.videoElement.volume=this.volume)}parseExtensions(){var e;const t=[...null!==(e=this.vastChain)&&void 0!==e?e:[]].reduce(((e,t)=>{var i,s,n,r,o,a;return[...e,...null!==(a=null===(o=null===(r=null===(n=null===(s=null===(i=null==t?void 0:t.ad)||void 0===i?void 0:i.elements)||void 0===s?void 0:s[0])||void 0===n?void 0:n.elements)||void 0===r?void 0:r.filter((e=>"extensions"===e.name))[0])||void 0===o?void 0:o.elements)&&void 0!==a?a:[]]}),[]);this.parseExtensionNodes(t)}parseExtensionNodes(e){var t,i,s;if(null==e?void 0:e.length)for(let n=0;n=0||this.extensions.skipTime2>=0)&&(this.extensions=null!==(i=null===(t=(e=this.adSystem).getSkipTime)||void 0===t?void 0:t.call(e,this.extensions,s/1e3))&&void 0!==i?i:this.extensions),this.extensions.skipTime2<0&&null!=n&&n>=0&&(this.extensions.skipTime2=n/1e3)}trackURLs(e){var t;if(!e||0===e.length)return;const i={};if(this.isLinear()){const{mediaFiles:e,durationInMs:s}=this.details;(null===(t=e[0])||void 0===t?void 0:t.src)&&(i.ASSETURI=(0,Hs.rT)(e[0].src)),s&&(i.CONTENTPLAYHEAD=(0,Hs.rT)((0,d.V1)(s,{hours:!0,ms:!0})))}i.CACHEBUSTING=(0,sn.Ro)(Math.round(1e8*Math.random()).toString(),"0",8),i.TIMESTAMP=(0,Hs.rT)((new Date).toISOString()),i.RANDOM=i.random=i.CACHEBUSTING,e.forEach((e=>{if("string"!=typeof e)return;let t=e;for(const s in i)if(i.hasOwnProperty(s)){const n=i[s];t=e.replace(`[${s}]`,n).replace(`%%${s}%%`,n)}(new Image).src=t}),{})}createInvisibleElement(){const e=document.createElement("div");return e.style.position="absolute",e.style.width="0px",e.style.height="0px",e.style.display="none",e}start(){var e;const{advertisement:t}=this;if(this.destroyed||!t)return;this.render();const{containerElement:i,videoElement:s,clickTrackingElement:n}=this.options,r="button"===(null===(e=t.channel)||void 0===e?void 0:e.clickElement)&&this.$acceptButton.get(0)||n;((e,t,i)=>{var s,n,r;let o,a=!1;const l=xs(i.onAdStart),d=Object.assign(Object.assign({vpaidEnabled:!0},i),{onAdReady:xs(i.onAdReady),onAdStart:e=>{o=e,l(o)},onError:xs(i.onError),onRunFinish:xs(i.onRunFinish)});/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream&&(null===(s=i.videoElement)||void 0===s?void 0:s.paused)&&(null===(n=i.videoElement)||void 0===n?void 0:n.canPlayType("application/vnd.apple.mpegurl"))&&(null===(r=i.videoElement)||void 0===r||r.load()),Bs((()=>Ns(e,d)),t,Object.assign(Object.assign({},d),{isCanceled:()=>a}))})(this.sources.url,i,{videoElement:s,responsive:!0,pauseOnAdClick:!1,timeout:ln.VAST_LOAD_TIMEOUT,onAdReady:this.onAdReady,onError:this.onAdError,onRunFinish:this.onAdFinish,hooks:{createSkipControl:this.createInvisibleElement,createClickControl:r&&(()=>r),getMediaFile:this.getMediaFile,transformVastResponse:this.onAdLoaded}})}pause(){var e,t;(null===(e=this.ad)||void 0===e?void 0:e.isStarted())&&(null===(t=this.ad)||void 0===t||t.pause())}resume(){var e,t;(null===(e=this.ad)||void 0===e?void 0:e.isStarted())&&(null===(t=this.ad)||void 0===t||t.resume())}setVolume(e){var t;null===(t=this.ad)||void 0===t||t.setVolume(e/100)}getVolume(){var e,t;return 100*(null!==(t=null===(e=this.ad)||void 0===e?void 0:e.getVolume())&&void 0!==t?t:0)}resize(e){var t,i,s,n,r,o;if(!(null===(t=this.ad)||void 0===t?void 0:t.isFinished())){const t=null!==(n=null===(s=(i=this.adSystem).getSize)||void 0===s?void 0:s.call(i,e,this.currentTime))&&void 0!==n?n:e;this.currentTime<=2&&this.adSystem.getSize&&this.adSize&&this.currentSize&&(t.width!==e.width?this.setAdElementsSize(t):this.adSize.width!==this.currentSize.width&&this.restoreAdElementsSize()),this.currentSize=e,this.adSize=t,(null===(r=this.ad)||void 0===r?void 0:r.isStarted())&&(null===(o=this.ad)||void 0===o||o.resize(this.adSize.width,this.adSize.height,"normal"))}}getDuration(){var e,t;const i=this.isLinear()?(null===(e=this.ad)||void 0===e?void 0:e.duration())||this.details.durationInMs/1e3:null===(t=this.ad)||void 0===t?void 0:t.duration();return null!=i?i:0}getCurrentTime(){return this.currentTime}isLinear(){var e;return null!=(null===(e=this.details)||void 0===e?void 0:e.durationInMs)}getAdSystem(){var e,t;return null!==(t=null===(e=this.details)||void 0===e?void 0:e.adSystem)&&void 0!==t?t:c.n4}getAdType(){var e;return this.details?(null===(e=this.details)||void 0===e?void 0:e.vpaid)?"vpaid":"vast":"unknown"}destroy(){var e,t,i;clearInterval(this.adProgressInterval),this.destroyed=!0,(null===(e=this.ad)||void 0===e?void 0:e.isFinished())||null===(t=this.ad)||void 0===t||t.cancel(),this.hideControls(),this.unbindControlsEvents(),this.unsubscribeFromSizeChanges(),null===(i=this.$el)||void 0===i||i.remove(),delete this.$el}hideControls(){const{advertisement:e,$el:t}=this;e&&t&&(this.$panel.hide(),this.$panelText.hide(),this.hidePreview(),t.toggleClass(this.classNames.withSkip,!1).toggleClass(this.classNames.withRemainTime,!1).toggleClass(this.classNames.withBlockCount,!1).toggleClass(this.classNames.withLabel,!1),this.$skipButton.hide(),this.$acceptButton.hide(),this.$volumeButton.hide(),this.$seekBar.hide())}render(){var e;const{advertisement:t}=this;if(!this.core.$el.parents().length||this.$el||!t)return this;const{playList:i}=this.core.options;return this.$el=$(this.template({preview:(null==i?void 0:i.snapshot)||"none",title:null!==(e=null==i?void 0:i.title)&&void 0!==e?e:"",duration:i?(0,d.V1)(i.duration):"",i18n:["advertisement","advertisement_link","advertisement_after","advertisement_skip","advertisement_skip_timer","advertisement_watch","advertisement_watch_timer","advertisement_block","advertisement_block_of","unmute"].reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this.core.i18n.t(t)})),{})})),t.$el.append(this.$el),this.$panel=this.$el.find(".eagleplayer-advertisement-panel"),this.$panelText=this.$el.find(".eagleplayer-advertisement-panel-text"),this.$preview=this.$el.find("[data-ad-preview]"),this.$showPreview=this.$el.find("[data-ad-preview-show]"),this.$hidePreview=this.$el.find("[data-ad-preview-hide]"),this.$skip=this.$el.find("[data-ad-skip]"),this.$skipTime=this.$el.find("[data-ad-skip-time]"),this.$blockCount=this.$el.find("[data-ad-block-count]"),this.$skipButton=this.$el.find(".eagleplayer-advertisement-skip-button"),this.$acceptButton=this.$el.find("[data-ad-accept], .eagleplayer-advertisement-accept-button"),this.$volumeButton=this.$el.find("[data-ad-volume], .eagleplayer-advertisement-volume-button"),this.$seekBar=this.$el.find("[data-ad-seek], .eagleplayer-advertisement-seek-bar"),this.hideControls(),this}}ln.VAST_LOAD_TIMEOUT=3e4,ln.PREVIEW_DURATION=3e3,ln.VOLUME=10,ln.PROGRESS_INTERVAL=500,ln.loaded=!1,ln.template="",ln.classNames={},ln.REFETCH_ERRORS=[r.VAST_LINEAR_ASSET_MISMATCH,r.VAST_PROBLEM_DISPLAYING_MEDIA_FILE,r.UNKNOWN_ERROR,r.VPAID_ERROR],ln.NOT_STARTED_ERRORS=[void 0,r.VAST_UNEXPECTED_AD_TYPE,r.VAST_UNEXPECTED_LINEARITY,r.VAST_UNEXPECTED_DURATION_ERROR,r.VAST_UNEXPECTED_MEDIA_FILE,r.VAST_WRAPPER_ERROR,r.VIDEO_PLAY_ERROR,r.VAST_MEDIA_FILE_NOT_FOUND,r.VAST_MEDIA_LOAD_TIMEOUT,r.VAST_LINEAR_ASSET_MISMATCH,r.VAST_PROBLEM_DISPLAYING_MEDIA_FILE,r.VAST_NONLINEAR_PLAYING_FAILED,r.VAST_NONLINEAR_DIMENSIONS_ERROR,r.VAST_NONLINEAR_LOADING_FAILED,r.VAST_NONLINEAR_ASSET_MISMATCH,r.UNKNOWN_ERROR,r.VPAID_ERROR];class dn extends en{constructor(){super(...arguments),this.currentTime=0,this.allowBlock=!1,this.reloadFailedAdTag=!1,this.onAdStarted=()=>{this.trigger(l.s.ADPLAYBACK_IMPRESSION,this.sources),this.trigger(l.s.ADPLAYBACK_STARTED,this.sources),this.onAdProgress(),this.adProgressInterval=window.setInterval(this.onAdProgress,dn.PROGRESS_INTERVAL)},this.onAdProgress=()=>{var e;if("play"!==this.adPlaybackController.getAdPlayingState())return void delete this.diffStartTime;const t=this.getDuration(),i=Date.now()/1e3,s=i-(null!==(e=this.diffStartTime)&&void 0!==e?e:i),n=this.currentTime<0?0:Math.min(this.currentTime+s,t);this.diffStartTime=i,n!==this.currentTime&&(this.currentTime=n,this.trigger(l.s.ADPLAYBACK_PROGRESS,Object.assign(Object.assign({},this.sources),{current:n,total:t})))},this.onAdVolumeChange=()=>{this.trigger(l.s.ADPLAYBACK_VOLUME_CHANGE,this.sources)},this.onAdClick=()=>{this.trigger(l.s.ADPLAYBACK_CLICK,this.sources)},this.onAdSkipped=()=>{this.trigger(l.s.ADPLAYBACK_SKIPPED,this.sources)},this.onAdPodError=e=>{this.adPodError=Object.assign({},e)},this.onAdStopped=()=>{var e,t;const i="VPAIDLoadingError"===(null===(e=this.adPodError)||void 0===e?void 0:e.code)||"NO_AD_SECTION"===(null===(t=this.adPodError)||void 0===t?void 0:t.code);this.adPodError&&i?this.onAdError(this.adPodError):this.onAdContentResumeRequested()},this.onAdContentResumeRequested=()=>{this.trigger(l.s.ADPLAYBACK_CONTENT_RESUME_REQUESTED,this.sources)},this.onAdError=e=>{const t=e.code&&dn.ErrorCode[e.code],i=this.createError({code:`${null!=t?t:c.n4}`,description:e.message,level:o.Mk.Levels.WARN,raw:Object.assign(Object.assign({},this.sources),{code:t})});this.trigger(l.s.ADPLAYBACK_ERROR,i)}}static canPlay(e){var t;return!!(null===(t=window.ya)||void 0===t?void 0:t.videoAd)&&"YANDEX"===e.provider&&!!e.partnerId}static async preload(){var e,t;if(!(null===(e=window.ya)||void 0===e?void 0:e.videoAd))return null!==(t=dn.preloadPromise)&&void 0!==t||(dn.preloadPromise=(async()=>{try{await(0,js.k0)("https://yandex.ru/ads/system/adsdk.js")}catch(e){delete dn.preloadPromise}})()),await dn.preloadPromise}get name(){return"yandexPlayback"}async createLoader(e){const{AdLoader:t}=await window.ya.videoAd.loadModule("AdLoader"),{partnerId:i,category:s,impId:n}=e;return await t.create({partnerId:i,category:s,impId:n})}async load(e){this.sources=e;try{const t=await this.createLoader(e);this.adViewer=await t.loadAd();const{containerElement:i,videoElement:s}=this.options;this.adPlaybackController=this.adViewer.createPlaybackController(s,i),this.adPlaybackController.subscribe("AdStarted",this.onAdStarted),this.adPlaybackController.subscribe("AdVolumeChange",this.onAdVolumeChange),this.adPlaybackController.subscribe("AdClickThru",this.onAdClick),this.adPlaybackController.subscribe("AdPodSkipped",this.onAdSkipped),this.adPlaybackController.subscribe("AdPodError",this.onAdPodError),this.adPlaybackController.subscribe("AdStopped",this.onAdStopped),this.trigger(l.s.ADPLAYBACK_LOADED,this.sources),this.trigger(l.s.ADPLAYBACK_READY,this.sources)}catch(e){this.onAdError(e)}}static getAdPlaybackSources(e,t){const{blockType:i}=t;return"YANDEX"===e.provider&&("partnerId"in e&&(e.partnerId=Number(e.partnerId)),"category"in e&&(e.category=Number(e.category)),e.impId=Number(e.impId)||dn.IMPID[i]),super.getAdPlaybackSources(e,t)}start(){var e;null===(e=this.adPlaybackController)||void 0===e||e.playAd()}pause(){var e;null===(e=this.adPlaybackController)||void 0===e||e.pauseAd(),this.trigger(l.s.ADPLAYBACK_PAUSED,this.sources)}resume(){var e;null===(e=this.adPlaybackController)||void 0===e||e.resumeAd(),this.trigger(l.s.ADPLAYBACK_RESUMED,this.sources)}skip(){var e;null===(e=this.adPlaybackController)||void 0===e||e.skipAd()}setVolume(e){var t;null===(t=this.adPlaybackController)||void 0===t||t.setAdVolume(e/100)}getVolume(){var e,t;return 100*(null!==(t=null===(e=this.adPlaybackController)||void 0===e?void 0:e.getAdVolume())&&void 0!==t?t:0)}resize(e){}getDuration(){var e;return null===(e=this.adPlaybackController)||void 0===e?void 0:e.getAdDuration()}getCurrentTime(){return this.currentTime}isLinear(){return!0}getAdSystem(){return"Yandex"}getAdType(){return"unknown"}destroy(){var e;clearInterval(this.adProgressInterval),null===(e=this.adViewer)||void 0===e||e.destroy()}}dn.PROGRESS_INTERVAL=500,dn.IMPID={preRoll:1,preRollMobile:1,postRoll:2,postRollMobile:2,middleRoll:3,middleRollMobile:3,pauseRoll:3,pauseRollMobile:3,banner:4,bannerMobile:4,pauseBanner:3,pauseBannerMobile:3,pseudostreaming:3,pseudostreamingMobile:3},dn.ErrorCode={NO_AD_SECTION:r.VAST_NO_ADS_AFTER_WRAPPER,VIDEO_PLAY_REJECTED:r.VIDEO_PLAY_ERROR,VPAID_METHOD_CALL_ERROR:r.VPAID_ERROR,YANDEX_VPAID_METHOD_CALL_ERROR:r.VPAID_ERROR,YANDEX_VPAID_FRIENDLY_IFRAME_SECURITY_POLICY_VIOLATION:r.VPAID_ERROR,SLOT_SMALL_SIZE:r.VAST_UNEXPECTED_MEDIA_FILE,VPAID_START_TIMEOUT:r.VAST_MEDIA_LOAD_TIMEOUT,VPAIDPlayingError:r.VIDEO_PLAY_ERROR,VMAP_LOAD_TIMEOUT:r.VAST_LOAD_TIMEOUT,MEDIA_ERR_SRC_NOT_SUPPORTED:r.VAST_LINEAR_ASSET_MISMATCH,VPAIDLoadingError:r.VAST_MEDIA_LOAD_TIMEOUT,WRAPPER_LOAD_TIMEOUT:r.VAST_LOAD_TIMEOUT,MEDIA_ERR_DECODE_ON_START:r.VAST_PROBLEM_DISPLAYING_MEDIA_FILE,WRAPPER_LOAD_ERROR:r.VAST_WRAPPER_ERROR,YANDEX_VAST_LOAD_TIMEOUT:r.VAST_LOAD_TIMEOUT,YANDEX_WRAPPER_LOAD_ERROR:r.VAST_WRAPPER_ERROR,YANDEX_WRAPPER_LOAD_TIMEOUT:r.VAST_LOAD_TIMEOUT,VIDEO_TIMEOUT:r.VAST_MEDIA_LOAD_TIMEOUT,YANDEX_NO_GET_VPAID_AD_FUNC:r.VPAID_ERROR,YANDEX_WRAPPER_MAX_COUNT_LIMIT:r.VAST_TOO_MANY_REDIRECTS,YANDEX_VPAID_FRIENDLY_IFRAME_UNHANDLED_GLOBAL_ERROR:r.VPAID_ERROR,MSE_VIDEO_ATTACH_FAIL:r.VIDEO_PLAY_ERROR};class cn extends dn{static canPlay(e){var t;return!!(null===(t=window.ya)||void 0===t?void 0:t.videoAd)&&"ADFOX"===e.provider&&!!e.url}get name(){return"adfoxPlayback"}async createLoader(e){const{AdLoader:t}=await window.ya.videoAd.loadModule("AdLoader"),{pathname:i}=new URL(e.url),{p1:s,p2:n}=(0,Hs.al)(e.url),r=null==i?void 0:i.split("/").find(Boolean);return await t.create({adFoxParameters:{ownerId:r,params:{p1:s,p2:n}}})}getAdSystem(){return"AdFox"}}const hn=(0,rn.L)((()=>i.e(7027).then(i.bind(i,7027)))),un=(0,rn.L)((()=>i.e(4671).then(i.bind(i,4671))));class fn extends tn{static async preload(e){var t;if(fn.loaded)return;fn.loaded=!0;const i=null===(t=e.mediaControl)||void 0===t?void 0:t.skinName,s=i&&n[i]||hn;await Promise.all([super.preload(e),s()])}static destroy(){var e;null===(e=fn.bannerDisplayContainer)||void 0===e||e.destroy(),delete fn.bannerDisplayContainer}get adDisplayContainer(){return fn.bannerDisplayContainer}set adDisplayContainer(e){fn.bannerDisplayContainer=e}get name(){return"overlayPlayback"}createAdDisplayContainer(){this.adDisplayContainer||(this.adDisplayContainer=new this.ima.AdDisplayContainer(this.options.containerElement),this.adDisplayContainer.initialize())}createAdsRequest(){const e=this.getSize(this.sources.url);this.adsRequest=new this.ima.AdsRequest,this.adsRequest.adTagUrl=this.sources.url,this.adsRequest.vastLoadTimeout=fn.VAST_LOAD_TIMEOUT,this.adsRequest.nonLinearAdSlotWidth=e.width,this.adsRequest.nonLinearAdSlotHeight=e.height,this.options.containerElement.style.height=`${e.height}px`,this.adsRequest.setAdWillAutoPlay(!0),this.adsRequest.setAdWillPlayMuted(this.options.muted)}async loadAdsManager(){let e;try{this.adsLoader=new this.ima.AdsLoader(this.adDisplayContainer),e=await new Promise(((e,t)=>{this.adsLoader.addEventListener(this.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,e),this.adsLoader.addEventListener(this.ima.AdErrorEvent.Type.AD_ERROR,t),this.adsLoader.requestAds(this.adsRequest)}))}catch(e){return void this.onAdError(e)}const t=new this.ima.AdsRenderingSettings;t.useStyledNonLinearAds=!0,t.loadVideoTimeout=fn.LOAD_VIDEO_TIMEOUT,t.restoreCustomPlaybackStateOnAdBreakComplete=!1,this.adsManager=e.getAdsManager(this.options.videoElement,t),this.adsManager.addEventListener(this.ima.AdEvent.Type.LOADED,(e=>this.onAdLoaded(e))),this.adsManager.addEventListener(this.ima.AdErrorEvent.Type.AD_ERROR,this.onAdError),this.adsManager.addEventListener(this.ima.AdEvent.Type.USER_CLOSE,this.onAdUserClose)}initAdsManager(){if(this.adsManager){const e=this.getSize(this.sources.url);this.adsManager.init(e.width,e.height,this.ima.ViewMode.NORMAL),this.trigger(l.s.ADPLAYBACK_READY,this.sources)}}getSize(e){const{offsetWidth:t}=this.options.videoElement,i=e.match(/sz=(\d+)x(\d+)/);let s,n;return i?(s=parseInt(i[1],10),n=parseInt(i[2],10),s>t&&(n=n*t/s,s=t)):(s=t,n=s<400?50:100,e.match("advarkads.com")&&(n=200),(e.match("ads.adfox.ru")||e.match("ssp.rambler.ru"))&&(n=s<400?55:105)),{width:s,height:n}}resize(){var e;const t=this.getSize(this.sources.url);this.options.containerElement.style.height=`${t.height}px`,null===(e=this.adsManager)||void 0===e||e.resize(t.width,t.height,this.ima.ViewMode.NORMAL)}destroy(){var e,t,i;null===(e=this.adsLoader)||void 0===e||e.contentComplete(),null===(t=this.adsLoader)||void 0===t||t.destroy(),null===(i=this.adsManager)||void 0===i||i.destroy()}}fn.bannerDisplayContainer=null,fn.loaded=!1;var pn=i(5072),gn=i.n(pn),mn=i(7825),vn=i.n(mn),An=i(7659),En=i.n(An),yn=i(5056),Tn=i.n(yn),bn=i(540),Sn=i.n(bn),_n=i(1113),Cn=i.n(_n),Rn=i(611),Ln={};Ln.styleTagTransform=Cn(),Ln.setAttributes=Tn(),Ln.insert=En().bind(null,"head"),Ln.domAPI=vn(),Ln.insertStyleElement=Sn(),gn()(Rn.A,Ln),Rn.A&&Rn.A.locals&&Rn.A.locals;const In=Symbol("onVisibleAreaChanged");class kn extends o.DI{constructor(){super(...arguments),this.viewability=!1,this.adSourcesLoadsCount=0,this._blockCompleteCount=0,this.lastRollStartTime=0,this.lastBannerStartTime=0,this.currentContainerTime=0,this.containerEnded=!1,this.playing=!1,this.rendered=!1,this.adSourcesIndex=0,this.bannerSourcesIndex=0,this.inStreamPlaybacks=[ln,dn,tn,cn],this.overlayPlaybacks=[fn,dn],this.skip=()=>{var e;null===(e=this.ad)||void 0===e||e.skip()},this.togglePause=()=>{this.pause(),this.trigger(l.s.ADVERTISEMENT_INTERACTION_PLAYING)},this.togglePlay=()=>{this.play(),this.trigger(l.s.ADVERTISEMENT_INTERACTION_PLAYING)}}static async preload(e){e.advertisement&&!kn.loaded&&(kn.loaded=!0,await Promise.all([tn.preload(e),fn.preload(e),dn.preload(),ln.preload(e)]))}get name(){return"advertisement"}get supportedVersion(){return{min:"0.5.0"}}get attributes(){return{class:"eagleplayer-advertisement",style:"width: 100%","data-advertisement":""}}get template(){return(0,o.vs)('
\n\n')}get multiPlayer(){return this.core.getPlugin("multiplayer")}get mediaControl(){return this.core.getPlugin("mediaControl")}get viewport(){return this.core.getPlugin("viewport")}get params(){return this.core.options.advertisement}get getVisibleArea(){var e,t;const{provider:i}=this.core.options;return null!==(t=null===(e=null==i?void 0:i.params)||void 0===e?void 0:e.getVisibleArea)&&void 0!==t?t:null==i?void 0:i.getVisibleArea}get channel(){return this._channel}get allowBlock(){var e,t,i,s,n;return Boolean((null!==(s=null!==(t=null===(e=this.channel)||void 0===e?void 0:e.allowBlock)&&void 0!==t?t:null===(i=this.ad)||void 0===i?void 0:i.allowBlock)&&void 0!==s?s:this.params.allowBlock)&&this.currentBlockType&&(null===(n=this.params[this.currentBlockType])||void 0===n?void 0:n.enableBlock))}get showBlockNumber(){var e,t,i;return this.ad instanceof ln&&Boolean(null!==(t=null===(e=this.channel)||void 0===e?void 0:e.showBlockNumber)&&void 0!==t?t:null===(i=this.ad)||void 0===i?void 0:i.showBlockNumber)}get maxBlockLength(){var e,t,i,s;return this.ad instanceof ln?null!==(s=null!==(t=null===(e=this.channel)||void 0===e?void 0:e.maxBlockLength)&&void 0!==t?t:null===(i=this.ad)||void 0===i?void 0:i.maxBlockLength)&&void 0!==s?s:1/0:1}get blockCompleteCount(){return this._blockCompleteCount}get currentTime(){var e,t;return null!==(t=null===(e=this.ad)||void 0===e?void 0:e.getCurrentTime())&&void 0!==t?t:0}get reloadFailedAdTag(){var e,t,i;return Boolean(null!==(t=null===(e=this.channel)||void 0===e?void 0:e.reloadFailedAdTag)&&void 0!==t?t:null===(i=this.ad)||void 0===i?void 0:i.reloadFailedAdTag)}get getNextAdBlockSources(){var e,t,i;return this.ad instanceof ln&&(null!==(t=null===(e=this.channel)||void 0===e?void 0:e.getNextAdBlockSources)&&void 0!==t?t:null===(i=this.ad)||void 0===i?void 0:i.getNextAdBlockSources)||void 0}get vodMiddleRollStartTime(){var e;const t=this.core.activePlayback.getDuration();return!this.lastRollStartTime&&(null===(e=this.channel)||void 0===e?void 0:e.middleRollStartTime)?this.channel.middleRollStartTime:t>600&&t<1620?540:t>=1620&&t<3600?900:t>=3600?1200:0}bindEvents(){const{activeContainer:e,activePlayback:t}=this.core;this.listenToOnce(this.core,l.s.CORE_READY,this.onReady),this.listenTo(this.core,l.s.CORE_ACTIVE_CONTAINER_CHANGED,this.onActiveContainerChange),this.listenTo(this.core,l.s.CORE_RESIZE,this.onResize),this.listenTo(this,l.s.ADVERTISEMENT_ENDED,this.onAdvertisementEnded),this.listenTo(this,l.s.ADVERTISEMENT_LOADING,this.hideBanner),this.mediaControl&&(this.listenTo(this.mediaControl,l.s.MEDIACONTROL_RENDERED,this.render),this.listenTo(this.mediaControl,l.s.MEDIACONTROL_SHARE,this.onMediaControlShare)),e&&(this.listenTo(e,l.s.CONTAINER_TIMEUPDATE,this.onTimeUpdate),this.listenTo(e,l.s.CONTAINER_PLAY,this.onPlay),this.listenTo(e,l.s.CONTAINER_PAUSE,this.onPause),this.listenToOnce(e,l.s.CONTAINER_ENDED,this.onEnded)),t&&!this.core.isReady&&this.listenToOnce(t,l.s.PLAYBACK_PLAY_INTENT,this.onInitialPlay),this.viewport&&this.listenTo(this.viewport,l.s.VIEWPORT_VISIBLE_AREA_CHANGED,this[In])}onActiveContainerChange(){this.stopListening(),this.bindEvents()}onReady(){var e,t;const{activePlayback:i,activeContainer:s}=this.core;s&&i.getPlaybackType()!==o.YZ.NO_OP?(null!==(e=this._channel)&&void 0!==e||(this._channel=new Gs(null!==(t=this.core.options.channel)&&void 0!==t?t:c.n4)),this.prepareBlockTime(),this.prepareAdTemplate(),this.render(),this.trigger(l.s.ADVERTISEMENT_READY)):this.disable()}onResize(){var e,t;const{offsetWidth:i,offsetHeight:s}=this.core.el;null===(e=this.ad)||void 0===e||e.resize({width:i,height:s}),this.$el.css("height",s),null===(t=this.banner)||void 0===t||t.resize()}isPreRollWithStartTime(e){const t=["preRoll","preRollMobile"].includes(e),i=this.params[e];return t&&!!(null==i?void 0:i.start)&&(null==i?void 0:i.start)>0}onInitialPlay(){var e;const t=o.Pw.isMobile?"preRollMobile":"preRoll";(null===(e=this.params[t])||void 0===e?void 0:e.sources)&&!this.isPreRollWithStartTime(t)&&(this.core.activePlayback.pause(),this.startRoll(o.Pw.isMobile?"preRollMobile":"preRoll"))}onPlayAfterPause(){const e=o.Pw.isMobile?this.params.pauseRollMobile:this.params.pauseRoll;(null==e?void 0:e.sources)&&(this.core.activePlayback.pause(),this.startRoll(o.Pw.isMobile?"pauseRollMobile":"pauseRoll"))}onMediaControlShare(){const e=this.core.getPlugin("share"),{activeContainer:t}=this.core;e&&t&&(this.stopListening(t,l.s.CONTAINER_PAUSE,this.onPause),this.listenToOnce(e,l.s.SHARE_CLOSE,(()=>{this.listenTo(t,l.s.CONTAINER_PAUSE,this.onPause)})))}startPreRollWithStartTime(e){const{activePlayback:t}=this.core,i=o.Pw.isMobile?"preRollMobile":"preRoll",s=this.params[i];if((null==s?void 0:s.sources)&&(null==s?void 0:s.start)&&(null==s?void 0:s.start)>this.lastRollStartTime&&(null==s?void 0:s.start)){const n=s.start-e.current,r=n<0&&t.isPlaying();this.trigger(l.s.ADVERTISEMENT_TIME_TO_PREROLL,n),r&&(this.lastRollStartTime=e.current,this.startRoll(i))}}startMiddleRoll(e){const{activePlayback:t}=this.core,i=o.Pw.isMobile?this.params.middleRollMobile:this.params.middleRoll;if(!(null==i?void 0:i.sources))return;let s;if(t.getPlaybackType()===o.YZ.LIVE){const t=((null==i?void 0:i.refreshTime)||0)/1e3,n=((null==i?void 0:i.startupTime)||0)/1e3;s=n&&t&&(e.current>n&&n>this.lastRollStartTime||e.current>this.lastRollStartTime+t)}const n=this.vodMiddleRollStartTime,r=n&&e.current>this.lastRollStartTime+n;t.isPlaying()&&(s||r)&&(this.lastRollStartTime=e.current,this.startRoll(o.Pw.isMobile?"middleRollMobile":"middleRoll"))}startBannerRoll(e){var t;const{activePlayback:i}=this.core,s=o.Pw.isMobile?this.params.bannerMobile:this.params.banner;if(!Array.isArray(null==s?void 0:s.sources)||!(null===(t=s.sources)||void 0===t?void 0:t[0]))return;const n=((null==s?void 0:s.startupTime)||0)/1e3;if("YANDEX"===s.sources[0].provider)return void(!o.Pw.isMobile&&e.current>n&&this.startBanner());const r=((null==s?void 0:s.showTime)||0)/1e3,a=((null==s?void 0:s.refreshTime)||0)/1e3;if(i.isPlaying()&&n&&r&&(e.current>n&&n>this.lastBannerStartTime||a&&e.current>this.lastBannerStartTime+r+a))return this.lastBannerStartTime=e.current,void(this.$bannerContainer?this.showBanner():this.startBanner());n&&r&&e.current>this.lastBannerStartTime+r&&(a?this.hideBanner():this.closeBanner())}startPseudoStreaming(e){var t,i;const{activePlayback:s}=this.core,n=o.Pw.isMobile?this.params.pseudostreamingMobile:this.params.pseudostreaming;if(!(Array.isArray(null==n?void 0:n.sources)&&e.current>this.lastRollStartTime)||(null===(t=this.mediaControl)||void 0===t?void 0:t.$el.hasClass("eplayer-time-to-ad-visible"))||!(null==n?void 0:n.urlCallTime))return;const r=60*n.urlCallTime;let a,l;if(this.core.options.usePseudoStreaming){const t=null===(i=this.multiPlayer)||void 0===i?void 0:i.prevItemsDuration;null!=t&&(l=e.current+t/1e3,a=Math.ceil((kn.lastPseudoStreamingStartTime||1)/r)*r)}else a=Math.ceil((this.lastRollStartTime||1)/r)*r;s.isPlaying()&&null!=a&&(null!=l?l:e.current)>a&&(this.lastRollStartTime=e.current,null!=l&&(kn.lastPseudoStreamingStartTime=l),this.startRoll(o.Pw.isMobile?"pseudostreamingMobile":"pseudostreaming"))}onTimeUpdate(e){this.startPreRollWithStartTime(e),this.startMiddleRoll(e),this.startBannerRoll(e),this.startPseudoStreaming(e)}onPause(){const{activeContainer:e,activePlayback:t}=this.core;e.ended||(this.startRoll(o.Pw.isMobile?"pauseBannerMobile":"pauseBanner"),this.listenToOnce(t,l.s.PLAYBACK_PLAY_INTENT,this.onPlayAfterPause))}onPlay(){this.containerEnded=!1}onEnded(){this.containerEnded=!0;const{multiPlayer:e}=this;e&&!e.isMainRecord||this.startRoll(o.Pw.isMobile?"postRollMobile":"postRoll"),(null==e?void 0:e.isLastRecord)&&(kn.lastPseudoStreamingStartTime=0),this.lastRollStartTime=0}prepareBlockTime(){Object.entries(kn.BLOCK_TIME).forEach((([e,t])=>{var i;const s=this.params[e];s&&(null!==(i=s.blockTime)&&void 0!==i||(s.blockTime=t))}))}prepareAdTemplate(){const{el:e,options:t}=this.core,{referrer:i=""}=t;Object.keys(this.params).forEach((t=>{const s=this.params[t];s&&Array.isArray(null==s?void 0:s.sources)&&(s.sources=s.sources.map((s=>{const n=(["banner","banner_mobile"].includes(t)?this.overlayPlaybacks:this.inStreamPlaybacks).find((e=>e.canPlay(s)));return null==n?void 0:n.getAdPlaybackSources(s,{referrer:i,width:e.offsetWidth,blockType:t})})).filter(Boolean))}))}isPlaying(){return this.playing}hasAd(){return Boolean(this.currentBlockType)}getVolume(){var e,t;return null!==(t=null===(e=this.ad)||void 0===e?void 0:e.getVolume())&&void 0!==t?t:0}async trackViewability(){if(this.getVisibleArea){const{height:e}=await this.getVisibleArea(),{parentElement:t}=this.core.options,i=t?e/t.offsetHeight:0;this[In](i)}}triggerAdEvent(e,t){var i,s,n;const r=null===(i=this.ad)||void 0===i?void 0:i.getAdSystem(),o=null===(s=this.ad)||void 0===s?void 0:s.getAdType();this.trigger(e,Object.assign(Object.assign({},t),{adSystem:r,adType:o,adPlayback:null===(n=this.ad)||void 0===n?void 0:n.name,blockType:this.currentBlockType,index:this.adSourcesIndex,requestCount:this.adSourcesLoadsCount}))}triggerBannerEvent(e,t){var i,s,n;const r=null===(i=this.banner)||void 0===i?void 0:i.getAdSystem(),a=null===(s=this.banner)||void 0===s?void 0:s.getAdType(),l=o.Pw.isMobile?"bannerMobile":"banner";this.trigger(e,Object.assign(Object.assign({},t),{adSystem:r,adType:a,adPlayback:null===(n=this.ad)||void 0===n?void 0:n.name,blockType:l,index:this.bannerSourcesIndex,requestCount:1}))}[In](e){if(this.playing&&!this.viewability){const t=!document.hidden&&e>=kn.MIN_VIEWABILITY_HEIGHT;!t&&this.viewabilityTimeout&&(clearTimeout(this.viewabilityTimeout),delete this.viewabilityTimeout),t&&!this.viewabilityTimeout&&(this.viewabilityTimeout=window.setTimeout((()=>this.onAdViewable()),kn.VIEWABILITY_TIMEOUT))}const{activeContainer:t}=this.core,{autoPlay:i,[a.gM]:s,minPlayingVisibleHeight:n=.5}=this.core.options;if(!this.playing&&t&&(i||s)){const i=!document.hidden&&(!s||e>=n);if(i===this.isVisible)return;i?this.listenTo(t,l.s.CONTAINER_PAUSE,this.onPause):this.stopListening(t,l.s.CONTAINER_PAUSE,this.onPause),this.isVisible=i}}startRoll(e){var t;if(!this.enabled||this.currentBlockType)return;const i=null===(t=this.params[e])||void 0===t?void 0:t.sources;Array.isArray(i)&&(null==i?void 0:i[0])&&(this.currentBlockType=e,this.requestAd(i[0]))}requestAd(e){var t,i,s;const{core:n}=this,{activeContainer:r}=n,a=this.inStreamPlaybacks.find((t=>t.canPlay(e)));if(this.currentContainerTime||(this.currentContainerTime=r.getCurrentTime()),this.currentContainerVolume=r.volume,this.adSourcesLoadsCount++,this.adSourcesIndex++,!a){const t=this.createError({code:`${Vs.VAST_UNEXPECTED_AD_SOURCE}`,description:"no ad playback found for such sources",level:o.Mk.Levels.WARN,raw:Object.assign(Object.assign({},e),{code:Vs.VAST_UNEXPECTED_AD_SOURCE})});return void this.onAdError(t)}this.hideControls(),this.currentBlockType&&this.isPreRollWithStartTime(this.currentBlockType)||"middleRoll"===this.currentBlockType||"middleRollMobile"===this.currentBlockType||"pseudostreaming"===this.currentBlockType||"pseudostreamingMobile"===this.currentBlockType||null===(t=null==r?void 0:r.getPlugin("click_to_pause"))||void 0===t||t.disable(),this.destroyAd();const d={muted:(null==e?void 0:e.mute)||(null===(i=this.mediaControl)||void 0===i?void 0:i.muted),containerElement:this.$adContainer.get(0),get videoElement(){return n.activePlayback.el},clickTrackingElement:this.$clickArea.get(0)};this.ad=new a(d,n),this.ad&&(this.listenToOnce(this.ad,l.s.ADPLAYBACK_READY,this.onAdReady),this.listenToOnce(this.ad,l.s.ADPLAYBACK_LOADED,this.onAdLoaded),this.listenToOnce(this.ad,l.s.ADPLAYBACK_STARTED,this.onAdStarted),this.listenToOnce(this.ad,l.s.ADPLAYBACK_IMPRESSION,this.onAdImpression),this.listenTo(this.ad,l.s.ADPLAYBACK_RESUMED,this.onAdResumed),this.listenTo(this.ad,l.s.ADPLAYBACK_PAUSED,this.onAdPaused),this.listenTo(this.ad,l.s.ADPLAYBACK_COMPLETE,this.onAdComplete),this.listenTo(this.ad,l.s.ADPLAYBACK_PROGRESS,this.onAdProgress),this.listenTo(this.ad,l.s.ADPLAYBACK_CLICK,this.onAdClick),this.listenTo(this.ad,l.s.ADPLAYBACK_WARNING,this.onAdWarning),this.listenToOnce(this.ad,l.s.ADPLAYBACK_ERROR,this.onAdError),this.listenToOnce(this.ad,l.s.ADPLAYBACK_CONTENT_RESUME_REQUESTED,this.onAdContentResumeRequested)),this.triggerAdEvent(l.s.ADVERTISEMENT_LOADING,e),null===(s=this.ad)||void 0===s||s.load(e)}onAdReady(){var e;null===(e=this.ad)||void 0===e||e.start()}onAdLoaded(e){var t,i;const{activePlayback:s,activeContainer:n}=this.core;n.isPlaying()&&n.pause(),o.Pw.isMobile&&s.consent();const r=s;null===(t=r._hls)||void 0===t||t.destroy(),delete r._hls,this.triggerAdEvent(l.s.ADVERTISEMENT_LOADED,e),this.$el.css("height",n.el.offsetHeight).show(),this.addFadeIn(),null===(i=this.mediaControl)||void 0===i||i.disable(),n.stopListening()}onAdStarted(e){this.playing=!0,this.trackViewability(),this.setInitialVolume(),this.triggerAdEvent(l.s.ADVERTISEMENT_STARTED,e),this.ad instanceof ln&&this.$clickArea.show()}onAdImpression(e){this.triggerAdEvent(l.s.ADVERTISEMENT_IMPRESSION,e)}onAdResumed(e){this.playing=!0,this.triggerAdEvent(l.s.ADVERTISEMENT_RESUMED,e)}onAdViewable(){var e;this.triggerAdEvent(l.s.ADVERTISEMENT_VIEWABLE,null===(e=this.ad)||void 0===e?void 0:e.sources),this.viewability=!0}onAdPaused(e){this.playing=!1,this.triggerAdEvent(l.s.ADVERTISEMENT_PAUSED,e)}onAdComplete(e){this.playing=!1,this.triggerAdEvent(l.s.ADVERTISEMENT_COMPLETE,e)}onAdProgress(e){var t;const{total:i=0}=e;this.triggerAdEvent(l.s.ADVERTISEMENT_PROGRESS,e),!(i<=0)&&this.ad instanceof ln&&(null===(t=this.ad)||void 0===t||t.controls)}setInitialVolume(){var e,t,i;const s=(null===(t=null===(e=this.ad)||void 0===e?void 0:e.options)||void 0===t?void 0:t.muted)?0:kn.VOLUME;null===(i=this.ad)||void 0===i||i.setVolume(s)}onAdClick(e){if(this.triggerAdEvent(l.s.ADVERTISEMENT_CLICK,e),!(this.ad instanceof ln))return;const{controls:t,isWOW:i,isClickable:s}=this.ad;if(!t&&!i||!s)return;const n=()=>{document.hidden||(this.playing||this.play(),document.removeEventListener("visibilitychange",n))};document.addEventListener("visibilitychange",n),this.pause()}onAdWarning(e){var t;null!==(t=e.raw)&&void 0!==t||(e.raw={}),e.raw.blockType=this.currentBlockType,e.raw.index=this.adSourcesIndex,e.raw.requestCount=this.adSourcesLoadsCount,this.trigger(l.s.ADVERTISEMENT_WARNING,e)}onAdError(e){var t,i,s,n;if(null!==(t=e.raw)&&void 0!==t||(e.raw={}),e.raw.blockType=this.currentBlockType,e.raw.index=this.adSourcesIndex,e.raw.requestCount=this.adSourcesLoadsCount,e.raw.adPlayback=null===(i=this.ad)||void 0===i?void 0:i.name,e.raw.adType=null===(s=this.ad)||void 0===s?void 0:s.getAdType(),this.trigger(l.s.ADVERTISEMENT_ERROR,e),this.adSourcesLoadsCount<2&&this.reloadFailedAdTag&&e.raw.canRefetch)return void this.requestAd(e.raw);this.adSourcesLoadsCount=0;const r=this.currentBlockType&&(null===(n=this.params[this.currentBlockType])||void 0===n?void 0:n.sources),o=Array.isArray(r)&&r.slice(this.adSourcesIndex);Array.isArray(o)&&(null==o?void 0:o[0])&&this._blockCompleteCountthis.requestResumeContent()),100)}onAdContentResumeRequested(e){this.triggerAdEvent(l.s.ADVERTISEMENT_ENDED,e),this.viewability||this.triggerAdEvent(l.s.ADVERTISEMENT_NOTVIEWABLE,e),this.requestResumeContent()}requestResumeContent(){var e,t,i,s,n,r,d,c,h,u,f;if(!this.currentBlockType)return;this.playing=!1,this.viewability=!1,clearTimeout(this.viewabilityTimeout),delete this.viewabilityTimeout;const p=this.currentBlockType&&(null===(e=this.params[this.currentBlockType])||void 0===e?void 0:e.sources),g=this.currentBlockType&&kn.PUID3[this.currentBlockType],m=this.ad instanceof ln&&(null===(t=this.ad)||void 0===t?void 0:t.sources)&&this.getNextAdBlockSources?this.getNextAdBlockSources(null===(i=this.ad)||void 0===i?void 0:i.sources,g):(null===(s=this.ad)||void 0===s?void 0:s.sources)&&Array.isArray(p)&&(null==p?void 0:p[this.adSourcesIndex]);if(this.allowBlock&&m&&++this._blockCompleteCount0&&(null===(e=this.core.activeContainer)||void 0===e||e.seek(this.currentContainerTime),this.currentContainerTime=0),null!=this.currentContainerVolume&&(null===(t=this.mediaControl)||void 0===t||t.setVolume(this.currentContainerVolume,!0),delete this.currentContainerVolume)}createBannerContainer(e){const t="YANDEX"===e.provider&&"none";return(0,o.$)("
").addClass("eagleplayer-advertisement-banner eplayer-skin-component eplayer-skin-fullsize eplayer-skin-shiftable").attr("data-banner","").css({pointerEvents:t}).hide()}onAdvertisementEnded(e){["banner","bannerMobile"].includes(e.blockType)||this.showBanner()}showBanner(){var e;this.currentBlockType||null===(e=this.$bannerContainer)||void 0===e||e.show()}hideBanner(){var e;null===(e=this.$bannerContainer)||void 0===e||e.hide()}startBanner(){var e,t;if(!this.enabled||this.$bannerContainer)return;const i=o.Pw.isMobile?null===(e=this.params.bannerMobile)||void 0===e?void 0:e.sources:null===(t=this.params.banner)||void 0===t?void 0:t.sources;Array.isArray(i)&&(null==i?void 0:i[0])&&this.requestBanner(i[0])}requestBanner(e){var t,i,s;const n=this.overlayPlaybacks.find((t=>t.canPlay(e)));if(this.bannerSourcesIndex++,!n){const t=this.createError({code:`${Vs.VAST_UNEXPECTED_AD_SOURCE}`,description:"no ad playback found for such sources",level:o.Mk.Levels.WARN,raw:Object.assign(Object.assign({},e),{code:Vs.VAST_UNEXPECTED_AD_SOURCE})});return void this.onBannerError(t)}this.destroyBanner();const{core:r}=this;this.$bannerContainer||(this.$bannerContainer=this.createBannerContainer(e),"universal"===(null===(t=this.options.mediaControl)||void 0===t?void 0:t.skinName)?null===(i=this.mediaControl)||void 0===i||i.$el.append(this.$bannerContainer.get(0)):r.$el.prepend(this.$bannerContainer.get(0)));const a={muted:(null==e?void 0:e.mute)||(null===(s=this.mediaControl)||void 0===s?void 0:s.muted),containerElement:this.$bannerContainer.get(0),get videoElement(){return r.activePlayback.el}};this.banner=new n(a,r),this.listenToOnce(this.banner,l.s.ADPLAYBACK_READY,this.onBannerReady),this.listenToOnce(this.banner,l.s.ADPLAYBACK_LOADED,this.onBannerLoaded),this.listenToOnce(this.banner,l.s.ADPLAYBACK_ERROR,this.onBannerError),this.listenTo(this.banner,l.s.ADPLAYBACK_USER_CLOSE,this.hideBanner),this.triggerBannerEvent(l.s.ADVERTISEMENT_LOADING,e),this.banner.load(e)}onBannerReady(){var e;null===(e=this.banner)||void 0===e||e.start()}onBannerLoaded(e){this.triggerBannerEvent(l.s.ADVERTISEMENT_LOADED,e),this.showBanner()}onBannerError(e){var t,i,s,n;const r=o.Pw.isMobile?"bannerMobile":"banner";null!==(t=e.raw)&&void 0!==t||(e.raw={}),e.raw.blockType=r,e.raw.index=this.bannerSourcesIndex,e.raw.requestCount=1,e.raw.adPlayback=null===(i=this.ad)||void 0===i?void 0:i.name,e.raw.adType=null===(s=this.banner)||void 0===s?void 0:s.getAdType(),this.trigger(l.s.ADVERTISEMENT_ERROR,e);const a=null===(n=this.params[r])||void 0===n?void 0:n.sources,d=Array.isArray(a)&&a.slice(this.bannerSourcesIndex);Array.isArray(d)&&(null==d?void 0:d[0])?this.requestBanner(d[0]):this.closeBanner()}closeBanner(){var e,t;(null===(e=this.$bannerContainer)||void 0===e?void 0:e.is(":visible"))&&(this.hideBanner(),this.triggerBannerEvent(l.s.ADVERTISEMENT_ENDED,null===(t=this.banner)||void 0===t?void 0:t.sources)),this.bannerSourcesIndex=0,this.lastBannerStartTime=0,this.destroyBanner(),delete this.params[o.Pw.isMobile?"bannerMobile":"banner"]}pause(){var e;null===(e=this.ad)||void 0===e||e.pause()}play(){var e;null===(e=this.ad)||void 0===e||e.resume()}hideControls(){this.$clickArea.hide().css("pointer-events",""),this.$el.find("iframe").css("opacity","")}addFadeIn(){var e,t;const i=null===(t=null===(e=this.ad)||void 0===e?void 0:e.sources)||void 0===t?void 0:t.provider;"YANDEX"!==i&&"ADFOX"!==i&&this.currentBlockType&&this.isPreRollWithStartTime(this.currentBlockType)&&(0,o.$)(".eagleplayer-advertisement").parent(".eagleplayer-container").addClass("fade")}render(){var e;if(!this.core.$el.parents().length||this.rendered)return this;const{playList:t}=this.core.options;return this.$el.html(this.template({preview:(null==t?void 0:t.snapshot)||"none",title:null!==(e=null==t?void 0:t.title)&&void 0!==e?e:"",duration:t?(0,d.V1)(t.duration):""})),this.$adContainer=this.$el.find("[data-ad-container]"),this.$clickArea=this.$el.find("[data-ad-click]"),this.$el.hide(),this.hideControls(),this.rendered=!0,this.core.$el.prepend(this.el),this}destroyAd(){this.ad&&(this.stopListening(this.ad,l.s.ADPLAYBACK_READY,this.onAdReady),this.stopListening(this.ad,l.s.ADPLAYBACK_LOADED,this.onAdLoaded),this.stopListening(this.ad,l.s.ADPLAYBACK_STARTED,this.onAdStarted),this.stopListening(this.ad,l.s.ADPLAYBACK_IMPRESSION,this.onAdImpression),this.stopListening(this.ad,l.s.ADPLAYBACK_RESUMED,this.onAdResumed),this.stopListening(this.ad,l.s.ADPLAYBACK_PAUSED,this.onAdPaused),this.stopListening(this.ad,l.s.ADPLAYBACK_COMPLETE,this.onAdComplete),this.stopListening(this.ad,l.s.ADPLAYBACK_PROGRESS,this.onAdProgress),this.stopListening(this.ad,l.s.ADPLAYBACK_CLICK,this.onAdClick),this.stopListening(this.ad,l.s.ADPLAYBACK_WARNING,this.onAdWarning),this.stopListening(this.ad,l.s.ADPLAYBACK_ERROR,this.onAdError),this.stopListening(this.ad,l.s.ADPLAYBACK_CONTENT_RESUME_REQUESTED,this.onAdContentResumeRequested),this.ad.destroy()),delete this.ad}destroyBanner(){this.banner&&(this.stopListening(this.banner,l.s.ADPLAYBACK_READY,this.onBannerReady),this.stopListening(this.banner,l.s.ADPLAYBACK_LOADED,this.onBannerLoaded),this.stopListening(this.banner,l.s.ADPLAYBACK_ERROR,this.onBannerError),this.stopListening(this.banner,l.s.ADPLAYBACK_USER_CLOSE,this.hideBanner),this.banner.destroy()),delete this.banner}stopListening(e,t,i){return i||clearTimeout(this.viewabilityTimeout),super.stopListening(e,t,i)}destroy(){var e;this.destroyAd(),this.destroyBanner(),this.inStreamPlaybacks.forEach((e=>e.destroy())),this.overlayPlaybacks.forEach((e=>e.destroy())),null===(e=this.$bannerContainer)||void 0===e||e.remove(),delete this.$bannerContainer,super.destroy()}}kn.VIEWABILITY_TIMEOUT=2e3,kn.MIN_VIEWABILITY_HEIGHT=.5,kn.PUID3={preRoll:6,preRollMobile:6,middleRoll:7,middleRollMobile:7,pauseRoll:void 0,pauseRollMobile:void 0,postRoll:15,postRollMobile:15,banner:void 0,bannerMobile:void 0,pauseBanner:void 0,pauseBannerMobile:void 0,pseudostreaming:7,pseudostreamingMobile:7},kn.BLOCK_TIME={preRoll:240,preRollMobile:240,middleRoll:900,middleRollMobile:900,postRoll:900,postRollMobile:900},kn.VOLUME=10,kn.loaded=!1,kn.lastPseudoStreamingStartTime=0},6682:(e,t,i)=>{"use strict";i.d(t,{E:()=>s});const s=(e,t={})=>{const{timeout:i}=t,s=function(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);ne.abort()),i)}return fetch(e,s)}},7007:e=>{"use strict";var t,i="object"==typeof Reflect?Reflect:null,s=i&&"function"==typeof i.apply?i.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};t=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function r(){r.init.call(this)}e.exports=r,e.exports.once=function(e,t){return new Promise((function(i,s){function n(i){e.removeListener(t,r),s(i)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",n),i([].slice.call(arguments))}g(e,t,r,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&g(e,"error",t,{once:!0})}(e,n)}))},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function l(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function d(e,t,i,s){var n,r,o,d;if(a(i),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),r=e._events),o=r[t]),void 0===o)o=r[t]=i,++e._eventsCount;else if("function"==typeof o?o=r[t]=s?[i,o]:[o,i]:s?o.unshift(i):o.push(i),(n=l(e))>0&&o.length>n&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,d=c,console&&console.warn&&console.warn(d)}return e}function c(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function h(e,t,i){var s={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},n=c.bind(s);return n.listener=i,s.wrapFn=n,n}function u(e,t,i){var s=e._events;if(void 0===s)return[];var n=s[t];return void 0===n?[]:"function"==typeof n?i?[n.listener||n]:[n]:i?function(e){for(var t=new Array(e.length),i=0;i0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var l=r[e];if(void 0===l)return!1;if("function"==typeof l)s(l,this,t);else{var d=l.length,c=p(l,d);for(i=0;i=0;r--)if(i[r]===t||i[r].listener===t){o=i[r].listener,n=r;break}if(n<0)return this;0===n?i.shift():function(e,t){for(;t+1=0;s--)this.removeListener(e,t[s]);return this},r.prototype.listeners=function(e){return u(this,e,!0)},r.prototype.rawListeners=function(e){return u(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},r.prototype.listenerCount=f,r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},7083:e=>{var t=1/0,i=/^\s+|\s+$/g,s=/^[-+]0x[0-9a-f]+$/i,n=/^0b[01]+$/i,r=/^0o[0-7]+$/i,o=parseInt,a=Object.prototype.toString;function l(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}e.exports=function(e){return function(e,d){var c;if("function"!=typeof d)throw new TypeError("Expected a function");return e=function(e){var d=function(e){return e?(e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==a.call(e)}(e))return NaN;if(l(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=l(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(i,"");var d=n.test(e);return d||r.test(e)?o(e.slice(2),d?2:8):s.test(e)?NaN:+e}(e))===t||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}(e),c=d%1;return d==d?c?d-c:d:0}(e),function(){return--e>0&&(c=d.apply(this,arguments)),e<=1&&(d=void 0),c}}(2,e)}},7166:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setScroll=s,t.getScroll=n,t.scrollToTop=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:200;return new Promise((function(o){var a=n(e),l=0;t=Math.max(t,0),function n(){var d=(l+=1/60)/(r/1e3),c=d;if(d<1){i(n);var h=Math.round(a+(t-a)*c);s(e,h)}else s(e,t),o()}()}))};var i=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(e){return setTimeout(e,1e3/60)};function s(e,t){e===document.body||e===document.documentElement?window.scrollTo(0,t):e.scrollTop=t}function n(e){return e===document.body||e===document.documentElement?document.body.scrollTop||document.documentElement.scrollTop:e.scrollTop}},7193:(e,t,i)=>{e=i.nmd(e);var s="__lodash_hash_undefined__",n=9007199254740991,r="[object Arguments]",o="[object Boolean]",a="[object Date]",l="[object Function]",d="[object GeneratorFunction]",c="[object Map]",h="[object Number]",u="[object Object]",f="[object Promise]",p="[object RegExp]",g="[object Set]",m="[object String]",v="[object Symbol]",A="[object WeakMap]",E="[object ArrayBuffer]",y="[object DataView]",T="[object Float32Array]",b="[object Float64Array]",S="[object Int8Array]",_="[object Int16Array]",C="[object Int32Array]",R="[object Uint8Array]",L="[object Uint8ClampedArray]",I="[object Uint16Array]",k="[object Uint32Array]",w=/\w*$/,P=/^\[object .+?Constructor\]$/,O=/^(?:0|[1-9]\d*)$/,D={};D[r]=D["[object Array]"]=D[E]=D[y]=D[o]=D[a]=D[T]=D[b]=D[S]=D[_]=D[C]=D[c]=D[h]=D[u]=D[p]=D[g]=D[m]=D[v]=D[R]=D[L]=D[I]=D[k]=!0,D["[object Error]"]=D[l]=D[A]=!1;var N="object"==typeof i.g&&i.g&&i.g.Object===Object&&i.g,M="object"==typeof self&&self&&self.Object===Object&&self,x=N||M||Function("return this")(),B=t&&!t.nodeType&&t,F=B&&e&&!e.nodeType&&e,U=F&&F.exports===B;function $(e,t){return e.set(t[0],t[1]),e}function V(e,t){return e.add(t),e}function G(e,t,i,s){var n=-1,r=e?e.length:0;for(s&&r&&(i=e[++n]);++n-1},Le.prototype.set=function(e,t){var i=this.__data__,s=Pe(i,e);return s<0?i.push([e,t]):i[s][1]=t,this},Ie.prototype.clear=function(){this.__data__={hash:new Re,map:new(pe||Le),string:new Re}},Ie.prototype.delete=function(e){return Me(this,e).delete(e)},Ie.prototype.get=function(e){return Me(this,e).get(e)},Ie.prototype.has=function(e){return Me(this,e).has(e)},Ie.prototype.set=function(e,t){return Me(this,e).set(e,t),this},ke.prototype.clear=function(){this.__data__=new Le},ke.prototype.delete=function(e){return this.__data__.delete(e)},ke.prototype.get=function(e){return this.__data__.get(e)},ke.prototype.has=function(e){return this.__data__.has(e)},ke.prototype.set=function(e,t){var i=this.__data__;if(i instanceof Le){var s=i.__data__;if(!pe||s.length<199)return s.push([e,t]),this;i=this.__data__=new Ie(s)}return i.set(e,t),this};var Be=ce?H(ce,Object):function(){return[]},Fe=function(e){return te.call(e)};function Ue(e,t){return!!(t=null==t?n:t)&&("number"==typeof e||O.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=n}(e.length)&&!Ye(e)}var He=he||function(){return!1};function Ye(e){var t=We(e)?te.call(e):"";return t==l||t==d}function We(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function ze(e){return Ke(e)?function(e,t){var i=je(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&Ke(e)}(e)&&ee.call(e,"callee")&&(!le.call(e,"callee")||te.call(e)==r)}(e)?function(e,t){for(var i=-1,s=Array(e);++i{"use strict";i.d(t,{D0:()=>g,EH:()=>c,Lt:()=>u,NB:()=>A,Q:()=>f,Uc:()=>h,VC:()=>T,WH:()=>m,XG:()=>v,_L:()=>l,bN:()=>p,t9:()=>d});var s=i(8952),n=i(9836),r=i(377);const o=["env","retention","service","app","deviceType","account"],a=["adPlayback","adType","adBlockType"],l=new s.Histogram({name:"player_loading_time",help:"Общее время загрузки плеера",buckets:[.1,.2,.3,.4,.5,.6,.7,1,2,5,10],labels:o}),d=new s.Histogram({name:"player_first_chunk_loading_time",help:"Время загрузки первого чанка",buckets:[.05,.1,.15,.2,.3,.4,.5,1,2,5,10],labels:[...o,"resolution"]}),c=new s.Histogram({name:"player_plugins_loading_time",help:"Время загрузки плагинов",buckets:[.05,.1,.15,.2,.3,.4,.5,1,2,5,10],labels:o}),h=new s.Histogram({name:"player_api_fetching_time",help:"Время запроса в API",buckets:[.05,.1,.15,.2,.3,.4,.5,1,2,5,10],labels:[...o,"endpoint"]}),u=new s.Counter({name:"player_buffering_delay",help:"Количество задержек буфферизации чанков более 500ms",labels:[...o,"resolution"]}),f=new s.Counter({name:"player_auto_play_error",help:"Количество ошибок автоплея (автоплей был включен, но не стартовал)",labels:[...o,"reason"]}),p=new s.Counter({name:"player_loading_error",help:"Количество ошибок при старте видео",labels:[...o,"errorCode"]}),g=new s.Counter({name:"player_ad_request",help:"Количество запросов рекламы",labels:[...o,...a]}),m=new s.Counter({name:"player_ad_start_error",help:"Количество ошибок при старте рекламы (реклама загрузилась, но не стартовала)",labels:[...o,...a,"adSystem","errorCode"]}),v=new s.Counter({name:"player_ad_viewability",help:"Видимость рекламы",labels:[...o,...a,"adSystem","visible"]}),A=e=>s.defaultRegistry.setDefaultLabels(e),E=new s.PushGateway({url:"https://atlas.rambler.ru/metrics",fetchOptions:{keepalive:!0,headers:{"X-Atlas-Ath":"Basic cm9vdDpva2FpWWlraWVnaDBhb3ZvbzVhaA=="}}});let y="";const T=async()=>{const e=s.defaultRegistry.expose();e!==y&&(y=e,(0,r._o)()&&n.t.debug("prometheus",e),(0,r.yz)()||(await E.push(),Object.values(s.defaultRegistry.collectors).forEach((e=>e.reset()))))}},7439:(e,t,i)=>{"use strict";i.d(t,{A:()=>a});var s=i(1354),n=i.n(s),r=i(6314),o=i.n(r)()(n());o.push([e.id,"[data-html5-video]{position:absolute;height:100%;width:100%;display:block}","",{version:3,sources:["webpack://./node_modules/@clappr/core/src/playbacks/html5_video/public/style.scss"],names:[],mappings:"AAAA,mBACE,iBAAA,CACA,WAAA,CACA,UAAA,CACA,aAAA",sourcesContent:["[data-html5-video] {\n position: absolute;\n height: 100%;\n width: 100%;\n display: block;\n}\n"],sourceRoot:""}]),o.locals={};const a=o},7546:(e,t,i)=>{"use strict";i.d(t,{QS:()=>n,Q_:()=>s,fx:()=>o});const s=Boolean(navigator.userAgent.match(new RegExp(`(${["googlebot/","Googlebot-Mobile","Googlebot-Image","Google favicon","Mediapartners-Google","bingbot","slurp","java","wget","curl","Commons-HttpClient","Python-urllib","libwww","httpunit","nutch","phpcrawl","msnbot","jyxobot","FAST-WebCrawler","FAST Enterprise Crawler","biglotron","teoma","convera","seekbot","gigablast","exabot","ngbot","ia_archiver","GingerCrawler","webmon","httrack","webcrawler","grub.org","UsineNouvelleCrawler","antibot","netresearchserver","speedy","fluffy","bibnum.bnf","findlink","msrbot","panscient","yacybot","AISearchBot","IOI","ips-agent","tagoobot","MJ12bot","dotbot","woriobot","yanga","buzzbot","mlbot","yandexbot","purebot","Linguee Bot","Voyager","CyberPatrol","voilabot","baiduspider","citeseerxbot","spbot","twengabot","postrank","turnitinbot","scribdbot","page2rss","sitebot","linkdex","Adidxbot","blekkobot","ezooms","dotbot","Mail.RU_Bot","discobot","heritrix","findthatfile","europarchive.org","NerdByNature.Bot","sistrix crawler","ahrefsbot","Aboundex","domaincrawle","wbsearchbot","summify","ccbot","edisterbot","seznambot","ec2linkfinder","gslfbot","aihitbot","intelium_bot","facebookexternalhit","yeti","RetrevoPageAnalyzer","lb-spider","sogou","lssbot","careerbot","wotbox","wocbot","ichiro","DuckDuckBot","lssrocketcrawler","drupact","webcompanycrawler","acoonbot","openindexspider","gnam gnam spider","web-archive-net.com.bot","backlinkcrawler","coccoc","integromedb","content crawler spider","toplistbot","seokicks-robot","it2media-domain-crawler","ip-web-crawler.com","siteexplorer.info","elisabot","proximic","changedetection","blexbot","arabot","WeSEE:Search","niki-bot","CrystalSemanticsBot","rogerbot","360Spider","psbot","InterfaxScanBot","Lipperhey SEO Service","CC Metadata Scaper","g00g1e.net","GrapeshotCrawler","urlappendbot","brainobot","fr-crawler","binlar","SimpleCrawler","Livelapbot","Twitterbot","cXensebot","smtbot","bnf.fr_bot","A6-Indexer","ADmantX","Facebot","Twitterbot","OrangeBot","memorybot","AdvBot","MegaIndex","SemanticScholarBot","ltx71","nerdybot","xovibot","BUbiNG","Qwantify","archive.org_bot","Applebot","TweetmemeBot","crawler4j","findxbot","SemrushBot","yoozBot","lipperhey","y!j-asr","Domain Re-Animator Bot","AddThis"].join("|")})`,"i"))),n="requestStorageAccess"in document&&"function"==typeof document.requestStorageAccess,r=["RVPCompat\\w+/[0-9.]+","Gazeta.Ru \\w+ Application"],o=()=>{const e=new RegExp(`(${r.join("|")})`,"i");return navigator.userAgent.match(e)?"webview":"browser"}},7659:e=>{"use strict";var t={};e.exports=function(e,i){var s=function(e){if(void 0===t[e]){var i=document.querySelector(e);if(window.HTMLIFrameElement&&i instanceof window.HTMLIFrameElement)try{i=i.contentDocument.head}catch(e){i=null}t[e]=i}return t[e]}(e);if(!s)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");s.appendChild(i)}},7825:e=>{"use strict";e.exports=function(e){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var t=e.insertStyleElement(e);return{update:function(i){!function(e,t,i){var s="";i.supports&&(s+="@supports (".concat(i.supports,") {")),i.media&&(s+="@media ".concat(i.media," {"));var n=void 0!==i.layer;n&&(s+="@layer".concat(i.layer.length>0?" ".concat(i.layer):""," {")),s+=i.css,n&&(s+="}"),i.media&&(s+="}"),i.supports&&(s+="}");var r=i.sourceMap;r&&"undefined"!=typeof btoa&&(s+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(r))))," */")),t.styleTagTransform(s,e,t.options)}(t,e,i)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}},8009:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t{"use strict";i.d(t,{$D:()=>f,DU:()=>p,Hn:()=>a,I:()=>c,_3:()=>h,o2:()=>u,zs:()=>g});var s=i(2136),n=i(6413),r=i(7204),o=i(6682);const a={ru:0,en:1,es:2,fr:3,de:4,ja:5,it:6,ko:7,zh:8,pt:9,other:10},l="https://api.vp.rambler.ru",d="/api/v3",c={UNKNOWN_ERROR:{code:"unknown_error",message:"unknown error"},RECORD_NOT_FOUND:{code:"video_not_found",message:"video not found"},RECORD_NOT_PUBLISHED:{code:"video_publish_finish",message:"publishing of video finished"},RECORD_NOT_PROCESSED:{code:"video_processing",message:"video is now processing"},RECORD_ACCESS_DENIED_SITE:{code:"access_denied",message:"access to this video is denied in your country or on this website"},RECORD_ACCESS_DENIED_COUNTRY:{code:"geo_access_denied",message:"video you requested cannot be played in your country"},TRANSLATION_NOT_FOUND:{code:"video_not_found",message:"video not found"},TRANSLATION_ACCESS_DENIED_SITE:{code:"access_denied",message:"access to this video is denied in your country or on this website"},TRANSLATION_ACCESS_DENIED_COUNTRY:{code:"geo_access_denied",message:"video you requested cannot be played in your country"},ACCESS_RESTRICTED:{code:"access_restricted",message:"you cannot watch this video"},NO_BROADCAST:{code:"no_broadcast",message:"no broadcast"},NO_SIGNAL:{code:"no_signal",message:"no signal"},NO_STREAM:{code:"no_stream",message:"no stream"},LIVE_FINISHED:{code:"live_finished",message:"live finished"},NO_CONNECTION:{code:"no_connection",message:"no connection"},ANNOUNCE:{code:"announce",message:""},TIMEOUT:{code:"timeout",message:"operation was aborted by timeout"},NOT_RESPOND:{code:"not_respond",message:"api does not respond"},INVALID_RESPONSE:{code:"invalid_response",message:"invalid response"},CACHE_NOT_READY:{code:"cache not ready",message:"cache not ready"}},h=async e=>{var t;const i={params:{referrer:e.referrer,accountCode:e.channel}},a=r.Uc.startTimer({endpoint:"/settings/getPlayerSettingsByAccount"});let h;try{const e=`${l}${d}/settings/getPlayerSettingsByAccount`,t=await(0,o.E)(e,{method:"post",credentials:"same-origin",timeout:1e4,body:JSON.stringify(i)});h=await t.json()}catch(e){if((0,n.Cp)(e,i),"AbortError"===e.name)throw new s.hD(c.TIMEOUT);throw new s.hD(c.NOT_RESPOND)}finally{a.observeDuration()}if((!h.success||!h.result)&&h.error){const{type:e,subtype:r,extra:o}=h.error,a=[e,r,o].filter(Boolean).join("_"),l=new s.hD(null!==(t=c[a])&&void 0!==t?t:c.UNKNOWN_ERROR);throw c[a]||(0,n.Cp)(l,Object.assign({},i)),l}if(!h.result){const e=new s.hD(c.INVALID_RESPONSE);throw(0,n.Cp)(e,i),e}return h.result},u=async e=>{var t;const{sessionId:i,channel:a,withCredentials:h}=e,u=!!i&&!!a,f=(({id:e,adTemplateId:t,playerTemplateId:i,multiplayerFilterId:s,suggestFilterId:n,pauseSuggestFilterId:r,suggestMobileFilterId:o,pauseSuggestMobileFilterId:a,referrer:l,sessionId:d,channel:c,checkReferrerCount:h},u)=>{const f={params:{referrer:l}};return"string"==typeof e?f.params.uuid=e:f.params.id=e,null!=t&&(f.params.adTemplateId=t),null!=i&&(f.params.playerTemplateId=i),null!=s&&(f.params.multiplayerFilterId=s),null!=n&&(f.params.suggestFilterId=n),null!=r&&(f.params.pauseSuggestFilterId=r),null!=o&&(f.params.suggestMobileFilterId=o),null!=a&&(f.params.pauseSuggestMobileFilterId=a),u&&(f.sessionId=d,f.params.account=c),h&&(f.params.checkReferrerCount=h),f})(e,u),p=(({id:e,live:t},i)=>{let s;return s=t?"string"==typeof e?"livestreams":"translations":"records",`/${s}/${i?"previewPlayerData":"getPlayerData"}`})(e,u),g=r.Uc.startTimer({endpoint:p});let m;try{let e=`${l}${d}${p}`;u||(e+=`?params=${encodeURIComponent(JSON.stringify(f.params))}`);const t=await(0,o.E)(e,Object.assign({method:u?"post":"get",credentials:h?"include":"same-origin",timeout:1e4},u&&{body:JSON.stringify(f)}));m=await t.json()}catch(e){throw(0,n.Cp)(e,f),new s.hD("AbortError"===e.name?c.TIMEOUT:c.NOT_RESPOND)}finally{g.observeDuration()}if((!m.success||!m.result)&&m.error){const{type:e,subtype:i,extra:r}=m.error,o=[e,i,r].filter(Boolean).join("_"),a=new s.hD(null!==(t=c[o])&&void 0!==t?t:c.UNKNOWN_ERROR);throw c[o]||(0,n.Cp)(a,Object.assign(Object.assign({},f),{type:e,subtype:i,extra:r})),a}if(!m.result){const e=new s.hD(c.INVALID_RESPONSE);throw(0,n.Cp)(e,f),e}return m.result},f=async e=>{try{const t=await(0,o.E)(e,{timeout:1e4});return await t.text()}catch(t){throw(0,n.Cp)(t,{url:e}),t}},p=async e=>{const t=`${l}${d}/subtitles/get`;try{const i=await(0,o.E)(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({params:e}),timeout:1e4}),n=await i.json();if(!n.result)throw new s.hD(c.INVALID_RESPONSE);return n.result}catch(i){throw(0,n.Cp)(i,{url:t,params:e}),i}},g=async e=>{const t=`${l}${d}/livestreams/getStatus`,i={id:e};try{const e=await(0,o.E)(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({params:i}),timeout:1e4}),n=await e.json();if(!n.result)throw new s.hD(c.INVALID_RESPONSE);return n.result}catch(e){throw(0,n.Cp)(e,{url:t,params:i}),e}}},8132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var s=i(2039);Object.defineProperty(t,"Provider",{enumerable:!0,get:function(){return r(s).default}});var n=i(6105);function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"Consumer",{enumerable:!0,get:function(){return r(n).default}})},8135:e=>{e.exports=""},8220:e=>{"use strict";e.exports=function(e){var t,i=null,s=function(){for(var s=arguments.length,n=new Array(s),r=0;r{"use strict";var s=i(8997);function n(e){for(var t=e.split("."),i=[],s=0;s{"use strict";i.r(t),i.d(t,{Mediascope:()=>d,Plugin:()=>d});var s=i(7083),n=i.n(s),r=i(9371),o=i(6121),a=i(7546),l=i(1162);class d extends r.rV{constructor(){super(...arguments),this.started=!1,this.stopped=!1,this.seekStarted=!1,this.adStarted=!1,this.adPaused=!1,this.currentGlobalLiveTime=0,this.currentLiveTime=0,this.onPageLeave=()=>{const{activeContainer:e}=this.core;!this.stopped&&this.getFTS()>0&&(this.stopListening(e,o.s.CONTAINER_TIMEUPDATE,this.onTimeUpdate),this.onStop()),this.adStarted&&this.onAdStop()}}get name(){return"mediascope"}get supportedVersion(){return{min:"0.5.0"}}get isLive(){var e;return this.core.options.live||(null===(e=this.core.activePlayback)||void 0===e?void 0:e.getPlaybackType())===r.YZ.LIVE}get provider(){return this.options.provider}get mediaControl(){return this.core.getPlugin("mediaControl")}get multiPlayer(){return this.core.getPlugin("multiplayer")}get suggest(){return this.core.getPlugin("suggest")}get watchNext(){return this.core.getPlugin("watchNext")}get advertisement(){return this.core.getPlugin("advertisement")}getFTS(){var e;const{activeContainer:t}=this.core,i=null!==(e=null==t?void 0:t.getCurrentTime())&&void 0!==e?e:0;return this.isLive?this.currentLiveTime:parseInt((1e3*i).toFixed())}sendMediascopeEvent(e,t=!1){var i,s;const{playList:n,channel:r,referrer:o}=this.core.options,a=null!==(i=null==n?void 0:n.uuid)&&void 0!==i?i:null==n?void 0:n.id;if(!a)return;const c="string"==typeof a?"uuid":"id",h={view:e,fts:t?this.getCurrentAdTime():this.getFTS(),cu_url:this.isLive?null!=o?o:"":`https://api.vp.rambler.ru/api/other/player/mediascope_export.html?${c}=${a}`,channel:`${null!=r?r:l.n4}`,referrer:null!=o?o:"",playerVersion:"1.147.1",cu_id:t?`adv_${a}`:a,live:this.isLive};null===(s=this.provider)||void 0===s||s.sendCustomVars(d.TOP100_ID,h)}setHeartbeatAdInterval(){var e;null!==(e=this.heartbeatAdInterval)&&void 0!==e||(this.heartbeatAdInterval=window.setInterval((()=>this.onAdHeartbeat()),d.HEARTBEAT_INTERVAL))}cleanHeartbeatAdInterval(){window.clearInterval(this.heartbeatAdInterval),delete this.heartbeatAdInterval}setHeartbeatInterval(){var e;null!==(e=this.heartbeatInterval)&&void 0!==e||(this.heartbeatInterval=window.setInterval((()=>this.heartbeat()),d.HEARTBEAT_INTERVAL))}cleanHeartbeatInterval(){window.clearInterval(this.heartbeatInterval),delete this.heartbeatInterval}onSeekInteractionEnd(){this.seekStarted=!1}onSeekInteractionStart(){var e;this.seekStarted=!0,(null===(e=this.core.activeContainer)||void 0===e?void 0:e.isPlaying())&&this.onStop()}getCurrentAdTime(){var e,t;return parseInt((1e3*(null!==(t=null===(e=this.advertisement)||void 0===e?void 0:e.currentTime)&&void 0!==t?t:0)).toFixed())}onAdStarted(){this.adStarted=!0,this.onPause(),this.onAdStart()}onAdStop(){this.cleanHeartbeatAdInterval(),this.sendMediascopeEvent(0,!0)}onAdPaused(){this.adPaused||(this.cleanHeartbeatAdInterval(),this.sendMediascopeEvent(3,!0),this.adPaused=!0)}onAdHeartbeat(){this.sendMediascopeEvent(2,!0)}onAdProgress(e){e.current>0&&this.adPaused&&(this.onAdStart(),this.adPaused=!1)}onAdStart(){this.sendMediascopeEvent(1,!0),this.setHeartbeatAdInterval()}onAdError(){this.adStarted&&(this.cleanHeartbeatAdInterval(),this.onAdStop())}onError(){var e;this.isLive&&this.getFTS()>0&&(null===(e=this.core.activeContainer)||void 0===e?void 0:e.isPlaying())&&!this.stopped&&this.onStop()}onStop(){this.cleanHeartbeatInterval(),this.started=!1,this.stopped=!0,this.sendMediascopeEvent(0)}onStart(){this.stopped=!1,this.setHeartbeatInterval(),this.sendMediascopeEvent(1)}heartbeat(){this.sendMediascopeEvent(2)}onPause(){const{activeContainer:e}=this.core;if(0!==this.getFTS()&&this.started){if(this.stopped=!1,e.ended)return void(this.started=!1);this.cleanHeartbeatInterval(),this.started=!1,this.sendMediascopeEvent(3)}}onPlay(){this.adStarted&&(this.adStarted=!1)}onTimeUpdate(){var e;const t=null===(e=this.core.activeContainer)||void 0===e?void 0:e.isPlaying();if(t&&this.isLive){const e=Date.now(),t=this.currentGlobalLiveTime||e;this.currentGlobalLiveTime=e,this.currentLiveTime+=this.currentGlobalLiveTime-t}this.seekStarted||t&&this.adStarted||t&&!this.started&&0!==this.getFTS()&&(this.onStart(),this.started=!0)}bindEvents(){const{activeContainer:e}=this.core;this.core.isReady||(this.onReady=n()(this.onReady)),this.listenToOnce(this.core,o.s.CORE_READY,this.onReady),this.listenTo(this.core,o.s.CORE_ACTIVE_CONTAINER_CHANGED,this.onActiveContainerChange),window.addEventListener("beforeunload",this.onPageLeave),e&&(this.listenTo(e,o.s.CONTAINER_TIMEUPDATE,this.onTimeUpdate),this.listenTo(e,o.s.CONTAINER_PAUSE,this.onPause),this.listenTo(e,o.s.CONTAINER_ENDED,this.onStop),this.listenTo(e,o.s.CONTAINER_PLAY,this.onPlay),this.listenTo(e,o.s.CONTAINER_ERROR,this.onError)),this.mediaControl&&(this.listenTo(this.mediaControl,o.s.MEDIACONTROL_SEEK_START,this.onSeekInteractionStart),this.listenTo(this.mediaControl,o.s.MEDIACONTROL_SEEK_END,this.onSeekInteractionEnd)),this.advertisement&&(this.listenTo(this.advertisement,o.s.ADVERTISEMENT_STARTED,this.onAdStarted),this.listenTo(this.advertisement,o.s.ADVERTISEMENT_ENDED,this.onAdStop),this.listenTo(this.advertisement,o.s.ADVERTISEMENT_PAUSED,this.onAdPaused),this.listenTo(this.advertisement,o.s.ADVERTISEMENT_PROGRESS,this.onAdProgress),this.listenTo(this.advertisement,o.s.ADVERTISEMENT_ERROR,this.onAdError)),this.multiPlayer&&this.listenTo(this.multiPlayer,o.s.MULTIPLAYER_SUGGEST_CLICK,this.onStop),this.suggest&&this.listenTo(this.suggest,o.s.SUGGEST_CLICK,this.onStop),this.watchNext&&(this.listenTo(this.watchNext,o.s.WATCH_NEXT_CLICK,this.onStop),this.listenTo(this.mediaControl,o.s.WATCH_NEXT_CLICK,this.onStop))}stopListening(e,t,i){return i||(window.removeEventListener("beforeunload",this.onPageLeave),this.cleanHeartbeatInterval(),this.cleanHeartbeatAdInterval()),super.stopListening(e,t,i)}onActiveContainerChange(){this.stopListening(),this.bindEvents()}onReady(){var e;if(!d.ready){const t=(0,a.fx)();null===(e=this.provider)||void 0===e||e.activateTop100({project:d.TOP100_ID,splits:[`env_${t}`]}),d.ready=!0}}}d.HEARTBEAT_INTERVAL=3e4,d.TOP100_ID="7643964",d.ready=!1},8644:(e,t,i)=>{"use strict";i.d(t,{HD:()=>l,Rv:()=>o,dA:()=>a});var s=i(997);const n=e=>{const t=(e=>{if(4!==e.length)return e;let t="#";for(let i=1;i{if("#"===e.charAt(0))return r((e=>{const[t,i,s]=n(e);return`rgb(${t}, ${i}, ${s})`})(e));const t=e.replace(/\s/g,""),i=t.indexOf("(");if(-1===i)throw new Error(`The ${t} color was not parsed correctly,\n because it has an unsupported format (color name or RGB %). This may cause issues in component rendering.`);return{type:t.substring(0,i),values:t.substring(i+1,t.length-1).split(",").map((e=>parseFloat(e)))}},o=(e,t)=>{const i=r(e);return"rgb"!==i.type&&"hsl"!==i.type||(i.type+="a"),i.values[3]=(e=>e<0?0:e>1?1:e)(t),(e=>{const{type:t}=e,i=e.values.map(((e,t)=>"number"==typeof e?e:t<3?parseInt(e,10):parseFloat(e)));let s;return s=t.indexOf("hsl")>-1?`${t}(${i[0]}, ${i[1]}%, ${i[2]}%`:`${t}(${i[0]}, ${i[1]}, ${i[2]}`,4===i.length?s+=`, ${i[3].toFixed(2)})`:s+=")",s})(i)},a=e=>{const t=e.toString(16);return"#"===t.charAt(0)?t:`#${(0,s.Ro)(t,"0",6)}`},l=e=>{const t=n(e);return(2126*t[0]+7152*t[1]+722*t[2])/1e4<128}},8814:(e,t,i)=>{"use strict";i.d(t,{A:()=>a});var s=i(1354),n=i.n(s),r=i(6314),o=i.n(r)()(n());o.push([e.id,"[data-no-op]{position:absolute;height:100%;width:100%;text-align:center}[data-no-op] p[data-no-op-msg]{position:absolute;text-align:center;font-size:25px;left:0;right:0;color:#fff;padding:10px;top:50%;transform:translateY(-50%);max-height:100%;overflow:auto}[data-no-op] canvas[data-no-op-canvas]{background-color:#777;height:100%;width:100%}","",{version:3,sources:["webpack://./node_modules/@clappr/core/src/playbacks/no_op/public/style.scss"],names:[],mappings:"AAAA,aACE,iBAAA,CACA,WAAA,CACA,UAAA,CACA,iBAAA,CAGF,+BACE,iBAAA,CACA,iBAAA,CACA,cAAA,CACA,MAAA,CACA,OAAA,CACA,UAAA,CACA,YAAA,CAEA,OAAA,CACA,0BAAA,CACA,eAAA,CACA,aAAA,CAGF,uCACE,qBAAA,CACA,WAAA,CACA,UAAA",sourcesContent:["[data-no-op] {\n position: absolute;\n height: 100%;\n width: 100%;\n text-align: center;\n}\n\n[data-no-op] p[data-no-op-msg] {\n position: absolute;\n text-align: center;\n font-size: 25px;\n left: 0;\n right: 0;\n color: white;\n padding: 10px;\n /* center vertically */\n top: 50%;\n transform: translateY(-50%);\n max-height: 100%;\n overflow: auto;\n}\n\n[data-no-op] canvas[data-no-op-canvas] {\n background-color: #777;\n height: 100%;\n width: 100%;\n}\n"],sourceRoot:""}]),o.locals={};const a=o},8952:function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0}),n(i(3271),t),n(i(234),t),n(i(9716),t),n(i(2737),t),n(i(5842),t),n(i(2717),t),n(i(9712),t),n(i(4975),t)},8997:e=>{"use strict";e.exports=function(e){var t=typeof e;return null!==e&&("object"===t||"function"===t)}},9200:(e,t,i)=>{"use strict";i.d(t,{QT:()=>o,gM:()=>n,qg:()=>l,yN:()=>r});var s=i(2633);const n=Symbol("playInVisibleArea"),r=Symbol("unmuteInVisibleArea"),o=Symbol("playInVisiblePage"),a=e=>{switch(e){case"left-down":case"left-up":case"right-down":case"right-up":return e;default:return}},l=e=>{const t={id:(0,s.x)(e.id),initialId:(0,s.x)(e.initialId)};e.adTemplateId&&(t.adTemplateId=Number(e.adTemplateId)),e.playerTemplateId&&(t.playerTemplateId=Number(e.playerTemplateId)),e.multiplayerFilterId&&(t.multiplayerFilterId=Number(e.multiplayerFilterId)),e.suggestFilterId&&(t.suggestFilterId=Number(e.suggestFilterId)),e.pauseSuggestFilterId&&(t.pauseSuggestFilterId=Number(e.pauseSuggestFilterId)),e.suggestMobileFilterId&&(t.suggestMobileFilterId=Number(e.suggestMobileFilterId)),e.pauseSuggestMobileFilterId&&(t.pauseSuggestMobileFilterId=Number(e.pauseSuggestMobileFilterId)),e.suggestFilterShuffle&&(t.suggestFilterShuffle="false"!==e.suggestFilterShuffle),e.pauseSuggestFilterShuffle&&(t.pauseSuggestFilterShuffle="false"!==e.pauseSuggestFilterShuffle),e.showSuggestNames&&(t.showSuggestNames="false"!==e.showSuggestNames),e.live&&(t.live="false"!==e.live),e.withCredentials&&(t.withCredentials="false"!==e.withCredentials),e.preload&&(t.preload="false"!==e.preload),e.autoPlay&&(t[n]="scroll"===e.autoPlay,t[r]="scroll_mute"===e.autoPlay,t.autoPlay="true"===e.autoPlay),e.mute&&(t.mute="false"!==e.mute),e.volume&&(t.volume=Number(e.volume)),e.startPosition&&(t.startPosition=Number(e.startPosition));const{docking:i}=e;if(null!=i){let e="boolean"==typeof i?i:(e=>{switch(e){case"middle-down":case"middle-up":return e;default:return a(e)}})(i);null==e&&("false"===i?e=!1:"true"===i&&(e=!0)),t.docking=e}return e.dockingWidth&&(t.dockingWidth=Number(e.dockingWidth)),e.dockingOffset&&(t.dockingOffset=Number(e.dockingOffset)),e.dockingOffsetX&&(t.dockingOffsetX=Number(e.dockingOffsetX)),e.dockingOffsetY&&(t.dockingOffsetY=Number(e.dockingOffsetY)),e.dockingParentId&&(t.dockingParentId=e.dockingParentId),e.dockingDirection&&(t.dockingDirection=e.dockingDirection),e.dockingCloseDelay&&(t.dockingCloseDelay=Number(e.dockingCloseDelay)),e.aspectRatio&&(t.aspectRatio=Number(e.aspectRatio)),e.replay&&(t.replay="false"!==e.replay),e.replayTimeout&&(t.replayTimeout=Number(e.replayTimeout)),e.mediaControlVisible&&(t.mediaControlVisible="false"!==e.mediaControlVisible),e.playbackRate&&(t.playbackRate="false"!==e.playbackRate),e.unmute&&(t.unmute="false"!==e.unmute),e.showTitle&&(t.showTitle="false"!==e.showTitle),e.clickOnTitle&&(t.clickOnTitle="false"!==e.clickOnTitle),e.volumeVisible&&(t.volumeVisible="false"!==e.volumeVisible),e.viewerVisible&&(t.viewerVisible="false"!==e.viewerVisible),e.qualityVisible&&(t.qualityVisible="false"!==e.qualityVisible),e.fullscreenVisible&&(t.fullscreenVisible="false"!==e.fullscreenVisible),e.seekBarVisible&&(t.seekBarVisible="false"!==e.seekBarVisible),e.debug&&(t.debug="false"!==e.debug),e.sspJparams&&(t.sspJparams="string"==typeof e.sspJparams?JSON.parse(e.sspJparams):e.sspJparams),e.sspUserId&&(t.sspUserId=e.sspUserId),e.sspUserIdScope&&(t.sspUserIdScope=e.sspUserIdScope),e.referrer&&(t.referrer=e.referrer),e.authToken&&(t.authToken=e.authToken),e.authTokenVerifyUrl&&(t.authTokenVerifyUrl=e.authTokenVerifyUrl),"watermark"in e&&(t.watermark=e.watermark),e.watermarkPosition&&(t.watermarkPosition=a(e.watermarkPosition)),"likes"in e&&(t.likes="false"!==e.likes),"promoButtonImage"in e&&(t.promoButtonImage=e.promoButtonImage),"promoButtonClickUrl"in e&&(t.promoButtonClickUrl=e.promoButtonClickUrl),e.promoButtonPosition&&(t.promoButtonPosition=a(e.promoButtonPosition)),"promoButtonSize"in e&&(t.promoButtonSize=e.promoButtonSize),e.poster&&(t.poster=e.poster),e.minPlayingVisibleHeight&&(t.minPlayingVisibleHeight=Number(e.minPlayingVisibleHeight)),e.enforceStartWhenPlayingInParent&&(t.enforceStartWhenPlayingInParent="false"!==e.enforceStartWhenPlayingInParent),e.userId&&(t.userId=e.userId),e.sessionId&&(t.sessionId="false"!==e.sessionId),e.channel&&(t.channel=e.channel),e.height&&(t.height=Number(e.height)),e.shareEmbedCodes&&(t.shareEmbedCodes="false"!==e.shareEmbedCodes),e.shareSocialNetworks&&(t.shareSocialNetworks="false"!==e.shareSocialNetworks),e.multiplayerHidden&&(t.multiplayerHidden="false"!==e.multiplayerHidden),e.watchNext&&(t.watchNext="false"!==e.watchNext),e.threeSixtyViewer&&(t.threeSixtyViewer="false"!==e.threeSixtyViewer),e.multiplayerShuffle&&(t.multiplayerShuffle="false"!==e.multiplayerShuffle),"multiplayerTextColor"in e&&(t.multiplayerTextColor=e.multiplayerTextColor),"multiplayerColor"in e&&(t.multiplayerColor=e.multiplayerColor),"multiplayerBackgroundColor"in e&&(t.multiplayerBackgroundColor=e.multiplayerBackgroundColor),"multiplayerFontUrl"in e&&(t.multiplayerFontUrl=e.multiplayerFontUrl),e.mediaControlSkinName&&(t.mediaControlSkinName=e.mediaControlSkinName),"mediaControlTextColor"in e&&(t.mediaControlTextColor=e.mediaControlTextColor),"mediaControlHoverColor"in e&&(t.mediaControlHoverColor=e.mediaControlHoverColor),"mediaControlForegroundColor"in e&&(t.mediaControlForegroundColor=e.mediaControlForegroundColor),"mediaControlBackgroundColor"in e&&(t.mediaControlBackgroundColor=e.mediaControlBackgroundColor),"mediaControlFontUrl"in e&&(t.mediaControlFontUrl=e.mediaControlFontUrl),"amp"in e&&(t.amp=!0),"widgetId"in e&&(t.widgetId=e.widgetId),e.redirectToSuggestOnClick&&(t.redirectToSuggestOnClick="false"!==e.redirectToSuggestOnClick),e.videoBackdropColor&&(t.videoBackdropColor=e.videoBackdropColor),e.aiAd&&(t.aiAd="false"!==e.aiAd),e.yandexMetrikaVideoType&&(t.yandexMetrikaVideoType=e.yandexMetrikaVideoType),"false"===e.multiplayer&&(t.multiplayer=!1),"false"===e.suggest&&(t.suggest=!1),e.saveUserVolume&&(t.saveUserVolume="false"!==e.saveUserVolume),"false"===e.eventsReportLive&&(t.eventsReportLive=!1),"minDurationToShowAd"in e&&(t.minDurationToShowAd=Number(e.minDurationToShowAd)),t}},9275:e=>{e.exports=""},9371:(e,t,i)=>{"use strict";i.d(t,{$:()=>r(),bI:()=>V,Pw:()=>u,o2:()=>Re,df:()=>z,iJ:()=>Pe,Ut:()=>Oe,rV:()=>q,yF:()=>Y,sV:()=>U,ab:()=>Ke,aH:()=>xe,tG:()=>N,YZ:()=>W,Mk:()=>K,WM:()=>de,rt:()=>Q,DI:()=>X,Aq:()=>I,vs:()=>ae});const s={mp4:"data:video/mp4;base64,AAAAHGZ0eXBpc29tAAACAGlzb21pc28ybXA0MQAAAAhmcmVlAAAC721kYXQhEAUgpBv/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3pwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcCEQBSCkG//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADengAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAAsJtb292AAAAbG12aGQAAAAAAAAAAAAAAAAAAAPoAAAALwABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAB7HRyYWsAAABcdGtoZAAAAAMAAAAAAAAAAAAAAAIAAAAAAAAALwAAAAAAAAAAAAAAAQEAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAAC8AAAAAAAEAAAAAAWRtZGlhAAAAIG1kaGQAAAAAAAAAAAAAAAAAAKxEAAAIAFXEAAAAAAAtaGRscgAAAAAAAAAAc291bgAAAAAAAAAAAAAAAFNvdW5kSGFuZGxlcgAAAAEPbWluZgAAABBzbWhkAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAADTc3RibAAAAGdzdHNkAAAAAAAAAAEAAABXbXA0YQAAAAAAAAABAAAAAAAAAAAAAgAQAAAAAKxEAAAAAAAzZXNkcwAAAAADgICAIgACAASAgIAUQBUAAAAAAfQAAAHz+QWAgIACEhAGgICAAQIAAAAYc3R0cwAAAAAAAAABAAAAAgAABAAAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAIAAAABAAAAHHN0c3oAAAAAAAAAAAAAAAIAAAFzAAABdAAAABRzdGNvAAAAAAAAAAEAAAAsAAAAYnVkdGEAAABabWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAAtaWxzdAAAACWpdG9vAAAAHWRhdGEAAAABAAAAAExhdmY1Ni40MC4xMDE="};var n=i(2996),r=i.n(n);const o=[{name:"Chromium",group:"Chrome",identifier:"Chromium/([0-9.]*)"},{name:"Chrome Mobile",group:"Chrome",identifier:"Chrome/([0-9.]*) Mobile",versionIdentifier:"Chrome/([0-9.]*)"},{name:"Chrome",group:"Chrome",identifier:"Chrome/([0-9.]*)"},{name:"Chrome for iOS",group:"Chrome",identifier:"CriOS/([0-9.]*)"},{name:"Android Browser",group:"Chrome",identifier:"CrMo/([0-9.]*)"},{name:"Firefox",group:"Firefox",identifier:"Firefox/([0-9.]*)"},{name:"Opera Mini",group:"Opera",identifier:"Opera Mini/([0-9.]*)"},{name:"Opera",group:"Opera",identifier:"Opera ([0-9.]*)"},{name:"Opera",group:"Opera",identifier:"Opera/([0-9.]*)",versionIdentifier:"Version/([0-9.]*)"},{name:"IEMobile",group:"Explorer",identifier:"IEMobile/([0-9.]*)"},{name:"Internet Explorer",group:"Explorer",identifier:"MSIE ([a-zA-Z0-9.]*)"},{name:"Internet Explorer",group:"Explorer",identifier:"Trident/([0-9.]*)",versionIdentifier:"rv:([0-9.]*)"},{name:"Spartan",group:"Spartan",identifier:"Edge/([0-9.]*)",versionIdentifier:"Edge/([0-9.]*)"},{name:"Safari",group:"Safari",identifier:"Safari/([0-9.]*)",versionIdentifier:"Version/([0-9.]*)"}],a=[{name:"Windows 2000",group:"Windows",identifier:"Windows NT 5.0",version:"5.0"},{name:"Windows XP",group:"Windows",identifier:"Windows NT 5.1",version:"5.1"},{name:"Windows Vista",group:"Windows",identifier:"Windows NT 6.0",version:"6.0"},{name:"Windows 7",group:"Windows",identifier:"Windows NT 6.1",version:"7.0"},{name:"Windows 8",group:"Windows",identifier:"Windows NT 6.2",version:"8.0"},{name:"Windows 8.1",group:"Windows",identifier:"Windows NT 6.3",version:"8.1"},{name:"Windows 10",group:"Windows",identifier:"Windows NT 10.0",version:"10.0"},{name:"Windows Phone",group:"Windows Phone",identifier:"Windows Phone ([0-9.]*)"},{name:"Windows Phone",group:"Windows Phone",identifier:"Windows Phone OS ([0-9.]*)"},{name:"Windows",group:"Windows",identifier:"Windows"},{name:"Chrome OS",group:"Chrome OS",identifier:"CrOS"},{name:"Android",group:"Android",identifier:"Android",versionIdentifier:"Android ([a-zA-Z0-9.-]*)"},{name:"iPad",group:"iOS",identifier:"iPad",versionIdentifier:"OS ([0-9_]*)",versionSeparator:"[_|.]"},{name:"iPod",group:"iOS",identifier:"iPod",versionIdentifier:"OS ([0-9_]*)",versionSeparator:"[_|.]"},{name:"iPhone",group:"iOS",identifier:"iPhone OS",versionIdentifier:"OS ([0-9_]*)",versionSeparator:"[_|.]"},{name:"Mac OS X High Sierra",group:"Mac OS",identifier:"Mac OS X (10([_|.])13([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Sierra",group:"Mac OS",identifier:"Mac OS X (10([_|.])12([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X El Capitan",group:"Mac OS",identifier:"Mac OS X (10([_|.])11([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Yosemite",group:"Mac OS",identifier:"Mac OS X (10([_|.])10([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Mavericks",group:"Mac OS",identifier:"Mac OS X (10([_|.])9([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Mountain Lion",group:"Mac OS",identifier:"Mac OS X (10([_|.])8([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Lion",group:"Mac OS",identifier:"Mac OS X (10([_|.])7([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Snow Leopard",group:"Mac OS",identifier:"Mac OS X (10([_|.])6([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Leopard",group:"Mac OS",identifier:"Mac OS X (10([_|.])5([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Tiger",group:"Mac OS",identifier:"Mac OS X (10([_|.])4([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Panther",group:"Mac OS",identifier:"Mac OS X (10([_|.])3([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Jaguar",group:"Mac OS",identifier:"Mac OS X (10([_|.])2([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Puma",group:"Mac OS",identifier:"Mac OS X (10([_|.])1([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Cheetah",group:"Mac OS",identifier:"Mac OS X (10([_|.])0([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS",group:"Mac OS",identifier:"Mac OS"},{name:"Ubuntu",group:"Linux",identifier:"Ubuntu",versionIdentifier:"Ubuntu/([0-9.]*)"},{name:"Debian",group:"Linux",identifier:"Debian"},{name:"Gentoo",group:"Linux",identifier:"Gentoo"},{name:"Linux",group:"Linux",identifier:"Linux"},{name:"BlackBerry",group:"BlackBerry",identifier:"BlackBerry"}],l={},d=function(e,t){let i=e.split(".",2);t.fullVersion=e,i[0]&&(t.majorVersion=parseInt(i[0])),i[1]&&(t.minorVersion=parseInt(i[1]))},c=function(e,t,i){let s="["==t.substr(0,1)?new RegExp(t,"g"):t;const n=e.split(s,2);"."!=t&&(e=e.replace(new RegExp(t,"g"),".")),i.fullVersion=e,n&&n[0]&&(i.majorVersion=parseInt(n[0])),n&&n[1]&&(i.minorVersion=parseInt(n[1]))},h=function(e){let t,i=e.match(/\b(playstation 4|nx|opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return t=/\brv[ :]+(\d+)/g.exec(e)||[],{name:"IE",version:parseInt(t[1]||"")};if("Chrome"===i[1]){if(t=e.match(/\bOPR\/(\d+)/),null!=t)return{name:"Opera",version:parseInt(t[1])};if(t=e.match(/\bEdge\/(\d+)/),null!=t)return{name:"Edge",version:parseInt(t[1])}}else/android/i.test(e)&&(t=e.match(/version\/(\d+)/i))&&(i.splice(1,1,"Android WebView"),i.splice(2,1,t[1]));return i=i[2]?[i[1],i[2]]:[navigator.appName,navigator.appVersion,"-?"],{name:i[0],version:parseInt(i[1])}}(navigator.userAgent);l.isEdge=/Edg|EdgiOS|EdgA/i.test(navigator.userAgent),l.isChrome=/Chrome|CriOS/i.test(navigator.userAgent)&&!l.isEdge,l.isSafari=/Safari/i.test(navigator.userAgent)&&!l.isChrome&&!l.isEdge,l.isFirefox=/Firefox/i.test(navigator.userAgent),l.isLegacyIE=!!window.ActiveXObject,l.isIE=l.isLegacyIE||/trident.*rv:1\d/i.test(navigator.userAgent),l.isIE11=/trident.*rv:11/i.test(navigator.userAgent),l.isChromecast=l.isChrome&&/CrKey/i.test(navigator.userAgent),l.isMobile=/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Mobile Safari|Opera Mini/i.test(navigator.userAgent),l.isiOS=/iPad|iPhone|iPod/i.test(navigator.userAgent),l.isAndroid=/Android/i.test(navigator.userAgent),l.isWindowsPhone=/Windows Phone/i.test(navigator.userAgent),l.isWin8App=/MSAppHost/i.test(navigator.userAgent),l.isWiiU=/WiiU/i.test(navigator.userAgent),l.isPS4=/PlayStation 4/i.test(navigator.userAgent),l.hasLocalstorage=function(){try{return localStorage.setItem("clappr","clappr"),localStorage.removeItem("clappr"),!0}catch(e){return!1}}(),l.hasFlash=function(){try{return!!new ActiveXObject("ShockwaveFlash.ShockwaveFlash")}catch(e){return!(!navigator.mimeTypes||void 0===navigator.mimeTypes["application/x-shockwave-flash"]||!navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin)}}(),l.name=h.name,l.version=h.version,l.userAgent=navigator.userAgent,l.data=function(){let e={},t=l.userAgent.toLowerCase();for(let i of o){let s=new RegExp(i.identifier.toLowerCase()).exec(t);if(null!=s&&s[1]){if(e.name=i.name,e.group=i.group,i.versionIdentifier){let s=new RegExp(i.versionIdentifier.toLowerCase()).exec(t);null!=s&&s[1]&&d(s[1],e)}else d(s[1],e);break}}return e}(),l.os=function(){let e={},t=l.userAgent.toLowerCase();for(let i of a){let s=new RegExp(i.identifier.toLowerCase()).exec(t);if(null!=s){if(e.name=i.name,e.group=i.group,i.version)c(i.version,i.versionSeparator?i.versionSeparator:".",e);else if(s[1])c(s[1],i.versionSeparator?i.versionSeparator:".",e);else if(i.versionIdentifier){let s=new RegExp(i.versionIdentifier.toLowerCase()).exec(t);null!=s&&s[1]&&c(s[1],i.versionSeparator?i.versionSeparator:".",e)}break}}return e}(),l.isWindows=/^Windows$/i.test(l.os.group),l.isMacOS=/^Mac OS$/i.test(l.os.group),l.isLinux=/^Linux$/i.test(l.os.group),l.viewport=function(){let e={};return e.width=r()(window).width(),e.height=r()(window).height(),e}(),l.device=function(e){let t=/\((iP(?:hone|ad|od))?(?:[^;]*; ){0,2}([^)]+(?=\)))/.exec(e);return t&&(t[1]||t[2])||""}(l.userAgent),void 0!==window.orientation&&function(){switch(window.orientation){case-90:case 90:l.viewport.orientation="landscape";break;default:l.viewport.orientation="portrait"}}();const u=l,f={},p=[],g=(window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||function(e){window.setTimeout(e,1e3/60)}).bind(window),m=(window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame||window.clearTimeout).bind(window);function v(e,t){if(t)for(const i in t){const s=Object.getOwnPropertyDescriptor(t,i);s?Object.defineProperty(e,i,s):e[i]=t[i]}return e}function A(e,t){class i extends e{constructor(...e){super(...e),t.initialize&&t.initialize.apply(this,e)}}return v(i.prototype,t),i}const E={fullscreenElement:function(){return document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement},requestFullscreen:function(e){if(e.requestFullscreen)return e.requestFullscreen();if(e.webkitRequestFullscreen){if("function"==typeof e.then)return e.webkitRequestFullscreen();e.webkitRequestFullscreen()}else{if(e.mozRequestFullScreen)return e.mozRequestFullScreen();if(e.msRequestFullscreen)return e.msRequestFullscreen();e.querySelector&&e.querySelector("video")&&e.querySelector("video").webkitEnterFullScreen?e.querySelector("video").webkitEnterFullScreen():e.webkitEnterFullScreen&&e.webkitEnterFullScreen()}},cancelFullscreen:function(e=document){e.exitFullscreen?e.exitFullscreen():e.webkitCancelFullScreen?e.webkitCancelFullScreen():e.webkitExitFullscreen?e.webkitExitFullscreen():e.mozCancelFullScreen?e.mozCancelFullScreen():e.msExitFullscreen&&e.msExitFullscreen()},fullscreenEnabled:function(){return!!(document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled)}};class y{static get params(){const e=window.location.search.substring(1);return e!==this.query&&(this._urlParams=this.parse(e),this.query=e),this._urlParams}static get hashParams(){const e=window.location.hash.substring(1);return e!==this.hash&&(this._hashParams=this.parse(e),this.hash=e),this._hashParams}static parse(e){let t;const i=/\+/g,s=/([^&=]+)=?([^&]*)/g,n=e=>decodeURIComponent(e.replace(i," ")),r={};for(;t=s.exec(e);)r[n(t[1]).toLowerCase()]=n(t[2]);return r}}function T(e="t"){let t=0;const i=y.params[e]||y.hashParams[e]||"",s=i.match(/[0-9]+[hms]+/g)||[];if(s.length>0){const e={h:3600,m:60,s:1};s.forEach((function(i){if(i){const s=i[i.length-1],n=parseInt(i.slice(0,i.length-1),10);t+=n*e[s]}}))}else i&&(t=parseInt(i,10));return t}function b(e){return f[e]||(f[e]=0),e+ ++f[e]}function S(e){return e-parseFloat(e)+1>=0}function _(){return window.navigator&&window.navigator.language}function C(e,t){let i=(t=Object.assign({inline:!1,muted:!1,timeout:250,type:"video",source:s.mp4,element:null},t)).element?t.element:document.createElement(t.type);i.muted=t.muted,!0===t.muted&&i.setAttribute("muted","muted"),!0===t.inline&&i.setAttribute("playsinline","playsinline"),i.src=t.source;let n=i.play(),r=setTimeout((()=>{o(!1,new Error(`Timeout ${t.timeout} ms has been reached`))}),t.timeout),o=(t,i=null)=>{clearTimeout(r),e(t,i)};void 0!==n?n.then((()=>o(!0))).catch((e=>o(!1,e))):o(!0)}class R{static configure(e){this.options=r().extend(!0,this.options,e)}static create(e){return this.options.recycleVideo&&"video"===e&&p.length>0?p.shift():document.createElement(e)}static garbage(e){this.options.recycleVideo&&"VIDEO"===e.tagName.toUpperCase()&&(r()(e).children().remove(),Object.values(e.attributes).forEach((t=>e.removeAttribute(t.name))),p.push(e))}}R.options={recycleVideo:!1};class L{constructor(e=500){this.delay=e,this.lastTime=0}handle(e,t,i=!0){let s=(new Date).getTime(),n=s-this.lastTime;n0&&(t(),i&&e.preventDefault()),this.lastTime=s}}const I={Config:class{static _defaultConfig(){return{volume:{value:100,parse:parseInt}}}static _defaultValueFor(e){try{return this._defaultConfig()[e].parse(this._defaultConfig()[e].value)}catch(e){return}}static _createKeyspace(e){return`clappr.${document.domain}.${e}`}static restore(e){return u.hasLocalstorage&&localStorage[this._createKeyspace(e)]?this._defaultConfig()[e].parse(localStorage[this._createKeyspace(e)]):this._defaultValueFor(e)}static persist(e,t){if(u.hasLocalstorage)try{return localStorage[this._createKeyspace(e)]=t,!0}catch(e){return!1}}},Fullscreen:E,QueryString:y,DomRecycler:R,assign:v,extend:A,formatTime:function(e,t){if(!isFinite(e))return"--:--";e*=1e3;const i=(e=parseInt(e/1e3))%60,s=(e=parseInt(e/60))%60,n=(e=parseInt(e/60))%24,r=parseInt(e/24);let o="";return r&&r>0&&(o+=r+":",n<1&&(o+="00:")),(n&&n>0||t)&&(o+=("0"+n).slice(-2)+":"),o+=("0"+s).slice(-2)+":",o+=("0"+i).slice(-2),o.trim()},seekStringToSeconds:T,uniqueId:b,currentScriptUrl:function(){const e=document.getElementsByTagName("script");return e.length?e[e.length-1].src:""},isNumber:S,requestAnimationFrame:g,cancelAnimationFrame:m,getBrowserLanguage:_,now:function(){return window.performance&&window.performance.now?performance.now():Date.now()},removeArrayItem:function(e,t){const i=e.indexOf(t);i>=0&&e.splice(i,1)},listContainsIgnoreCase:function(e,t){return void 0!==e&&void 0!==t&&void 0!==t.find((t=>e.toLowerCase()===t.toLowerCase()))},canAutoPlayMedia:C,Media:s,DoubleEventHandler:L},k="font-weight: bold; font-size: 13px;",w="color: #ff8000;"+k,P="color: #ff0000;"+k,O=["color: #0000ff;"+k,"color: #006600;"+k,w,P,P],D=["debug","info","warn","error","disabled"];class N{get level(){return this._level}set level(e){this._level=e}constructor(e=1,t=3){this.EXCLUDE_LIST=["timeupdate","playback:timeupdate","playback:progress","container:hover","container:timeupdate","container:progress"],this.level=e,this.previousLevel=this.level,this.offLevel=t}debug(e){this.log(e,0,Array.prototype.slice.call(arguments,1))}info(e){this.log(e,1,Array.prototype.slice.call(arguments,1))}warn(e){this.log(e,2,Array.prototype.slice.call(arguments,1))}error(e){this.log(e,3,Array.prototype.slice.call(arguments,1))}onOff(){this.level===this.offLevel?this.level=this.previousLevel:(this.previousLevel=this.level,this.level=this.offLevel),window.console&&window.console.log&&window.console.log("%c[Clappr.Log] set log level to "+D[this.level],w)}log(e,t,i){if(this.EXCLUDE_LIST.indexOf(i[0])>=0)return;if(tthis.off(e,s);return s=function(){n(),t.apply(this,arguments)},this.on(e,s,i)}off(e,t,i){let s,n,r,o,a,l,d,c;if(!this._events||!B(this,"off",e,[t,i]))return this;if(!e&&!t&&!i)return this._events=void 0,this;for(o=e?[e]:Object.keys(this._events),a=0,l=o.length;a0===t?e:e=e[0].toUpperCase()+e.slice(1))).join(""):N.error("Events","Error when register event: "+e)}static listAvailableCustomEvents(){return U.Custom||(U.Custom={}),Object.keys(U.Custom).filter((e=>"string"==typeof U.Custom[e]))}}const $={listenTo:"on",listenToOnce:"once"};Object.keys($).forEach((function(e){U.prototype[e]=function(t,i,s){return(this._listeningTo||(this._listeningTo={}))[t._listenId||(t._listenId=b("l"))]=t,s||"object"!=typeof i||(s=this),t[$[e]](i,s,this),this}})),U.PLAYER_READY="ready",U.PLAYER_RESIZE="resize",U.PLAYER_FULLSCREEN="fullscreen",U.PLAYER_PLAY="play",U.PLAYER_PAUSE="pause",U.PLAYER_STOP="stop",U.PLAYER_ENDED="ended",U.PLAYER_SEEK="seek",U.PLAYER_ERROR="playererror",U.ERROR="error",U.PLAYER_TIMEUPDATE="timeupdate",U.PLAYER_VOLUMEUPDATE="volumeupdate",U.PLAYER_SUBTITLE_AVAILABLE="subtitleavailable",U.PLAYBACK_PROGRESS="playback:progress",U.PLAYBACK_TIMEUPDATE="playback:timeupdate",U.PLAYBACK_READY="playback:ready",U.PLAYBACK_BUFFERING="playback:buffering",U.PLAYBACK_BUFFERFULL="playback:bufferfull",U.PLAYBACK_SETTINGSUPDATE="playback:settingsupdate",U.PLAYBACK_LOADEDMETADATA="playback:loadedmetadata",U.PLAYBACK_HIGHDEFINITIONUPDATE="playback:highdefinitionupdate",U.PLAYBACK_BITRATE="playback:bitrate",U.PLAYBACK_LEVELS_AVAILABLE="playback:levels:available",U.PLAYBACK_LEVEL_SWITCH_START="playback:levels:switch:start",U.PLAYBACK_LEVEL_SWITCH_END="playback:levels:switch:end",U.PLAYBACK_PLAYBACKSTATE="playback:playbackstate",U.PLAYBACK_DVR="playback:dvr",U.PLAYBACK_MEDIACONTROL_DISABLE="playback:mediacontrol:disable",U.PLAYBACK_MEDIACONTROL_ENABLE="playback:mediacontrol:enable",U.PLAYBACK_ENDED="playback:ended",U.PLAYBACK_PLAY_INTENT="playback:play:intent",U.PLAYBACK_PLAY="playback:play",U.PLAYBACK_PAUSE="playback:pause",U.PLAYBACK_SEEK="playback:seek",U.PLAYBACK_SEEKED="playback:seeked",U.PLAYBACK_STOP="playback:stop",U.PLAYBACK_ERROR="playback:error",U.PLAYBACK_STATS_ADD="playback:stats:add",U.PLAYBACK_FRAGMENT_LOADED="playback:fragment:loaded",U.PLAYBACK_LEVEL_SWITCH="playback:level:switch",U.PLAYBACK_SUBTITLE_AVAILABLE="playback:subtitle:available",U.PLAYBACK_SUBTITLE_CHANGED="playback:subtitle:changed",U.PLAYBACK_AUDIO_AVAILABLE="playback:audio:available",U.PLAYBACK_AUDIO_CHANGED="playback:audio:changed",U.CORE_CONTAINERS_CREATED="core:containers:created",U.CORE_ACTIVE_CONTAINER_CHANGED="core:active:container:changed",U.CORE_OPTIONS_CHANGE="core:options:change",U.CORE_READY="core:ready",U.CORE_FULLSCREEN="core:fullscreen",U.CORE_RESIZE="core:resize",U.CORE_SCREEN_ORIENTATION_CHANGED="core:screen:orientation:changed",U.CORE_MOUSE_MOVE="core:mousemove",U.CORE_MOUSE_LEAVE="core:mouseleave",U.CONTAINER_PLAYBACKSTATE="container:playbackstate",U.CONTAINER_PLAYBACKDVRSTATECHANGED="container:dvr",U.CONTAINER_BITRATE="container:bitrate",U.CONTAINER_STATS_REPORT="container:stats:report",U.CONTAINER_DESTROYED="container:destroyed",U.CONTAINER_READY="container:ready",U.CONTAINER_RESIZE="container:resize",U.CONTAINER_ERROR="container:error",U.CONTAINER_LOADEDMETADATA="container:loadedmetadata",U.CONTAINER_SUBTITLE_AVAILABLE="container:subtitle:available",U.CONTAINER_SUBTITLE_CHANGED="container:subtitle:changed",U.CONTAINER_AUDIO_AVAILABLE="container:audio:available",U.CONTAINER_AUDIO_CHANGED="container:audio:changed",U.CONTAINER_TIMEUPDATE="container:timeupdate",U.CONTAINER_PROGRESS="container:progress",U.CONTAINER_PLAY="container:play",U.CONTAINER_STOP="container:stop",U.CONTAINER_PAUSE="container:pause",U.CONTAINER_ENDED="container:ended",U.CONTAINER_CLICK="container:click",U.CONTAINER_DBLCLICK="container:dblclick",U.CONTAINER_CONTEXTMENU="container:contextmenu",U.CONTAINER_MOUSE_ENTER="container:mouseenter",U.CONTAINER_MOUSE_LEAVE="container:mouseleave",U.CONTAINER_MOUSE_UP="container:mouseup",U.CONTAINER_MOUSE_DOWN="container:mousedown",U.CONTAINER_SEEK="container:seek",U.CONTAINER_SEEKED="container:seeked",U.CONTAINER_VOLUME="container:volume",U.CONTAINER_FULLSCREEN="container:fullscreen",U.CONTAINER_STATE_BUFFERING="container:state:buffering",U.CONTAINER_STATE_BUFFERFULL="container:state:bufferfull",U.CONTAINER_SETTINGSUPDATE="container:settingsupdate",U.CONTAINER_HIGHDEFINITIONUPDATE="container:highdefinitionupdate",U.CONTAINER_MEDIACONTROL_SHOW="container:mediacontrol:show",U.CONTAINER_MEDIACONTROL_HIDE="container:mediacontrol:hide",U.CONTAINER_MEDIACONTROL_DISABLE="container:mediacontrol:disable",U.CONTAINER_MEDIACONTROL_ENABLE="container:mediacontrol:enable",U.CONTAINER_STATS_ADD="container:stats:add",U.CONTAINER_OPTIONS_CHANGE="container:options:change",U.MEDIACONTROL_RENDERED="mediacontrol:rendered",U.MEDIACONTROL_FULLSCREEN="mediacontrol:fullscreen",U.MEDIACONTROL_SHOW="mediacontrol:show",U.MEDIACONTROL_HIDE="mediacontrol:hide",U.MEDIACONTROL_MOUSEMOVE_SEEKBAR="mediacontrol:mousemove:seekbar",U.MEDIACONTROL_MOUSELEAVE_SEEKBAR="mediacontrol:mouseleave:seekbar",U.MEDIACONTROL_PLAYING="mediacontrol:playing",U.MEDIACONTROL_NOTPLAYING="mediacontrol:notplaying",U.MEDIACONTROL_CONTAINERCHANGED="mediacontrol:containerchanged",U.MEDIACONTROL_OPTIONS_CHANGE="mediacontrol:options:change";class V extends U{get options(){return this._options}constructor(e={}){super(e),this._options=e,this.uniqueId=b("o")}}const G=/^(\S+)\s*(.*)$/;class j extends V{get tagName(){return"div"}get events(){return{}}get attributes(){return{}}constructor(e){super(e),this.cid=b("c"),this._ensureElement(),this.delegateEvents()}$(e){return this.$el.find(e)}render(){return this}destroy(){return this.$el.remove(),this.stopListening(),this.undelegateEvents(),this}setElement(e,t){return this.$el&&this.undelegateEvents(),this.$el=r().zepto.isZ(e)?e:r()(e),this.el=this.$el[0],!1!==t&&this.delegateEvents(),this}delegateEvents(e){e||(e=this.events),this.undelegateEvents();for(const t in e){let i=e[t];if(i&&i.constructor!==Function&&(i=this[e[t]]),!i)continue;const s=t.match(G);let n=s[1],r=s[2];n+=".delegateEvents"+this.cid,""===r?this.$el.on(n,i.bind(this)):this.$el.on(n,r,i.bind(this))}return this}undelegateEvents(){return this.$el.off(".delegateEvents"+this.cid),this}_ensureElement(){if(this.el)this.setElement(this.el,!1);else{const e=r().extend(!0,{},this.attributes);this.id&&(e.id=this.id),this.className&&(e.class=this.className);const t=r()(R.create(this.tagName)).attr(e);this.setElement(t,!1)}}}const K=class extends V{get name(){return"error"}static get Levels(){return{FATAL:"FATAL",WARN:"WARN",INFO:"INFO"}}constructor(e={},t){super(e),this.core=t}createError(e){this.core?this.core.trigger(U.ERROR,e):N.warn(this.name,"Core is not set. Error: ",e)}},H={createError(e,t={useCodePrefix:!0}){const i=this.constructor&&this.constructor.type||"",s=this.name||i,n=this.i18n||this.core&&this.core.i18n||this.container&&this.container.i18n,r=`${s}:${e&&e.code||"unknown"}`,o={description:"",level:K.Levels.FATAL,origin:s,scope:i,raw:{}},a=Object.assign({},o,e,{code:t.useCodePrefix?r:e.code});if(n&&a.level==K.Levels.FATAL&&!a.UI){const e={title:n.t("default_error_title"),message:n.t("default_error_message")};a.UI=e}return this.playerError?this.playerError.createError(a):N.warn(s,"PlayerError is not defined. Error: ",a),a}},Y=H;class W extends j{get isAudioOnly(){return!1}get isAdaptive(){return!1}get ended(){return!1}get i18n(){return this._i18n}get buffering(){return!1}constructor(e,t,i){super(e),this.settings={},this._i18n=t,this.playerError=i,this._consented=!1}consent(e){"function"==typeof e&&e()}play(){}pause(){}stop(){}seek(e){}seekPercentage(e){}getStartTimeOffset(){return 0}getDuration(){return 0}isPlaying(){return!1}get isReady(){return!1}get hasClosedCaptionsTracks(){return this.closedCaptionsTracks.length>0}get closedCaptionsTracks(){return[]}get closedCaptionsTrackId(){return-1}set closedCaptionsTrackId(e){}get audioTracks(){return[]}get currentAudioTrack(){return null}switchAudioTrack(e){}getPlaybackType(){return W.NO_OP}isHighDefinitionInUse(){return!1}mute(){}unmute(){}volume(e){}configure(e){this._options=r().extend(!0,this._options,e)}attemptAutoPlay(){this.canAutoPlay(((e,t)=>{e&&this.play()}))}canAutoPlay(e){e(!0,null)}}Object.assign(W.prototype,Y),W.extend=function(e){return A(W,e)},W.canPlay=(e,t)=>!1,W.VOD="vod",W.AOD="aod",W.LIVE="live",W.NO_OP="no_op",W.type="playback";class z extends V{get playerError(){return this.container.playerError}constructor(e){super(e.options),this.container=e,this.enabled=!0,this.bindEvents()}enable(){this.enabled||(this.bindEvents(),this.enabled=!0)}disable(){this.enabled&&(this.stopListening(),this.enabled=!1)}bindEvents(){}destroy(){this.stopListening()}}Object.assign(z.prototype,Y),z.extend=function(e){return A(z,e)},z.type="container";class q extends V{get playerError(){return this.core.playerError}constructor(e){super(e.options),this.core=e,this.enabled=!0,this.bindEvents()}bindEvents(){}enable(){this.enabled||(this.bindEvents(),this.enabled=!0)}disable(){this.enabled&&(this.stopListening(),this.enabled=!1)}getExternalInterface(){return{}}destroy(){this.stopListening()}}Object.assign(q.prototype,Y),q.extend=function(e){return A(q,e)},q.type="core";class X extends j{get playerError(){return this.core.playerError}constructor(e){super(e.options),this.core=e,this.enabled=!0,this.bindEvents(),this.render()}bindEvents(){}getExternalInterface(){return{}}enable(){this.enabled||(this.bindEvents(),this.$el.show(),this.enabled=!0)}disable(){this.stopListening(),this.$el.hide(),this.enabled=!1}render(){return this}}Object.assign(X.prototype,Y),X.extend=function(e){return A(X,e)},X.type="core";class Q extends j{get playerError(){return this.container.playerError}constructor(e){super(e.options),this.container=e,this.enabled=!0,this.bindEvents()}enable(){this.enabled||(this.bindEvents(),this.$el.show(),this.enabled=!0)}disable(){this.stopListening(),this.$el.hide(),this.enabled=!1}bindEvents(){}}Object.assign(Q.prototype,Y),Q.extend=function(e){return A(Q,e)},Q.type="container";var Z={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},J=/(.)^/,ee={"'":"'","\\":"\\","\r":"r","\n":"n","\t":"t","\u2028":"u2028","\u2029":"u2029"},te=/\\|'|\r|\n|\t|\u2028|\u2029/g,ie={"&":"&","<":"<",">":">",'"':""","'":"'"},se=new RegExp("[&<>\"']","g"),ne=function(e){return null===e?"":(""+e).replace(se,(function(e){return ie[e]}))},re=0,oe=function(e,t){var i,s=new RegExp([(Z.escape||J).source,(Z.interpolate||J).source,(Z.evaluate||J).source].join("|")+"|$","g"),n=0,r="__p+='";e.replace(s,(function(t,i,s,o,a){return r+=e.slice(n,a).replace(te,(function(e){return"\\"+ee[e]})),i&&(r+="'+\n((__t=("+i+"))==null?'':escapeExpr(__t))+\n'"),s&&(r+="'+\n((__t=("+s+"))==null?'':__t)+\n'"),o&&(r+="';\n"+o+"\n__p+='"),n=a+t.length,t})),r+="';\n",Z.variable||(r="with(obj||{}){\n"+r+"}\n"),r="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+r+"return __p;\n//# sourceURL=/microtemplates/source["+re+++"]";try{i=new Function(Z.variable||"obj","escapeExpr",r)}catch(e){throw e.source=r,e}if(t)return i(t,ne);var o=function(e){return i.call(this,e,ne)};return o.source="function("+(Z.variable||"obj")+"){\n"+r+"}",o};oe.settings=Z;const ae=oe,le={getStyleFor:function(e,t={baseUrl:""}){return r()('').html(ae(e.toString())(t))}},de=le;var ce=i(5072),he=i.n(ce),ue=i(7825),fe=i.n(ue),pe=i(7659),ge=i.n(pe),me=i(5056),ve=i.n(me),Ae=i(540),Ee=i.n(Ae),ye=i(1113),Te=i.n(ye),be=i(6434),Se={};Se.styleTagTransform=Te(),Se.setAttributes=ve(),Se.insert=ge().bind(null,"head"),Se.domAPI=fe(),Se.insertStyleElement=Ee(),he()(be.A,Se);const _e=be.A&&be.A.locals?be.A.locals:void 0;class Ce extends j{get name(){return"Container"}get attributes(){return{class:"container","data-container":""}}get events(){return{click:"clicked",dblclick:"dblClicked",touchend:"dblTap",contextmenu:"onContextMenu",mouseenter:"mouseEnter",mouseleave:"mouseLeave",mouseup:"onMouseUp",mousedown:"onMouseDown"}}get ended(){return this.playback.ended}get buffering(){return this.playback.buffering}get i18n(){return this._i18n}get hasClosedCaptionsTracks(){return this.playback.hasClosedCaptionsTracks}get closedCaptionsTracks(){return this.playback.closedCaptionsTracks}get closedCaptionsTrackId(){return this.playback.closedCaptionsTrackId}set closedCaptionsTrackId(e){this.playback.closedCaptionsTrackId=e}get audioTracks(){return this.playback.audioTracks}get currentAudioTrack(){return this.playback.currentAudioTrack}constructor(e,t,i){super(e),this._i18n=t,this.currentTime=0,this.volume=100,this.playback=e.playback,this.playerError=i,this.settings=r().extend(!0,{},this.playback.settings),this.isReady=!1,this.mediaControlDisabled=!1,this.plugins=[this.playback],this.dblTapHandler=new L(500),this.clickTimer=null,this.clickDelay=200,this.actionsMetadata={},this.bindEvents()}bindEvents(){this.listenTo(this.playback,U.PLAYBACK_PROGRESS,this.onProgress),this.listenTo(this.playback,U.PLAYBACK_TIMEUPDATE,this.timeUpdated),this.listenTo(this.playback,U.PLAYBACK_READY,this.ready),this.listenTo(this.playback,U.PLAYBACK_BUFFERING,this.onBuffering),this.listenTo(this.playback,U.PLAYBACK_BUFFERFULL,this.bufferfull),this.listenTo(this.playback,U.PLAYBACK_SETTINGSUPDATE,this.settingsUpdate),this.listenTo(this.playback,U.PLAYBACK_LOADEDMETADATA,this.loadedMetadata),this.listenTo(this.playback,U.PLAYBACK_HIGHDEFINITIONUPDATE,this.highDefinitionUpdate),this.listenTo(this.playback,U.PLAYBACK_BITRATE,this.updateBitrate),this.listenTo(this.playback,U.PLAYBACK_PLAYBACKSTATE,this.playbackStateChanged),this.listenTo(this.playback,U.PLAYBACK_DVR,this.playbackDvrStateChanged),this.listenTo(this.playback,U.PLAYBACK_MEDIACONTROL_DISABLE,this.disableMediaControl),this.listenTo(this.playback,U.PLAYBACK_MEDIACONTROL_ENABLE,this.enableMediaControl),this.listenTo(this.playback,U.PLAYBACK_SEEK,this.onSeek),this.listenTo(this.playback,U.PLAYBACK_SEEKED,this.onSeeked),this.listenTo(this.playback,U.PLAYBACK_ENDED,this.onEnded),this.listenTo(this.playback,U.PLAYBACK_PLAY,this.playing),this.listenTo(this.playback,U.PLAYBACK_PAUSE,this.paused),this.listenTo(this.playback,U.PLAYBACK_STOP,this.stopped),this.listenTo(this.playback,U.PLAYBACK_ERROR,this.error),this.listenTo(this.playback,U.PLAYBACK_SUBTITLE_AVAILABLE,this.subtitleAvailable),this.listenTo(this.playback,U.PLAYBACK_SUBTITLE_CHANGED,this.subtitleChanged),this.listenTo(this.playback,U.PLAYBACK_AUDIO_AVAILABLE,this.audioAvailable),this.listenTo(this.playback,U.PLAYBACK_AUDIO_CHANGED,this.audioChanged)}subtitleAvailable(){this.trigger(U.CONTAINER_SUBTITLE_AVAILABLE)}subtitleChanged(e){this.trigger(U.CONTAINER_SUBTITLE_CHANGED,e)}audioAvailable(e){this.trigger(U.CONTAINER_AUDIO_AVAILABLE,e)}audioChanged(e){this.trigger(U.CONTAINER_AUDIO_CHANGED,e)}playbackStateChanged(e){this.trigger(U.CONTAINER_PLAYBACKSTATE,e)}playbackDvrStateChanged(e){this.settings=this.playback.settings,this.dvrInUse=e,this.trigger(U.CONTAINER_PLAYBACKDVRSTATECHANGED,e)}updateBitrate(e){this.trigger(U.CONTAINER_BITRATE,e)}statsReport(e){this.trigger(U.CONTAINER_STATS_REPORT,e)}getPlaybackType(){return this.playback.getPlaybackType()}isDvrEnabled(){return!!this.playback.dvrEnabled}isDvrInUse(){return!!this.dvrInUse}destroy(){this.disableResizeObserver(),this.trigger(U.CONTAINER_DESTROYED,this,this.name),this.stopListening(),this.plugins.forEach((e=>e.destroy())),this.$el.remove()}setStyle(e){this.$el.css(e)}animate(e,t){return this.$el.animate(e,t).promise()}ready(){this.isReady=!0,this.trigger(U.CONTAINER_READY,this.name)}isPlaying(){return this.playback.isPlaying()}getStartTimeOffset(){return this.playback.getStartTimeOffset()}getCurrentTime(){return this.currentTime}getDuration(){return this.playback.getDuration()}error(e){this.isReady||this.ready(),this.trigger(U.CONTAINER_ERROR,e,this.name)}loadedMetadata(e){this.trigger(U.CONTAINER_LOADEDMETADATA,e)}timeUpdated(e){this.currentTime=e.current,this.trigger(U.CONTAINER_TIMEUPDATE,e,this.name)}onProgress(...e){this.trigger(U.CONTAINER_PROGRESS,...e,this.name)}playing(){this.trigger(U.CONTAINER_PLAY,this.name,this.actionsMetadata.playEvent||{}),this.actionsMetadata.playEvent={}}paused(){this.trigger(U.CONTAINER_PAUSE,this.name,this.actionsMetadata.pauseEvent||{}),this.actionsMetadata.pauseEvent={}}stopped(){this.trigger(U.CONTAINER_STOP,this.actionsMetadata.stopEvent||{}),this.actionsMetadata.stopEvent={}}play(e={}){this.actionsMetadata.playEvent=e,this.playback.play(e)}stop(e={}){this.actionsMetadata.stopEvent=e,this.playback.stop(e),this.currentTime=0}switchAudioTrack(e){this.playback.switchAudioTrack(e)}pause(e={}){this.actionsMetadata.pauseEvent=e,this.playback.pause(e)}onEnded(){this.trigger(U.CONTAINER_ENDED,this,this.name),this.currentTime=0}clicked(){this.options.chromeless&&!this.options.allowUserInteraction||(this.clickTimer=setTimeout((()=>{this.clickTimer&&this.trigger(U.CONTAINER_CLICK,this,this.name)}),this.clickDelay))}cancelClicked(){clearTimeout(this.clickTimer),this.clickTimer=null}dblClicked(){this.options.chromeless&&!this.options.allowUserInteraction||(this.cancelClicked(),this.trigger(U.CONTAINER_DBLCLICK,this,this.name))}dblTap(e){this.options.chromeless&&!this.options.allowUserInteraction||this.dblTapHandler.handle(e,(()=>{this.cancelClicked(),this.trigger(U.CONTAINER_DBLCLICK,this,this.name)}))}onContextMenu(e){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(U.CONTAINER_CONTEXTMENU,e,this.name)}seek(e){this.playback.seek(e)}onSeek(e){this.trigger(U.CONTAINER_SEEK,e,this.name)}onSeeked(){this.trigger(U.CONTAINER_SEEKED,this.name)}seekPercentage(e){const t=this.getDuration();if(e>=0&&e<=100){const i=t*(e/100);this.seek(i)}}setVolume(e){this.volume=parseFloat(e),this.trigger(U.CONTAINER_VOLUME,this.volume,this.name),this.playback.volume(this.volume)}fullscreen(){this.trigger(U.CONTAINER_FULLSCREEN,this.name)}onBuffering(){this.trigger(U.CONTAINER_STATE_BUFFERING,this.name)}bufferfull(){this.trigger(U.CONTAINER_STATE_BUFFERFULL,this.name)}addPlugin(e){this.plugins.push(e)}hasPlugin(e){return!!this.getPlugin(e)}getPlugin(e){return this.plugins.filter((t=>t.name===e))[0]}mouseEnter(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(U.CONTAINER_MOUSE_ENTER)}mouseLeave(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(U.CONTAINER_MOUSE_LEAVE)}mouseUp(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(U.CONTAINER_MOUSE_UP)}mouseDown(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(U.CONTAINER_MOUSE_DOWN)}settingsUpdate(){this.settings=this.playback.settings,this.trigger(U.CONTAINER_SETTINGSUPDATE)}highDefinitionUpdate(e){this.trigger(U.CONTAINER_HIGHDEFINITIONUPDATE,e)}isHighDefinitionInUse(){return this.playback.isHighDefinitionInUse()}disableMediaControl(){this.mediaControlDisabled||(this.mediaControlDisabled=!0,this.trigger(U.CONTAINER_MEDIACONTROL_DISABLE))}enableMediaControl(){this.mediaControlDisabled&&(this.mediaControlDisabled=!1,this.trigger(U.CONTAINER_MEDIACONTROL_ENABLE))}updateStyle(){!this.options.chromeless||this.options.allowUserInteraction?this.$el.removeClass("chromeless"):this.$el.addClass("chromeless")}enableResizeObserver(){this.disableResizeObserver(),this.resizeObserverInterval=setInterval((()=>this.checkResize()),500)}disableResizeObserver(){this.resizeObserverInterval&&clearInterval(this.resizeObserverInterval)}checkResize(){const e={width:this.el.clientWidth,height:this.el.clientHeight},{width:t,height:i}=this.currentSize||{};(i!==e.height||t!==e.width)&&(this.currentSize=e,this.trigger(U.CONTAINER_RESIZE,e))}configure(e){this._options=r().extend(!0,this._options,e),this.updateStyle(),this.playback.configure(this.options),this.trigger(U.CONTAINER_OPTIONS_CHANGE)}render(){const e=de.getStyleFor(_e.toString(),{baseUrl:this.options.baseUrl});return this.$el.append(e[0]),this.$el.append(this.playback.render().el),this.updateStyle(),this.checkResize(),this.enableResizeObserver(),this}}Object.assign(Ce.prototype,Y);class Re extends V{get options(){return this._options}set options(e){this._options=e}constructor(e,t,i,s){super(e),this._i18n=i,this.loader=t,this.playerError=s}createContainers(){return r().Deferred((e=>{e.resolve(this.options.sources.map((e=>this.createContainer(e))))}))}findPlaybackPlugin(e,t){return this.loader.playbackPlugins.filter((i=>i.canPlay(e,t)))[0]}createContainer(e){let t=null,i=this.options.mimeType;"object"==typeof e?(t=e.source.toString(),e.mimeType&&(i=e.mimeType)):t=e.toString(),t.match(/^\/\//)&&(t=window.location.protocol+t);let s=Object.assign(Object.assign({},this.options),{src:t,mimeType:i});const n=this.findPlaybackPlugin(t,i),o=n?new n(s,this._i18n,this.playerError):new W;s=Object.assign(Object.assign({},s),{playback:o});const a=new Ce(s,this._i18n,this.playerError),l=r().Deferred();return l.promise(a),this.addContainerPlugins(a),this.listenToOnce(a,U.CONTAINER_READY,(()=>l.resolve(a))),a}addContainerPlugins(e){this.loader.containerPlugins.forEach((t=>{e.addPlugin(new t(e))}))}}var Le={};Le.styleTagTransform=Te(),Le.setAttributes=ve(),Le.insert=ge().bind(null,"head"),Le.domAPI=fe(),Le.insertStyleElement=Ee(),he()(be.A,Le);const Ie=be.A&&be.A.locals?be.A.locals:void 0;var ke={};ke.styleTagTransform=Te(),ke.setAttributes=ve(),ke.insert=ge().bind(null,"head"),ke.domAPI=fe(),ke.insertStyleElement=Ee(),he()(be.A,ke);const we=be.A&&be.A.locals?be.A.locals:void 0;class Pe extends j{get events(){return{webkitfullscreenchange:"handleFullscreenChange",mousemove:"onMouseMove",mouseleave:"onMouseLeave"}}get attributes(){return{"data-player":"",tabindex:9999}}get isReady(){return!!this.ready}get i18n(){return this.getPlugin("strings")||{t:e=>e}}get mediaControl(){return this._mediaControl||(this._mediaControl=this.getPlugin("media_control"))||this.dummyMediaControl}get dummyMediaControl(){return this._dummyMediaControl||(this._dummyMediaControl=new X(this)),this._dummyMediaControl}get activeContainer(){return this._activeContainer}set activeContainer(e){this._activeContainer=e,this.trigger(U.CORE_ACTIVE_CONTAINER_CHANGED,this._activeContainer)}get activePlayback(){return this.activeContainer&&this.activeContainer.playback}get activePlaybackEl(){if(this.activePlayback)return this.activePlayback.$el?this.activePlayback.$el.find("video")[0]:this.activePlayback.el}constructor(e){super(e),this.playerError=new K(e,this),this.configureDomRecycler(),this.firstResize=!0,this.plugins=[],this.containers=[],this._boundFullscreenHandler=()=>this.handleFullscreenChange(),r()(document).bind("fullscreenchange",this._boundFullscreenHandler),r()(document).bind("MSFullscreenChange",this._boundFullscreenHandler),r()(document).bind("mozfullscreenchange",this._boundFullscreenHandler),u.isMobile&&r()(window).bind("resize",(e=>{this.handleWindowResize(e)}))}configureDomRecycler(){let e=this.options&&this.options.playback&&this.options.playback.recycleVideo;R.configure({recycleVideo:e})}createContainers(e){this.defer=r().Deferred(),this.defer.promise(this),this.containerFactory=new Re(e,e.loader,this.i18n,this.playerError),this.prepareContainers()}prepareContainers(){this.containerFactory.createContainers().then((e=>this.setupContainers(e))).then((e=>this.resolveOnContainersReady(e)))}updateSize(){this.isFullscreen()?this.setFullscreen():this.setPlayerSize()}setFullscreen(){u.isiOS||(this.$el.addClass("fullscreen"),this.$el.removeAttr("style"),this.previousSize={width:this.options.width,height:this.options.height},this.currentSize={width:r()(window).width(),height:r()(window).height()})}setPlayerSize(){this.$el.removeClass("fullscreen"),this.currentSize=this.previousSize,this.previousSize={width:r()(window).width(),height:r()(window).height()},this.resize(this.currentSize)}resize(e){S(e.height)||S(e.width)?(this.el.style.height=`${e.height}px`,this.el.style.width=`${e.width}px`):(this.el.style.height=`${e.height}`,this.el.style.width=`${e.width}`),this.previousSize={width:this.options.width,height:this.options.height},this.options.width=e.width,this.options.height=e.height,this.currentSize=e,this.triggerResize(this.currentSize)}enableResizeObserver(){this.disableResizeObserver(),this.resizeObserverInterval=setInterval((()=>{this.triggerResize({width:this.el.clientWidth,height:this.el.clientHeight})}),500)}triggerResize(e){(this.firstResize||this.oldHeight!==e.height||this.oldWidth!==e.width)&&(this.oldHeight=e.height,this.oldWidth=e.width,this.computedSize=e,this.firstResize=!1,this.trigger(U.CORE_RESIZE,e))}disableResizeObserver(){this.resizeObserverInterval&&clearInterval(this.resizeObserverInterval),this.resizeObserverInterval=null}resolveOnContainersReady(e){r().when.apply(r(),e).done((()=>{this.defer.resolve(this),this.ready=!0,this.trigger(U.CORE_READY)}))}addPlugin(e){this.plugins.push(e)}hasPlugin(e){return!!this.getPlugin(e)}getPlugin(e){return this.plugins.filter((t=>t.name===e))[0]}load(e,t){this.options.mimeType=t,e=e&&e.constructor===Array?e:[e],this.options.sources=e,this.containers.forEach((e=>e.destroy())),this.containerFactory.options=r().extend(!0,this.options,{sources:e}),this.prepareContainers()}destroy(){this.disableResizeObserver(),this.containers.forEach((e=>e.destroy())),this.plugins.forEach((e=>e.destroy())),this.$el.remove(),r()(document).unbind("fullscreenchange",this._boundFullscreenHandler),r()(document).unbind("MSFullscreenChange",this._boundFullscreenHandler),r()(document).unbind("mozfullscreenchange",this._boundFullscreenHandler),this.stopListening()}handleFullscreenChange(){this.trigger(U.CORE_FULLSCREEN,this.isFullscreen()),this.updateSize()}handleWindowResize(e){const t=window.innerWidth>window.innerHeight?"landscape":"portrait";this._screenOrientation!==t&&(this._screenOrientation=t,this.triggerResize({width:this.el.clientWidth,height:this.el.clientHeight}),this.trigger(U.CORE_SCREEN_ORIENTATION_CHANGED,{event:e,orientation:this._screenOrientation}))}removeContainer(e){this.stopListening(e),this.containers=this.containers.filter((t=>t!==e))}setupContainer(e){this.listenTo(e,U.CONTAINER_DESTROYED,this.removeContainer),this.containers.push(e)}setupContainers(e){return e.forEach(this.setupContainer.bind(this)),this.trigger(U.CORE_CONTAINERS_CREATED),this.renderContainers(),this.activeContainer=e[0],this.render(),this.appendToParent(),this.containers}renderContainers(){this.containers.forEach((e=>this.el.appendChild(e.render().el)))}createContainer(e,t){const i=this.containerFactory.createContainer(e,t);return this.setupContainer(i),this.el.appendChild(i.render().el),i}getCurrentContainer(){return this.activeContainer}getCurrentPlayback(){return this.activePlayback}getPlaybackType(){return this.activeContainer&&this.activeContainer.getPlaybackType()}isFullscreen(){const e=E.fullscreenElement();return e&&e===this.el||e&&e===this.activePlaybackEl||this.activePlaybackEl&&this.activePlaybackEl.webkitDisplayingFullscreen||!1}toggleFullscreen(){if(this.isFullscreen()){const e=u.isiOS?this.activePlaybackEl:document;E.cancelFullscreen(e),!u.isiOS&&this.$el.removeClass("fullscreen nocursor")}else{const e=u.isiOS?this.activePlaybackEl:this.el;if(!e)return;u.isSafari||u.isiOS?E.requestFullscreen(e):E.requestFullscreen(e).then((e=>e),(e=>setTimeout((()=>{if(!this.isFullscreen())throw new ReferenceError(e)}),600))),!u.isiOS&&this.$el.addClass("fullscreen")}}onMouseMove(e){this.trigger(U.CORE_MOUSE_MOVE,e)}onMouseLeave(e){this.trigger(U.CORE_MOUSE_LEAVE,e)}configure(e){this._options=r().extend(!0,this._options,e),this.configureDomRecycler();const t=e.source||e.sources;t&&this.load(t,e.mimeType||this.options.mimeType),this.trigger(U.CORE_OPTIONS_CHANGE,e),this.containers.forEach((e=>e.configure(this.options)))}appendToParent(){const e=de.getStyleFor(Ie.toString(),{baseUrl:this.options.baseUrl}),t=de.getStyleFor(we.toString(),{baseUrl:this.options.baseUrl});this.$el.append(e[0]),this.options.includeResetStyle&&this.$el.append(t[0]),(!this.$el.parent()||!this.$el.parent().length)&&this.$el.appendTo(this.options.parentElement)}render(){this.options.width=this.options.width||this.$el.width(),this.options.height=this.options.height||this.$el.height();const e={width:this.options.width,height:this.options.height};return this.previousSize=this.currentSize=this.computedSize=e,this.updateSize(),this.enableResizeObserver(),this}}Object.assign(Pe.prototype,Y);class Oe extends V{get loader(){return this.player.loader}constructor(e){super(e.options),this.player=e}create(){return this.options.loader=this.loader,this.core=new Pe(this.options),this.addCorePlugins(),this.core.createContainers(this.options),this.core}addCorePlugins(){return this.loader.corePlugins.forEach((e=>{const t=new e(this.core);this.core.addPlugin(t),this.setupExternalInterface(t)})),this.core}setupExternalInterface(e){const t=e.getExternalInterface();for(const i in t)this.player[i]=t[i].bind(e)}}const De=/(\d+)(?:\.(\d+))?(?:\.(\d+))?/;class Ne{static parse(e=""){const t=e.match(De)||[],[,i,s,n]=t;return void 0===i?null:new Ne(i,s,n)}constructor(e,t,i){this.major=parseInt(e||0,10),this.minor=parseInt(t||0,10),this.patch=parseInt(i||0,10)}compare(e){let t=this.major-e.major;return t=t||this.minor-e.minor,t=t||this.patch-e.patch,t}inc(e="patch"){return void 0!==this[e]&&(this[e]+=1),this}satisfies(e,t){return this.compare(e)>=0&&(!t||this.compare(t)<0)}toString(){return`${this.major}.${this.minor}.${this.patch}`}}const Me=(e,t)=>e&&t?Object.entries(e).filter((([,e])=>e.type===t)).reduce(((e,[t,i])=>(e[t]=i,e)),{}):{},xe=(()=>{const e={plugins:{},playbacks:[]},t="0.5.0";return class i{static get registeredPlaybacks(){return[...e.playbacks]}static get registeredPlugins(){const{plugins:t}=e;return{core:Me(t,"core"),container:Me(t,"container")}}static checkVersionSupport(e){const{supportedVersion:i,name:s}=e.prototype;if(!i||!i.min)return N.warn("Loader",`missing version information for ${s}`),!1;const n=i.max?Ne.parse(i.max):Ne.parse(i.min).inc("minor"),r=Ne.parse(i.min);return!!Ne.parse(t).satisfies(r,n)||(N.warn("Loader",`unsupported plugin ${s}: Clappr version ${t} does not match required range [${r},${n})`),!1)}static registerPlugin(t){if(!t||!t.prototype.name)return N.warn("Loader",`missing information to register plugin: ${t}`),!1;i.checkVersionSupport(t);const s=e.plugins;if(!s)return!1;const n=s[t.prototype.name];return n&&N.warn("Loader",`overriding plugin entry: ${t.prototype.name} - ${n}`),s[t.prototype.name]=t,!0}static registerPlayback(t){if(!t||!t.prototype.name)return!1;i.checkVersionSupport(t);let{playbacks:s}=e;const n=s.findIndex((e=>e.prototype.name===t.prototype.name));if(n>=0){const e=s[n];s.splice(n,1),N.warn("Loader",`overriding playback entry: ${e.name} - ${e}`)}return e.playbacks=[t,...s],!0}static unregisterPlugin(t){if(!t)return!1;const{plugins:i}=e;return!!i[t]&&(delete i[t],!0)}static unregisterPlayback(t){if(!t)return!1;let{playbacks:i}=e;const s=i.findIndex((e=>e.prototype.name===t));return!(s<0||(i.splice(s,1),e.playbacks=i,0))}static clearPlugins(){e.plugins={}}static clearPlaybacks(){e.playbacks=[]}constructor(t=[],s=0){this.playerId=s,this.playbackPlugins=[...e.playbacks];const{core:n,container:r}=i.registeredPlugins;this.containerPlugins=Object.values(r),this.corePlugins=Object.values(n),Array.isArray(t)||this.validateExternalPluginsType(t),this.addExternalPlugins(t)}groupPluginsByType(e){return Array.isArray(e)&&(e=e.reduce((function(e,t){return e[t.type]||(e[t.type]=[]),e[t.type].push(t),e}),{})),e}removeDups(e,t=!1){const i=e.reduceRight(((e,i)=>(e[i.prototype.name]&&t||(e[i.prototype.name]&&delete e[i.prototype.name],e[i.prototype.name]=i),e)),Object.create(null)),s=[];for(let e in i)s.unshift(i[e]);return s}addExternalPlugins(e){const t="boolean"!=typeof e.loadExternalPluginsFirst||e.loadExternalPluginsFirst,s="boolean"!=typeof e.loadExternalPlaybacksFirst||e.loadExternalPlaybacksFirst;if((e=this.groupPluginsByType(e)).playback){const t=e.playback.filter((e=>(i.checkVersionSupport(e),!0)));this.playbackPlugins=s?this.removeDups(t.concat(this.playbackPlugins)):this.removeDups(this.playbackPlugins.concat(t),!0)}if(e.container){const s=e.container.filter((e=>(i.checkVersionSupport(e),!0)));this.containerPlugins=t?this.removeDups(s.concat(this.containerPlugins)):this.removeDups(this.containerPlugins.concat(s),!0)}if(e.core){const s=e.core.filter((e=>(i.checkVersionSupport(e),!0)));this.corePlugins=t?this.removeDups(s.concat(this.corePlugins)):this.removeDups(this.corePlugins.concat(s),!0)}}validateExternalPluginsType(e){["playback","container","core"].forEach((t=>{(e[t]||[]).forEach((e=>{const i="external "+e.type+" plugin on "+t+" array";if(e.type!==t)throw new ReferenceError(i)}))}))}}})();var Be=i(7439),Fe={};Fe.styleTagTransform=Te(),Fe.setAttributes=ve(),Fe.insert=ge().bind(null,"head"),Fe.domAPI=fe(),Fe.insertStyleElement=Ee(),he()(Be.A,Fe);const Ue=Be.A&&Be.A.locals?Be.A.locals:void 0,$e={mp4:["avc1.42E01E","avc1.58A01E","avc1.4D401E","avc1.64001E","mp4v.20.8","mp4v.20.240","mp4a.40.2"].map((e=>'video/mp4; codecs="'+e+', mp4a.40.2"')),ogg:['video/ogg; codecs="theora, vorbis"','video/ogg; codecs="dirac"','video/ogg; codecs="theora, speex"'],"3gpp":['video/3gpp; codecs="mp4v.20.8, samr"'],webm:['video/webm; codecs="vp8, vorbis"'],mkv:['video/x-matroska; codecs="theora, vorbis"'],m3u8:["application/x-mpegurl"]};$e.ogv=$e.ogg,$e["3gp"]=$e["3gpp"];const Ve={wav:["audio/wav"],mp3:["audio/mp3",'audio/mpeg;codecs="mp3"'],aac:['audio/mp4;codecs="mp4a.40.5"'],oga:["audio/ogg"]},Ge=Object.keys(Ve).reduce(((e,t)=>[...e,...Ve[t]]),[]),je={code:"unknown",message:"unknown"};class Ke extends W{get name(){return"html5_video"}get supportedVersion(){return{min:"0.5.0"}}get tagName(){return this.isAudioOnly?"audio":"video"}get isAudioOnly(){const e=this.options.src;let t=Ke._mimeTypesForUrl(e,Ve,this.options.mimeType);return this.options.playback&&this.options.playback.audioOnly||this.options.audioOnly||Ge.indexOf(t[0])>=0}get attributes(){return{"data-html5-video":""}}get events(){return{canplay:"_onCanPlay",canplaythrough:"_handleBufferingEvents",durationchange:"_onDurationChange",ended:"_onEnded",error:"_onError",loadeddata:"_onLoadedData",loadedmetadata:"_onLoadedMetadata",pause:"_onPause",playing:"_onPlaying",progress:"_onProgress",seeking:"_onSeeking",seeked:"_onSeeked",stalled:"_handleBufferingEvents",timeupdate:"_onTimeUpdate",waiting:"_onWaiting"}}get ended(){return this.el.ended}get buffering(){return this._isBuffering}get isLive(){return this.getPlaybackType()===W.LIVE}get dvrEnabled(){return this.getDuration()>=this._minDvrSize&&this.isLive}get minimumDVRSizeConfig(){return this.options.playback&&this.options.playback.minimumDvrSize}get isValidMinimumDVRSizeConfig(){return void 0!==this.minimumDVRSizeConfig&&"number"==typeof this.minimumDVRSizeConfig}get sourceMedia(){return this._src}constructor(...e){super(...e),this._destroyed=!1,this._loadStarted=!1,this._isBuffering=!1,this._playheadMoving=!1,this._playheadMovingTimer=null,this._stopped=!1,this._ccTrackId=-1,this._setupSrc(this.options.src),this.options.playback||(this.options.playback=this.options||{}),this.options.playback.disableContextMenu=this.options.playback.disableContextMenu||this.options.disableVideoTagContextMenu,this._minDvrSize=this.isValidMinimumDVRSizeConfig?this.minimumDVRSizeConfig:60;const t=this.options.playback,i=t.preload||(u.isSafari?"auto":this.options.preload);let s;this.options.poster&&("string"==typeof this.options.poster?s=this.options.poster:"string"==typeof this.options.poster.url&&(s=this.options.poster.url)),r().extend(!0,this.el,{muted:this.options.mute,defaultMuted:this.options.mute,loop:this.options.loop,poster:s,preload:i||"metadata",crossOrigin:t.crossOrigin,"x-webkit-playsinline":t.playInline}),(t.controls||this.options.useVideoTagDefaultControls)&&this.$el.attr("controls",""),t.playInline&&this.$el.attr({playsinline:"playsinline"}),t.crossOrigin&&this.$el.attr({crossorigin:t.crossOrigin}),this.settings={default:["seekbar"]},this.settings.left=["playpause","position","duration"],this.settings.right=["fullscreen","volume","hd-indicator"],t.externalTracks&&this._setupExternalTracks(t.externalTracks),this.options.autoPlay&&this.attemptAutoPlay()}configure(e){super.configure(e),this.el.loop=!!e.loop}attemptAutoPlay(){this.canAutoPlay(((e,t)=>{t&&N.warn(this.name,"autoplay error.",{result:e,error:t}),e&&setTimeout((()=>!this._destroyed&&this.play()),0)}))}canAutoPlay(e){if(this.options.disableCanAutoPlay)return void e(!0,null);let t={timeout:this.options.autoPlayTimeout||500,inline:this.options.playback.playInline||!1,muted:this.options.mute||!1};u.isMobile&&R.options.recycleVideo&&(t.element=this.el),C(e,t)}_setupExternalTracks(e){this._externalTracks=e.map((e=>({kind:e.kind||"subtitles",label:e.label,lang:e.lang,src:e.src})))}load(e){this._setupSrc(e)}_setupSrc(e){this.el.src!==e&&(this._ccIsSetup=!1,this.el.src=e,this._src=this.el.src)}_onLoadedMetadata(e){this._handleBufferingEvents(),this.trigger(U.PLAYBACK_LOADEDMETADATA,{duration:e.target.duration,data:e}),this._updateSettings();const t=void 0===this._options.autoSeekFromUrl||this._options.autoSeekFromUrl;this.getPlaybackType()!==W.LIVE&&t&&this._checkInitialSeek()}_onDurationChange(){this._updateSettings(),this._onTimeUpdate(),this._onProgress()}_updateSettings(){this.getPlaybackType()===W.VOD||this.getPlaybackType()===W.AOD?this.settings.left=["playpause","position","duration"]:this.settings.left=["playstop"],this.settings.seekEnabled=this.isSeekEnabled(),this.trigger(U.PLAYBACK_SETTINGSUPDATE)}isSeekEnabled(){return isFinite(this.getDuration())}getPlaybackType(){const e="audio"===this.tagName?W.AOD:W.VOD;return[0,void 0,1/0].indexOf(this.el.duration)>=0?W.LIVE:e}isHighDefinitionInUse(){return!1}consent(e){if(this.isPlaying()||this.el._consented)super.consent(e);else{let t=()=>{this.el.removeEventListener("loadedmetadata",t,!1),this.el.removeEventListener("error",t,!1),this.el._consented=!0,super.consent(e)};this.el.addEventListener("loadedmetadata",t,!1),this.el.addEventListener("error",t,!1),this.el.load()}}play(){this.trigger(U.PLAYBACK_PLAY_INTENT),this._stopped=!1,this._setupSrc(this._src),this._handleBufferingEvents();let e=this.el.play();return e&&e.catch&&e.catch((e=>N.warn(this.name,"HTML5 play failed",e))),e}pause(){this.el.pause(),this.dvrEnabled&&this._updateDvr(!0)}stop(){this.pause(),this._stopped=!0,this.el.removeAttribute("src"),this.el.load(),this._stopPlayheadMovingChecks(),this._handleBufferingEvents(),this.trigger(U.PLAYBACK_STOP)}volume(e){0===e?(this.$el.attr({muted:"true"}),this.el.muted=!0):(this.$el.attr({muted:null}),this.el.muted=!1,this.el.volume=e/100)}mute(){this.el.muted=!0}unmute(){this.el.muted=!1}isMuted(){return!0===this.el.muted||0===this.el.volume}isPlaying(){return!this.el.paused&&!this.el.ended}get isReady(){return this._isReadyState}_startPlayheadMovingChecks(){null===this._playheadMovingTimer&&(this._playheadMovingTimeOnCheck=null,this._determineIfPlayheadMoving(),this._playheadMovingTimer=setInterval(this._determineIfPlayheadMoving.bind(this),500))}_stopPlayheadMovingChecks(){null!==this._playheadMovingTimer&&(clearInterval(this._playheadMovingTimer),this._playheadMovingTimer=null,this._playheadMoving=!1)}_determineIfPlayheadMoving(){const e=this._playheadMovingTimeOnCheck,t=this.el.currentTime;this._playheadMoving=e!==t,this._playheadMovingTimeOnCheck=t,this._handleBufferingEvents()}_onWaiting(){this._loadStarted=!0,this._handleBufferingEvents()}_onLoadedData(){this._loadStarted=!0,this._handleBufferingEvents()}_onCanPlay(){this._handleBufferingEvents()}_onPlaying(){this._checkForClosedCaptions(),this._startPlayheadMovingChecks(),this._handleBufferingEvents(),this.trigger(U.PLAYBACK_PLAY)}_onPause(){this._stopPlayheadMovingChecks(),this._handleBufferingEvents(),this.trigger(U.PLAYBACK_PAUSE)}_onSeeking(){this.trigger(U.PLAYBACK_SEEK,this.getCurrentTime()),this._handleBufferingEvents()}_onSeeked(){this._handleBufferingEvents(),this.trigger(U.PLAYBACK_SEEKED)}_onEnded(){this._handleBufferingEvents(),this.trigger(U.PLAYBACK_ENDED,this.name)}_handleBufferingEvents(){const e=!this.el.ended&&!this.el.paused,t=this._loadStarted&&!this.el.ended&&!this._stopped&&(e&&!this._playheadMoving||this.el.readyState0)return this.el.seekable.end(0)-this.el.seekable.start(0);this._scheduleUpdateSettingsCheck()}return this.el.duration}_scheduleUpdateSettingsCheck(){this._updateSettingsCheckInFlight||(this._updateSettingsCheckInFlight=setTimeout((()=>{this._updateSettings(),this._updateSettingsCheckInFlight=null}),1e3))}_onTimeUpdate(){const e=this.isLive?this.getDuration():this.el.duration;this.trigger(U.PLAYBACK_TIMEUPDATE,{current:this.el.currentTime,total:e},this.name)}_onProgress(){if(!this.el.buffered.length)return;let e=[],t=0;for(let i=0;i=e[i].start&&this.el.currentTime<=e[i].end&&(t=i);const i={start:e[t].start,current:e[t].end,total:this.el.duration};this.trigger(U.PLAYBACK_PROGRESS,i,e)}_typeFor(e){let t=Ke._mimeTypesForUrl(e,$e,this.options.mimeType);return 0===t.length&&(t=Ke._mimeTypesForUrl(e,Ve,this.options.mimeType)),(t[0]||"").split(";")[0]}_ready(){this._isReadyState||(this._isReadyState=!0,this.trigger(U.PLAYBACK_READY,this.name))}_checkForClosedCaptions(){if(this.isHTML5Video&&!this._ccIsSetup){if(this.hasClosedCaptionsTracks){this.trigger(U.PLAYBACK_SUBTITLE_AVAILABLE);const e=this.closedCaptionsTrackId;this.closedCaptionsTrackId=e,this.handleTextTrackChange=this._handleTextTrackChange.bind(this),this.el.textTracks.addEventListener("change",this.handleTextTrackChange)}this._ccIsSetup=!0}}_handleTextTrackChange(){let e=this.closedCaptionsTracks.find((e=>"showing"===e.track.mode))||{id:-1};this._ccTrackId!==e.id&&(this._ccTrackId=e.id,this.trigger(U.PLAYBACK_SUBTITLE_CHANGED,{id:e.id}))}get isHTML5Video(){return this.name===Ke.prototype.name}get closedCaptionsTracks(){let e=0;return(this.el.textTracks?Array.from(this.el.textTracks):[]).filter((e=>"subtitles"===e.kind||"captions"===e.kind)).map((t=>({id:e++,name:t.label,track:t})))}get closedCaptionsTrackId(){return this._ccTrackId}set closedCaptionsTrackId(e){if(!S(e))return;let t,i=this.closedCaptionsTracks;if(-1!==e){if(t=i.find((t=>t.id===e)),!t)return;if("showing"===t.track.mode)return}i.filter((e=>"hidden"!==e.track.mode)).forEach((e=>e.track.mode="hidden")),t&&(t.track.mode="showing"),this._ccTrackId=e,this.trigger(U.PLAYBACK_SUBTITLE_CHANGED,{id:e})}get template(){return ae('<% for (var i = 0; i < tracks.length; i++) { %>\n \n<% }; %>\n')}render(){this.options.playback.disableContextMenu&&this.$el.on("contextmenu",(()=>!1)),this._externalTracks&&this._externalTracks.length>0&&this.$el.html(this.template({tracks:this._externalTracks})),this._ready();const e=de.getStyleFor(Ue.toString(),{baseUrl:this.options.baseUrl});return this.$el.append(e[0]),this}}Ke._mimeTypesForUrl=function(e,t,i){const s=(e.split("?")[0].match(/.*\.(.*)$/)||[])[1];let n=i||s&&t[s.toLowerCase()]||[];return n.constructor===Array?n:[n]},Ke._canPlay=function(e,t,i,s){let n=Ke._mimeTypesForUrl(i,t,s);const r=document.createElement(e);return!!n.filter((e=>!!r.canPlayType(e).replace(/no/,"")))[0]},Ke.canPlay=function(e,t){return Ke._canPlay("audio",Ve,e,t)||Ke._canPlay("video",$e,e,t)};var He=i(8814),Ye={};Ye.styleTagTransform=Te(),Ye.setAttributes=ve(),Ye.insert=ge().bind(null,"head"),Ye.domAPI=fe(),Ye.insertStyleElement=Ee(),he()(He.A,Ye);const We=He.A&&He.A.locals?He.A.locals:void 0;(class extends W{get name(){return"no_op"}get supportedVersion(){return{min:"0.5.0"}}get template(){return ae("\n

<%=message%>

\n")}get attributes(){return{"data-no-op":""}}constructor(...e){super(...e),this._noiseFrameNum=-1}render(){const e=this.options.playbackNotSupportedMessage||this.i18n.t("playback_not_supported"),t=de.getStyleFor(We.toString(),{baseUrl:this.options.baseUrl});this.$el.append(t[0]),this.$el.html(this.template({message:e})),this.trigger(U.PLAYBACK_READY,this.name);const i=!(!this.options.poster||!this.options.poster.showForNoOp);return!this.options.autoPlay&&i||this._animate(),this}_noise(){if(this._noiseFrameNum=(this._noiseFrameNum+1)%5,this._noiseFrameNum)return;const e=this.context.createImageData(this.context.canvas.width,this.context.canvas.height);let t;try{t=new Uint32Array(e.data.buffer)}catch(i){t=new Uint32Array(this.context.canvas.width*this.context.canvas.height*4);const s=e.data;for(let e=0;ethis._loop())))}destroy(){this._animationHandle&&(m(this._animationHandle),this._stop=!0)}_animate(){this.canvas=this.$el.find("canvas[data-no-op-canvas]")[0],this.context=this.canvas.getContext("2d"),this._loop()}}).canPlay=e=>!0,xe.registerPlugin(class extends q{get name(){return"strings"}get supportedVersion(){return{min:"0.5.0"}}constructor(e){super(e),this._initializeMessages()}t(e){const t=this._language(),i=this._messages.en;return(t&&this._messages[t]||i)[e]||i[e]||e}_language(){return this.core.options.language||_()}_initializeMessages(){this._messages=r().extend(!0,{en:{live:"live",back_to_live:"back to live",disabled:"Disabled",playback_not_supported:"Your browser does not support the playback of this video. Please try using a different browser.",default_error_title:"Could not play video.",default_error_message:"There was a problem trying to load the video."},de:{live:"Live",back_to_live:"Zurück zum Live-Video",disabled:"Deaktiviert",playback_not_supported:"Ihr Browser unterstützt das Playback Verfahren nicht. Bitte vesuchen Sie es mit einem anderen Browser.",default_error_title:"Video kann nicht abgespielt werden",default_error_message:"Es gab ein Problem beim Laden des Videos"},pt:{live:"ao vivo",back_to_live:"voltar para o ao vivo",disabled:"Desativado",playback_not_supported:"Seu navegador não supporta a reprodução deste video. Por favor, tente usar um navegador diferente.",default_error_title:"Não foi possível reproduzir o vídeo.",default_error_message:"Ocorreu um problema ao tentar carregar o vídeo."},es_am:{live:"vivo",back_to_live:"volver en vivo",disabled:"No disponible",playback_not_supported:"Su navegador no soporta la reproducción de este video. Por favor, utilice un navegador diferente.",default_error_title:"No se puede reproducir el video.",default_error_message:"Se ha producido un error al cargar el video."},es:{live:"en directo",back_to_live:"volver al directo",disabled:"No disponible",playback_not_supported:"Este navegador no es compatible para reproducir este vídeo. Utilice un navegador diferente.",default_error_title:"No se puede reproducir el vídeo.",default_error_message:"Se ha producido un problema al cargar el vídeo."},ru:{live:"прямой эфир",back_to_live:"к прямому эфиру",disabled:"Отключено",playback_not_supported:"Ваш браузер не поддерживает воспроизведение этого видео. Пожалуйста, попробуйте другой браузер."},bg:{live:"на живо",back_to_live:"Върни на живо",disabled:"Изключено",playback_not_supported:"Вашият браузър не поддържа възпроизвеждането на това видео. Моля, пробвайте с друг браузър.",default_error_title:"Видеото не може да се възпроизведе.",default_error_message:"Възникна проблем при зареждането на видеото."},fr:{live:"en direct",back_to_live:"retour au direct",disabled:"Désactivé",playback_not_supported:"Votre navigateur ne supporte pas la lecture de cette vidéo. Merci de tenter sur un autre navigateur.",default_error_title:"Impossible de lire la vidéo.",default_error_message:"Un problème est survenu lors du chargement de la vidéo."},tr:{live:"canlı",back_to_live:"canlı yayına dön",disabled:"Engelli",playback_not_supported:"Tarayıcınız bu videoyu oynatma desteğine sahip değil. Lütfen farklı bir tarayıcı ile deneyin."},et:{live:"Otseülekanne",back_to_live:"Tagasi otseülekande juurde",disabled:"Keelatud",playback_not_supported:"Teie brauser ei toeta selle video taasesitust. Proovige kasutada muud brauserit."},ar:{live:"مباشر",back_to_live:"الرجوع إلى المباشر",disabled:"معطّل",playback_not_supported:"المتصفح الذي تستخدمه لا يدعم تشغيل هذا الفيديو. الرجاء إستخدام متصفح آخر.",default_error_title:"غير قادر الى التشغيل.",default_error_message:"حدثت مشكلة أثناء تحميل الفيديو."},zh:{live:"直播",back_to_live:"返回直播",disabled:"已禁用",playback_not_supported:"您的浏览器不支持该视频的播放。请尝试使用另一个浏览器。",default_error_title:"无法播放视频。",default_error_message:"在尝试加载视频时出现了问题。"}},this.core.options.strings||{}),this._messages["de-DE"]=this._messages.de,this._messages["pt-BR"]=this._messages.pt,this._messages["en-US"]=this._messages.en,this._messages["bg-BG"]=this._messages.bg,this._messages["es-419"]=this._messages.es_am,this._messages["es-ES"]=this._messages.es,this._messages["fr-FR"]=this._messages.fr,this._messages["tr-TR"]=this._messages.tr,this._messages["et-EE"]=this._messages.et,this._messages["ar-IQ"]=this._messages.ar,this._messages["zh-CN"]=this._messages.zh}}),xe.registerPlugin(class extends q{get name(){return"sources"}get supportedVersion(){return{min:"0.5.0"}}bindEvents(){this.listenTo(this.core,U.CORE_CONTAINERS_CREATED,this.onContainersCreated)}onContainersCreated(){const e=this.core.containers.filter((e=>"no_op"!==e.playback.name))[0]||this.core.containers[0];e&&this.core.containers.forEach((t=>{t!==e&&t.destroy()}))}})},9712:function(e,t,i){"use strict";var s,n=this&&this.__extends||(s=function(e,t){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},s(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}s(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0}),t.Counter=void 0;var r=i(3271),o=i(2737),a=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.type="counter",t.counterValueMap={},t}return n(t,e),t.prototype.inc=function(e,t){if(void 0===e&&(e=1),!Number.isFinite(e))throw new Error("Invalid Counter value: ".concat(e));var i=t?(0,o.hashLabelMap)(t):"",s=this.counterValueMap[i];s?s.value+=e:(s={value:e,labelMap:t},this.counterValueMap[i]=s)},t.prototype.reset=function(){this.counterValueMap={}},t.prototype.collect=function(){for(var e,t=[],i=0,s=Object.values(this.counterValueMap);i0){var d="# HELP ".concat(a.name," ").concat(a.help,"\n"),c="# TYPE ".concat(a.name," ").concat(a.type,"\n");if(t.length>0)for(var h=0,u=l;h{"use strict";i.r(t),i.d(t,{Plugin:()=>c,Prometheus:()=>c});var s=i(9371),n=i(7204),r=i(377),o=i(6121),a=i(8081),l=i(6653),d=i(1162);class c extends s.rV{constructor(){super(...arguments),this.started=!1,this.adStarted=!1,this.stopMetricsPush=()=>{clearInterval(c.pushInterval),delete c.pushInterval,(0,n.VC)()},this.onBufferfull=()=>{this.bufferingStartTime&&(Date.now()-this.bufferingStartTime>c.BUFFERING_TIMEOUT&&n.Lt.inc(1,{resolution:this.resolution}),delete this.bufferingStartTime)}}get name(){return"prometheus"}get supportedVersion(){return{min:"0.5.0"}}get provider(){return this.options.provider}get advertisement(){return this.core.getPlugin("advertisement")}get resolution(){var e;const{activePlayback:t}=this.core,i=t.el.offsetWidth0&&i.filter((({name:e})=>e.includes("seg-1"))).map((({duration:e,fetchStart:t,responseEnd:i})=>Math.round(e||i-t))),r=Array.isArray(s)&&s.length>0?s[s.length-1]:this.firstChunkLoadingTime;n.t9.observe(r/1e3,{resolution:this.resolution})}}onLevelSwitch(e){const{activePlayback:t}=this.core,[i]=t.levels.filter((t=>t.id===(null==e?void 0:e.level)));this.currentLevel=i}onLoadingError(e){var t;e.level===s.Mk.Levels.FATAL&&((null==e?void 0:e.code)&&c.LOADING_ERRORS.includes(e.code)&&n.bN.inc(1,{errorCode:null!==(t=e.code)&&void 0!==t?t:d.n4}),this.stopMetricsPush())}onPlay(){this.started=!0}onBuffering(){var e;(null===(e=this.core.activeContainer)||void 0===e?void 0:e.getCurrentTime())>0&&(this.bufferingStartTime=Date.now())}onError(e){var t;e.level===s.Mk.Levels.FATAL&&(this.started||n.bN.inc(1,{errorCode:null!==(t=e.code)&&void 0!==t?t:d.n4}),this.stopMetricsPush())}onAdLoading(e){n.D0.inc(1,{adPlayback:e.adPlayback,adType:e.adType,adBlockType:e.blockType}),this.adStarted=!1,delete this.playStartTime}onAdStarted(){this.adStarted=!0}onAdViewable(e){var t;n.XG.inc(1,{adPlayback:e.adPlayback,adType:e.adType,adBlockType:e.blockType,adSystem:null!==(t=e.adSystem)&&void 0!==t?t:d.n4,visible:"1"})}onAdNotViewable(e){var t;n.XG.inc(1,{adPlayback:e.adPlayback,adType:e.adType,adBlockType:e.blockType,adSystem:null!==(t=e.adSystem)&&void 0!==t?t:d.n4,visible:"0"})}onAdError(e){var t,i,s,r,o,a,l;!this.adStarted&&c.AD_NOT_STARTED_ERRORS.includes(null===(t=null==e?void 0:e.raw)||void 0===t?void 0:t.code)&&n.WH.inc(1,{adPlayback:null===(i=null==e?void 0:e.raw)||void 0===i?void 0:i.adPlayback,adType:null===(s=null==e?void 0:e.raw)||void 0===s?void 0:s.adType,adBlockType:null===(r=null==e?void 0:e.raw)||void 0===r?void 0:r.blockType,adSystem:null!==(a=null===(o=null==e?void 0:e.raw)||void 0===o?void 0:o.adSystem)&&void 0!==a?a:d.n4,errorCode:null!==(l=null==e?void 0:e.code)&&void 0!==l?l:d.n4})}}c.BUFFERING_TIMEOUT=500,c.METRICS_PUSH_INTERVAL=3e4,c.LOADING_ERRORS=[a.I.UNKNOWN_ERROR.code,a.I.NOT_RESPOND.code,a.I.TIMEOUT.code,a.I.INVALID_RESPONSE.code],c.AUTO_PLAY_ERRORS=["notAllowed","notAllowedForSearchBot"],c.AD_NOT_STARTED_ERRORS=[void 0,l.AdErrorCode.VAST_UNEXPECTED_AD_TYPE,l.AdErrorCode.VAST_UNEXPECTED_LINEARITY,l.AdErrorCode.VAST_UNEXPECTED_DURATION_ERROR,l.AdErrorCode.VAST_UNEXPECTED_MEDIA_FILE,l.AdErrorCode.VAST_UNEXPECTED_AD_SOURCE,l.AdErrorCode.VAST_WRAPPER_ERROR,l.AdErrorCode.VIDEO_PLAY_ERROR,l.AdErrorCode.VAST_MEDIA_FILE_NOT_FOUND,l.AdErrorCode.VAST_MEDIA_LOAD_TIMEOUT,l.AdErrorCode.VAST_LINEAR_ASSET_MISMATCH,l.AdErrorCode.VAST_PROBLEM_DISPLAYING_MEDIA_FILE,l.AdErrorCode.VAST_NONLINEAR_PLAYING_FAILED,l.AdErrorCode.VAST_NONLINEAR_DIMENSIONS_ERROR,l.AdErrorCode.VAST_NONLINEAR_LOADING_FAILED,l.AdErrorCode.VAST_NONLINEAR_ASSET_MISMATCH,l.AdErrorCode.UNKNOWN_ERROR,l.AdErrorCode.VPAID_ERROR],c.readySent=!1,c.autoPlaySent=!1},9836:(e,t,i)=>{"use strict";i.d(t,{Q:()=>a,t:()=>s.tG});var s=i(9371),n=i(377),r=i(6121);const o=[r.s.CORE_MOUSE_MOVE,r.s.CORE_MOUSE_LEAVE,r.s.CONTAINER_MOUSE_ENTER,r.s.CONTAINER_MOUSE_LEAVE,r.s.CONTAINER_MEDIACONTROL_SHOW,r.s.MEDIACONTROL_SHOW,r.s.MEDIACONTROL_MOUSEMOVE_SEEKBAR,r.s.MEDIACONTROL_MOUSELEAVE_SEEKBAR,r.s.ADVERTISEMENT_PROGRESS],a=()=>{(0,n._o)()&&(s.tG.setLevel(-1),s.tG.getInstance().EXCLUDE_LIST.push(...o),s.tG.debug("RamblerPlayer","1.147.1"))}},9987:(e,t,i)=>{"use strict";i.d(t,{ez:()=>c,gD:()=>o,n_:()=>a,yP:()=>h});var s=i(377),n=i(5542);const r="color: #0000ff; font-weight: bold; font-size: 13px;",o=(e,t)=>{var i;if((0,s._o)()&&console.log("%c[debug][init]",r,e,t),!(0,s.yz)()){if(!window.ym)try{n=window,o=document,a="script",n[l="ym"]=n[l]||function(){(n[l].a=n[l].a||[]).push(arguments)},n[l].l=1*new Date,d=o.createElement(a),c=o.getElementsByTagName(a)[0],d.async=1,d.src="https://mc.yandex.ru/metrika/tag.js",c.parentNode.insertBefore(d,c)}catch(e){}var n,o,a,l,d,c;null===(i=window.ym)||void 0===i||i.call(window,e,"init",t)}},a=(e,t,i)=>{var n;(0,s._o)()&&console.log("%c[debug][reachGoal]",r,t,i),(0,s.yz)()||null===(n=window.ym)||void 0===n||n.call(window,e,"reachGoal",...[t,i].filter(Boolean))};let l=null;const d={},c=(e={})=>{if((0,s._o)()&&console.log("%c[debug][top100]",r,e.project),(0,s.yz)())return;const{project:t}=e;d.hasOwnProperty(t)||(d[t]=(async()=>{try{if(!window.top100){l||(l=(0,n.k0)("//st.top100.ru/top100/top100.js"));try{await l}catch(e){throw l=null,e}}const i=new window.top100(Object.assign(Object.assign({},e),{checkInit:!0})),s=`initKraken${t}`;return await new Promise((e=>{const t=()=>{document.removeEventListener(s,t),e(null)};document.addEventListener(s,t)})),i}catch(e){throw delete d[t],e}})())},h=async(e,t)=>{if((0,s._o)()&&console.log("%c[debug][sendCustomVars]",r,t),!(0,s.yz)())try{const i=await d[e];null==i||i.sendCustomVars(t)}catch(e){}}}},s={};function n(e){var t=s[e];if(void 0!==t)return t.exports;var r=s[e]={id:e,loaded:!1,exports:{}};return i[e].call(r.exports,r,r.exports,n),r.loaded=!0,r.exports}n.m=i,n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},n.f={},n.e=e=>Promise.all(Object.keys(n.f).reduce(((t,i)=>(n.f[i](e,t),t)),[])),n.u=e=>e+"-"+{158:"2eb57b0a76c6dd016efa",169:"b9048a291f9f5dac6647",426:"a1874943fb7b3fc6cf4e",443:"3ed5a234baf8af5d8076",635:"eebe8ffaf48a04eca617",738:"619e47c2f8904fe5b88a",1070:"f019cf3e891ed6fb551b",1174:"4e63008d06e83d310317",1185:"a8fbcdc9f5f485c6b56b",1237:"a85099b14d98adf8efde",1301:"645b1c6225762a185fd4",1363:"8ebafc6f78121d156c9d",1760:"d3367a2b81afeab0a757",1793:"329bbc1555016c8fd908",1886:"7118fe747dc632f1d1cd",1915:"02b0ac7bc0f77dd6fcb8",1997:"f4e058a75aaa1e196fcb",2178:"e2e864f433603b17fdc0",2244:"54209cf0faf1039ba862",2597:"69eb312c2214065ecbb9",2763:"85dc7715885d8889406a",2907:"67f8ba725e2031b000c6",3201:"ec4e133e40322cb93a79",3207:"e40a069f085b6d8a8fe7",3436:"6e24d6bad2854f5825a9",3462:"c102f8b832f54f92319a",3477:"7decfb6b5b11d9904150",3502:"bb0028b3633c515c13cc",3689:"4ce0529ab2a1612ed6af",3721:"41b1323150695150c268",3749:"cdb85f692ff568ac0d2e",3883:"b7f166785441a81cba39",3973:"a7e6d3f90843b5ef3b10",4052:"8f6be2594078ddd5c91d",4480:"414a614efa4505f24fb9",4570:"d7d5f1b4aacbfc027f82",4655:"714bee3ab2349af55830",4671:"70cad8e40bb1a52dbbc6",4683:"a34040599fef5074608e",4746:"3f03f68585bed45c808d",4929:"7d195e552e2bf7093ae0",5015:"fb960f64e49d433d3bff",5327:"3ed15e885c2ccd8b9cf8",5488:"3138710449584ad460a1",5518:"23878d4cbee2212fd3ca",5645:"1034f3577a17978d5cdf",6002:"9a4d369e6cc96680c998",6316:"5ab7fd7c13e7a8b97019",6453:"59f5dc233127aa293674",6530:"02fd44c30510e4f0e5c1",6639:"31087cc2d2b1f39e1171",6684:"202323f8d1e30e2f7dc5",6689:"f78ccb411fdab3a80f4f",6747:"0450987d8acaba7dcd4b",6947:"63e9089f76b0946a1546",6969:"9c44aa45d4868ea3caa5",7027:"d528e75d06d0cb9131ac",7156:"bb51d104a00413492bc4",7233:"0244c728c488f1264a98",7354:"cd80f1b5f2ae03922630",7432:"900b6163596edb5ff261",7441:"fb5830fc2792e301597b",7547:"496c24edc0f663600569",7658:"9ad69f4242feeda67818",7885:"889c5fc0804ba24afcd0",7984:"21cf52c7d99434e1ae15",8573:"1f910199445fa5467fbd",8864:"a3fe3a3a36a18df797d6",9071:"4b974ddefded00694b41",9139:"907dad92088700e73588",9349:"1a14ea6222bbba37510b",9354:"488f6752da0e4c214d26",9408:"d67f416d930be779be4c",9600:"9b2cff36a0f22095c000",9681:"94f749116d011b7d6739",9778:"a821c6af24f9e79ac246",9897:"c84cdf1428a3394bd6d8",9988:"adaf5b572091f588a93a"}[e]+".js",n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),e={},t="@rambler-vp/player:",n.l=(i,s,r,o)=>{if(e[i])e[i].push(s);else{var a,l;if(void 0!==r)for(var d=document.getElementsByTagName("script"),c=0;c{a.onerror=a.onload=null,clearTimeout(f);var n=e[i];if(delete e[i],a.parentNode&&a.parentNode.removeChild(a),n&&n.forEach((e=>e(s))),t)return t(s)},f=setTimeout(u.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=u.bind(null,a.onerror),a.onload=u.bind(null,a.onload),l&&document.head.appendChild(a)}},n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),n.p="https://vp.rambler.ru/player/1.147.1/",(()=>{n.b=document.baseURI||self.location.href;var e={1088:0};n.f.j=(t,i)=>{var s=n.o(e,t)?e[t]:void 0;if(0!==s)if(s)i.push(s[2]);else{var r=new Promise(((i,n)=>s=e[t]=[i,n]));i.push(s[2]=r);var o=n.p+n.u(t),a=new Error;n.l(o,(i=>{if(n.o(e,t)&&(0!==(s=e[t])&&(e[t]=void 0),s)){var r=i&&("load"===i.type?"missing":i.type),o=i&&i.target&&i.target.src;a.message="Loading chunk "+t+" failed.\n("+r+": "+o+")",a.name="ChunkLoadError",a.type=r,a.request=o,s[1](a)}}),"chunk-"+t,t)}};var t=(t,i)=>{var s,r,[o,a,l]=i,d=0;if(o.some((t=>0!==e[t]))){for(s in a)n.o(a,s)&&(n.m[s]=a[s]);l&&l(n)}for(t&&t(i);d{"use strict";var e={};n.r(e),n.d(e,{en:()=>ed,ru:()=>td});var t={};n.r(t),n.d(t,{advertisement:()=>nd,aiAd:()=>od,clickToPause:()=>ad,comscore:()=>vd,docking:()=>Sd,eventsReport:()=>_d,levelSelector:()=>Nd,likes:()=>Id,liveStatus:()=>Md,mediaControl:()=>sd,mediascope:()=>Od,multiplayer:()=>hd,notifier:()=>wd,playbackRate:()=>pd,poster:()=>Td,prometheus:()=>Cd,promoButton:()=>Ld,recommender:()=>Rd,replay:()=>dd,settingsMenu:()=>kd,share:()=>Ad,subtitles:()=>cd,suggest:()=>Ed,threeSixtyViewer:()=>ud,thumbnails:()=>yd,timeToAdvertisement:()=>rd,tns:()=>md,unmute:()=>fd,videoBackdrop:()=>Dd,viewport:()=>bd,watchNext:()=>Pd,watermark:()=>ld,yametrika:()=>gd});var i={};n.r(i),n.d(i,{isSupports:()=>oc,registerIFrame:()=>ac});var s={};n.r(s),n.d(s,{isSupports:()=>dc,registerIFrame:()=>cc});var r={};n.r(r),n.d(r,{isSupports:()=>fc,registerIFrame:()=>pc});var o,a=[],l="ResizeObserver loop completed with undelivered notifications.";!function(e){e.BORDER_BOX="border-box",e.CONTENT_BOX="content-box",e.DEVICE_PIXEL_CONTENT_BOX="device-pixel-content-box"}(o||(o={}));var d,c=function(e){return Object.freeze(e)},h=function(e,t){this.inlineSize=e,this.blockSize=t,c(this)},u=function(){function e(e,t,i,s){return this.x=e,this.y=t,this.width=i,this.height=s,this.top=this.y,this.left=this.x,this.bottom=this.top+this.height,this.right=this.left+this.width,c(this)}return e.prototype.toJSON=function(){var e=this;return{x:e.x,y:e.y,top:e.top,right:e.right,bottom:e.bottom,left:e.left,width:e.width,height:e.height}},e.fromRect=function(t){return new e(t.x,t.y,t.width,t.height)},e}(),f=function(e){return e instanceof SVGElement&&"getBBox"in e},p=function(e){if(f(e)){var t=e.getBBox(),i=t.width,s=t.height;return!i&&!s}var n=e,r=n.offsetWidth,o=n.offsetHeight;return!(r||o||e.getClientRects().length)},g=function(e){var t;if(e instanceof Element)return!0;var i=null===(t=null==e?void 0:e.ownerDocument)||void 0===t?void 0:t.defaultView;return!!(i&&e instanceof i.Element)},m="undefined"!=typeof window?window:{},v=new WeakMap,A=/auto|scroll/,E=/^tb|vertical/,y=/msie|trident/i.test(m.navigator&&m.navigator.userAgent),T=function(e){return parseFloat(e||"0")},b=function(e,t,i){return void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=!1),new h((i?t:e)||0,(i?e:t)||0)},S=c({devicePixelContentBoxSize:b(),borderBoxSize:b(),contentBoxSize:b(),contentRect:new u(0,0,0,0)}),_=function(e,t){if(void 0===t&&(t=!1),v.has(e)&&!t)return v.get(e);if(p(e))return v.set(e,S),S;var i=getComputedStyle(e),s=f(e)&&e.ownerSVGElement&&e.getBBox(),n=!y&&"border-box"===i.boxSizing,r=E.test(i.writingMode||""),o=!s&&A.test(i.overflowY||""),a=!s&&A.test(i.overflowX||""),l=s?0:T(i.paddingTop),d=s?0:T(i.paddingRight),h=s?0:T(i.paddingBottom),g=s?0:T(i.paddingLeft),m=s?0:T(i.borderTopWidth),_=s?0:T(i.borderRightWidth),C=s?0:T(i.borderBottomWidth),R=g+d,L=l+h,I=(s?0:T(i.borderLeftWidth))+_,k=m+C,w=a?e.offsetHeight-k-e.clientHeight:0,P=o?e.offsetWidth-I-e.clientWidth:0,O=n?R+I:0,D=n?L+k:0,N=s?s.width:T(i.width)-O-P,M=s?s.height:T(i.height)-D-w,x=N+R+P+I,B=M+L+w+k,F=c({devicePixelContentBoxSize:b(Math.round(N*devicePixelRatio),Math.round(M*devicePixelRatio),r),borderBoxSize:b(x,B,r),contentBoxSize:b(N,M,r),contentRect:new u(g,l,N,M)});return v.set(e,F),F},C=function(e,t,i){var s=_(e,i),n=s.borderBoxSize,r=s.contentBoxSize,a=s.devicePixelContentBoxSize;switch(t){case o.DEVICE_PIXEL_CONTENT_BOX:return a;case o.BORDER_BOX:return n;default:return r}},R=function(e){var t=_(e);this.target=e,this.contentRect=t.contentRect,this.borderBoxSize=c([t.borderBoxSize]),this.contentBoxSize=c([t.contentBoxSize]),this.devicePixelContentBoxSize=c([t.devicePixelContentBoxSize])},L=function(e){if(p(e))return 1/0;for(var t=0,i=e.parentNode;i;)t+=1,i=i.parentNode;return t},I=function(){var e=1/0,t=[];a.forEach((function(i){if(0!==i.activeTargets.length){var s=[];i.activeTargets.forEach((function(t){var i=new R(t.target),n=L(t.target);s.push(i),t.lastReportedSize=C(t.target,t.observedBox),ne?t.activeTargets.push(i):t.skippedTargets.push(i))}))}))},w=[],P=0,O={attributes:!0,characterData:!0,childList:!0,subtree:!0},D=["resize","load","transitionend","animationend","animationstart","animationiteration","keyup","keydown","mouseup","mousedown","mouseover","mouseout","blur","focus"],N=function(e){return void 0===e&&(e=0),Date.now()+e},M=!1,x=new(function(){function e(){var e=this;this.stopped=!0,this.listener=function(){return e.schedule()}}return e.prototype.run=function(e){var t=this;if(void 0===e&&(e=250),!M){M=!0;var i,s=N(e);i=function(){var i=!1;try{i=function(){var e,t=0;for(k(t);a.some((function(e){return e.activeTargets.length>0}));)t=I(),k(t);return a.some((function(e){return e.skippedTargets.length>0}))&&("function"==typeof ErrorEvent?e=new ErrorEvent("error",{message:l}):((e=document.createEvent("Event")).initEvent("error",!1,!1),e.message=l),window.dispatchEvent(e)),t>0}()}finally{if(M=!1,e=s-N(),!P)return;i?t.run(1e3):e>0?t.run(e):t.start()}},function(e){if(!d){var t=0,i=document.createTextNode("");new MutationObserver((function(){return w.splice(0).forEach((function(e){return e()}))})).observe(i,{characterData:!0}),d=function(){i.textContent="".concat(t?t--:t++)}}w.push(e),d()}((function(){requestAnimationFrame(i)}))}},e.prototype.schedule=function(){this.stop(),this.run()},e.prototype.observe=function(){var e=this,t=function(){return e.observer&&e.observer.observe(document.body,O)};document.body?t():m.addEventListener("DOMContentLoaded",t)},e.prototype.start=function(){var e=this;this.stopped&&(this.stopped=!1,this.observer=new MutationObserver(this.listener),this.observe(),D.forEach((function(t){return m.addEventListener(t,e.listener,!0)})))},e.prototype.stop=function(){var e=this;this.stopped||(this.observer&&this.observer.disconnect(),D.forEach((function(t){return m.removeEventListener(t,e.listener,!0)})),this.stopped=!0)},e}()),B=function(e){!P&&e>0&&x.start(),!(P+=e)&&x.stop()},F=function(){function e(e,t){this.target=e,this.observedBox=t||o.CONTENT_BOX,this.lastReportedSize={inlineSize:0,blockSize:0}}return e.prototype.isActive=function(){var e,t=C(this.target,this.observedBox,!0);return e=this.target,f(e)||function(e){switch(e.tagName){case"INPUT":if("image"!==e.type)break;case"VIDEO":case"AUDIO":case"EMBED":case"OBJECT":case"CANVAS":case"IFRAME":case"IMG":return!0}return!1}(e)||"inline"!==getComputedStyle(e).display||(this.lastReportedSize=t),this.lastReportedSize.inlineSize!==t.inlineSize||this.lastReportedSize.blockSize!==t.blockSize},e}(),U=function(e,t){this.activeTargets=[],this.skippedTargets=[],this.observationTargets=[],this.observer=e,this.callback=t},$=new WeakMap,V=function(e,t){for(var i=0;i=0&&(n&&a.splice(a.indexOf(i),1),i.observationTargets.splice(s,1),B(-1))},e.disconnect=function(e){var t=this,i=$.get(e);i.observationTargets.slice().forEach((function(i){return t.unobserve(e,i.target)})),i.activeTargets.splice(0,i.activeTargets.length)},e}(),j=function(){function e(e){if(0===arguments.length)throw new TypeError("Failed to construct 'ResizeObserver': 1 argument required, but only 0 present.");if("function"!=typeof e)throw new TypeError("Failed to construct 'ResizeObserver': The callback provided as parameter 1 is not a function.");G.connect(this,e)}return e.prototype.observe=function(e,t){if(0===arguments.length)throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': 1 argument required, but only 0 present.");if(!g(e))throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': parameter 1 is not of type 'Element");G.observe(this,e,t)},e.prototype.unobserve=function(e){if(0===arguments.length)throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': 1 argument required, but only 0 present.");if(!g(e))throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': parameter 1 is not of type 'Element");G.unobserve(this,e)},e.prototype.disconnect=function(){G.disconnect(this)},e.toString=function(){return"function ResizeObserver () { [polyfill code] }"},e}(),K=n(2452),H=n(377),Y=n(6413),W=n(9836),z=n(9200),q=n(5542);const X=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Q=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=Z},Z=Number.MAX_SAFE_INTEGER||9007199254740991;let J=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),ee=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),te=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});var ie="manifest",se="level",ne="audioTrack",re="subtitleTrack",oe="main",ae="audio",le="subtitle";class de{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 ce{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 de(e),this.fast_=new de(t),this.defaultTTFB_=s,this.ttfb_=new de(e)}update(e,t){const{slow_:i,fast_:s,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new de(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new de(t,s.getEstimate(),s.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new de(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){const i=(e=Math.max(e,this.minDelayMs_))/1e3,s=8*t/i;this.fast_.sample(i,s),this.slow_.sample(i,s)}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_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function he(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var s=i.call(e,t);if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function ue(){return ue=Object.assign?Object.assign.bind():function(e){for(var t=1;t`):me}(e,i)}const ye=Ae(),Te=ye;function be(e=!0){if("undefined"!=typeof self)return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Se(e,t){const i=Object.keys(e),s=Object.keys(t),n=i.length,r=s.length;return!n||!r||n===r&&!i.some((e=>-1===s.indexOf(e)))}function _e(e,t=!1){if("undefined"!=typeof TextDecoder){const i=new TextDecoder("utf-8").decode(e);if(t){const e=i.indexOf("\0");return-1!==e?i.substring(0,e):i}return i.replace(/\0/g,"")}const i=e.length;let s,n,r,o="",a=0;for(;a>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:n=e[a++],o+=String.fromCharCode((31&s)<<6|63&n);break;case 14:n=e[a++],r=e[a++],o+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&r)}}return o}const Ce=function(e){let t="";for(let i=0;i1||1===t&&this.levelkeys[e[0]].encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){X(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return $e(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,i,s,n,r=!1){const{elementaryStreams:o}=this,a=o[e];a?(a.startPTS=Math.min(a.startPTS,t),a.endPTS=Math.max(a.endPTS,i),a.startDTS=Math.min(a.startDTS,s),a.endDTS=Math.max(a.endDTS,n)):o[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:n,partial:r}}}class Ge extends Ue{constructor(e,t,i,s,n){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.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 r=e.enumeratedString("BYTERANGE");r&&this.setByteRange(r,n),n&&(this.fragOffset=n.fragOffset+n.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function je(e,t){const i=Object.getPrototypeOf(e);if(i){return Object.getOwnPropertyDescriptor(i,t)||je(i,t)}}const Ke=Math.pow(2,32)-1,He=[].push,Ye={video:1,audio:2,id3:3,text:4};function We(e){return String.fromCharCode.apply(null,e)}function ze(e,t){const i=e[t]<<8|e[t+1];return i<0?65536+i:i}function qe(e,t){const i=Qe(e,t);return i<0?4294967296+i:i}function Xe(e,t){let i=qe(e,t);return i*=Math.pow(2,32),i+=qe(e,t+4),i}function Qe(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Ze(e,t,i){e[t]=i>>24,e[t+1]=i>>16&255,e[t+2]=i>>8&255,e[t+3]=255&i}function Je(e,t){const i=[];if(!t.length)return i;const s=e.byteLength;for(let n=0;n1?n+r:s;if(We(e.subarray(n+4,n+8))===t[0])if(1===t.length)i.push(e.subarray(n+8,o));else{const s=Je(e.subarray(n+8,o),t.slice(1));s.length&&He.apply(i,s)}n=o}return i}function et(e){const t=[],i=e[0];let s=8;const n=qe(e,s);s+=4;let r=0,o=0;0===i?(r=qe(e,s),o=qe(e,s+4),s+=8):(r=Xe(e,s),o=Xe(e,s+8),s+=16),s+=2;let a=e.length+o;const l=ze(e,s);s+=2;for(let i=0;i>>31)return Te.warn("SIDX has hierarchical references (not supported)"),null;const l=qe(e,i);i+=4,t.push({referenceSize:o,subsegmentDuration:l,info:{duration:l/n,start:a,end:a+o-1}}),a+=o,i+=4,s=i}return{earliestPresentationTime:r,timescale:n,version:i,referencesCount:l,references:t}}function tt(e){const t=[],i=Je(e,["moov","trak"]);for(let e=0;e{const i=qe(e,4),s=t[i];s&&(s.default={duration:qe(e,12),flags:qe(e,20)})})),t}function it(e){const t=e.subarray(8),i=t.subarray(86),s=We(t.subarray(4,8));let n,r=s;const o="enca"===s||"encv"===s;if(o){const e=Je(t,[s])[0];Je(e.subarray("enca"===s?28:78),["sinf"]).forEach((e=>{const t=Je(e,["schm"])[0];if(t){const i=We(t.subarray(4,8));if("cbcs"===i||"cenc"===i){const t=Je(e,["frma"])[0];t&&(r=We(t))}}}))}const a=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const e=Je(i,["avcC"])[0];e&&e.length>3&&(r+="."+rt(e[1])+rt(e[2])+rt(e[3]),n=st("avc1"===a?"dva1":"dvav",i));break}case"mp4a":{const e=Je(t,[s])[0],i=Je(e.subarray(28),["esds"])[0];if(i&&i.length>7){let e=4;if(3!==i[e++])break;e=nt(i,e),e+=2;const t=i[e++];if(128&t&&(e+=2),64&t&&(e+=i[e++]),4!==i[e++])break;e=nt(i,e);const s=i[e++];if(64!==s)break;if(r+="."+rt(s),e+=12,5!==i[e++])break;e=nt(i,e);const n=i[e++];let o=(248&n)>>3;31===o&&(o+=1+((7&n)<<3)+((224&i[e])>>5)),r+="."+o}break}case"hvc1":case"hev1":{const e=Je(i,["hvcC"])[0];if(e&&e.length>12){const t=e[1],i=["","A","B","C"][t>>6],s=31&t,n=qe(e,2),o=(32&t)>>5?"H":"L",a=e[12],l=e.subarray(6,12);r+="."+i+s,r+="."+n.toString(16).toUpperCase(),r+="."+o+a;let d="";for(let e=l.length;e--;){const t=l[e];(t||d)&&(d="."+t.toString(16).toUpperCase()+d)}r+=d}n=st("hev1"==a?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":r=st(r,i)||r;break;case"vp09":{const e=Je(i,["vpcC"])[0];if(e&&e.length>6){const t=e[4],i=e[5],s=e[6]>>4&15;r+="."+ot(t)+"."+ot(i)+"."+ot(s)}break}case"av01":{const e=Je(i,["av1C"])[0];if(e&&e.length>2){const t=e[1]>>>5,s=31&e[1],o=e[2]>>>7?"H":"M",a=(64&e[2])>>6,l=(32&e[2])>>5,d=2===t&&a?l?12:10:a?10:8,c=(16&e[2])>>4,h=(8&e[2])>>3,u=(4&e[2])>>2,f=3&e[2],p=1,g=1,m=1,v=0;r+="."+t+"."+ot(s)+o+"."+ot(d)+"."+c+"."+h+u+f+"."+ot(p)+"."+ot(g)+"."+ot(m)+"."+v,n=st("dav1",i)}break}}return{codec:r,encrypted:o,supplemental:n}}function st(e,t){const i=Je(t,["dvvC"]),s=i.length?i[0]:Je(t,["dvcC"])[0];if(s){const t=s[2]>>1&127,i=s[2]<<5&32|s[3]>>3&31;return e+"."+ot(t)+"."+ot(i)}}function nt(e,t){const i=t+5;for(;128&e[t++]&&t{const l=a.byteOffset-8;Je(a,["traf"]).map((a=>{const d=Je(a,["tfdt"]).map((e=>{const t=e[0];let i=qe(e,4);return 1===t&&(i*=Math.pow(2,32),i+=qe(e,8)),i/n}))[0];return void 0!==d&&(e=d),Je(a,["tfhd"]).map((d=>{const c=qe(d,4),h=16777215&qe(d,0);let u=0;const f=!!(16&h);let p=0;const g=!!(32&h);let m=8;c===r&&(!!(1&h)&&(m+=8),!!(2&h)&&(m+=4),!!(8&h)&&(u=qe(d,m),m+=4),f&&(p=qe(d,m),m+=4),g&&(m+=4),"video"===t.type&&(o=ht(t.codec)),Je(a,["trun"]).map((r=>{const a=r[0],d=16777215&qe(r,0),c=!!(1&d);let h=0;const f=!!(4&d),g=!!(256&d);let m=0;const v=!!(512&d);let A=0;const E=!!(1024&d),y=!!(2048&d);let T=0;const b=qe(r,4);let S=8;c&&(h=qe(r,S),S+=4),f&&(S+=4);let _=h+l;for(let l=0;l>1&63;return 39===e||40===e}return 6==(31&t)}function ft(e,t,i,s){const n=pt(e);let r=0;r+=t;let o=0,a=0,l=0;for(;r=n.length)break;l=n[r++],o+=l}while(255===l);a=0;do{if(r>=n.length)break;l=n[r++],a+=l}while(255===l);const e=n.length-r;let t=r;if(ae){Te.error(`Malformed SEI payload. ${a} is too small, only ${e} bytes left to parse.`);break}if(4===o){if(181===n[t++]){const e=ze(n,t);if(t+=2,49===e){const e=qe(n,t);if(t+=4,1195456820===e){const e=n[t++];if(3===e){const r=n[t++],a=64&r,l=a?2+3*(31&r):0,d=new Uint8Array(l);if(a){d[0]=r;for(let e=1;e16){const e=[];for(let i=0;i<16;i++){const s=n[t++].toString(16);e.push(1==s.length?"0"+s:s),3!==i&&5!==i&&7!==i&&9!==i||e.push("-")}const r=a-16,l=new Uint8Array(r);for(let e=0;e>>24;if(0!==n&&1!==n)return{offset:i,size:t};const r=e.buffer,o=Ce(new Uint8Array(r,i+12,16)),a=e.getUint32(28);let l=null,d=null;if(0===n){if(t-32/\(Windows.+Firefox\//i.test(navigator.userAgent),vt={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function At(e,t){const i=vt[t];return!!i&&!!i[e.slice(0,4)]}function Et(e,t,i=!0){return!e.split(",").some((e=>!yt(e,t,i)))}function yt(e,t,i=!0){var s;const n=be(i);return null!=(s=null==n?void 0:n.isTypeSupported(Tt(e,t)))&&s}function Tt(e,t){return`${t}/mp4;codecs=${e}`}function bt(e){if(e){const t=e.substring(0,4);return vt.video[t]}return 2}function St(e){const t=mt();return e.split(",").reduce(((e,i)=>{const s=t&&ht(i)?9:vt.video[i];return s?(2*s+e)/(e?3:2):(vt.audio[i]+e)/(e?2:1)}),0)}const _t={},Ct=/flac|opus|mp4a\.40\.34/i;function Rt(e,t=!0){return e.replace(Ct,(e=>function(e,t=!0){if(_t[e])return _t[e];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let n=0;n4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e)))return e;if(t){const i=t.split(",");if(i.length>1){if(e)for(let t=i.length;t--;)if(i[t].substring(0,4)===e.substring(0,4))return i[t];return i[0]}}return t||e}function It(e){if(e.startsWith("av01.")){const t=e.split("."),i=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=i[e-4];return t.join(".")}return e}function kt(e){const t=be(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function wt(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Pt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Ot(e,t){return{supported:!1,configurations:t,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:e}}const Dt={};function Nt(e,t,i,s,n,r){const o=e.audioCodec?e.audioGroups:null,a=null==r?void 0:r.audioCodec,l=null==r?void 0:r.channels,d=l?parseInt(l):a?1/0:2;let c=null;if(null!=o&&o.length)try{c=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce(((e,i)=>{if(i){const s=t.groups[i];if(!s)throw new Error(`Audio track group ${i} not found`);Object.keys(s.channels).forEach((t=>{e[t]=(e[t]||0)+s.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==e.videoCodec&&(e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(s,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(n,8e6))||!!c&&X(d)&&Object.keys(c).some((e=>parseInt(e)>d))}function Mt(e,t,i){const s=e.videoCodec,n=e.audioCodec;if(!s&&!n||!i)return Promise.resolve(Pt);const r=[];if(s){const t={width:e.width,height:e.height,bitrate:Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)),framerate:e.frameRate||30},i=e.videoRange;"SDR"!==i&&(t.transferFunction=i.toLowerCase());const n=s.split(","),o=navigator.userAgent;if(n.some((e=>ht(e)))&&mt())return Promise.resolve(Ot(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: (${o})`),r));r.push.apply(r,n.map((e=>({type:"media-source",video:pe(pe({},t),{},{contentType:Tt(It(e),"video")})}))))}return n&&e.audioGroups&&e.audioGroups.forEach((e=>{var i;e&&(null==(i=t.groups[e])||i.tracks.forEach((t=>{if(t.groupId===e){const e=t.channels||"",i=parseFloat(e);X(i)&&i>2&&r.push.apply(r,n.split(",").map((e=>({type:"media-source",audio:{contentType:Tt(e,"audio"),channels:""+i}}))))}})))})),Promise.all(r.map((e=>{const t=function(e){const{audio:t,video:i}=e,s=i||t;if(s){const e=wt(s.contentType);if(i)return`r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${e}_${Math.ceil(i.bitrate/1e5)}`;if(t)return`c${t.channels}${t.spatialRendering?"s":"n"}_${e}`}return""}(e);return Dt[t]||(Dt[t]=i.decodingInfo(e))}))).then((e=>({supported:!e.some((e=>!e.supported)),configurations:r,decodingInfoResults:e}))).catch((e=>({supported:!1,configurations:r,decodingInfoResults:[],error:e})))}const xt=["NONE","TYPE-0","TYPE-1",null],Bt=["SDR","PQ","HLG"];function Ft(e){const{canSkipUntil:t,canSkipDateRanges:i,age:s}=e;return t&&s!!e)).map((e=>e.substring(0,4))).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=null==(t=e.supplemental)?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Vt(this._audioGroups,e)}hasSubtitleGroup(e){return Vt(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.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 null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function Vt(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}const Gt=(e,t)=>JSON.stringify(e,(e=>{const t=new WeakSet;return(i,s)=>{if(e&&(s=e(i,s)),"object"==typeof s&&null!==s){if(t.has(s))return;t.add(s)}return s}})(t));function jt(e,t){Te.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function Kt(e){return e.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 Ht(e){if(!e)return e;const{lang:t,assocLang:i,characteristics:s,channels:n,audioCodec:r}=e;return{lang:t,assocLang:i,characteristics:s,channels:n,audioCodec:r}}function Yt(e,t,i){if("attrs"in e){const i=t.indexOf(e);if(-1!==i)return i}for(let s=0;s-1===s.indexOf(e)))}(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function zt(e,t){const{audioCodec:i,channels:s}=e;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==s&&s!==(t.channels||"2"))}function qt(e,t,i){for(let s=t;s>-1;s--)if(i(e[s]))return s;for(let s=t+1;s0)i=n+1;else{if(!(o<0))return r;s=n-1}}return null};function Zt(e,t,i=0,s=0,n=.005){let r=null;if(e){r=t[1+e.sn-t[0].sn]||null;const s=e.endDTS-i;s>0&&s<15e-7&&(i+=15e-7),r&&e.level!==r.level&&r.end<=e.end&&(r=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(r=t[0]);if(r&&((!e||e.level===r.level)&&0===Jt(i,s,r)||function(e,t,i){if(t&&0===t.start&&t.level0){const s=t.tagList.reduce(((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e)),i);return e.start<=s}return!1}(r,e,Math.min(n,s))))return r;const o=Qt(t,Jt.bind(null,i,s));return!o||o===e&&r?r:o}function Jt(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;const s=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-s<=e?1:i.start-s>e&&i.start?-1:0}function ei(e,t,i){const s=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-s>e}function ti(e,t){return Qt(e,(e=>e.cct?-1:0))}function ii(e){switch(e.details){case ee.FRAG_LOAD_TIMEOUT:case ee.KEY_LOAD_TIMEOUT:case ee.LEVEL_LOAD_TIMEOUT:case ee.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function si(e,t){const i=ii(t);return e.default[(i?"timeout":"error")+"Retry"]}function ni(e,t){const i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function ri(e){return pe(pe({},e),{errorRetry:null,timeoutRetry:null})}function oi(e,t,i,s){if(!e)return!1;const n=null==s?void 0:s.code,r=t499)}(n)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,s,r):r}function ai(e){const t={action:0,flags:0};return e&&(t.resolved=!0),t}var li="NOT_LOADED",di="APPENDING",ci="PARTIAL",hi="OK";class ui{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(te.MANIFEST_LOADING,this.onManifestLoading,this),e.on(te.BUFFER_APPENDED,this.onBufferAppended,this),e.on(te.FRAG_BUFFERED,this.onFragBuffered,this),e.on(te.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(te.MANIFEST_LOADING,this.onManifestLoading,this),e.off(te.BUFFER_APPENDED,this.onBufferAppended,this),e.off(te.FRAG_BUFFERED,this.onFragBuffered,this),e.off(te.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 t=i.length;t--;){const s=i[t];if(!s)break;const n=s.end;if(s.start<=e&&null!==n&&e<=n)return s}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){const{fragments:s}=this,n=Object.keys(s);for(let r=n.length;r--;){const o=s[n[r]];if((null==o?void 0:o.body.type)===t&&(!i||o.buffered)){const t=o.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,i,s,n){this.timeRanges&&(this.timeRanges[e]=t);const r=(null==s?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach((s=>{const o=this.fragments[s];if(!o)return;if(r>=o.body.sn)return;if(!o.buffered&&(!o.loaded||n))return void(o.body.type===i&&this.removeFragment(o.body));const a=o.range[e];a&&(0!==a.time.length?a.time.some((e=>{const i=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&this.removeFragment(o.body),i})):this.removeFragment(o.body))}))}detectPartialFragments(e){const t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;const i=e.frag,s=pi(i),n=this.fragments[s];if(!n||n.buffered&&i.gap)return;const r=!i.relurl;Object.keys(t).forEach((s=>{const o=i.elementaryStreams[s];if(!o)return;const a=t[s],l=r||!0===o.partial;n.range[s]=this.getBufferedTimes(i,e.part,l,a)})),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,(n.body.endList=i.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),fi(n)||this.removeParts(i.sn-1,i.type)):this.removeFragment(n.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=gi(i,(t=>t.fragment.sn>=e)))}fragBuffered(e,t){const i=pi(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 n={time:[],partial:i},r=e.start,o=e.end,a=e.minEndPTS||o,l=e.maxStartPTS||r;for(let e=0;e=t&&a<=i){n.time.push({startPTS:Math.max(r,s.start(e)),endPTS:Math.min(o,s.end(e))});break}if(rt){const t=Math.max(r,s.start(e)),i=Math.min(o,s.end(e));i>t&&(n.partial=!0,n.time.push({startPTS:t,endPTS:i}))}else if(o<=t)break}return n}getPartialFragment(e){let t,i,s,n=null,r=0;const{bufferPadding:o,fragments:a}=this;return Object.keys(a).forEach((l=>{const d=a[l];d&&fi(d)&&(i=d.body.start-o,s=d.body.end+o,e>=i&&e<=s&&(t=Math.min(e-i,s-e),r<=t&&(n=d.body,r=t)))})),n}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||fi(t))}getState(e){const t=pi(e),i=this.fragments[t];return i?i.buffered?fi(i)?ci:hi:di:li}isTimeBuffered(e,t,i){let s,n;for(let r=0;r=s&&t<=n)return!0;if(t<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;const i=t.frag,s=t.part?null:t,n=pi(i);this.fragments[n]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:s,timeRanges:n,type:r}=t;if("initSegment"===i.sn)return;const o=i.type;if(s){let e=this.activePartLists[o];e||(this.activePartLists[o]=e=[]),e.push(s)}this.timeRanges=n;const a=n[r];this.detectEvictedFragments(r,a,o,s)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=pi(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let s=i.length;s--;){const n=t[i[s]];if((null==n?void 0:n.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,i,s,n){s&&!this.hasGaps||Object.keys(this.fragments).forEach((r=>{const o=this.fragments[r];if(!o)return;const a=o.body;a.type!==i||s&&!a.gap||a.starte&&(o.buffered||n)&&this.removeFragment(a)}))}removeFragment(e){const t=pi(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const t=e.sn;this.activePartLists[e.type]=gi(i,(e=>e.fragment.sn!==t))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e,t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const i=null==(e=this.hls)||null==(t=e.latestLevelDetails)?void 0:t.partList;i&&i.forEach((e=>e.clearElementaryStreamInfo()))}}function fi(e){var t,i,s;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(i=e.range.audio)?void 0:i.partial)||(null==(s=e.range.audiovideo)?void 0:s.partial))}function pi(e){return`${e.type}_${e.level}_${e.sn}`}function gi(e,t){return e.filter((e=>{const i=t(e);return i||e.clearElementaryStreamInfo(),i}))}class mi{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case 0:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case 1:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class vi{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 e=0;e<4;e++)i[e]=t.getUint32(4*e);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],n=i[1],r=i[2],o=i[3],a=this.invSubMix,l=a[0],d=a[1],c=a[2],h=a[3],u=new Uint32Array(256);let f=0,p=0,g=0;for(g=0;g<256;g++)u[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){let i=p^p<<1^p<<2^p<<3^p<<4;i=i>>>8^255&i^99,e[f]=i,t[i]=f;const a=u[f],g=u[a],m=u[g];let v=257*u[i]^16843008*i;s[f]=v<<24|v>>>8,n[f]=v<<16|v>>>16,r[f]=v<<8|v>>>24,o[f]=v,v=16843009*m^65537*g^257*a^16843008*f,l[i]=v<<24|v>>>8,d[i]=v<<16|v>>>16,c[i]=v<<8|v>>>24,h[i]=v,f?(f=a^u[u[u[m^a]]],p^=u[u[p]]):f=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,s=0;for(;s{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,i,s);const a=this.flush();a?n(a.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,i,s)}softwareDecrypt(e,t,i,s){const{currentIV:n,currentResult:r,remainderData:o}=this;if(0!==s||16!==t.byteLength)return Te.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=dt(o,e),this.remainderData=null);const a=this.getValidChunk(e);if(!a.length)return null;n&&(i=n);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new vi),l.expandKey(t);const d=r;return this.currentResult=l.decrypt(a.buffer,0,i),this.currentIV=a.slice(-16).buffer,d||null}webCryptoDecrypt(e,t,i,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,s));this.key=t,this.fastAesKey=new Ai(this.subtle,t,s)}return this.fastAesKey.expandKey().then((t=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new mi(this.subtle,new Uint8Array(i),s).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized")))).catch((n=>(Te.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i,s))))}onWebCryptoError(e,t,i,s){const n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,s);const n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%16;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(Te.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const yi=Math.pow(2,17);class Ti{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 _i({type:J.NETWORK_ERROR,details:ee.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,n=s.fLoader,r=s.loader;return new Promise(((o,a)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void a(Si(e));e.gap=!1}const l=this.loader=n?new n(s):new r(s),d=bi(e);e.loader=l;const c=ri(s.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:yi};e.stats=l.stats;const u={onSuccess:(t,i,s,n)=>{this.resetLoader(e,l);let r=t.data;s.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(r.slice(0,16)),r=r.slice(16)),o({frag:e,part:null,payload:r,networkDetails:n})},onError:(t,s,n,r)=>{this.resetLoader(e,l),a(new _i({type:J.NETWORK_ERROR,details:ee.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:pe({url:i,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:n,stats:r}))},onAbort:(t,i,s)=>{this.resetLoader(e,l),a(new _i({type:J.NETWORK_ERROR,details:ee.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:s,stats:t}))},onTimeout:(t,i,s)=>{this.resetLoader(e,l),a(new _i({type:J.NETWORK_ERROR,details:ee.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:s,stats:t}))}};t&&(u.onProgress=(i,s,n,r)=>t({frag:e,part:null,payload:n,networkDetails:r})),l.load(d,h,u)}))}loadPart(e,t,i){this.abort();const s=this.config,n=s.fLoader,r=s.loader;return new Promise(((o,a)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void a(Si(e,t));const l=this.loader=n?new n(s):new r(s),d=bi(e,t);e.loader=l;const c=ri(s.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:yi};t.stats=l.stats,l.load(d,h,{onSuccess:(s,n,r,a)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const d={frag:e,part:t,payload:s.data,networkDetails:a};i(d),o(d)},onError:(i,s,n,r)=>{this.resetLoader(e,l),a(new _i({type:J.NETWORK_ERROR,details:ee.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:pe({url:d.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:n,stats:r}))},onAbort:(i,s,n)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),a(new _i({type:J.NETWORK_ERROR,details:ee.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:n,stats:i}))},onTimeout:(i,s,n)=>{this.resetLoader(e,l),a(new _i({type:J.NETWORK_ERROR,details:ee.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:n,stats:i}))}})}))}updateStatsFromPart(e,t){const i=e.stats,s=t.stats,n=s.total;if(i.loaded+=s.loaded,n){const s=Math.round(e.duration/t.duration),r=Math.min(Math.round(i.loaded/n),s),o=(s-r)*Math.round(i.loaded/r);i.total=i.loaded+o}else i.total=Math.max(i.loaded,i.total);const r=i.loading,o=s.loading;r.start?r.first+=o.first-o.start:(r.start=o.start,r.first=o.first),r.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function bi(e,t=null){const i=t||e,s={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},n=i.byteRangeStartOffset,r=i.byteRangeEndOffset;if(X(n)&&X(r)){var o;let t=n,i=r;if("initSegment"===e.sn&&("AES-128"===(a=null==(o=e.decryptdata)?void 0:o.method)||"AES-256"===a)){const e=r-n;e%16&&(i=r+(16-e%16)),0!==n&&(s.resetIV=!0,t=n-16)}s.rangeStart=t,s.rangeEnd=i}var a;return s}function Si(e,t){const i=new Error(`GAP ${e.gap?"tag":"attribute"} found`),s={type:J.MEDIA_ERROR,details:ee.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(s.part=t),(t||e).stats.aborted=!0,new _i(s)}class _i extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Ci extends ge{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Ri{constructor(e,t,i,s=0,n=-1,r=!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={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=n,this.partial=r}}const Li={length:0,start:()=>0,end:()=>0};class Ii{static isBuffered(e,t){if(e){const i=Ii.getBuffered(e);for(let e=i.length;e--;)if(t>=i.start(e)&&t<=i.end(e))return!0}return!1}static bufferedRanges(e){if(e){const t=Ii.getBuffered(e);return Ii.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let i=0;i1&&e.sort(((e,t)=>e.start-t.start||t.end-e.end));let s=-1,n=[];if(i)for(let r=0;r=e[r].start&&t<=e[r].end&&(s=r);const o=n.length;if(o){const t=n[o-1].end;e[r].start-tt&&(n[o-1].end=e[r].end):n.push(e[r])}else n.push(e[r])}else n=e;let r,o=0,a=t,l=t;for(let e=0;e=d&&t<=c&&(s=e),t+i>=d&&t{const s=t.substring(2,t.length-1),n=null==i?void 0:i[s];return void 0===n?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),t):n}))}return t}function Oi(e,t,i){let s,n,r=e.variableList;if(r||(e.variableList=r={}),"QUERYPARAM"in t){s=t.QUERYPARAM;try{const e=new self.URL(i).searchParams;if(!e.has(s))throw new Error(`"${s}" does not match any query parameter in URI: "${i}"`);n=e.get(s)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else s=t.NAME,n=t.VALUE;s in r?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):r[s]=n||""}function Di(e,t,i){const s=t.IMPORT;if(i&&s in i){let t=e.variableList;t||(e.variableList=t={}),t[s]=i[s]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const Ni=/^(\d+)x(\d+)$/,Mi=/(.+?)=(".*?"|.*?)(?:,|$)/g;class xi{constructor(e,t){"string"==typeof e&&(e=xi.parseAttrList(e,t)),ue(this,e)}get clientAttrs(){return Object.keys(this).filter((e=>"X-"===e.substring(0,2)))}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=(1&t.length?"0":"")+t;const i=new Uint8Array(t.length/2);for(let e=0;eNumber.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]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce(((e,t)=>(e[t.toLowerCase()]=!0,e)),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=Ni.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const s={};for(Mi.lastIndex=0;null!==(i=Mi.exec(e));){const n=i[1].trim();let r=i[2];const o=0===r.indexOf('"')&&r.lastIndexOf('"')===r.length-1;let a=!1;if(o)r=r.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":a=!0}if(t&&(o||a))r=Pi(t,r);else if(!a&&!o)switch(n){case"CLOSED-CAPTIONS":if("NONE"===r)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Te.warn(`${e}: attribute ${n} is missing quotes`)}s[n]=r}return s}}function Bi(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}class Fi{constructor(e,t,i=0){var s;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(s=null==t?void 0:t.tagOrder)?s:i,t){const i=t.attr;for(const t in i)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==i[t]){Te.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=ue(new xi({}),i,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);X(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return null===e||null===e.programDateTime?(Te.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(X(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&X(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}class Ui{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);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||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}get hasProgramDateTime(){return!!this.fragments.length&&X(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function $i(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function Vi(e){switch(e){case"AES-128":case"AES-256":return 0;case"AES-256-CTR":return 1;default:throw new Error(`invalid full segment method ${e}`)}}function Gi(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function ji(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}const Ki="undefined"!=typeof self?self:void 0;var Hi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Yi="org.w3.clearkey",Wi="com.apple.streamingkeydelivery",zi="com.microsoft.playready",qi="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Xi(e){switch(e){case Wi:return Hi.FAIRPLAY;case zi:return Hi.PLAYREADY;case qi:return Hi.WIDEVINE;case Yi:return Hi.CLEARKEY}}function Qi(e){return"edef8ba979d64acea3c827dcd51d21ed"===e?Hi.WIDEVINE:"9a04f07998404286ab92e65be0885f95"===e?Hi.PLAYREADY:"1077efecc0b24d02ace33c1e52e2fb4b"===e||"e2719d58a985b3c9781ab030af78d30e"===e?Hi.CLEARKEY:void 0}function Zi(e){switch(e){case Hi.FAIRPLAY:return Wi;case Hi.PLAYREADY:return zi;case Hi.WIDEVINE:return qi;case Hi.CLEARKEY:return Yi}}function Ji(e){const{drmSystems:t,widevineLicenseUrl:i}=e,s=t?[Hi.FAIRPLAY,Hi.WIDEVINE,Hi.PLAYREADY,Hi.CLEARKEY].filter((e=>!!t[e])):[];return!s[Hi.WIDEVINE]&&i&&s.push(Hi.WIDEVINE),s}const es=null!=Ki&&null!=(ts=Ki.navigator)&&ts.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var ts;function is(e){const t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),s=i.substring(i.indexOf("<"),i.length),n=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(n){const e=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(e){const t=Gi(e).subarray(0,16);return function(e){const t=function(e,t,i){const s=e[t];e[t]=e[i],e[i]=s};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}(t),t}}return null}let ss={};class ns{static clearKeyUriToKeyIdMap(){ss={}}constructor(e,t,i,s=[1],n=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=n,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!$i(e)}isSupported(){if(this.method){if($i(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Wi:case qi:case zi:case Yi:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if($i(this.method)&&this.uri&&!this.iv){"number"!=typeof e&&(Te.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const t=function(e){const t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(e);return new ns(this.method,this.uri,"identity",this.keyFormatVersions,t)}const t=function(e){const t=e.split(":");let i=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),s=e[e.length-1].split(",");if(2===s.length){const t="base64"===s[0],n=s[1];t?(e.splice(-1,1),i=Gi(n)):i=function(e){const t=ji(e).subarray(0,16),i=new Uint8Array(16);return i.set(t,16-t.length),i}(n)}}return i}(this.uri);if(t)switch(this.keyFormat){case qi:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case zi:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=function(e,t,i){if(16!==e.byteLength)throw new RangeError("Invalid system id");let s,n,r;s=0,n=new Uint8Array,r=new Uint8Array;const o=new Uint8Array(4);return i&&i.byteLength>0&&new DataView(o.buffer).setUint32(0,i.byteLength,!1),function(e,...t){const i=t.length;let s=8,n=i;for(;n--;)s+=t[n].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=255&s,r.set(e,4),n=0,s=8;n0&&s.length({id:e.attrs.AUDIO,audioCodec:e.audioCodec}))),SUBTITLES:r.map((e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec}))),"CLOSED-CAPTIONS":[]};let a=0;for(os.lastIndex=0;null!==(s=os.exec(e));){const e=new xi(s[1],i),r=e.TYPE;if(r){const i=o[r],s=n[r]||[];n[r]=s;const l=e.LANGUAGE,d=e["ASSOC-LANGUAGE"],c=e.CHANNELS,h=e.CHARACTERISTICS,u=e["INSTREAM-ID"],f={attrs:e,bitrate:0,id:a++,groupId:e["GROUP-ID"]||"",name:e.NAME||l||"",type:r,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:l,url:e.URI?cs.resolve(e.URI,t):""};if(d&&(f.assocLang=d),c&&(f.channels=c),h&&(f.characteristics=h),u&&(f.instreamId=u),null!=i&&i.length){const e=cs.findGroup(i,f.groupId)||i[0];ms(f,e,"audioCodec"),ms(f,e,"textCodec")}s.push(f)}}return n}static parseLevelPlaylist(e,t,i,s,n,r){var o;const a={url:t},l=new Ui(t),d=l.fragments,c=[];let h,u,f,p,g=null,m=0,v=0,A=0,E=0,y=0,T=null,b=new Ve(s,a),S=-1,_=!1,C=null;if(ls.lastIndex=0,l.m3u8=e,l.hasVariableRefs=wi(e),"#EXTM3U"!==(null==(o=ls.exec(e))?void 0:o[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(h=ls.exec(e));){_&&(_=!1,b=new Ve(s,a),b.playlistOffset=A,b.start=A,b.sn=m,b.cc=E,y&&(b.bitrate=y),b.level=i,g&&(b.initSegment=g,g.rawProgramDateTime&&(b.rawProgramDateTime=g.rawProgramDateTime,g.rawProgramDateTime=null),C&&(b.setByteRange(C),C=null)));const e=h[1];if(e){b.duration=parseFloat(e);const t=(" "+h[2]).slice(1);b.title=t||null,b.tagList.push(t?["INF",e,t]:["INF",e])}else if(h[3]){if(X(b.duration)){b.playlistOffset=A,b.start=A,f&&Es(b,f,l),b.sn=m,b.level=i,b.cc=E,d.push(b);const e=(" "+h[3]).slice(1);b.relurl=Pi(l,e),vs(b,T,c),T=b,A+=b.duration,m++,v=0,_=!0}}else{if(h=h[0].match(ds),!h){Te.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u0&&Ts(l,e,h),m=l.startSN=parseInt(n);break;case"SKIP":{l.skippedSegments&&ys(l,e,h);const t=new xi(n,l),i=t.decimalInteger("SKIPPED-SEGMENTS");if(X(i)){l.skippedSegments+=i;for(let e=i;e--;)d.push(null);m+=i}const s=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(s.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&ys(l,e,h),l.targetduration=Math.max(parseInt(n),1);break;case"VERSION":null!==l.version&&ys(l,e,h),l.version=parseInt(n);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||ys(l,e,h),l.live=!1;break;case"#":(n||o)&&b.tagList.push(o?[n,o]:[n]);break;case"DISCONTINUITY":E++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([e]);break;case"BITRATE":b.tagList.push([e,n]),y=1e3*parseInt(n),X(y)?b.bitrate=y:y=0;break;case"DATERANGE":{const e=new xi(n,l),t=new Fi(e,l.dateRanges[e.ID],l.dateRangeTagCount);l.dateRangeTagCount++,t.isValid||l.skippedSegments?l.dateRanges[t.id]=t:Te.warn(`Ignoring invalid DATERANGE tag: "${n}"`),b.tagList.push(["EXT-X-DATERANGE",n]);break}case"DEFINE":{const e=new xi(n,l);"IMPORT"in e?Di(l,e,r):Oi(l,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC?ys(l,e,h):d.length>0&&Ts(l,e,h),l.startCC=E=parseInt(n);break;case"KEY":{const e=fs(n,t,l);if(e.isSupported()){if("NONE"===e.method){f=void 0;break}f||(f={}),f[e.keyFormat]&&(f=ue({},f)),f[e.keyFormat]=e}else Te.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${n}"`);break}case"START":l.startTimeOffset=ps(n);break;case"MAP":{const e=new xi(n,l);if(b.duration){const t=new Ve(s,a);As(t,e,i,f),g=t,b.initSegment=g,g.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=g.rawProgramDateTime)}else{const t=b.byteRangeEndOffset;if(t){const e=b.byteRangeStartOffset;C=`${t-e}@${e}`}else C=null;As(b,e,i,f),g=b,_=!0}g.cc=E;break}case"SERVER-CONTROL":p&&ys(l,e,h),p=new xi(n),l.canBlockReload=p.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=p.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&p.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=p.optionalFloat("PART-HOLD-BACK",0),l.holdBack=p.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&ys(l,e,h);const t=new xi(n);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=l.partList;e||(e=l.partList=[]);const t=v>0?e[e.length-1]:void 0,i=v++,s=new xi(n,l),r=new Ge(s,b,a,i,t);e.push(r),b.duration+=r.duration;break}case"PRELOAD-HINT":{const e=new xi(n,l);l.preloadHint=e;break}case"RENDITION-REPORT":{const e=new xi(n,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(e);break}default:Te.warn(`line parsed but not handled: ${h}`)}}}T&&!T.relurl?(d.pop(),A-=T.duration,l.partList&&(l.fragmentHint=T)):l.partList&&(vs(b,T,c),b.cc=E,l.fragmentHint=b,f&&Es(b,f,l)),l.targetduration||(l.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const R=d.length,L=d[0],I=d[R-1];if(A+=l.skippedSegments*l.targetduration,A>0&&R&&I){l.averagetargetduration=A/R;const e=I.sn;l.endSN="initSegment"!==e?e:0,l.live||(I.endList=!0),L&&void 0===l.startCC&&(l.startCC=L.cc),S>0&&(function(e,t){let i=e[t];for(let s=t;s--;){const t=e[s];if(!t)return;t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(d,S),L&&c.unshift(L))}else l.endSN=0,l.startCC=0;return l.fragmentHint&&(A+=l.fragmentHint.duration),l.totalduration=A,c.length&&l.dateRangeTagCount&&L&&hs(c,l),l.endCC=E,l}}function hs(e,t){const i=e.length,s=e[i-1],n=t.live?1/0:t.totalduration,r=Object.keys(t.dateRanges);for(let o=r.length;o--;){const a=t.dateRanges[r[o]],l=a.startDate.getTime();a.tagAnchor=s.ref;for(let s=i;s--;){const i=us(t,l,e,s,n);if(-1!==i){a.tagAnchor=t.fragments[i].ref;break}}}}function us(e,t,i,s,n){const r=i[s];if(r){const a=r.programDateTime;var o;if(t>=a||0===s)if(t<=a+1e3*(((null==(o=i[s+1])?void 0:o.start)||n)-r.start)){const n=i[s].sn-e.startSN,r=e.fragments;if(r.length>i.length)for(let o=(i[s+1]||r[r.length-1]).sn-e.startSN;o>n;o--){const e=r[o].programDateTime;if(t>=e&&te));["video","audio","text"].forEach((e=>{const s=i.filter((t=>At(t,e)));s.length&&(t[`${e}Codec`]=s.map((e=>e.split("/")[0])).join(","),i=i.filter((e=>-1===s.indexOf(e))))})),t.unknownCodecs=i}function ms(e,t,i){const s=t[i];s&&(e[i]=s)}function vs(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function As(e,t,i,s){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",s&&(e.levelkeys=s),e.initSegment=null}function Es(e,t,i){e.levelkeys=t;const{encryptedFragments:s}=i;s.length&&s[s.length-1].levelkeys===t||!Object.keys(t).some((e=>t[e].isCommonEncryption))||s.push(e)}function ys(e,t,i){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${i[0]})`)}function Ts(e,t,i){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${i[0]})`)}function bs(e,t){const i=t.startPTS;if(X(i)){let s,n=0;t.sn>e.sn?(n=i-e.start,s=e):(n=e.start-i,s=t),s.duration!==n&&s.setDuration(n)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function Ss(e,t,i,s,n,r){s-i<=0&&(Te.warn("Fragment should have a positive duration",t),s=i+t.duration,r=n+t.duration);let o=i,a=s;const l=t.startPTS,d=t.endPTS;if(X(l)){const e=Math.abs(l-i);X(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,o=Math.max(i,l),i=Math.min(i,l),n=Math.min(n,t.startDTS),a=Math.min(s,d),s=Math.max(s,d),r=Math.max(r,t.endDTS)}const c=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(s-t.start),t.startPTS=i,t.maxStartPTS=o,t.startDTS=n,t.endPTS=s,t.minEndPTS=a,t.endDTS=r;const h=t.sn;if(!e||he.endSN)return 0;let u;const f=h-e.startSN,p=e.fragments;for(p[f]=t,u=f;u>0;u--)bs(p[u],p[u-1]);for(u=f;u=0;let o=0;if(r&&st){const e=1e3*s[s.length-1].duration;e{var i;null==(i=e.details)||i.fragments.forEach((e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)}))}))}function Os(e,t){for(let s=0,n=e.length;se.startCC)}(t,e))return;const i=Math.min(t.endCC,e.endCC),s=Os(t.fragments,i),n=Os(e.fragments,i);s&&n&&(Te.log(`Aligning playlist at start of dicontinuity sequence ${i}`),Ns(s.start-n.start,e))}function xs(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const i=e.fragments,s=t.fragments;if(!i.length||!s.length)return;let n,r;const o=Math.min(t.endCC,e.endCC);t.startCC{const{config:e,fragCurrent:t,media:i,mediaBuffer:s,state:n}=this,r=i?i.currentTime:0,o=Ii.bufferInfo(s||i,r,e.maxBufferHole);if(this.log(`media seeking to ${X(r)?r.toFixed(3):r}, state: ${n}`),this.state===Hs)this.resetLoadingState();else if(t){const i=e.maxFragLookUpTolerance,s=t.start-i,n=t.start+t.duration+i;if(!o.len||no.end){const e=r>n;(rthis.lastCurrentTime&&(this.lastCurrentTime=r),!this.loadingParts)){const e=Math.max(o.end,r),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${r.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}this.hls.hasEnoughToStart||o.len||(this.log(`setting startPosition to ${r} because of seek before start`),this.nextLoadPosition=this.startPosition=r),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=e,this.fragmentLoader=new Ti(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ei(e.config)}registerListeners(){const{hls:e}=this;e.on(te.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(te.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(te.MANIFEST_LOADING,this.onManifestLoading,this),e.on(te.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(te.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(te.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(te.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(te.MANIFEST_LOADING,this.onManifestLoading,this),e.off(te.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(te.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Bs)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Bs}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return-1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const n=e.nextStart;if(n&&n>s&&n{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)})).then((e=>{if(!e)return;const t=this.state,i=e.frag;this.fragContextChanged(i)?(t===$s||!this.fragCurrent&&t===js)&&(this.fragmentTracker.removeFragment(i),this.state=Fs):("payload"in e&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level}`),this.hls.trigger(te.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))})).catch((t=>{this.state!==Bs&&this.state!==Ys&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===di){const t=e.type,s=this.getFwdBufferInfo(this.mediaBuffer,t),n=Math.max(e.duration,s?s.len:this.config.maxBufferLength),r=this.backtrackFragment;(1==(r?e.sn-r.sn:0)||this.reduceMaxBufferLength(n,e.duration))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===ci&&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)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const s={startOffset:e,endOffset:t,type:i};this.hls.trigger(te.BUFFER_FLUSHING,s)}_loadInitSegment(e,t){this._doFragLoad(e,t).then((e=>{const t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e})).then((e=>{const{hls:t}=this,{frag:i,payload:s}=e,n=i.decryptdata;if(s&&s.byteLength>0&&null!=n&&n.key&&n.iv&&$i(n.method)){const r=self.performance.now();return this.decrypter.decrypt(new Uint8Array(s),n.key.buffer,n.iv.buffer,Vi(n.method)).catch((e=>{throw t.trigger(te.ERROR,{type:J.MEDIA_ERROR,details:ee.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e})).then((s=>{const n=self.performance.now();return t.trigger(te.FRAG_DECRYPTED,{frag:i,payload:s,stats:{tstart:r,tdecrypt:n}}),e.payload=s,this.completeInitSegmentLoad(e)}))}return this.completeInitSegmentLoad(e)})).catch((t=>{this.state!==Bs&&this.state!==Ys&&(this.warn(t),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!==Bs&&(this.state=Fs),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){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?function(e){let t="";const i=e.length;for(let s=0;s!!t[e])))return void(this.state=Fs)}const t=null==(s=this.levels)?void 0:s[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=Fs}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:s,partsLoaded:n}=e,r=!n||0===n.length||n.some((e=>!e)),o=new Ri(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!r);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,s){var n;this.fragCurrent=e;const r=null==t?void 0:t.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" detail"}s`);let o=null;!e.encrypted||null!=(n=e.decryptdata)&&n.key?!e.encrypted&&r.encryptedFragments.length&&this.keyLoader.loadClear(e,r.encryptedFragments):(this.log(`Loading key for ${e.sn} of [${r.startSN}-${r.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Us,this.fragCurrent=e,o=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(te.KEY_LOADED,e),this.state===Us&&(this.state=Fs),e})),this.hls.trigger(te.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"))));const a=this.fragPrevious;if($e(e)&&(!a||e.sn!==a.sn)){const i=this.shouldLoadParts(t.details,e.end);i!==this.loadingParts&&(this.log(`LL-Part loading ${i?"ON":"OFF"} loading sn ${null==a?void 0:a.sn}->${e.sn}`),this.loadingParts=i)}if(i=Math.max(e.start,i||0),this.loadingParts&&$e(e)){const n=r.partList;if(n&&s){i>e.end&&r.fragmentHint&&(e=r.fragmentHint);const a=this.getNextPart(n,e,i);if(a>-1){const l=n[a];let d;return e=this.fragCurrent=l.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${a}/${n.length-1}) of ${this.fragInfo(e,!1,l)}) cc: ${e.cc} [${r.startSN}-${r.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=$s,d=o?o.then((i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(e,l,t,s))).catch((e=>this.handleFragLoadError(e))):this.doFragPartsLoad(e,l,t,s).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(te.FRAG_LOADING,{frag:e,part:l,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!e.url||this.loadedEndOfParts(n,i))return Promise.resolve(null)}}if($e(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${r?"["+r.startSN+"-"+r.endSN+"]":""}, target: ${parseFloat(i.toFixed(3))}`),X(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=$s;const l=this.config.progressive;let d;return d=l&&o?o.then((t=>!t||this.fragContextChanged(null==t?void 0:t.frag)?null:this.fragmentLoader.load(e,s))).catch((e=>this.handleFragLoadError(e))):Promise.all([this.fragmentLoader.load(e,l?s:void 0),o]).then((([e])=>(!l&&e&&s&&s(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(te.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(e,t,i,s){return new Promise(((n,r)=>{var o;const a=[],l=null==(o=i.details)?void 0:o.partList,d=t=>{this.fragmentLoader.loadPart(e,t,s).then((s=>{a[t.index]=s;const r=s.part;this.hls.trigger(te.FRAG_LOADED,s);const o=ks(i.details,e.sn,t.index+1)||ws(l,e.sn,t.index+1);if(!o)return n({frag:e,part:r,partsLoaded:a});d(o)})).catch(r)};d(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===ee.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(te.ERROR,t)}else this.hls.trigger(te.ERROR,{type:J.OTHER_ERROR,details:ee.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==js)return void(this.fragCurrent||this.state===Bs||this.state===Ys||(this.state=Fs));const{frag:i,part:s,level:n}=t,r=self.performance.now();i.stats.parsing.end=r,s&&(s.stats.parsing.end=r);const o=this.getLevelDetails(),a=o&&i.sn>o.endSN||this.shouldLoadParts(o,i.end);a!==this.loadingParts&&(this.log(`LL-Part loading ${a?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=a),this.updateLevelTiming(i,s,n,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(null!=e&&e.partList){var i;const n=e.partList[0];var s;if(t>=n.end+((null==(i=e.fragmentHint)?void 0:i.duration)||0))if((this.hls.hasEnoughToStart?(null==(s=this.media)?void 0:s.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:s,sn:n,part:r}=e;if(null==t||!t[s])return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const o=t[s],a=o.details,l=r>-1?ks(a,n,r):null,d=l?l.fragment:Is(a,n,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:l,level:o}):null}bufferFragmentData(e,t,i,s,n){var r;if(!e||this.state!==js)return;const{data1:o,data2:a}=e;let l=o;if(o&&a&&(l=dt(o,a)),null==(r=l)||!r.length)return;const d={type:e.type,frag:t,part:i,chunkMeta:s,parent:t.type,data:l};if(this.hls.trigger(te.BUFFER_APPENDING,d),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Ii.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const i=t.currentTime,s=Ii.bufferInfo(t,i,0),n=e.duration,r=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),o=Math.max(Math.min(e.start-r,s.end-r),i+r);e.start-o>r&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var i;const s=this.getLoadPosition();if(!X(s))return null;const n=this.lastCurrentTime>s||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,n)}getFwdBufferInfoAtPos(e,t,i,s){const n=Ii.bufferInfo(e,t,s);if(0===n.len&&void 0!==n.nextStart){const r=this.fragmentTracker.getBufferedFrag(t,i);if(r&&(n.nextStart<=r.end||r.gap)){const i=Math.max(Math.min(n.nextStart,r.end)-t,s);return Ii.bufferInfo(e,t,i)}}return n}getMaxBufferLength(e){const{config:t}=this;let i;return i=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t),n=Math.max(e-3*t,i.maxMaxBufferLength/2,s);return n>=s&&(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0)}getAppendedFrag(e,t=oe){var i;const s=null==(i=this.fragmentTracker)?void 0:i.getAppendedFrag(e,t);return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const i=t.fragments,s=i.length;if(!s)return null;const{config:n}=this,r=i[0].start,o=n.lowLatencyMode&&!!t.partList;let a=null;if(t.live){const d=n.initialLiveManifestSize;if(s=r?s:n)||a.start:e;this.log(`Setting startPosition to ${d} to match start frag at live edge. mainStart: ${s} liveSyncPosition: ${n} frag.start: ${null==(l=a)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=d}}else e<=r&&(a=i[0]);if(!a){const i=this.loadingParts?t.partEnd:t.fragmentEnd;a=this.getFragmentAtPosition(e,i,t)}let d=this.filterReplacedPrimary(a,t);if(!d&&a){const e=a.sn-t.startSN;d=this.filterReplacedPrimary(i[e+1]||null,t)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===hi||i===ci&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,s,n){let r=null;if(e.gap&&(r=this.getNextFragment(this.nextLoadPosition,t),r&&!r.gap&&i.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(null!==e&&i.len+e.len>=n){const e=r.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,r}get primaryPrefetch(){var e,t;if(Xs(this.hls.config)&&(null==(e=this.hls.interstitialsManager)||null==(t=e.playingItem)?void 0:t.event))return!0;return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Xs(this.hls.config)&&e.type!==le){const i=this.hls.interstitialsManager,s=null==i?void 0:i.bufferingItem;if(s){const i=s.event;if(i){if(i.appendInPlace||Math.abs(e.start-s.start)>1||0===s.start)return null}else{if(e.end<=s.start&&!1===(null==t?void 0:t.live))return null;if(e.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||e.start-s.end>1))return null}}const n=null==i?void 0:i.playerQueue;if(n)for(let t=n.length;t--;){const i=n[t].interstitial;if(i.appendInPlace&&e.start>=i.startTime&&e.end<=i.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,i){let s=-1,n=!1,r=!0;for(let o=0,a=e.length;o-1&&ii.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=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!X(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;i=i||0;for(let s=0;s=e.startSN&&n<=e.endSN){const r=t[n-e.startSN];i.cc===r.cc&&(s=r,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=ti(t,i.cc),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(s=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){const{config:s}=this;let{fragPrevious:n}=this,{fragments:r,endSN:o}=i;const{fragmentHint:a}=i,{maxFragLookUpTolerance:l}=s,d=i.partList,c=!!(this.loadingParts&&null!=d&&d.length&&a);let h;var u;(c&&a&&!this.bitrateTest&&d[d.length-1].fragment.sn===a.sn&&(r=r.concat(a),o=a.sn),et-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l):h=r[r.length-1];if(h){const e=h.sn-i.startSN,t=this.fragmentTracker.getState(h);if((t===hi||t===ci&&h.gap)&&(n=h),n&&h.sn===n.sn&&(!c||d[0].fragment.sn>h.sn||!i.live&&!c)&&n&&h.level===n.level){const t=r[e+1];h=h.sn${e.startSN} fragments: ${s}`),n}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let i=this.startPosition;i=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&$e(e)&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===Vs)||(this.state=Fs)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;var s;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.url} > ${null==(s=this.fragCurrent)?void 0:s.url}`);const n=t.details===ee.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const r=t.errorAction,{action:o,flags:a,retryCount:l=0,retryConfig:d}=r||{},c=!!r&&!!d,h=c&&5===o,u=c&&!r.resolved&&1===a;if(!h&&u&&$e(i)&&!i.endList)this.resetFragmentErrors(e),this.treatAsGap(i),r.resolved=!0;else if((h||u)&&l.5;n&&this.reduceMaxBufferLength(s.len,(null==t?void 0:t.duration)||10);const r=!n;return r&&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(),r}return!1}resetFragmentErrors(e){e===ae&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Bs&&(this.state=Fs)}afterBufferFlushed(e,t,i){if(!e)return;const s=Ii.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,i),this.state===Hs&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Bs&&(this.state=Fs)}resetStartWhenNotLoaded(e){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of ${this.playlistLabel()} ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){const n=i.details;if(n){var r;if(!Object.keys(e.elementaryStreams).reduce(((t,r)=>{const o=e.elementaryStreams[r];if(o){const a=o.endPTS-o.startPTS;if(a<=0)return this.warn(`Could not parse fragment ${e.sn} ${r} duration reliably (${a})`),t||!1;const l=s?0:Ss(n,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return this.hls.trigger(te.LEVEL_PTS_UPDATED,{details:n,level:i,drift:l,type:r,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t}),!1)&&(0===i.fragmentError&&this.treatAsGap(e,i),null===(null==(r=this.transmuxer)?void 0:r.error))){const t=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(te.ERROR,{type:J.MEDIA_ERROR,details:ee.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=Ks,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(te.FRAG_PARSED,{frag:e,part:t})}else this.warn("level.details undefined")}playlistLabel(){return this.playlistType===oe?"level":"track"}fragInfo(e,t=!0,i){var s,n;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${(null!=(s=t&&!i?e.startPTS:(i||e).start)?s:NaN).toFixed(3)}-${(null!=(n=t&&!i?e.endPTS:(i||e).end)?n:NaN).toFixed(3)}]${i&&"main"===e.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function Xs(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}class Qs{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;return e.length?(i=1===e.length?e[0]:function(e,t){const i=new Uint8Array(t);let s=0;for(let t=0;t0)return e.subarray(i,i+s)}function dn(e,t){return 255===e[t]&&240==(246&e[t+1])}function cn(e,t){return 1&e[t+1]?7:9}function hn(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function un(e,t){return t+1=e.length)return!1;const s=hn(e,t);if(s<=i)return!1;const n=t+s;return n===e.length||un(e,n)}return!1}function pn(e,t,i,s,n){if(!e.samplerate){const r=function(e,t,i,s){const n=t[i+2],r=n>>2&15;if(r>12){const t=new Error(`invalid ADTS sampling index:${r}`);return void e.emit(te.ERROR,te.ERROR,{type:J.MEDIA_ERROR,details:ee.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const o=1+(n>>6&3),a=t[i+3]>>6&3|(1&n)<<2,l="mp4a.40."+o,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][r];let c=r;5!==o&&29!==o||(c-=3);const h=[o<<3|(14&c)>>1,(1&c)<<7|a<<3];return Te.log(`manifest codec:${s}, parsed codec:${l}, channels:${a}, rate:${d} (ADTS object type:${o} sampling index:${r})`),{config:h,samplerate:d,channelCount:a,codec:l,parsedCodec:l,manifestCodec:s}}(t,i,s,n);if(!r)return;ue(e,r)}}function gn(e){return 9216e4/e}function mn(e,t,i,s,n){const r=s+n*gn(e.samplerate),o=function(e,t){const i=cn(e,t);if(t+i<=e.length){const s=hn(e,t)-i;if(s>0)return{headerLength:i,frameLength:s}}}(t,i);let a;if(o){const{frameLength:s,headerLength:n}=o,l=n+s,d=Math.max(0,i+l-t.length);d?(a=new Uint8Array(l-n),a.set(t.subarray(i+n,t.length),0)):a=t.subarray(i+n,i+l);const c={unit:a,pts:r};return d||e.samples.push(c),{sample:c,length:l,missing:d}}const l=t.length-i;return a=new Uint8Array(l),a.set(t.subarray(i,t.length),0),{sample:{unit:a,pts:r},length:l,missing:-1}}function vn(e,t){return on(e,t)&&an(e,t+6)+10<=e.length-t}function An(e,t){if(e<0)return-An(-e,t);const i=Math.pow(10,t);if(Math.abs(e*i%1-.5)>6&1&&(t+=10),t+=10;const n=t+s;for(;t+100&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Rn.audioId3,duration:Number.POSITIVE_INFINITY});nX(e)?90*e:9e4*t+(i?9e4*i.baseTime/i.timescale:0);let wn=null;const Pn=[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],On=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Dn=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Nn=[0,1,1,4];function Mn(e,t,i,s,n){if(i+24>t.length)return;const r=xn(t,i);if(r&&i+r.frameLength<=t.length){const o=s+n*(9e4*r.samplesPerFrame/r.sampleRate),a={unit:t.subarray(i,i+r.frameLength),pts:o,dts:o};return e.config=[],e.channelCount=r.channelCount,e.samplerate=r.sampleRate,e.samples.push(a),{sample:a,length:r.frameLength,missing:0}}}function xn(e,t){const i=e[t+1]>>3&3,s=e[t+1]>>1&3,n=e[t+2]>>4&15,r=e[t+2]>>2&3;if(1!==i&&0!==n&&15!==n&&3!==r){const o=e[t+2]>>1&1,a=e[t+3]>>6,l=1e3*Pn[14*(3===i?3-s:3===s?3:4)+n-1],d=On[3*(3===i?0:2===i?1:2)+r],c=3===a?1:2,h=Dn[i][s],u=Nn[s],f=8*h*u,p=Math.floor(h*l/d+o)*u;if(null===wn){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);wn=e?parseInt(e[1]):0}return!!wn&&wn<=87&&2===s&&l>=224e3&&0===a&&(e[t+3]=128|e[t+3]),{sampleRate:d,channelCount:c,frameLength:p,samplesPerFrame:f}}}function Bn(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function Fn(e,t){return t+1{let i=0,s=5;t+=s;const n=new Uint32Array(1),r=new Uint32Array(1),o=new Uint8Array(1);for(;s>0;){o[0]=e[t];const a=Math.min(s,8),l=8-a;r[0]=4278190080>>>24+l<>l,i=i?i<t.length)return-1;if(11!==t[i]||119!==t[i+1])return-1;const r=t[i+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],a=63&t[i+4],l=2*[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][3*a+r];if(i+l>t.length)return-1;const d=t[i+6]>>5;let c=0;2===d?c+=2:(1&d&&1!==d&&(c+=2),4&d&&(c+=2));const h=(t[i+6]<<8|t[i+7])>>12-c&1,u=[2,1,2,3,3,4,4,5][d]+h,f=t[i+5]>>3,p=7&t[i+5],g=new Uint8Array([r<<6|f<<1|p>>2,(3&p)<<6|d<<3|h<<2|a>>4,a<<4&224]),m=s+n*(1536/o*9e4),v=t.subarray(i,i+l);return e.config=g,e.channelCount=u,e.samplerate=o,e.samples.push({unit:v,pts:m}),l}const Gn=/\/emsg[-/]ID3/i;function jn(e,t){return X(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class Kn{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Ei(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,0)}decryptAacSample(e,t,i){const s=e[t].unit;if(s.length<=16)return;const n=s.subarray(16,s.length-s.length%16),r=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(r).then((n=>{const r=new Uint8Array(n);s.set(r,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}))}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,i),this.decrypter.isSync())))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t);let s=0;for(let t=32;t{n.data=this.getAvcDecryptedUnit(r,o),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)return void s();const n=e[t].units;for(;!(i>=n.length);i++){const r=n[i];if(!(r.data.length<=48||1!==r.type&&5!==r.type||(this.decryptAvcSample(e,t,i,s,r),this.decrypter.isSync())))return}}}}class Hn{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i,s=this.VideoSample;if(s&&0!==s.units.length||(s=e[e.length-1]),null!=(t=s)&&t.units){const e=s.units;i=e[e.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const i=t.samples,s=i.length;if(!s)return void t.dropped++;{const t=i[s-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,i){const s=t.byteLength;let n=e.naluState||0;const r=n,o=[];let a,l,d,c=0,h=-1,u=0;for(-1===n&&(h=0,u=this.getNALuType(t,0),n=0,c=1);c=0){const e={data:t.subarray(h,l),type:u};o.push(e)}else{const i=this.getLastNalUnit(e.samples);i&&(r&&c<=4-r&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-r)),l>0&&(i.data=dt(i.data,t.subarray(0,l)),i.state=0))}c=0&&n>=0){const e={data:t.subarray(h,s),type:u,state:n};o.push(e)}if(0===o.length){const i=this.getLastNalUnit(e.samples);i&&(i.data=dt(i.data,t))}return e.naluState=n,o}}class Yn{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),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");s.set(e.subarray(i,i+n)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>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&&Te.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?i<>>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 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Wn extends Hn{parsePES(e,t,i,s){const n=this.parseNALu(e,i.data,s);let r,o=this.VideoSample,a=!1;i.data=null,o&&n.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),n.forEach((s=>{var n,l;switch(s.type){case 1:{let t=!1;r=!0;const n=s.data;if(a&&n.length>4){const e=this.readSliceType(n);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var d;t&&null!=(d=o)&&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=t;break}case 5:r=!0,null!=(n=o)&&n.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:r=!0,ft(s.data,1,i.pts,t.samples);break;case 7:{var c,h;r=!0,a=!0;const t=s.data,i=this.readSPS(t);if(!e.sps||e.width!==i.width||e.height!==i.height||(null==(c=e.pixelRatio)?void 0:c[0])!==i.pixelRatio[0]||(null==(h=e.pixelRatio)?void 0:h[1])!==i.pixelRatio[1]){e.width=i.width,e.height=i.height,e.pixelRatio=i.pixelRatio,e.sps=[t];const s=t.subarray(1,4);let n="avc1.";for(let e=0;e<3;e++){let t=s[e].toString(16);t.length<2&&(t="0"+t),n+=t}e.codec=n}break}case 8:r=!0,e.pps=[s.data];break;case 9:r=!0,e.audFound=!0,null!=(l=o)&&l.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:r=!0;break;default:r=!1}o&&r&&o.units.push(s)})),s&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new Yn(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i,s=8,n=8;for(let r=0;r{var n,l;switch(s.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.frame=!0,r=!0;break;case 16:case 17:case 18:case 21:var d;r=!0,a&&null!=(d=o)&&d.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 19:case 20:r=!0,null!=(n=o)&&n.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 39:r=!0,ft(s.data,2,i.pts,t.samples);break;case 32:r=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=ue(e.params,this.readVPS(s.data)),this.initVPS=s.data),e.vps=[s.data];break;case 33:if(r=!0,a=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],s.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const t=this.readSPS(s.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={});for(const i in t.params)e.params[i]=t.params[i]}this.pushParameterSet(e.sps,s.data,e.vps),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0;break;case 34:if(r=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];const t=this.readPPS(s.data);for(const i in t)e.params[i]=t[i]}this.pushParameterSet(e.pps,s.data,e.vps)}break;case 35:r=!0,e.audFound=!0,null!=(l=o)&&l.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:r=!1}o&&r&&o.units.push(s)})),s&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let s=0;s=2&&3===e[s]&&0===e[s-1]&&0===e[s-2]||(t[i]=e[s],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Yn(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){const t=new Yn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const s=t.readBits(2),n=t.readBoolean(),r=t.readBits(5),o=t.readUByte(),a=t.readUByte(),l=t.readUByte(),d=t.readUByte(),c=t.readUByte(),h=t.readUByte(),u=t.readUByte(),f=t.readUByte(),p=t.readUByte(),g=t.readUByte(),m=t.readUByte(),v=[],A=[];for(let e=0;e0)for(let e=i;e<8;e++)t.readBits(2);for(let e=0;e1&&t.readEG();for(let e=0;e0&&e<16?(D=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],N=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(D=t.readBits(16),N=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),F=t.readBoolean(),F&&(S+=t.readUEG(),_+=t.readUEG(),C+=t.readUEG(),R+=t.readUEG()),t.readBoolean()&&(x=t.readBits(32),B=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const e=t.readBoolean(),s=t.readBoolean();let n=!1;(e||s)&&(n=t.readBoolean(),n&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),n&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let r=0;r<=i;r++){M=t.readBoolean();let i=!1;M||t.readBoolean()?t.readEG():i=t.readBoolean();const r=i?1:t.readUEG()+1;if(e)for(let e=0;e>e&1)<<31-e)>>>0;let K=j.toString(16);return 1===r&&"2"===K&&(K="6"),{codecString:`hvc1.${V}${r}.${K}.${n?"H":"L"}${m}.B0`,params:{general_tier_flag:n,general_profile_idc:r,general_profile_space:s,general_profile_compatibility_flags:[o,a,l,d],general_constraint_indicator_flags:[c,h,u,f,p,g],general_level_idc:m,bit_depth:L+8,bit_depth_luma_minus8:L,bit_depth_chroma_minus8:I,min_spatial_segmentation_idc:O,chroma_format_idc:E,frame_rate:{fixed:M,fps:B/x}},width:U,height:$,pixelRatio:[D,N]}}readPPS(e){const t=new Yn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const i=t.readBoolean(),s=t.readBoolean();let n=1;return s&&i?n=0:s?n=3:i&&(n=2),{parallelismType:n}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const qn=188;class Xn{constructor(e,t,i,s){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(e,t){const i=Xn.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(e){const t=e.length;let i=Math.min(940,t-qn)+1,s=0;for(;s1&&(0===r&&o>2||a+qn>i))return r}s++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Ye[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,i,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Xn.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=Xn.createTrack("audio",s),this._id3Track=Xn.createTrack("id3"),this._txtTrack=Xn.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}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){let n;i||(this.sampleAes=null);const r=this._videoTrack,o=this._audioTrack,a=this._id3Track,l=this._txtTrack;let d=r.pid,c=r.pesData,h=o.pid,u=a.pid,f=o.pesData,p=a.pesData,g=null,m=this.pmtParsed,v=this._pmtId,A=e.length;if(this.remainderData&&(A=(e=dt(this.remainderData,e)).length,this.remainderData=null),A>4>1){if(y=t+5+e[t+4],y===t+qn)continue}else y=t+4;switch(A){case d:if(s){if(c&&(n=ir(c,this.logger))){if(null===this.videoParser)switch(r.segmentCodec){case"avc":this.videoParser=new Wn;break;case"hevc":this.videoParser=new zn}null!==this.videoParser&&this.videoParser.parsePES(r,l,n,!1)}c={data:[],size:0}}c&&(c.data.push(e.subarray(y,t+qn)),c.size+=t+qn-y);break;case h:if(s){if(f&&(n=ir(f,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n)}f={data:[],size:0}}f&&(f.data.push(e.subarray(y,t+qn)),f.size+=t+qn-y);break;case u:s&&(p&&(n=ir(p,this.logger))&&this.parseID3PES(a,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(y,t+qn)),p.size+=t+qn-y);break;case 0:s&&(y+=e[y]+1),v=this._pmtId=Zn(e,y);break;case v:{s&&(y+=e[y]+1);const n=Jn(e,y,this.typeSupported,i,this.observer,this.logger);d=n.videoPid,d>0&&(r.pid=d,r.segmentCodec=n.segmentVideoCodec),h=n.audioPid,h>0&&(o.pid=h,o.segmentCodec=n.segmentAudioCodec),u=n.id3Pid,u>0&&(a.pid=u),null===g||m||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${g}'. Backtracking to sync byte @${E} to parse all TS packets.`),g=null,t=E-188),m=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=A}}else y++;y>0&&er(this.observer,new Error(`Found ${y} TS packet/s that do not start with 0x47`),void 0,this.logger),r.pesData=c,o.pesData=f,a.pesData=p;const T={audioTrack:o,videoTrack:r,id3Track:a,textTrack:l};return s&&this.extractRemainingSamples(T),T}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{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:n}=e,r=i.pesData,o=t.pesData,a=s.pesData;let l;if(r&&(l=ir(r,this.logger))){if(null===this.videoParser)switch(i.segmentCodec){case"avc":this.videoParser=new Wn;break;case"hevc":this.videoParser=new zn}null!==this.videoParser&&(this.videoParser.parsePES(i,n,l,!0),i.pesData=null)}else i.pesData=r;if(o&&(l=ir(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;a&&(l=ir(a,this.logger))?(this.parseID3PES(s,l),s.pesData=null):s.pesData=a}demuxSampleAes(e,t,i){const s=this.demux(e,i,!0,!this.config.progressive),n=this.sampleAes=new Kn(this.observer,this.config,t);return this.decrypt(s,n)}decrypt(e,t){return new Promise((i=>{const{audioTrack:s,videoTrack:n}=e;s.samples&&"aac"===s.segmentCodec?t.decryptAacSamples(s.samples,0,(()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,(()=>{i(e)})):i(e)})):n.samples&&t.decryptAvcSamples(n.samples,0,0,(()=>{i(e)}))}))}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0;const s=this.aacOverFlow;let n,r,o,a=t.data;if(s){this.aacOverFlow=null;const t=s.missing,n=s.sample.unit.byteLength;if(-1===t)a=dt(s.sample.unit,a);else{const r=n-t;s.sample.unit.set(a.subarray(0,t),r),e.samples.push(s.sample),i=s.missing}}for(n=i,r=a.length;n0;)a+=r}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=ue({},t,{type:this._videoTrack?Rn.emsg:Rn.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Qn(e,t){return((31&e[t+1])<<8)+e[t+2]}function Zn(e,t){return(31&e[t+10])<<8|e[t+11]}function Jn(e,t,i,s,n,r){const o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t0){let s=t+5,n=l;for(;n>2;){106===e[s]&&(!0!==i.ac3?r.log("AC-3 audio found, not supported in this browser for now"):(o.audioPid=a,o.segmentAudioCodec="ac3"));const t=e[s+1]+2;s+=t,n-=t}}break;case 194:case 135:return er(n,new Error("Unsupported EC-3 in M2TS found"),void 0,r),o;case 36:-1===o.videoPid&&(o.videoPid=a,o.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"))}t+=l+5}return o}function er(e,t,i,s){s.warn(`parsing error: ${t.message}`),e.emit(te.ERROR,te.ERROR,{type:J.MEDIA_ERROR,details:ee.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function tr(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function ir(e,t){let i,s,n,r,o,a=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=dt(l[0],l[1]),l.splice(1,1);if(i=l[0],1===(i[0]<<16)+(i[1]<<8)+i[2]){if(s=(i[4]<<8)+i[5],s&&s>e.size-6)return null;const d=i[7];192&d&&(r=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&d?(o=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,r-o>54e5&&(t.warn(`${Math.round((r-o)/9e4)}s delta between PTS and DTS, align them`),r=o)):o=r),n=i[8];let c=n+9;if(e.size<=c)return null;e.size-=c;const h=new Uint8Array(e.size);for(let e=0,t=l.length;et){c-=t;continue}i=i.subarray(c),t-=c,c=0}h.set(i,a),a+=t}return s&&(s-=n+3),{data:h,pts:r,dts:o,len:s}}return null}class sr{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)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(6===t)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])}else{if(1===t)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(2===t)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(3===t)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])}}}const nr=Math.pow(2,32)-1;class rr{static init(){let e;for(e in rr.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},rr.types)rr.types.hasOwnProperty(e)&&(rr.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]);rr.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]),n=new Uint8Array([0,0,0,0,0,0,0,0]);rr.STTS=rr.STSC=rr.STCO=n,rr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),rr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),rr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),rr.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const r=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),a=new Uint8Array([0,0,0,1]);rr.FTYP=rr.box(rr.types.ftyp,r,a,r,o),rr.DINF=rr.box(rr.types.dinf,rr.box(rr.types.dref,s))}static box(e,...t){let i=8,s=t.length;const n=s;for(;s--;)i+=t[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]=255&i,r.set(e,4),s=0,i=8;s>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))}static mdia(e){return rr.box(rr.types.mdia,rr.mdhd(e.timescale||0,e.duration||0),rr.hdlr(e.type),rr.minf(e))}static mfhd(e){return rr.box(rr.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?rr.box(rr.types.minf,rr.box(rr.types.smhd,rr.SMHD),rr.DINF,rr.stbl(e)):rr.box(rr.types.minf,rr.box(rr.types.vmhd,rr.VMHD),rr.DINF,rr.stbl(e))}static moof(e,t,i){return rr.box(rr.types.moof,rr.mfhd(e),rr.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=rr.trak(e[t]);return rr.box.apply(null,[rr.types.moov,rr.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(rr.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=rr.trex(e[t]);return rr.box.apply(null,[rr.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(nr+1)),s=Math.floor(t%(nr+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,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 rr.box(rr.types.mvhd,n)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let s,n;for(s=0;s>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(i));for(t=0;t>>8&255),r.push(255&s),r=r.concat(Array.prototype.slice.call(i));const o=rr.box(rr.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|e.sps.length].concat(n).concat([e.pps.length]).concat(r))),a=e.width,l=e.height,d=e.pixelRatio[0],c=e.pixelRatio[1];return rr.box(rr.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,a>>8&255,255&a,l>>8&255,255&l,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,rr.box(rr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),rr.box(rr.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return rr.box(rr.types.mp4a,rr.audioStsd(e),rr.box(rr.types.esds,rr.esds(e)))}static mp3(e){return rr.box(rr.types[".mp3"],rr.audioStsd(e))}static ac3(e){return rr.box(rr.types["ac-3"],rr.audioStsd(e),rr.box(rr.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return rr.box(rr.types.stsd,rr.STSD,rr.mp4a(e));if("ac3"===t&&e.config)return rr.box(rr.types.stsd,rr.STSD,rr.ac3(e));if("mp3"===t&&"mp3"===e.codec)return rr.box(rr.types.stsd,rr.STSD,rr.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if("avc"===t)return rr.box(rr.types.stsd,rr.STSD,rr.avc1(e));if("hevc"===t&&e.vps)return rr.box(rr.types.stsd,rr.STSD,rr.hvc1(e))}throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,i=(e.duration||0)*(e.timescale||0),s=e.width||0,n=e.height||0,r=Math.floor(i/(nr+1)),o=Math.floor(i%(nr+1));return rr.box(rr.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,255&t,0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,o>>24,o>>16&255,o>>8&255,255&o,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,255&s,0,0,n>>8&255,255&n,0,0]))}static traf(e,t){const i=rr.sdtp(e),s=e.id,n=Math.floor(t/(nr+1)),r=Math.floor(t%(nr+1));return rr.box(rr.types.traf,rr.box(rr.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),rr.box(rr.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,r>>24,r>>16&255,r>>8&255,255&r])),rr.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,rr.box(rr.types.trak,rr.tkhd(e),rr.mdia(e))}static trex(e){const t=e.id;return rr.box(rr.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,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,n=12+16*s,r=new Uint8Array(n);let o,a,l,d,c,h;for(t+=8+n,r.set(["video"===e.type?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,255&s,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),o=0;o>>24&255,l>>>16&255,l>>>8&255,255&l,d>>>24&255,d>>>16&255,d>>>8&255,255&d,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,h>>>24&255,h>>>16&255,h>>>8&255,255&h],12+16*o);return rr.box(rr.types.trun,r)}static initSegment(e){rr.types||rr.init();const t=rr.moov(e);return dt(rr.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],s=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let n=s.length;for(let e=0;e>8,255&i[e][t].length]),n),n+=2,r.set(i[e][t],n),n+=i[e][t].length}const a=rr.box(rr.types.hvcC,r),l=e.width,d=e.height,c=e.pixelRatio[0],h=e.pixelRatio[1];return rr.box(rr.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,d>>8&255,255&d,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]),a,rr.box(rr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),rr.box(rr.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,h>>24,h>>16&255,h>>8&255,255&h])))}}function or(e,t,i=1,s=!1){const n=e*t*i;return s?Math.round(n):n}function ar(e,t=!1){return or(e,1e3,1/9e4,t)}rr.types=void 0,rr.HDLR_TYPES=void 0,rr.STTS=void 0,rr.STSC=void 0,rr.STCO=void 0,rr.STSZ=void 0,rr.VMHD=void 0,rr.SMHD=void 0,rr.STSD=void 0,rr.FTYP=void 0,rr.DINF=void 0;let lr,dr=null,cr=null;function hr(e,t,i,s){return{duration:t,size:i,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class ur{constructor(e,t,i,s){if(this.logger=void 0,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.logger=s,this.ISGenerated=!1,null===dr){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);dr=e?parseInt(e[1]):0}if(null===cr){const e=navigator.userAgent.match(/Safari\/(\d+)/i);cr=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,s=e.reduce(((e,s)=>{let n=s.pts,r=n-e;return r<-4294967296&&(t=!0,n=fr(n,i),r=n-e),r>0?e:n}),i);return t&&this.logger.debug("PTS rollover detected"),s}remux(e,t,i,s,n,r,o,a){let l,d,c,h,u,f,p=n,g=n;const m=e.pid>-1,v=t.pid>-1,A=t.samples.length,E=e.samples.length>0,y=o&&A>0||A>1;if((!m||E)&&(!v||y)||this.ISGenerated||o){if(this.ISGenerated){var T,b,S,_;const e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(b=e.pixelRatio)?void 0:b[0])||(null==(S=t.pixelRatio)?void 0:S[1])!==(null==(_=e.pixelRatio)?void 0:_[1]))||!e&&y||null===this.nextAudioPts&&E)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,n,r));const i=this.isVideoContiguous;let s,o=-1;if(y&&(o=function(e){for(let t=0;t0){this.logger.warn(`[mp4-remuxer]: Dropped ${o} out of ${A} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(o),t.dropped+=o,g+=(t.samples[0].pts-e)/t.inputTimeScale,s=g}else-1===o&&(this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${A} video samples`),f=!1);if(this.ISGenerated){if(E&&y){const i=this.getVideoStartPts(t.samples),s=(fr(e.samples[0].pts,i)-i)/t.inputTimeScale;p+=Math.max(0,s),g+=Math.max(0,-s)}if(E){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(e,t,n,r)),d=this.remuxAudio(e,p,this.isAudioContiguous,r,v||y||a===ae?g:void 0),y){const s=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(e,t,n,r)),l=this.remuxVideo(t,g,i,s)}}else y&&(l=this.remuxVideo(t,g,i,0));l&&(l.firstKeyFrame=o,l.independent=-1!==o,l.firstKeyFramePTS=s)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(u=pr(i,n,this._initPTS,this._initDTS)),s.samples.length&&(h=gr(s,n,this._initPTS))),{audio:d,video:l,initSegment:c,independent:f,text:h,id3:u}}generateIS(e,t,i,s){const n=e.samples,r=t.samples,o=this.typeSupported,a={},l=this._initPTS;let d,c,h,u=!l||s,f="audio/mp4";if(u&&(d=c=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(f="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}a.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&o.mpeg?new Uint8Array(0):rr.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(h=e.inputTimeScale,l&&h===l.timescale?u=!1:d=c=n[0].pts-Math.round(h*i))}if(t.sps&&t.pps&&r.length){if(t.timescale=t.inputTimeScale,a.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:rr.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(h=t.inputTimeScale,l&&h===l.timescale)u=!1;else{const e=this.getVideoStartPts(r),t=Math.round(h*i);c=Math.min(c,fr(r[0].dts,e)-t),d=Math.min(d,e-t)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(a).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:d,timescale:h},this._initDTS={baseTime:c,timescale:h}):d=h=void 0,{tracks:a,initPTS:d,timescale:h}}remuxVideo(e,t,i,s){const n=e.inputTimeScale,r=e.samples,o=[],a=r.length,l=this._initPTS;let d,c,h=this.nextAvcDts,u=8,f=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,m=!1;if(!i||null===h){const e=t*n,s=r[0].pts-fr(r[0].dts,r[0].pts);dr&&null!==h&&Math.abs(e-s-h)<15e3?i=!0:h=e-s}const v=l.baseTime*n/l.timescale;for(let e=0;e0?e-1:e].dts&&(m=!0)}m&&r.sort((function(e,t){const i=e.dts-t.dts,s=e.pts-t.pts;return i||s})),d=r[0].dts,c=r[r.length-1].dts;const A=c-d,E=A?Math.round(A/(a-1)):f||e.inputTimeScale/30;if(i){const i=d-h,s=i>E,n=i<-1;if((s||n)&&(s?this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ar(i,!0)} ms (${i}dts) hole between fragments detected at ${t.toFixed(3)}`):this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ar(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!n||h>=r[0].pts||dr)){d=h;const e=r[0].pts-i;if(s)r[0].dts=d,r[0].pts=e;else{let t=!0;for(let s=0;se&&t);s++){const e=r[s].pts;if(r[s].dts-=i,r[s].pts-=i,s0?t.dts-r[e-1].dts:E;if(l=e>0?t.pts-r[e-1].pts:E,i.stretchShortVideoTrack&&null!==this.nextAudioPts){const e=Math.floor(i.maxBufferHole*n),r=(s?p+s*n:this.nextAudioPts)-t.pts;r>e?(f=r-o,f<0?f=o:R=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${r/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=o}else f=o}const c=Math.round(t.pts-t.dts);L=Math.min(L,f),k=Math.max(k,f),I=Math.min(I,l),w=Math.max(w,l),o.push(hr(t.key,f,d,c))}if(o.length)if(dr){if(dr<70){const e=o[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(cr&&w-I0&&(s&&Math.abs(m-g)<9e3||Math.abs(fr(f[0].pts-v,m)-g)<20*l),f.forEach((function(e){e.pts=fr(e.pts-v,m)})),!i||g<0){if(f=f.filter((e=>e.pts>=0)),!f.length)return;g=0===n?0:s&&!u?Math.max(0,m):f[0].pts}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let i=0,s=g;i=t*l&&d<1e4&&u){let t=Math.round(a/l);s=o-t*l,s<0&&(t--,s+=l),0===i&&(this.nextAudioPts=g=s),this.logger.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(s/r).toFixed(3)}s due to ${Math.round(1e3*a/r)} ms gap.`);for(let r=0;r0))return;T+=p;try{A=new Uint8Array(T)}catch(e){return void this.observer.emit(te.ERROR,te.ERROR,{type:J.MUX_ERROR,details:ee.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:T,reason:`fail allocating audio mdat ${T}`})}c||(new DataView(A.buffer).setUint32(0,T),A.set(rr.types.mdat,4))}A.set(n,p);const l=n.byteLength;p+=l,h.push(hr(!0,a,l,0)),y=r}const S=h.length;if(!S)return;const _=h[h.length-1];this.nextAudioPts=g=y+o*_.duration;const C=c?new Uint8Array(0):rr.moof(e.sequenceNumber++,E/o,ue({},e,{samples:h}));e.samples=[];const R=E/r,L=g/r,I={data1:C,data2:A,startPTS:R,endPTS:L,startDTS:R,endDTS:L,type:"audio",hasAudio:!0,hasVideo:!1,nb:S};return this.isAudioContiguous=!0,I}}function fr(e,t){let i;if(null===t)return e;for(i=t4294967296;)e+=i;return e}function pr(e,t,i,s){const n=e.samples.length;if(!n)return;const r=e.inputTimeScale;for(let o=0;oe.pts-t.pts));const r=e.samples;return e.samples=[],{samples:r}}function mr(e,t){const i=null==e?void 0:e.codec;return i&&i.length>4?i:t===xe?"ec-3"===i||"ac-3"===i||"alac"===i?i:"fLaC"===i||"Opus"===i?Rt(i,!1):(Te.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(Te.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}try{lr=self.performance.now.bind(self.performance)}catch(e){lr=Date.now}const vr=[{demux:class{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 n=this.videoTrack=Ln("video",1),r=this.audioTrack=Ln("audio",1),o=this.txtTrack=Ln("text",1);if(this.id3Track=Ln("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const a=tt(e);if(a.video){const{id:e,timescale:t,codec:i,supplemental:s}=a.video;n.id=e,n.timescale=o.timescale=t,n.codec=i,n.supplemental=s}if(a.audio){const{id:e,timescale:t,codec:i}=a.audio;r.id=e,r.timescale=t,r.codec=i}o.id=Ye.text,n.sampleDuration=0,n.duration=r.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let i=0;i8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=s>1?i+s:t}return!1}(e)}demux(e,t){this.timeOffset=t;let i=e;const s=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=dt(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},i=Je(e,["moof"]);if(i.length<2)return t.remainder=e,t;const s=i[i.length-1];return t.valid=e.slice(0,s.byteOffset-8),t.remainder=e.slice(s.byteOffset-8),t}(i);this.remainderData=t.remainder,s.samples=t.valid||new Uint8Array}else s.samples=i;const r=this.extractID3Track(s,t);return n.samples=ct(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:r,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=ct(e,t),{videoTrack:t,audioTrack:Ln(),id3Track:s,textTrack:Ln()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const s=Je(e.samples,["emsg"]);s&&s.forEach((e=>{const s=function(e){const t=e[0];let i="",s="",n=0,r=0,o=0,a=0,l=0,d=0;if(0===t){for(;"\0"!==We(e.subarray(d,d+1));)i+=We(e.subarray(d,d+1)),d+=1;for(i+=We(e.subarray(d,d+1)),d+=1;"\0"!==We(e.subarray(d,d+1));)s+=We(e.subarray(d,d+1)),d+=1;s+=We(e.subarray(d,d+1)),d+=1,n=qe(e,12),r=qe(e,16),a=qe(e,20),l=qe(e,24),d=28}else if(1===t){d+=4,n=qe(e,d),d+=4;const t=qe(e,d);d+=4;const r=qe(e,d);for(d+=4,o=2**32*t+r,Q(o)||(o=Number.MAX_SAFE_INTEGER,Te.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),a=qe(e,d),d+=4,l=qe(e,d),d+=4;"\0"!==We(e.subarray(d,d+1));)i+=We(e.subarray(d,d+1)),d+=1;for(i+=We(e.subarray(d,d+1)),d+=1;"\0"!==We(e.subarray(d,d+1));)s+=We(e.subarray(d,d+1)),d+=1;s+=We(e.subarray(d,d+1)),d+=1}return{schemeIdUri:i,value:s,timeScale:n,presentationTime:o,presentationTimeDelta:r,eventDuration:a,id:l,payload:e.subarray(d,e.byteLength)}}(e);if(Gn.test(s.schemeIdUri)){const e=jn(s,t);let n=4294967295===s.eventDuration?Number.POSITIVE_INFINITY:s.eventDuration/s.timeScale;n<=.001&&(n=Number.POSITIVE_INFINITY);const r=s.payload;i.samples.push({data:r,len:r.byteLength,dts:e,pts:e,type:Rn.emsg,duration:n})}else if(this.config.enableEmsgKLVMetadata&&s.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const e=jn(s,t);i.samples.push({data:s.payload,len:s.payload.byteLength,dts:e,pts:e,type:Rn.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class{constructor(e,t,i,s){this.logger=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.logger=s}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(function(e,t){if(!e||!t)return e;const i=t.keyId;return i&&t.isCommonEncryption&&Je(e,["moov","trak"]).forEach((e=>{const t=Je(e,["mdia","minf","stbl","stsd"])[0].subarray(8);let s=Je(t,["enca"]);const n=s.length>0;n||(s=Je(t,["encv"])),s.forEach((e=>{Je(n?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const t=at(e);if(t){const e=t.subarray(8,24);e.some((e=>0!==e))||(Te.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${Ce(e)} -> ${Ce(i)}`),t.set(i,8))}}))}))})),e}(e,s)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const s=this.initData=tt(e);s.audio&&(t=mr(s.audio,xe)),s.video&&(i=mr(s.video,Be));const n={};s.audio&&s.video?n.audiovideo={container:"video/mp4",codec:t+","+i,supplemental:s.video.supplemental,initSegment:e,id:"main"}:s.audio?n.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:s.video?n.video={container:"video/mp4",codec:i,supplemental:s.video.supplemental,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(e,t,i,s,n,r){var o,a;let{initPTS:l,lastEndTime:d}=this;const c={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};X(d)||(d=this.lastEndTime=n||0);const h=t.samples;if(null==h||!h.length)return c;const u={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(o=f)&&o.length||(this.generateInitSegment(h),f=this.initData),null==(a=f)||!a.length)return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const p=function(e,t){let i=0,s=0,n=0;const r=Je(e,["moof","traf"]);for(let e=0;ee+t.info.duration||0),0);i=Math.max(i,e+r.earliestPresentationTime/r.timescale),s=i-t}}if(s&&X(s))return s}return s||n}(h,f),g=function(e,t){return Je(t,["moof","traf"]).reduce(((t,i)=>{const s=Je(i,["tfdt"])[0],n=s[0],r=Je(i,["tfhd"]).reduce(((t,i)=>{const r=qe(i,4),o=e[r];if(o){let e=qe(s,4);if(1===n){if(e===Ke)return Te.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;e*=Ke+1,e+=qe(s,8)}const i=e/(o.timescale||9e4);if(X(i)&&(null===t||in}(l,m,n,p)&&u.timescale===l.timescale||(u.initPTS=m-n,l&&1===l.timescale&&this.logger.warn(`Adjusting initPTS @${n} from ${l.baseTime/l.timescale} to ${u.initPTS}`),this.initPTS=l={baseTime:u.initPTS,timescale:1});const v=e?m-l.baseTime/l.timescale:d,A=v+p;!function(e,t,i){Je(t,["moof","traf"]).forEach((t=>{Je(t,["tfhd"]).forEach((s=>{const n=qe(s,4),r=e[n];if(!r)return;const o=r.timescale||9e4;Je(t,["tfdt"]).forEach((e=>{const t=e[0],s=i*o;if(s){let i=qe(e,4);if(0===t)i-=s,i=Math.max(i,0),Ze(e,4,i);else{i*=Math.pow(2,32),i+=qe(e,8),i-=s,i=Math.max(i,0);const t=Math.floor(i/(Ke+1)),n=Math.floor(i%(Ke+1));Ze(e,4,t),Ze(e,8,n)}}}))}))}))}(f,h,l.baseTime/l.timescale),p>0?this.lastEndTime=A:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const E=!!f.audio,y=!!f.video;let T="";E&&(T+="audio"),y&&(T+="video");const b={data1:h,startPTS:v,startDTS:v,endPTS:A,endDTS:A,type:T,hasAudio:E,hasVideo:y,nb:1,dropped:0};return c.audio="audio"===b.type?b:void 0,c.video="audio"!==b.type?b:void 0,c.initSegment=u,c.id3=pr(i,n,l,l),s.samples.length&&(c.text=gr(s,n,l)),c}}},{demux:Xn,remux:ur},{demux:class extends In{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,t){if(!e)return!1;const i=ln(e,0);let s=(null==i?void 0:i.length)||0;if(Un(e,s))return!1;for(let i=e.length;s0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(i=t),i}(r,t);if(E&&$i(E.method)){const e=this.getDecrypter(),t=Vi(E.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(r,E.key.buffer,E.iv.buffer,t).then((e=>{const t=this.push(e,null,i);return this.decryptionPromise=null,t})),this.decryptionPromise;{let s=e.softwareDecrypt(r,E.key.buffer,E.iv.buffer,t);if(i.part>-1){const t=e.flush();s=t?t.buffer:t}if(!s)return n.executeEnd=lr(),Er(i);r=new Uint8Array(s)}}const y=this.needsProbing(d,c);if(y){const e=this.configureTransmuxer(r);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(te.ERROR,te.ERROR,{type:J.MEDIA_ERROR,details:ee.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),n.executeEnd=lr(),Er(i)}(d||c||f||y)&&this.resetInitSegment(A,p,g,v,t),(d||f||y)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const T=this.transmux(r,E,u,h,i);this.asyncResult=yr(T);const b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,n.executeEnd=lr(),T}flush(e){const t=e.transmuxing;t.executeStart=lr();const{decrypter:i,currentTransmuxState:s,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then((()=>this.flush(e)));const r=[],{timeOffset:o}=s;if(i){const t=i.flush();t&&r.push(this.push(t.buffer,null,e))}const{demuxer:a,remuxer:l}=this;if(!a||!l){t.executeEnd=lr();const i=[Er(e)];return this.asyncResult?Promise.resolve(i):i}const d=a.flush(o);return yr(d)?(this.asyncResult=!0,d.then((t=>(this.flushRemux(r,t,e),r)))):(this.flushRemux(r,d,e),this.asyncResult?Promise.resolve(r):r)}flushRemux(e,t,i){const{audioTrack:s,videoTrack:n,id3Track:r,textTrack:o}=t,{accurateTimeOffset:a,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===oe?"level":"track"} ${i.level}`);const d=this.remuxer.remux(s,n,r,o,l,a,!0,this.id);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=lr()}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,n){const{demuxer:r,remuxer:o}=this;r&&o&&(r.resetInitSegment(e,t,i,s),o.resetInitSegment(e,t,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,s,n){let r;return r=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,s,n):this.transmuxUnencrypted(e,i,s,n),r}transmuxUnencrypted(e,t,i,s){const{audioTrack:n,videoTrack:r,id3Track:o,textTrack:a}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,r,o,a,t,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,i,s,n){return this.demuxer.demuxSampleAes(e,t,i).then((e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,s,!1,this.id),chunkMeta:n})))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:s}=this;let n;for(let t=0,i=vr.length;t({remuxResult:{},chunkMeta:e});function yr(e){return"then"in e&&e.then instanceof Function}class Tr{constructor(e,t,i,s,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=s,this.defaultInitPts=n||null}}class br{constructor(e,t,i,s,n,r){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=n,this.initSegmentChange=r}}let Sr=0;class _r{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Sr++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=e=>{const t=e.data,i=this.hls;if(i&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var s;const e=null==(s=this.workerContext)?void 0:s.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,i.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(te.ERROR,{type:J.OTHER_ERROR,details:ee.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const r=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===te.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new tn,this.observer.on(te.FRAG_DECRYPTED,r),this.observer.on(te.ERROR,r);const o=kt(n.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const i=this.hls.logger;if(n.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{n.workerPath?(i.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=function(e){const t=nn[e];if(t)return t.clientCount++,t;const i=new self.URL(e,self.location.href).href,s={worker:new self.Worker(i),scriptURL:i,clientCount:1};return nn[e]=s,s}(n.workerPath)):(i.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=nn[sn];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(t),s={worker:new self.Worker(i),objectURL:i,clientCount:1};return nn[sn]=s,s}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:Gt(n)})}catch(s){i.warn(`Error setting up "${t}" Web Worker, fallback to inline`,s),this.terminateWorker(),this.error=null,this.transmuxer=new Ar(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new Ar(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Sr++;const t=this.hls.config,i=kt(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:Gt(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){const t=nn[e||sn];if(t&&1==t.clientCount--){const{worker:i,objectURL:s}=t;delete nn[e||sn],s&&self.URL.revokeObjectURL(s),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,s,n,r,o,a,l,d){var c,h;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,p=r?r.start:n.start,g=n.decryptdata,m=this.frag,v=!(m&&n.cc===m.cc),A=!(m&&l.level===m.level),E=m?l.sn-m.sn:-1,y=this.part?l.part-this.part.index:-1,T=0===E&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),b=!A&&(1===E||0===E&&(1===y||T&&y<=0)),S=self.performance.now();(A||E||0===n.stats.parsing.start)&&(n.stats.parsing.start=S),!r||!y&&b||(r.stats.parsing.start=S);const _=!(m&&(null==(c=n.initSegment)?void 0:c.url)===(null==(h=m.initSegment)?void 0:h.url)),C=new br(v,b,a,A,p,_);if(!b||v||_){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===oe?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${A}\n contiguous: ${b}\n accurateTimeOffset: ${a}\n timeOffset: ${p}\n initSegmentChange: ${_}`);const e=new Tr(i,s,t,o,d);this.configureTransmuxer(e)}if(this.frag=n,this.part=r,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:e,decryptdata:g,chunkMeta:l,state:C},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,g,l,C);yr(t)?t.then((e=>{this.handleTransmuxComplete(e)})).catch((e=>{this.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const t=i.flush(e);yr(t)?t.then((t=>{this.handleFlushResult(t,e)})).catch((t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")})):this.handleFlushResult(t,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(te.ERROR,{type:J.MEDIA_ERROR,details:ee.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach((e=>{this.handleTransmuxComplete(e)})),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class Cr extends ge{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const s=null==t?void 0:t.renditionReports;if(s){let n=-1;for(let i=0;i=0&&e>t.partTarget&&(o+=1)}const a=i&&Ft(i);return new Ut(r,o>=0?o:void 0,a)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,i){const{details:s,stats:n}=t,r=self.performance.now(),o=n.loading.first?Math.max(0,r-n.loading.first):0;s.advancedDateTime=Date.now()-o;const a=this.hls.config.timelineOffset;if(a!==s.appliedTimelineOffset){const e=Math.max(a||0,0);s.appliedTimelineOffset=e,s.fragments.forEach((t=>{t.start=t.playlistOffset+e}))}if(s.live||null!=i&&i.live){const a="levelInfo"in t?t.levelInfo:t.track;if(s.reloaded(i),i&&s.fragments.length>0){!function(e,t){if(e===t)return;let i=null;const s=e.fragments;for(let e=s.length-1;e>=0;e--){const t=s[e].initSegment;if(t){i=t;break}}let n;e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,i){const s=t.skippedSegments,n=Math.max(e.startSN,t.startSN)-t.startSN,r=(e.fragmentHint?1:0)+(s?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,o=t.startSN-e.startSN,a=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let d=n;d<=r;d++){const n=l[o+d];let r=a[d];if(s&&!r&&n&&(r=t.fragments[d]=n),n&&r){if(i(n,r,d,a),n.url&&n.url!==r.url)return void(t.playlistParsingError=_s(`media sequence mismatch ${r.sn}:`,e,t,0,r));if(n.cc!==r.cc)return void(t.playlistParsingError=_s(`discontinuity sequence mismatch (${n.cc}!=${r.cc})`,e,t,0,r))}}}(e,t,((s,r,o,a)=>{if(!t.startCC&&r.cc!==s.cc){var l,d;const i=s.cc-r.cc;for(let e=o;e{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)})),t.skippedSegments)if(t.deltaUpdateFailed=r.some((e=>!e)),t.deltaUpdateFailed){Te.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)r.shift();t.startSN=r[0].sn}else{t.endCC=r[r.length-1].cc,t.canSkipDateRanges&&(t.dateRanges=function(e,t){const{dateRanges:i,recentlyRemovedDateranges:s}=t,n=ue({},e);s&&s.forEach((e=>{delete n[e]}));const r=Object.keys(n).length;return r&&Object.keys(i).forEach((e=>{const t=n[e],s=new Fi(i[e].attr,t);s.isValid?(n[e]=s,t||(s.tagOrder+=r)):Te.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Gt(i[e].attr)}"`)})),n}(e.dateRanges,t));const i=e.fragments.filter((e=>e.rawProgramDateTime));if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),n?Ss(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):Cs(e,t),r.length&&(t.totalduration=t.edge-r[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const a=t.advancedDateTime;if(t.advanced&&a){const e=t.edge;t.driftStart||(t.driftStartTime=a,t.driftStart=e),t.driftEndTime=a,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}(i,s);const e=s.playlistParsingError;if(e){this.warn(e);const i=this.hls;if(!i.config.ignorePlaylistParsingErrors){var l;const{networkDetails:r}=t;return void i.trigger(te.ERROR,{type:J.NETWORK_ERROR,details:ee.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(l=s.fragments[0])?void 0:l.type,networkDetails:r,stats:n})}s.playlistParsingError=null}}-1===s.requestScheduled&&(s.requestScheduled=n.loading.start);const d=this.hls.mainForwardBufferInfo,c=d?d.end-d.len:0,h=Ls(s,1e3*(s.edge-c));if(s.requestScheduled+h0){if(h>3*s.targetduration)this.log(`Playlist last advanced ${c.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,p=void 0;else if(null!=i&&i.tuneInGoal&&h-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${g} with playlist age: ${s.age}`),g=0;else{const e=Math.floor(g/s.targetduration);f+=e,void 0!==p&&(p+=Math.round(g%s.targetduration/s.partTarget)),this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${c.toFixed(2)}s goal: ${g} skip sn ${e} to part ${p}`)}s.tuneInGoal=g}if(u=this.getDeliveryDirectives(s,t.deliveryDirectives,f,p),e||!d)return s.requestScheduled=r,void this.loadingPlaylist(a,u)}else(s.canBlockReload||s.canSkipUntil)&&(u=this.getDeliveryDirectives(s,t.deliveryDirectives,f,p));u&&void 0!==f&&s.canBlockReload&&(s.requestScheduled=n.loading.first+Math.max(h-2*o,h/2)),this.scheduleLoading(a,u,s)}else this.clearTimer()}scheduleLoading(e,t,i){const s=i||e.details;if(!s)return void this.loadingPlaylist(e,t);const n=self.performance.now(),r=s.requestScheduled;if(n>=r)return void this.loadingPlaylist(e,t);const o=r-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout((()=>this.loadingPlaylist(e,t)),o)}getDeliveryDirectives(e,t,i,s){let n=Ft(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,n=""),new Ut(i,s,n)}checkRetry(e){const t=e.details,i=ii(e),s=e.errorAction,{action:n,retryCount:r=0,retryConfig:o}=s||{},a=!!s&&!!o&&(5===n||!s.resolved&&2===n);if(a){var l;if(r>=o.maxNumRetry)return!1;if(i&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${r+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=ni(o,r);this.clearTimer(),this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${r+1}/${o.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,s.resolved=!0}return a}}function Rr(e,t){if(e.length!==t.length)return!1;for(let i=0;ie[i]!==t[i]))}function Ir(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}class kr{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(null===this.queues||null===this.tracks)return;const s=this.queues[t];s.push(e),1!==s.length||i||this.executeNext(t)}appendBlocker(e){return new Promise((t=>{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)}))}prependBlocker(e){return new Promise((t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}}))}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((e=>{var t;const i=null==(t=e[0])?void 0:t.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(e[0].execute(),e.splice(0,1))}))}unblockAudio(e){null!==this.queues&&this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const s=t[0];try{s.execute()}catch(t){var i;if(s.onError(t),null===this.queues||null===this.tracks)return;const n=null==(i=this.tracks[e])?void 0:i.buffer;null!=n&&n.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=null==(t=this.tracks)?void 0:t[e],s=null==i?void 0:i.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map((e=>e.label)).join(", "))||""}}const wr=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Pr="HlsJsTrackRemovedError";class Or extends Error{constructor(e){super(e),this.name=Pr}}function Dr(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach((t=>{e.removeChild(t)}))}function Nr(e){return"audio"===e?1:0}class Mr{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(te.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(te.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(te.MANIFEST_PARSED,this.onManifestParsed,this),e.on(te.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(te.BUFFER_CODECS,this.onBufferCodecs,this),e.on(te.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(te.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(te.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(te.MANIFEST_PARSED,this.onManifestParsed,this),e.off(te.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(te.BUFFER_CODECS,this.onBufferCodecs,this),e.off(te.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&&X(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter(((t,i)=>this.isLevelAllowed(t)&&i<=e));return this.clientRect=null,Mr.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(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some((t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height))}static getMaxLevelByMediaSize(e,t,i){if(null==e||!e.length)return-1;let s=e.length-1;const n=Math.max(t,i);for(let t=0;t=n||i.height>=n)&&(r=i,!(o=e[t+1])||r.width!==o.width||r.height!==o.height)){s=t;break}}var r,o;return s}}const xr="m",Br="a",Fr="v",Ur="av",$r="i",Vr="tt",Gr="h",jr="CMCD-Object",Kr="CMCD-Request",Hr="CMCD-Session",Yr="CMCD-Status",Wr={[jr]:["br","d","ot","tb"],[Kr]:["bl","dl","mtp","nor","nrr","su"],[Hr]:["cid","pr","sf","sid","st","v"],[Yr]:["bs","rtp"]};class zr{constructor(e,t){Array.isArray(e)&&(e=e.map((e=>e instanceof zr?e:new zr(e)))),this.value=e,this.params=t}}function qr(e,t,i){return function(e,t,i,s){return new Error(`failed to ${e} "${n=t,Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"==typeof n?JSON.stringify(n):String(n)}" as ${i}`,{cause:s});var n}("serialize",e,t,i)}class Xr{constructor(e){this.description=e}}const Qr="Bare Item";function Zr(e){if(function(e){return e<-999999999999999||99999999999999912)throw qr(e,"Decimal");const i=t.toString();return i.includes(".")?i:`${i}.0`}const eo=/[\x00-\x1f\x7f]+/;function to(e){const t=(i=e).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw qr(t,"Token");return t}function io(e){switch(typeof e){case"number":if(!X(e))throw qr(e,Qr);return Number.isInteger(e)?Zr(e):Jr(e);case"string":return function(e){if(eo.test(e))throw qr(e,"String");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return to(e);case"boolean":return function(e){if("boolean"!=typeof e)throw qr(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return`@${Zr(e.getTime()/1e3)}`}(e);if(e instanceof Uint8Array)return function(e){if(!1===ArrayBuffer.isView(e))throw qr(e,"Byte Sequence");return`:${t=e,btoa(String.fromCharCode(...t))}:`;var t}(e);if(e instanceof Xr)return to(e);default:throw qr(e,Qr)}}function so(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw qr(e,"Key");return e}function no(e){return null==e?"":Object.entries(e).map((([e,t])=>!0===t?`;${so(e)}`:`;${so(e)}=${io(t)}`)).join("")}function ro(e){return e instanceof zr?`${io(e.value)}${no(e.params)}`:io(e)}const oo=e=>Math.round(e),ao=e=>100*oo(e/100),lo={br:oo,d:oo,bl:ao,dl:ao,mtp:ao,nor:(e,t)=>((null==t?void 0:t.baseUrl)&&(e=function(e,t){const i=new URL(e),s=new URL(t);if(i.origin!==s.origin)return e;const n=i.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1);for(;n[0]===r[0];)n.shift(),r.shift();for(;r.length;)r.shift(),n.unshift("..");return n.join("/")}(e,t.baseUrl)),encodeURIComponent(e)),rtp:ao,tb:oo};function co(e,t={}){return e?function(e,t){return function(e,t={whitespace:!0}){if("object"!=typeof e)throw qr(e,"Dict");const i=e instanceof Map?e.entries():Object.entries(e),s=(null==t?void 0:t.whitespace)?" ":"";return Array.from(i).map((([e,t])=>{t instanceof zr==0&&(t=new zr(t));let i=so(e);var s;return!0===t.value?i+=no(t.params):(i+="=",Array.isArray(t.value)?i+=`(${(s=t).value.map(ro).join(" ")})${no(s.params)}`:i+=ro(t)),i})).join(`,${s}`)}(e,t)}(function(e,t){const i={};if(null==e||"object"!=typeof e)return i;const s=Object.keys(e).sort(),n=ue({},lo,null==t?void 0:t.formatters),r=null==t?void 0:t.filter;return s.forEach((s=>{if(null==r?void 0:r(s))return;let o=e[s];const a=n[s];a&&(o=a(o,t)),"v"===s&&1===o||"pr"==s&&1===o||function(e){return"number"==typeof e?X(e):null!=e&&""!==e&&!1!==e}(o)&&(function(e){return"ot"===e||"sf"===e||"st"===e}(s)&&"string"==typeof o&&(o=new Xr(o)),i[s]=o)})),i}(e,t),ue({whitespace:!1},t)):""}const ho=/CMCD=[^&#]+/;function uo(e,t,i,s){e&&Object.keys(t).forEach((n=>{const r=e.filter((e=>e.groupId===n)).map((e=>{const r=ue({},e);return r.details=void 0,r.attrs=new xi(r.attrs),r.url=r.attrs.URI=fo(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),r.groupId=r.attrs["GROUP-ID"]=t[n],r.attrs["PATHWAY-ID"]=s,r}));e.push(...r)}))}function fo(e,t,i,s){const{HOST:n,PARAMS:r,[i]:o}=s;let a;t&&(a=null==o?void 0:o[t],a&&(e=a));const l=new self.URL(e);return n&&!a&&(l.host=n),r&&Object.keys(r).sort().forEach((e=>{e&&l.searchParams.set(e,r[e])})),l.href}class po extends ge{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=po.CDMCleanupPromise?[po.CDMCleanupPromise]:[],this.onMediaEncrypted=e=>{const{initDataType:t,initData:i}=e,s=`"${e.type}" event: init data type: "${t}"`;if(this.debug(s),null!==i){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=Ji(this.config));const t=e.map(Zi).filter((e=>!!e));this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then((n=>{const r=Xi(n);let o,a;if("sinf"===t){if(r!==Hi.FAIRPLAY)return void this.warn(`Ignoring unexpected "${e.type}" event with init data type: "${t}" for selected key-system ${r}`);const n=We(new Uint8Array(i));try{const e=at(Gi(JSON.parse(n).sinf));if(!e)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(e.subarray(8,24)),a=Hi.FAIRPLAY}catch(e){return void this.warn(`${s} Failed to parse sinf: ${e}`)}}else{if(r!==Hi.WIDEVINE&&r!==Hi.PLAYREADY)return void this.warn(`Ignoring unexpected "${e.type}" event with init data type: "${t}" for selected key-system ${r}`);const n=function(e){const t=[];if(e instanceof ArrayBuffer){const i=e.byteLength;let s=0;for(;s+32!!e.systemId&&Qi(e.systemId)===r));l.length>1&&this.warn(`${s} Using first of ${l.length} pssh found for selected key-system ${r}`);const d=l[0];if(!d)return void(0===n.length||n.some((e=>!e.systemId))?this.warn(`${s} contains incomplete or invalid pssh data`):this.log(`ignoring ${s} for ${n.map((e=>Qi(e.systemId))).join(",")} pssh data in favor of playlist keys`));if(a=Qi(d.systemId),0===d.version&&d.data)if(a===Hi.WIDEVINE){const e=d.data.length-22;o=new Uint8Array(d.data.subarray(e,e+16))}else a===Hi.PLAYREADY&&(o=is(d.data))}if(!a||!o)return;const l=Ce(o),{keyIdToKeySessionPromise:d,mediaKeySessions:c}=this;let h=d[l];for(let e=0;ethis.generateRequestWithPreferredKeySession(s,t,i,"encrypted-event-key-match"))),h.catch((e=>this.handleError(e)));break}}if(!h){if(a!==r)return void this.log(`Ignoring "${e.type}" event with ${a} init data for selected key-system ${r}`);h=d[l]=this.getKeySystemSelectionPromise([a]).then((({keySystem:e,mediaKeys:s})=>{var n;this.throwIfDestroyed();const r=new ns("ISO-23001-7",l,null!=(n=Zi(e))?n:"");return r.pssh=new Uint8Array(i),r.keyId=o,this.attemptSetMediaKeys(e,s).then((()=>{this.throwIfDestroyed();const n=this.createMediaKeySessionContext({decryptdata:r,keySystem:e,mediaKeys:s});return this.generateRequestWithPreferredKeySession(n,t,i,"encrypted-event-no-match")}))})),h.catch((e=>this.handleError(e)))}}))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){const e=this.media;this.unregisterListeners(),this.onMediaDetached(),this._clear(e);const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(te.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(te.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(te.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(te.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(te.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(te.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(te.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(te.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,s=t[e];return s?s.licenseUrl:e===Hi.WIDEVINE&&i?i:void 0}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error(`no license server URL configured for key-system "${e}"`);return t}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=(e,t,i)=>!!e&&i.indexOf(e)===t,s=t.map((e=>e.audioCodec)).filter(i),n=t.map((e=>e.videoCodec)).filter(i);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise(((t,i)=>{const r=e=>{const o=e.shift();this.getMediaKeysPromise(o,s,n).then((e=>t({keySystem:o,mediaKeys:e}))).catch((t=>{e.length?r(e):i(t instanceof go?t:new go({type:J.KEY_SYSTEM_ERROR,details:ee.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};r(e)}))}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let e=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===es&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return i(e,t)}getMediaKeysPromise(e,t,i){const s=function(e,t,i,s){let n;switch(e){case Hi.FAIRPLAY:n=["cenc","sinf"];break;case Hi.WIDEVINE:case Hi.PLAYREADY:n=["cenc"];break;case Hi.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,i,s){return[{initDataTypes:e,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:t.map((e=>({contentType:`audio/mp4; codecs=${e}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null}))),videoCapabilities:i.map((e=>({contentType:`video/mp4; codecs=${e}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null})))}]}(n,t,i,s)}(e,t,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[e];let r=null==n?void 0:n.keySystemAccess;if(!r){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Gt(s)}`),r=this.requestMediaKeySystemAccess(e,s);const t=this.keySystemAccessPromises[e]={keySystemAccess:r};return r.catch((t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)})),r.then((i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const s=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),t.mediaKeys=i.createMediaKeys().then((t=>(this.log(`Media-keys created for "${e}"`),s.then((i=>i?this.setMediaKeysServerCertificate(t,e,i):t))))),t.mediaKeys.catch((t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)})),t.mediaKeys}))}return r.then((()=>n.mediaKeys))}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${Ce(e.keyId||[])}`);const s=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),s=this.getKeyIdString(t),n="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,n,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return Ce(e.keyId)}updateKeySession(e,t){var i;const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyID ${Ce((null==(i=e.decryptdata)?void 0:i.keyId)||[])}\n } (data length: ${t?t.byteLength:t})`),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=Ji(this.config),n=e.map(Xi).filter((e=>!!e&&-1!==s.indexOf(e)));return this.getKeySystemSelectionPromise(n).then((({keySystem:e})=>{const s=Zi(e);s?t(s):i(new Error(`Unable to find format for key-system "${e}"`))})).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 n=this.keyIdToKeySessionPromise[i];return n||(n=this.getKeySystemForKeyPromise(t).then((({keySystem:i,mediaKeys:n})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${s}`),this.attemptSetMediaKeys(i,n).then((()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:i,mediaKeys:n,decryptdata:t}))))))),(this.keyIdToKeySessionPromise[i]=n.then((e=>{const i=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,"cenc",i,"playlist-key")}))).catch((e=>this.handleError(e)))),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof go?this.hls.trigger(te.ERROR,e.data):this.hls.trigger(te.ERROR,{type:J.KEY_SYSTEM_ERROR,details:ee.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const t=Xi(e.keyFormat),i=t?[t]:Ji(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Ji(this.config)),0===e.length)throw new go({type:J.KEY_SYSTEM_ERROR,details:ee.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Gt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}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((e=>-1===i.indexOf(e)))}))}generateRequestWithPreferredKeySession(e,t,i,s){var n,r;const o=null==(n=this.config.drmSystems)||null==(r=n[e.keySystem])?void 0:r.generateRequest;if(o)try{const s=o.call(this.hls,t,i,e);if(!s)throw new Error("Invalid response from configured generateRequest filter");t=s.initDataType,i=s.initData?s.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(e){var a;if(this.warn(e.message),null!=(a=this.hls)&&a.config.debug)throw e}if(null===i)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${s}": ${l} (init data type: ${t} length: ${i?i.byteLength:null})`);const d=new tn,c=e._onmessage=t=>{const i=e.mediaKeysSession;if(!i)return void d.emit("error",new Error("invalid state"));const{messageType:s,message:n}=t;this.log(`"${s}" message event for session "${i.sessionId}" message size: ${n.byteLength}`),"license-request"===s||"license-renewal"===s?this.renewLicense(e,n).catch((e=>{d.eventNames().length?d.emit("error",e):this.handleError(e)})):"license-release"===s?e.keySystem===Hi.FAIRPLAY&&(this.updateKeySession(e,ji("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${s}"`)},h=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void d.emit("error",new Error("invalid state"));this.onKeyStatusChange(e);const i=e.keyStatus;d.emit("keyStatus",i),"expired"===i&&(this.warn(`${e.keySystem} expired for key ${l}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",c),e.mediaKeysSession.addEventListener("keystatuseschange",h);const u=new Promise(((e,t)=>{d.on("error",t),d.on("keyStatus",(i=>{i.startsWith("usable")?e():"output-restricted"===i?t(new go({type:J.KEY_SYSTEM_ERROR,details:ee.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?t(new go({type:J.KEY_SYSTEM_ERROR,details:ee.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${i}"`)):"expired"===i?t(new Error("key expired while generating request")):this.warn(`unhandled key status change "${i}"`)}))}));return e.mediaKeysSession.generateRequest(t,i).then((()=>{var t;this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${l}`)})).catch((e=>{throw new go({type:J.KEY_SYSTEM_ERROR,details:ee.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>u)).catch((t=>{throw d.removeAllListeners(),this.removeSession(e),t})).then((()=>(d.removeAllListeners(),e)))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach(((t,i)=>{if("string"==typeof i&&"object"==typeof t){const e=i;i=t,t=e}this.log(`key status change "${t}" for keyStatuses keyId: ${Ce("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${Ce(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t}))}fetchServerCertificate(e){const t=this.config,i=new(0,t.loader)(t),s=this.getServerCertificateUrl(e);return s?(this.log(`Fetching server certificate for "${e}"`),new Promise(((n,r)=>{const o={responseType:"arraybuffer",url:s},a=t.certLoadPolicy.default,l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,t,i,s)=>{n(e.data)},onError:(t,i,n,a)=>{r(new go({type:J.KEY_SYSTEM_ERROR,details:ee.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:pe({url:o.url,data:void 0},t)},`"${e}" certificate request failed (${s}). Status: ${t.code} (${t.text})`))},onTimeout:(t,i,n)=>{r(new go({type:J.KEY_SYSTEM_ERROR,details:ee.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:{url:o.url,data:void 0}},`"${e}" certificate request timed out (${s})`))},onAbort:(e,t,i)=>{r(new Error("aborted"))}};i.load(o,l,d)}))):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise(((s,n)=>{e.setServerCertificate(i).then((n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${null==i?void 0:i.byteLength}) on "${t}"`),s(e)})).catch((e=>{n(new go({type:J.KEY_SYSTEM_ERROR,details:ee.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then((t=>this.updateKeySession(e,new Uint8Array(t)).catch((e=>{throw new go({type:J.KEY_SYSTEM_ERROR,details:ee.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.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"),n=s.querySelectorAll("HttpHeader");if(n.length>0){let t;for(let i=0,s=n.length;i in key message");return ji(atob(l))}setupLicenseXHR(e,t,i,s){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then((()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,s)})).catch((r=>{if(!i.decryptdata)throw r;return e.open("POST",t,!0),n.call(this.hls,e,t,i,s)})).then((i=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:i||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,n)=>{const r=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${r}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(4===o.readyState)if(200===o.status){this._requestLicenseFailureCount=0;let t=o.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const i=this.config.licenseResponseCallback;if(i)try{t=i.call(this.hls,o,r,e)}catch(e){this.error(e)}s(t)}else{const a=i.errorRetry,l=a?a.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)n(new go({type:J.KEY_SYSTEM_ERROR,details:ee.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:r,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${r}). Status: ${o.status} (${o.statusText})`));else{const i=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(e,t).then(s,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,r,e,t).then((({xhr:t,licenseChallenge:i})=>{e.keySystem==Hi.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(t,i)),t.send(i)}))}))}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.removeEventListener("encrypted",this.onMediaEncrypted),i.removeEventListener("waitingforkey",this.onWaitingForKey),i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null)}_clear(e){var t;const i=this.mediaKeySessions;this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},ns.clearKeyUriToKeyIdMap();const s=i.length;po.CDMCleanupPromise=Promise.all(i.map((e=>this.removeSession(e))).concat(null==e||null==(t=e.setMediaKeys(null))?void 0:t.catch((e=>{var t;this.log(`Could not clear media keys: ${e}`),null==(t=this.hls)||t.trigger(te.ERROR,{type:J.OTHER_ERROR,details:ee.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${e}`)})})))).then((()=>{s&&(this.log("finished closing key sessions and clearing media keys"),i.length=0)})).catch((e=>{var t;this.log(`Could not close sessions and clear media keys: ${e}`),null==(t=this.hls)||t.trigger(te.ERROR,{type:J.OTHER_ERROR,details:ee.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${e}`)})}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce(((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e)),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}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);s>-1&&this.mediaKeySessions.splice(s,1);const{drmSystemOptions:n}=this.config,r=function(e){var t;return"persistent-license"===e.sessionType||!(null==(t=e.sessionTypes)||!t.some((e=>"persistent-license"===e)))}(n)?new Promise(((e,i)=>{self.setTimeout((()=>i(new Error("MediaKeySession.remove() timeout"))),8e3),t.remove().then(e)})):Promise.resolve();return r.catch((e=>{var t;this.log(`Could not remove session: ${e}`),null==(t=this.hls)||t.trigger(te.ERROR,{type:J.OTHER_ERROR,details:ee.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${e}`)})})).then((()=>t.close())).catch((e=>{var t;this.log(`Could not close session: ${e}`),null==(t=this.hls)||t.trigger(te.ERROR,{type:J.OTHER_ERROR,details:ee.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${e}`)})}))}}}po.CDMCleanupPromise=void 0;class go extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function mo(e,t){let i;try{i=new Event("addtrack")}catch(e){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function vo(e,t){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(i){Te.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){Te.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===i&&(e.mode=i)}function Ao(e,t){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues)for(let i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===i&&(e.mode=i)}function Eo(e,t,i,s){const n=e.mode;if("disabled"===n&&(e.mode="hidden"),e.cues&&e.cues.length>0){const n=function(e,t,i){const s=[],n=function(e,t){if(t<=e[0].startTime)return 0;const i=e.length-1;if(t>e[i].endTime)return-1;let s,n=0,r=i;for(;n<=r;)if(s=Math.floor((r+n)/2),te[s].startTime&&n-1)for(let r=n,o=e.length;r=t&&n.endTime<=i)s.push(n);else if(n.startTime>i)return s}return s}(e.cues,t,i);for(let t=0;t>>0).toString()}const bo=.025;let So=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function _o(e,t,i){return`${e.identifier}-${i+1}-${To(t)}`}class Co{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){if(e>=this.assetList.length)return!0;const t=this.playoutLimit;return!(e<=0||isNaN(t))&&this.assetList[e].startOffset>t}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return Ro(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-Ro(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=X(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return Ro(e,t)}return e}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||null!==this.assetListResponse}toString(){return`["${(e=this).identifier}" ${e.cue.pre?"

":e.cue.post?"":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`;var e}}function Ro(e,t){return e-t.start{const e=this.interstitial.playoutLimit,t=this.currentTime;this.startOffset+t>=e&&this.hls.trigger(te.PLAYOUT_LIMIT_REACHED,{})};const n=this.hls=new e(t);this.interstitial=i,this.assetItem=s;let r=s.uri;try{r=Lo(r,n.sessionId).href}catch(e){}n.loadSource(r);const o=()=>{this.hasDetails=!0};n.once(te.LEVEL_LOADED,o),n.once(te.AUDIO_TRACK_LOADED,o),n.once(te.SUBTITLE_TRACK_LOADED,o),n.on(te.MEDIA_ATTACHING,((e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t,this.interstitial.playoutLimit&&t.addEventListener("timeupdate",this.checkPlayout)}))}bufferedInPlaceToEnd(e){var t;if(!this.interstitial.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e||!this._bufferedEosTime)return!1;const i=this.timelineOffset,s=Ii.bufferInfo(e,i,0);return this.getAssetTime(s.end)>=this._bufferedEosTime-.02}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=Ii.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){return this.assetItem.duration||0}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const i=e-t;if(Math.abs(i)>1/9e4){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var e;this.mediaAttached&&null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}destroy(){this.removeMediaListeners(),this.hls.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){this.hls.attachMedia(e)}detachMedia(){this.removeMediaListeners(),this.mediaAttached=null,this.hls.detachMedia()}resumeBuffering(){this.hls.resumeBuffering()}pauseBuffering(){this.hls.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls.transferMedia()}on(e,t,i){this.hls.on(e,t)}once(e,t,i){this.hls.once(e,t)}off(e,t,i){this.hls.off(e,t)}toString(){var e,t;return`HlsAssetPlayer: ${Io(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${null!=(t=this.interstitial)&&t.appendInPlace?"append-in-place":""}`}}class wo extends ge{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((e=>e.reset())),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce(((i,s)=>e<=s.startOffset&&t>s.startOffset?(delete s.error,i+1):i),0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const s=this.items;if(s)for(s[i]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(n=s[i])&&n.event;){var n;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let s=0;sn.start&&e1)for(let e=0;ei&&t!o.includes(e.identifier))):[];r.length&&r.sort(((e,t)=>{const i=e.cue.pre,s=e.cue.post,n=t.cue.pre,r=t.cue.post;if(i&&!n)return-1;if(n&&!i)return 1;if(s&&!r)return 1;if(r&&!s)return-1;if(!(i||n||s||r)){const i=e.startTime,s=t.startTime;if(i!==s)return i-s}return e.dateRange.tagOrder-t.dateRange.tagOrder})),this.events=r,a.forEach((e=>{this.removeEvent(e)})),this.updateSchedule(e,a)}updateSchedule(e,t=[]){const i=this.events||[];if(i.length||t.length||this.length<2){const s=this.items,n=this.parseSchedule(i,e);(t.length||(null==s?void 0:s.length)!==n.length||n.some(((e,t)=>Math.abs(e.playout.start-s[t].playout.start)>.005||Math.abs(e.playout.end-s[t].playout.end)>.005)))&&(this.items=n,this.onScheduleUpdate(t,s))}}parseDateRanges(e,t,i){const s=[],n=Object.keys(e);for(let r=0;r!(e.error||e.cue.once&&e.hasPlayed)))).length){this.resolveOffsets(e,t);let s=0,a=0;if(e.forEach(((t,o)=>{const l=t.cue.pre,d=t.cue.post,c=e[o-1]||null,h=t.appendInPlace,u=d?n:t.startOffset,f=t.duration,p=t.timelineOccupancy===So.Range?f:0,g=t.resumptionOffset,m=(null==c?void 0:c.startTime)===u,v=u+t.cumulativeDuration;let A=h?v+f:u+g;if(l||!d&&u<=0){const e=a;a+=p,t.timelineStart=v;const s=r;r+=f,i.push({event:t,start:v,end:A,playout:{start:s,end:r},integrated:{start:e,end:a}})}else{if(!(u<=n))return;{if(!m){const n=u-s;if(n>.033){const l=s,d=a;a+=n;const c=r;r+=n;const h={previousEvent:e[o-1]||null,nextEvent:t,start:l,end:l+n,playout:{start:c,end:r},integrated:{start:d,end:a}};i.push(h)}else n>0&&c&&(c.cumulativeDuration+=n,i[i.length-1].end=u)}d&&(A=v),t.timelineStart=v;const n=a;a+=p;const l=r;r+=f,i.push({event:t,start:v,end:A,playout:{start:l,end:r},integrated:{start:n,end:a}})}}const E=t.resumeTime;s=d||E>n?n:E})),s{const l=o.cue.pre,d=o.cue.post,c=l?0:d?s:o.startTime;this.updateAssetDurations(o),r===c?o.cumulativeDuration=n:(n=0,r=c),!d&&o.snapOptions.in&&(o.resumeAnchor=Zt(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&a+1bo?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1):t?!Object.keys(t).some((s=>{const n=t[s].details,r=n.edge;if(i>=r)return this.log(`"${e.identifier}" resumption ${i} past ${s} playlist end ${r}`),!1;const o=Zt(null,n.fragments,i);if(!o)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${s} playlist (${n.fragStart}-${n.fragmentEnd})`),!0;const a="audio"===s?.175:0;return!(Math.abs(o.start-i){const o=t+i;e.startOffset=i,e.timelineStart=o,s||(s=null===e.duration),n||(n=!!e.error);const a=e.error?0:e.duration||0;i+=a})),e.duration=s&&!n?Math.max(i,e.duration):i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function Po(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}class Oo{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const i=e.assetListUrl;let s;try{s=Lo(i,this.hls.sessionId,e.baseUrl)}catch(t){const s=this.assignAssetListError(e,ee.ASSET_LIST_LOAD_ERROR,t,i);return void this.hls.trigger(te.ERROR,s)}t&&"data:"!==s.protocol&&s.searchParams.set("_HLS_start_offset",""+t);const n=this.hls.config,r=new(0,n.loader)(n),o={responseType:"json",url:s.href},a=n.interstitialAssetListLoadPolicy.default,l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,i,s,n)=>{const r=t.data,o=null==r?void 0:r.ASSETS;if(Array.isArray(o))e.assetListResponse=r,this.hls.trigger(te.ASSET_LIST_LOADED,{event:e,assetListResponse:r,networkDetails:n});else{const t=this.assignAssetListError(e,ee.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),s.url,i,n);this.hls.trigger(te.ERROR,t)}},onError:(t,i,s,n)=>{const r=this.assignAssetListError(e,ee.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${i.url})`),i.url,n,s);this.hls.trigger(te.ERROR,r)},onTimeout:(t,i,s)=>{const n=this.assignAssetListError(e,ee.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,t,s);this.hls.trigger(te.ERROR,n)}};return r.load(o,l,d),this.hls.trigger(te.ASSET_LIST_LOADING,{event:e}),r}assignAssetListError(e,t,i,s,n,r){return e.error=i,{type:J.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:s,error:i,networkDetails:r,stats:n}}}function Do(e,t,i){No(e,t,i),e.addEventListener(t,i)}function No(e,t,i){e.removeEventListener(t,i)}function Mo(e){null==e||e.play().catch((()=>{}))}class xo{constructor(e){this.buffered=void 0;const t=(t,i,s)=>{if((i>>>=0)>s-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${s})`);return e[i][t]};this.buffered={get length(){return e.length},end:i=>t("end",i,e.length),start:i=>t("start",i,e.length)}}}const Bo={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},Fo=e=>String.fromCharCode(Bo[e]||e),Uo=15,$o=100,Vo={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Go={17:2,18:4,21:6,22:8,23:10,19:13,20:15},jo={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Ko={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Ho=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Yo{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i="function"==typeof t?t():t;Te.log(`${this.time} [${e}] ${i}`)}}}const Wo=function(e){const t=[];for(let i=0;i$o&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=$o)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e=144&&this.backSpace();const t=Fo(e);this.pos>=$o?this.logger.log(0,(()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<$o;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<$o;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 Qo{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t"pacData = "+Gt(e)));let t=e.row-1;if(this.nrRollUpRows&&t"bkgData = "+Gt(e))),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");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 i=0;i0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}getTextAndFormat(){return this.rows}}class Zo{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 Qo(i),this.nonDisplayedMemory=new Qo(i),this.lastOutputScreen=new Qo(i),this.currRollUpRow=this.displayedMemory.rows[14],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[14],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)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;tt+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(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"),"MODE_TEXT"!==this.mode&&(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"),"MODE_POP-ON"===this.mode){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: "+Gt(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?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.cueStartTime=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 Jo{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const s=this.logger=new Yo;this.channels=[null,new Zo(e,t,s),new Zo(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 e=0;e"["+Wo([t[e],t[e+1]])+"] -> ("+Wo([i,s])+")"));const o=this.cmdHistory;if(i>=16&&i<=31){if(ta(i,s,o)){ea(null,null,o),this.logger.log(3,(()=>"Repeated command ("+Wo([i,s])+") is dropped"));continue}ea(i,s,this.cmdHistory),n=this.parseCmd(i,s),n||(n=this.parseMidrow(i,s)),n||(n=this.parsePAC(i,s)),n||(n=this.parseBackgroundAttributes(i,s))}else ea(null,null,o);if(!n&&(r=this.parseChars(i,s),r)){const e=this.currentChannel;e&&e>0?this.channels[e].insertChars(r):this.logger.log(2,"No channel found yet. TEXT-MODE?")}n||r||this.logger.log(2,(()=>"Couldn't parse cleaned data "+Wo([i,s])+" orig: "+Wo([t[e],t[e+1]])))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;const i=20===e||21===e||23===e?1:2,s=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?s.ccRCL():33===t?s.ccBS():34===t?s.ccAOF():35===t?s.ccAON():36===t?s.ccDER():37===t?s.ccRU(2):38===t?s.ccRU(3):39===t?s.ccRU(4):40===t?s.ccFON():41===t?s.ccRDC():42===t?s.ccTR():43===t?s.ccRTD():44===t?s.ccEDM():45===t?s.ccCR():46===t?s.ccENM():47===t&&s.ccEOC():s.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let i=0;if((17===e||25===e)&&t>=32&&t<=47){if(i=17===e?1: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 ("+Wo([e,t])+")")),!0)}return!1}parsePAC(e,t){let i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(16===e||24===e)&&t>=64&&t<=95))return!1;const s=e<=23?1:2;i=t>=64&&t<=95?1===s?Vo[e]:jo[e]:1===s?Go[e]:Ko[e];const n=this.channels[s];return!!n&&(n.setPAC(this.interpretPAC(i,t)),this.currentChannel=s,!0)}interpretPAC(e,t){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,s.underline=!(1&~i),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=4*Math.floor((i-16)/2),s}parseChars(e,t){let i,s=null,n=null;if(e>=25?(i=2,n=e-8):(i=1,n=e),n>=17&&n<=19){let e;e=17===n?t+80:18===n?t+112:t+144,this.logger.log(2,(()=>"Special char '"+Fo(e)+"' in channel "+i)),s=[e]}else e>=32&&e<=127&&(s=0===t?[e]:[e,t]);return s&&this.logger.log(3,(()=>"Char codes =  "+Wo(s).join(","))),s}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;let i;const s={};16===e||24===e?(i=Math.floor((t-32)/2),s.background=Ho[i],t%2==1&&(s.background=s.background+"_semi")):45===t?s.background="transparent":(s.foreground="black",47===t&&(s.underline=!0));const n=e<=23?1:2;return this.channels[n].setBkgData(s),!0}reset(){for(let e=0;e100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"positionAlign",n({},l,{get:function(){return y},set:function(e){const t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(a,"size",n({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"align",n({},l,{get:function(){return b},set:function(e){const t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");b=t,this.hasBeenReset=!0}})),a.displayState=void 0}return r.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},r}();class sa{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function na(e){function t(e,t,i,s){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(s||0)}const i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}class ra{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=0&&i<=100)return this.set(e,i),!0}return!1}}function oa(e,t,i,s){const n=s?e.split(s):[e];for(const e in n){if("string"!=typeof n[e])continue;const s=n[e].split(i);2===s.length&&t(s[0],s[1])}}const aa=new ia(0,0,""),la="middle"===aa.align?"middle":"center";function da(e,t,i){const s=e;function n(){const t=na(e);if(null===t)throw new Error("Malformed timestamp: "+s);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function r(){e=e.replace(/^\s+/,"")}if(r(),t.startTime=n(),r(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+s);e=e.slice(3),r(),t.endTime=n(),r(),function(e,t){const s=new ra;oa(e,(function(e,t){let n;switch(e){case"region":for(let n=i.length-1;n>=0;n--)if(i[n].id===t){s.set(e,i[n].region);break}break;case"vertical":s.alt(e,t,["rl","lr"]);break;case"line":n=t.split(","),s.integer(e,n[0]),s.percent(e,n[0])&&s.set("snapToLines",!1),s.alt(e,n[0],["auto"]),2===n.length&&s.alt("lineAlign",n[1],["start",la,"end"]);break;case"position":n=t.split(","),s.percent(e,n[0]),2===n.length&&s.alt("positionAlign",n[1],["start",la,"end","line-left","line-right","auto"]);break;case"size":s.percent(e,t);break;case"align":s.alt(e,t,["start",la,"end","left","right"])}}),/:/,/\s/),t.region=s.get("region",null),t.vertical=s.get("vertical","");let n=s.get("line","auto");"auto"===n&&-1===aa.line&&(n=-1),t.line=n,t.lineAlign=s.get("lineAlign","start"),t.snapToLines=s.get("snapToLines",!0),t.size=s.get("size",100),t.align=s.get("align",la);let r=s.get("position","auto");"auto"===r&&50===aa.position&&(r="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=r}(e,t)}function ca(e){return e.replace(//gi,"\n")}class ha{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new sa,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function i(){let e=t.buffer,i=0;for(e=ca(e);i_e(e))),o=function(e,t,i=1,s=!1){return or(e,t,1/i,s)}(t.baseTime,1,t.timescale);try{r.forEach((e=>i(function(e,t){const i=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(s).reduce(((e,t)=>(e[t]=i.getAttribute(`ttp:${t}`)||s[t],e)),{}),r="preserve"!==i.getAttribute("xml:space"),o=Ta(ya(i,"styling","style")),a=Ta(ya(i,"layout","region")),l=ya(i,"body","[begin]");return[].map.call(l,(e=>{const i=ba(e,r);if(!i||!e.hasAttribute("begin"))return null;const s=Ca(e.getAttribute("begin"),n),l=Ca(e.getAttribute("dur"),n);let d=Ca(e.getAttribute("end"),n);if(null===s)throw _a(e);if(null===d){if(null===l)throw _a(e);d=s+l}const c=new ia(s-t,d-t,i);c.id=pa(c.startTime,c.endTime,c.text);const h=function(e,t,i){const s="http://www.w3.org/ns/ttml#styling";let n=null;const r=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return r&&i.hasOwnProperty(r)&&(n=i[r]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce(((i,r)=>{const o=Sa(t,s,r)||Sa(e,s,r)||Sa(n,s,r);return o&&(i[r]=o),i}),{})}(a[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:u}=h;if(u){const e=Aa[u];e&&(c.lineAlign=e),c.align=u}return ue(c,h),c})).filter((e=>null!==e))}(e,o))))}catch(e){s(e)}}function ya(e,t,i){const s=e.getElementsByTagName(t)[0];return s?[].slice.call(s.querySelectorAll(i)):[]}function Ta(e){return e.reduce(((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e}),{})}function ba(e,t){return[].slice.call(e.childNodes).reduce(((e,i,s)=>{var n;return"br"===i.nodeName&&s?e+"\n":null!=(n=i.childNodes)&&n.length?ba(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent}),"")}function Sa(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function _a(e){return new Error(`Could not parse ttml timestamp ${e}`)}function Ca(e,t){if(!e)return null;let i=na(e);return null===i&&(ma.test(e)?i=function(e,t){const i=ma.exec(e),s=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+s/t.frameRate}(e,t):va.test(e)&&(i=function(e,t){const i=va.exec(e),s=Number(i[1]);switch(i[2]){case"h":return 3600*s;case"m":return 60*s;case"ms":return 1e3*s;case"f":return s/t.frameRate;case"t":return s/t.tickRate}return s}(e,t))),i}class Ra{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(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function La(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function Ia(e,t){return!!e&&e.kind===La(t)&&Ir(t,e)}const ka=/\s/,wa={newCue(e,t,i,s){const n=[];let r,o,a,l,d;const c=self.VTTCue||self.TextTrackCue;for(let u=0;u=16?l--:l++;const s=ca(d.trim()),f=pa(t,i,s);null!=e&&null!=(h=e.cues)&&h.getCueById(f)||(o=new c(t,i,s),o.id=f,o.line=u+1,o.align="left",o.position=10+Math.min(80,10*Math.floor(8*l/32)),n.push(o))}return e&&n.length&&(n.sort(((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line)),n.forEach((t=>vo(e,t)))),n}},Pa=/(\d+)-(\d+)\/(\d+)/;class Oa{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||Da,this.controller=new self.AbortController,this.stats=new Me}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(),null!=(e=this.callbacks)&&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 n=function(e,t){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(ue({},e.headers))};return e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),i}(e,this.controller.signal),r="arraybuffer"===e.responseType,o=r?"byteLength":"length",{maxTimeToFirstByteMs:a,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=a&&X(a)?a:l,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))}),t.timeout),(yr(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((i=>{var n;this.response=this.loader=i;const o=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))}),l-(o-s.loading.start)),!i.ok){const{status:e,statusText:t}=i;throw new Na(t||"fetch, bad network response",e,i)}s.loading.first=o,s.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=Pa.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(X(e))return e}const i=e.get("Content-Length");if(i)return parseInt(i)}(i.headers)||s.total;const a=null==(n=this.callbacks)?void 0:n.onProgress;return a&&X(t.highWaterMark)?this.loadProgressively(i,s,e,t.highWaterMark,a):r?i.arrayBuffer():"json"===e.responseType?i.json():i.text()})).then((i=>{var n,r;const a=this.response;if(!a)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const l=i[o];l&&(s.loaded=s.total=l);const d={url:a.url,data:i,code:a.status},c=null==(n=this.callbacks)?void 0:n.onProgress;c&&!X(t.highWaterMark)&&c(s,e,i,a),null==(r=this.callbacks)||r.onSuccess(d,s,e,a)})).catch((t=>{var i;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const n=t&&t.code||0,r=t?t.message:null;null==(i=this.callbacks)||i.onError({code:n,text:r},e,t?t.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,n){const r=new Qs,o=e.body.getReader(),a=()=>o.read().then((o=>{if(o.done)return r.dataLength&&n(t,i,r.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=o.value,d=l.length;return t.loaded+=d,d=s&&n(t,i,r.flush().buffer,e)):n(t,i,l.buffer,e),a()})).catch((()=>Promise.reject()));return a()}}function Da(e,t){return new self.Request(e.url,t)}class Na extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const Ma=/^age:\s*[\d.]+\s*$/im;class xa{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 Me,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,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&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 n=this.xhrSetup;n?Promise.resolve().then((()=>{if(this.loader===i&&!this.stats.aborted)return n(i,t.url)})).catch((e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),n(i,t.url)})).then((()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)})).catch((e=>{var n;null==(n=this.callbacks)||n.onError({code:i.status,text:e.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:n,maxLoadTimeMs:r}=i.loadPolicy;if(s)for(const t in s)e.setRequestHeader(t,s[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&X(n)?n:r,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,n=this.config;if(!i.aborted&&s>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===s)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const s=t.status,l="text"===t.responseType?t.responseText:null;if(s>=200&&s<300){const n=null!=l?l:t.response;if(null!=n){var r,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);const a="arraybuffer"===t.responseType?n.byteLength:n.length;i.loaded=i.total=a,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);const l=null==(r=this.callbacks)?void 0:r.onProgress;l&&l(i,e,n,t);const d={url:t.responseURL,data:n,code:s};return void(null==(o=this.callbacks)||o.onSuccess(d,i,e,t))}}const d=n.loadPolicy.errorRetry;var a;oi(d,i.retry,!1,{url:e.url,data:void 0,code:s})?this.retry(d):(Te.error(`${s} while loading ${e.url}`),null==(a=this.callbacks)||a.onError({code:s,text:t.statusText},e,t,i))}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(oi(e,this.stats.retry,!0))this.retry(e);else{var t;Te.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=ni(e,i.retry),i.retry++,Te.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?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&&Ma.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const Ba=pe(pe({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:xa,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends ge{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;const{fragCurrent:i,partCurrent:s,hls:n}=this,{autoLevelEnabled:r,media:o}=n;if(!i||!o)return;const a=performance.now(),l=s?s.stats:i.stats,d=s?s.duration:i.duration,c=a-l.loading.start,h=n.minAutoLevel,u=i.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||u<=h)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r)return;const p=f>-1&&f!==u,g=!!e||p;if(!g&&(o.paused||!o.playbackRate||!o.readyState))return;const m=n.mainForwardBufferInfo;if(!g&&null===m)return;const v=this.bwEstimator.getEstimateTTFB(),A=Math.abs(o.playbackRate);if(c<=Math.max(v,d/(2*A)*1e3))return;const E=m?m.len/A:0,y=l.loading.first?l.loading.first-l.loading.start:-1,T=l.loaded&&y>-1,b=this.getBwEstimate(),S=n.levels,_=S[u],C=Math.max(l.loaded,Math.round(d*(i.bitrate||_.averageBitrate)/8));let R=T?c-y:c;R<1&&T&&(R=Math.min(c,8*l.loaded/b));const L=T?1e3*l.loaded/R:0,I=v/1e3,k=L?(C-l.loaded)/L:8*C/b+I;if(k<=E)return;const w=L?8*L:b,P=!0===(null==(t=(null==e?void 0:e.details)||this.hls.latestLevelDetails)?void 0:t.live),O=this.hls.config.abrBandWidthUpFactor;let D,N=Number.POSITIVE_INFINITY;for(D=u-1;D>h;D--){const e=S[D].maxBitrate,t=!S[D].details||P;if(N=this.getTimeToLoadFrag(I,w,d*e,t),N=k)return;if(N>10*d)return;T?this.bwEstimator.sample(c-Math.min(v,y),l.loaded):this.bwEstimator.sampleTTFB(c);const M=S[D].maxBitrate;this.getBwEstimate()*O>M&&this.resetEstimator(M);const x=this.findBestLevel(M,h,D,0,E,1,1);x>-1&&(D=x),this.warn(`Fragment ${i.sn}${s?" part "+s.index:""} of level ${u} is loading too slowly;\n      Fragment duration: ${i.duration.toFixed(3)}\n      Time to underbuffer: ${E.toFixed(3)} s\n      Estimated load time for current fragment: ${k.toFixed(3)} s\n      Estimated load time for down switch fragment: ${N.toFixed(3)} s\n      TTFB estimate: ${0|y} ms\n      Current BW estimate: ${X(b)?0|b:"Unknown"} bps\n      New BW estimate: ${0|this.getBwEstimate()} bps\n      Switching to level ${D} @ ${0|M} bps`),n.nextLoadLevel=n.nextAutoLevel=D,this.clearTimer();const B=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===D&&D>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${D>0?"and switching down":""}\n      Fragment duration: ${i.duration.toFixed(3)} s\n      Time to underbuffer: ${e.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,D>h){let t=this.findBestLevel(this.hls.levels[h].bitrate,h,D,0,e,1,1);-1===t&&(t=h),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};p||k>2*N?B():this.timer=self.setInterval(B,1e3*N),n.trigger(te.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:s,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new ce(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(te.MANIFEST_LOADING,this.onManifestLoading,this),e.on(te.FRAG_LOADING,this.onFragLoading,this),e.on(te.FRAG_LOADED,this.onFragLoaded,this),e.on(te.FRAG_BUFFERED,this.onFragBuffered,this),e.on(te.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(te.LEVEL_LOADED,this.onLevelLoaded,this),e.on(te.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(te.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(te.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(te.MANIFEST_LOADING,this.onManifestLoading,this),e.off(te.FRAG_LOADING,this.onFragLoading,this),e.off(te.FRAG_LOADED,this.onFragLoaded,this),e.off(te.FRAG_BUFFERED,this.onFragBuffered,this),e.off(te.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(te.LEVEL_LOADED,this.onLevelLoaded,this),e.off(te.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(te.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(te.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;var s;this.ignoreFragment(i)||(i.bitrateTest||(this.fragCurrent=i,this.partCurrent=null!=(s=t.part)?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 ee.BUFFER_ADD_CODEC_ERROR:case ee.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ee.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:i,partCurrent:s}=this;if(e&&i&&e.sn===i.sn&&e.level===i.level){const t=performance.now(),i=s?s.stats:e.stats,n=t-i.loading.start,r=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&r>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(n-Math.min(e,r),i.loaded)}else this.bwEstimator.sampleTTFB(n)}break}}}getTimeToLoadFrag(e,t,i,s){return e+i/t+(s?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const i=this.hls.config,{loading:s}=t.stats,n=s.end-s.first;X(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const s=i?i.stats:t.stats;if(t.type===oe&&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 e=i?i.duration:t.duration,n=this.hls.levels[t.level],r=(n.loaded?n.loaded.bytes:0)+s.loaded,o=(n.loaded?n.loaded.duration:0)+e;n.loaded={bytes:r,duration:o},n.realBitrate=Math.round(8*r/o)}if(t.bitrateTest){const e={stats:s,frag:t,part:i,id:t.type};this.onFragBuffered(te.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:s}=t,n=null!=s&&s.stats.loaded?s.stats:i.stats;if(n.aborted)return;if(this.ignoreFragment(i))return;const r=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(r,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=r/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==oe||"initSegment"===e.sn}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,n=this.findBestLevel(i,t,e,0,s,1,1);if(n>-1)return n;const r=this.hls.firstLevel,o=Math.min(Math.max(r,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${r} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const s=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,s)&&t[e].loadError<=t[s].loadError)return e}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:n,minAutoLevel:r}=i,o=t?t.duration:e?e.duration:0,a=this.getBwEstimate(),l=this.getStarvationDelay();let d=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(a,r,s,l,0,d,c);if(e>=0)return this.rebufferNotice=-1,e}let h=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;e&&(h=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),d=c=1)}const u=this.findBestLevel(a,r,s,l,h,d,c);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=i.levels[r],p=i.loadLevelObj;return p&&(null==f?void 0:f.bitrate){if(!i.codecSet)return e;const n=i.audioGroups;let r=e[i.codecSet];r||(e[i.codecSet]=r={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:s,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,fragmentError:0}),r.minBitrate=Math.min(r.minBitrate,i.bitrate);const o=Math.min(i.height,i.width);return r.minHeight=Math.min(r.minHeight,o),r.minFramerate=Math.min(r.minFramerate,i.frameRate),r.minIndex=Math.min(r.minIndex,s),r.maxScore=Math.max(r.maxScore,i.score),r.fragmentError+=i.fragmentError,r.videoRanges[i.videoRange]=(r.videoRanges[i.videoRange]||0)+1,n&&n.forEach((e=>{if(!e)return;const i=t.groups[e];i&&(r.hasDefaultAudio=r.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach((e=>{r.channels[e]=(r.channels[e]||0)+i.channels[e]})))})),e}),{})}(f,C,t,i)),n=function(e,t,i,s,n){const r=Object.keys(e),o=null==s?void 0:s.channels,a=null==s?void 0:s.audioCodec,l=null==n?void 0:n.videoCodec,d=o&&2===parseInt(o);let c=!1,h=!1,u=1/0,f=1/0,p=1/0,g=1/0,m=0,v=[];const{preferHDR:A,allowedVideoRanges:E}=function(e,t){let i=!1,s=[];if(e&&(i="SDR"!==e,s=[e]),t){s=t.allowedVideoRanges||Bt.slice(0);const e="SDR"!==s.join("")&&!t.videoCodec;i=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),i||(s=["SDR"])}return{preferHDR:i,allowedVideoRanges:s}}(t,n);for(let t=r.length;t--;){const i=e[r[t]];c||(c=i.channels[2]>0),u=Math.min(u,i.minHeight),f=Math.min(f,i.minFramerate),p=Math.min(p,i.minBitrate),E.filter((e=>i.videoRanges[e]>0)).length>0&&(h=!0)}u=X(u)?u:0,f=X(f)?f:0;const y=Math.max(1080,u),T=Math.max(30,f);p=X(p)?p:i,i=Math.max(p,i),h||(t=void 0);const b=r.length>1;return{codecSet:r.reduce(((t,s)=>{const n=e[s];if(s===t)return t;if(v=h?E.filter((e=>n.videoRanges[e]>0)):[],b){if(n.minBitrate>i)return jt(s,`min bitrate of ${n.minBitrate} > current estimate of ${i}`),t;if(!n.hasDefaultAudio)return jt(s,"no renditions with default or auto-select sound found"),t;if(a&&s.indexOf(a.substring(0,4))%5!=0)return jt(s,`audio codec preference "${a}" not found`),t;if(o&&!d){if(!n.channels[o])return jt(s,`no renditions with ${o} channel sound found (channels options: ${Object.keys(n.channels)})`),t}else if((!a||d)&&c&&0===n.channels[2])return jt(s,"no renditions with stereo sound found"),t;if(n.minHeight>y)return jt(s,`min resolution of ${n.minHeight} > maximum of ${y}`),t;if(n.minFramerate>T)return jt(s,`min framerate of ${n.minFramerate} > maximum of ${T}`),t;if(!v.some((e=>n.videoRanges[e]>0)))return jt(s,`no variants with VIDEO-RANGE of ${Gt(v)} found`),t;if(l&&s.indexOf(l.substring(0,4))%5!=0)return jt(s,`video codec preference "${l}" not found`),t;if(n.maxScore=St(t)||n.fragmentError>e[t].fragmentError)?t:(g=n.minIndex,m=n.maxScore,s)}),void 0),videoRanges:v,preferHDR:A,minFramerate:f,minBitrate:p,minIndex:g}}(s,T,e,S,_),{codecSet:r,videoRanges:o,minFramerate:a,minBitrate:l,minIndex:d,preferHDR:c}=n;R=d,y=r,T=c?o[o.length-1]:o[0],b=a,e=Math.max(e,l),this.log(`picked start tier ${Gt(n)}`)}else y=null==v?void 0:v.codecSet,T=null==v?void 0:v.videoRange;const L=u?u.duration:h?h.duration:0,I=this.bwEstimator.getEstimateTTFB()/1e3,k=[];for(let a=i;a>=t;a--){var w;const t=f[a],h=a>c;if(!t)continue;if(m.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&(Nt(t,C,T,b,e,S)||ht(t.videoCodec))?(t.supportedPromise=Mt(t,C,i),t.supportedPromise.then((e=>{if(!this.hls)return;t.supportedResult=e;const i=this.hls.levels,s=i.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${s} ${Gt(e)}`):e.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${s} ${Gt(e)}`),s>-1&&i.length>1&&(this.log(`Removing unsupported level ${s}`),this.hls.removeLevel(s),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}))):t.supportedResult=Pt}if((y&&t.codecSet!==y||T&&t.videoRange!==T||h&&b>t.frameRate||!h&&b>0&&b=2*L&&0===n?t.averageBitrate:t.maxBitrate,O=this.getTimeToLoadFrag(I,_,P*v,void 0===p);if(_>=P&&(a===d||0===t.loadError&&0===t.fragmentError)&&(O<=I||!X(O)||A&&!this.bitrateTestDelay||O${a} adjustedbw(${Math.round(_)})-bitrate=${Math.round(_-P)} ttfb:${I.toFixed(1)} avgDuration:${v.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${O.toFixed(1)} firstSelection:${E} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${g}`)),E&&(this.firstSelection=a),a}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},bufferController:class extends ge{constructor(e,t){var i;super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:i}=this;e&&this.log("Media source opened"),t&&i&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(te.MEDIA_ATTACHED,{media:t,mediaSource:i}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=(i=be(e.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(te.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(te.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(te.MANIFEST_LOADING,this.onManifestLoading,this),e.on(te.MANIFEST_PARSED,this.onManifestParsed,this),e.on(te.BUFFER_RESET,this.onBufferReset,this),e.on(te.BUFFER_APPENDING,this.onBufferAppending,this),e.on(te.BUFFER_CODECS,this.onBufferCodecs,this),e.on(te.BUFFER_EOS,this.onBufferEos,this),e.on(te.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(te.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(te.FRAG_PARSED,this.onFragParsed,this),e.on(te.FRAG_CHANGED,this.onFragChanged,this),e.on(te.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(te.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(te.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(te.MANIFEST_LOADING,this.onManifestLoading,this),e.off(te.MANIFEST_PARSED,this.onManifestParsed,this),e.off(te.BUFFER_RESET,this.onBufferReset,this),e.off(te.BUFFER_APPENDING,this.onBufferAppending,this),e.off(te.BUFFER_CODECS,this.onBufferCodecs,this),e.off(te.BUFFER_EOS,this.onBufferEos,this),e.off(te.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(te.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(te.FRAG_PARSED,this.onFragParsed,this),e.off(te.FRAG_CHANGED,this.onFragChanged,this),e.off(te.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===t?ue(i,s.tracks):this.sourceBuffers.forEach((e=>{const[t]=e;t&&(i[t]=ue({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null})),{media:e,mediaSource:t,tracks:i}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var i;let s=2;(t.audio&&!t.video||!t.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media,s=be(this.appendSource);if(this.transferData=this.overrides=void 0,i&&s){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const n=this.mediaSource=t.mediaSource||new s;if(this.assignMediaSource(n),e)this._objectUrl=i.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{i.removeAttribute("src");const t=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||t&&n instanceof t,Dr(i),function(e,t){const i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,e),i.load()}catch(t){i.src=e}else i.src=e}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(i=e.constructor)?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const i=this.tracks,s=t.tracks,n=s?Object.keys(s):null,r=n?n.length:0,o=()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()};if(s&&n&&r){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${Gt(i,((e,t)=>"initSegment"===e?void 0:t))};\ntransfer tracks: ${Gt(s,((e,t)=>"initSegment"===e?void 0:t))}}`),!Se(s,i)){t.mediaSource=null,t.tracks=void 0;const n=e.currentTime,r=this.details,o=Math.max(n,(null==r?void 0:r.fragments[0].start)||0);return o-n>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${n} -> ${o}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${o} currentTime: ${n}`),this.onMediaDetaching(te.MEDIA_DETACHING,{}),this.onMediaAttaching(te.MEDIA_ATTACHING,t),void(e.currentTime=o))}this.transferData=void 0,n.forEach((e=>{const t=e,i=s[t];if(i){const e=i.buffer;if(e){const s=this.fragmentTracker,n=i.id;if(s.hasFragments(n)||s.hasParts(n)){const i=Ii.getBuffered(e);s.detectEvictedFragments(t,i,n,null,!0)}const r=Nr(t),o=[t,e];this.sourceBuffers[r]=o,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,i)}}})),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:n,_objectUrl:r}=this;if(n){if(this.log("media source "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach((([e])=>{e&&this.removeBuffer(e)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===n.readyState;try{const t=n.sourceBuffers;for(let i=t.length;i--;)e&&t[i].abort(),n.removeSourceBuffer(t[i]);e&&n.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),i||(r&&self.URL.revokeObjectURL(r),this.mediaSrc===r?(s.removeAttribute("src"),this.appendSource&&Dr(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(te.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach((([e])=>{e&&this.resetBuffer(e)})),this.initTracks()}resetBuffer(e){var t;const i=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),i)try{var s;null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Nr(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new kr(this.tracks)}onBufferCodecs(e,t){const i=this.tracks,s=Object.keys(t);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),r=!n&&this.sourceBufferCount&&this.media&&s.some((e=>!i[e]));n||r?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${s}" SourceBuffers`):(s.forEach((e=>{var s,n,r;const o=t[e],{id:a,codec:l,levelCodec:d,container:c,metadata:h,supplemental:u}=o;let f=i[e];const p=null==(s=this.transferData)||null==(n=s.tracks)?void 0:n[e],g=null!=p&&p.buffer?p:f,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),v=null==g?void 0:g.levelCodec;f||(f=i[e]={buffer:void 0,listeners:[],codec:l,supplemental:u,container:c,levelCodec:d,metadata:h,id:a});const A=Lt(m,v),E=null==A?void 0:A.replace(wr,"$1");let y=Lt(l,d);const T=null==(r=y)?void 0:r.replace(wr,"$1");y&&A&&E!==T&&("audio"===e.slice(0,5)&&(y=Rt(y,this.appendSource)),this.log(`switching codec ${m} to ${y}`),y!==(f.pendingCodec||f.codec)&&(f.pendingCodec=y),f.container=c,this.appendChangeType(e,c,y))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce(((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e}),{})}appendChangeType(e,t,i){const s=`${t};codecs=${i}`,n={label:`change-type=${s}`,execute:()=>{const n=this.tracks[e];if(n){const r=n.buffer;null!=r&&r.changeType&&(this.log(`changing ${e} sourceBuffer type to ${s}`),r.changeType(s),n.codec=i,n.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(n,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,s=i+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,oe))?void 0:t.gap))return;const n={label:"block-audio",execute:()=>{var e;const t=this.tracks.video;(this.lastVideoAppendEnd>s||null!=t&&t.buffer&&Ii.isBuffered(t.buffer,s)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(s,oe))?void 0:e.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:n,frag:e},this.append(n,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:s,type:n,parent:r,frag:o,part:a,chunkMeta:l}=t,d=l.buffering[n],c=o.sn,h=self.performance.now();d.start=h;const u=o.stats.buffering,f=a?a.stats.buffering:null;0===u.start&&(u.start=h),f&&0===f.start&&(f.start=h);const p=i.audio;let g=!1;"audio"===n&&"audio/mpeg"===(null==p?void 0:p.container)&&(g=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const m=this.tracks.video,v=null==m?void 0:m.buffer;if(v&&"initSegment"!==c){const e=a||o,t=this.blockedAudioAppend;if("audio"!==n||"main"===r||this.blockedAudioAppend){if("video"===n){const i=e.end;if(t){const e=t.frag.start;(i>e||i{if(d.executeStart=self.performance.now(),g){const e=this.tracks[n];if(e){const t=e.buffer;if(t){const e=A-t.timestampOffset;Math.abs(e)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${A} (delta: ${e}) sn: ${c})`),t.timestampOffset=A)}}}this.appendExecutor(s,n)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();d.executeEnd=d.end=e,0===u.first&&(u.first=e),f&&0===f.first&&(f.first=e);const t={};this.sourceBuffers.forEach((([e,i])=>{e&&(t[e]=Ii.getBuffered(i))})),this.appendErrors[n]=0,"audio"===n||"video"===n?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(te.BUFFER_APPENDED,{type:n,frag:o,part:a,chunkMeta:l,parent:o.type,timeRanges:t})},onError:e=>{var t;const i={type:J.MEDIA_ERROR,parent:o.type,details:ee.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:a,chunkMeta:l,error:e,err:e,fatal:!1},s=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR)i.details=ee.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!s)i.errorAction=ai(!0);else if(e.name===Pr&&0===this.sourceBufferCount)i.errorAction=ai(!0);else{const e=++this.appendErrors[n];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${s||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||s)&&(i.fatal=!0)}this.hls.trigger(te.ERROR,i)}};this.append(E,n,this.isPending(this.tracks[n]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(te.BUFFER_FLUSHED,{type:e})},onError:s=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,s)}}}onBufferFlushing(e,t){const{type:i,startOffset:s,endOffset:n}=t;i?this.append(this.getFlushOp(i,s,n),i):this.sourceBuffers.forEach((([e])=>{e&&this.append(this.getFlushOp(e,s,n),e)}))}onFragParsed(e,t){const{frag:i,part:s}=t,n=[],r=s?s.elementaryStreams:i.elementaryStreams;r[Fe]?n.push("audiovideo"):(r[xe]&&n.push("audio"),r[Be]&&n.push("video")),0===n.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers((()=>{const e=self.performance.now();i.stats.buffering.end=e,s&&(s.stats.buffering.end=e);const t=s?s.stats:i.stats;this.hls.trigger(te.FRAG_BUFFERED,{frag:i,part:s,stats:t,id:i.type})}),n).catch((e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)}))}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some((([e])=>{var t,i;return e&&(!(null!=(t=this.tracks[e])&&t.ended)||(null==(i=this.tracks[e])?void 0:i.ending))}))}onBufferEos(e,t){var i;this.sourceBuffers.forEach((([e])=>{if(e){const i=this.tracks[e];t.type&&t.type!==e||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${e} buffer reached EOS`)))}}));const s=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)}))&&(s?(this.log("Queueing EOS"),this.blockUntilOpen((()=>{this.tracksEnded();const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(te.BUFFERED_TO_END,void 0)):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)}))):(this.tracksEnded(),this.hls.trigger(te.BUFFERED_TO_END,void 0)))}tracksEnded(){this.sourceBuffers.forEach((([e])=>{if(null!==e){const t=this.tracks[e];t&&(t.ending=!1)}}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){const e=this.getDurationAndRange();e&&this.blockUntilOpen((()=>this.updateMediaSource(e)))}onError(e,t){if(t.details===ee.BUFFER_APPEND_ERROR&&t.frag){var i;const e=null==(i=t.errorAction)?void 0:i.nextAutoLevel;X(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||null===t)return;if(!this.sourceBufferCount)return;const s=e.config,n=i.currentTime,r=t.levelTargetDuration,o=t.live&&null!==s.liveBackBufferLength?s.liveBackBufferLength:s.backBufferLength;if(X(o)&&o>=0){const e=Math.max(o,r),t=Math.floor(n/r)*r-e;this.flushBackBuffer(n,r,t)}if(X(s.frontBufferFlushThreshold)&&s.frontBufferFlushThreshold>0){const e=Math.max(s.maxBufferLength,s.frontBufferFlushThreshold),t=Math.max(e,r),i=Math.floor(n/r)*r+t;this.flushFrontBuffer(n,r,i)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach((([e,t])=>{if(t){const n=Ii.getBuffered(t);if(n.length>0&&i>n.start(0)){var s;this.hls.trigger(te.BACK_BUFFER_REACHED,{bufferEnd:i});const t=this.tracks[e];if(null!=(s=this.details)&&s.live)this.hls.trigger(te.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(te.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:e})}}}))}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach((([t,s])=>{if(s){const n=Ii.getBuffered(s),r=n.length;if(r<2)return;const o=n.start(r-1),a=n.end(r-1);if(i>o||e>=o&&e<=a)return;this.hls.trigger(te.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:t})}}))}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||"open"!==(null==i?void 0:i.readyState))return null;const s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&i.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,s)}}return{duration:1/0}}const n=null==(e=this.overrides)?void 0:e.duration;if(n)return X(n)?{duration:n}:null;const r=this.media.duration;return s>(X(i.duration)?i.duration:0)&&s>r||!X(r)?{duration:s}:null}updateMediaSource({duration:e,start:t,end:i}){const s=this.mediaSource;this.media&&s&&"open"===s.readyState&&(s.duration!==e&&(X(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),void 0!==t&&void 0!==i&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${t}-${i}.`),s.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Gt(i)}`),this.tracksReady){var s;const e=null==(s=this.transferData)?void 0:s.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach((([t,i])=>{if(t){const s=this.tracks[t];e[t]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}})),this.hls.trigger(te.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach((([e])=>{this.executeNext(e)}))}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(te.ERROR,{type:J.MEDIA_ERROR,details:ee.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in e){const r=n,o=e[r];if(this.isPending(o)){const e=this.getTrackCodec(o,r),n=`${o.container};codecs=${e}`;o.codec=e,this.log(`creating sourceBuffer(${n})${this.currentOp(r)?" Queued":""} ${Gt(o)}`);try{const e=i.addSourceBuffer(n),s=Nr(r),a=[r,e];t[s]=a,o.buffer=e}catch(e){var s;return this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(r),null==(s=this.operationQueue)||s.removeBlockers(),delete this.tracks[r],void this.hls.trigger(te.ERROR,{type:J.MEDIA_ERROR,details:ee.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:r,mimeType:n,parent:o.id})}this.trackSourceBuffer(r,o)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let s=e.codec;i&&("video"===t||"audiovideo"===t)&&Et(i,"video")&&(s=function(e,t){const i=[];if(e){const t=e.split(",");for(let e=0;e{const i=t.removedRanges;null!=i&&i.length&&this.hls.trigger(te.BUFFER_FLUSHED,{type:e})}))}get mediaSrc(){var e,t;const i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==i?void 0:i.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const s=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${s}`,t),this.hls.trigger(te.ERROR,{type:J.MEDIA_ERROR,details:ee.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});const n=this.currentOp(e);n&&n.onError(s)}removeExecutor(e,t,i){const{media:s,mediaSource:n}=this,r=this.tracks[e],o=null==r?void 0:r.buffer;if(!s||!n||!o)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(e);const a=X(s.duration)?s.duration:1/0,l=X(n.duration)?n.duration:1/0,d=Math.max(0,t),c=Math.min(i,a,l);c>d&&(!r.ending||r.ended)?(r.ended=!1,this.log(`Removing [${d},${c}] from the ${e} SourceBuffer`),o.remove(d,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],s=null==i?void 0:i.buffer;if(!s)throw new Or(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,s.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch((e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)}));else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some((([e,t])=>e&&t.updating))}isQueued(){return this.sourceBuffers.some((([e])=>e&&!!this.currentOp(e)))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,s=t.map((e=>this.appendBlocker(e)));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then((t=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))}))}stepOperationQueue(e){e.forEach((e=>{var t;const i=null==(t=this.tracks[e])?void 0:t.buffer;i&&!i.updating&&this.shiftAndExecuteNext(e)}))}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce(((e,t)=>e+(this.isPending(this.tracks[t])?1:0)),0)}get sourceBufferCount(){return this.sourceBuffers.reduce(((e,[t])=>e+(t?1:0)),0)}get sourceBufferTypes(){return this.sourceBuffers.map((([e])=>e)).filter((e=>!!e))}addBufferListener(e,t,i){const s=this.tracks[e];if(!s)return;const n=s.buffer;if(!n)return;const r=i.bind(this,e);s.listeners.push({event:t,listener:r}),n.addEventListener(t,r)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach((e=>{i.removeEventListener(e.event,e.listener)})),t.listeners.length=0)}},capLevelController:Mr,errorController:class extends ge{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(te.ERROR,this.onError,this),e.on(te.MANIFEST_LOADING,this.onManifestLoading,this),e.on(te.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(te.ERROR,this.onError,this),e.off(te.ERROR,this.onErrorOut,this),e.off(te.MANIFEST_LOADING,this.onManifestLoading,this),e.off(te.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===oe?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const s=this.hls,n=t.context;switch(t.details){case ee.FRAG_LOAD_ERROR:case ee.FRAG_LOAD_TIMEOUT:case ee.KEY_LOAD_ERROR:case ee.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case ee.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap)return void(t.errorAction=ai());case ee.FRAG_GAP:case ee.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=2);case ee.LEVEL_EMPTY_ERROR:case ee.LEVEL_PARSING_ERROR:{var r,o;const e=t.parent===oe?t.level:s.loadLevel;t.details===ee.LEVEL_EMPTY_ERROR&&null!=(r=t.context)&&null!=(o=r.levelDetails)&&o.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case ee.LEVEL_LOAD_ERROR:case ee.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case ee.AUDIO_TRACK_LOAD_ERROR:case ee.AUDIO_TRACK_LOAD_TIMEOUT:case ee.SUBTITLE_LOAD_ERROR:case ee.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const e=s.loadLevelObj;if(e&&(n.type===ne&&e.hasAudioGroup(n.groupId)||n.type===re&&e.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=2,void(t.errorAction.flags=1)}return;case ee.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const e=s.loadLevelObj,i=null==e?void 0:e.attrs["HDCP-LEVEL"];i?t.errorAction={action:2,flags:2,hdcpLevel:i}:this.keySystemError(t)}return;case ee.BUFFER_ADD_CODEC_ERROR:case ee.REMUX_ALLOC_ERROR:case ee.BUFFER_APPEND_ERROR:var a;return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,null!=(a=t.level)?a:s.loadLevel)));case ee.INTERNAL_EXCEPTION:case ee.BUFFER_APPENDING_ERROR:case ee.BUFFER_FULL_ERROR:case ee.LEVEL_SWITCH_ERROR:case ee.BUFFER_STALLED_ERROR:case ee.BUFFER_SEEK_OVER_HOLE:case ee.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=ai())}t.type===J.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=si(this.hls.config.playlistLoadPolicy,e),s=this.playlistError++;if(oi(i,s,ii(e),e.response))return{action:5,flags:0,retryConfig:i,retryCount:s};const n=this.getLevelSwitchAction(e,t);return i&&(n.retryConfig=i,n.retryCount=s),n}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:r}=t.config,o=si(e.details.startsWith("key")?r:n,e),a=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(s&&(e.details!==ee.FRAG_GAP&&s.fragmentError++,oi(o,a,ii(e),e.response)))return{action:5,flags:0,retryConfig:o,retryCount:a};const l=this.getLevelSwitchAction(e,i);return o&&(l.retryConfig=o,l.retryCount=a),l}getLevelSwitchAction(e,t){const i=this.hls;null==t&&(t=i.loadLevel);const s=this.hls.levels[t];if(s){var n,r;const t=e.details;s.loadError++,t===ee.BUFFER_APPEND_ERROR&&s.fragmentError++;let l=-1;const{levels:d,loadLevel:c,minAutoLevel:h,maxAutoLevel:u}=i;i.autoLevelEnabled||(i.loadLevel=-1);const f=null==(n=e.frag)?void 0:n.type,p=(f===ae&&t===ee.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===ee.BUFFER_ADD_CODEC_ERROR||t===ee.BUFFER_APPEND_ERROR))&&d.some((({audioCodec:e})=>s.audioCodec!==e)),g="video"===e.sourceBufferName&&(t===ee.BUFFER_ADD_CODEC_ERROR||t===ee.BUFFER_APPEND_ERROR)&&d.some((({codecSet:e,audioCodec:t})=>s.codecSet!==e&&s.audioCodec===t)),{type:m,groupId:v}=null!=(r=e.context)?r:{};for(let i=d.length;i--;){const n=(i+c)%d.length;if(n!==c&&n>=h&&n<=u&&0===d[n].loadError){var o,a;const i=d[n];if(t===ee.FRAG_GAP&&f===oe&&e.frag){const t=d[n].details;if(t){const i=Zt(e.frag,t.fragments,e.frag.start);if(null!=i&&i.gap)continue}}else{if(m===ne&&i.hasAudioGroup(v)||m===re&&i.hasSubtitleGroup(v))continue;if(f===ae&&null!=(o=s.audioGroups)&&o.some((e=>i.hasAudioGroup(e)))||f===le&&null!=(a=s.subtitleGroups)&&a.some((e=>i.hasSubtitleGroup(e)))||p&&s.audioCodec===i.audioCodec||!p&&s.audioCodec!==i.audioCodec||g&&s.codecSet===i.codecSet)continue}l=n;break}}if(l>-1&&i.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:2,flags:0,nextAutoLevel:l}}return{action:2,flags:1}}onErrorOut(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case 0:break;case 2:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===ee.FRAG_GAP?/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()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:s,hdcpLevel:n,nextAutoLevel:r}=i;switch(s){case 0:this.switchLevel(e,r);break;case 2:n&&(t.maxHdcpLevel=xt[xt.indexOf(n)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)}i.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===ee.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){const t=wt(e.mimeType),i=this.hls.levels;for(let s=i.length;s--;)i[s][`${e.sourceBufferName}Codec`]===t&&this.hls.removeLevel(s)}}},fpsController:class{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(te.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(te.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(te.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(te.MEDIA_DETACHING,this.onMediaDetaching,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 e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){const s=performance.now();if(t){if(this.lastTime){const e=s-this.lastTime,n=i-this.lastDroppedFrames,r=t-this.lastDecodedFrames,o=1e3*n/e,a=this.hls;if(a.trigger(te.FPS_DROP,{currentDropped:n,currentDecoded:r,totalDroppedFrames:i}),o>0&&n>a.config.fpsDroppedMonitoringThreshold*r){let e=a.currentLevel;a.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===a.autoLevelCapping||a.autoLevelCapping>=e)&&(e-=1,a.trigger(te.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:a.currentLevel}),a.autoLevelCapping=e,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)}},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:es,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:wa,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends qs{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",le),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(te.LEVEL_LOADED,this.onLevelLoaded,this),e.on(te.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(te.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(te.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(te.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(te.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(te.LEVEL_LOADED,this.onLevelLoaded,this),e.off(te.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(te.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(te.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(te.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(te.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Fs,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:s}=t;if($e(i)&&(this.fragPrevious=i),this.state=Fs,!s)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let r;const o=i.start;for(let e=0;e=n[e].start&&o<=n[e].end){r=n[e];break}const a=i.start+i.duration;r?r.end=a:(r={start:o,end:a},n.push(r)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:s}=t;if(0===i&&s!==Number.POSITIVE_INFINITY){const e=s-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach((t=>{for(let i=0;inew $t(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{const t=new $t(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,le),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const s=this.levels[this.currentTrackId];null!=s&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.state!==Bs&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:s,levels:n}=this,{details:r,id:o}=t;if(!n)return void this.warn(`Subtitle tracks were reset while loading level ${o}`);const a=n[o];if(o>=n.length||!a)return;this.log(`Subtitle track ${o} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(r.live||null!=(i=a.details)&&i.live){const e=this.mainDetails;if(r.deltaUpdateFailed||!e)return;const t=e.fragments[0];var d;a.details?(l=this.alignPlaylists(r,a.details,null==(d=this.levelLastLoaded)?void 0:d.details),0===l&&t&&(l=t.start,Rs(r,l))):r.hasProgramDateTime&&e.hasProgramDateTime?(xs(r,e),l=r.fragmentStart):t&&(l=t.start,Rs(r,l))}a.details=r,this.levelLastLoaded=a,o===s&&(this.hls.trigger(te.SUBTITLE_TRACK_UPDATED,{details:r,id:o,groupId:t.groupId}),this.tick(),r.live&&!this.fragCurrent&&this.media&&this.state===Fs)&&(Zt(null,r.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),a.details=void 0))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,s=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&null!=s&&s.key&&s.iv&&$i(s.method)){const e=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,Vi(s.method)).catch((e=>{throw n.trigger(te.ERROR,{type:J.MEDIA_ERROR,details:ee.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((i=>{const s=performance.now();n.trigger(te.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:e,tdecrypt:s}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=Fs}))}}doTick(){if(this.media){if(this.state===Fs){const{currentTrackId:e,levels:t}=this,i=null==t?void 0:t[e];if(!i||!t.length||!i.details)return;if(this.waitForLive(i))return;const{config:s}=this,n=this.getLoadPosition(),r=Ii.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,s.maxBufferHole),{end:o,len:a}=r,l=i.details;if(a>this.hls.maxBufferLength+l.levelTargetDuration)return;const d=l.fragments,c=d.length,h=l.edge;let u=null;const f=this.fragPrevious;if(oh-e?0:e;u=Zt(f,d,Math.max(d[0].start,o),t),!u&&f&&f.startthis.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null;const t=yo(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(te.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(te.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(te.MANIFEST_LOADING,this.onManifestLoading,this),e.on(te.MANIFEST_PARSED,this.onManifestParsed,this),e.on(te.LEVEL_LOADING,this.onLevelLoading,this),e.on(te.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(te.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(te.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(te.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(te.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(te.MANIFEST_LOADING,this.onManifestLoading,this),e.off(te.MANIFEST_PARSED,this.onManifestParsed,this),e.off(te.LEVEL_LOADING,this.onLevelLoading,this),e.off(te.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(te.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(te.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const s=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,s||yo(i.textTracks).forEach((e=>{Ao(e)}))}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:n}=t,r=this.tracksInGroup[i];if(!r||r.groupId!==s)return void this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${null==r?void 0:r.groupId}`);const o=r.details;r.details=t.details,this.log(`Subtitle track ${i} "${r.name}" lang:${r.lang} group:${s} loaded [${n.startSN}-${n.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 n=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some((e=>-1===(null==s?void 0:s.indexOf(e))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!i||-1!==i.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.subtitlePreference;if(!n&&t){this.selectDefaultTrack=!1;const i=Yt(t,e);if(i>-1)n=e[i];else{const e=Yt(t,this.tracks);n=this.tracks[e]}}let s=this.findTrackId(n);-1===s&&n&&(s=this.findTrackId(null));const r={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(te.SUBTITLE_TRACKS_UPDATED,r),-1!==s&&-1===this.trackId&&this.setSubtitleTrack(s)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s-1){const e=this.tracksInGroup[s];return this.setSubtitleTrack(s),e}if(i)return null;{const i=Yt(e,t);if(i>-1)return t[i]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,s=e.groupId,n=this.getUrlWithDirectives(e.url,t),r=e.details,o=null==r?void 0:r.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${s}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${o&&r.live?" age "+o.toFixed(1)+(r.type?" "+r.type||0:""):""} ${n}`),this.hls.trigger(te.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=yo(e.textTracks),i=this.currentTrack;let s;if(i&&(s=t.filter((e=>Ir(i,e)))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach((e=>{"disabled"!==e.mode&&e!==s&&(e.mode="disabled")})),s){const e=this.subtitleDisplay?"showing":"hidden";s.mode!==e&&(s.mode=e)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!X(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e]||null;if(this.trackId=e,this.currentTrack=s,this.toggleTrackModes(),!s)return void this.hls.trigger(te.SUBTITLE_TRACK_SWITCH,{id:e});const n=!!s.details&&!s.details.live;if(e===this.trackId&&s===i&&n)return;this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:r,groupId:o="",name:a,type:l,url:d}=s;this.hls.trigger(te.SUBTITLE_TRACK_SWITCH,{id:r,groupId:o,name:a,type:l,url:d});const c=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(c)}},timelineController:class{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={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},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(te.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(te.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(te.MANIFEST_LOADING,this.onManifestLoading,this),e.on(te.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(te.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(te.FRAG_LOADING,this.onFragLoading,this),e.on(te.FRAG_LOADED,this.onFragLoaded,this),e.on(te.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(te.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(te.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(te.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(te.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(te.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(te.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(te.MANIFEST_LOADING,this.onManifestLoading,this),e.off(te.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(te.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(te.FRAG_LOADING,this.onFragLoading,this),e.off(te.FRAG_LOADED,this.onFragLoaded,this),e.off(te.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(te.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(te.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(te.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(te.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Ra(this,"textTrack1"),t=new Ra(this,"textTrack2"),i=new Ra(this,"textTrack3"),s=new Ra(this,"textTrack4");this.cea608Parser1=new Jo(1,e,t),this.cea608Parser2=new Jo(3,i,s)}addCues(e,t,i,s,n){let r=!1;for(let e=n.length;e--;){const s=n[e],c=(o=s[0],a=s[1],l=t,d=i,Math.min(a,d)-Math.max(o,l));if(c>=0&&(s[0]=Math.min(s[0],t),s[1]=Math.max(s[1],i),r=!0,c/(i-t)>.5))return}var o,a,l,d;if(r||n.push([t,i]),this.config.renderTextTracksNatively){const n=this.captionsTracks[e];this.Cues.newCue(n,t,i,s)}else{const n=this.Cues.newCue(null,t,i,s);this.hls.trigger(te.CUES_PARSED,{type:"captions",cues:n,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n}){const{unparsedVttFrags:r}=this;i===oe&&(this.initPTS[t.cc]={baseTime:s,timescale:n}),r.length&&(this.unparsedVttFrags=[],r.forEach((e=>{this.onFragLoaded(te.FRAG_LOADED,e)})))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let s=0;s{Ao(s[e]),delete s[e]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},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 e=0;ee.textCodec===ga));if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Rr(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const e=this.media,t=e?yo(e.textTracks):null;if(this.tracks.forEach(((e,i)=>{let s;if(t){let i=null;for(let s=0;snull!==e)).map((e=>e.label));e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const e=this.tracks.map((e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e})));this.hls.trigger(te.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const i=`textTrack${t[1]}`,s=this.captionsProperties[i];s&&(s.label=e.name,e.lang&&(s.languageCode=e.lang),s.media=e)}))}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===oe){var i,s;const{cea608Parser1:e,cea608Parser2:n,lastSn:r}=this,{cc:o,sn:a}=t.frag,l=null!=(i=null==(s=t.part)?void 0:s.index)?i:-1;e&&n&&(a!==r+1||a===r&&l!==this.lastPartIndex+1||o!==this.lastCc)&&(e.reset(),n.reset()),this.lastCc=o,this.lastSn=a,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:i,payload:s}=t;if(i.type===le)if(s.byteLength){const e=i.decryptdata,n="stats"in t;if(null==e||!e.encrypted||n){const e=this.tracks[i.level],n=this.vttCCs;n[i.cc]||(n[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),e&&e.textCodec===ga?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(te.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;Ea(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),i.trigger(te.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{i.logger.log(`Failed to parse IMSC1: ${t}`),i.trigger(te.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;const{frag:i,payload:s}=e,{initPTS:n,unparsedVttFrags:r}=this,o=n.length-1;if(!n[i.cc]&&-1===o)return void r.push(e);const a=this.hls;!function(e,t,i,s,n,r,o){const a=new ha,l=_e(new Uint8Array(e)).trim().replace(ua,"\n").split("\n"),d=[],c=t?function(e,t=1){return or(e,9e4,1/t)}(t.baseTime,t.timescale):0;let h,u="00:00.000",f=0,p=0,g=!0;a.oncue=function(e){const r=i[s];let o=i.ccOffset;const a=(f-c)/9e4;if(null!=r&&r.new&&(void 0!==p?o=i.ccOffset=r.start:function(e,t,i){let s=e[t],n=e[s.prevCC];if(!n||!n.new&&s.new)return e.ccOffset=e.presentationOffset=s.start,void(s.new=!1);for(;null!=(r=n)&&r.new;){var r;e.ccOffset+=s.start-n.start,s.new=!1,s=n,n=e[s.prevCC]}e.presentationOffset=i}(i,s,a)),a){if(!t)return void(h=new Error("Missing initPTS for VTT MPEGTS"));o=a-i.presentationOffset}const l=e.endTime-e.startTime,u=fr(9e4*(e.startTime+o-p),9e4*n)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);const g=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(g)),e.id||(e.id=pa(e.startTime,e.endTime,g)),e.endTime>0&&d.push(e)},a.onparsingerror=function(e){h=e},a.onflush=function(){h?o(h):r(d)},l.forEach((e=>{if(g){if(fa(e,"X-TIMESTAMP-MAP=")){g=!1,e.slice(16).split(",").forEach((e=>{fa(e,"LOCAL:")?u=e.slice(6):fa(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))}));try{p=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(X(t)&&X(i)&&X(s)&&X(n)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=6e4*s,t+=36e5*n,t}(u)/1e3}catch(e){h=e}return}""===e&&(g=!1)}a.parse(e+"\n")})),a.flush()}(null!=(t=i.initSegment)&&t.data?dt(i.initSegment.data,new Uint8Array(s)).buffer:s,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,(e=>{this._appendCues(e,i.level),a.trigger(te.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})}),(t=>{const n="Missing initPTS for VTT MPEGTS"===t.message;n?r.push(e):this._fallbackToIMSC1(i,s),a.logger.log(`Failed to parse VTT cue: ${t}`),n&&o>i.cc||a.trigger(te.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})}))}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||Ea(t,this.initPTS[e.cc],(()=>{i.textCodec=ga,this._parseIMSC1(e,t)}),(()=>{i.textCodec="wvtt"}))}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach((e=>vo(i,e)))}else{const s=this.tracks[t];if(!s)return;const n=s.default?"default":"subtitles"+t;i.trigger(te.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===le&&this.onFragLoaded(te.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=t;if(i.type!==oe||"NONE"!==this.closedCaptionsForLevel(i))for(let e=0;eEo(e[s],t,i)))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==s){const{textTracks:e}=this;Object.keys(e).forEach((i=>Eo(e[i],t,s)))}}}extractCea608Data(e){const t=[[],[]],i=31&e[0];let s=2;for(let n=0;n=t){const s=i.start,n=i.end;let r=e.fragments;if(!i.relurl){const{fragmentHint:t}=e;t&&(r=r.concat(t))}return Qt(r,(e=>e.cct||e.start>=n?-1:0))}return null}(t,i,e)||t&&ti(t.fragments,i)||e}startLoad(e,t){if(!this.levels)return this.startPosition=e,void(this.state=Bs);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=Fs):this.state=Gs,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case Fs:this.doTickIdle();break;case Gs:{const{levels:e,trackId:t}=this,i=null==e?void 0:e[t],s=null==i?void 0:i.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=Ws}break}case Vs:{var e;const t=performance.now(),i=this.retryDate;if(!i||t>=i||null!=(e=this.media)&&e.seeking){const{levels:e,trackId:t}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==e?void 0:e[t])||null),this.state=Fs}break}case Ws:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:s,complete:n}=e,r=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=$s;const e={frag:t,part:i,payload:s.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),n&&super._handleFragmentLoadComplete(e)}else r&&r.cc!==e.frag.cc&&(this.log(`Waiting fragment cc (${t.cc}) cancelled because video is at cc ${r.cc}`),this.nextLoadPosition=this.findSyncFrag(r).start,this.clearWaitingFragment())}else this.state=Fs}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.state!==Bs&&(this.state=Fs))}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:s,trackId:n}=this,r=t.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!r.startFragPrefetch)||null==i||!i[n])return;const o=i[n],a=o.details;if(!a||this.waitForLive(o)||this.waitForCdnTuneIn(a))return this.state=Gs,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,xe,ae));const d=this.getFwdBufferInfo(l,ae);if(null===d)return;if(!this.switchingTrack&&this._streamEnded(d,a))return t.trigger(te.BUFFER_EOS,{type:"audio"}),void(this.state=Hs);const c=d.len,h=t.maxBufferLength,u=a.fragments,f=u[0].start,p=this.getLoadPosition(),g=this.flushing?p:d.end;if(this.switchingTrack&&s){const e=p;a.PTSKnown&&ef||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=f+.05)}if(c>=h&&!this.switchingTrack&&gv.end){const e=this.fragmentTracker.getFragAtPos(g,oe);e&&e.end>v.end&&(v=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(m.start>v.end)return}this.loadFragment(m,o,g)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map((e=>new $t(e)))}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.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==Bs&&(this.setInterval(100),this.state=Fs,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(te.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:s}=this,{details:n,id:r,groupId:o,track:a}=t;if(!s)return void this.warn(`Audio tracks reset while loading track ${r} "${a.name}" of "${o}"`);const l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==Bs&&(this.state=Gs));this.cachedTrackLoadedData=null,this.log(`Audio track ${r} "${a.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const d=s[r];let c=0;if(n.live||null!=(i=d.details)&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;var h;d.details&&(c=this.alignPlaylists(n,d.details,null==(h=this.levelLastLoaded)?void 0:h.details)),n.alignedSliding||(Ms(n,l),n.alignedSliding||xs(n,l),c=n.fragmentStart)}d.details=n,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(te.AUDIO_TRACK_UPDATED,{details:n,id:r,groupId:t.groupId}),this.state!==Gs||this.waitForCdnTuneIn(n)||(this.state=Fs),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:n}=e,{config:r,trackId:o,levels:a}=this;if(!a)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const l=a[o];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const d=l.details;if(!d)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const c=r.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new _r(this.hls,ae,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==u){const e=!1,t=s?s.index:-1,r=-1!==t,o=new Ri(i.level,i.sn,i.stats.chunkCount,n.byteLength,t,r);h.push(n,f,c,"",i,s,d.totalduration,e,o,u)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${o}`);const{cache:e}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Qs,complete:!1};e.push(new Uint8Array(n)),this.state!==Bs&&(this.state=Ws)}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===oe&&$e(t.frag)&&(this.mainFragLoading=t,this.state===Fs&&this.tick())}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i.type===ae)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"}`);else{if($e(i)){this.fragPrevious=i;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(te.AUDIO_TRACK_SWITCHED,pe({},e)))}this.fragBufferedComplete(i,s),this.media&&this.tick()}else this.audioOnly||i.type!==oe||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(e,t){var i;if(t.fatal)this.state=Ys;else switch(t.details){case ee.FRAG_GAP:case ee.FRAG_PARSING_ERROR:case ee.FRAG_DECRYPT_ERROR:case ee.FRAG_LOAD_ERROR:case ee.FRAG_LOAD_TIMEOUT:case ee.KEY_LOAD_ERROR:case ee.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ae,t);break;case ee.AUDIO_TRACK_LOAD_ERROR:case ee.AUDIO_TRACK_LOAD_TIMEOUT:case ee.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Gs||(null==(i=t.context)?void 0:i.type)!==ne||(this.state=Fs);break;case ee.BUFFER_ADD_CODEC_ERROR:case ee.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.resetLoadingState();break;case ee.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case ee.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==Be&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Be){this.flushing=!1,this.bufferFlushed=!0,this.state===Hs&&(this.state=Fs);const e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,ae),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:s}=this,{remuxResult:n,chunkMeta:r}=e,o=this.getCurrentContext(r);if(!o)return void this.resetWhenMissingContext(r);const{frag:a,part:l,level:d}=o,{details:c}=d,{audio:h,text:u,id3:f,initSegment:p}=n;if(!this.fragContextChanged(a)&&c){if(this.state=js,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){const e=a.initSegment||a;this._bufferInitSegment(d,p.tracks,e,r),s.trigger(te.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:p.tracks})}if(h){const{startPTS:e,endPTS:t,startDTS:i,endDTS:s}=h;l&&(l.elementaryStreams[xe]={startPTS:e,endPTS:t,startDTS:i,endDTS:s}),a.setElementaryStreamInfo(xe,e,t,i,s),this.bufferFragmentData(h,a,l,r)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=ue({id:i,frag:a,details:c},f);s.trigger(te.FRAG_PARSING_METADATA,e)}if(u){const e=ue({id:i,frag:a,details:c},u);s.trigger(te.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(a)}_bufferInitSegment(e,t,i,s){if(this.state!==js)return;if(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio)return;const n=t.audio;n.id=ae;const r=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${r}/${n.codec}]`),r&&1===r.split(",").length&&(n.levelCodec=r),this.hls.trigger(te.BUFFER_CODECS,t);const o=n.initSegment;if(null!=o&&o.byteLength){const e={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:o};this.hls.trigger(te.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);var n;if(this.switchingTrack||s===li||s===ci)if($e(e))if(null!=(n=t.details)&&n.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=Ws;const i=this.mainDetails;i&&i.fragmentStart!==t.details.fragmentStart&&xs(t.details,i)}else super.loadFragment(e,t,i);else this._loadInitSegment(e,t);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:s,characteristics:n,audioCodec:r,channels:o}=this.bufferedTrack;Wt({name:t,lang:i,assocLang:s,characteristics:n,audioCodec:r,channels:o},e,zt)||(Xt(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(te.AUDIO_TRACK_SWITCHED,pe({},e))}},audioTrackController:class extends Cr{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(te.MANIFEST_LOADING,this.onManifestLoading,this),e.on(te.MANIFEST_PARSED,this.onManifestParsed,this),e.on(te.LEVEL_LOADING,this.onLevelLoading,this),e.on(te.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(te.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(te.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(te.MANIFEST_LOADING,this.onManifestLoading,this),e.off(te.MANIFEST_PARSED,this.onManifestParsed,this),e.off(te.LEVEL_LOADING,this.onLevelLoading,this),e.off(te.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(te.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(te.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:n}=t,r=this.tracksInGroup[i];if(!r||r.groupId!==s)return void this.warn(`Audio track with id:${i} and group:${s} not found in active group ${null==r?void 0:r.groupId}`);const o=r.details;r.details=t.details,this.log(`Audio track ${i} "${r.name}" lang:${r.lang} group:${s} loaded [${n.startSN}-${n.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 n=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some((e=>-1===(null==s?void 0:s.indexOf(e))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!i||-1!==i.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!n&&t){const i=Yt(t,e,zt);if(i>-1)n=e[i];else{const e=Yt(t,this.tracks);n=this.tracks[e]}}let s=this.findTrackId(n);-1===s&&n&&(s=this.findTrackId(null));const o={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(te.AUDIO_TRACKS_UPDATED,o);const a=this.trackId;if(-1!==s&&-1===a)this.setAudioTrack(s);else if(e.length&&-1===a){var r;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(r=this.groupIds)?void 0:r.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(te.ERROR,{type:J.MEDIA_ERROR,details:ee.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&(t.context.type!==ne||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||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&&Wt(e,s,zt))return s;const n=Yt(e,this.tracksInGroup,zt);if(n>-1){const e=this.tracksInGroup[n];return this.setAudioTrack(n),e}if(s){let s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);const n=function(e,t,i,s,n){const r=t[s],o=t.reduce(((e,t,i)=>{const s=t.uri;return(e[s]||(e[s]=[])).push(i),e}),{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const a=r.videoRange,l=r.frameRate,d=r.codecSet.substring(0,4),c=qt(t,s,(t=>{if(t.videoRange!==a||t.frameRate!==l||t.codecSet.substring(0,4)!==d)return!1;const s=t.audioGroups,r=i.filter((e=>!s||-1!==s.indexOf(e.groupId)));return Yt(e,r,n)>-1}));return c>-1?c:qt(t,s,(t=>{const s=t.audioGroups,r=i.filter((e=>!s||-1!==s.indexOf(e.groupId)));return Yt(e,r,n)>-1}))}(e,t.levels,i,s,zt);if(-1===n)return null;t.nextLoadLevel=n}if(e.channels||e.audioCodec){const t=Yt(e,i);if(t>-1)return i[t]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e],n=s.details&&!s.details.live;if(e===this.trackId&&s===i&&n)return;if(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(te.AUDIO_TRACK_SWITCHING,pe({},s)),n)return;const r=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(r)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:xr,su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const{frag:t,part:i}=e,s=this.hls.levels[t.level],n=this.getObjectType(t),r={d:1e3*(i||t).duration,ot:n};n!==Fr&&n!==Br&&n!=Ur||(r.br=s.bitrate/1e3,r.tb=this.getTopBandwidth(n)/1e3,r.bl=this.getBufferLength(n));const o=i?this.getNextPart(i):this.getNextFrag(t);null!=o&&o.url&&o.url!==t.url&&(r.nor=o.url),this.apply(e,r)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;null!=i&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(te.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(te.MEDIA_DETACHED,this.onMediaDetached,this),e.on(te.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(te.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(te.MEDIA_DETACHED,this.onMediaDetached,this),e.off(te.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,s;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(s=t.tracks.video)?void 0:s.buffer}createData(){var e;return{v:1,sf:Gr,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ue(t,this.createData());const i=t.ot===$r||t.ot===Fr||t.ot===Ur;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:s}=this;s&&(t=Object.keys(t).reduce(((e,i)=>(s.includes(i)&&(e[i]=t[i]),e)),{}));const n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),function(e,t,i){ue(e,function(e,t={}){const i={};if(!e)return i;const s=Object.entries(e),n=Object.entries(Wr).concat(Object.entries((null==t?void 0:t.customHeaderMap)||{})),r=s.reduce(((e,t)=>{var i,s;const[r,o]=t,a=(null===(i=n.find((e=>e[1].includes(r))))||void 0===i?void 0:i[0])||Kr;return null!==(s=e[a])&&void 0!==s||(e[a]={}),e[a][r]=o,e}),{});return Object.entries(r).reduce(((e,[i,s])=>(e[i]=co(s,t),e)),i)}(t,i))}(e.headers,t,n)):e.url=function(e,t,i){const s=function(e,t={}){if(!e)return"";const i=co(e,t);return`CMCD=${encodeURIComponent(i)}`}(t,i);if(!s)return e;if(ho.test(e))return e.replace(ho,s);const n=e.includes("?")?"&":"?";return`${e}${n}${s}`}(e.url,t,n)}getNextFrag(e){var t;const i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){const t=e.sn-i.startSN;return i.fragments[t+1]}}getNextPart(e){var t,i;const{index:s,fragment:n}=e,r=null==(t=this.hls.levels[n.level])||null==(i=t.details)?void 0:i.partList;if(r){const{sn:e}=n;for(let t=r.length-1;t>=0;t--){const i=r[t];if(i.index===s&&i.fragment.sn===e)return r[t+1]}}}getObjectType(e){const{type:t}=e;return"subtitle"===t?Vr:"initSegment"===e.sn?$r:"audio"===t?Br:"main"===t?this.hls.audioTracks.length?Fr:Ur:void 0}getTopBandwidth(e){let t,i=0;const s=this.hls;if(e===Br)t=s.audioTracks;else{const e=s.maxAutoLevel,i=e>-1?e+1:s.levels.length;t=s.levels.slice(0,i)}for(const e of t)e.bitrate>i&&(i=e.bitrate);return i>0?i:NaN}getBufferLength(e){const t=this.media,i=e===Br?this.audioBuffer:this.videoBuffer;return i&&t?1e3*Ii.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len:NaN}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,s){t(e),this.loader.load(e,i,s)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,s){t(e),this.loader.load(e,i,s)}}}},contentSteeringController:class extends ge{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(te.MANIFEST_LOADING,this.onManifestLoading,this),e.on(te.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(te.MANIFEST_PARSED,this.onManifestParsed,this),e.on(te.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(te.MANIFEST_LOADING,this.onManifestLoading,this),e.off(te.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(te.MANIFEST_PARSED,this.onManifestParsed,this),e.off(te.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce(((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e)),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(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((t=>t!==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;null!==i&&(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(2===(null==i?void 0:i.action)&&1===i.flags){const e=this.levels;let s=this._pathwayPriority,n=this.pathwayId;if(t.context){const{groupId:i,pathwayId:s,type:r}=t.context;i&&e?n=this.getPathwayForGroupId(i,r,n):s&&(n=s)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!s&&e&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==n),i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${n} levels: ${e?e.length:e} priorities: ${Gt(s)} penalized: ${Gt(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){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 null===this.levels?[]:this.levels.filter((t=>e===t.pathwayId))}updatePathwayPriority(e){let t;this._pathwayPriority=e;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach((e=>{s-i[e]>3e5&&delete i[e]}));for(let s=0;s0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,Ps(t),this.hls.trigger(te.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[r];o&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=r);break}}}getPathwayForGroupId(e,t,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i{const{ID:n,"BASE-ID":r,"URI-REPLACEMENT":o}=e;if(t.some((e=>e.pathwayId===n)))return;const a=this.getLevelsForPathway(r).map((e=>{const t=new xi(e.attrs);t["PATHWAY-ID"]=n;const r=t.AUDIO&&`${t.AUDIO}_clone_${n}`,a=t.SUBTITLES&&`${t.SUBTITLES}_clone_${n}`;r&&(i[t.AUDIO]=r,t.AUDIO=r),a&&(s[t.SUBTITLES]=a,t.SUBTITLES=a);const l=fo(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),d=new $t({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t{this.log(`Loaded steering manifest: "${s}"`);const r=e.data;if(1!==(null==r?void 0:r.VERSION))return void this.log(`Steering VERSION ${r.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=r.TTL;const{"RELOAD-URI":o,"PATHWAY-CLONES":a,"PATHWAY-PRIORITY":l}=r;if(o)try{this.uri=new self.URL(o,s).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${o}`)}this.scheduleRefresh(this.uri||i.url),a&&this.clonePathways(a);const d={steeringManifest:r,url:s.toString()};this.hls.trigger(te.STEERING_MANIFEST_LOADED,d),l&&this.updatePathwayPriority(l)},onError:(e,t,i,s)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let n=1e3*this.timeToLoad;if(429!==e.code)this.scheduleRefresh(this.uri||t.url,n);else{const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(n=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`)}},onTimeout:(e,t,i)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,a,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var t;const i=null==(t=this.hls)?void 0:t.media;!i||i.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)}),t)}},interstitialsController:class extends ge{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;const t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;const i=t<=-.01;this.timelinePos=e,this.bufferedPos=e;const s=this.playingItem;if(!s)return void this.checkBuffer();if(i&&this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(),this.checkBuffer(),i&&e=s.end){var n;const e=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(s)&&null!=(n=this.media)&&n.paused&&(this.shouldPlay=!1),!i){const t=this.findItemIndex(s);if(e>t){const i=this.schedule.findJumpRestrictedIndex(t+1,e);if(i>t)return void this.setSchedulePosition(i)}}return void this.setSchedulePosition(e)}const r=this.playingAsset;if(!r){if(this.playingLastItem&&this.isInterstitial(s)){const t=s.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}const o=r.timelineStart,a=r.duration||0;(i&&e=o+a)&&this.setScheduleToAssetAtTime(e,r)},this.onTimeupdate=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;if(!(e>this.timelinePos))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();const t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}const i=this.playingAsset;i&&e>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(e,i)},this.onScheduleUpdate=(e,t)=>{const i=this.schedule,s=this.playingItem,n=i.events||[],r=i.items||[],o=i.durations,a=e.map((e=>e.identifier)),l=!(!n.length&&!a.length);if(l&&this.log(`INTERSTITIALS_UPDATED (${n.length}): ${n}\nSchedule: ${r.map((e=>Po(e)))}`),a.length&&this.log(`Removed events ${a}`),this.playerQueue.forEach((e=>{if(e.interstitial.appendInPlace){const t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(s){Math.abs(i)>bo&&this.warn(`${s} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}})),s){const e=this.updateItem(s,this.timelinePos);this.itemsMatch(s,e)&&(this.playingItem=e,this.waitingItem=this.endedItem=null)}else this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const d=this.bufferingItem;if(d){const e=this.updateItem(d,this.bufferedPos);this.itemsMatch(d,e)?this.bufferingItem=e:d.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(d.event,null))}if(e.forEach((e=>{e.assetList.forEach((e=>{this.clearAssetPlayer(e.identifier,null)}))})),l||t){if(this.hls.trigger(te.INTERSTITIALS_UPDATED,{events:n.slice(0),schedule:r.slice(0),durations:o,removedIds:a}),this.isInterstitial(s)&&a.includes(s.event.identifier))return this.warn(`Interstitial "${s.event.identifier}" removed while playing`),void this.primaryFallback(s.event);this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Oo(e),this.schedule=new wo(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e.on(te.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(te.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(te.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(te.MANIFEST_LOADING,this.onManifestLoading,this),e.on(te.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(te.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(te.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(te.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(te.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(te.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(te.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(te.BUFFER_APPENDED,this.onBufferAppended,this),e.on(te.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(te.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(te.MEDIA_ENDED,this.onMediaEnded,this),e.on(te.ERROR,this.onError,this),e.on(te.DESTROYING,this.onDestroying,this)}unregisterListeners(){const e=this.hls;e&&(e.off(te.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(te.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(te.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(te.MANIFEST_LOADING,this.onManifestLoading,this),e.off(te.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(te.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(te.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(te.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(te.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(te.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(te.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(te.BUFFER_CODECS,this.onBufferCodecs,this),e.off(te.BUFFER_APPENDED,this.onBufferAppended,this),e.off(te.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(te.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(te.MEDIA_ENDED,this.onMediaEnded,this),e.off(te.ERROR,this.onError,this),e.off(te.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.manager=null,this.hls=this.HlsPlayerClass=this.schedule=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){No(e,"play",this.onPlay),No(e,"pause",this.onPause),No(e,"seeking",this.onSeeking),No(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;Do(i,"seeking",this.onSeeking),Do(i,"timeupdate",this.onTimeupdate),Do(i,"play",this.onPlay),Do(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!s){this.clearScheduleState();const e=this.findItemIndex(i);this.setSchedulePosition(e)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const i=!!t.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){const e=this.getBufferingPlayer();e&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.manager){if(!this.hls)return null;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=t=>t?e.getAssetPlayer(t.identifier):t,s=(t,s,n,o,a)=>{if(t){let l=t[s].start;const d=t.event;if(d){if("playout"===s||d.timelineOccupancy!==So.Point){const e=i(n);(null==e?void 0:e.interstitial)===d&&(l+=e.assetItem.startOffset+e[a])}}else l+=("bufferedPos"===o?r():e[o])-t.start;return l}return 0},n=(t,i)=>{if(0!==t&&"primary"!==i&&e.schedule.length){var s;const n=e.schedule.findItemIndexAtTime(t),r=null==(s=e.schedule.items)?void 0:s[n];if(r)return t+(r[i].start-r.start)}return t},r=()=>{const t=e.bufferedPos;return t===Number.MAX_VALUE?o("primary"):Math.max(t,0)},o=t=>{var i;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:e.schedule.durations[t]},a=(t,n)=>{var r,o;const a=e.effectivePlayingItem;if(null!=a&&null!=(r=a.event)&&r.restrictions.skip)return;e.log(`seek to ${t} "${n}"`);const l=e.effectivePlayingItem,d=e.schedule.findItemIndexAtTime(t,n),c=null==(o=e.schedule.items)?void 0:o[d],h=e.getBufferingPlayer(),u=null==h?void 0:h.interstitial,f=null==u?void 0:u.appendInPlace,p=l&&e.itemsMatch(l,c);if(l&&(f||p)){const r=i(e.playingAsset),o=(null==r?void 0:r.media)||e.primaryMedia;if(o){const i="primary"===n?o.currentTime:s(l,n,e.playingAsset,"timelinePos","currentTime"),a=t-i,d=(f?i:o.currentTime)+a;if(d>=0&&(!r||f||d<=r.duration))return void(o.currentTime=d)}}if(c){let i=t;if("primary"!==n){const e=t-c[n].start;i=c.start+e}const s=!e.isInterstitial(c);if(e.isInterstitial(l)&&!l.event.appendInPlace||!s&&!c.event.appendInPlace){if(l){const r=e.findItemIndex(l);if(d>r){const t=e.schedule.findJumpRestrictedIndex(r+1,d);if(t>r)return void e.setSchedulePosition(t)}let o=0;if(s)e.timelinePos=i,e.checkBuffer();else{var g;const e=null==c||null==(g=c.event)?void 0:g.assetList;if(e){const i=t-(c[n]||c).start;for(let t=e.length;t--;){const s=e[t];if(s.duration&&i>=s.startOffset&&i{const i=e.effectivePlayingItem;if(e.isInterstitial(i))return i;const s=t();return e.isInterstitial(s)?s:null},d={get currentTime(){const t=l(),i=e.effectivePlayingItem;return i&&i===t?s(i,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(t){const i=l(),s=e.effectivePlayingItem;s&&s===i&&a(t+s.playout.start,"playout")},get duration(){const e=l();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t;const i=null==(t=l())?void 0:t.event.assetList;return i?i.map((t=>e.getAssetPlayer(t.identifier))):[]},get playingIndex(){var t;const i=null==(t=l())?void 0:t.event;return i&&e.effectivePlayingAsset?i.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};this.manager={get events(){var t,i;return(null==(t=e.schedule)||null==(i=t.events)?void 0:i.slice(0))||[]},get schedule(){var t,i;return(null==(t=e.schedule)||null==(i=t.items)?void 0:i.slice(0))||[]},get interstitialPlayer(){return l()?d:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const i=t();return e.findItemIndex(i)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return r()},get currentTime(){const t=e.timelinePos;return t>0?t:0},set currentTime(e){a(e,"primary")},get duration(){return o("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return s(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){a(e,"integrated")},get duration(){return o("integrated")},get seekableStart(){var t;return n((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:()=>{const t=e.effectivePlayingItem,i=null==t?void 0:t.event;if(i&&!i.restrictions.skip){const s=e.findItemIndex(t);if(i.appendInPlace){const e=t.playout.start+t.event.duration;a(e+.001,"playout")}else e.advanceAfterAssetEnded(i,s,1/0)}}}}return this.manager}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,i=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&i)&&this.findItemIndex(t)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t,i;if(null===this.mediaSelection)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let n=this.media;!n&&null!=(e=this.bufferingItem)&&null!=(t=e.event)&&t.appendInPlace&&(n=this.primaryMedia);const r=null==(i=n)?void 0:i.currentTime;return void 0!==r&&X(r)?r:void 0}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!(null==e||!e.event)}retreiveMediaSource(e,t){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const i=e.interstitial.appendInPlace,s=e.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&s)return void(this.detachedData={media:s});const i=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Gt(i)}`),this.detachedData=i}else t&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(e,t){var i,s;if(e.media===t)return;let n=null;const r=this.hls,o=e!==r,a=o&&e.interstitial.appendInPlace,l=null==(i=this.detachedData)?void 0:i.mediaSource;let d;if(r.media)a&&(n=r.transferMedia(),this.detachedData=n),d="Primary";else if(l){const e=this.getBufferingPlayer();e?(n=e.transferMedia(),d=`${e}`):d="detached MediaSource"}else d="detached media";if(!n)if(l)n=this.detachedData,this.log(`using detachedData: MediaSource ${Gt(n)}`);else if(!this.detachedData||r.media===t){const e=this.playerQueue;e.length>1&&e.forEach((e=>{if(o&&e.interstitial.appendInPlace!==a){const t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}})),this.hls.detachMedia(),this.detachedData={media:t}}const c=n&&"mediaSource"in n&&"closed"!==(null==(s=n.mediaSource)?void 0:s.readyState),h=c&&n?n:t;if(this.log(`${c?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${d}`),h===n){const t=o&&e.assetId===this.schedule.assetIdAtEnd;h.overrides={duration:this.schedule.duration,endOfStream:!o||t,cueRemoval:!o}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e.events;if(!t||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const i=this.timelinePos,s=this.effectivePlayingItem;if(-1===i){const i=this.hls.startPosition;if(this.timelinePos=i,t.length&&t[0].cue.pre){const i=e.findEventIndex(t[0].identifier);this.setSchedulePosition(i)}else if(i>=0||!this.primaryLive){const t=this.timelinePos=i>0?i:0,s=e.findItemIndexAtTime(t);this.setSchedulePosition(s)}}else if(s&&!this.playingItem){const t=e.findItemIndex(s);this.setSchedulePosition(t)}}advanceAfterAssetEnded(e,t,i){const s=i+1;if(e.isAssetPastPlayoutLimit(s)||e.assetList[s].error){const i=this.schedule.items;if(i){const s=t+1;if(s>=i.length)return void this.setSchedulePosition(-1);const n=e.resumeTime;this.timelinePos=0?i[e]:null,n=this.playingItem,r=this.playingLastItem;if(this.isInterstitial(n)){var o;const l=n.event,d=this.playingAsset,c=null==d?void 0:d.identifier,h=c?this.getAssetPlayer(c):null;if(h&&c&&(!this.eventItemsMatch(n,s)||void 0!==t&&c!==(null==(o=l.assetList)?void 0:o[t].identifier))){var a;const t=l.findAssetIndex(d);this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${l.assetList.length} ${Io(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(te.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:t,event:l,schedule:i.slice(0),scheduleIndex:e,player:h}),this.retreiveMediaSource(c,s),!h.media||null!=(a=this.detachedData)&&a.mediaSource||h.detachMedia()}if(!this.eventItemsMatch(n,s)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${l} ${Po(n)}`),l.hasPlayed=!0,this.hls.trigger(te.INTERSTITIAL_ENDED,{event:l,schedule:i.slice(0),scheduleIndex:e}),l.cue.once)){this.updateSchedule();const e=this.schedule.items;if(s&&e){const i=this.schedule.findItemIndex(s);this.advanceSchedule(i,e,t,n,r)}return}}this.advanceSchedule(e,i,t,n,r)}advanceSchedule(e,t,i,s,n){const r=e>=0?t[e]:null,o=this.primaryMedia,a=this.playerQueue;if(a.length&&a.forEach((t=>{const i=t.interstitial,s=this.schedule.findEventIndex(i.identifier);(se+1)&&this.clearInterstitial(i,r)})),this.isInterstitial(r)){this.timelinePos=Math.min(Math.max(this.timelinePos,r.start),r.end);const n=r.event;void 0===i&&(i=this.schedule.findAssetIndex(n,this.timelinePos));const a=this.waitingItem;this.assetsBuffered(r,o)||this.setBufferingItem(r);let l=this.preloadAssets(n,i);if(this.eventItemsMatch(r,a||s)||(this.waitingItem=r,this.log(`INTERSTITIAL_STARTED ${Po(r)} ${n.appendInPlace?"append in place":""}`),this.hls.trigger(te.INTERSTITIAL_STARTED,{event:n,schedule:t.slice(0),scheduleIndex:e})),!n.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${n}`);if(n.assetListLoader&&(n.assetListLoader.destroy(),n.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${n}`);this.waitingItem=this.endedItem=null,this.playingItem=r;const d=n.assetList[i];if(!d){const s=t[e+1],r=this.media;return s&&r&&!this.isInterstitial(s)&&r.currentTime=e.end)&&(i=this.getPrimaryResumption(e,t),this.timelinePos=i),this.attachPrimary(i,e)}if(!i)return;const n=this.schedule.items;n&&(this.log(`resumed ${Po(e)}`),this.hls.trigger(te.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const e=this.primaryDetails;if(0===t)return this.hls.startPosition;if(e&&(ie.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:Ii.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const s=this.primaryMedia;if(!s)return;const n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,s),i&&this.startLoadingPrimaryAt(e,i)),i||(this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const s=this.hls;!s.loadingEnabled||!s.media||Math.abs(((null==(i=s.mainForwardBufferInfo)?void 0:i.start)||s.media.currentTime)-e)>.5?s.startLoad(e,t):s.bufferingEnabled||s.resumeBuffering()}onManifestLoading(){this.stopLoad(),this.schedule.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(te.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(te.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level)return;const i=this.hls.levels[t.level],s=pe(pe({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s,this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s)return void(this.altSelection=pe(pe({},this.altSelection),{},{audio:i}));const n=pe(pe({},s),{},{audio:i});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s)return void(this.altSelection=pe(pe({},this.altSelection),{},{subtitles:i}));const n=pe(pe({},s),{},{subtitles:i});this.mediaSelection=n}onAudioTrackSwitching(e,t){const i=Ht(t);this.playerQueue.forEach((e=>e.hls.setAudioOption(t)||e.hls.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=Ht(t);this.playerQueue.forEach((e=>e.hls.setSubtitleOption(t)||-1!==t.id&&e.hls.setSubtitleOption(i)))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){const t=this.schedule.events;if(this.bufferedPose)return;if(1===t.length&&this.itemsMatch(t[0],n))return void(this.bufferedPos=e);const r=this.playingItem,o=this.findItemIndex(r);let a=s.findItemIndexAtTime(e);if(this.bufferedPos=n.end||null!=(l=r.event)&&l.appendInPlace&&e+.01>=r.start)&&(a=s),s-o>1&&!1===(null==n||null==(d=n.event)?void 0:d.appendInPlace))return;if(this.bufferedPos=e,a>i&&a>o)this.bufferedToItem(r);else{const t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&r.start{const i=this.getAssetPlayer(e.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(t))}))}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(this.itemsMatch(e,t))this.bufferingItem!==e&&(this.bufferingItem=e);else{const{items:s,events:n}=i;if(!s||!n)return t;const r=this.isInterstitial(e),o=this.getBufferingPlayer();if(this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos)),!this.playbackDisabled){const i=o?o.remaining:t?t.end-this.timelinePos:0;this.log(`buffered to boundary ${Po(e)}`+(t?` (${i.toFixed(2)} remaining)`:"")),r?e.event.assetList.forEach((e=>{const t=this.getAssetPlayer(e.identifier);t&&t.resumeBuffering()})):(this.hls.resumeBuffering(),this.playerQueue.forEach((e=>e.pauseBuffering())))}this.hls.trigger(te.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==i){this.bufferingAsset=null;const t=this.detachedData;if(t)if(t.mediaSource){const t=!0;this.attachPrimary(e.start,e,t)}else this.preloadPrimary(e);else this.preloadPrimary(e)}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,s=0===i.assetList.length&&!i.assetListLoader,n=i.cue.once;if(s||!n){const e=this.preloadAssets(i,t);if(null!=e&&e.interstitial.appendInPlace){const s=i.assetList[t],n=this.primaryMedia;s&&n&&this.bufferAssetPlayer(e,n)}}}preloadAssets(e,t){const i=e.assetUrl,s=e.assetList.length,n=0===s&&!e.assetListLoader,r=e.cue.once;if(n){const n=e.timelineStart;if(e.appendInPlace){var o;const t=this.playingItem;this.isInterstitial(t)||(null==t||null==(o=t.nextEvent)?void 0:o.identifier)!==e.identifier||this.flushFrontBuffer(n+.25)}let r,a=0;if(!this.playingItem&&this.primaryLive&&(a=this.hls.startPosition,-1===a&&(a=this.hls.liveSyncPosition||0)),a&&!e.cue.pre&&!e.cue.post){const e=a-n;e>0&&(r=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:s} ${e}${r?` live-start: ${a} start-offset: ${r}`:""}`),i)return this.createAsset(e,0,0,n,e.duration,i);const l=this.assetListLoader.loadAssetList(e,r);l&&(e.assetListLoader=l)}else if(!r&&s){for(let i=t;i{this.hls.trigger(te.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})})))}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i1){const i=t.duration;i&&e{if(s.live){const t=new Error(`Interstitials MUST be VOD assets ${e}`),s={fatal:!0,type:J.OTHER_ERROR,details:ee.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};return void this.handleAssetItemError(s,e,this.schedule.findEventIndex(e.identifier),i,t.message)}const n=s.edge-s.fragmentStart,r=t.duration;(null===r||n>r)&&(this.log(`Interstitial asset "${c}" duration change ${r} > ${n}`),t.duration=n,this.updateSchedule())};f.on(te.LEVEL_UPDATED,((e,{details:t})=>p(t))),f.on(te.LEVEL_PTS_UPDATED,((e,{details:t})=>p(t)));const g=(e,t)=>{const i=this.getAssetPlayer(c);if(i&&t.tracks){i.off(te.BUFFER_CODECS,g),i.tracks=t.tracks;const e=this.primaryMedia;this.bufferingAsset===i.assetItem&&e&&!i.media&&this.bufferAssetPlayer(i,e)}};f.on(te.BUFFER_CODECS,g);const m=()=>{var i;const s=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${s}`),!s)return;const n=this.schedule.findEventIndex(e.identifier),r=e.findAssetIndex(t),o=r+1,a=null==(i=this.schedule.items)?void 0:i[n];if(this.isInterstitial(a))if(-1===r||e.isAssetPastPlayoutLimit(o)||e.assetList[o].error){var l;const e=null==(l=this.schedule.items)?void 0:l[n+1];e&&this.bufferedToItem(e)}else this.bufferedToItem(a,o)};f.on(te.BUFFERED_TO_END,m);const v=t=>()=>{if(!this.getAssetPlayer(c))return;this.shouldPlay=!0;const i=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,t)};return f.once(te.MEDIA_ENDED,v(i)),f.once(te.PLAYOUT_LIMIT_REACHED,v(1/0)),f.on(te.ERROR,((t,s)=>{const n=this.getAssetPlayer(c);if(s.details!==ee.BUFFER_STALLED_ERROR)this.handleAssetItemError(s,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${s.error} ${e}`);else if(null!=n&&n.media){const t=n.currentTime,i=n.duration-t;t&&e.appendInPlace&&i/n.media.playbackRate<.5?(this.log(`Advancing buffer past end of asset ${c} ${e} at ${n.media.currentTime}`),m()):(this.warn(`Stalled at ${t} of ${t+i} in asset ${c} ${e}`),this.onTimeupdate(),this.checkBuffer(!0))}})),f.on(te.DESTROYING,(()=>{if(!this.getAssetPlayer(c))return;const t=new Error(`Asset player destroyed unexpectedly ${c}`),s={fatal:!0,type:J.OTHER_ERROR,details:ee.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(s,e,this.schedule.findEventIndex(e.identifier),i,t.message)})),this.hls.trigger(te.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:f}),f}clearInterstitial(e,t){e.assetList.forEach((e=>{this.clearAssetPlayer(e.identifier,t)})),e.reset()}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(-1!==i){this.log(`clearAssetPlayer "${e}" toSegment: ${t?Po(t):t}`);const s=this.playerQueue[i];this.transferMediaFromPlayer(s,t),this.playerQueue.splice(i,1),s.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,s,n){const{interstitial:r,assetItem:o,assetId:a}=e,l=r.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=o,d&&d.identifier===a||(d&&(this.clearAssetPlayer(d.identifier,i[s]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${e}`),this.hls.trigger(te.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:r,schedule:i.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var i,s;const{interstitial:n,assetItem:r,assetId:o}=e,a=this.schedule.findEventIndex(n.identifier),l=null==(i=this.schedule.items)?void 0:i[a];if(!l)return;this.setBufferingItem(l),this.bufferingAsset=r;const d=this.getBufferingPlayer();if(d===e)return;const c=n.appendInPlace;if(c&&!1===(null==d?void 0:d.interstitial.appendInPlace))return;const h=(null==d?void 0:d.tracks)||(null==(s=this.detachedData)?void 0:s.tracks)||this.requiredTracks;if(c&&r!==this.playingAsset){if(!e.tracks)return;if(h&&!Se(h,e.tracks)){const t=new Error(`Asset "${o}" SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),i={fatal:!0,type:J.OTHER_ERROR,details:ee.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},s=n.findAssetIndex(r);return void this.handleAssetItemError(i,n,a,s,t.message)}}this.transferMediaTo(e,t)}handleAssetItemError(e,t,i,s,n){if(e.details===ee.BUFFER_STALLED_ERROR)return;const r=t.assetList[s]||null;let o=null;if(r){const e=this.getAssetPlayerQueueIndex(r.identifier);o=this.playerQueue[e]||null}const a=this.schedule.items,l=ue({},e,{fatal:!1,errorAction:ai(!0),asset:r,assetListIndex:s,event:t,schedule:a,scheduleIndex:i,player:o});if(this.warn(`Asset item error: ${e.error}`),this.hls.trigger(te.INTERSTITIAL_ASSET_ERROR,l),!e.fatal)return;const d=new Error(n);r&&(this.playingAsset!==r&&this.clearAssetPlayer(r.identifier,null),r.error=d),t.assetList.some((e=>!e.error))?t.appendInPlace&&(t.error=d):t.error=d,this.primaryFallback(t)}primaryFallback(e){const t=e.timelineStart,i=this.effectivePlayingItem;if(this.updateSchedule(),i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${i?Po(i):""} error: ${e.error}`),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t));let s=this.timelinePos;-1===s&&(s=this.hls.startPosition);const n=this.updateItem(i,s);if(this.itemsMatch(i,n))this.clearInterstitial(e,null);else{const e=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(e)}}else this.checkStart()}onAssetListLoaded(e,t){var i;const s=t.event,n=s.identifier,r=t.assetListResponse.ASSETS;if(!this.schedule.hasEvent(n))return;const o=s.timelineStart,a=s.duration;let l=0;r.forEach(((e,t)=>{const i=parseFloat(e.DURATION);this.createAsset(s,t,l,o+l,i,e.URI),l+=i})),s.duration=l,this.log(`Loaded asset-list with duration: ${l} (was: ${a}) ${s}`);const d=this.waitingItem,c=(null==d?void 0:d.event.identifier)===n;this.updateSchedule();const h=null==(i=this.bufferingItem)?void 0:i.event;if(c){var u;const e=this.schedule.findEventIndex(n),t=null==(u=this.schedule.items)?void 0:u[e];if(t){if(!this.playingItem&&this.timelinePos>t.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==e)return s.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${s}`),void this.primaryFallback(s);this.setBufferingItem(t)}this.setSchedulePosition(e)}else if((null==h?void 0:h.identifier)===n&&h.appendInPlace){const e=s.assetList[0],t=this.getAssetPlayer(e.identifier),i=this.primaryMedia;e&&t&&i&&this.bufferAssetPlayer(t,i)}}onError(e,t){switch(t.details){case ee.ASSET_LIST_PARSING_ERROR:case ee.ASSET_LIST_LOAD_ERROR:case ee.ASSET_LIST_LOAD_TIMEOUT:{const e=t.interstitial;e&&this.primaryFallback(e);break}case ee.BUFFER_STALLED_ERROR:this.onTimeupdate(),this.checkBuffer(!0)}}}});function Fa(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(Fa):Object.keys(e).reduce(((t,i)=>(t[i]=Fa(e[i]),t)),{}):e}class Ua extends Ci{constructor(e,t){super("gap-controller",e.logger),this.hls=null,this.fragmentTracker=null,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var e;this.hls&&(this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(te.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(te.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(te.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(te.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(te.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(te.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(te.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;const i=this.media=t.media;Do(i,"playing",this.onMediaPlaying),Do(i,"waiting",this.onMediaWaiting),Do(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(No(i,"playing",this.onMediaPlaying),No(i,"waiting",this.onMediaWaiting),No(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(null==(e=this.media)||!e.readyState||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,s;const n=null==(i=this.hls)?void 0:i.config;if(!n)return;const{media:r,stalled:o}=this;if(!r)return;const{seeking:a}=r,l=this.seeking&&!a,d=!this.seeking&&a,c=r.paused&&!a||r.ended||0===r.playbackRate;if(this.seeking=a,e!==t)return t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!c&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(d||l)return void(l&&this.stallResolved(e));if(c)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&r.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(te.MEDIA_ENDED,{stalled:!1})));if(!Ii.getBuffered(r).length)return void(this.nudgeRetry=0);const h=Ii.bufferInfo(r,e,0),u=h.nextStart||0,f=this.fragmentTracker;if(a&&f&&this.hls){const t=$a(this.hls.inFlightFragments,e),i=h.len>2,s=!u||t||u-e>2&&!f.getPartialFragment(e);if(i||s)return;this.moved=!1}const p=null==(s=this.hls)?void 0:s.latestLevelDetails;if(!this.moved&&null!==this.stalled&&f){if(!(h.len>0||u))return;const t=Math.max(u,h.start||0)-e,i=null!=p&&p.live?2*p.targetduration:2,s=f.getPartialFragment(e);if(t>0&&(t<=i||s))return void(r.paused||this._trySkipBufferHole(s))}const g=n.detectStallWithCurrentTimeMs,m=self.performance.now(),v=this.waiting;if(null===o)return void(this.stalled=v>0&&m-v=g||v)&&this.hls){var E;if("ended"===(null==(E=this.mediaSource)?void 0:E.readyState)&&(null==p||!p.live)&&Math.abs(e-((null==p?void 0:p.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(te.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(h),!this.media||!this.hls)return}const y=Ii.bufferInfo(r,e,n.maxBufferHole);this._tryFixBufferStall(y,A)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(te.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&s&&s.length>1&&e>s.end(0)){const i=Ii.bufferedInfo(Ii.timeRangesToArray(this.buffered.audio),e,0);if(i.len>1&&t>=i.start){const i=Ii.timeRangesToArray(s),n=Ii.bufferedInfo(i,t,0).bufferedIndex;if(n>-1&&nn)&&r-s<1&&e-s<2){const i=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${s} -> ${r} buffered index: ${t}`);this.warn(i.message),this.media.currentTime+=1e-6;const n=this.fragmentTracker.getPartialFragment(e)||void 0,o=Ii.bufferInfo(this.media,e,0);this.hls.trigger(te.ERROR,{type:J.MEDIA_ERROR,details:ee.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:n,buffer:o.len,bufferInfo:o})}}}}}_tryFixBufferStall(e,t){var i,s;const{fragmentTracker:n,media:r}=this,o=null==(i=this.hls)?void 0:i.config;if(!r||!n||!o)return;const a=r.currentTime,l=null==(s=this.hls)?void 0:s.latestLevelDetails,d=n.getPartialFragment(a);if((d||null!=l&&l.live&&a1&&e.len>o.maxBufferHole||e.nextStart&&e.nextStart-a1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}_reportStall(e){const{hls:t,media:i,stallReported:s,stalled:n}=this;if(!s&&null!==n&&i&&t){this.stallReported=!0;const s=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Gt(e)})`);this.warn(s.message),t.trigger(te.ERROR,{type:J.MEDIA_ERROR,details:ee.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:s}=this,n=null==(t=this.hls)?void 0:t.config;if(!s||!i||!n)return 0;const r=s.currentTime,o=Ii.bufferInfo(s,r,0),a=r0&&o.len<1&&s.readyState<3,c=a-r;if(c>0&&(t||d)){if(c>n.maxBufferHole){let t=!1;if(0===r){const e=i.getAppendedFrag(0,oe);e&&a{const e=Ga();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Ha{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(te.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e.on(te.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(te.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(te.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(te.MANIFEST_LOADING,this.onManifestLoading,this),e.on(te.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(te.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(te.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(te.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(te.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(te.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(te.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(te.MANIFEST_LOADING,this.onManifestLoading,this),e.off(te.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(te.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(te.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(te.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(e,t){var i;this.media=t.media,!1===(null==(i=t.overrides)?void 0:i.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){const e=this.hls.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null,t.transferMedia||(this.id3Track&&(this.removeCues&&Ao(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;tKa&&(s=Ka),s-i<=0&&(s=i+.25);for(let e=0;ee.type===Rn.audioId3&&a:"video"===s?e=>e.type===Rn.emsg&&o:e=>e.type===Rn.audioId3&&a||e.type===Rn.emsg&&o,Eo(n,t,i,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{id3Track:i}=this,{dateRanges:s}=e,n=Object.keys(s);let r=this.dateRangeCuesAppended;var o;if(i&&t)if(null!=(o=i.cues)&&o.length){const e=Object.keys(r).filter((e=>!n.includes(e)));for(let t=e.length;t--;){const s=e[t],n=r[s].cues;delete r[s],Object.keys(n).forEach((e=>{try{const t=n[e];t.removeEventListener("enter",this.onEventCueEnter),i.removeCue(t)}catch(e){}}))}}else r=this.dateRangeCuesAppended={};const a=e.fragments[e.fragments.length-1];if(0===n.length||!X(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=Ga();for(let e=0;e{if(t!==i.id){const n=s[t];if(n.class===i.class&&n.startDate>i.startDate&&(!e||i.startDate.01&&(n.startTime=o,n.endTime=f);else if(l){let e=i.attr[s];Bi(s)&&(d=e,e=Uint8Array.from(d.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);const n=ja(l,o,f,{key:s,data:e},Rn.dateRange);n&&(n.id=t,this.id3Track.addCue(n),h[s]=n,this.hls.config.interstitialsController&&("X-ASSET-LIST"!==s&&"X-ASSET-URL"!==s||n.addEventListener("enter",this.onEventCueEnter)))}}r[t]={cues:h,dateRange:i,durationKnown:u}}var d,c}}class Ya{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:n}=this.config;if(!s||1===n||!t.live)return;const r=this.targetLatency;if(null===r)return;const o=i-r;if(o.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,n)),i=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20,s=Math.min(t,Math.max(1,i));this.changeMediaPlaybackRate(e,s)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(null===e||null===this.hls)return null;const{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:n,liveSyncDurationCount:r,lowLatencyMode:o}=this.config,a=this.hls.userConfig;let l=o&&i||t;(this._targetLatencyUpdated||a.liveSyncDuration||a.liveSyncDurationCount||0===l)&&(l=void 0!==n?n:r*s);const d=s;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;const i=this.levelDetails;if(null===i)return null;const s=i.edge,n=e-t-this.edgeStalled,r=s-i.totalduration,o=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(r,n),o)}get drift(){const e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;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.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(te.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(te.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(te.MANIFEST_LOADING,this.onManifestLoading,this),e.on(te.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(te.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(te.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(te.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(te.MANIFEST_LOADING,this.onManifestLoading,this),e.off(te.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(te.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===ee.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,s;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(s=this.targetLatency)?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class Wa extends Cr{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(te.MANIFEST_LOADING,this.onManifestLoading,this),e.on(te.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(te.LEVEL_LOADED,this.onLevelLoaded,this),e.on(te.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(te.FRAG_BUFFERED,this.onFragBuffered,this),e.on(te.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(te.MANIFEST_LOADING,this.onManifestLoading,this),e.off(te.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(te.LEVEL_LOADED,this.onLevelLoaded,this),e.off(te.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(te.FRAG_BUFFERED,this.onFragBuffered,this),e.off(te.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((e=>{e.loadError=0,e.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=[],n={},r={};let o=!1,a=!1,l=!1;t.levels.forEach((e=>{var t;const d=e.attrs;let{audioCodec:c,videoCodec:h}=e;c&&(e.audioCodec=c=Rt(c,i)||void 0),0===(null==(t=h)?void 0:t.indexOf("avc1"))&&(h=e.videoCodec=function(e){const t=e.split(",");for(let e=0;e2){let s=i.shift()+".";s+=parseInt(i.shift()).toString(16),s+=("000"+parseInt(i.shift()).toString(16)).slice(-4),t[e]=s}}return t.join(",")}(h));const{width:u,height:f,unknownCodecs:p}=e;let g=p?p.length:0;if(p)for(let t=g;t--;){const i=p[t];this.isAudioSupported(i)?(e.audioCodec=c=c?`${c},${i}`:i,g--,vt.audio[c.substring(0,4)]=2):this.isVideoSupported(i)&&(e.videoCodec=h=h?`${h},${i}`:i,g--,vt.video[h.substring(0,4)]=2)}if(o||(o=!(!u||!f)),a||(a=!!h),l||(l=!!c),g||c&&!this.isAudioSupported(c)||h&&!this.isVideoSupported(h))return void this.log(`Some or all CODECS not supported "${d.CODECS}"`);const{CODECS:m,"FRAME-RATE":v,"HDCP-LEVEL":A,"PATHWAY-ID":E,RESOLUTION:y,"VIDEO-RANGE":T}=d,b=`${E||"."}-${e.bitrate}-${y}-${v}-${m}-${T}-${A}`;if(n[b])if(n[b].uri===e.url||e.attrs["PATHWAY-ID"])n[b].addGroupId("audio",d.AUDIO),n[b].addGroupId("text",d.SUBTITLES);else{const t=r[b]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const i=this.createLevel(e);n[b]=i,s.push(i)}else{const t=this.createLevel(e);n[b]=t,r[b]=1,s.push(t)}})),this.filterAndSortMediaOptions(s,t,o,a,l)}createLevel(e){const t=new $t(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const e=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(e.message),t.supportedResult=Ot(e,[])}return t}isAudioSupported(e){return Et(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Et(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,s,n){let r=[],o=[],a=e;if((i||s)&&n&&(a=a.filter((({videoCodec:e,videoRange:t,width:i,height:s})=>{return(!!e||!(!i||!s))&&!!(n=t)&&Bt.indexOf(n)>-1;var n}))),0===a.length)return void Promise.resolve().then((()=>{if(this.hls){let e="no level with compatible codecs found in manifest",i=e;t.levels.length&&(i=`one or more CODECS in variant not supported: ${Gt(t.levels.map((e=>e.attrs.CODECS)).filter(((e,t,i)=>i.indexOf(e)===t)))}`,this.warn(i),e+=` (${i})`);const s=new Error(e);this.hls.trigger(te.ERROR,{type:J.MEDIA_ERROR,details:ee.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:s,reason:i})}}));t.audioTracks&&(r=t.audioTracks.filter((e=>!e.audioCodec||this.isAudioSupported(e.audioCodec))),za(r)),t.subtitles&&(o=t.subtitles,za(o));const l=a.slice(0);a.sort(((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Bt.indexOf(e.videoRange)-Bt.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const i=bt(e.videoCodec),s=bt(t.videoCodec);if(i!==s)return s-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const i=St(e.codecSet),s=St(t.codecSet);if(i!==s)return s-i}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));let d=l[0];if(this.steering&&(a=this.steering.filterParsedLevels(a),a.length!==l.length))for(let e=0;ei&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const h=n&&!s,u=this.hls.config,f=!(!u.audioStreamController||!u.audioTrackController),p={levels:a,audioTracks:r,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:s,altAudio:f&&!h&&r.some((e=>!!e.url))};this.hls.trigger(te.MANIFEST_PARSED,p)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const i=new Error("invalid level idx"),s=e<0;if(this.hls.trigger(te.ERROR,{type:J.OTHER_ERROR,details:ee.LEVEL_SWITCH_ERROR,level:e,fatal:s,error:i,reason:i.message}),s)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,r=t[e],o=r.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=r,i===e&&s&&n===o)return;this.log(`Switching to level ${e} (${r.height?r.height+"p ":""}${r.videoRange?r.videoRange+" ":""}${r.codecSet?r.codecSet+" ":""}@${r.bitrate})${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);const a={level:e,attrs:r.attrs,details:r.details,bitrate:r.bitrate,averageBitrate:r.averageBitrate,maxBitrate:r.maxBitrate,realBitrate:r.realBitrate,width:r.width,height:r.height,codecSet:r.codecSet,audioCodec:r.audioCodec,videoCodec:r.videoCodec,audioGroups:r.audioGroups,subtitleGroups:r.subtitleGroups,loaded:r.loaded,loadError:r.loadError,fragmentError:r.fragmentError,name:r.name,id:r.id,uri:r.uri,url:r.url,urlId:0,audioGroupIds:r.audioGroupIds,textGroupIds:r.textGroupIds};this.hls.trigger(te.LEVEL_SWITCHING,a);const l=r.details;if(!l||l.live){const e=this.switchParams(r.uri,null==s?void 0:s.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),i=e.filter((e=>-1!==t.indexOf(e)));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=i}}onError(e,t){!t.fatal&&t.context&&t.context.type===se&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===oe){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return;const i=this._levels[t.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var i;const{level:s,details:n}=t,r=t.levelInfo;var o;if(!r)return this.warn(`Invalid level index ${s}`),void(null!=(o=t.deliveryDirectives)&&o.skip&&(n.deltaUpdateFailed=!0));if(r===this.currentLevel||t.withoutMultiVariant){0===r.fragmentError&&(r.loadError=0);let e=r.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(s,t,e)}else null!=(i=t.deliveryDirectives)&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],r=e.details,o=null==r?void 0:r.age;this.log(`Loading level index ${s}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&r.live?" age "+o.toFixed(1)+(r.type?" "+r.type||0:""):""} ${i}`),this.hls.trigger(te.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const i=this._levels.filter(((t,i)=>i!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((e=>e.level=-1))),!1)));Ps(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(te.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(te.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function za(e){const t={};e.forEach((e=>{const i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++}))}function qa(){return self.SourceBuffer||self.WebKitSourceBuffer}function Xa(){if(!be())return!1;const e=qa();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class Qa extends qs{constructor(e,t,i){super(e,t,i,"stream-controller",oe),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const e=this.media,t=e?e.currentTime:null;if(null===t||!X(t))return;if(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t))return;const i=this.getFwdBufferInfoAtPos(e,t,oe,0);null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length at ${t} on "seeked" event ${i?i.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(te.MANIFEST_PARSED,this.onManifestParsed,this),e.on(te.LEVEL_LOADING,this.onLevelLoading,this),e.on(te.LEVEL_LOADED,this.onLevelLoaded,this),e.on(te.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(te.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(te.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(te.BUFFER_CREATED,this.onBufferCreated,this),e.on(te.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(te.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(te.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(te.MANIFEST_PARSED,this.onManifestParsed,this),e.off(te.LEVEL_LOADED,this.onLevelLoaded,this),e.off(te.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(te.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(te.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(te.BUFFER_CREATED,this.onBufferCreated,this),e.off(te.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(te.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(te.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=s.startLevel;-1===e&&(s.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=s.firstAutoLevel),s.nextLoadLevel=e,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=Fs,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=Bs}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case zs:{const{levels:e,level:t}=this,i=null==e?void 0:e[t],s=null==i?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=Fs;break}if(this.hls.nextLoadLevel!==this.level){this.state=Fs;break}break}case Vs:{var e;const t=self.performance.now(),i=this.retryDate;if(!i||t>=i||null!=(e=this.media)&&e.seeking){const{levels:e,level:t}=this,i=null==e?void 0:e[t];this.resetStartWhenNotLoaded(i||null),this.state=Fs}}}this.state===Fs&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(null===t||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const n=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==i||!i[n])return;const r=i[n],o=this.getMainFwdBufferInfo();if(null===o)return;const a=this.getLevelDetails();if(a&&this._streamEnded(o,a)){const e={};return 2===this.altAudio&&(e.type="video"),this.hls.trigger(te.BUFFER_EOS,e),void(this.state=Hs)}if(!this.buffering)return;e.loadLevel!==n&&-1===e.manualLevel&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;const l=r.details;if(!l||this.state===zs||this.waitForLive(r))return this.level=n,this.state=zs,void(this.startFragRequested=!1);const d=o.len,c=this.getMaxBufferLength(r.maxBitrate);if(d>=c)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:o.end;let u=this.getNextFragment(h,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&$e(u)&&this.fragmentTracker.getState(u)!==hi){var f;const e=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,t=l.fragments[e-1];t&&u.cc===t.cc&&(u=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,h)){if(!u.gap){const e=this.audioOnly&&!this.altAudio?xe:Be,t=(e===Be?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,oe)}u=this.getNextFragmentLoopLoading(u,l,o,oe,c)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,r,h))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);s===li||s===ci?$e(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,oe)}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(null!=t&&t.readyState){let i;const s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const n=this.getLevelDetails();if(null!=n&&n.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*n.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],s=this.fragLastKbps;i=s&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*s)+1:0}else i=0;const r=this.getBufferedFrag(t.currentTime+i);if(r){const e=this.followingBufferedFrag(r);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,i=e.duration,s=Math.max(r.end,t+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(s,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 Us:case $s:case Vs:case js:case Ks:this.state=Fs}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;Do(i,"playing",this.onMediaPlaying),Do(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:i}=this;i&&(No(i,"playing",this.onMediaPlaying),No(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(te.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;t.levels.forEach((e=>{const t=e.audioCodec;t&&(i=i||-1!==t.indexOf("mp4a.40.2"),s=s||-1!==t.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=i&&s&&!function(){var e;const t=qa();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),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!==Fs)return;const s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=zs)}onLevelLoaded(e,t){var i;const{levels:s,startFragRequested:n}=this,r=t.level,o=t.details,a=o.totalduration;if(!s)return void this.warn(`Levels were reset while loading level ${r}`);this.log(`Level ${r} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${a}`);const l=t.levelInfo,d=this.fragCurrent;!d||this.state!==$s&&this.state!==Vs||d.level!==t.level&&d.loader&&this.abortCurrentFrag();let c=0;if(o.live||null!=(i=l.details)&&i.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,l.details,null==(h=this.levelLastLoaded)?void 0:h.details)}if(l.details=o,this.levelLastLoaded=l,n||this.setStartPosition(o,c),this.hls.trigger(te.LEVEL_UPDATED,{details:o,level:r}),this.state===zs){if(this.waitForCdnTuneIn(o))return;this.state=Fs}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,n=this.getLoadPosition(),r=e.fragmentStart,o=e.edge,a=n>=r-t.maxFragLookUpTolerance&&n<=o;if(null!==s&&i.duration>s&&(n{var e;null==(e=this.hls)||e.trigger(te.AUDIO_TRACK_SWITCHED,t)})),void i.trigger(te.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(te.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=Xt(t.url,this.hls);if(i){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,n,r=!1;for(const e in i){const t=i[e];if("main"===t.id){if(n=e,s=t,"video"===e){const t=i[e];t&&(this.videoBuffer=t.buffer)}}else r=!0}r&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:s}=t,n=i.type===oe;if(n){if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Ks&&(this.state=Fs));const e=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),$e(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const r=this.media;r&&(!this._hasEnoughToStart&&Ii.getBuffered(r).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal)this.state=Ys;else switch(t.details){case ee.FRAG_GAP:case ee.FRAG_PARSING_ERROR:case ee.FRAG_DECRYPT_ERROR:case ee.FRAG_LOAD_ERROR:case ee.FRAG_LOAD_TIMEOUT:case ee.KEY_LOAD_ERROR:case ee.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(oe,t);break;case ee.LEVEL_LOAD_ERROR:case ee.LEVEL_LOAD_TIMEOUT:case ee.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==zs||(null==(i=t.context)?void 0:i.type)!==se||(this.state=Fs);break;case ee.BUFFER_ADD_CODEC_ERROR:case ee.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.resetLoadingState();break;case ee.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case ee.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=Fs,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==xe||!this.altAudio){const e=(t===Be?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,oe),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t0&&(a{const{hls:i}=this,s=null==e?void 0:e.frag;if(!s||this.fragContextChanged(s))return;t.fragmentError=0,this.state=Fs,this.startFragRequested=!1,this.bitrateTest=!1;const n=s.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),i.trigger(te.FRAG_LOADED,e),s.bitrateTest=!1}))}_handleTransmuxComplete(e){var t;const i=this.playlistType,{hls:s}=this,{remuxResult:n,chunkMeta:r}=e,o=this.getCurrentContext(r);if(!o)return void this.resetWhenMissingContext(r);const{frag:a,part:l,level:d}=o,{video:c,text:h,id3:u,initSegment:f}=n,{details:p}=d,g=this.altAudio?void 0:n.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=js,f){if(null!=f&&f.tracks){const e=a.initSegment||a;this._bufferInitSegment(d,f.tracks,e,r),s.trigger(te.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:f.tracks})}const e=f.initPTS,t=f.timescale;X(e)&&(this.initPTS[a.cc]={baseTime:e,timescale:t},s.trigger(te.INIT_PTS_FOUND,{frag:a,id:i,initPTS:e,timescale:t}))}if(c&&p){g&&"audiovideo"===c.type&&this.logMuxedErr(a);const e=p.fragments[a.sn-1-p.startSN],t=a.sn===p.startSN,i=!e||a.cc>e.cc;if(!1!==n.independent){const{startPTS:e,endPTS:s,startDTS:n,endDTS:o}=c;if(l)l.elementaryStreams[c.type]={startPTS:e,endPTS:s,startDTS:n,endDTS:o};else if(c.firstKeyFrame&&c.independent&&1===r.id&&!i&&(this.couldBacktrack=!0),c.dropped&&c.independent){const n=this.getMainFwdBufferInfo(),r=(n?n.end:this.getLoadPosition())+this.config.maxBufferHole,l=c.firstKeyFramePTS?c.firstKeyFramePTS:e;if(!t&&r2&&(a.gap=!0);a.setElementaryStreamInfo(c.type,e,s,n,o),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(c,a,l,r,t||i)}else{if(!t&&!i)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:i,endDTS:s}=g;l&&(l.elementaryStreams[xe]={startPTS:e,endPTS:t,startDTS:i,endDTS:s}),a.setElementaryStreamInfo(xe,e,t,i,s),this.bufferFragmentData(g,a,l,r)}if(p&&null!=u&&null!=(t=u.samples)&&t.length){const e={id:i,frag:a,details:p,samples:u.samples};s.trigger(te.FRAG_PARSING_METADATA,e)}if(p&&h){const e={id:i,frag:a,details:p,samples:h.samples};s.trigger(te.FRAG_PARSING_USERDATA,e)}}}logMuxedErr(e){this.warn(`${$e(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==js)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:n,video:r,audiovideo:o}=t;if(n){let i=Lt(n.codec,e.audioCodec);"mp4a"===i&&(i="mp4a.40.5");const s=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=n.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===s.indexOf("firefox")&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&-1!==s.indexOf("android")&&"audio/mpeg"!==n.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),e.audioCodec&&e.audioCodec!==i&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${i}"`),n.levelCodec=i,n.id=oe,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${i||""}/${e.audioCodec||""}/${n.codec}]`),delete t.audiovideo}if(r){r.levelCodec=e.videoCodec,r.id=oe;const i=r.codec;if(4===(null==i?void 0:i.length))switch(i){case"hvc1":case"hev1":r.codec="hvc1.1.6.L120.90";break;case"av01":r.codec="av01.0.04M.08";break;case"avc1":r.codec="avc1.42e01e"}this.log(`Init video buffer, container:${r.container}, codecs[level/parsed]=[${e.videoCodec||""}/${i}]${r.codec!==i?" parsed-corrected="+r.codec:""}${r.supplemental?" supplemental="+r.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const a=Object.keys(t);if(a.length){if(this.hls.trigger(te.BUFFER_CODECS,t),!this.hls)return;a.forEach((e=>{const n=t[e].initSegment;null!=n&&n.byteLength&&this.hls.trigger(te.BUFFER_APPENDING,{type:e,data:n,frag:i,part:null,chunkMeta:s,parent:i.type})}))}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,oe)}get maxBufferLength(){const{levels:e,level:t}=this,i=null==e?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Fs}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const i=e.currentTime;if(Ii.isBuffered(e,i)?t=this.getAppendedFrag(i):Ii.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,i=t.level;e&&t.sn===e.sn&&e.level===i||(this.fragPlaying=t,this.hls.trigger(te.FRAG_CHANGED,{frag:t}),e&&e.level===i||this.hls.trigger(te.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return X(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(X(t)){const e=this.getLevelDetails(),i=this.currentFrag||(e?Zt(null,e.fragments,t):null);if(i){const e=i.programDateTime;if(null!==e){const s=e+1e3*(t-i.start);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 Za{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!==(null==(t=s.context)?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=ee.KEY_LOAD_ERROR,i,s,n){return new _i({type:J.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:s})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:s}=e;for(let e=0;e{n.setKeyFormat(e)}));break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then((t=>this.loadInternal(e,t))):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const i=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,ee.KEY_LOAD_ERROR,i))}const r=n.uri;if(!r)return Promise.reject(this.createKeyLoadError(e,ee.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${r}"`)));let o=this.keyUriToKeyInfo[r];if(null!=(i=o)&&i.decryptdata.key)return n.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});var a;if(null!=(s=o)&&s.keyLoadPromise)switch(null==(a=o.mediaKeySessionContext)?void 0:a.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then((t=>(n.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:o})))}switch(o=this.keyUriToKeyInfo[r]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===n.keyFormat?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,ee.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const t=this.emeController.loadKey(i);if(t)return(e.keyLoadPromise=t.then((t=>(e.mediaKeySessionContext=t,i)))).catch((t=>{throw e.keyLoadPromise=null,t}))}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,s=new(0,i.loader)(i);return t.keyLoader=e.loader=s,e.keyLoadPromise=new Promise(((n,r)=>{const o={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},a=i.keyLoadPolicy.default,l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,t,i,s)=>{const{frag:o,keyInfo:a,url:l}=i;if(!o.decryptdata||a!==this.keyUriToKeyInfo[l])return r(this.createKeyLoadError(o,ee.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));a.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=null,a.loader=null,n({frag:o,keyInfo:a})},onError:(e,i,s,n)=>{this.resetLoader(i),r(this.createKeyLoadError(t,ee.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),s,pe({url:o.url,data:void 0},e)))},onTimeout:(e,i,s)=>{this.resetLoader(i),r(this.createKeyLoadError(t,ee.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:(e,i,s)=>{this.resetLoader(i),r(this.createKeyLoadError(t,ee.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};s.load(o,l,d)}))}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[s],n&&n.destroy()}}function Ja(e){const{type:t}=e;switch(t){case ne:return ae;case re:return le;default:return oe}}function el(e,t){let i=e.url;return void 0!==i&&0!==i.indexOf("data:")||(i=t.url),i}class tl{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(te.MANIFEST_LOADING,this.onManifestLoading,this),e.on(te.LEVEL_LOADING,this.onLevelLoading,this),e.on(te.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(te.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(te.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(te.MANIFEST_LOADING,this.onManifestLoading,this),e.off(te.LEVEL_LOADING,this.onLevelLoading,this),e.off(te.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(te.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(te.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,n=new(i||s)(t);return this.loaders[e.type]=n,n}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,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:s,pathwayId:n,url:r,deliveryDirectives:o,levelInfo:a}=t;this.load({id:i,level:s,pathwayId:n,responseType:"text",type:se,url:r,deliveryDirectives:o,levelOrTrack:a})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:r,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:ne,url:n,deliveryDirectives:r,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:r,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:re,url:n,deliveryDirectives:r,levelOrTrack:o})}onLevelsUpdated(e,t){const i=this.loaders[se];if(i){const e=i.context;e&&!t.levels.some((t=>t===e.levelOrTrack))&&(i.abort(),delete this.loaders[se])}}load(e){var t;const i=this.hls.config;let s,n=this.getInternalLoader(e);if(n){const t=this.hls.logger,i=n.context;if(i&&i.levelOrTrack===e.levelOrTrack&&(i.url===e.url||i.deliveryDirectives&&!e.deliveryDirectives))return void(i.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${i.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}if(s=e.type===ie?i.manifestLoadPolicy.default:ue({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),X(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===se&&null!==e.level?t=this.hls.levels[e.level].details:e.type===ne&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===re&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,i=t.targetduration;if(e&&i){const t=1e3*Math.max(3*e,.8*i);s=ue({},s,{maxTimeToFirstByteMs:Math.min(t,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,s.maxTimeToFirstByteMs)})}}}const r=s.errorRetry||s.timeoutRetry||{},o={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:r.maxNumRetry||0,retryDelay:r.retryDelayMs||0,maxRetryDelay:r.maxRetryDelayMs||0},a={onSuccess:(e,t,i,s)=>{const n=this.getInternalLoader(i);this.resetInternalLoader(i.type);const r=e.data;0===r.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),cs.isMediaPlaylist(r)||i.type!==ie?this.handleTrackOrLevelPlaylist(e,t,i,s||null,n):this.handleMasterPlaylist(e,t,i,s)):this.handleManifestParsingError(e,i,new Error("no EXTM3U delimiter"),s||null,t)},onError:(e,t,i,s)=>{this.handleNetworkError(t,i,!1,e,s)},onTimeout:(e,t,i)=>{this.handleNetworkError(t,i,!0,void 0,e)}};n.load(e,o,a)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,s){const n=this.hls,r=e.data,o=el(e,i),a=cs.parseMasterPlaylist(r,o);if(a.playlistParsingError)return void this.handleManifestParsingError(e,i,a.playlistParsingError,s,t);const{contentSteering:l,levels:d,sessionData:c,sessionKeys:h,startTimeOffset:u,variableList:f}=a;this.variableList=f;const{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":m}=cs.parseMasterPlaylistMedia(r,o,a);p.length&&(p.some((e=>!e.url))||!d[0].audioCodec||d[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new xi({}),bitrate:0,url:""}))),n.trigger(te.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:g,captions:m,contentSteering:l,url:o,stats:t,networkDetails:s,sessionData:c,sessionKeys:h,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(e,t,i,s,n){const r=this.hls,{id:o,level:a,type:l}=i,d=el(e,i),c=X(a)?a:X(o)?o:0,h=Ja(i),u=cs.parseLevelPlaylist(e.data,d,c,h,0,this.variableList);if(l===ie){const e={attrs:new xi({}),bitrate:0,details:u,name:"",url:d};u.requestScheduled=t.loading.start+Ls(u,0),r.trigger(te.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:d,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=u,this.handlePlaylistLoaded(u,e,t,i,s,n)}handleManifestParsingError(e,t,i,s,n){this.hls.trigger(te.ERROR,{type:J.NETWORK_ERROR,details:ee.MANIFEST_PARSING_ERROR,fatal:t.type===ie,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:n})}handleNetworkError(e,t,i=!1,s,n){let r=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===se?r+=`: ${e.level} id: ${e.id}`:e.type!==ne&&e.type!==re||(r+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(r);this.hls.logger.warn(`[playlist-loader]: ${r}`);let a=ee.UNKNOWN,l=!1;const d=this.getInternalLoader(e);switch(e.type){case ie:a=i?ee.MANIFEST_LOAD_TIMEOUT:ee.MANIFEST_LOAD_ERROR,l=!0;break;case se:a=i?ee.LEVEL_LOAD_TIMEOUT:ee.LEVEL_LOAD_ERROR,l=!1;break;case ne:a=i?ee.AUDIO_TRACK_LOAD_TIMEOUT:ee.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case re:a=i?ee.SUBTITLE_TRACK_LOAD_TIMEOUT:ee.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(e.type);const c={type:J.NETWORK_ERROR,details:a,fatal:l,url:e.url,loader:d,context:e,error:o,networkDetails:t,stats:n};if(s){const i=(null==t?void 0:t.url)||e.url;c.response=pe({url:i,data:void 0},s)}this.hls.trigger(te.ERROR,c)}handlePlaylistLoaded(e,t,i,s,n,r){const o=this.hls,{type:a,level:l,id:d,groupId:c,deliveryDirectives:h}=s,u=el(t,s),f=Ja(s),p="number"==typeof s.level&&f===oe?l:void 0;if(!e.fragments.length){const r=e.playlistParsingError=new Error("No Segments found in Playlist");return void o.trigger(te.ERROR,{type:J.NETWORK_ERROR,details:ee.LEVEL_EMPTY_ERROR,fatal:!1,url:u,error:r,reason:r.message,response:t,context:s,level:p,parent:f,networkDetails:n,stats:i})}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const g=e.playlistParsingError;if(g){if(this.hls.logger.warn(g),!o.config.ignorePlaylistParsingErrors)return void o.trigger(te.ERROR,{type:J.NETWORK_ERROR,details:ee.LEVEL_PARSING_ERROR,fatal:!1,url:u,error:g,reason:g.message,response:t,context:s,level:p,parent:f,networkDetails:n,stats:i});e.playlistParsingError=null}switch(e.live&&r&&(r.getCacheAge&&(e.ageHeader=r.getCacheAge()||0),r.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),a){case ie:case se:o.trigger(te.LEVEL_LOADED,{details:e,levelInfo:s.levelOrTrack||o.levels[0],level:p||0,id:d||0,stats:i,networkDetails:n,deliveryDirectives:h,withoutMultiVariant:a===ie});break;case ne:o.trigger(te.AUDIO_TRACK_LOADED,{details:e,track:s.levelOrTrack,id:d||0,groupId:c||"",stats:i,networkDetails:n,deliveryDirectives:h});break;case re:o.trigger(te.SUBTITLE_TRACK_LOADED,{details:e,track:s.levelOrTrack,id:d||0,groupId:c||"",stats:i,networkDetails:n,deliveryDirectives:h})}}}class il{static get version(){return sn}static isMSESupported(){return Xa()}static isSupported(){return function(){if(!Xa())return!1;const e=be();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((t=>e.isTypeSupported(Tt(t,"video"))))||["mp4a.40.2","fLaC"].some((t=>e.isTypeSupported(Tt(t,"audio")))))}()}static getMediaSource(){return be()}static get Events(){return te}static get MetadataSchema(){return Rn}static get ErrorTypes(){return J}static get ErrorDetails(){return ee}static get DefaultConfig(){return il.defaultConfig?il.defaultConfig:Ba}static set DefaultConfig(e){il.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new tn,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=function(e,t,i){const s=Ae();if("object"==typeof console&&!0===e||"object"==typeof e){const t=["debug","log","info","warn","error"];t.forEach((t=>{s[t]=Ee(t,e,i)}));try{s.log('Debug logs enabled for "Hls instance" in hls.js version 1.6.2')}catch(e){return Ae()}t.forEach((t=>{ye[t]=Ee(t,e)}))}else ue(ye,s);return s}(e.debug||!1,0,e.assetPlayerId),i=this.config=function(e,t,i){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=Fa(e),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const r=`${"level"===e?"playlist":e}LoadPolicy`,o=void 0===t[r],a=[];n.forEach((i=>{const n=`${e}Loading${i}`,l=t[n];if(void 0!==l&&o){a.push(n);const e=s[r].default;switch(t[r]={default:e},i){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&i.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${r}": ${Gt(t[r])}`)})),pe(pe({},s),t)}(il.DefaultConfig,e,t);this.userConfig=e,i.progressive&&function(e,t){const i=e.loader;i!==Oa&&i!==xa?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(e.loader=Oa,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}(i,t);const{abrController:s,bufferController:n,capLevelController:r,errorController:o,fpsController:a}=i,l=new o(this),d=this.abrController=new s(this),c=new ui(this),h=i.interstitialsController,u=h?this.interstitialsController=new h(this,il):null,f=this.bufferController=new n(this,c),p=this.capLevelController=new r(this),g=new a(this),m=new tl(this),v=i.contentSteeringController,A=v?new v(this):null,E=this.levelController=new Wa(this,A),y=new Ha(this),T=new Za(this.config),b=this.streamController=new Qa(this,c,T),S=this.gapController=new Ua(this,c);p.setStreamController(b),g.setStreamController(b);const _=[m,E,b];u&&_.splice(1,0,u),A&&_.splice(1,0,A),this.networkControllers=_;const C=[d,f,S,p,g,y,c];this.audioTrackController=this.createController(i.audioTrackController,_);const R=i.audioStreamController;R&&_.push(this.audioStreamController=new R(this,c,T)),this.subtitleTrackController=this.createController(i.subtitleTrackController,_);const L=i.subtitleStreamController;L&&_.push(this.subtititleStreamController=new L(this,c,T)),this.createController(i.timelineController,C),T.emeController=this.emeController=this.createController(i.emeController,C),this.cmcdController=this.createController(i.cmcdController,C),this.latencyController=this.createController(Ya,C),this.coreComponents=C,_.push(l);const I=l.onErrorOut;"function"==typeof I&&this.on(te.ERROR,I,l),this.on(te.MANIFEST_LOADED,m.onManifestLoaded,m)}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(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const i=e===te.ERROR;this.trigger(te.ERROR,{type:J.OTHER_ERROR,details:ee.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(te.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((e=>e.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((e=>e.destroy())),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(te.ERROR,{type:J.OTHER_ERROR,details:ee.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,i=t?e.media:e,s=t?e:{media:i};this._media=i,this.trigger(te.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(te.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(te.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,s=this._url=Ne.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(te.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", ":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i{e.resumeBuffering&&e.resumeBuffering()})))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((e=>{e.pauseBuffering&&e.pauseBuffering()})))}get inFlightFragments(){const e={[oe]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[ae]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[le]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const i=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?i:3&i|8).toString(16)}))}}}()),e}get levels(){return this.levelController.levels||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){(function(e){return xt.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}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=t)return s;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let s;if(s=-1===t&&null!=e&&e.length?e.length-1:t,i)for(let t=s;t--;){const s=e[t].attrs["HDCP-LEVEL"];if(s&&s<=i)return t}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return Mt(e,Kt(t),navigator.mediaCapabilities)}}il.defaultConfig=void 0;var sl=n(8220),nl=n.n(sl),rl=n(5858),ol=n.n(rl),al=n(9371),ll=n(8081),dl=n(6121),cl=n(997);const hl=async(e={})=>{var{muted:t}=e,i=function(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);nnew Promise((t=>al.Aq.canAutoPlayMedia(t,Object.assign({inline:!0,muted:e},i)))))));return r?"unmuted":n?"muted":"notAllowed"},ul=e=>null!=e.audioTracks?e.audioTracks.length>0:null!=e.mozHasAudio?!0===e.mozHasAudio:null!=e.webkitAudioDecodedByteCount?e.webkitAudioDecodedByteCount>0:void 0;var fl=n(6119);class pl extends al.iJ{get name(){return"Core"}get attributes(){return{class:"eagleplayer-container eagleplayer-loader",style:"width: 100%",tabindex:"9999","data-player":""}}get mediaControl(){return this.getPlugin("mediaControl")||this.dummyMediaControl}get i18n(){return this.getPlugin("strings")||{t:e=>e}}get activePlaybackEl(){return this.activePlayback?this.activePlayback.$el?this.activePlayback.$el.get(0):this.activePlayback.el:null}constructor(e,t){super(e),this.loading=!1,this.handleVolumeChange=e=>{const t=e.target.muted?0:100*e.target.volume;this.activeContainer.volume!==t&&this.activeContainer.setVolume(t)},this.handleBeginFullscreen=()=>{this.trigger(dl.s.CORE_FULLSCREEN,!0),this.updateSize()},this.handleEndFullscreen=()=>{this.trigger(dl.s.CORE_FULLSCREEN,!1),this.updateSize()},t&&(this.optionsLoader=t)}resize(e){this.el.style.width="100%",super.resize(e)}renderContainers(){this.containers.forEach((e=>this.el.prepend(e.render().el)))}setupContainers(e){var t;if(super.setupContainers(e),al.Pw.isiOS){const e=null===(t=this.activePlayback)||void 0===t?void 0:t.el;e&&(e.addEventListener("volumechange",this.handleVolumeChange),e.addEventListener("webkitbeginfullscreen",this.handleBeginFullscreen),e.addEventListener("webkitendfullscreen",this.handleEndFullscreen))}}removeContainer(e){if(al.Pw.isiOS){const e=this.activePlayback.el;e.removeEventListener("volumechange",this.handleVolumeChange),e.removeEventListener("webkitbeginfullscreen",this.handleBeginFullscreen),e.removeEventListener("webkitendfullscreen",this.handleEndFullscreen)}super.removeContainer(e)}async reload(e){var t,i;this.loading||(this.loading=!0,await(null===(i=(t=this.options).reload)||void 0===i?void 0:i.call(t,e)),this.loading=!1)}createContainerFactory(e){if(e.loader){const t=al.$;this.defer=t.Deferred(),this.defer.promise(this),this.containerFactory=new al.o2(e,e.loader,this.i18n,this.playerError)}}stopContainersAndPlugins(){this.disableResizeObserver(),this.containers.forEach((e=>e.destroy())),this.plugins.forEach((e=>e.destroy())),this.stopListening(),this.plugins=[],this.containers=[],this.ready=!1}replace(e){this._options=Object.assign({},e)}}var gl=n(5705),ml=n(6243),vl=n(5166),Al=n(2591);const{now:El,listContainsIgnoreCase:yl}=al.Aq;al.sV.register("PLAYBACK_FRAGMENT_CHANGED"),al.sV.register("PLAYBACK_FRAGMENT_PARSING_METADATA");class Tl extends al.ab{get name(){return"hls"}get supportedVersion(){return{min:"0.5.0"}}get levels(){return this._levels||[]}get currentLevel(){return null===this._currentLevel||void 0===this._currentLevel?-1:this._currentLevel}get isReady(){return this._isReadyState}set currentLevel(e){this._currentLevel=e,this.trigger(al.sV.PLAYBACK_LEVEL_SWITCH_START),this.options.playback.hlsUseNextLevel?this._hls.nextLevel=this._currentLevel:this._hls.currentLevel=this._currentLevel}get latency(){return this._hls.latency}get liveSyncPosition(){return this._hls.liveSyncPosition}get currentProgramDateTime(){return this._hls.playingDate}get _startTime(){return this._playbackType===al.YZ.LIVE&&"EVENT"!==this._playlistType?this._extrapolatedStartTime:this._playableRegionStartTime}get _now(){return El()}get _extrapolatedStartTime(){if(!this._localStartTimeCorrelation)return this._playableRegionStartTime;let e=this._localStartTimeCorrelation,t=this._now-e.local,i=(e.remote+t)/1e3;return Math.min(i,this._playableRegionStartTime+this._extrapolatedWindowDuration)}get _extrapolatedEndTime(){let e=this._playableRegionStartTime+this._playableRegionDuration;if(!this._localEndTimeCorrelation)return e;const t=this._localEndTimeCorrelation,i=this._now-t.local,s=(t.remote+i)/1e3;return Math.max(e-this._extrapolatedWindowDuration,Math.min(s,e))}get _duration(){return this._extrapolatedEndTime-this._startTime}get _extrapolatedWindowDuration(){return null===this._segmentTargetDuration?0:this._extrapolatedWindowNumSegments*this._segmentTargetDuration}get bandwidthEstimate(){return this._hls&&this._hls.bandwidthEstimate}get defaultOptions(){return{preload:!0}}get customListeners(){return this.options.hlsPlayback&&this.options.hlsPlayback.customListeners||[]}get sourceMedia(){return this.options.src}get currentTimestamp(){return this._currentFragment?(this._currentFragment.programDateTime+1e3*(this.el.currentTime-this._currentFragment.start))/1e3:null}static get HLSJS(){return il}constructor(...e){super(...e),this.options.hlsPlayback=Object.assign(Object.assign({},this.defaultOptions),this.options.hlsPlayback),this._timeUpdateThrottleDelay=200,this._timeUpdateFiringRate=.2,this._durationChangeMinOffset=.5,this._setInitialState()}_setInitialState(){this._minDvrSize=void 0===this.options.hlsMinimumDvrSize?60:this.options.hlsMinimumDvrSize,this._extrapolatedWindowNumSegments=this.options.playback&&void 0!==this.options.playback.extrapolatedWindowNumSegments?this.options.playback.extrapolatedWindowNumSegments:2,this._playbackType=al.YZ.VOD,this._lastTimeUpdate={current:0,total:0,firstFragDateTime:0},this._lastTimeUpdateFiredTime=0,this._lastDuration=null,this._playableRegionStartTime=0,this._localStartTimeCorrelation=null,this._localEndTimeCorrelation=null,this._playableRegionDuration=0,this._programDateTime=0,this._durationExcludesAfterLiveSyncPoint=!1,this._segmentTargetDuration=null,this._playlistType=null,this._recoverAttemptsRemaining=this.options.hlsRecoverAttempts||16}_setup(){this._destroyHLSInstance(),this._createHLSInstance(),this._listenHLSEvents(),this._attachHLSMedia()}_destroyHLSInstance(){this._hls&&(this._manifestLoading=!1,this._ccIsSetup=!1,this._ccTracksUpdated=!1,this._setInitialState(),this._hls.destroy(),this._hls=null)}_createHLSInstance(){const e=Object.assign({},this.options.playback.hlsjsConfig);this._hls=new il(e)}_attachHLSMedia(){this._hls&&this._hls.attachMedia(this.el)}_listenHLSEvents(){this._hls&&(this._hls.once(il.Events.MEDIA_ATTACHED,(()=>{this.options.hlsPlayback.preload&&this._hls.loadSource(this.options.src)})),this._hls.on(il.Events.MANIFEST_LOADING,(()=>this._manifestLoading=!0)),this._hls.on(il.Events.LEVEL_LOADED,((e,t)=>this._updatePlaybackType(e,t))),this._hls.on(il.Events.LEVEL_UPDATED,((e,t)=>this._onLevelUpdated(e,t))),this._hls.on(il.Events.LEVEL_SWITCHED,((e,t)=>this._onLevelSwitch(e,t))),this._hls.on(il.Events.FRAG_CHANGED,((e,t)=>this._onFragmentChanged(e,t))),this._hls.on(il.Events.FRAG_LOADED,((e,t)=>this._onFragmentLoaded(e,t))),this._hls.on(il.Events.FRAG_BUFFERED,((e,t)=>this._onFragmentBuffered(e,t))),this._hls.on(il.Events.FRAG_PARSING_METADATA,((e,t)=>this._onFragmentParsingMetadata(e,t))),this._hls.on(il.Events.ERROR,((e,t)=>this._onHLSJSError(e,t))),this._hls.on(il.Events.SUBTITLE_TRACK_LOADED,((e,t)=>this._onSubtitleLoaded(e,t))),this._hls.on(il.Events.SUBTITLE_TRACKS_UPDATED,(()=>this._ccTracksUpdated=!0)),this.bindCustomListeners())}bindCustomListeners(){this.customListeners.forEach((e=>{const t=e.eventName,i=e.once?"once":"on";t&&this._hls[`${i}`](t,e.callback)}))}unbindCustomListeners(){this.customListeners.forEach((e=>{const t=e.eventName;t&&this._hls.off(t,e.callback)}))}_onFragmentParsingMetadata(e,t){this.trigger(al.sV.Custom.PLAYBACK_FRAGMENT_PARSING_METADATA,{evt:e,data:t})}render(){return this._ready(),super.render()}_ready(){this._isReadyState||(!this._hls&&this._setup(),this._isReadyState=!0,this.trigger(al.sV.PLAYBACK_READY,this.name))}_recover(e,t,i){if(this._recoveredDecodingError)if(this._recoveredAudioCodecError){al.tG.error("hlsjs: failed to recover",{evt:e,data:t}),i.level=al.Mk.Levels.FATAL;const s=this.createError(i);this.trigger(al.sV.PLAYBACK_ERROR,s),this.stop()}else this._recoveredAudioCodecError=!0,this._hls.swapAudioCodec(),this._hls.recoverMediaError(),this.play();else this._recoveredDecodingError=!0,this._hls.recoverMediaError(),this.play()}_setupSrc(e){}_startTimeUpdateTimer(){this._timeUpdateTimer||(this._timeUpdateTimer=setInterval((()=>{this._onDurationChange(),this._onTimeUpdate()}),100))}_stopTimeUpdateTimer(){this._timeUpdateTimer&&(clearInterval(this._timeUpdateTimer),this._timeUpdateTimer=null)}getProgramDateTime(){return this._programDateTime}getDuration(){return this._duration}getCurrentTime(){return Math.max(0,this.el.currentTime-this._startTime)}getStartTimeOffset(){return this._startTime}seekPercentage(e){const t=e>0?this._duration*(e/100):this._duration;this.seek(t)}seek(e){e<0&&(al.tG.warn("Attempt to seek to a negative time. Resetting to live point. Use seekToLivePoint() to seek to the live point."),e=this.getDuration()),e+=this._startTime,this.el.currentTime=e}seekToLivePoint(){this.seek(this.getDuration())}_updateSettings(){this._playbackType===al.YZ.VOD?this.settings.left=["playpause","position","duration"]:this.dvrEnabled?this.settings.left=["playpause"]:this.settings.left=["playstop"],this.settings.seekEnabled=this.isSeekEnabled(),this.trigger(al.sV.PLAYBACK_SETTINGSUPDATE)}_onHLSJSError(e,t){const i={code:`${t.type}_${t.details}`,description:`${this.name} error: type: ${t.type}, details: ${t.details}`,raw:t};let s;if(t.response&&(i.description+=`, response: ${JSON.stringify(t.response)}`),t.fatal)if(this._recoverAttemptsRemaining>0)switch(this._recoverAttemptsRemaining-=1,t.type){case il.ErrorTypes.NETWORK_ERROR:switch(t.details){case il.ErrorDetails.MANIFEST_LOAD_ERROR:case il.ErrorDetails.MANIFEST_LOAD_TIMEOUT:case il.ErrorDetails.MANIFEST_PARSING_ERROR:case il.ErrorDetails.LEVEL_LOAD_ERROR:case il.ErrorDetails.LEVEL_LOAD_TIMEOUT:al.tG.error("hlsjs: unrecoverable network fatal error.",{evt:e,data:t}),s=this.createError(i),this.trigger(al.sV.PLAYBACK_ERROR,s),this.stop();break;default:al.tG.warn("hlsjs: trying to recover from network error.",{evt:e,data:t}),i.level=al.Mk.Levels.WARN,this._hls.startLoad()}break;case il.ErrorTypes.MEDIA_ERROR:al.tG.warn("hlsjs: trying to recover from media error.",{evt:e,data:t}),i.level=al.Mk.Levels.WARN,this._recover(e,t,i);break;default:al.tG.error("hlsjs: could not recover from error.",{evt:e,data:t}),s=this.createError(i),this.trigger(al.sV.PLAYBACK_ERROR,s),this.stop()}else al.tG.error("hlsjs: could not recover from error after maximum number of attempts.",{evt:e,data:t}),s=this.createError(i),this.trigger(al.sV.PLAYBACK_ERROR,s),this.stop();else{if(this.options.playback.triggerFatalErrorOnResourceDenied&&this._keyIsDenied(t))return al.tG.error("hlsjs: could not load decrypt key.",{evt:e,data:t}),s=this.createError(i),this.trigger(al.sV.PLAYBACK_ERROR,s),void this.stop();i.level=al.Mk.Levels.WARN,al.tG.warn("hlsjs: non-fatal error occurred",{evt:e,data:t})}}_keyIsDenied(e){return e.type===il.ErrorTypes.NETWORK_ERROR&&e.details===il.ErrorDetails.KEY_LOAD_ERROR&&e.response&&e.response.code>=400}_onTimeUpdate(){const e={current:this.getCurrentTime(),total:this.getDuration(),firstFragDateTime:this.getProgramDateTime()};this._shouldThrottleTimeUpdate(e)||(this._lastTimeUpdate=e,this._lastTimeUpdateFiredTime=this._now,this.trigger(al.sV.PLAYBACK_TIMEUPDATE,e,this.name))}_shouldThrottleTimeUpdate(e){const t=Math.abs(e.current-this._lastTimeUpdate.current)=e[i].start&&this.el.currentTime<=e[i].end&&(t=i);const i={start:e[t].start,current:e[t].end,total:this.getDuration()};this.trigger(al.sV.PLAYBACK_PROGRESS,i,e)}load(e){this._stopTimeUpdateTimer(),this.options.src=e,this._setup()}play(){!this._hls&&this._setup(),!this._manifestLoading&&!this.options.hlsPlayback.preload&&this._hls.loadSource(this.options.src),super.play(),this._startTimeUpdateTimer()}pause(){this._hls&&this.el.pause()}stop(){this._stopTimeUpdateTimer(),this._hls&&super.stop(),this._destroyHLSInstance()}destroy(){this._stopTimeUpdateTimer(),this._destroyHLSInstance(),super.destroy()}_updatePlaybackType(e,t){this._playbackType=t.details.live?al.YZ.LIVE:al.YZ.VOD,this._onLevelUpdated(e,t),this._ccTracksUpdated&&this._playbackType===al.YZ.LIVE&&this.hasClosedCaptionsTracks&&this._onSubtitleLoaded()}_fillLevels(){this._levels=this._hls.levels.map(((e,t)=>({id:t,level:e,label:e.bitrate/1e3+"Kbps"}))),this.trigger(al.sV.PLAYBACK_LEVELS_AVAILABLE,this._levels)}_onLevelUpdated(e,t){this._segmentTargetDuration=t.details.targetduration,this._playlistType=t.details.type||null;let i=!1,s=!1,n=t.details.fragments,r=this._playableRegionStartTime,o=this._playableRegionDuration;if(0===n.length)return;if(n[0].rawProgramDateTime&&(this._programDateTime=n[0].rawProgramDateTime),this._playableRegionStartTime!==n[0].start&&(i=!0,this._playableRegionStartTime=n[0].start),i)if(this._localStartTimeCorrelation){let e=this._localStartTimeCorrelation,t=this._now-e.local,i=(e.remote+t)/1e3;ir+this._extrapolatedWindowDuration&&(this._localStartTimeCorrelation={local:this._now,remote:1e3*Math.max(n[0].start,r+this._extrapolatedWindowDuration)})}else this._localStartTimeCorrelation={local:this._now,remote:1e3*(n[0].start+this._extrapolatedWindowDuration/2)};let a=t.details.totalduration;if(this._playbackType===al.YZ.LIVE){let e=t.details.targetduration*((this.options.playback.hlsjsConfig||{}).liveSyncDurationCount||il.DefaultConfig.liveSyncDurationCount);e<=a?(a-=e,this._durationExcludesAfterLiveSyncPoint=!0):this._durationExcludesAfterLiveSyncPoint=!1}a!==this._playableRegionDuration&&(s=!0,this._playableRegionDuration=a);let l=n[0].start+a,d=r+o;if(l!==d)if(this._localEndTimeCorrelation){let e=this._localEndTimeCorrelation,t=this._now-e.local,i=(e.remote+t)/1e3;i>l?this._localEndTimeCorrelation={local:this._now,remote:1e3*l}:id&&(this._localEndTimeCorrelation={local:this._now,remote:1e3*d})}else this._localEndTimeCorrelation={local:this._now,remote:1e3*l};s&&this._onDurationChange(),i&&this._onProgress()}_onFragmentChanged(e,t){this._currentFragment=t.frag,this.trigger(al.sV.Custom.PLAYBACK_FRAGMENT_CHANGED,t)}_onFragmentLoaded(e,t){this.trigger(al.sV.PLAYBACK_FRAGMENT_LOADED,t)}_onFragmentBuffered(e,t){this.trigger(al.sV.PLAYBACK_FRAGMENT_BUFFERED,t)}_onSubtitleLoaded(){if(!this._ccIsSetup){this.trigger(al.sV.PLAYBACK_SUBTITLE_AVAILABLE);const e=this._playbackType===al.YZ.LIVE?-1:this.closedCaptionsTrackId;this.closedCaptionsTrackId=e,this._ccIsSetup=!0}}_onLevelSwitch(e,t){this.levels.length||this._fillLevels(),this.trigger(al.sV.PLAYBACK_LEVEL_SWITCH_END),this.trigger(al.sV.PLAYBACK_LEVEL_SWITCH,t);let i=this._hls.levels[t.level];i&&(this.highDefinition=i.height>=720||i.bitrate/1e3>=2e3,this.trigger(al.sV.PLAYBACK_HIGHDEFINITIONUPDATE,this.highDefinition),this.trigger(al.sV.PLAYBACK_BITRATE,{height:i.height,width:i.width,bandwidth:i.bitrate,bitrate:i.bitrate,level:t.level}))}get dvrEnabled(){return this._durationExcludesAfterLiveSyncPoint&&this._duration>=this._minDvrSize&&this.getPlaybackType()===al.YZ.LIVE}getPlaybackType(){return this._playbackType}isSeekEnabled(){return this._playbackType===al.YZ.VOD||this.dvrEnabled}}Tl.canPlay=function(e,t){const i=e.split("?")[0].match(/.*\.(.*)$/)||[],s=i.length>1&&"m3u8"===i[1].toLowerCase()||yl(t,["application/vnd.apple.mpegurl","application/x-mpegURL"]);return!(!il.isSupported()||!s)};var bl=n(7546);class Sl extends Tl{constructor(){super(...arguments),this.playing=!1}get hasAudio(){return this._hasAudio}set hasAudio(e){this._hasAudio=e}static canPlay(e,t){const i=e.split("?")[0].match(/.*\.(.*)$/)||[],s=i.length>1&&"m3u8"===i[1].toLowerCase()||(r=["application/vnd.apple.mpegurl","application/x-mpegURL"],void 0!==(n=t)&&void 0!==r&&r.filter((e=>n.toLowerCase()===e.toLowerCase())).length>0);var n,r;return!(!il.isSupported()&&!bl.Q_||!s)}get shouldLimitBuffering(){const{currentTime:e,duration:t}=this.el;return this.getPlaybackType()===al.YZ.VOD&&e+30super.play()),0),this.trigger(dl.s.PLAYBACK_PLAY_INTENT),this.checkBuffering(!0)}pause(){this.clearPlayTimeout(),super.pause(),this.checkBuffering(!1)}stop(){this.clearPlayTimeout(),super.stop(),this.checkBuffering(!1)}seek(e){super.seek(e),this.checkBuffering()}configure(e){this.clearPlayTimeout(),super.configure(e)}destroy(){this.clearPlayTimeout(),super.destroy()}}Sl.bufferingEnabled=!0;var _l=n(5072),Cl=n.n(_l),Rl=n(7825),Ll=n.n(Rl),Il=n(7659),kl=n.n(Il),wl=n(5056),Pl=n.n(wl),Ol=n(540),Dl=n.n(Ol),Nl=n(1113),Ml=n.n(Nl),xl=n(242),Bl={};Bl.styleTagTransform=Ml(),Bl.setAttributes=Pl(),Bl.insert=kl().bind(null,"head"),Bl.domAPI=Ll(),Bl.insertStyleElement=Dl(),Cl()(xl.A,Bl);const Fl=xl.A&&xl.A.locals?xl.A.locals:void 0,Ul=`\n
<%- message %>
\n<% if (canReload) { %>\n
\n \n \n \n Обновить\n
\n<% } %>\n<% if (hasSuggest) { %>\n
\n Показать рекомендации\n
\n<% } %>\n`;class $l extends al.YZ{static canPlay(){return!0}get name(){return"no_op"}get supportedVersion(){return{min:"0.5.0"}}get template(){return(0,al.vs)(Ul)}get attributes(){return{class:Fl.noop}}get events(){return{"click [data-noop-reload]":"reload","click [data-noop-hide]":"hide"}}reload(){const{id:e,reload:t}=this.options;e&&t({id:e})}hide(){this.$el.hide()}render(){const{handledLiveErrorCode:e,playbackNotSupportedMessage:t,playbackNotSupportedCanReload:i,sources:s}=this.options;return e||this.$el.html(this.template({message:t||this.i18n.t("playback_not_supported"),hasSuggest:!!(null==s?void 0:s.includes("not_found_fallback")),canReload:i})),this.$el.toggle(!e),this.trigger(dl.s.PLAYBACK_READY,this.name),this}}class Vl extends al.ab{get hasAudio(){return this._hasAudio}set hasAudio(e){this._hasAudio=e}isSeekEnabled(){const e=this.getDuration();return isFinite(e)||this.dvrEnabled}_onLoadedData(e){var t;super._onLoadedData(e),null!==(t=this.hasAudio)&&void 0!==t||(this.hasAudio=ul(this.el)),this.trigger(dl.s.PLAYBACK_LOADEDDATA)}clearPlayTimeout(){clearTimeout(this.playTimeout)}play(){this.playTimeout=window.setTimeout((()=>super.play()),0),this.trigger(dl.s.PLAYBACK_PLAY_INTENT)}pause(){this.clearPlayTimeout(),super.pause()}stop(){this.clearPlayTimeout(),super.stop()}configure(e){this.clearPlayTimeout(),super.configure(e)}destroy(){this.clearPlayTimeout(),super.destroy()}}var Gl=n(1978),jl=n(8522),Kl=n(9749);const Hl=[gl.dZ,gl.N6,ml.Poster,vl.Viewport,Al.EventsReport,Gl.Docking,jl.Mediascope,Kl.Prometheus],Yl=[Vl,Sl],Wl=[$l,...al.Pw.isiOS||al.Pw.isSafari?Yl.reverse():Yl];Hl.forEach((e=>{al.aH.registerPlugin(e)})),Wl.forEach((e=>{al.aH.registerPlayback(e)}));class zl extends al.Ut{constructor(){super(...arguments),this.configure=async e=>{var t,i,s,n,r,o;if(!this.core)return;const a=null===(t=this.core)||void 0===t?void 0:t.getPlugin("multiplayer");if(e.id){const{registeredPlugins:e,registeredPlaybacks:t}=al.aH;this.loader.corePlugins=this.loader.corePlugins.filter((t=>~Object.keys(e.core).map((t=>e.core[t])).indexOf(t))),this.loader.containerPlugins=this.loader.containerPlugins.filter((t=>~Object.keys(e.container).map((t=>e.container[t])).indexOf(t))),this.loader.playbackPlugins=this.loader.playbackPlugins.filter((e=>~t.indexOf(e))),null===(i=this.core)||void 0===i||i.stopContainersAndPlugins()}await this.optionsLoader.load(e),this._options=Object.assign({},this.optionsLoader.options),this.options.reload=this.configure,this.options.loader=this.loader,this.options.disableCanAutoPlay=!0;const l=this.options,{sources:d}=l,c=function(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);n{this.listenToOnce(this.core,dl.s.CORE_RESIZE,e)}))}}get loader(){return this.player.loader}get optionsLoader(){return this.player.optionsLoader}create(){var e;return this.options.reload=this.configure,this.options.loader=this.loader,this.core=new pl(this.options,this.optionsLoader),null===(e=this.core)||void 0===e||e.createContainerFactory(this.options),this.core}}var ql=n(7193),Xl=n.n(ql),Ql=n(7083),Zl=n.n(Ql),Jl=n(2136);const ed=JSON.parse('{"unknown_error":"Video cannot be played now","video_not_found":"Video not found","video_publish_finish":"Publishing of video finished","access_denied":"Access to this video is denied in your country or on this website","geo_access_denied":"The video you requested cannot be played in your country. Sorry for the inconvenience.","warning_proxy_anon":"If you use traffic boosters, proxy servers or anonymizers please consider turning them off before viewing this content","access_restricted":"You cannot watch this video","video_processing":"Video is now processing","announce":"Broadcasting will start on {time}","no_broadcast":"No broadcast","no_signal":"No signal","no_stream":"No stream","no_connection":"Server connection terminated. Please check network settings. If you are using firewall or antivirus software then disable it.","secure_link_fail":"The link is no longer valid. Try reload the page.","watch_next":"Watch next","share":"Share","share_copy":"Copy","share_copied":"Copied","share_link":"URL","share_copy_link":"Copy URL","share_link_copied":"URL copied","share_code":"Code","share_copy_code":"Copy code","share_code_copied":"Code copied","ai_ad_hide":"Hide products","ai_ad_show":"Show products","ai_ad_buy":"Buy","ai_ad_note":"Advertisement. Advertiser: ООО «МАРКЕТПЛЕЙС»","suggest":"You may also like","replay":"Play again","advertisement":"Advertisement","advertisement_link":"More details","advertisement_after":"After advertisement","advertisement_skip":"Skip","advertisement_skip_timer":"Skip:","advertisement_watch":"Watch","advertisement_watch_timer":"Watch:","advertisement_block":"Advertisement","advertisement_block_of":"of","advertisement_block_number":"Advertisement #","advertisement_starting_in":"Advertisement starting in:","live":"Live","live_no_signal":"No signal","live_finished":"Broadcast ended","live_back_to":"Back to live","complaint":"Report","settings":"Settings","quality":"Quality","quality_auto":"Auto","speed":"Speed","speed_normal":"Normal","subtitles":"Subtitles","subtitles_off":"Off","ru":"Russian","en":"English","es":"Spanish","fr":"French","de":"Deutsch","ja":"Japanese","it":"Italian","ko":"Korean","zh":"Chinese","pt":"Portuguese","other":"Other","unmute":"Unmute","unmuted":"Unmuted","muted":"Muted","no_sound":"This video doesn\'t have sound","not_found_fallback":"Video not found, but you can choose from recommendations"}'),td=JSON.parse('{"unknown_error":"Просмотр видео в данный момент недоступен","video_not_found":"Видео не найдено","video_publish_finish":"Видео снято с публикации","access_denied":"Просмотр этого видео запрещен в вашей стране или на этом сайте","geo_access_denied":"К сожалению, просмотр данного видео в вашей стране невозможен.","warning_proxy_anon":"Если вы используете ускорители трафика, прокси-серверы и анонимайзеры - пожалуйста, выключите их перед просмотром видео.","access_restricted":"Вы не можете смотреть данное видео","video_processing":"Видео находится в обработке","announce":"Трансляция начнется {time}","no_broadcast":"Нет трансляции","no_signal":"Нет сигнала","no_stream":"Нет потока","no_connection":"Соединение с сервером не установлено. Пожалуйста, проверьте настройки сети. Если вы используете фаерволлы и антивирусы - отключите их на время просмотра трансляции.","secure_link_fail":"Ссылка более не действительна, попробуйте перезагрузить страницу.","watch_next":"Смотрите далее","share":"Поделиться","share_copy":"Скопировать","share_copied":"Скопировано","share_link":"Ссылка","share_copy_link":"Копировать ссылку","share_link_copied":"Ссылка скопирована","share_code":"Код","share_copy_code":"Копировать код","share_code_copied":"Код скопирован","ai_ad_hide":"Скрыть товары","ai_ad_show":"Показать товары из видео","ai_ad_buy":"Купить","ai_ad_note":"Реклама. Рекламодатель: ООО «МАРКЕТПЛЕЙС»","suggest":"Рекомендации к просмотру","replay":"Смотреть заново","advertisement":"Реклама","advertisement_link":"Узнать больше","advertisement_after":"После рекламы","advertisement_skip":"Пропустить","advertisement_skip_timer":"Пропустить:","advertisement_watch":"Смотреть","advertisement_watch_timer":"Смотрите:","advertisement_block":"Реклама","advertisement_block_of":"из","advertisement_block_number":"Рекламный блок №","advertisement_starting_in":"Реклама через:","live":"Трансляция","live_no_signal":"Нет сигнала трансляции","live_finished":"Трансляция завершена","live_back_to":"К прямой трансляции","complaint":"Пожаловаться","settings":"Настройки","quality":"Качество","quality_auto":"Авто","speed":"Скорость","speed_normal":"Обычная","subtitles":"Субтитры","subtitles_off":"Выключены","ru":"Русский","en":"Английский","es":"Испанский","fr":"Французский","de":"Немецкий","ja":"Японский","it":"Итальянский","ko":"Корейский","zh":"Китайский","pt":"Португальский","other":"Другой","unmute":"Включить звук","unmuted":"Звук включён","muted":"Звук выключен","no_sound":"Это видео без звука","default_error_message":"Возникла проблема при загрузке видео","playback_not_supported":"Ваш браузер не поддерживает воспроизведение этого видео. Пожалуйста, попробуйте использовать другой браузер","not_found_fallback":"Видео не найдено, но вы можете выбрать похожее из рекомендаций"}');var id=n(5008);const sd=(0,id.L)((()=>n.e(1793).then(n.bind(n,1793)))),nd=(0,id.L)((()=>Promise.resolve().then(n.bind(n,6653)))),rd=(0,id.L)((()=>n.e(7156).then(n.bind(n,7156)))),od=(0,id.L)((()=>n.e(8573).then(n.bind(n,8573)))),ad=(0,id.L)((()=>n.e(3883).then(n.bind(n,3883)))),ld=(0,id.L)((()=>n.e(7233).then(n.bind(n,7233)))),dd=(0,id.L)((()=>n.e(6969).then(n.bind(n,6969)))),cd=(0,id.L)((()=>n.e(6639).then(n.bind(n,6639)))),hd=(0,id.L)((()=>n.e(9988).then(n.bind(n,9988)))),ud=(0,id.L)((()=>n.e(9349).then(n.bind(n,9349)))),fd=(0,id.L)((()=>n.e(3973).then(n.bind(n,3973)))),pd=(0,id.L)((()=>n.e(7885).then(n.bind(n,7885)))),gd=(0,id.L)((()=>n.e(1363).then(n.bind(n,1363)))),md=(0,id.L)((()=>n.e(6453).then(n.bind(n,6453)))),vd=(0,id.L)((()=>n.e(738).then(n.bind(n,738)))),Ad=(0,id.L)((()=>n.e(4746).then(n.bind(n,4746)))),Ed=(0,id.L)((()=>n.e(2178).then(n.bind(n,2178)))),yd=(0,id.L)((()=>n.e(635).then(n.bind(n,635)))),Td=(0,id.L)((()=>Promise.resolve().then(n.bind(n,6243)))),bd=(0,id.L)((()=>Promise.resolve().then(n.bind(n,5166)))),Sd=(0,id.L)((()=>Promise.resolve().then(n.bind(n,1978)))),_d=(0,id.L)((()=>Promise.resolve().then(n.bind(n,2591)))),Cd=(0,id.L)((()=>Promise.resolve().then(n.bind(n,9749)))),Rd=(0,id.L)((()=>n.e(9139).then(n.bind(n,9139)))),Ld=(0,id.L)((()=>n.e(9600).then(n.bind(n,9600)))),Id=(0,id.L)((()=>n.e(6689).then(n.bind(n,6689)))),kd=(0,id.L)((()=>n.e(6947).then(n.bind(n,6947)))),wd=(0,id.L)((()=>n.e(3477).then(n.bind(n,3477)))),Pd=(0,id.L)((()=>n.e(2763).then(n.bind(n,2763)))),Od=(0,id.L)((()=>Promise.resolve().then(n.bind(n,8522)))),Dd=(0,id.L)((()=>n.e(1174).then(n.bind(n,1174)))),Nd=(0,id.L)((()=>n.e(4480).then(n.bind(n,4480)))),Md=(0,id.L)((()=>n.e(6684).then(n.bind(n,6684))));var xd=n(7204);const Bd=n.p+"55c0750ac5225c3d6f96.png",Fd=n.p+"4e75069800b136c59203.gif";class Ud extends al.bI{get name(){return"OptionsLoader"}get provider(){return this.options.provider}get playerError(){return this.player.playerError}constructor(e){super(e.options),this.multiPlayerLoaded=!1,this.createError=al.yF.createError.bind(this),this.testDownloadSpeed=Zl()((async()=>{var e,t;try{if(!al.Pw.isSafari&&!al.Pw.isiOS){const{download:i,startLevel:s}=(null===(e=window.navigator)||void 0===e?void 0:e.connection)?this.testConnection():await this.testImageDownload();(null===(t=this.options.playback)||void 0===t?void 0:t.hlsjsConfig)&&(this.options.playback.hlsjsConfig.startLevel=s),this.trigger(dl.s.OPTIONS_LOADER_SPEEDTEST,{download:i,startLevel:s})}}catch(e){}})),this.player=e}async load(e){var t,i;const s=Boolean(e.id||e.playList);s&&this.trigger(dl.s.OPTIONS_LOADER_LOADING,e);try{this.prepareOptions(e),e.id?(this.testDownloadSpeed(),await this.loadPlayerData(),await Promise.all([this.verifyAuthToken(),(async()=>{var e;try{this.parseSources(),await this.loadPlugins()}catch(t){throw(null===(e=t.details)||void 0===e?void 0:e.shouldHandleLiveError)&&await this.loadPlugins(["mediaControl","liveStatus","videoBackdrop"]),t}})(),this.testAutoPlayOptions()])):e.playList&&this.parseSources(),s&&this.trigger(dl.s.OPTIONS_LOADER_LOADED,this.options)}catch(e){const n=this.createError({code:e.code,description:null!==(i=null===(t=e.details)||void 0===t?void 0:t.message)&&void 0!==i?i:e.message,level:al.Mk.Levels.FATAL},{useCodePrefix:!1});s&&window.setTimeout((()=>{this.trigger(dl.s.OPTIONS_LOADER_ERROR,n)}),0)}}prepareOptions(t){var i,s;const{strings:n,playerTemplateId:r,checkReferrerCount:o}=this.options,{playback:a,playList:l}=this.player.options;let d;if(null==o)try{d=null===(s=(i=JSON.parse('["vp.rambler.ru","vp.dev.rambler.ru","vp-stage01.rambler.ru","vp-stage02.rambler.ru","vp-dev01.rambler.ru","vp-dev02.rambler.ru"]')).every)||void 0===s?void 0:s.call(i,(e=>{var t,i;return!(null===(i=null===(t=this.options)||void 0===t?void 0:t.referrer)||void 0===i?void 0:i.match(e))}))}catch(e){}else d=!1;if(this._options=Object.assign(Object.assign(Object.assign({},this.player.options),t),{strings:n,checkReferrerCount:d}),r&&(this._options.playerTemplateId=r),t.playback&&(this.options.playback=Object.assign(Object.assign({},a),t.playback)),t.playList&&(this.options.playList=Object.assign(Object.assign({},l),t.playList)),this.options.plugins||(this.options.plugins={core:[],container:[]}),!this.options.strings){const{language:t}=this.options;t&&(this.options.strings={[t]:e[t]})}}testConnection(){const{downlink:e,effectiveType:t}=window.navigator.connection;let i=2;t.includes("2g")?i=0:"3g"===t&&(i=1);const s=Object.keys(Ud.START_LEVEL_DOWNLINK).sort(((e,t)=>Number(e)-Number(t))).reduce(((t,s)=>"number"!=typeof t&&e{t.addEventListener("load",e),t.addEventListener("error",e),window.setTimeout(e,Ud.TEST_DOWNLOAD_SPEED_TIMEOUT),t.src=`${Fd}?_=${this.options.playerId}`}));const i=null===performance||void 0===performance?void 0:performance.getEntriesByType("resource");let s,n;if(i){const r=i.find((e=>e.name.includes(t.src)));(null===(e=this.options.playback)||void 0===e?void 0:e.hlsjsConfig)&&(s=r?8*r.transferSize/1e3/((r.responseEnd-r.requestStart)/1e3):-1,n=Object.keys(Ud.START_LEVEL_SPEED).reduce(((e,t)=>"number"!=typeof e&&se.params))),St.forEach((({type:e,params:t})=>{var i;this.options[e]=(null!==(i=this.options[e])&&void 0!==i?i:[]).concat(t)})),mt&&(this.options.promoButton={image:mt,clickUrl:At,position:vt,size:Et}),null!==(F=(ke=this.options).likes)&&void 0!==F||(ke.likes=null==tt?void 0:tt.likes),null!==(U=(we=this.options).videoBackdropColor)&&void 0!==U||(we.videoBackdropColor=null==tt?void 0:tt.videoBackdropColor),this.options.videoBackdrop="none"!==this.options.videoBackdropColor;const _t=null===(V=null===($=et.allFrontSettings)||void 0===$?void 0:$.record)||void 0===V?void 0:V.episodes;if(yt&&We&&_t){const e=_t.filter((([e])=>ee-t)),t=Object.create(null);e.length<2||0!==e[0][0]||e.some((([e])=>{if(t[e])return!0;t[e]=!0}))||(bt=e.map((([e,t],i,s)=>{var n,r;return{start:e,end:null!==(r=null===(n=s[i+1])||void 0===n?void 0:n[0])&&void 0!==r?r:We.duration/1e3,label:t}})))}this.options.episodes=bt,bt&&(null!==(G=(Pe=this.options).thumbnails)&&void 0!==G||(Pe.thumbnails={thumbs:[]})),null!==(j=(Oe=this.options).aiAd)&&void 0!==j||(Oe.aiAd=!0===(null===(H=null===(K=et.allFrontSettings)||void 0===K?void 0:K.record)||void 0===H?void 0:H.aiAd)),et.aiAdInfo||delete this.options.aiAd,yt&&rt&&this.options.multiplayerHidden?null!==(Y=(De=this.options).watchNext)&&void 0!==Y||(De.watchNext=null==tt?void 0:tt.watchNext):delete this.options.watchNext,null!==(W=(Ne=this.options).preload)&&void 0!==W||(Ne.preload=!0===et.preloadChunksEnabled),this.options.preload||(this.options.playback&&(this.options.playback.preload="none"),this.options.hlsPlayback&&(this.options.hlsPlayback.preload=!1)),null!=(null==tt?void 0:tt.replayTimeout)&&(null!==(q=(Me=this.options).replayTimeout)&&void 0!==q||(Me.replayTimeout=null==tt?void 0:tt.replayTimeout)),null!==(X=(xe=this.options).threeSixtyViewer)&&void 0!==X||(xe.threeSixtyViewer=null===(Z=null===(Q=et.allFrontSettings)||void 0===Q?void 0:Q.record)||void 0===Z?void 0:Z.threeSixtyViewer),null!==(J=(Be=this.options).saveUserVolume)&&void 0!==J||(Be.saveUserVolume=null==tt?void 0:tt.saveUserVolume),null!==(ee=(Fe=this.options).volume)&&void 0!==ee||(Fe.volume=null!==(se=null===(ie=null===(te=et.allFrontSettings)||void 0===te?void 0:te.account)||void 0===ie?void 0:ie.initialVolume)&&void 0!==se?se:Ud.VOLUME),this.options.saveUserVolume&&(this.options.volume=null!==(oe=await(null===(re=null===(ne=this.provider)||void 0===ne?void 0:ne.mediator)||void 0===re?void 0:re.getOptionStorage("volume")))&&void 0!==oe?oe:this.options.volume),null!==(ae=(Ue=this.options).playbackRate)&&void 0!==ae||(Ue.playbackRate=!0===(null==tt?void 0:tt.playbackRate)),null!==(le=($e=this.options).minDurationToShowAd)&&void 0!==le||($e.minDurationToShowAd=null===(ce=null===(de=et.allFrontSettings)||void 0===de?void 0:de.account)||void 0===ce?void 0:ce.minDurationToShowAd)}async verifyAuthToken(){var e;const{playList:t,authToken:i,allFrontSettings:s,authTokenVerifyUrl:n=(null===(e=null==s?void 0:s.account)||void 0===e?void 0:e.authTokenVerifyUrl)}=this.options;if(n){const e=xd.Uc.startTimer({endpoint:"authTokenVerifyUrl"});try{const e=(0,K.JT)(n,{recordId:null==t?void 0:t.id,token:i});await new Promise(((t,i)=>{const s=new XMLHttpRequest;s.open("get",e,!0),s.setRequestHeader("content-type","text/plain"),s.timeout=Ud.VERIFY_AUTH_TOKEN_TIMEOUT,s.onload=()=>{200===s.status?t():i(new Error(s.statusText))},s.onerror=()=>i(new Error(s.statusText)),s.send(null)}))}catch(e){throw new Jl.hD(ll.I.ACCESS_RESTRICTED)}finally{e.observeDuration()}}}parseSources(){var e;const{playList:t,sources:i,mediaControl:s}=this.options;if(null==i?void 0:i.includes("not_found_fallback"))return;const n="empty"===(null==t?void 0:t.type)||"online"===(null==t?void 0:t.type)&&!(null==t?void 0:t.source)&&!(null==t?void 0:t.directSource),r=this.options.live?{shouldHandleLiveError:"universal"===(null==s?void 0:s.skinName)}:void 0;if(n){const i=null===(e=null==t?void 0:t.startsAtDate)||void 0===e?void 0:e.getTime();if(i&&i>Date.now())throw new Jl.hD(Object.assign(Object.assign({},ll.I.ANNOUNCE),{details:r}));if(i&&iBoolean(e[t])))),e.qualityVisible&&n.push("levelSelector"),e.allowUserInteraction&&n.push("clickToPause"),"universal"===r&&((e.qualityVisible||e.playbackRate||(null===(i=e.subtitles)||void 0===i?void 0:i.length))&&n.push("settingsMenu"),(e.unmute||(null===(s=e.share)||void 0===s?void 0:s.embedCodes)||e.advertisement)&&n.push("notifier"),e.live&&n.push("liveStatus")),e.advertisement&&("universal"===r||"unity"===r||"rambler_2018"===r||"rambler_html5"===r||"lenta"===r||"championat_html5"===r)&&n.push("timeToAdvertisement")}const r=xd.EH.startTimer(),o=await Promise.all(n.map((e=>this.loadPlugin(e))));r.observeDuration(),o.forEach((e=>{e&&Object.keys(e).forEach((t=>{this.options[t]=e[t]}))}))}async testAutoPlayOptions(){var e,t,i,s;const{mute:n,recordIsMute:r,autoPlayTimeout:o,autoPlay:a,[z.gM]:l,[z.yN]:d}=this.options;if(a||l||d||null!==(e=(i=this.options).autoPlayPolicy)&&void 0!==e||(i.autoPlayPolicy="off"),bl.Q_&&(this.options.autoPlay=!1,this.options[z.gM]=!1,this.options[z.yN]=!1,null!==(t=(s=this.options).autoPlayPolicy)&&void 0!==t||(s.autoPlayPolicy="notAllowedForSearchBot")),this.options.autoPlay&&document.hidden&&(this.options.autoPlay=!1,this.options[z.QT]=!0),this.options.autoPlay){const e=await hl({muted:n||r,timeout:o});"unmuted"!==e&&("muted"===e?this.options.mute=!0:this.options.autoPlay=!1),this.options.autoPlayPolicy=e}}}Ud.TEST_DOWNLOAD_SPEED_TIMEOUT=1e3,Ud.VERIFY_AUTH_TOKEN_TIMEOUT=5e3,Ud.DEFAULT_CHUNK_DURATION=1e4,Ud.NEXT_LEVEL_MAX_CHUNK_DURATION=2e3,Ud.VOLUME=10,Ud.START_LEVEL_SPEED={3:0,8:1,10:2,20:3,Infinity:void 0},Ud.START_LEVEL_DOWNLINK={2:[0,0,0],4.8:[0,0,1],8:[0,1,2],Infinity:[0,2,3]};var $d=n(1162),Vd=n(1669),Gd={};Gd.styleTagTransform=Ml(),Gd.setAttributes=Pl(),Gd.insert=kl().bind(null,"head"),Gd.domAPI=Ll(),Gd.insertStyleElement=Dl(),Cl()(Vd.A,Gd),Vd.A&&Vd.A.locals&&Vd.A.locals;var jd;const Kd=Symbol("onVisibleAreaChanged"),Hd=[ll.I.UNKNOWN_ERROR.code,ll.I.RECORD_NOT_PROCESSED.code,ll.I.ANNOUNCE.code,ll.I.NO_BROADCAST.code,ll.I.NO_SIGNAL.code,ll.I.NO_STREAM.code,ll.I.NO_CONNECTION.code,"warning_proxy_anon","secure_link_fail"],Yd=[ll.I.ANNOUNCE.code,ll.I.LIVE_FINISHED.code,ll.I.NO_BROADCAST.code,ll.I.NO_SIGNAL.code,...[il.ErrorDetails.MANIFEST_LOAD_ERROR,il.ErrorDetails.MANIFEST_LOAD_TIMEOUT,il.ErrorDetails.MANIFEST_PARSING_ERROR].map((e=>`hls:${il.ErrorTypes.NETWORK_ERROR}_${e}`))];class Wd extends al.bI{get name(){return"Player"}get $parent(){return(0,al.$)(this.options.parentElement)}get provider(){return this.core.options.provider}get aspectRatio(){var e,t,i;return null!==(i=null!==(t=null===(e=this.core)||void 0===e?void 0:e.options.aspectRatio)&&void 0!==t?t:this.options.aspectRatio)&&void 0!==i?i:$d.nT}get ended(){var e;return!(null===(e=this.advertisement)||void 0===e?void 0:e.hasAd())&&(this.core.activeContainer.ended||this.recordEnded)}get isReady(){return this.core.isReady}get mediaControl(){return this.core.getPlugin("mediaControl")}get share(){return this.core.getPlugin("share")}get viewport(){return this.core.getPlugin("viewport")}get advertisement(){return this.core.getPlugin("advertisement")}get docking(){return this.core.getPlugin("docking")}get multiPlayer(){return this.core.getPlugin("multiplayer")}get clickToPause(){var e;return null===(e=this.core.activeContainer)||void 0===e?void 0:e.getPlugin("click_to_pause")}get suggest(){return this.core.getPlugin("suggest")}get playerError(){return this.core.playerError}constructor(e){var t,i,s,n,r;super(e),this.recordEnded=!1,this.loadingErrors=0,this.onMouseMove=({target:e})=>{const t=e&&(0,al.$)(e).closest("[data-active-state]").data("activeState");null!=t?t?this.setActiveState(!1):this.unsetActiveState():this.setActiveState()},this.setActiveState=ol()(((e=!0)=>{this.stateTimeout&&this.clearStateTimeout(),this.stateTimeout&&e||(window.setTimeout((()=>{this.$parent.addClass("eplayer-active"),this.$parent.css("cursor",null)}),0),window.setTimeout(this.toggleClickToPause,Wd.ACTIVATE_TIMEOUT,!0)),e&&(this.stateTimeout=window.setTimeout(this.unsetActiveState,Wd.ACTIVE_STATE_TIMEOUT))}),Wd.ACTIVE_STATE_THROTTLE_TIMEOUT),this.unsetActiveState=()=>{var e;this.clearStateTimeout(),this.$parent.removeClass("eplayer-active"),this.$parent.css("cursor","none"),(null===(e=this.core.activeContainer)||void 0===e?void 0:e.isPlaying())&&this.toggleClickToPause(!1)},this.onInitialPlay=async()=>{var e,t;const{enforceStartWhenPlayingInParent:i,autoPlay:s,[z.QT]:n,[z.gM]:r,[z.yN]:o,playerId:a,dockingParentId:l}=this.core.options;i&&!(o||r||s||n)&&await(null===(t=null===(e=this.provider)||void 0===e?void 0:e.mediator)||void 0===t?void 0:t.enforceStart(a,l))},this.cleanPlayingState=(e=!1)=>{var t,i,s;const n=null===(t=this.docking)||void 0===t?void 0:t.isDocked(),{playerId:r,dockingParentId:o,enforceStartWhenPlayingInParent:a}=this.core.options;n&&!e||a||null===(s=null===(i=this.provider)||void 0===i?void 0:i.mediator)||void 0===s||s.stopPlaying(r,o)},this.toggleClickToPause=e=>{var t,i;e?null===(t=this.clickToPause)||void 0===t||t.enable():null===(i=this.clickToPause)||void 0===i||i.disable()},this.onParentResize=nl()((()=>{var e,t;const i=this.fixedHeight?Number(this.core.options.height):Math.round(this.core.el.offsetWidth/this.aspectRatio);this.core.isFullscreen()||i===this.core.el.offsetHeight||(this.options.height=(null===(e=this.docking)||void 0===e?void 0:e.isDocked())||(null===(t=this.docking)||void 0===t?void 0:t.isDockingRequested())||this.multiPlayer?i:this.core.options.height,this.core.resize({width:"100%",height:i}))})),this[jd]=ol()((async e=>{var t,i,s,n,r,o,a,l,d,c,h,u,f,p,g,m;const{mute:v,recordIsMute:A,autoPlay:E,autoPlayTimeout:y,minPlayingVisibleHeight:T=.5,playerId:b,dockingParentId:S,[z.QT]:_,[z.gM]:C,[z.yN]:R,enforceStartWhenPlayingInParent:L}=this.core.options;document.hidden&&(this.recordEnded=!1);const I=R||C||E||_,k=this.ended&&!(null===(t=this.multiPlayer)||void 0===t?void 0:t.isNextRecordRequested())&&(null===(i=this.multiPlayer)||void 0===i?void 0:i.isLastRecord),w=null===(s=this.docking)||void 0===s?void 0:s.enabled;if(!L&&(!I||k))return;if(document.hidden||!(!C&&!R||e>=T||(null===(n=this.docking)||void 0===n?void 0:n.isDockingAwaited())||(null===(r=this.docking)||void 0===r?void 0:r.isDockingRequested()))){if((this.isPlaying()||(null===(o=this.advertisement)||void 0===o?void 0:o.hasAd()))&&!this.core.isFullscreen()){if(R&&w)return void this.mute();R&&!w&&(this.mute(),this.cleanPlayingState()),R||this.pause()}return void((null===(a=this.multiPlayer)||void 0===a?void 0:a.isNextRecordRequested())&&(null===(l=this.multiPlayer)||void 0===l||l.waitNextRecord(),w||this.cleanPlayingState()))}if(null===(d=this.multiPlayer)||void 0===d?void 0:d.isNextRecordAwaited())return void(null===(c=this.multiPlayer)||void 0===c||c.autoPlayNextRecord());if(null===(h=this.multiPlayer)||void 0===h?void 0:h.isNextRecordRequested())return;if(null==this.core.options.autoPlayPolicy){const e=await hl({muted:v||A,timeout:y});this.core.configure({autoPlayPolicy:e})}const{autoPlayPolicy:P}=this.core.options;"muted"===P||"unmuted"===P?(!v&&R&&"unmuted"===P&&this.unmute(),this.isPlaying()||!1!==(E||_||(C||R)&&(L||await(null===(f=null===(u=this.provider)||void 0===u?void 0:u.mediator)||void 0===f?void 0:f.canPlay(b,S))))&&("muted"===P&&this.mute(),this.play(),_&&(this.core.options.autoPlay=!0,this.core.options[z.QT]=!1)),L&&e>=T&&!(null===(p=this.docking)||void 0===p?void 0:p.isDocked())&&!await(null===(m=null===(g=this.provider)||void 0===g?void 0:g.mediator)||void 0===m?void 0:m.canPlay(b,S))&&(this.isPlaying()?await this.onEnforceStarted():this.listenAdOrContainerPlay())):this.toggleHold(!0)}),Wd.VIEWPORT_CHANGE_THROTTLE_TIMEOUT,{leading:!1}),this.onErrorWithPlayNext=e=>{var t;this.trigger(dl.s.PLAYER_ERROR,e),null===(t=this.multiPlayer)||void 0===t||t.playNext()},this.hideSpinner=()=>{this.spinnerTimeout&&(clearTimeout(this.spinnerTimeout),delete this.spinnerTimeout),this.toggleSpinner(!1)},this.toggleSpinner=e=>{this.$parent.toggleClass("loading",e)};const o={recycleVideo:al.Pw.isMobile,disableContextMenu:!0,preload:"metadata",controls:!1,playInline:!0,crossOrigin:"anonymous",audioOnly:!1,hlsjsConfig:{capLevelToPlayerSize:!0,enableWorker:!0}};this._options=Object.assign(Object.assign({},{allowUserInteraction:!0,disableKeyboardShortcuts:!1,loop:!1,hideMediaControl:!1,hideVolumeBar:!1,disableVideoTagContextMenu:!0,exitFullscreenOnEnd:!1,disableErrorScreen:!0,autoPlayTimeout:2500,eventsReportLive:!0}),e),this.options.playback=Object.assign(Object.assign({},o),e.playback),this.options.hlsPlayback=Object.assign(Object.assign({},{preload:!0}),e.hlsPlayback),this.options.playerId=(0,cl.DU)(),null!==(t=(n=this.options).referrer)&&void 0!==t||(n.referrer=document.referrer||window.location.href),this.options.referrer=null===(i=this.options.referrer)||void 0===i?void 0:i.replace(/#.+/m,""),null!==(s=(r=this.options).language)&&void 0!==s||(r.language=/^(ru|ru-RU)$/.test(al.Aq.getBrowserLanguage())?"ru":"en"),this.options.chromeless||(this.options.allowUserInteraction=!0),this.options.allowUserInteraction||(this.options.disableKeyboardShortcuts=!0),null!=this.options.height&&(this.fixedHeight=!0),this.loader=new al.aH([],this.options.playerId),this.optionsLoader=new Ud(this),this.coreFactory=new zl(this),this.resizeObserver=new ResizeObserver(this.onParentResize),this.mutationObserver=new MutationObserver(this.onParentResize),this.options.parentId?this.setParentId(this.options.parentId):this.options.parent&&this.attachTo(this.options.parent)}setParentId(e){const t=document.querySelector(e);return t instanceof HTMLElement&&this.attachTo(t),this}attachTo(e){var t,i,s;return this.options.parentElement=e,this.options.width="100%",null!==(t=(s=this.options).height)&&void 0!==t||(s.height=Math.round(e.offsetWidth/this.aspectRatio)),this.core=this.coreFactory.create(),this.addEventListeners(),this.coreFactory.configure(this.options),null===(i=this.provider)||void 0===i||i.setPlayerId(this.options.playerId),this}configure(e){return e.id&&this.$parent.css("height",this.$parent.offset().height),this.coreFactory.configure(e),this}clearStateTimeout(){this.setActiveState.cancel(),clearTimeout(this.stateTimeout),delete this.stateTimeout}addEventListeners(){return this.core.isReady?this.onReady():this.listenToOnce(this.core,dl.s.CORE_READY,this.onReady),this.listenTo(this.core,dl.s.CORE_ACTIVE_CONTAINER_CHANGED,this.onActiveContainerChange),this.listenTo(this.core,dl.s.CORE_FULLSCREEN,this.onFullscreenChange),this.listenTo(this.core,dl.s.CORE_RESIZE,this.onResize),this.listenTo(this.optionsLoader,dl.s.OPTIONS_LOADER_LOADING,this.onLoading),this.listenTo(this.optionsLoader,dl.s.OPTIONS_LOADER_LOADED,this.onLoaded),this.listenTo(this.optionsLoader,dl.s.OPTIONS_LOADER_ERROR,this.onLoadingError),this.viewport&&this.listenTo(this.viewport,dl.s.VIEWPORT_VISIBLE_AREA_CHANGED,this[Kd]),this.docking&&this.listenTo(this.docking,dl.s.DOCKING_CHANGED,this.onDockingChange),this.mediaControl&&(this.listenToOnce(this.mediaControl,dl.s.MEDIACONTROL_RENDERED,this.restoreHeight),this.listenTo(this.mediaControl,dl.s.MEDIACONTROL_SHARE,this.onMediaControlShare),this.listenToOnce(this.mediaControl,dl.s.MEDIACONTROL_PLAYPAUSE_CLICK,this.stopPlayInVisibleArea),this.listenTo(this.mediaControl,dl.s.MEDIACONTROL_VOLUME_CLICK,this.stopUnmuteInVisibleArea),this.listenTo(this.mediaControl,dl.s.MEDIACONTROL_MUTE_CLICK,this.stopUnmuteInVisibleArea)),this.multiPlayer&&this.listenTo(this.multiPlayer,dl.s.MULTIPLAYER_SUGGEST_TIMEOUT,this.onMultiPlayerSuggestTimeout),this.advertisement&&(this.listenTo(this.advertisement,dl.s.ADVERTISEMENT_LOADING,this.onAdLoading),this.listenTo(this.advertisement,dl.s.ADVERTISEMENT_LOADED,this.hideSpinner),this.listenTo(this.advertisement,dl.s.ADVERTISEMENT_ERROR,this.onAdError),this.listenTo(this.advertisement,dl.s.ADVERTISEMENT_STARTED,this.onAdStarted),this.listenTo(this.advertisement,dl.s.ADVERTISEMENT_PAUSED,this.onAdPaused),this.listenTo(this.advertisement,dl.s.ADVERTISEMENT_COMPLETE,this.onAdPaused),this.listenTo(this.advertisement,dl.s.ADVERTISEMENT_RESUMED,this.onAdResumed),this.listenTo(this.advertisement,dl.s.ADVERTISEMENT_ENDED,this.onAdEnded),this.listenTo(this.advertisement,dl.s.ADVERTISEMENT_CONTENT_RESUME_REQUESTED,this.onAdContentResumeRequested),this.listenToOnce(this.advertisement,dl.s.ADVERTISEMENT_INTERACTION_PLAYING,this.stopPlayInVisibleArea)),this}addContainerEventListeners(){var e;const{activeContainer:t,activePlayback:i}=this.core;return t&&(this.listenToOnce(t,dl.s.CONTAINER_PLAY,this.onStartPlay),this.listenToOnce(t,dl.s.CONTAINER_CLICK,this.stopPlayInVisibleArea),this.listenTo(t,dl.s.CONTAINER_PLAY,this.onPlay),this.listenTo(t,dl.s.CONTAINER_PAUSE,this.onPause),this.listenTo(t,dl.s.CONTAINER_STOP,this.onStop),this.listenTo(t,dl.s.CONTAINER_ENDED,this.onEnded),this.listenTo(t,dl.s.CONTAINER_SEEK,this.onSeek),this.listenTo(t,dl.s.CONTAINER_ERROR,this.onError),this.suggest&&this.listenTo(this.suggest,dl.s.SUGGEST_ERROR,this.onError),this.listenTo(t,dl.s.CONTAINER_TIMEUPDATE,this.onTimeUpdate),this.listenTo(t,dl.s.CONTAINER_VOLUME,this.onVolumeUpdate),this.listenTo(t,dl.s.CONTAINER_SUBTITLE_AVAILABLE,this.onSubtitleAvailable)),i&&(this.listenTo(i,dl.s.PLAYBACK_BUFFERING,this.onBuffering),(null===(e=this.docking)||void 0===e?void 0:e.enabled)&&this.listenTo(i,dl.s.PLAYBACK_PLAY_INTENT,this.onInitialPlay),this.listenTo(i,dl.s.PLAYBACK_BUFFERFULL,this.hideSpinner),i.buffering&&this.showSpinner()),this}stopListening(e,t,i){return i||(this.clearStateTimeout(),clearTimeout(this.spinnerTimeout),delete this.spinnerTimeout,this.resizeObserver.disconnect(),this.mutationObserver.disconnect(),document.removeEventListener("mousemove",this.onMouseMove)),super.stopListening(e,t,i)}onActiveContainerChange(){this.stopListening(),this.addEventListeners()}stopPlayInVisibleArea(){this.core.options.autoPlay=!1,this.core.options[z.gM]=!1}stopUnmuteInVisibleArea(e){const{[z.yN]:t}=this.core.options;if(0===e&&t)return this.autoPlayCache=t,void(this.core.options[z.yN]=!1);const i=e>0;i&&this.core.configure({autoPlayPolicy:"unmuted"}),i&&this.isPlaying()&&this.autoPlayCache&&(this.core.options[z.yN]=!0,this.autoPlayCache=null)}onReady(){var e,t,i;this.addContainerEventListeners();const{playList:s,useDvrControls:n,autoPlay:r,[z.QT]:o,[z.gM]:a,[z.yN]:l,sources:d}=this.core.options;this.$parent.addClass("eagleplayer eagleplayer-instance eplayer eplayer-ios-noskin"),this.$parent.toggleClass("eplayer-mobile",al.Pw.isMobile).toggleClass("eplayer-not-mobile",!al.Pw.isMobile).toggleClass("eplayer-not-found",null==d?void 0:d.includes("not_found_fallback"));const c=l||a||r||o;this.toggleHold(!c),this.toggleSize((null===(e=this.core.activeContainer)||void 0===e?void 0:e.el.offsetWidth)<$d.Pn);const h="online"===(null==s?void 0:s.type)||"empty"===(null==s?void 0:s.type);this.$parent.toggleClass("eplayer-live",h&&!0!==n).toggleClass("eplayer-live-dvr",h&&!0===n),this.$parent.css({color:"white",fontSize:16,fontFamily:"Helvetica, Helvetica Neue, Arial",overflow:"hidden",position:"relative"}),null===(t=this.core.activeContainer)||void 0===t||t.$el.css({width:"100%",height:"100%",position:"relative",top:0,background:"black"}),null===(i=this.core.activePlayback)||void 0===i||i.$el.css({width:"100%",height:"100%"});const u=document.body||document.documentElement;this.resizeObserver.observe(u),this.mutationObserver.observe(u,{childList:!0,subtree:!0}),document.addEventListener("mousemove",this.onMouseMove),this.setActiveState()}listenAdOrContainerPlay(){this.listenToOnce(this.advertisement,dl.s.ADVERTISEMENT_STARTED,this.onEnforceStarted),this.listenToOnce(this.core.activeContainer,dl.s.CONTAINER_PLAY,this.onEnforceStarted)}async onEnforceStarted(){var e,t;const{playerId:i,dockingParentId:s}=this.core.options;this.stopListening(this.advertisement,dl.s.ADVERTISEMENT_STARTED,this.onEnforceStarted),this.stopListening(this.core.activeContainer,dl.s.CONTAINER_PLAY,this.onEnforceStarted),await(null===(t=null===(e=this.provider)||void 0===e?void 0:e.mediator)||void 0===t?void 0:t.enforceStart(i,s))}onFullscreenChange(e){this.trigger(dl.s.PLAYER_FULLSCREEN,e),this.$parent.toggleClass("eagleplayer-fullscreen fullscreen-on",e)}onDockingChange(e){const{dockingWidth:t=$d.Pn}=this.options;"boolean"==typeof this.fixedHeight&&(e?this.dockedHeight=this.core.options.height:this.core.options.height=this.dockedHeight,this.fixedHeight=!e),t<$d.Pn&&this.toggleSize(e),this.$parent.toggleClass("eplayer-docked",e),this.trigger(dl.s.PLAYER_DOCK,e)}onVolumeUpdate(e){var t;this.trigger(dl.s.PLAYER_VOLUMEUPDATE,e),this.$parent.toggleClass("eplayer-mute",0===e),(null===(t=this.docking)||void 0===t?void 0:t.enabled)||this.isPlaying()&&0===e&&this.cleanPlayingState()}onSubtitleAvailable(){this.trigger(dl.s.PLAYER_SUBTITLE_AVAILABLE)}onResize(e){Number(e.width)&&Number(e.height)&&(this.toggleSize(Number(e.width)<$d.Pn),this.$parent.toggleClass("eplayer-vertical",this.aspectRatio<1),this.trigger(dl.s.PLAYER_RESIZE,e))}onStartPlay(){const{startPosition:e}=this.core.options;e&&this.seek(e)}onPlay(){var e,t;this.recordEnded=!1,this.trigger(dl.s.PLAYER_PLAY),this.toggleHold(!1),this.$parent.addClass("eagleplayer-state-play"),null===(t=null===(e=this.core.options.playback)||void 0===e?void 0:e.hlsjsConfig)||void 0===t||delete t.startLevel,clearTimeout(this.cleanMediatorStateTimeout),delete this.cleanMediatorStateTimeout,this.getVolume()&&this.autoPlayCache&&(this.autoPlayCache=null,this.core.options[z.yN]=!0)}onPause(){var e;const{[z.yN]:t}=this.core.options;this.trigger(dl.s.PLAYER_PAUSE),this.toggleHold(!0),this.$parent.removeClass("eagleplayer-state-play"),this.toggleClickToPause(!0),null!==(e=this.cleanMediatorStateTimeout)&&void 0!==e||(this.cleanMediatorStateTimeout=window.setTimeout(this.cleanPlayingState,Wd.CLEAN_MEDIATOR_STATE_TIMEOUT)),t&&(this.autoPlayCache=t),this.core.options[z.yN]=!1}onStop(){var e;this.trigger(dl.s.PLAYER_STOP,this.getCurrentTime()),this.toggleHold(!0),this.hideSpinner(),this.toggleClickToPause(!0),null!==(e=this.cleanMediatorStateTimeout)&&void 0!==e||(this.cleanMediatorStateTimeout=window.setTimeout(this.cleanPlayingState,Wd.CLEAN_MEDIATOR_STATE_TIMEOUT))}onEnded(){var e;this.recordEnded=!0,this.trigger(dl.s.PLAYER_ENDED),this.hideSpinner(),this.seek(0),this.toggleHold(!0),this.toggleClickToPause(!0),null!==(e=this.cleanMediatorStateTimeout)&&void 0!==e||(this.cleanMediatorStateTimeout=window.setTimeout(this.cleanPlayingState,Wd.CLEAN_MEDIATOR_STATE_TIMEOUT))}onSeek(e){this.trigger(dl.s.PLAYER_SEEK,e)}onTimeUpdate(e){this.trigger(dl.s.PLAYER_TIMEUPDATE,e)}onError(e){var t,i,s,n;const{i18n:r,options:{playList:o,language:a,mediaControl:l}}=this.core;if(this.trigger(dl.s.PLAYER_ERROR,e),this.hideSpinner(),(null==e?void 0:e.level)!==al.Mk.Levels.FATAL)return;let d=e.code&&r.t(e.code)||null;const c=null==o?void 0:o.startsAtDate,h=null==o?void 0:o.startsAtTimeZone;if("universal"!==(null===(t=null==l?void 0:l.skinName)||void 0===t?void 0:t.toLowerCase())&&null!=c&&null!=h&&(e.code===ll.I.ANNOUNCE.code||e.code===ll.I.LIVE_FINISHED.code)){const t=(0,fl.po)(c,h,"numeric",a);d=(0,cl._U)(r.t(e.code),{time:t})}if(e.code===d&&(d=null),e.origin!==this.optionsLoader.name&&e.origin!==(null===(i=this.suggest)||void 0===i?void 0:i.name)){const t=new Error("playback failed"),i=this.getCurrentTime(),n=null!==(s=null==o?void 0:o.directSource)&&void 0!==s?s:null==o?void 0:o.source,{UI:r}=e,a=function(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);n-1};this.core.configure(f),u||null===(n=this.mediaControl)||void 0===n||n.disable()}onLoading(){clearTimeout(this.nextRecordTimeout),this.onBuffering()}onLoaded(){this.hideSpinner(),this.loadingErrors=0,this.trigger(dl.s.PLAYER_READY)}onLoadingError(e){if(this.multiPlayer&&e.level===al.Mk.Levels.FATAL)return this.loadingErrors{clearTimeout(this.cleanMediatorStateTimeout),delete this.cleanMediatorStateTimeout}),0)}onAdLoading(e){var t;"banner"!==e.blockType&&"bannerMobile"!==e.blockType&&!(null===(t=this.advertisement)||void 0===t?void 0:t.isPreRollWithStartTime(e.blockType))&&"middleRoll"!==e.blockType&&"middleRollMobile"!==e.blockType&&"pseudostreaming"!==e.blockType&&"pseudostreamingMobile"!==e.blockType&&(clearTimeout(this.hideAdSpinnerTimeout),delete this.hideAdSpinnerTimeout,this.toggleSpinner(!0)),clearTimeout(this.cleanMediatorStateTimeout),delete this.cleanMediatorStateTimeout}onAdError(){this.hideAdSpinnerTimeout=window.setTimeout(this.hideSpinner,0)}onAdStarted(){this.trigger(dl.s.ADVERTISEMENT_STARTED)}onAdPaused(){var e;this.trigger(dl.s.ADVERTISEMENT_PAUSED),(null===(e=this.docking)||void 0===e?void 0:e.enabled)||this.cleanPlayingState()}onAdResumed(){this.trigger(dl.s.ADVERTISEMENT_RESUMED)}onAdEnded(){this.trigger(dl.s.ADVERTISEMENT_ENDED)}onAdContentResumeRequested(e){var t;("postRoll"===e.blockType||"postRollMobile"===e.blockType||"pauseBanner"===e.blockType||"pauseBannerMobile"===e.blockType)&&(null!==(t=this.cleanMediatorStateTimeout)&&void 0!==t||(this.cleanMediatorStateTimeout=window.setTimeout(this.cleanPlayingState,Wd.CLEAN_MEDIATOR_STATE_TIMEOUT)))}onMediaControlShare(){this.share&&this.viewport&&(this.stopListening(this.viewport,dl.s.VIEWPORT_VISIBLE_AREA_CHANGED,this[Kd]),this.listenToOnce(this.share,dl.s.SHARE_CLOSE,(()=>{this.listenTo(this.viewport,dl.s.VIEWPORT_VISIBLE_AREA_CHANGED,this[Kd])})))}onBuffering(){this.showSpinner(),this.toggleHold(!1)}showSpinner(){this.spinnerTimeout||(this.spinnerTimeout=window.setTimeout(this.toggleSpinner,Wd.SPINNER_TIMEOUT,!0))}toggleHold(e){this.$parent.toggleClass("eplayer-hold-skin",e)}toggleSize(e){this.$parent.toggleClass("eplayer-xs",e)}restoreHeight(){this.$parent.css("height",null)}toggleFullscreen(){var e;return null===(e=this.mediaControl)||void 0===e||e.toggleFullscreen(),this}resize(e){var t;const i=null!==(t=e.height)&&void 0!==t?t:Math.round(this.core.el.offsetWidth/this.aspectRatio);null!=e.height?this.fixedHeight=!0:delete this.fixedHeight,this.core.resize({width:"100%",height:i})}destroy(){return this.stopListening(),this.core.destroy(),this.cleanPlayingState(!0),this}play(){var e,t;return(null===(e=this.advertisement)||void 0===e?void 0:e.hasAd())?null===(t=this.advertisement)||void 0===t||t.play():this.core.activeContainer.play(),this}pause(){var e,t;return(null===(e=this.advertisement)||void 0===e?void 0:e.hasAd())?null===(t=this.advertisement)||void 0===t||t.pause():this.core.activeContainer.pause(),this}stop(){return this.core.activeContainer.stop(),this}seek(e){return this.core.activeContainer.seek(e),this}seekPercentage(e){return this.core.activeContainer.seekPercentage(e),this}mute(){var e,t,i;return(null===(e=this.mediaControl)||void 0===e?void 0:e.muted)||(this.mutedVolume=null===(t=this.mediaControl)||void 0===t?void 0:t.volume,null===(i=this.mediaControl)||void 0===i||i.setVolume(0)),this}unmute(){var e,t,i;const{volume:s}=this.core.options;return(null===(e=this.mediaControl)||void 0===e?void 0:e.muted)&&(null===(t=this.mediaControl)||void 0===t||t.setVolume(null!==(i=this.mutedVolume)&&void 0!==i?i:s),delete this.mutedVolume),this}setVolume(e){var t;return null===(t=this.mediaControl)||void 0===t||t.setVolume(e),this}isPlaying(){var e;return this.core.activeContainer.isPlaying()||!!(null===(e=this.advertisement)||void 0===e?void 0:e.isPlaying())}getVolume(){var e,t;return null!==(t=null===(e=this.mediaControl)||void 0===e?void 0:e.volume)&&void 0!==t?t:0}getCurrentTime(){return this.core.activeContainer.getCurrentTime()}getStartTimeOffset(){return this.core.activeContainer.getStartTimeOffset()}getDuration(){return this.core.activeContainer.getDuration()}getSourceLink(){var e,t;return null!==(t=null===(e=this.core.options.playList)||void 0===e?void 0:e.link)&&void 0!==t?t:""}}var zd;jd=Kd,Wd.SPINNER_TIMEOUT=300,Wd.ACTIVE_STATE_TIMEOUT=3e3,Wd.ACTIVE_STATE_THROTTLE_TIMEOUT=300,Wd.VIEWPORT_CHANGE_THROTTLE_TIMEOUT=200,Wd.ACTIVATE_TIMEOUT=al.Pw.isMobile?1e3:0,Wd.CLEAN_MEDIATOR_STATE_TIMEOUT=100,Wd.NEXT_RECORD_AFTER_ERROR_TIMEOUT=1e3,Wd.MAX_LOADING_ERRORS=3,function(e){e.PLAYER_READY="ready",e.PLAYER_RESIZE="resize",e.PLAYER_FULLSCREEN="fullscreen",e.PLAYER_DOCK="dock",e.PLAYER_PLAY="play",e.PLAYER_PAUSE="pause",e.PLAYER_STOP="stop",e.PLAYER_ENDED="ended",e.PLAYER_SEEK="seek",e.PLAYER_ERROR="playererror",e.PLAYER_TIMEUPDATE="timeupdate",e.PLAYER_VOLUMEUPDATE="volumeupdate",e.PLAYER_DESTROY="destroy",e.ADVERTISEMENT_STARTED="advertisement:started",e.ADVERTISEMENT_PAUSED="advertisement:paused",e.ADVERTISEMENT_RESUMED="advertisement:resumed",e.ADVERTISEMENT_ENDED="advertisement:ended",e.ADVERTISEMENT_ERROR="advertisement:error"}(zd||(zd={}));var qd=n(7007);let Xd,Qd;const Zd=async()=>{if(!Xd){Qd||(Qd=(async()=>{window.ramblerIdHelper=window.ramblerIdHelper||[],await Promise.all([new Promise((e=>{window.ramblerIdHelper.push((()=>{Xd=window.ramblerIdHelper,e()}))})),(0,q.k0)("https://id.rambler.ru/rambler-id-helper/auth_events.js")])})());try{await Qd}catch(e){}}return Xd},Jd=async()=>{const e=await Zd();return new Promise(((t,i)=>{e.getSessionToken(((e,s)=>{s?i(s):t(e)}))}))},ec=(()=>{let e;return()=>(e||(e=(async()=>{window.userID=window.userID||[];try{const[e]=await Promise.all([new Promise((e=>{window.userID.push((()=>{e(new window.userID)}))})),(0,q.k0)("https://ssp.rambler.ru/user-id-sdk.js")]);return e}catch(t){throw e=void 0,t}})()),e)})(),tc=async()=>{try{return(await ec()).getFingerPrint()}catch(e){return""}};var ic=n(5250),sc=n(9987);class nc extends qd.EventEmitter{constructor(){super(...arguments),this.startTime=Date.now(),this.getSessionToken=Jd,this.getCookie=ic.R,this.setCookie=ic.T,this.activateTop100=sc.ez,this.sendCustomVars=sc.yP,this.getFingerPrintUserId=tc}getStartTime(){return this.startTime}setPlayerId(e){this.playerId=e}}class rc extends nc{constructor(e){super(),this.docked=!1,this.getVisibleArea=()=>new Promise((e=>{this.ampIntegration.getIntersection((t=>{const{offsetWidth:i,offsetHeight:s}=document.documentElement,n=s*(this.docked?1:t.intersectionRatio);e({width:i,height:n,left:0,top:0,right:i,bottom:n})}))})),this.getEmbedVisibleArea=()=>this.getVisibleArea(),this.subscribePageScroll=e=>()=>null,this.subscribeVisibleAreaChange=e=>{const t=window.setInterval((async()=>{const t=await this.getVisibleArea();e(t)}),2e3);return()=>{clearInterval(t)}},this.ampIntegration=e,this.ampIntegration.method("showcontrols",(()=>{this.docked=!1})),this.ampIntegration.method("hidecontrols",(()=>{this.docked=!0}))}}const oc=e=>Boolean(e.amp),ac=async e=>{const t=await new Promise((e=>{window.AmpVideoIframe=window.AmpVideoIframe||[],window.AmpVideoIframe.push(e),(0,q.k0)("https://cdn.ampproject.org/video-iframe-integration-v0.js")})),i=new rc(t),s=new Wd(Object.assign(Object.assign({},e),{provider:i,docking:!1}));let n=!1;t.method("play",(()=>s.play())),t.method("pause",(()=>s.pause())),t.method("mute",(()=>s.mute())),t.method("unmute",(()=>s.unmute())),t.method("fullscreenenter",(()=>!n&&s.toggleFullscreen())),t.method("fullscreenexit",(()=>n&&s.toggleFullscreen())),s.on(zd.PLAYER_READY,(()=>{t.postEvent("canplay"),0===s.getVolume()&&t.postEvent("muted")})),s.on(zd.PLAYER_PLAY,(()=>t.postEvent("playing"))),s.on(zd.PLAYER_PAUSE,(()=>t.postEvent("pause"))),s.on(zd.PLAYER_ENDED,(()=>t.postEvent("ended"))),s.on(zd.PLAYER_FULLSCREEN,(e=>{n=e})),s.on(zd.PLAYER_VOLUMEUPDATE,(e=>t.postEvent(0===e?"muted":"unmuted"))),s.on(zd.PLAYER_RESIZE,(e=>{window.parent.postMessage({sentinel:"amp",type:"embed-size",height:e.height},"*")})),s.on(zd.ADVERTISEMENT_STARTED,(()=>{t.postEvent("playing"),t.postEvent("ad_start")})),s.on(zd.ADVERTISEMENT_PAUSED,(()=>t.postEvent("pause"))),s.on(zd.ADVERTISEMENT_RESUMED,(()=>t.postEvent("playing"))),s.on(zd.ADVERTISEMENT_ENDED,(()=>t.postEvent("ad_end")))};class lc extends nc{getVisibleArea(){return Promise.resolve({})}getEmbedVisibleArea(){return this.getVisibleArea()}subscribePageScroll(e){return()=>null}subscribeVisibleAreaChange(e){return()=>null}}const dc=e=>!0,cc=e=>{const t=new lc;new Wd(Object.assign(Object.assign({},e),{provider:t,docking:!1,[z.gM]:!1,[z.yN]:!1}))};var hc=n(1687),uc=n(2633);const fc=e=>Boolean(e.widgetId&&window!==window.top),pc=e=>{(0,hc._s)({async initialize(){this.player=new Wd(Object.assign(Object.assign({},e),{provider:this.provider}));try{await new Promise(((e,t)=>{this.player.once(zd.PLAYER_READY,e),this.player.once(zd.PLAYER_ERROR,t)})),this.provider.once("widgetShown",(()=>{this.provider.emit(zd.PLAYER_READY)}))}catch(e){this.provider.once("widgetShown",(()=>{this.provider.emit(zd.PLAYER_ERROR,e)}))}finally{Object.keys(zd).forEach((e=>{const t=zd[e];this.player.on(t,((...e)=>{this.provider.emit(t,...e)}))}))}}},{toggleFullscreen(){this.player.toggleFullscreen()},resize(e){this.player.resize(e)},play(){this.player.play()},pause(){this.player.pause()},stop(){this.player.stop()},seek(e){this.player.seek(e)},seekPercentage(e){this.player.seekPercentage(e)},mute(){this.player.mute()},unmute(){this.player.unmute()},setVolume(e){this.player.setVolume(e)},configure(e){e.id=(0,uc.x)(e.id),this.player.configure(e)},isReady(){return this.player.isReady},isPlaying(){return this.player.isPlaying()},getVolume(){return this.player.getVolume()},getCurrentTime(){return this.player.getCurrentTime()},getStartTimeOffset(){return this.player.getStartTimeOffset()},getDuration(){return this.player.getDuration()},getSourceLink(){return this.player.getSourceLink()}})};var gc,mc=n(4774),vc={};vc.styleTagTransform=Ml(),vc.setAttributes=Pl(),vc.insert=kl().bind(null,"head"),vc.domAPI=Ll(),vc.insertStyleElement=Dl(),Cl()(mc.A,vc),mc.A&&mc.A.locals&&mc.A.locals;const Ac=[i,r,s];(0,Y.hD)(),null!==(gc=n.g.ResizeObserver)&&void 0!==gc||(n.g.ResizeObserver=j);const{href:Ec,hash:yc,protocol:Tc,hostname:bc}=window.location,Sc=(0,K.J1)({protocol:Tc,host:bc}),_c=(0,K.al)(Ec),Cc=(0,K.al)(`${Sc}${yc.replace(/^#/,"?")}`),Rc=Object.assign(Object.assign({},_c),Cc),Lc=(0,z.qg)(Rc);Lc.parent=document.createElement("div"),document.body.appendChild(Lc.parent);const Ic=Ac.find((e=>e.isSupports(Lc)));if(!Ic)throw new Error("supported player integration not found");Lc.referrer&&(0,Y.NA)("referrer",Lc.referrer),(0,H.o)(Boolean(Lc.debug)),(0,W.Q)(),Ic.registerIFrame(Lc)})()})(); //# sourceMappingURL=player-2de6c55daa4fa74feaaa.js.map
OSZAR »