@flowplayer/player 3.7.2-rc.0 → 3.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/core.js +1 -1
- package/default.js +1 -1
- package/embed.js +2 -281
- package/package.json +2 -2
- package/plugins/ads.js +1 -1
- package/plugins/analytics.js +1 -1
- package/plugins/health.js +1 -1
- package/plugins/hls.js +1 -280
package/embed.js
CHANGED
|
@@ -1,286 +1,7 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).flowplayer=e()}(this,(function(){"use strict";const t=[],e=[];function r(){const t="undefined"!=typeof document&&"undefined"!=typeof window,e=t?navigator.userAgent:"",r=/iP(hone|od)/i.test(e)&&!/iPad/.test(e)&&!/IEMobile/i.test(e),i=/Android/.test(e)&&!/Firefox/.test(e),n=/^((?!chrome|android).)*safari/i.test(e),s=/SamsungBrowser/.test(e),a=s&&/SMART-TV/.test(e);return{controls:!r,video:function(e){return t&&document.createElement("video").canPlayType(e)},lang:t&&window.navigator.language,android:i,iphone:r,safari:n,ios:t&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,samsung:s,samsung_tv:s&&a,touch:"ontouchstart"in window,tizen:"tizen"in window,webOS:"webos"in window}}const i="error",n="click",s="dblclick",a="load",o="mouseenter",l="mouseleave",d="mousemove",u="touchmove",c="touchend",h="fullscreenenter",f="fullscreenexit",p="loadedmetadata",g="loadeddata",v="progress",m="loadstart",y="pause",E="playing",T="waiting",_="canplay",S="ended",b="seeked",A="seeking",L="recover",w="reap",D="config",R="landscape",I="portrait",k="retry";var O=Object.freeze({__proto__:null,MOUNT:"mount",ERROR:i,CONTEXT_MENU:"contextmenu",CLICK:n,DBL_CLICK:s,KEYUP:"keyup",KEYDOWN:"keydown",LOAD:a,MOUSE_ENTER:o,MOUSE_LEAVE:l,MOUSE_UP:"mouseup",MOUSE_DOWN:"mousedown",MOUSE_MOVE:d,TOUCH_START:"touchstart",TOUCH_MOVE:u,TOUCH_END:c,TOUCH_CANCEL:"touchcancel",RESIZE:"resize",SCROLL:"scroll",FULLSCREEN_ENTER:h,FULLSCREEN_EXIT:f,FULLSCREEN_CHANGE:"fullscreenchange",WEBKIT_NEEDKEY:"webkitneedkey",METADATA:p,DATA:g,PROGRESS:v,TIME_UPDATE:"timeupdate",LOAD_START:m,VOLUME_CHANGE:"volumechange",PAUSE:y,PLAYING:E,PLAY:"play",WAITING:T,CAN_PLAY:_,ENDED:S,SEEKED:b,SEEKING:A,DURATION_CHANGE:"durationchange",BEFORE_PLAY:"beforeplay",BEFORE_PAUSE:"beforepause",STATE:"state",CUEPOINTS:"cuepoints",CUEPOINT_START:"cuepointstart",CUEPOINT_END:"cuepointend",VIEW_ENTER:"viewenter",VIEW_LEAVE:"viewleave",SOURCE:"src",RECOVER:L,REAP:w,CONFIG:D,QUALITIES:"qualities",VIDEO_TRACKS:"videoTracks",SET_QUALITY:"quality:set",VIDEO_TRACK_SELECT:"tracks:video:select",NON_RECOVERABLE_ERROR:"error:fatal",RECOMMENDATIONS_READY:"recommendationsready",AUDIO_ONLY_SOURCE:"audioonlysource",LANDSCAPE:R,PORTRAIT:I,RENDER_PLUGIN:"renderplugin",DVR:"dvr",LIVE:"live",SEEK_QUEUED:"seek:queued",SEEK_CANCEL:"seek:cancel",PLUGIN_REGISTERED:"plugin:registered",REMOTE_SESSION_STARTED:"remotesession:started",REMOTE_SESSION_ENDED:"remotesession:ended",INTERSECTIONCHANGE:"intersectionchange",RETRY:k});const C="flowplayer-ui",P="flowplayer-logo",x="flowplayer-control",M="flowplayer-live-status",N="flowplayer-elapsed-time",F="flowplayer-timeline-bar",U="flowplayer-volume-bar",B="flowplayer-header",G="flowplayer-header-right-zone",H="flowplayer-middle",j="flowplayer-middle-zone",V="flowplayer-wait",K="flowplayer-small-play-icon",q="flowplayer-small-pause-icon",W="flowplayer-play-icon",z="flowplayer-pause-icon",Y="flowplayer-rewind-icon",X="flowplayer-volume-icon",Q="flowplayer-live-countdown";var $=Object.freeze({__proto__:null,SUBTITLES_MENU:"flowplayer-subtitles-menu",SHARE_MENU:"flowplayer-share-menu",SPEED_MENU:"flowplayer-speed-menu",QUALITY_MENU:"flowplayer-quality-menu",AUDIO_MENU:"flowplayer-audio-menu",VIDEO_MENU:"flowplayer-video-menu",UI:C,LOGO:P,CONTROL:x,CONTROL_BUTTONS:"flowplayer-control-buttons",LIVE_STATUS:M,ELAPSED:N,TIMELINE:F,CONTROL_DURATION:"flowplayer-control-duration",VOLUME_CONTROL:"flowplayer-volume-control",VOLUME_BAR:U,HEADER:B,HEADER_LEFT_ZONE:"flowplayer-header-left-zone",HEADER_RIGHT_ZONE:G,HEADER_DURATION:"flowplayer-header-duration",MIDDLE:H,MIDDLE_ZONE:j,WAIT:V,MIDDLE_BUTTONS:"flowplayer-middle-buttons",MIDDLE_LEFT_ZONE:"flowplayer-middle-left-zone",MIDDLE_RIGHT_ZONE:"flowplayer-middle-right-zone",ENDSCREEN_INTERSTITIAL:"flowplayer-endscreen-interstitial",ENDSCREEN_UP_NEXT:"flowplayer-endscreen-up-next",ENDSCREEN_GRID:"flowplayer-endscreen-grid",PLAYLIST_INTERSTITIAL:"flowplayer-playlist-interstitial",AIRPLAY_ICON:"flowplayer-airplay-icon",CHROMECAST_ICON:"flowplayer-chromecast-icon",SMALL_PLAY_ICON:K,SMALL_PAUSE_ICON:q,PLAY_ICON:W,PAUSE_ICON:z,FULLSCREEN_ENTER_ICON:"flowplayer-fullscreen-enter-icon",FULLSCREEN_EXIT_ICON:"flowplayer-fullscreen-exit-icon",SKIP_NEXT_ICON:"flowplayer-skip-next-icon",SKIP_PREVIOUS_ICON:"flowplayer-skip-previous-icon",FAST_FORWARD_ICON:"flowplayer-fast-forward-icon",REWIND_ICON:Y,SHARE_ICON:"flowplayer-share-icon",VOLUME_ICON:X,MUTE_ICON:"flowplayer-mute-icon",UNMUTE_ICON:"flowplayer-unmute-icon",CLOSE_ICON:"flowplayer-close-icon",FACEBOOK_ICON:"flowplayer-facebook-icon",TWITTER_ICON:"flowplayer-twitter-icon",LINK_ICON:"flowplayer-link-icon",EMBED_ICON:"flowplayer-embed-icon",LIVE_COUNTDOWN:Q,PLAYLIST_CONTROLS:"flowplayer-playlist-controls",THUMBNAILS_CAROUSEL:"flowplayer-thumbnails-carousel",ERROR_COMPONENT:"flowplayer-error",TV_MENU:"flowplayer-tv-menu",CUE_COMPONENT:"flowplayer-cue"});const Z="is-playing",J="is-paused",tt="is-loaded",et="is-loading",rt="is-starting",it="is-seeking",nt="is-ended",st="is-live",at="is-waiting",ot="is-live-seeked",lt="no-timeline",dt="will-play",ut="will-pause",ct="is-touched",ht="is-in-viewport",ft="is-source-processing";var pt=Object.freeze({__proto__:null,PLAYING:Z,FULLSCREEN:"is-fullscreen",PAUSED:J,MUTED:"is-muted",LOADED:tt,LOADING:et,STARTING:rt,SEEKING:it,GRABBING:"is-grabbing",DISABLED:"is-disabled",SMALL:"is-small",TINY:"is-tiny",RTL:"is-rtl",TV:"is-tv",ENDED:nt,LIVE:st,ERRORED:"is-error",WAITING:at,AUTOPLAY:"is-autoplay",NO_AUTOPLAY:"no-autoplay",SEAMLESS:"is-seamless",TOGGLING:"is-toggling",LIVE_SEEKED:ot,NO_DVR:lt,HAS_POSTER:"has-poster",WILL_PLAY:dt,WILL_PAUSE:ut,MENU_OPENED:"has-menu-opened",TOUCHED:ct,HOVERED:"is-hovered",TOUCH_DEVICE:"is-touch-device",WILL_SEEK:"will-seek",SEEKABLE:"is-seekable",IN_VIEWPORT:ht,NO_CONTROLS:"no-controls",DESTROYED:"is-destroyed",IS_SOURCE_PROCESSING:ft});function gt(t){this.message=t}gt.prototype=new Error,gt.prototype.name="InvalidCharacterError";var vt="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new gt("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,i,n=0,s=0,a="";i=e.charAt(s++);~i&&(r=n%4?64*r+i:i,n++%4)?a+=String.fromCharCode(255&r>>(-2*n&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return a};var mt=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(vt(t).replace(/(.)/g,(function(t,e){var r=e.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(e)}catch(t){return vt(e)}};function yt(t){this.message=t}yt.prototype=new Error,yt.prototype.name="InvalidTokenError";var Et=function(t,e){if("string"!=typeof t)throw new yt("Invalid token specified");var r=!0===(e=e||{}).header?0:1;try{return JSON.parse(mt(t.split(".")[r]))}catch(t){throw new yt("Invalid token specified: "+t.message)}};Et.InvalidTokenError=yt;const Tt=new Map,_t=(t,e)=>new(((t,e)=>{const r=t.get(e);if(!r)throw new Error(`no flowplayer component with the name ${e} exists`);const i=window.customElements.get(e);if(!i)throw new Error(`no default flowplayer component with the name ${e} exists`);const n=window.customElements.get(r);return"function"!=typeof n?i:n})(t._customElements,e))(t),St=(t,e,r)=>{window.customElements.get(e)||window.customElements.define(e,r),t.customElements.get(e)||t.customElements.set(e,e)};var bt,At;!function(t){t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=4]="HIGH"}(bt||(bt={})),function(t){t[t.OFF=0]="OFF",t[t.ON=1]="ON",t[t.AUDIO_REQUIRED=2]="AUDIO_REQUIRED"}(At||(At={}));function Lt(t,e,r){const i="boolean"==typeof r;if("boolean"!=typeof r&&(r=!!t.hasState(ut)||t.paused),function(t,e,r){const i=t.poll(e?"beforeplay":"beforepause",{forced:r});return i&&i.defaultPrevented}(t,r,i))return Promise.resolve();if(!r)return t.hasState(dt)?(t.setState(ut,!0),t.setState(dt,!1),Promise.resolve()):Promise.resolve(t.pause());if(0==t.reaper)return Promise.resolve();const n=t.reaper.get("__pending_play");return t.paused||n?n?(n.src!==Dt(t.original_src)&&wt(t),n):(function(t){return(0==t.networkState||0==t.readyState)&&t.currentSrc==Dt(t.original_src)}(t)&&wt(t),(t=>t.autoplay&&At.AUDIO_REQUIRED&t.autoplay)(e)?function(t){t.muted=!1,0==t.volume&&(t.volume=1);return t.play().catch(t=>{console.warn("[flowplayer/play] autoplay audio required\n%s",t.message)})}(t):t.play().then(()=>{t.hasState(ut)&&t.togglePlay(!1)}).catch(e=>(console.warn("[flowplayer/play] attempting muted autoplay\n%s",e.message),t.muted=!0,t.volume=0,t.play()))):(t.setState(ut,!1),!t.hasState(Z)&&t.setState(dt,!0),Promise.resolve())}function wt(t){t.currentSrc.match(/^blob:/)||t.load()}function Dt(t){const e=document.createElement("a");return e.href=t,e.href}function Rt(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(t);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(r[i[n]]=t[i[n]])}return r}function It(t){const e=document.createElement("a");e.href=t;const r=e.pathname&&e.pathname.split(".");return r.length>1&&r[r.length-1]}function kt(t){switch(t){case"video/mpd":return"application/dash+xml";case"video/m3u8":return"application/x-mpegurl";default:return t}}const Ot=t=>{var{src:e}=t,r=Rt(t,["src"]);return[Object.assign({src:e,type:e?kt("video/"+It(e)):""},r)]};function Ct(t){return Ot({src:t})}function Pt(t){var{src:e,type:r}=t,i=Rt(t,["src","type"]);return e&&r?[Object.assign({src:e,type:r},i)]:r&&!e?[Object.assign({type:r},i)]:Ot(Object.assign({src:e},i))}var xt;function Mt(t,e,r,i={safari:!1}){const n=Nt(r);return function(t){[it,ut,dt,Z,J,et,tt,ot].forEach(e=>t.setState(e,!1)),t.setState(rt,!0)}(t),Array(...Array(n.length)).map((t,e)=>e).some(r=>{const s=n[r];if(xt.Ok==function(t,e,r){t.emit("src",r),"string"==typeof r.src&&(t.original_src=r.src);const i=function(t,e,r){return t.plugins.filter(t=>{return(e=t)&&"wants"in e;var e}).find(t=>t.wants(r.src||"",r,e))}(t,e,r);return t.setOpts({is_native:!i}),i?(i.onload(e,t.root,t,r),xt.Ok):xt.Err}(t,e,s)||xt.Ok==function(t,e,r,i={safari:!1}){var n;/^audio\//.test(r.type||"")&&t.emit("audioonlysource");e.start_time&&(r.src=r.src+"#t="+e.start_time);if(""==t.canPlayType(r.type||""))return xt.Err;if(r.drm&&(!r.drm["com.apple.fps.1_0"]||!i.safari))return xt.Err;"string"==typeof r.src&&(t.preload=e.autoplay?"auto":null!==(n=e.preload)&&void 0!==n?n:"auto",t.src=r.src,e.autoplay&&i.safari&&t.load(),"none"!==t.preload&&t.setState(et,!0));return xt.Ok}(t,e,s,i))return!0;r==n.length-1&&"string"==typeof s.src&&(t.src=s.src)}),function(t,e){!function(t,e){if(!t.currentSrc)return;if("none"==t.opt("preload"))return;if(e.autoplay&&e.autoplay>0)return;t.load()}(t,e)}(t,e),t}function Nt(t){return"string"==typeof t?Ct(t):Array.isArray(t)||"object"!=typeof t?t.reduce((function(t,e){return"string"==typeof e&&(e=Ct(e)),"object"!=typeof e||Array.isArray(e)||(e=Pt(e)),t.concat(e)}),[]):Pt(t)}!function(t){t[t.Err=0]="Err",t[t.Ok=1]="Ok"}(xt||(xt={}));const Ft=[w,A,"src","seek:cancel"];var Ut;function Bt(t,e,r){return isNaN(t.duration)||isNaN(t.currentTime)?{}:(e.offset+=r,0==e.offset?Gt(t,e):(e.timer&&clearTimeout(e.timer),e.timer=setTimeout((function(){0!=t.reaper&&(t.currentTime=function(t,e,r=0){return Math.max(Math.min(e,t),r)}(t.currentTime+e.offset,t.duration),e.timer=0,Gt(t,e))}),1e3),function(t,e){t.setState("will-seek",!0),t.setState(Ut.BACKWARD,e.offset<0),t.setState(Ut.FORWARD,e.offset>0)}(t,e),t.emit("seek:queued",e),e))}function Gt(t,e){e.timer&&clearTimeout(e.timer),e.timer=e.offset=0,function(t){t.setState(Ut.FORWARD,!1),t.setState(Ut.BACKWARD,!1),t.setState("will-seek",!1)}(t)}function Ht(t,e){const r=t._customElements.get(e);return r&&t.root.querySelector(r)||void 0}function jt(){if("undefined"==typeof document)return!1;const t=document.documentElement;return t&&"rtl"==t.getAttribute("dir")}function Vt(...t){const e=document.createElement("div");return 0==t.length||e.classList.add(...t),e}function Kt(t,e,r){const i=function(t){return Array.isArray(t)?t.slice(0):t.split(".")}(e);for(;i.length;){if(null==t)return r;const e=i.shift();if("string"!=typeof e)return r;t=t[e]}return null==t?r:t}function qt(t){const e="number"==typeof t?t:parseInt(t,10);return(e>9?"":"0")+e}function Wt(t){if(isNaN(t)||t>=Number.MAX_SAFE_INTEGER)return"";const e=t<0?"-":"";t=Math.round(Math.abs(t));const r=Math.floor(t/3600);let i=Math.floor(t/60);return t-=60*i,r>=1?(i-=60*r,e+r+":"+qt(i)+":"+qt(t)):e+qt(i)+":"+qt(t)}!function(t){t.FORWARD="forward",t.BACKWARD="backward"}(Ut||(Ut={}));const zt=navigator.languages||[navigator.language];function Yt(t,e,r){const i={};return r=e.lang||r,t[r]&&(i[r]=t[r]),function(){try{return zt.reduce((t,e)=>~e.indexOf("-")?t.concat(e,e.split("-")[0]):t.concat(e),[])}catch(t){return[]}}().forEach((function(e){t[e]&&!i[e]&&(i[e]=t[e])})),Object.values(i)}const Xt=[1e7]+""+-1e3+-4e3+-8e3+-1e11,Qt=()=>"undefined"==typeof crypto?"":Xt.replace(/[018]/g,t=>(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16));let $t="";!function(){let t=!1;try{const e=Object.defineProperty({},"passive",{get:function(){t=!0}});window.addEventListener("testPassive",null,e),window.removeEventListener("testPassive",null,e)}catch(t){}}();const Zt=["touchstart","touchmove"];function Jt(t,e){const r=new CustomEvent(t,{detail:e,cancelable:!0});return e&&Object.defineProperty(r,"data",{get:()=>e}),r}function te(t,e,r){const i=Jt(e,r);return t.dispatchEvent(i),t}function ee(t,e,r){const i=Jt(e,r);return t.dispatchEvent(i),i}function re(t,e,r,i){Array.isArray(e)?e.forEach(e=>ie(t,e,r,i)):ie(t,e,r,i)}function ie(t,e,r,i){if(n=e,!~Zt.indexOf(n))return t.addEventListener(e,r,i),t;var n;const s=Object.assign(i||{},{passive:!0});return t.addEventListener(e,r,s),t}function ne(t,e,r,i){return re(t,e,r,Object.assign(i||{},{once:!0}))}class PlayerStorage{constructor(t,e){this.implementation=t,e&&e.keys().forEach(t=>{"string"==typeof e.implementation[t]&&this.implementation.setItem(t,e.implementation[t])})}keys(){var t;const e=[];for(var r=0;r<this.implementation.length;r++)(null===(t=this.implementation.key(r))||void 0===t?void 0:t.startsWith("flowplayer/"))&&e.push(this.implementation.key(r));return e}removeItem(t){try{this.implementation.removeItem("flowplayer/"+t)}catch(t){}}getItem(t){try{return this.implementation.getItem("flowplayer/"+t)}catch(t){return null}}setItem(t,e){try{this.implementation.setItem("flowplayer/"+t,e)}catch(t){}}clear(){try{this.keys().forEach(t=>this.implementation.removeItem(t))}catch(t){}}get length(){try{return this.keys().length}catch(t){return 0}}key(t){try{return this.implementation.key(t)}catch(t){return null}}}class InMemoryStorage{constructor(){this.pairs=[]}get length(){return this.pairs.length}clear(){this.pairs=[]}getItem(t){var e;return(null===(e=this.pairs.find(e=>e[0]===t))||void 0===e?void 0:e[1])||null}key(t){return this.pairs[t][0]||null}removeItem(t){this.pairs=this.pairs.filter(e=>e[0]!==t)}setItem(t,e){this.removeItem(t),this.pairs.push([t,e])}}const se={preload:"none",rtl:!1,controls:!0},ae=["loop","muted","preload"];function oe(t,i,n){let s;n.live_state={dvr_window:void 0,get dvr(){return s},set dvr(e){s=e;const r=!(!t.live||e);n.hasState(lt)!=r&&n.setState(lt,r)}},n._storage=new PlayerStorage(["localStorage","sessionStorage"].map(t=>{try{const e=window[t];return e.getItem(""),e}catch(e){return console.debug(`Access to window.${t} denied, trying next option`),null}}).find(t=>!!t)||new InMemoryStorage),n.toJSON=function(){return{duration:n.duration,volume:n.volume,currentTime:n.currentTime,states:n.root.className}},n.setSrc=function(e){return Mt(n,t,e,r())},n.playerState=n.playerState||{},n.setState=function(t,e){if(n.playerState[t]===!!e)return n;const r=Object.assign({},n.playerState,{[t]:e});return n.playerState=r,te(n,"state",n.playerState),n},n.createComponents=function(...t){return Array.from({length:t.length}).map((e,r)=>_t(this,t[r]))},n.hasState=function(t){return!!n.playerState[t]},n.transitionState=function(t,e,r){!n.hasState(t)&&n.hasState(e)||(r=0),r&&n.setState("is-toggling",!0),n.setState(e,!1),n.setState(t,!0),r&&setTimeout((function(){n.setState("is-toggling",!1)}),r)},n.emit=(t,e)=>(te(n,t,e),n),n.on=(t,e)=>(re(n,t,e),n),n.once=(t,e)=>(ne(n,t,e),n),n.off=(t,e)=>{var r,i;return r=t,i=e,n.removeEventListener(r,i),n},n.poll=(t,e)=>ee(n,t,e),n.togglePlay=function(e){return Lt(n,t,e)},n.toggleMute=function(t){t=null==t?!n.muted:!!t,n.muted=t,n.muted||n.volume||(n.volume=1),te(n,"volumechange")},n.toggleDisable=function(t){t=null==t?!n.disabled:!!t,n.setState("is-disabled",t),n.disabled=t},n.destroy=function(){n.pause();const t=e.indexOf(n);~t&&e.splice(t,1),setTimeout((function(){n.setSrc([]),n.reaper&&n.reaper.clear(),te(n,w),n.setState("is-destroyed",!0)}),0)},n.setAttrs=function(t){return ae.forEach(e=>{if(!(e in t))return;const r=t[e];r?n.setAttribute(e,r.toString()):n.removeAttribute(e)}),n},n.opt=function(e,r){return r=void 0===r?Kt(se,e):r,Kt(t,e,r)},n.i18n=function(t,e){if(!n.reaper)return"";const r=n.reaper.get("translations");return r?function t(e,r,i,n){return(n=n||0)>=e.length?i:Kt(e[n],r,t(e,r,i,n+1))}(r,t,e||""):e||""},n.setOpts=function(e){Object.assign(t,e),t.live&&!n.hasState(st)&&(n.setState(lt,!0),te(n,"live")),"disabled"in e&&void 0!==e.disabled&&n.toggleDisable(e.disabled),"muted"in e&&void 0!==e.muted&&n.toggleMute(e.muted),"dvr"in t&&(n.live_state.dvr=n.opt("dvr"));const r=!!t.autoplay&&!n.hasState("no-autoplay");n.setState("is-autoplay",r),n.setState("is-rtl",n.opt("rtl",function(t){if(!t)return jt();const e=t.getAttribute("dir");return e?"rtl"==e:jt()}(i))),n.setState(st,!!t.live),n.setState("has-poster","string"==typeof t.poster&&t.poster.length>0),n.setState("is-seekable",!!t.seekable),n.setState("no-controls",0==t.controls),i.style.backgroundImage=n.hasState("has-poster")?"url('"+t.poster+"')":"",te(n,D,t)},n.renderPlugin=function(t){ee(n,"renderplugin",t).defaultPrevented||n.root.appendChild(t)};const a={offset:0,timer:0};var o,l;l=a,(o=n).on(Ft,(function(){Gt(o,l)})),n.enqueueSeek=function(t){if(0!=n.opts.seekable&&!(1==n.opts.disabled&&t>0))return Bt(n,a,t)},n.deviceId=function(){return function(t){if($t)return $t;try{const e=t.getItem("flowplayer/uuid");if(e)return e;const r=Qt();return t.setItem("flowplayer/uuid",r),r}catch(t){return $t=Qt()}}(n._storage)}}function le(t,e){const r=e.querySelector("video"),i=r||(t._video_element_callback?t._video_element_callback(t):document.createElement("video"));return i.classList.add("fp-engine"),i.playsInline=!0,r||e.append(i),i}var de="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function ue(t,e){if("object"==typeof exports&&"undefined"!=typeof module)return e;if(null===document.currentScript)return e;"flowplayer"in t||(t.flowplayer={extensions:[]});const r=t.flowplayer;return"function"==typeof r?(r(e),e):(Array.isArray(r.extensions)||(r.extensions=[]),~r.extensions.indexOf(e)||r.extensions.push(e),e)}function ce(){return"undefined"!=typeof window?window:void 0!==de?de:{}}const he=["localhost","127.0.0.1","0.0.0.0","s.codepen.io","cdpn.io","try.flowplayer.com"];function fe(t,e){return!!~he.indexOf(t)||t.indexOf(e)===t.length-e.length}fe.check_whitelist=function(t){return!!~he.indexOf(t)};const pe="production";function ge(t,e){const r={valid_jwt:!1,raw:"",data:{acl:0},exp:0};let i={c:"{}",exp:0};e=e||{};try{i=Et(t),r.valid_jwt=!0}catch(t){}return r.raw=t,r.data=JSON.parse(i.c),r.exp=i.exp,e.require_valid_token&&ge.validate(r),r}function ve(t){try{return ge.validate(t),{success:!0,message:""}}catch(t){return{success:!1,message:t.message}}}var me;function ye(t){return{grant:t,is_granted:e=>(t&e)===e}}function Ee({root:t,video:e,data:r}){e&&e.destroy(),console.error(new Error(r.details||r.reason)),t.innerHTML="",t.classList.remove("flowplayer"),t.classList.add("flowplayer-fatal"),t.style.removeProperty("background-image");const i=document.createElement("h2");i.textContent="Playback Error";const n=document.createElement("p");n.textContent="Are you the site owner?";const s=document.createElement("a");s.classList.add("troubleshoot"),s.target="_blank",s.href="https://docs.flowplayer.com/troubleshooting/player#"+r.reason,s.textContent="Troubleshoot?";const a=document.createElement("img");a.src="https://flowplayer.com/user/pages/images/logo-white.png",t.append(i,n,s,a)}ge.validate=function(t){if("string"==typeof t&&(t=ge(t)),!t||!t.raw){if(fe.check_whitelist(window.location.hostname)||"dev"===pe.toString())return!0;throw new Error("No token provided in configuration")}if(!t.valid_jwt)throw new Error("Invalid token provided");const e=window.location.hostname,r=fe.bind(null,e);if("dev"!==pe.toString()&&t.data.domain&&t.data.domain.length&&!t.data.domain.some(r))throw new Error("Domain not allowed");if("dev"!==pe.toString()&&1e3*t.exp-Date.now()<0)throw new Error("Expired token");return!0},ge.id=function(t){if(t)return"string"==typeof t&&(t=ge(t)),t.data.id},function(t){t[t.ADS=2]="ADS",t[t.ANALYTICS=4]="ANALYTICS",t[t.NO_METERING=8]="NO_METERING",t[t.DEVELOPER_PLAN=16]="DEVELOPER_PLAN",t[t.WOWZA_VIDEO=32]="WOWZA_VIDEO"}(me||(me={})),ye.of=ye,ye.from_token=function(t){const e=ge(t,{require_valid_token:!0});return ye.of(e.data.acl)},ye.permissions=me;function Te(t,e){const r=e.clientWidth;e.classList.toggle("is-small",r<600),e.classList.toggle("is-tiny",r<400)}function _e(t,e,i){let n=!0;e.classList.add("flowplayer"),Te(0,e),re(i,[m,"resize"],(function(){Te(0,e)})),re(i,"state",(function(){Object.entries(i.playerState).forEach((function([t,r]){e.classList.toggle(t,r)}))})),re(i,"timeupdate",(function(){i.setState(at,!i.hasState("is-casting")&&!i.hasState(rt)&&i.readyState<3)})),re(i,S,(function(e){setTimeout((function(){if(!e.defaultPrevented){if(t.rewind&&!i.loop){const e=i.src;t.autoplay&&(t.autoplay=0,i.setState("is-autoplay",!1)),i.setState(it,!0),ne(i,b,(function(){e===i.src&&(i.setState(it,!1),i.pause(),i.setState(rt,!0))})),i.currentTime=0}ne(i,"timeupdate",(function(){i.setState(nt,!1)})),i.transitionState(nt,Z,t.loop||t.rewind?0:300)}}),0)})),re(i,[A,b],(function(t){i.setState(it,t.type==A)})),re(i,"remotesession:ended",(function(t){setTimeout(()=>i.currentTime=t.detail.currentTime,0)})),re(i,S,(function(){i.setState(Z,!1),n=!0})),re(i,v,()=>{if(!i.opts.live||!i.opts.is_native)return;const t=i.seekable;0!=t.length&&i.emit("dvr/window",t.end(t.length-1)-t.start(0))}),re(i,r().ios?p:g,(function(){var t,e;i.setState(tt,!0),i.setState(et,!1);const r=i;0===(null===(t=r.videoTracks)||void 0===t?void 0:t.length)&&(null===(e=r.audioTracks)||void 0===e?void 0:e.length)>0&&i.emit("audioonlysource")})),re(i,"play",()=>{i.setState(dt,!0)}),re(i,[T,_,m],(function(e){if(!i.hasState(it)&&(e.type!=_||t.autoplay||i.setState(at,!1),e.type!=m||"none"!=i.opt("preload")||t.autoplay)){if(e.type==m&&t.autoplay)return ne(i,E,(function(){i.setState(at,!1)}));e.type!=T||i.hasState(tt)||i.setState(et,!0),i.setState(nt,!1),i.setState(at,e.type==T)}})),re(i,[E,y],(function(e){setTimeout(()=>{const t=new CustomEvent("flowplayer/"+e.type,{detail:i});document.dispatchEvent(t)},0);const r=e.type==E,s=i.currentTime==i.duration,a=r&&n&&t.autoplay||i.hasState(at);if(r&&(i.started=!0,n=!1),i.setState(at,!1).setState(rt,!1).setState(dt,!1),!r&&i.setState(ut,!1),s)return;const o=r?Z:J,l=r?J:Z;i.transitionState(o,l,a?0:300),r&&i.setState("no-autoplay",!1)}))}const Se=[0].concat(Array.from({length:100}).map((t,e)=>(e+1)/100));function be(t,e,r){if(!window.IntersectionObserver)return;const i={should_resume:!!t.autoplay,has_user_gesture:!1,locked:!1};[c,n].forEach(t=>ne(r,t,()=>i.has_user_gesture=!0)),re(r,"play",(function(){i.locked||(i.should_resume=!0)})),re(r,"src",(function(){i.should_resume=!!t.autoplay})),re(r,y,(function(){i.locked||(i.should_resume=!1)}));const s=()=>{setTimeout(()=>{r.setState(rt,!0),r.setState("is-autoplay",!1)},100)};re(r,_,()=>{if(t.autoplay)return r.hasState(ht)&&i.should_resume?r.togglePlay(!0).catch(s):void(t.autopause||r.hasState(ht)||!i.should_resume||ne(r,"viewenter",()=>{t.autoplay&&i.should_resume&&r.togglePlay(!0).catch(s)}))});const a=new IntersectionObserver(t=>{t.forEach(t=>{setTimeout(()=>{const e=t.intersectionRatio,i=r.hasState(ht);if(r.setState(ht,e>=.2),r.emit("intersectionchange",{ratio:e}),i===r.hasState(ht))return;const n=r.hasState(ht)?"viewenter":"viewleave";r.emit(n)},0)})},{threshold:Se});a.observe(e),r.on(w,()=>a.disconnect()),re(r,"viewenter",(function(){i.should_resume&&t.autopause&&!Ae()&&r.togglePlay(!0)})),re(r,"viewleave",(function(){if(!t.autopause||Ae())return;const e=!r.paused;i.locked=!0,r.pause(),setTimeout((function(){i.should_resume=e,i.locked=!1}),0)}))}function Ae(){return e.find(t=>t.hasState("is-casting"))}function Le(t,e){if(!window.ResizeObserver)return;const r=new ResizeObserver(t=>{const r=t[t.length-1];e.emit("resize",r)});r.observe(t),e.on(w,()=>r.disconnect())}function we(t){if("number"==typeof t&&!isNaN(t))return Number(t);if("string"==typeof t){const e=t.split(":");return Number(e[1])/Number(e[0])}return t}function De(t,e,r){const i=!!t.ratio,n=document.createElement("div");n.classList.add("fp-ratio"),e.append(n);let s=we(t.ratio||.5625);n.style.paddingTop=100*s+"%";const a=[g,p];r.on(a,(function(){if(i)return;const t=r.videoHeight&&r.videoWidth&&r.videoHeight/r.videoWidth;t&&r.setOpts({ratio:t})})),r.on(D,(function(){const e=r.videoHeight&&r.videoWidth&&r.videoHeight/r.videoWidth,i=we((null==t?void 0:t.ratio)||e||.5625);s!==i&&(s=i,n.style.paddingTop=100*i+"%")}))}class ExplorerPlan{constructor(){this.cleanUp=this.cleanUp.bind(this),this.render=this.render.bind(this),this.wireUp=this.wireUp.bind(this)}init(t,e,r){this.root=e,this.player=r,this.wireUp()}wireUp(){var t,e;this.cleanUp(),null===(t=this.player)||void 0===t||t.once(E,this.render),null===(e=this.player)||void 0===e||e.once(S,this.wireUp)}cleanUp(){var t,e,r,i;null===(e=null===(t=this._logo)||void 0===t?void 0:t.parentElement)||void 0===e||e.removeChild(this._logo),null===(r=this.player)||void 0===r||r.off(E,this.render),null===(i=this.player)||void 0===i||i.off(S,this.wireUp)}render(){var t,e,r;null===(e=null===(t=this._logo)||void 0===t?void 0:t.parentElement)||void 0===e||e.removeChild(this._logo);const i=(null===(r=this.root)||void 0===r?void 0:r.querySelector(".fp-ui"))||this.root;if(!i)return;const n=this._logo=document.createElement("a");n.href="https://explorer.flowplayer.com",n.target="_blank",Object.entries(Re).forEach(([t,e])=>{n.style.setProperty(t,e,"important")}),i.appendChild(n)}}const Re={display:"block",opacity:"1",visibility:"visible",width:"33%","padding-top":"9%",position:"absolute","z-index":"9999",bottom:"25%",left:"10%","background-size":"cover","background-image":"url(https://static.flowplayer.com/explorer/explorer.svg)"},Ie="flowplayer/"+E;function ke(t){const e=e=>{e.detail!==t&&!1===t.opt("multiplay")&&t.togglePlay(!1)};t.on(w,()=>document.removeEventListener(Ie,e)),document.addEventListener(Ie,e)}function Oe(t,e){const r=[];t.addEventListener("contextmenu",i=>{const n=i.timeStamp;for(r.push(n);r.length>3;)r.shift();r.length>=3&&r.every(t=>t-n<3e3)&&(console.debug("flowplayer/debug rendering info"),function(t,e){var r;!function(t){const e=t.querySelector(".debug-info");null==e||e.remove()}(t);const i=document.createElement("div");i.classList.add("debug-info");const n=Ce("flowplayer.version","3.7.2-rc.0");i.append(n);const s=null===(r=null==e?void 0:e.hls)||void 0===r?void 0:r.constructor;if(s&&s.version){const t=Ce("hls.version",s.version);i.append(t)}t.appendChild(i)}(t,e))})}const Ce=(t,e)=>{const r=document.createElement("div");r.classList.add("row",t);const i=document.createElement("span");i.classList.add("attr"),i.textContent=t;const n=document.createElement("span");return n.textContent=e,n.classList.add("value"),r.append(i,n),r};function Pe(t,e){const r=function(){try{return localStorage.getItem("flowplayer/debug")}catch(t){return""}}(),i=(i,...n)=>{try{const s=(null==e?void 0:e.debug)||r;s&&t.match(s)&&console.log(`flowplayer/${t} -- ${i}`,...n)}catch(t){console.warn(t)}};return i.log=i,i}function xe(t){return e=>{setTimeout((function(){if(!e.defaultPrevented)return t(e)}),0)}}const Me=Pe("core/retry");function Ne(t,e){const r={pending:void 0,count:0};t.on(i,i=>{e.retry&&void 0===r.pending&&(++r.count,r.pending=function(t,e){return setTimeout(()=>{t.hasState("is-destroyed")||(e.pending=void 0,[L,k].forEach(e=>t.emit(e)),Me("%s try",e.count))},3e3*e.count)}(t,r))}),t.on(E,()=>{r.count=0}),t.on(["src",L],()=>{r.pending&&(clearTimeout(r.pending),r.pending=void 0)}),t.on(k,xe(e=>{e.defaultPrevented||t.load()}))}const Fe=function(){const t=ce(),e=t.flowplayer?t.flowplayer:{extensions:[]};return Array.isArray(e.extensions)||(e.extensions=[]),e}();function Ue(r,i){if("function"==typeof r)return t.push(...[...arguments].filter(t=>"function"==typeof t)),Ue;"string"==typeof i&&(i={src:i}),i||(i={}),i.token||"string"!=typeof window.__FLOWPLAYER_TOKEN||(i.token=window.__FLOWPLAYER_TOKEN);const n="string"==typeof r?document.querySelector(r):r;if(!n)return console.error(new Error("Flowplayer: '"+r.toString()+"' not found"));const s=n.querySelector("video.fp-engine");if(s)return s;const a=ve(i.token);if(!a.success)return Ee({root:n,data:{reason:"token",details:a.message}});const o=new Map,l=le(i,n);l.reaper=o,l._customElements=Tt,Object.defineProperty(l,"token",{value:"string"==typeof i.token?ge.id(i.token):"",writable:!1}),l.addEventListener(w,()=>{o.clear(),l.reaper=0,delete l.root}),l.root=n,i.token&&ye.from_token(i.token).is_granted(ye.permissions.DEVELOPER_PLAN)&&t.push(ExplorerPlan),!~e.indexOf(l)&&e.push(l),oe(i,n,l),l.setAttrs(i),l.plugins=Ue.extensions.map(t=>new t(Ue,l)),_e(i,n,l),be(i,n,l),Le(n,l),De(i,n,l),ke(l),Oe(n,l),Ne(l,i),l.plugins.forEach(t=>{try{t.init(i,n,l)}catch(e){console.log("Error(plugin/%s)",t.constructor.name,e)}}),l.setOpts(i),l.opts=i,i.src&&l.setSrc(i.src);const d=l.readyState;return d>0&&l.currentSrc&&l.emit(p),d>2&&l.currentSrc&&l.emit(_),l.emit("mount"),l.on("error:fatal",(function(t){Ee({root:n,video:l,data:t.data||{}})})),setTimeout(te,0,document,"flowplayer:player:created",l),l}Object.assign(Ue,Fe),function(i){Array.isArray(i.extensions)&&i.extensions.forEach(e=>t.push(e)),i.customElements=Tt,i.defaultElements=$,i.version="3.7.2-rc.0",i.commit="25a53f1895cceddb2c6e8e5780fc14e86d28af25",i.instances=e,i.extensions=t,i.support=r,i.events=O,i.states=pt,i.jwt=Et,i.autoplay=At,i.quality=bt}(Ue),"object"==typeof document&&setTimeout(te,0,document,"flowplayer:umd",Ue);var Be="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Ge(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function He(t){var e={exports:{}};return t(e,e.exports),e.exports}var je=He((function(t,e){var r=Be&&Be.__assign||function(){return(r=Object.assign||function(t){for(var e,r=1,i=arguments.length;r<i;r++)for(var n in e=arguments[r])Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}).apply(this,arguments)};e.__esModule=!0,e.remove=e.downcase=e.pluck=e.merge=void 0,e.merge=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return t.reduce((function(t,e){return r(r({},t),e)}),{})},e.pluck=function(t){for(var r=[],i=1;i<arguments.length;i++)r[i-1]=arguments[i];return Object.keys(t).filter((function(t){return~r.indexOf(t)})).reduce((function(r,i){var n;return e.merge(r,((n={})[i]=t[i],n))}),{})},e.downcase=function(t){return(t||"").toString().toLowerCase()},e.remove=function(t,e){var r=t.lastIndexOf(e);return~r&&t.splice(r,1),t}})),Ve=He((function(t,e){var r=Be&&Be.__createBinding||(Object.create?function(t,e,r,i){void 0===i&&(i=r),Object.defineProperty(t,i,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,i){void 0===i&&(i=r),t[i]=e[r]}),i=Be&&Be.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),n=Be&&Be.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.hasOwnProperty.call(t,n)&&r(e,t,n);return i(e,t),e};e.__esModule=!0;var s=n(je),a=function(){function t(){this.pending=[],this.open=[],this.stats={failures:0,ttl:0}}return t.of=function(){return new t},t.is_empty=function(t){return 0==t.pending.length},t.is_high_water=function(e){return e.open.length==t.MAX_OPEN_REQUESTS},t.maybe_spawn_req=function(e){if(t.is_empty(e))return e;if(t.is_high_water(e))return e;try{var r=t.lpop(e);r&&t.request(e,r)}catch(t){}},t.increment_failures=function(e){return e.stats.failures++,e.stats.failures>t.MAX_FAILURE_COUNT&&(e.stats.ttl=Date.now()+t.REQUEST_TTL_MS),e},t.handle_error=function(e,r){t.rm(e,r),t.increment_failures(e)},t.request=function(e,r){var i=r[0],n=r[1],s=r[2];if(!(Date.now()<e.stats.ttl)){var a=new XMLHttpRequest;e.open.push(a),a.timeout=t.REQUEST_TIMEOUT_MS,a.ontimeout=function(){t.handle_error(e,a)},a.onerror=function(r){t.handle_error(e,a)},a.onreadystatechange=function(){a.readyState==XMLHttpRequest.DONE&&t.rm(e,a),Math.floor(a.status/100)},a.onload=function(){t.rm(e,a),e.stats.failures&&e.stats.failures--},a.open(n,i),a.setRequestHeader("Content-Type","text/plain;charset=UTF-8");try{a.send(JSON.stringify(s))}catch(t){}}},t.rpush=function(e){for(var r=[],i=1;i<arguments.length;i++)r[i-1]=arguments[i];return r.forEach((function(r){e.pending.length>=t.MAX_PENDING||(e.pending.push(r),t.maybe_spawn_req(e))})),e},t.lpop=function(t){return t.pending.shift()},t.rm=function(t,e){return s.remove(t.open,e),t},t.MAX_OPEN_REQUESTS=3,t.MAX_PENDING=5,t.REQUEST_TIMEOUT_MS=4e3,t.REQUEST_TTL_MS=5e3,t.MAX_FAILURE_COUNT=3,t}();e.default=a})),Ke=He((function(t,e){var r=Be&&Be.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};e.__esModule=!0;var i=r(Ve);e.default=i.default.of()})),qe=He((function(t,e){e.__esModule=!0,e.prepare_url=e.URL_PARAM=void 0,e.URL_PARAM=/:([a-zA-Z_]+)/g,e.prepare_url=function(t,r){return t.url.replace(e.URL_PARAM,(function(e){if((e=e.slice(1,e.length))in r)return r[e].toString();t.log.error(new Error("\n preparing url["+t.url+"] failed\n \n parameter["+e+"] not detected in params:\n \n "+JSON.stringify(r,null,2)+"\n "))}))}})),We=He((function(t,e){e.__esModule=!0,e.Log=void 0;var r=function(){function t(t){this.emitter=t}return t.prepare=function(t,e){var r=document.createEvent("Event");return r.initEvent(t,!1,!0),r.ns=t,r.data=e,r},t.of=function(e){return new t(e)},t.prototype.info=function(e){this.emitter.dispatchEvent(t.prepare(t.NAMESPACE.INFO,e))},t.prototype.error=function(e){this.emitter.dispatchEvent(t.prepare(t.NAMESPACE.ERROR,e))},t.prototype.warn=function(e){this.emitter.dispatchEvent(t.prepare(t.NAMESPACE.WARN,e))},t.NAMESPACE={INFO:"tracker:info",ERROR:"tracker:err",WARN:"tracker:warn"},t}();e.Log=r})),ze=He((function(t,e){var r;e.__esModule=!0,e.Verb=void 0,(r=e.Verb||(e.Verb={})).POST="POST",r.PUT="PUT",r.GET="GET"})),Ye=He((function(t,e){var r=Be&&Be.__createBinding||(Object.create?function(t,e,r,i){void 0===i&&(i=r),Object.defineProperty(t,i,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,i){void 0===i&&(i=r),t[i]=e[r]}),i=Be&&Be.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),n=Be&&Be.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.hasOwnProperty.call(t,n)&&r(e,t,n);return i(e,t),e},s=Be&&Be.__spreadArrays||function(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;var i=Array(t),n=0;for(e=0;e<r;e++)for(var s=arguments[e],a=0,o=s.length;a<o;a++,n++)i[n]=s[a];return i},a=Be&&Be.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};e.__esModule=!0;var o=a(Ke),l=a(Ve),d=n(qe),u=n(je),c=function(){function t(e,r){var i=this;void 0===r&&(r={});var n=this;if(this.emitter=e,this.url=r.url,this.log=We.Log.of(this.emitter),this.verb=r.verb,this.metadata=u.merge({},r.metadata||{}),this.rq=r.rq||o.default,this.events=r.events||[],this.required_keys=r.required_keys||[],this.optional_keys=r.optional_keys||[],this.listeners=[],this.valid_keys=this.required_keys.slice(0).concat(this.optional_keys),t.assert_emitter_api(this.emitter),void 0===t.verb[this.verb])throw new Error("invalid HTTP verb["+this.verb+"] passed");if("string"!=typeof this.url)throw new Error("invalid API url["+this.url+"] passed");t.TRACKERS.push(this),n.events.forEach((function(e){t.create_listener(i,e,(function(r){void 0===r&&(r={});var s=u.merge(n.metadata,{event_type:e},r.data||r),a=d.prepare_url(n,s),o=t.pluck_valid_keys(n,s),c=t.ensure_required_keys(n,o);if(c.length)return n.log.error("Tracker.validate_metadata() failed for \n Event["+e+"]\n missing keys: "+c+"\n payload:\n "+JSON.stringify(o,null,2));l.default.rpush(i.rq,[a,i.verb,o])}))}))}return t.of=function(e,r){return new t(e,r)},t.ensure_required_keys=function(t,e){return t.required_keys.filter((function(t){return!(t in e)}))},t.pluck_valid_keys=function(t,e){return u.pluck.apply(u,s([e],t.valid_keys))},t.merge_metadata=function(e,r){return void 0===r&&(r={}),e.metadata=t.pluck_valid_keys(e,u.merge(e.metadata,r)),e},t.assert_emitter_api=function(t){if("function"!=typeof(t||{}).addEventListener)throw new Error("Tracker() received an emitter that does not implement the addEventListener method");if("function"!=typeof(t||{}).removeEventListener)throw new Error("Tracker() received an emitter that does not implement the removeEventListener method")},t.create_listener=function(t,e,r){t.listeners.push([e,r]),t.emitter.addEventListener(e,r)},t.prototype.destroy=function(){var e=this;this.listeners.forEach((function(t){var r=t[0],i=t[1];return e.emitter.removeEventListener(r,i)})),delete this.rq,delete this.emitter,u.remove(t.TRACKERS,this)},t.prototype.put=function(e){return void 0===e&&(e={}),t.merge_metadata(this,e),this},t.TRACKERS=[],t.QUEUE=o.default,t.verb=ze.Verb,t}();e.default=c})),Xe=He((function(t,e){var r=Be&&Be.__createBinding||(Object.create?function(t,e,r,i){void 0===i&&(i=r),Object.defineProperty(t,i,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,i){void 0===i&&(i=r),t[i]=e[r]}),i=Be&&Be.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),n=Be&&Be.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.hasOwnProperty.call(t,n)&&r(e,t,n);return i(e,t),e},s=Be&&Be.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};e.__esModule=!0,e.API=e.Tracker=void 0;var a=s(Ye);e.Tracker=a.default;var o=n(qe);e.API=o})),Qe="ping",$e="display",Ze="view";const Je=["sitegroup_id","session_id","media_id","site_id","player_id","video_type"],tr=["created","position"],er=["player_version","created","source","category","category_id","autoplay","muted","customer_user_id"];function rr(t,e){return t.duration/1===t.duration&&Object.assign(e,function(t){const e=t/100;return{segment_duration:e,breakpoints:Array(...Array(100)).map((function(t,r){return Math.floor(r*e*1e3)/1e3}))}}(t.duration))}function ir(t,e,r){if(!e.segment_duration&&!rr(t,e))return;const i=function(t,e,r){const i=e.last_idx,n=r?99:nr(t,e);return e.last_idx=n,n<=i?[]:e.breakpoints.slice(i,99==n?100:n).map((function(t){return e.breakpoints.indexOf(t)}))}(t,e,r);0!=i.length&&t.emit(Qe,{position:i})}function nr(t,e){return Math.min(Math.floor(t.currentTime/e.segment_duration),99)}function sr(){try{return window.location!==window.parent.location?document.referrer:document.location.href}catch(t){return!1}}const ar="vod",or="live",lr=[$e,Qe,Ze];function dr(t,e,r){switch(null==e?void 0:e.kind){case"live":return function(t,e){const r=Date.now();r-e.last_tracked_ts<6e4||(e.last_tracked_ts=r,++e.ticks,t.emit(Qe,{position:60*e.ticks}))}(t,e);case"vod":return ir(t,e,"boolean"==typeof r&&r)}}function ur(t){const e=t.ads;return void 0!==e&&(void 0!==e.schedule&&("function"==typeof e.hasPreroll&&(e.currentRequests?e.currentRequests:!!e.adPlaying||!(!e.hasPreroll()||0!=e.nextIndex))))}class Analytics$1{init(t,e,r){if(!ye.from_token(t.token||"").is_granted(ye.permissions.ANALYTICS))return;if(r.hasState("consent-no-tracking"))return;if(r.analytics)return;const i=r.analytics={ticker:void 0,last_media_id:"",ended:!1},n={locked:!1,ttl:6e3,task:()=>{dr(r,i.ticker)}};const s={session_id:r.deviceId(),autoplay:r.autoplay,muted:r.muted,player_id:t.player_id,customer_user_id:t.customer_user_id,player_version:"3.7.2-rc.0"},a=Xe.Tracker.of(r,{verb:Xe.Tracker.verb.POST,url:"https://ptm.flowplayer.com/:video_type/:sitegroup_id/:event_type",events:lr,required_keys:Je,optional_keys:er.concat(tr).slice(0),metadata:s});r.on(w,(function(){a&&a.destroy()})),r.on(D,(function(e){if(!a)return;const n=Kt(e,"data.metadata",{});if(!n.media_id)return;const s=Kt(a,"metadata.media_id");if(s&&n.media_id==s)return;const o=Kt(t,"analytics",{});a.put(n),a.put(o);const l=Kt(t,"metadata.live_start_time",t.live)?or:ar;a.put({video_type:l,source:t.source||sr()||""}),i.ticker=t.live?{ticks:0,last_tracked_ts:Date.now(),kind:"live"}:{last_idx:0,segment_duration:0,breakpoints:[],kind:"vod"},i.ended=!1,r.emit($e)}));let o=0;r.on(E,(function(){if(!a)return;if(o||function(t,e){return t.metadata.media_id&&t.metadata.media_id==e.last_media_id}(a,i))return;a.put({muted:r.muted});const t=ur(r);if(t)return o=Promise.resolve(t).then((function(){i.last_media_id=a.metadata.media_id,r.emit(Ze),o=0})).catch((function(){o=0}));i.last_media_id=a.metadata.media_id,r.emit(Ze)})),r.on("timeupdate",(function(){var e;a&&(o||ur(r)||i.ended||(!t.live&&r.currentTime+.25>=r.duration&&dr(r,i.ticker,!0),(e=n).locked||(e.locked=setTimeout((function(){return e.task(),function(t){return t.locked=!1,t}(e)}),e.ttl))))})),r.on(b,(function(){a&&i.ticker&&"vod"==i.ticker.kind&&function(t,e){rr(t,e),e.last_idx=nr(t,e)}(r,i.ticker)})),r.on(S,(function(){a&&function(t,e){e.ended||(e.ended=!0,dr(t,e.ticker))}(r,i)}))}}var cr;function hr(t){switch(t){case cr.MEDIA_PLAYBACK_ABORTED:return"media playback was aborted";case cr.MEDIA_ERR_NETWORK:return"a network error occurred";case cr.MEDIA_ERR_DECODE:return"unable to decode media content";case cr.MEDIA_ERR_SRC_NOT_SUPPORTED:return"unsupported media type";case cr.NO_INTERNET:return"no internet connection detected";case cr.MIXED_CONTENT:return"cannot load insecure content in a secure context";default:return"an unknown error occurred"}}function fr(){}function pr(){return"https:"===location.protocol}function gr(t){const e=document.createElement("a");return e.href=t,e}function vr(t){try{return!!new URL(t)}catch(t){return!1}}ue(ce(),Analytics$1),"undefined"!=typeof window&&window.matchMedia&&[R,I].forEach((function(t){window.matchMedia("(orientation: "+t+")").addListener((function(r){e.length&&e.forEach((function(e){r.matches&&e.emit(t)}))}))})),function(t){t[t.UNKNOWN=-1]="UNKNOWN",t[t.MEDIA_PLAYBACK_ABORTED=1]="MEDIA_PLAYBACK_ABORTED",t[t.MEDIA_ERR_NETWORK=2]="MEDIA_ERR_NETWORK",t[t.MEDIA_ERR_DECODE=3]="MEDIA_ERR_DECODE",t[t.MEDIA_ERR_SRC_NOT_SUPPORTED=4]="MEDIA_ERR_SRC_NOT_SUPPORTED",t[t.MIXED_CONTENT=1001]="MIXED_CONTENT",t[t.NO_INTERNET=1002]="NO_INTERNET"}(cr||(cr={}));function mr(t,e){if(e.message)return e.message;if(e.stack)return e.stack;const r=e.code||-1,i=hr(r);return t.i18n("media_errors."+r,i)}const yr=()=>!0===(navigator||{}).onLine;function Er(t,e,r){const n=r.togglePlay;r.on(i,(function(t){const e=t.data||r.error,s="Error: %s\n"+(null===(a=(new Error).stack)||void 0===a?void 0:a.split("\n").slice(2).join("\n"));var a;setTimeout((function(){const a=Ht(r,C);if(t.defaultPrevented||!a||r.root.querySelector("#qul_error"))return;if("AbortError"==e.name)return;r.setState("is-error",!0),r.togglePlay=fr;const o=function(t,e){return{code:"http:0"===e.code?_r(t):e.code,message:mr(t,e)}}(r,e);console.error(s,o.message);let l=Ht(r,"flowplayer-error");l||(l=_t(r,"flowplayer-error"),a.append(l)),te(l,i,{data:e,formatted_data:o}),r.once(m,()=>{Tr(r,n)})}))})),r.on(L,()=>Tr(r,n))}function Tr(t,e){const r=Ht(t,"flowplayer-error");t.togglePlay=e,t.opt("retry")&&t.setState(at,!0),t.setState("is-error",!1),null==r||r.remove()}function _r(t){return function(t){try{return pr()&&"http:"==gr(t).protocol}catch(t){return!1}}(t.original_src)?{code:cr.MIXED_CONTENT}:yr()?{code:cr.MEDIA_ERR_NETWORK}:yr()?{code:cr.UNKNOWN}:{code:cr.NO_INTERNET}}var Sr=Object.freeze({__proto__:null,NO_FULLSCREEN:1,NO_VOLUME_CONTROL:2,NO_MUTE:4,LOGO_ON_RIGHT:8,USE_DRAG_HANDLE:16,USE_PLAY_2:32,USE_PLAY_3:64,USE_THIN_CONTROLBAR:128,NO_TITLE:256,NO_DESCRIPTION:512,NO_CONTROLS:1024,NO_DURATION:2048,NO_HEADER:4096,AUDIO_ONLY:8192,NO_TOUCH_ZONES:16384,LOGO_ON_BOTTOM:32768});function br(t,e,r){let i=()=>document.fullscreenElement,n="fullscreenchange";if(!Element.prototype.requestFullscreen){const t=Element.prototype,e=document;t.webkitRequestFullScreen&&(t.requestFullscreen=t.webkitRequestFullScreen,e.fullscreenEnabled=!0),e.webkitCancelFullScreen&&(document.exitFullscreen=e.webkitCancelFullScreen),n="webkit"+n,i=()=>e.webkitCurrentFullScreenElement}const a=()=>r.getFullsceenTarget?r.getFullsceenTarget():e;r.toggleFullScreen=function(t,e){if(r.ios_fullscreen_disabled)return;if("boolean"!=typeof t&&(t=!r.hasState("is-fullscreen")),Ar(r)&&(t?function(t){t.getAttribute("playsinline")&&t.removeAttribute("playsinline");t.getAttribute("webkit-playsinline")&&t.removeAttribute("webkit-playsinline");t.webkitEnterFullScreen()}(r):function(t,e){t.getAttribute("playsinline")||t.setAttribute("playsinline","");t.getAttribute("webkit-playsinline")||t.setAttribute("webkit-playsinline","");e||t.webkitExitFullScreen();t.togglePlay(!1),t.hasState(ct)||t.setState(ct,!0)}(r,e)),!document.fullscreenEnabled)return;const n=a();if(t)return n.requestFullscreen();i()===n&&document.exitFullscreen()},Ar(r)&&(r.ios_fullscreen_disabled=!0,r.once("beforeplay",(function(){r.ios_fullscreen_disabled=!1})),r.on("webkitendfullscreen",(function(){r.toggleFullScreen(!1,!0)}))),setTimeout(()=>{const t=a();t.addEventListener(n,(function(){const e=i(),n=e===t||e==r;r.emit(n?h:f),r.setState("is-fullscreen",n)}))},0),!1!==t.doubleclick&&e.addEventListener(s,(function(t){var e;t.target&&(null===(e=t.target)||void 0===e?void 0:e.classList.contains("fp-ui"))&&r.toggleFullScreen()}))}function Ar(t){return r().ios&&"function"==typeof t.webkitEnterFullScreen&&"function"==typeof t.webkitExitFullScreen}function Lr(t,e){const r=t.seekable;if("object"!=typeof t.opts||0==r.length)return{head:0,tail:0};const i=Rr(t),n=e||t.live_state.dvr_window;return{head:i,tail:"number"!=typeof n||i-n<0?r.start(0):i-n}}function wr(t){return t.opt("live",!1)||t.duration>=Number.MAX_SAFE_INTEGER}function Dr(t){return isFinite(t.duration)?t.duration:0==t.seekable.length?0:Lr(t).head}function Rr(t){var e;const r=t.seekable;return r.length?t.hasState("is-chromecast-playing")||!(null===(e=t.hls)||void 0===e?void 0:e.liveSyncPosition)?r.end(r.length-1):t.hls.liveSyncPosition:0}function Ir(t,e,r){if(!r.reaper)return;const i=document.createDocumentFragment(),n=_t(r,C),s=_t(r,P);e.append(s),i.append(n),r.reaper.set("ui",n),~e.className.indexOf("use-play-")||e.classList.add("use-play-1"),function(t,e,r){const i=Vt("fp-footer");e.append(i),r.on(D,(function(t){var e,r;const n=null===(e=t.data)||void 0===e?void 0:e.description,s=null===(r=t.data)||void 0===r?void 0:r.title;if(i.innerHTML="","string"==typeof s){const t=Vt("fp-title");t.innerText=s,i.append(t)}if("string"==typeof n){const t=n.split(" "),e=Vt("fp-desc");for(e.innerText=t.join(" "),i.append(e);t.length>1&&e.scrollHeight>e.offsetHeight;)t.pop(),e.innerText=t.join(" ")+"..."}}))}(0,e,r),Er(0,0,r),e.appendChild(i),[o,l].forEach(t=>{e.addEventListener(t,(function(t){r.setState("is-hovered",t.type==o),r.setState("is-accessibility",!1)}))}),br(t,e,r),r.on("volumechange",(function(){const t=0==r.volume||r.muted;r.setState("is-muted",t),r._storage.setItem("mute",t.toString())})),"true"==r._storage.getItem("mute")&&(r.muted=!0,r.setState("is-muted",r.muted));const a=r._storage.getItem("volume");a&&!isNaN(Number(a))&&(r.volume=Number(a)),r.emit("volumechange"),r.on("dvr/window",e=>{t.live&&(r.live_state.dvr=r.seekable.length>0&&function(t,e,r){if(0==e)return!0;const i=Lr(t,r);return i.head-i.tail>=e}(r,t.seconds_to_dvr||60,e.detail),r.live_state.dvr_window=e.detail)}),r.on("live",()=>{const t=setInterval(()=>{if(r.opts.live&&!r.hasState("is-error")&&0!=r.reaper||(r.setState(st,!1),clearInterval(t)),0==r.seekable.length)return;const e=function(t){const e=t.currentTime,r=Lr(t);return{progress:Math.min(100,Math.max(0,(e-r.tail)/(r.head-r.tail)*100)),is_live:e-r.head>=-10}}(r);r.hasState(ot)==e.is_live&&r.setState(ot,!e.is_live),r.live_state.dvr&&r.emit("dvr",e.progress)},200)}),r.on(p,(function(){r.setOpts({live:wr(r)})})),r.on("durationchange",(function(t){const e=wr(r),i=e?Dr(r):t.data||r.duration;isNaN(i)||r.setOpts({live:e,duration:i})})),r.on(["playlist/advance","src"],e=>{if(r.root.classList.contains("is-livecountdown"))return kr(r,t);r.currentSrc&&("src"===e.type&&["is-playlist",ft].some(t=>r.root.classList.contains(t))||kr(r,t))}),r.on(D,(function(r){var i,n;t.seekable=void 0===(null===(i=null==r?void 0:r.data)||void 0===i?void 0:i.seekable)||r.data.seekable;const s=null===(n=r.data)||void 0===n?void 0:n.ui;if("number"!=typeof s)return;const a=e.classList;a.toggle("use-play-1",!(32&s||64&s)),a.toggle("use-play-2",(32&s)>0),a.toggle("use-play-3",(64&s)>0),a.toggle("use-thin-controlbar",(128&s)>0),a.toggle("no-title",(256&s)>0),a.toggle("no-description",(512&s)>0),a.toggle("logo-on-right",(8&s)>0),a.toggle("logo-on-bottom",(32768&s)>0),a.toggle("use-drag-handle",(16&s)>0),a.toggle("no-controls",(1024&s)>0),a.toggle("no-duration",(2048&s)>0),a.toggle("no-header",(4096&s)>0),a.toggle("no-mute",(4&s)>0),a.toggle("no-volume",(2&s)>0),a.toggle("no-fullscreen",(1&s)>0),a.toggle("no-touch-zones",(16384&s)>0)}));let c=null;[d,u].forEach(t=>n.addEventListener(t,(function(t){r.hasState("is-touch-device")&&t.type===d||("number"==typeof c&&clearTimeout(c),r.setState("is-hovered",!0),c=0==r.paused&&setTimeout((function(){r.setState("is-hovered",!1)}),2e3))})))}function kr(t,e){delete e.live_start_time,t.setOpts({live:!1}),t.live_state.dvr=void 0,t.live_state.dvr_window=void 0,delete e.live,delete e.poster,delete e.duration,delete e.title,delete e.description}function Or(t,e,r){if(ye.from_token(t.token||"").is_granted(ye.permissions.NO_METERING))return;ge.id(t.token||"")&&r.once(E,async()=>await async function t(e,r){const i=ge.id(r||"");e.once("src",()=>{e.once(E,()=>t(e,r))}),function(t,e){if(!function(t){return ye.from_token(t).is_granted(ye.permissions.WOWZA_VIDEO)}(e))return;if(function(t){try{return new URL(t).hostname.endsWith(".wowza.com")}catch(t){return!1}}(t.original_src))return;t.emit("error:fatal",{reason:"token",details:"This token only allows wowza video sources"})}(e,r);if(401==(await fetch("https://pmi.flowplayer.com/in",{method:"POST",body:JSON.stringify({token_id:i,factor:1,rnd:Math.random().toString(36).substring(2)})})).status)return e.emit("error:fatal",{reason:"token",details:"The token online validation failed"})}(r,t.token||""))}var Cr={ads:{ad:"Ad",ads:"Ads",advertisement:"Advertisement"},audio:{button_txt:"Audio",menu_title:"Audio"},core:{exit_fullscreen:"Exit fullscreen",fullscreen:"Fullscreen",mute:"Mute",pause:"Pause",play:"Play",unmute:"Unmute",volume:"Volume"},ovp:{starting_in:"Countdown"},playlist:{cancel:"Cancel",up_next:"Up next"},qsel:{menu_title:"Quality"},share:{clipboard_failure:"Access to clipboard failed",clipboard_success:"The text is now on your clipboard",embed:"Embed",link:"Link",menu_title:"Share"},speed:{menu_title:"Speed"}};class I18n{init(t,e,r){r.reaper&&r.reaper.set("translations",Yt(I18n,t,"en"))}}I18n.en=Cr;const Pr="health:record",xr="rebuffer";var Mr=Object.freeze({__proto__:null,RECORD:Pr,REBUFFER:xr,DISPLAY:"display"});const Nr=navigator;function Fr(t){var e,r;const i=null===(e=t.hls)||void 0===e?void 0:e.bandwidthEstimate;return i?1e-6*i:(null===(r=Nr.connection)||void 0===r?void 0:r.downlink)||-1}function Ur(t,e){return async function(t,e){try{await fetch(t,{body:e,method:"POST",mode:"no-cors"})}catch(t){}}(t,JSON.stringify({events:e}))}const Br="https://ljsp.lwcdn.com".concat("/web/public/countdown/time.json"),Gr=window,Hr=Gr._flowplayerTimekeeper||(Gr._flowplayerTimekeeper={});async function jr(){const t=Hr.cachedServerOffset;if(t)return t;const e=Hr.pendingRequest||(Hr.pendingRequest=fetch(Br)),r=await e,i=parseInt(r.headers.get("age")||"0"),n=await r.json(),s=Date.now()-n.millisUtc-1e3*i;return Hr.cachedServerOffset=s,Hr.cachedServerOffset}const Vr=t=>{switch(t){case!0:return At.ON;case!1:return At.OFF;default:return t}},Kr=[],qr="https://ihi.flowplayer.com/v1/health/events";function Wr(t){if(t.suspended)return;const e=Kr.slice(0);Kr.length=0,0!=e.length&&(t.logger.log(`:dispatch events={${e.length}}`),Ur(function(){try{return"undefined"==typeof window?qr:window.__FLOWPLAYER_INSIGHTS_URL?window.__FLOWPLAYER_INSIGHTS_URL:qr}catch(t){return qr}}(),e))}async function zr(t,e,r){const i=await Xr();Kr.push(Object.assign(e,i)),t.logger.log(":enqueue",e.event,e),Kr.length<10&&!r||Wr(t)}const Yr=()=>{var t,e;try{const r=window;return null===(e=null===(t=null==r?void 0:r.google)||void 0===t?void 0:t.ima)||void 0===e?void 0:e.VERSION}catch(t){return}},Xr=async()=>{const t=Date.now();try{return{adjusted_time:t-await jr(),client_time:t}}catch(e){return{client_time:t}}},Qr=(t,e)=>Object.assign(t,{detail:e}),$r=(t,{event:e,media_session_id:r,session_id:i,play_range_id:n})=>({event:e,media_session_id:r,session_id:i,play_range_id:n,device_id:t.deviceId(),version:"3.7.2-rc.0",commit:"25a53f1895cceddb2c6e8e5780fc14e86d28af25",ima_sdk_version:Yr(),preload:t.opt("preload"),autoplay:Vr(t.opt("autoplay")),live:t.opt("live"),dvr:!!t.live_state.dvr,source:t.original_src,downlink_mbs:Fr(t),page_url:sr(),player_id:t.opt("metadata.player_id"),media_id:t.opt("metadata.media_id"),site_id:t.opt("metadata.site_id"),category_id:t.opt("metadata.category_id"),sitegroup_id:t.opt("metadata.sitegroup_id"),token:t.token,plugins:t.plugins.map(t=>t.constructor.name).sort((t,e)=>t.localeCompare(e)),current_time:t.currentTime,external_media_id:t.opt("external_media_id")}),Zr=t=>({bitrate:null==t?void 0:t.bitrate,resolution:null==t?void 0:t.attrs.RESOLUTION,frame_rate:null==t?void 0:t.attrs["FRAME-RATE"]});function Jr(t,e,r,i){const n=$r(e,t.eventInfo(r)),{before:s,after:a}=i;zr(t,((t,e,r)=>Object.assign(t,{state:{before:e,after:r}}))(n,Zr(s),Zr(a)))}const ti=(t,e)=>{let r=null;return(...i)=>{null!==r&&(clearTimeout(r),r=null),r=setTimeout(()=>e(...i),t)}},ei=Qt();class Health{constructor(t,e){this.session_id=ei,this.suspended=!1,this.logger=Pe("health",e.opts),this.media_session_id=Qt(),this.play_range_id=Qt(),this.analyticsLoop=setInterval(()=>Wr(this),2e3),e.on(w,()=>clearInterval(this.analyticsLoop)),e.on(E,()=>{this.play_range_id=Qt()});const r=this;if(e.health={get media_session_id(){return r.media_session_id},set media_session_id(t){r.media_session_id=t},get session_id(){return r.session_id},set session_id(t){r.session_id=t},toggle(t){t?r.resume():r.suspend()}},!Health._UNLOAD_SUBSCRIBED){Health._UNLOAD_SUBSCRIBED=!0;const e=e=>t.instances.forEach(t=>t.emit(e.type));document.addEventListener("visibilitychange",t=>{"hidden"==document.visibilityState&&e(t)}),window.addEventListener("pagehide",e)}}eventInfo(t){return{event:t,media_session_id:this.media_session_id,session_id:this.session_id,play_range_id:this.play_range_id}}suspend(){this.suspended=!0,clearInterval(this.analyticsLoop)}resume(){this.suspended=!1,this.analyticsLoop=setInterval(()=>Wr(this),2e3)}init(t,e,r){!function(t){t.on(T,(function(e){t.seeking||t.networkState===t.NETWORK_LOADING&&t.readyState!==t.HAVE_NOTHING&&t.emit(xr)}))}(r),r.on("display",t=>{zr(this,$r(r,this.eventInfo(t.type)),!0)}),r.on(Pr,({detail:t})=>{const e=$r(r,this.eventInfo(t.event));Object.assign(e,t.detail||{}),zr(this,e)}),[_,m,a,p,g,v,T,xr].forEach(t=>{r.on(t,t=>{zr(this,$r(r,this.eventInfo(t.type)))})}),[E,y,A,b,S,h,f].forEach(t=>{r.on(t,t=>{zr(this,$r(r,this.eventInfo(t.type)))})}),r.on("volumechange",ti(800,t=>{const e=$r(r,this.eventInfo(t.type));zr(this,Qr(e,{volume:parseFloat(r.volume.toFixed(2)),muted:r.muted}))})),r.on("resize",ti(800,t=>{const i=$r(r,this.eventInfo(t.type));zr(this,Qr(i,{height:e.clientHeight,width:e.clientWidth}))})),r.on("hls/failover",t=>{const e=$r(r,this.eventInfo(t.type)),i=t.detail,{reason:n,from:s}=i;zr(this,Qr(e,{reason:n,from:s}))}),r.on("qualitychange",({type:t,detail:e})=>{switch(e.kind){case"hls":return Jr(this,r,t,e)}});let n=Date.now()+5e3;r.on("timeupdate",t=>{if(Date.now()<n)return;n=Date.now()+5e3;const e=$r(r,this.eventInfo(t.type));var i;zr(this,Qr(e,{duration:(i=r.duration,Number.isFinite(i)?i:i===1/0?-1:void 0)}))}),r.addEventListener(i,t=>{const e=$r(r,this.eventInfo(t.type)),i=t.error||r.error;if(!i)return zr(this,e,!0);const n=i.code,s={error_message:i.message||hr(n),error_code:n,error_stack:i.stack||""};return zr(this,Qr(e,s),!0)}),r.on("src",t=>{var e;const i=null===(e=t.detail)||void 0===e?void 0:e.src;if("string"!=typeof i)return;if(!vr(r.original_src))return;if(!vr(i))return;if(i==r.original_src)return;this.media_session_id=Qt();zr(this,$r(r,this.eventInfo(t.type))),Wr(this)}),r.on("visibilitychange",t=>{zr(this,$r(r,this.eventInfo(t.type))),Wr(this)})}}Health.events=Mr,Health._UNLOAD_SUBSCRIBED=!1,ue(window,Health);class FlowplayerComponent extends HTMLElement{constructor(t){super(),this.player=t}}class FlowplayerLogo extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-logo");const e={logo:""};t.on(D,t=>{var r;const i=e.logo,n=(null===(r=null==t?void 0:t.data)||void 0===r?void 0:r.logo)||"";i!=n&&(e.logo=n,this.set_logo(n,t.detail.logo_alt_text,t.detail.logo_href))})}set_logo(t,e,r){this.innerHTML="";const i=document.createElement("img");if(!t)return;if(i.src=t,e&&(i.alt=e),!r)return this.append(i);const n=document.createElement("a");n.href=r,n.append(i),this.append(n)}}class FlowplayerHeaderDuration extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-duration"),t.on(D,t=>{var e;const r=(null===(e=null==t?void 0:t.data)||void 0===e?void 0:e.duration)||NaN;this.innerText=isFinite(r)?Wt(r):""})}}const ri={name:"fp-fullscreen",translation_key:"core.fullscreen"},ii={name:"fp-fullscreen-exit",translation_key:"core.exit_fullscreen"},ni={name:"fp-play",translation_key:"core.play"},si={name:"fp-pause",translation_key:"core.pause"},ai={translation_key:"core.mute",name:"fp-volume-mute-unmute"},oi={translation_key:"core.play",name:"fp-small-play"},li={translation_key:"core.pause",name:"fp-small-pause"},di={name:"fp-fast-forward"},ui={name:"fp-rewind"};class FlowplayerIcon extends FlowplayerComponent{constructor(t,e){super(t),this.classList.add("fp-icon",e.name),e.title&&this.setAttribute("title",e.title),e.title&&this.setAttribute("aria-label",e.title),e.translation_key&&this.setAttribute("aria-label",t.i18n(e.translation_key)),this.setAttribute("tabindex","0"),this.setAttribute("focusable","true")}}document.addEventListener(n,(function(t){this.active_menu&&!t.composedPath().includes(this.active_menu)&&(Array.from(document.querySelectorAll(".fp-engine")).forEach(t=>{var e;const r=t.root.querySelector("details[open].fp-menu-container");r&&(r.open=!1,null===(e=r.querySelector("summary"))||void 0===e||e.removeAttribute("aria-expanded"),t.root.classList.toggle("has-menu-opened",!1))}),this.active_menu=void 0)}));const ci={passive:!0};var hi;function fi(t,e){let r=0,i=-1,n=-1;const s=Math.random().toString(36).replace(/[^a-z]+/g,"").substr(0,5),a=t.classList;t.id=s,a.remove(hi.GRABBING),a.remove(hi.TOUCHING);const o=e.onseek||fr,l=e.onstart||fr,h=e.onend||fr,f=e.onmouse||fr,p=e.ontouch||fr,g=e.ontouchend||fr;function v(e){!function(){const e=t.getBoundingClientRect();r=e.left,i=e.width}();let n=(function(t){return"function"==typeof window.TouchEvent&&t instanceof TouchEvent}(e)?e.changedTouches[0].pageX:e.pageX)-r;return n>i&&(n=i),n<0&&(n=0),n/i*100}function m(e){const r=v(e);r!=n&&(o(t,r),n=r)}return t.addEventListener("touchstart",(function(e){pi(t,e)&&(a.add(hi.TOUCHING),gi(t.parentElement)&&(a.add(hi.GRABBING),p(t,v(e)),l(t,v(e)),m(e)))}),ci),t.addEventListener(u,(function(e){m(e),f(t,v(e))}),ci),t.addEventListener(c,(function(e){setTimeout((function(){a.remove(hi.TOUCHING)}),500),pi(t,e)&&(a.remove(hi.GRABBING),g(t,v(e)),h(t,v(e)),i=0)}),ci),t.addEventListener("touchcancel",(function(){a.remove(hi.GRABBING,hi.TOUCHING),i=0}),ci),t.addEventListener("mousedown",(function(e){a.contains(hi.TOUCHING)||(document.addEventListener(d,m),a.add(hi.GRABBING),l(t,v(e)),e.preventDefault(),m(e))})),t.addEventListener(d,(function(e){a.contains(hi.TOUCHING)||f(t,v(e))})),document.addEventListener("mouseup",(function(e){a.contains(hi.TOUCHING)||(document.removeEventListener(d,m),a.contains(hi.GRABBING)&&(a.remove(hi.GRABBING),h(t,v(e)),i=0))})),t}function pi(t,e){const r=e.target;return!!r&&(r&&!r.closest(t.id)||!gi(t.parentElement)||!t.classList.contains(hi.TOUCHING))}function gi(t){if(!t)return!1;const e=window.getComputedStyle(t);return"0"!==e.width&&"0"!==e.height&&"0"!==e.opacity&&"none"!==e.display&&"hidden"!==e.visibility}!function(t){t.GRABBING="has-grab",t.TOUCHING="has-touch"}(hi||(hi={}));class FlowplayerVolumeBar extends FlowplayerComponent{constructor(t){super(t),this.className="fp-volume";const e=t.root.classList,r=e.contains("is-tiny")?6:e.contains("is-small")?8:10,i=Array.from({length:r}).map(()=>{const t=document.createElement("i");return t.className="fp-tick",t});this.append(...i),fi(this,{onseek:(e,r)=>{r>0&&(t.muted=!1,t._storage.removeItem("mute")),t._storage.setItem("volume",(t.volume=r/100).toString()),this.adjustVolumeSlider(t.volume)}}),this.setAttribute("tabindex","0"),this.setAttribute("role","slider"),this.setAttribute("aria-valuemin","0"),this.setAttribute("aria-valuemax","1"),this.setAttribute("aria-label",t.i18n("core.volume","volume")),t.on("volumechange",()=>{const e=0==t.volume||t.muted;e&&this.adjustVolumeSlider(0);const r=t.opt("ui");this.classList.contains(hi.GRABBING)||e&&"number"==typeof r&&(4&r)>0||this.adjustVolumeSlider(t.volume)})}adjustVolumeSlider(t){this.setAttribute("aria-valuenow",t.toString()),this.setAttribute("aria-valuetext",Math.round(100*t)+"%");const e=Array.from(this.querySelectorAll(".fp-tick")),r=Math.round(t*e.length);e.forEach((t,e)=>{t.classList.toggle("fp-color",e<r)})}}function vi(t,e){if(!t.parentElement)return;const r=t.clientWidth/t.parentElement.clientWidth*100/2;t.style.left=e-r+"%",t.style.display="block"}function mi(t,e){if(isNaN(t.duration))return;const r=t.buffered;r.length&&(e.style.width=Math.min(r.end(r.length-1)/t.duration*100,100)+"%")}function yi(t,e){t.style.width="0",e.style.display="none"}function Ei(t,e,r){if(!e.seekable||0==e.seekable.length)return;vi(r,t);const i=Lr(e),n=(100-Math.max(0,Math.min(t,100)))/100*(i.head-i.tail);r.innerText="-"+Wt(n)}function Ti(t){try{t.dvr_offset=0,t.currentTime=Rr(t)}catch(t){console.warn("failed to seek to now: %j",t)}}function _i(t,e){t/=100,e.currentTime=function(t,e){if(e>1||e<0)return console.warn("cannot calculate a percent outside of range(0..1)"),0;const r=Lr(t);return r.tail+e*(r.head-r.tail)}(e,t)}function Si(t,e){t.style.width="0",e.style.display="none"}class FlowplayerTimelineBar extends FlowplayerComponent{constructor(t){let e;super(t),this.bufferEle=Vt("fp-buffer"),this.progress=Vt("fp-progress","fp-color"),this.tooltipEle=Vt("fp-timestamp"),this.proposedSeekBar=Vt("fp-hover"),this.dragger=Vt("fp-dragger","fp-color"),this.classList.add("fp-timeline","fp-bar"),this.tooltipEle.style.display="none",this.setAttribute("role","slider"),this.setAttribute("tabindex","0"),this.setAttribute("aria-label",t.i18n("timeline","Timeline")),this.setAttribute("aria-valuenow","0"),this.progress.append(this.dragger),this.append(this.bufferEle,this.progress,this.proposedSeekBar,this.tooltipEle);const r=requestAnimationFrame;let i=void 0;const n=()=>{0==t.reaper||e.live||(!function(t,e){e.style.width=t.currentTime/t.duration*100+"%"}(t,this.progress),i=void 0,t.paused||this.classList.contains(hi.GRABBING)||i||(i=setTimeout(n,200)))},s=()=>!!this.player.opt("seekable",!0)&&!isNaN(this.player.duration);fi(this,{onseek:(r,i)=>{if(s())switch(!!e.live){case!0:Ei(i,t,this.tooltipEle);break;case!1:!function(t,e,r){const i=e.duration*(t/100);if(e.disabled&&i>e.currentTime)return!1;r.style.width=t+"%",e.currentTime=i}(i,t,this.progress),vi(this.tooltipEle,i)}},onstart:()=>{s()&&(t.emit("timeline/gesture/start"),!t.hasState("is-casting")&&t.setState(it,!0),e.live||function(t){t.style.display="block"}(this.tooltipEle))},onend:function(i,s){r(n),0!=e.seekable&&e.live&&_i(s,t)},ontouchend:()=>{e.live?Si(this.proposedSeekBar,this.tooltipEle):yi(this.proposedSeekBar,this.tooltipEle),setTimeout(()=>t.emit("timeline/gesture/end"),0)},onmouse:(r,i)=>{if(s()&&(t.emit("timeline/gesture/move",{percent:i}),!this.classList.contains(hi.GRABBING)))switch(!!e.live){case!0:!function(t,e){e.style.width=t+"%"}(i,this.proposedSeekBar),Ei(i,t,this.tooltipEle);break;case!1:!function(t,e){e.style.width=t+"%"}(i,this.proposedSeekBar),function(t,e,r){if(isNaN(t)||isNaN(e.duration))return;vi(r,t),r.innerHTML="";const i=document.createElement("span");i.innerText=Wt(t/100*e.duration),r.append(i)}(i,t,this.tooltipEle)}}}),t.on(D,(function(t){t.data&&(e=t.data)})),t.on(E,()=>r(n)),t.on(v,()=>{0==t.reaper||e.live||mi(t,this.bufferEle)}),t.on("dvr",t=>{this.progress.style.width=t.detail+"%"}),t.on("timeupdate",()=>{0!=t.reaper&&(r(n),this.setAttribute("aria-valuenow",t.currentTime+""),this.setAttribute("aria-valuetext",Math.round(t.currentTime)+t.i18n("core.sec","sec")),e.live||mi(t,this.bufferEle))}),t.on(p,()=>{0!=t.reaper&&(e.live||mi(t,this.bufferEle))}),t.on("durationchange",e=>{if(0==t.reaper)return;const r=wr(t)?Dr(t):e.data||t.duration;isNaN(r)||(this.setAttribute("aria-valuemax",r+""),this.setAttribute("aria-valuemin","0"))}),this.addEventListener(l,()=>{t.emit("timeline/gesture/end"),e.live?Si(this.proposedSeekBar,this.tooltipEle):yi(this.proposedSeekBar,this.tooltipEle)})}}class FlowplayerChaptersTimelineBar extends FlowplayerTimelineBar{constructor(t){super(t),this.handleChapters(t)}handleChapters(t){const e=document.createElement("div");let r;this.addEventListener("chapters:new",t=>{e.innerText="",this.querySelectorAll(".fp-chapter").forEach(t=>this.removeChild(t)),t.data&&t.data.forEach(t=>{const i=document.createElement("div");i.className="fp-chapter",i.style.left=t.left,i.style.bottom=i.style.top="0",i.style.width=t.width,i.title=t.title,i.onmouseover=()=>{e.innerText=t.title},i.onmouseleave=()=>{e.innerText=r||""},this.appendChild(i)})}),this.addEventListener("chapter:changed",i=>{var n;const s=i.data;s&&(e.parentNode||(null===(n=Ht(t,x))||void 0===n||n.insertAdjacentElement("beforebegin",e),e.classList.toggle("fp-togglable",!0),e.classList.toggle("fp-chapter-info",!0)),r=s,e.innerText=s)})}}class FlowplayerLiveStatus extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-live-status");const e=Vt("fp-live-text"),r=Vt("fp-live-indicator","fp-color");e.textContent="live",this.setAttribute("tabindex","0"),this.setAttribute("role","button"),this.append(r,e),this.addEventListener(n,(function(){Ti(t)}))}}class FlowplayerDuration extends FlowplayerComponent{constructor(t){let e;super(t),this.classList.add("fp-duration"),this.setAttribute("aria-hidden","true"),t.on(D,r=>{if(0==t.reaper||!r.data)return;e=r.data;const i=wr(t)?NaN:r.data.duration||0;if(isNaN(i)||i>=Number.MAX_SAFE_INTEGER)return this.style.display="none";this.style.display="inline-block",this.innerText=Wt(i)}),t.on(p,()=>{0==t.reaper||e.live||function(t,e){t.duration&&(e.innerText=Wt(t.duration))}(t,this)})}}class FlowplayerElapsedTime extends FlowplayerComponent{constructor(t){let e;super(t),this.classList.add("fp-elapsed"),this.innerText=Wt(0),this.setAttribute("aria-hidden","true"),t.on(D,t=>{t.data&&(e=t.data)}),t.on("timeupdate",()=>{0!=t.reaper&&(e.live?function(t,e){e.innerText=Wt(t.currentTime)}(t,this):function(t,e){e.innerText=Wt(t.currentTime)}(t,this))})}}class FlowplayerControlButtons extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-btns","fp-small-switch");const e=_t(t,q),r=_t(t,K);e.addEventListener("click",(function(){t.togglePlay(),setTimeout((function(){r.focus&&r.focus()}),100)})),r.addEventListener("click",(function(){t.togglePlay(),setTimeout((function(){e.focus&&e.focus()}),100)})),this.append(e,r)}}class FlowplayerLeftRightZone extends FlowplayerComponent{constructor(t,e){super(t),this.classList.add(e);const r=this.classList.contains("fp-left-zone")?-1:1,i=document.createElement("span"),n=_t(t,this.classList.contains("fp-left-zone")?Y:"flowplayer-fast-forward-icon");n.removeAttribute("tabindex"),i.classList.add("fp-zone-seconds"),this.append(i,n);t.on(b,()=>{i.innerText=""}),t.on("seek:queued",t=>{const e=t.data;if(!e)return;if("number"!=typeof e.offset)return;const r=e.offset;if(0==r)return this.reset_zone();r>0&&this.classList.contains("fp-right-zone")||r<0&&!this.classList.contains("fp-right-zone")?this.render_zone_state(r):this.reset_zone()}),t.on("seek:cancel",()=>{this.reset_zone()}),this.reset_zone(),this.addEventListener(c,(function(e){isNaN(t.duration)||isNaN(t.currentTime)||16384&t.opt("ui")||t.hasState(lt)||!t.hasState("will-seek")&&!t.hasState(ct)||t.enqueueSeek(5*r)&&(e.stopPropagation(),e.preventDefault())}))}reset_zone(){const t=this.querySelector(".fp-zone-seconds");t&&(t.innerText="")}render_zone_state(t){const e=this.querySelector(".fp-zone-seconds");e&&(e.innerText=Math.abs(t)+"")}}class FlowplayerError extends FlowplayerComponent{constructor(t){super(t),this.className="fp-error",this.message=document.createElement("p"),this.message.className="error-message",this.append(this.message),this.addEventListener("error",t=>{const e=t.detail;e&&(this.message.textContent=e.formatted_data.message)})}}class FlowplayerHeaderLeftRight extends FlowplayerComponent{constructor(t,e,...r){super(t),this.className=e;const i=t.createComponents(...r);this.append(...i),"fp-left"!==e&&i.forEach(e=>{e.addEventListener(n,()=>t.toggleFullScreen())})}}class FlowplayerMiddleWait extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-wait"),Array(...Array(4)).map((t,e)=>e).forEach(()=>{this.append(document.createElement("b"))})}}class FlowplayerMiddleZone extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-middle-zone");const e=t.createComponents(V,"flowplayer-middle-buttons");this.append(...e)}}class FlowplayerMiddleButtons extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-switch"),[W,z].forEach(e=>{const r=_t(t,e);r.removeAttribute("tabindex"),this.append(r)})}}class FlowplayerVolumeControl extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-volume-control");const e=_t(t,X);this.append(e),!r().ios&&this.append(_t(t,U)),e instanceof FlowplayerIcon&&e.addEventListener(n,(function(){t.toggleMute()}))}}class FlowplayerHeader extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-header"),this.append(...t.createComponents("flowplayer-header-left-zone",G)),t.reaper&&t.reaper.set("header",this)}}class FlowplayerControls extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-controls","fp-togglable"),this.append(...t.createComponents("flowplayer-control-buttons",M,N,F,"flowplayer-control-duration","flowplayer-volume-control"))}}class FullscreenIcon extends FlowplayerIcon{constructor(t,e){super(t,e),this.setAttribute("role","button")}}class FlowplayerMiddle extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-middle"),this.append(...t.createComponents("flowplayer-middle-left-zone",j,"flowplayer-middle-right-zone")),this.setAttribute("tabindex","0"),t.reaper&&t.reaper.set("middle",this),this.handleClick(t),this.handleTouch(t),t.once("beforeplay",()=>{this.removeAttribute("tabindex"),this.removeAttribute("role"),this.removeAttribute("aria-label")})}handleClick(t){[n,s].forEach(e=>this.addEventListener(e,(function(r){if(!(r.defaultPrevented||t.root.classList.contains("is-endscreen")||e===s&&t.root.classList.contains("no-fullscreen")))return r.preventDefault(),t.emit(r.type),!1}))),t.on(n,(function(e){setTimeout((function(){e.defaultPrevented||t.togglePlay()}),0)})),t.on(s,(function(e){setTimeout((function(){e.defaultPrevented||t.toggleFullScreen()}),0)}))}handleTouch(t){let e=!1;this.addEventListener(c,(function(e){e.cancelable&&!t.hasState("is-endscreen")&&(e.preventDefault(),t.emit(e.type,{source:e}))})),t.on(c,(function(r){setTimeout((function(){if(r.defaultPrevented)return;if(t.ended)return t.togglePlay(!0);const i=t.hasState(rt);e&&clearTimeout(e),(i||t.hasState(ct)||t.hasState("no-autoplay"))&&(t.hasState(ct)&&(t.setState(ct,!1),t.setState("is-hovered",!1)),t.togglePlay(),i)||(t.setState(ct,!0),t.paused||(e=setTimeout((function(){e=!1,t.setState(ct,!1),t.setState("is-hovered",!1)}),2e3)))}),0)}))}}class FlowplayerUi extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-ui"),this.append(...t.createComponents(B,H,x))}}Ue.extensions.unshift.apply(Ue.extensions,[I18n,Analytics$1,Health,class Default{constructor(t){St(t,C,FlowplayerUi),St(t,"flowplayer-error",FlowplayerError),St(t,x,FlowplayerControls),St(t,M,FlowplayerLiveStatus),St(t,"flowplayer-control-duration",FlowplayerDuration),St(t,F,t.extensions.find(t=>"Chapters"===t.name)?FlowplayerChaptersTimelineBar:FlowplayerTimelineBar),St(t,N,FlowplayerElapsedTime),St(t,U,FlowplayerVolumeBar),St(t,"flowplayer-volume-control",FlowplayerVolumeControl),St(t,"flowplayer-control-buttons",FlowplayerControlButtons),St(t,B,FlowplayerHeader),St(t,P,FlowplayerLogo),St(t,"flowplayer-header-duration",FlowplayerHeaderDuration),St(t,"flowplayer-header-left-zone",class extends FlowplayerHeaderLeftRight{constructor(t){super(t,"fp-left","flowplayer-header-duration")}}),St(t,G,class extends FlowplayerHeaderLeftRight{constructor(t){super(t,"fp-right fp-togglable","flowplayer-fullscreen-enter-icon","flowplayer-fullscreen-exit-icon")}}),St(t,H,FlowplayerMiddle),St(t,j,FlowplayerMiddleZone),St(t,V,FlowplayerMiddleWait),St(t,"flowplayer-middle-buttons",FlowplayerMiddleButtons),St(t,"flowplayer-middle-right-zone",class extends FlowplayerLeftRightZone{constructor(t){super(t,"fp-right-zone")}}),St(t,"flowplayer-middle-left-zone",class extends FlowplayerLeftRightZone{constructor(t){super(t,"fp-left-zone")}}),St(t,K,class extends FlowplayerIcon{constructor(t){super(t,oi),this.setAttribute("role","button")}}),St(t,q,class extends FlowplayerIcon{constructor(t){super(t,li),this.setAttribute("role","button")}}),St(t,W,class extends FlowplayerIcon{constructor(t){super(t,ni),this.setAttribute("role","button")}}),St(t,z,class extends FlowplayerIcon{constructor(t){super(t,si),this.setAttribute("role","button")}}),St(t,"flowplayer-fullscreen-enter-icon",class extends FullscreenIcon{constructor(t){super(t,ri)}}),St(t,"flowplayer-fullscreen-exit-icon",class extends FullscreenIcon{constructor(t){super(t,ii)}}),St(t,"flowplayer-fast-forward-icon",class extends FlowplayerIcon{constructor(t){super(t,di)}}),St(t,Y,class extends FlowplayerIcon{constructor(t){super(t,ui)}}),St(t,X,class extends FlowplayerIcon{constructor(t){super(t,ai),this.classList.add("fp-volumebtn"),this.setAttribute("role","switch"),t.on("volumechange",()=>{const e=0==t.volume||t.muted;this.setAttribute("aria-label",t.i18n("core.muted","Muted")),this.setAttribute("aria-checked",e?"true":"false")})}})}init(t,e,r){Or(t,0,r),Ir(t,e,r),function(t,e,r){"undefined"!=typeof window&&"ontouchstart"in window&&r.setState("is-touch-device",!0),r.setState("is-accessibility",!1)}(0,0,r)}}]);var bi=Object.assign(Ue,{ui:Sr,i18n:I18n}),Ai=Ge(He((function(t,e){var r;"undefined"!=typeof window&&(r=()=>(()=>{var t={"./src/config.ts":
|
|
2
|
-
/*!***********************!*\
|
|
3
|
-
!*** ./src/config.ts ***!
|
|
4
|
-
\***********************/(t,e,r)=>{r.r(e),r.d(e,{enableStreamingMode:()=>L,hlsDefaultConfig:()=>b,mergeConfig:()=>A});var i=r(/*! ./controller/abr-controller */"./src/controller/abr-controller.ts"),n=r(/*! ./controller/audio-stream-controller */"./src/controller/audio-stream-controller.ts"),s=r(/*! ./controller/audio-track-controller */"./src/controller/audio-track-controller.ts"),a=r(/*! ./controller/subtitle-stream-controller */"./src/controller/subtitle-stream-controller.ts"),o=r(/*! ./controller/subtitle-track-controller */"./src/controller/subtitle-track-controller.ts"),l=r(/*! ./controller/buffer-controller */"./src/controller/buffer-controller.ts"),d=r(/*! ./controller/timeline-controller */"./src/controller/timeline-controller.ts"),u=r(/*! ./controller/cap-level-controller */"./src/controller/cap-level-controller.ts"),c=r(/*! ./controller/fps-controller */"./src/controller/fps-controller.ts"),h=r(/*! ./controller/eme-controller */"./src/controller/eme-controller.ts"),f=r(/*! ./controller/cmcd-controller */"./src/controller/cmcd-controller.ts"),p=r(/*! ./utils/xhr-loader */"./src/utils/xhr-loader.ts"),g=r(/*! ./utils/fetch-loader */"./src/utils/fetch-loader.ts"),v=r(/*! ./utils/cues */"./src/utils/cues.ts"),m=r(/*! ./utils/mediakeys-helper */"./src/utils/mediakeys-helper.ts"),y=r(/*! ./utils/logger */"./src/utils/logger.ts");function E(){return(E=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t}).apply(this,arguments)}function T(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,i)}return r}function _(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?T(Object(r),!0).forEach((function(e){S(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):T(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}function S(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}var b=_(_({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,enableSoftwareAES:!0,manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,startLevel:void 0,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:p.default,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:i.default,bufferController:l.default,capLevelController:u.default,fpsController:c.default,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystemOptions:{},requestMediaKeySystemAccessFunc:m.requestMediaKeySystemAccess,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0},{cueHandler:v.default,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:a.SubtitleStreamController,subtitleTrackController:o.default,timelineController:d.TimelineController,audioStreamController:n.default,audioTrackController:s.default,emeController:h.default,cmcdController:f.default});function A(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');return E({},t,e)}function L(t){var e=t.loader;e!==g.default&&e!==p.default?(y.logger.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):(0,g.fetchSupported)()&&(t.loader=g.default,t.progressive=!0,t.enableSoftwareAES=!0,y.logger.log("[config]: Progressive streaming enabled, using FetchLoader"))}},"./src/controller/abr-controller.ts":
|
|
5
|
-
/*!******************************************!*\
|
|
6
|
-
!*** ./src/controller/abr-controller.ts ***!
|
|
7
|
-
\******************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>u});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../utils/ewma-bandwidth-estimator */"./src/utils/ewma-bandwidth-estimator.ts"),s=r(/*! ../events */"./src/events.ts"),a=r(/*! ../errors */"./src/errors.ts"),o=r(/*! ../types/loader */"./src/types/loader.ts"),l=r(/*! ../utils/logger */"./src/utils/logger.ts");function d(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}const u=function(){function t(t){this.hls=void 0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=void 0,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=t;var e=t.config;this.bwEstimator=new n.default(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate),this.registerListeners()}var e,r,u,c=t.prototype;return c.registerListeners=function(){var t=this.hls;t.on(s.Events.FRAG_LOADING,this.onFragLoading,this),t.on(s.Events.FRAG_LOADED,this.onFragLoaded,this),t.on(s.Events.FRAG_BUFFERED,this.onFragBuffered,this),t.on(s.Events.LEVEL_LOADED,this.onLevelLoaded,this),t.on(s.Events.ERROR,this.onError,this)},c.unregisterListeners=function(){var t=this.hls;t.off(s.Events.FRAG_LOADING,this.onFragLoading,this),t.off(s.Events.FRAG_LOADED,this.onFragLoaded,this),t.off(s.Events.FRAG_BUFFERED,this.onFragBuffered,this),t.off(s.Events.LEVEL_LOADED,this.onLevelLoaded,this),t.off(s.Events.ERROR,this.onError,this)},c.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null},c.onFragLoading=function(t,e){var r,i=e.frag;i.type===o.PlaylistLevelType.MAIN&&(this.timer||(this.fragCurrent=i,this.partCurrent=null!=(r=e.part)?r:null,this.timer=self.setInterval(this.onCheck,100)))},c.onLevelLoaded=function(t,e){var r=this.hls.config;e.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD)},c._abandonRulesCheck=function(){var t=this.fragCurrent,e=this.partCurrent,r=this.hls,n=r.autoLevelEnabled;r.config;var a=r.media;if(t&&a){var o=e?e.stats:t.stats,d=e?e.duration:t.duration;if(o.aborted||o.loaded&&o.loaded===o.total||0===t.level)return this.clearTimer(),void(this._nextAutoLevel=-1);if(n&&!a.paused&&a.playbackRate&&a.readyState){var u=r.mainForwardBufferInfo;if(null!==u){var c=performance.now()-o.loading.start,h=Math.abs(a.playbackRate);if(!(c<=500*d/h)){var f=o.loaded&&o.loading.first,p=this.bwEstimator.getEstimate(),g=r.levels,v=r.minAutoLevel,m=g[t.level],y=o.total||Math.max(o.loaded,Math.round(d*m.maxBitrate/8)),E=f?1e3*o.loaded/c:0,T=E?(y-o.loaded)/E:8*y/p,_=u.len/h;if(!(T<=_)){var S,b=Number.POSITIVE_INFINITY;for(S=t.level-1;S>v;S--){var A=g[S].maxBitrate;if((b=E?d*A/(6.4*E):d*A/p)<_)break}b>=T||(l.logger.warn("Fragment "+t.sn+(e?" part "+e.index:"")+" of level "+t.level+" is loading too slowly and will cause an underbuffer; aborting and switching to level "+S+"\n Current BW estimate: "+((0,i.isFiniteNumber)(p)?(p/1024).toFixed(3):"Unknown")+" Kb/s\n Estimated load time for current fragment: "+T.toFixed(3)+" s\n Estimated load time for the next fragment: "+b.toFixed(3)+" s\n Time to underbuffer: "+_.toFixed(3)+" s"),r.nextLoadLevel=S,f&&this.bwEstimator.sample(c,o.loaded),this.clearTimer(),t.loader&&(this.fragCurrent=this.partCurrent=null,t.loader.abort()),r.trigger(s.Events.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:o}))}}}}}},c.onFragLoaded=function(t,e){var r=e.frag,n=e.part;if(r.type===o.PlaylistLevelType.MAIN&&(0,i.isFiniteNumber)(r.sn)){var a=n?n.stats:r.stats,l=n?n.duration:r.duration;if(this.clearTimer(),this.lastLoadedFragLevel=r.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var d=this.hls.levels[r.level],u=(d.loaded?d.loaded.bytes:0)+a.loaded,c=(d.loaded?d.loaded.duration:0)+l;d.loaded={bytes:u,duration:c},d.realBitrate=Math.round(8*u/c)}if(r.bitrateTest){var h={stats:a,frag:r,part:n,id:r.type};this.onFragBuffered(s.Events.FRAG_BUFFERED,h)}}},c.onFragBuffered=function(t,e){var r=e.frag,i=e.part,n=i?i.stats:r.stats;if(!n.aborted&&r.type===o.PlaylistLevelType.MAIN&&"initSegment"!==r.sn){var s=n.parsing.end-n.loading.start;this.bwEstimator.sample(s,n.loaded),n.bwEstimate=this.bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=s/1e3:this.bitrateTestDelay=0}},c.onError=function(t,e){switch(e.details){case a.ErrorDetails.FRAG_LOAD_ERROR:case a.ErrorDetails.FRAG_LOAD_TIMEOUT:this.clearTimer()}},c.clearTimer=function(){self.clearInterval(this.timer),this.timer=void 0},c.getNextABRAutoLevel=function(){var t=this.fragCurrent,e=this.partCurrent,r=this.hls,i=r.maxAutoLevel,n=r.config,s=r.minAutoLevel,a=r.media,o=e?e.duration:t?t.duration:0;a&&a.currentTime;var d=a&&0!==a.playbackRate?Math.abs(a.playbackRate):1,u=this.bwEstimator?this.bwEstimator.getEstimate():n.abrEwmaDefaultEstimate,c=r.mainForwardBufferInfo,h=(c?c.len:0)/d,f=this.findBestLevel(u,s,i,h,n.abrBandWidthFactor,n.abrBandWidthUpFactor);if(f>=0)return f;l.logger.trace((h?"rebuffering expected":"buffer is empty")+", finding optimal quality level");var p=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay,g=n.abrBandWidthFactor,v=n.abrBandWidthUpFactor;if(!h){var m=this.bitrateTestDelay;m&&(p=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-m,l.logger.trace("bitrate test took "+Math.round(1e3*m)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*p)+" ms"),g=v=1)}return f=this.findBestLevel(u,s,i,h+p,g,v),Math.max(f,0)},c.findBestLevel=function(t,e,r,n,s,a){for(var o,d=this.fragCurrent,u=this.partCurrent,c=this.lastLoadedFragLevel,h=this.hls.levels,f=h[c],p=!(null==f||null===(o=f.details)||void 0===o||!o.live),g=null==f?void 0:f.codecSet,v=u?u.duration:d?d.duration:0,m=r;m>=e;m--){var y=h[m];if(y&&(!g||y.codecSet===g)){var E=y.details,T=(u?null==E?void 0:E.partTarget:null==E?void 0:E.averagetargetduration)||v,_=void 0;_=m<=c?s*t:a*t;var S=h[m].maxBitrate,b=S*T/_;if(l.logger.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+m+"/"+Math.round(_)+"/"+S+"/"+T+"/"+n+"/"+b),_>S&&(0===b||!(0,i.isFiniteNumber)(b)||p&&!this.bitrateTestDelay||b<n))return m}}return-1},e=t,(r=[{key:"nextAutoLevel",get:function(){var t=this._nextAutoLevel,e=this.bwEstimator;if(-1!==t&&!e.canEstimate())return t;var r=this.getNextABRAutoLevel();return-1!==t&&this.hls.levels[r].loadError?t:(-1!==t&&(r=Math.min(t,r)),r)},set:function(t){this._nextAutoLevel=t}}])&&d(e.prototype,r),u&&d(e,u),Object.defineProperty(e,"prototype",{writable:!1}),t}()},"./src/controller/audio-stream-controller.ts":
|
|
8
|
-
/*!***************************************************!*\
|
|
9
|
-
!*** ./src/controller/audio-stream-controller.ts ***!
|
|
10
|
-
\***************************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>E});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ./base-stream-controller */"./src/controller/base-stream-controller.ts"),s=r(/*! ../events */"./src/events.ts"),a=r(/*! ../utils/buffer-helper */"./src/utils/buffer-helper.ts"),o=r(/*! ./fragment-tracker */"./src/controller/fragment-tracker.ts"),l=r(/*! ../types/level */"./src/types/level.ts"),d=r(/*! ../types/loader */"./src/types/loader.ts"),u=r(/*! ../loader/fragment */"./src/loader/fragment.ts"),c=r(/*! ../demux/chunk-cache */"./src/demux/chunk-cache.ts"),h=r(/*! ../demux/transmuxer-interface */"./src/demux/transmuxer-interface.ts"),f=r(/*! ../types/transmuxer */"./src/types/transmuxer.ts"),p=r(/*! ./fragment-finders */"./src/controller/fragment-finders.ts"),g=r(/*! ../utils/discontinuities */"./src/utils/discontinuities.ts"),v=r(/*! ../errors */"./src/errors.ts");function m(){return(m=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t}).apply(this,arguments)}function y(t,e){return(y=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}const E=function(t){var e,r;function E(e,r){var i;return(i=t.call(this,e,r,"[audio-stream-controller]")||this).videoBuffer=null,i.videoTrackCC=-1,i.waitingVideoCC=-1,i.audioSwitch=!1,i.trackId=-1,i.waitingData=null,i.mainDetails=null,i.bufferFlushed=!1,i.cachedTrackLoadedData=null,i._registerListeners(),i}r=t,(e=E).prototype=Object.create(r.prototype),e.prototype.constructor=e,y(e,r);var T=E.prototype;return T.onHandlerDestroying=function(){this._unregisterListeners(),this.mainDetails=null},T._registerListeners=function(){var t=this.hls;t.on(s.Events.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(s.Events.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(s.Events.MANIFEST_LOADING,this.onManifestLoading,this),t.on(s.Events.LEVEL_LOADED,this.onLevelLoaded,this),t.on(s.Events.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(s.Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(s.Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(s.Events.ERROR,this.onError,this),t.on(s.Events.BUFFER_RESET,this.onBufferReset,this),t.on(s.Events.BUFFER_CREATED,this.onBufferCreated,this),t.on(s.Events.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(s.Events.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(s.Events.FRAG_BUFFERED,this.onFragBuffered,this)},T._unregisterListeners=function(){var t=this.hls;t.off(s.Events.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(s.Events.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(s.Events.MANIFEST_LOADING,this.onManifestLoading,this),t.off(s.Events.LEVEL_LOADED,this.onLevelLoaded,this),t.off(s.Events.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(s.Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(s.Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(s.Events.ERROR,this.onError,this),t.off(s.Events.BUFFER_RESET,this.onBufferReset,this),t.off(s.Events.BUFFER_CREATED,this.onBufferCreated,this),t.off(s.Events.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(s.Events.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(s.Events.FRAG_BUFFERED,this.onFragBuffered,this)},T.onInitPtsFound=function(t,e){var r=e.frag,i=e.id,s=e.initPTS;if("main"===i){var a=r.cc;this.initPTS[r.cc]=s,this.log("InitPTS for cc: "+a+" found from main: "+s),this.videoTrackCC=a,this.state===n.State.WAITING_INIT_PTS&&this.tick()}},T.startLoad=function(t){if(!this.levels)return this.startPosition=t,void(this.state=n.State.STOPPED);var e=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),this.fragLoadError=0,e>0&&-1===t?(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e,this.state=n.State.IDLE):(this.loadedmetadata=!1,this.state=n.State.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()},T.doTick=function(){switch(this.state){case n.State.IDLE:this.doTickIdle();break;case n.State.WAITING_TRACK:var e,r=this.levels,i=this.trackId,s=null==r||null===(e=r[i])||void 0===e?void 0:e.details;if(s){if(this.waitForCdnTuneIn(s))break;this.state=n.State.WAITING_INIT_PTS}break;case n.State.FRAG_LOADING_WAITING_RETRY:var o,l=performance.now(),d=this.retryDate;(!d||l>=d||null!==(o=this.media)&&void 0!==o&&o.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=n.State.IDLE);break;case n.State.WAITING_INIT_PTS:var u=this.waitingData;if(u){var c=u.frag,h=u.part,f=u.cache,g=u.complete;if(void 0!==this.initPTS[c.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=n.State.FRAG_LOADING;var v={frag:c,part:h,payload:f.flush(),networkDetails:null};this._handleFragmentLoadProgress(v),g&&t.prototype._handleFragmentLoadComplete.call(this,v)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log("Waiting fragment cc ("+c.cc+") cancelled because video is at cc "+this.videoTrackCC),this.clearWaitingFragment();else{var m=this.getLoadPosition(),y=a.BufferHelper.bufferInfo(this.mediaBuffer,m,this.config.maxBufferHole);(0,p.fragmentWithinToleranceTest)(y.end,this.config.maxFragLookUpTolerance,c)<0&&(this.log("Waiting fragment cc ("+c.cc+") @ "+c.start+" cancelled because another fragment at "+y.end+" is needed"),this.clearWaitingFragment())}}else this.state=n.State.IDLE}this.onTickEnd()},T.clearWaitingFragment=function(){var t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=n.State.IDLE)},T.resetLoadingState=function(){this.clearWaitingFragment(),t.prototype.resetLoadingState.call(this)},T.onTickEnd=function(){var t=this.media;if(t&&t.readyState){var e=(this.mediaBuffer?this.mediaBuffer:t).buffered;!this.loadedmetadata&&e.length&&(this.loadedmetadata=!0),this.lastCurrentTime=t.currentTime}},T.doTickIdle=function(){var t,e,r=this.hls,i=this.levels,a=this.media,o=this.trackId,l=r.config;if(i&&i[o]&&(a||!this.startFragRequested&&l.startFragPrefetch)){var c=i[o].details;if(!c||c.live&&this.levelLastLoaded!==o||this.waitForCdnTuneIn(c))this.state=n.State.WAITING_TRACK;else{var h=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&h&&(this.bufferFlushed=!1,this.afterBufferFlushed(h,u.ElementaryStreamTypes.AUDIO,d.PlaylistLevelType.AUDIO));var f=this.getFwdBufferInfo(h,d.PlaylistLevelType.AUDIO);if(null!==f){var p=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,d.PlaylistLevelType.MAIN),g=f.len,v=this.getMaxBufferLength(null==p?void 0:p.len),m=this.audioSwitch;if(!(g>=v)||m){if(!m&&this._streamEnded(f,c))return r.trigger(s.Events.BUFFER_EOS,{type:"audio"}),void(this.state=n.State.ENDED);var y=c.fragments[0].start,E=f.end;if(m&&a){var T=this.getLoadPosition();E=T,c.PTSKnown&&T<y&&(f.end>y||f.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),a.currentTime=y+.05)}if(!(p&&E>p.end+c.targetduration)&&(p&&p.len||!f.len)){var _=this.getNextFragment(E,c);_?"identity"!==(null===(t=_.decryptdata)||void 0===t?void 0:t.keyFormat)||null!==(e=_.decryptdata)&&void 0!==e&&e.key?this.loadFragment(_,c,E):this.loadKey(_,c):this.bufferFlushed=!0}}}}}},T.getMaxBufferLength=function(e){var r=t.prototype.getMaxBufferLength.call(this);return e?Math.max(r,e):r},T.onMediaDetaching=function(){this.videoBuffer=null,t.prototype.onMediaDetaching.call(this)},T.onAudioTracksUpdated=function(t,e){var r=e.audioTracks;this.resetTransmuxer(),this.levels=r.map((function(t){return new l.Level(t)}))},T.onAudioTrackSwitching=function(t,e){var r=!!e.url;this.trackId=e.id;var i=this.fragCurrent;null!=i&&i.loader&&i.loader.abort(),this.fragCurrent=null,this.clearWaitingFragment(),r?this.setInterval(100):this.resetTransmuxer(),r?(this.audioSwitch=!0,this.state=n.State.IDLE):this.state=n.State.STOPPED,this.tick()},T.onManifestLoading=function(){this.mainDetails=null,this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1},T.onLevelLoaded=function(t,e){this.mainDetails=e.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(s.Events.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)},T.onAudioTrackLoaded=function(t,e){var r;if(null!=this.mainDetails){var i=this.levels,s=e.details,a=e.id;if(i){this.log("Track "+a+" loaded ["+s.startSN+","+s.endSN+"],duration:"+s.totalduration);var o=i[a],l=0;if(s.live||null!==(r=o.details)&&void 0!==r&&r.live){var d=this.mainDetails;if(s.fragments[0]||(s.deltaUpdateFailed=!0),s.deltaUpdateFailed||!d)return;!o.details&&s.hasProgramDateTime&&d.hasProgramDateTime?((0,g.alignMediaPlaylistByPDT)(s,d),l=s.fragments[0].start):l=this.alignPlaylists(s,o.details)}o.details=s,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(o.details,l),this.state!==n.State.WAITING_TRACK||this.waitForCdnTuneIn(s)||(this.state=n.State.IDLE),this.tick()}else this.warn("Audio tracks were reset while loading level "+a)}else this.cachedTrackLoadedData=e},T._handleFragmentLoadProgress=function(t){var e,r=t.frag,i=t.part,s=t.payload,a=this.config,o=this.trackId,l=this.levels;if(l){var u=l[o];console.assert(u,"Audio track is defined on fragment load progress");var p=u.details;console.assert(p,"Audio track details are defined on fragment load progress");var g=a.defaultAudioCodec||u.audioCodec||"mp4a.40.2",v=this.transmuxer;v||(v=this.transmuxer=new h.default(this.hls,d.PlaylistLevelType.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var m=this.initPTS[r.cc],y=null===(e=r.initSegment)||void 0===e?void 0:e.data;if(void 0!==m){var E=i?i.index:-1,T=-1!==E,_=new f.ChunkMetadata(r.level,r.sn,r.stats.chunkCount,s.byteLength,E,T);v.push(s,y,g,"",r,i,p.totalduration,!1,_,m)}else this.log("Unknown video PTS for cc "+r.cc+", waiting for video PTS before demuxing audio frag "+r.sn+" of ["+p.startSN+" ,"+p.endSN+"],track "+o),(this.waitingData=this.waitingData||{frag:r,part:i,cache:new c.default,complete:!1}).cache.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=n.State.WAITING_INIT_PTS}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},T._handleFragmentLoadComplete=function(e){this.waitingData?this.waitingData.complete=!0:t.prototype._handleFragmentLoadComplete.call(this,e)},T.onBufferReset=function(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1},T.onBufferCreated=function(t,e){var r=e.tracks.audio;r&&(this.mediaBuffer=r.buffer||null),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer||null)},T.onFragBuffered=function(t,e){var r=e.frag,i=e.part;r.type===d.PlaylistLevelType.AUDIO&&(this.fragContextChanged(r)?this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state+", audioSwitch: "+this.audioSwitch):("initSegment"!==r.sn&&(this.fragPrevious=r,this.audioSwitch&&(this.audioSwitch=!1,this.hls.trigger(s.Events.AUDIO_TRACK_SWITCHED,{id:this.trackId}))),this.fragBufferedComplete(r,i)))},T.onError=function(e,r){switch(r.details){case v.ErrorDetails.FRAG_LOAD_ERROR:case v.ErrorDetails.FRAG_LOAD_TIMEOUT:case v.ErrorDetails.KEY_LOAD_ERROR:case v.ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(d.PlaylistLevelType.AUDIO,r);break;case v.ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case v.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:this.state!==n.State.ERROR&&this.state!==n.State.STOPPED&&(this.state=r.fatal?n.State.ERROR:n.State.IDLE,this.warn(r.details+" while loading frag, switching to "+this.state+" state"));break;case v.ErrorDetails.BUFFER_FULL_ERROR:if("audio"===r.parent&&(this.state===n.State.PARSING||this.state===n.State.PARSED)){var i=!0,s=this.getFwdBufferInfo(this.mediaBuffer,d.PlaylistLevelType.AUDIO);s&&s.len>.5&&(i=!this.reduceMaxBufferLength(s.len)),i&&(this.warn("Buffer full error also media.currentTime is not buffered, flush audio buffer"),this.fragCurrent=null,t.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio")),this.resetLoadingState()}}},T.onBufferFlushed=function(t,e){e.type===u.ElementaryStreamTypes.AUDIO&&(this.bufferFlushed=!0)},T._handleTransmuxComplete=function(t){var e,r="audio",i=this.hls,a=t.remuxResult,o=t.chunkMeta,l=this.getCurrentContext(o);if(!l)return this.warn("The loading context changed while buffering fragment "+o.sn+" of level "+o.level+". This chunk will not be buffered."),void this.resetStartWhenNotLoaded(o.level);var d=l.frag,c=l.part,h=l.level.details,f=a.audio,p=a.text,g=a.id3,v=a.initSegment;if(!this.fragContextChanged(d)&&h){if(this.state=n.State.PARSING,this.audioSwitch&&f&&this.completeAudioSwitch(),null!=v&&v.tracks&&(this._bufferInitSegment(v.tracks,d,o),i.trigger(s.Events.FRAG_PARSING_INIT_SEGMENT,{frag:d,id:r,tracks:v.tracks})),f){var y=f.startPTS,E=f.endPTS,T=f.startDTS,_=f.endDTS;c&&(c.elementaryStreams[u.ElementaryStreamTypes.AUDIO]={startPTS:y,endPTS:E,startDTS:T,endDTS:_}),d.setElementaryStreamInfo(u.ElementaryStreamTypes.AUDIO,y,E,T,_),this.bufferFragmentData(f,d,c,o)}if(null!=g&&null!==(e=g.samples)&&void 0!==e&&e.length){var S=m({id:r,frag:d,details:h},g);i.trigger(s.Events.FRAG_PARSING_METADATA,S)}if(p){var b=m({id:r,frag:d,details:h},p);i.trigger(s.Events.FRAG_PARSING_USERDATA,b)}}},T._bufferInitSegment=function(t,e,r){if(this.state===n.State.PARSING){t.video&&delete t.video;var i=t.audio;if(i){i.levelCodec=i.codec,i.id="audio",this.log("Init audio buffer, container:"+i.container+", codecs[parsed]=["+i.codec+"]"),this.hls.trigger(s.Events.BUFFER_CODECS,t);var a=i.initSegment;if(null!=a&&a.byteLength){var o={type:"audio",frag:e,part:null,chunkMeta:r,parent:e.type,data:a};this.hls.trigger(s.Events.BUFFER_APPENDING,o)}this.tick()}}},T.loadFragment=function(e,r,s){var a=this.fragmentTracker.getState(e);this.fragCurrent=e,(this.audioSwitch||a===o.FragmentState.NOT_LOADED||a===o.FragmentState.PARTIAL)&&("initSegment"===e.sn?this._loadInitSegment(e):r.live&&!(0,i.isFiniteNumber)(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=n.State.WAITING_INIT_PTS):(this.startFragRequested=!0,t.prototype.loadFragment.call(this,e,r,s)))},T.completeAudioSwitch=function(){var e=this.hls,r=this.media,i=this.trackId;r&&(this.log("Switching audio track : flushing all audio"),t.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio")),this.audioSwitch=!1,e.trigger(s.Events.AUDIO_TRACK_SWITCHED,{id:i})},E}(n.default)},"./src/controller/audio-track-controller.ts":
|
|
11
|
-
/*!**************************************************!*\
|
|
12
|
-
!*** ./src/controller/audio-track-controller.ts ***!
|
|
13
|
-
\**************************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>d});var i=r(/*! ../events */"./src/events.ts"),n=r(/*! ../errors */"./src/errors.ts"),s=r(/*! ./base-playlist-controller */"./src/controller/base-playlist-controller.ts"),a=r(/*! ../types/loader */"./src/types/loader.ts");function o(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function l(t,e){return(l=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}const d=function(t){var e,r;function s(e){var r;return(r=t.call(this,e,"[audio-track-controller]")||this).tracks=[],r.groupId=null,r.tracksInGroup=[],r.trackId=-1,r.trackName="",r.selectDefaultTrack=!0,r.registerListeners(),r}r=t,(e=s).prototype=Object.create(r.prototype),e.prototype.constructor=e,l(e,r);var d,u,c,h=s.prototype;return h.registerListeners=function(){var t=this.hls;t.on(i.Events.MANIFEST_LOADING,this.onManifestLoading,this),t.on(i.Events.MANIFEST_PARSED,this.onManifestParsed,this),t.on(i.Events.LEVEL_LOADING,this.onLevelLoading,this),t.on(i.Events.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(i.Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(i.Events.ERROR,this.onError,this)},h.unregisterListeners=function(){var t=this.hls;t.off(i.Events.MANIFEST_LOADING,this.onManifestLoading,this),t.off(i.Events.MANIFEST_PARSED,this.onManifestParsed,this),t.off(i.Events.LEVEL_LOADING,this.onLevelLoading,this),t.off(i.Events.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(i.Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(i.Events.ERROR,this.onError,this)},h.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,t.prototype.destroy.call(this)},h.onManifestLoading=function(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.trackName="",this.selectDefaultTrack=!0},h.onManifestParsed=function(t,e){this.tracks=e.audioTracks||[]},h.onAudioTrackLoaded=function(t,e){var r=e.id,i=e.details,n=this.tracksInGroup[r];if(n){var s=n.details;n.details=e.details,this.log("audioTrack "+r+" loaded ["+i.startSN+"-"+i.endSN+"]"),r===this.trackId&&(this.retryCount=0,this.playlistLoaded(r,e,s))}else this.warn("Invalid audio track id "+r)},h.onLevelLoading=function(t,e){this.switchLevel(e.level)},h.onLevelSwitching=function(t,e){this.switchLevel(e.level)},h.switchLevel=function(t){var e=this.hls.levels[t];if(null!=e&&e.audioGroupIds){var r=e.audioGroupIds[e.urlId];if(this.groupId!==r){this.groupId=r;var n=this.tracks.filter((function(t){return!r||t.groupId===r}));this.selectDefaultTrack&&!n.some((function(t){return t.default}))&&(this.selectDefaultTrack=!1),this.tracksInGroup=n;var s={audioTracks:n};this.log("Updating audio tracks, "+n.length+' track(s) found in "'+r+'" group-id'),this.hls.trigger(i.Events.AUDIO_TRACKS_UPDATED,s),this.selectInitialTrack()}}},h.onError=function(e,r){t.prototype.onError.call(this,e,r),!r.fatal&&r.context&&r.context.type===a.PlaylistContextType.AUDIO_TRACK&&r.context.id===this.trackId&&r.context.groupId===this.groupId&&this.retryLoadingOrFail(r)},h.setAudioTrack=function(t){var e=this.tracksInGroup;if(t<0||t>=e.length)this.warn("Invalid id passed to audio-track controller");else{this.clearTimer();var r=e[this.trackId];this.log("Now switching to audio-track index "+t);var n=e[t],s=n.id,a=n.groupId,o=void 0===a?"":a,l=n.name,d=n.type,u=n.url;if(this.trackId=t,this.trackName=l,this.selectDefaultTrack=!1,this.hls.trigger(i.Events.AUDIO_TRACK_SWITCHING,{id:s,groupId:o,name:l,type:d,url:u}),!n.details||n.details.live){var c=this.switchParams(n.url,null==r?void 0:r.details);this.loadPlaylist(c)}}},h.selectInitialTrack=function(){var t=this.tracksInGroup;console.assert(t.length,"Initial audio track should be selected when tracks are known");var e=this.trackName,r=this.findTrackId(e)||this.findTrackId();-1!==r?this.setAudioTrack(r):(this.warn("No track found for running audio group-ID: "+this.groupId),this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.AUDIO_TRACK_LOAD_ERROR,fatal:!0}))},h.findTrackId=function(t){for(var e=this.tracksInGroup,r=0;r<e.length;r++){var i=e[r];if((!this.selectDefaultTrack||i.default)&&(!t||t===i.name))return i.id}return-1},h.loadPlaylist=function(t){var e=this.tracksInGroup[this.trackId];if(this.shouldLoadTrack(e)){var r=e.id,n=e.groupId,s=e.url;if(t)try{s=t.addDirectives(s)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}this.log("loading audio-track playlist for id: "+r),this.clearTimer(),this.hls.trigger(i.Events.AUDIO_TRACK_LOADING,{url:s,id:r,groupId:n,deliveryDirectives:t||null})}},d=s,(u=[{key:"audioTracks",get:function(){return this.tracksInGroup}},{key:"audioTrack",get:function(){return this.trackId},set:function(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}}])&&o(d.prototype,u),c&&o(d,c),Object.defineProperty(d,"prototype",{writable:!1}),s}(s.default)},"./src/controller/base-playlist-controller.ts":
|
|
14
|
-
/*!****************************************************!*\
|
|
15
|
-
!*** ./src/controller/base-playlist-controller.ts ***!
|
|
16
|
-
\****************************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>l});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../types/level */"./src/types/level.ts"),s=r(/*! ./level-helper */"./src/controller/level-helper.ts"),a=r(/*! ../utils/logger */"./src/utils/logger.ts"),o=r(/*! ../errors */"./src/errors.ts"),l=function(){function t(t,e){this.hls=void 0,this.timer=-1,this.canLoad=!1,this.retryCount=0,this.log=void 0,this.warn=void 0,this.log=a.logger.log.bind(a.logger,e+":"),this.warn=a.logger.warn.bind(a.logger,e+":"),this.hls=t}var e=t.prototype;return e.destroy=function(){this.clearTimer(),this.hls=this.log=this.warn=null},e.onError=function(t,e){e.fatal&&e.type===o.ErrorTypes.NETWORK_ERROR&&this.clearTimer()},e.clearTimer=function(){clearTimeout(this.timer),this.timer=-1},e.startLoad=function(){this.canLoad=!0,this.retryCount=0,this.loadPlaylist()},e.stopLoad=function(){this.canLoad=!1,this.clearTimer()},e.switchParams=function(t,e){var r=null==e?void 0:e.renditionReports;if(r)for(var s=0;s<r.length;s++){var a=r[s],o=""+a.URI;if(o===t.slice(-o.length)){var l=parseInt(a["LAST-MSN"]),d=parseInt(a["LAST-PART"]);if(e&&this.hls.config.lowLatencyMode){var u=Math.min(e.age-e.partTarget,e.targetduration);void 0!==d&&u>e.partTarget&&(d+=1)}if((0,i.isFiniteNumber)(l))return new n.HlsUrlParameters(l,(0,i.isFiniteNumber)(d)?d:void 0,n.HlsSkip.No)}}},e.loadPlaylist=function(t){},e.shouldLoadTrack=function(t){return this.canLoad&&t&&!!t.url&&(!t.details||t.details.live)},e.playlistLoaded=function(t,e,r){var i=this,n=e.details,a=e.stats,o=a.loading.end?Math.max(0,self.performance.now()-a.loading.end):0;if(n.advancedDateTime=Date.now()-o,n.live||null!=r&&r.live){if(n.reloaded(r),r&&this.log("live playlist "+t+" "+(n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:"MISSED")),r&&n.fragments.length>0&&(0,s.mergeDetails)(r,n),!this.canLoad||!n.live)return;var l,d=void 0,u=void 0;if(n.canBlockReload&&n.endSN&&n.advanced){var c=this.hls.config.lowLatencyMode,h=n.lastPartSn,f=n.endSN,p=n.lastPartIndex,g=h===f;-1!==p?(d=g?f+1:h,u=g?c?0:p:p+1):d=f+1;var v=n.age,m=v+n.ageHeader,y=Math.min(m-n.partTarget,1.5*n.targetduration);if(y>0){if(r&&y>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+y+" with playlist age: "+n.age),y=0;else{var E=Math.floor(y/n.targetduration);d+=E,void 0!==u&&(u+=Math.round(y%n.targetduration/n.partTarget)),this.log("CDN Tune-in age: "+n.ageHeader+"s last advanced "+v.toFixed(2)+"s goal: "+y+" skip sn "+E+" to part "+u)}n.tuneInGoal=y}if(l=this.getDeliveryDirectives(n,e.deliveryDirectives,d,u),c||!g)return void this.loadPlaylist(l)}else l=this.getDeliveryDirectives(n,e.deliveryDirectives,d,u);var T=(0,s.computeReloadInterval)(n,a);void 0!==d&&n.canBlockReload&&(T-=n.partTarget||1),this.log("reload live playlist "+t+" in "+Math.round(T)+" ms"),this.timer=self.setTimeout((function(){return i.loadPlaylist(l)}),T)}else this.clearTimer()},e.getDeliveryDirectives=function(t,e,r,i){var s=(0,n.getSkipValue)(t,r);return null!=e&&e.skip&&t.deltaUpdateFailed&&(r=e.msn,i=e.part,s=n.HlsSkip.No),new n.HlsUrlParameters(r,i,s)},e.retryLoadingOrFail=function(t){var e,r=this,i=this.hls.config,n=this.retryCount<i.levelLoadingMaxRetry;if(n)if(this.retryCount++,t.details.indexOf("LoadTimeOut")>-1&&null!==(e=t.context)&&void 0!==e&&e.deliveryDirectives)this.warn("retry playlist loading #"+this.retryCount+' after "'+t.details+'"'),this.loadPlaylist();else{var s=Math.min(Math.pow(2,this.retryCount)*i.levelLoadingRetryDelay,i.levelLoadingMaxRetryTimeout);this.timer=self.setTimeout((function(){return r.loadPlaylist()}),s),this.warn("retry playlist loading #"+this.retryCount+" in "+s+' ms after "'+t.details+'"')}else this.warn('cannot recover from error "'+t.details+'"'),this.clearTimer(),t.fatal=!0;return n},t}()},"./src/controller/base-stream-controller.ts":
|
|
17
|
-
/*!**************************************************!*\
|
|
18
|
-
!*** ./src/controller/base-stream-controller.ts ***!
|
|
19
|
-
\**************************************************/(t,e,r)=>{r.r(e),r.d(e,{State:()=>S,default:()=>b});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../task-loop */"./src/task-loop.ts"),s=r(/*! ./fragment-tracker */"./src/controller/fragment-tracker.ts"),a=r(/*! ../utils/buffer-helper */"./src/utils/buffer-helper.ts"),o=r(/*! ../utils/logger */"./src/utils/logger.ts"),l=r(/*! ../events */"./src/events.ts"),d=r(/*! ../errors */"./src/errors.ts"),u=r(/*! ../types/transmuxer */"./src/types/transmuxer.ts"),c=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts"),h=r(/*! ../utils/discontinuities */"./src/utils/discontinuities.ts"),f=r(/*! ./fragment-finders */"./src/controller/fragment-finders.ts"),p=r(/*! ./level-helper */"./src/controller/level-helper.ts"),g=r(/*! ../loader/fragment-loader */"./src/loader/fragment-loader.ts"),v=r(/*! ../crypt/decrypter */"./src/crypt/decrypter.ts"),m=r(/*! ../utils/time-ranges */"./src/utils/time-ranges.ts"),y=r(/*! ../types/loader */"./src/types/loader.ts");function E(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function T(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function _(t,e){return(_=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}var S={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},b=function(t){var e,r;function n(e,r,i){var n;return(n=t.call(this)||this).hls=void 0,n.fragPrevious=null,n.fragCurrent=null,n.fragmentTracker=void 0,n.transmuxer=null,n._state=S.STOPPED,n.media=null,n.mediaBuffer=null,n.config=void 0,n.bitrateTest=!1,n.lastCurrentTime=0,n.nextLoadPosition=0,n.startPosition=0,n.loadedmetadata=!1,n.fragLoadError=0,n.retryDate=0,n.levels=null,n.fragmentLoader=void 0,n.levelLastLoaded=null,n.startFragRequested=!1,n.decrypter=void 0,n.initPTS=[],n.onvseeking=null,n.onvended=null,n.logPrefix="",n.log=void 0,n.warn=void 0,n.logPrefix=i,n.log=o.logger.log.bind(o.logger,i+":"),n.warn=o.logger.warn.bind(o.logger,i+":"),n.hls=e,n.fragmentLoader=new g.default(e.config),n.fragmentTracker=r,n.config=e.config,n.decrypter=new v.default(e,e.config),e.on(l.Events.KEY_LOADED,n.onKeyLoaded,T(n)),e.on(l.Events.LEVEL_SWITCHING,n.onLevelSwitching,T(n)),n}r=t,(e=n).prototype=Object.create(r.prototype),e.prototype.constructor=e,_(e,r);var b,A,L,w=n.prototype;return w.doTick=function(){this.onTickEnd()},w.onTickEnd=function(){},w.startLoad=function(t){},w.stopLoad=function(){this.fragmentLoader.abort();var t=this.fragCurrent;t&&this.fragmentTracker.removeFragment(t),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=S.STOPPED},w._streamEnded=function(t,e){var r=this.fragCurrent,i=this.fragmentTracker;if(!e.live&&r&&this.media&&r.sn>=e.endSN&&!t.nextStart){var n=e.partList;if(null!=n&&n.length){var o=n[n.length-1];return a.BufferHelper.isBuffered(this.media,o.start+o.duration/2)}var l=i.getState(r);return l===s.FragmentState.PARTIAL||l===s.FragmentState.OK}return!1},w.onMediaAttached=function(t,e){var r=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),r.addEventListener("seeking",this.onvseeking),r.addEventListener("ended",this.onvended);var i=this.config;this.levels&&i.autoStartLoad&&this.state===S.STOPPED&&this.startLoad(i.startPosition)},w.onMediaDetaching=function(){var t=this.media;null!=t&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&this.onvseeking&&this.onvended&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()},w.onMediaSeeking=function(){var t=this.config,e=this.fragCurrent,r=this.media,n=this.mediaBuffer,s=this.state,o=r?r.currentTime:0,l=a.BufferHelper.bufferInfo(n||r,o,t.maxBufferHole);if(this.log("media seeking to "+((0,i.isFiniteNumber)(o)?o.toFixed(3):o)+", state: "+s),s===S.ENDED)this.resetLoadingState();else if(e&&!l.len){var d=t.maxFragLookUpTolerance,u=e.start-d,c=o>e.start+e.duration+d;(o<u||c)&&(c&&e.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),e.loader.abort()),this.resetLoadingState())}r&&(this.lastCurrentTime=o),this.loadedmetadata||l.len||(this.nextLoadPosition=this.startPosition=o),this.tickImmediate()},w.onMediaEnded=function(){this.startPosition=this.lastCurrentTime=0},w.onKeyLoaded=function(t,e){if(this.state===S.KEY_LOADING&&e.frag===this.fragCurrent&&this.levels){this.state=S.IDLE;var r=this.levels[e.frag.level].details;r&&this.loadFragment(e.frag,r,e.frag.start)}},w.onLevelSwitching=function(t,e){this.fragLoadError=0},w.onHandlerDestroying=function(){this.stopLoad(),t.prototype.onHandlerDestroying.call(this)},w.onHandlerDestroyed=function(){this.state=S.STOPPED,this.hls.off(l.Events.KEY_LOADED,this.onKeyLoaded,this),this.hls.off(l.Events.LEVEL_SWITCHING,this.onLevelSwitching,this),this.fragmentLoader&&this.fragmentLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.fragmentLoader=this.fragmentTracker=null,t.prototype.onHandlerDestroyed.call(this)},w.loadKey=function(t,e){this.log("Loading key for "+t.sn+" of ["+e.startSN+"-"+e.endSN+"], "+("[stream-controller]"===this.logPrefix?"level":"track")+" "+t.level),this.state=S.KEY_LOADING,this.fragCurrent=t,this.hls.trigger(l.Events.KEY_LOADING,{frag:t})},w.loadFragment=function(t,e,r){this._loadFragForPlayback(t,e,r)},w._loadFragForPlayback=function(t,e,r){var i=this;this._doFragLoad(t,e,r,(function(e){if(i.fragContextChanged(t))return i.warn("Fragment "+t.sn+(e.part?" p: "+e.part.index:"")+" of level "+t.level+" was dropped during download."),void i.fragmentTracker.removeFragment(t);t.stats.chunkCount++,i._handleFragmentLoadProgress(e)})).then((function(e){if(e){i.fragLoadError=0;var r=i.state;i.fragContextChanged(t)?(r===S.FRAG_LOADING||!i.fragCurrent&&r===S.PARSING)&&(i.fragmentTracker.removeFragment(t),i.state=S.IDLE):("payload"in e&&(i.log("Loaded fragment "+t.sn+" of level "+t.level),i.hls.trigger(l.Events.FRAG_LOADED,e)),i._handleFragmentLoadComplete(e))}})).catch((function(e){i.state!==S.STOPPED&&i.state!==S.ERROR&&(i.warn(e),i.resetFragmentLoading(t))}))},w.flushMainBuffer=function(t,e,r){if(void 0===r&&(r=null),t-e){var i={startOffset:t,endOffset:e,type:r};this.fragLoadError=0,this.hls.trigger(l.Events.BUFFER_FLUSHING,i)}},w._loadInitSegment=function(t){var e=this;this._doFragLoad(t).then((function(r){if(!r||e.fragContextChanged(t)||!e.levels)throw new Error("init load aborted");return r})).then((function(r){var i=e.hls,n=r.payload,s=t.decryptdata;if(n&&n.byteLength>0&&s&&s.key&&s.iv&&"AES-128"===s.method){var a=self.performance.now();return e.decrypter.webCryptoDecrypt(new Uint8Array(n),s.key.buffer,s.iv.buffer).then((function(e){var n=self.performance.now();return i.trigger(l.Events.FRAG_DECRYPTED,{frag:t,payload:e,stats:{tstart:a,tdecrypt:n}}),r.payload=e,r}))}return r})).then((function(r){var i=e.fragCurrent,n=e.hls,s=e.levels;if(!s)throw new Error("init load aborted, missing levels");var a=s[t.level].details;console.assert(a,"Level details are defined when init segment is loaded");var o=t.stats;e.state=S.IDLE,e.fragLoadError=0,t.data=new Uint8Array(r.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),r.frag===i&&n.trigger(l.Events.FRAG_BUFFERED,{stats:o,frag:i,part:null,id:t.type}),e.tick()})).catch((function(r){e.state!==S.STOPPED&&e.state!==S.ERROR&&(e.warn(r),e.resetFragmentLoading(t))}))},w.fragContextChanged=function(t){var e=this.fragCurrent;return!t||!e||t.level!==e.level||t.sn!==e.sn||t.urlId!==e.urlId},w.fragBufferedComplete=function(t,e){var r,i,n=this.mediaBuffer?this.mediaBuffer:this.media;this.log("Buffered "+t.type+" sn: "+t.sn+(e?" part: "+e.index:"")+" of "+("[stream-controller]"===this.logPrefix?"level":"track")+" "+t.level+" "+(n?m.default.toString(a.BufferHelper.getBuffered(n)):"(detached)")),this.state=S.IDLE,n&&(!this.loadedmetadata&&n.buffered.length&&(null===(r=this.fragCurrent)||void 0===r?void 0:r.sn)===(null===(i=this.fragPrevious)||void 0===i?void 0:i.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())},w.seekToStartPos=function(){},w._handleFragmentLoadComplete=function(t){var e=this.transmuxer;if(e){var r=t.frag,i=t.part,n=t.partsLoaded,s=!n||0===n.length||n.some((function(t){return!t})),a=new u.ChunkMetadata(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!s);e.flush(a)}},w._handleFragmentLoadProgress=function(t){},w._doFragLoad=function(t,e,r,n){var s=this;if(void 0===r&&(r=null),!this.levels)throw new Error("frag load aborted, missing levels");if(r=Math.max(t.start,r||0),this.config.lowLatencyMode&&e){var a=e.partList;if(a&&n){r>t.end&&e.fragmentHint&&(t=e.fragmentHint);var o=this.getNextPart(a,t,r);if(o>-1){var d=a[o];return this.log("Loading part sn: "+t.sn+" p: "+d.index+" cc: "+t.cc+" of playlist ["+e.startSN+"-"+e.endSN+"] parts [0-"+o+"-"+(a.length-1)+"] "+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=d.start+d.duration,this.state=S.FRAG_LOADING,this.hls.trigger(l.Events.FRAG_LOADING,{frag:t,part:a[o],targetBufferTime:r}),this.doFragPartsLoad(t,a,o,n).catch((function(t){return s.handleFragLoadError(t)}))}if(!t.url||this.loadedEndOfParts(a,r))return Promise.resolve(null)}}return this.log("Loading fragment "+t.sn+" cc: "+t.cc+" "+(e?"of ["+e.startSN+"-"+e.endSN+"] ":"")+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),(0,i.isFiniteNumber)(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=S.FRAG_LOADING,this.hls.trigger(l.Events.FRAG_LOADING,{frag:t,targetBufferTime:r}),this.fragmentLoader.load(t,n).catch((function(t){return s.handleFragLoadError(t)}))},w.doFragPartsLoad=function(t,e,r,i){var n=this;return new Promise((function(s,a){var o=[];!function r(d){var u=e[d];n.fragmentLoader.loadPart(t,u,i).then((function(i){o[u.index]=i;var a=i.part;n.hls.trigger(l.Events.FRAG_LOADED,i);var c=e[d+1];if(!c||c.fragment!==t)return s({frag:t,part:a,partsLoaded:o});r(d+1)})).catch(a)}(r)}))},w.handleFragLoadError=function(t){var e=t.data;return e&&e.details===d.ErrorDetails.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(l.Events.ERROR,e),null},w._handleTransmuxerFlush=function(t){var e=this.getCurrentContext(t);if(e&&this.state===S.PARSING){var r=e.frag,i=e.part,n=e.level,s=self.performance.now();r.stats.parsing.end=s,i&&(i.stats.parsing.end=s),this.updateLevelTiming(r,i,n,t.partial)}else this.fragCurrent||(this.state=S.IDLE)},w.getCurrentContext=function(t){var e=this.levels,r=t.level,i=t.sn,n=t.part;if(!e||!e[r])return this.warn("Levels object was unset while buffering fragment "+i+" of level "+r+". The current chunk will not be buffered."),null;var s=e[r],a=n>-1?(0,p.getPartWith)(s,i,n):null,o=a?a.fragment:(0,p.getFragmentWithSN)(s,i,this.fragCurrent);return o?{frag:o,part:a,level:s}:null},w.bufferFragmentData=function(t,e,r,i){if(t&&this.state===S.PARSING){var n=t.data1,s=t.data2,a=n;if(n&&s&&(a=(0,c.appendUint8Array)(n,s)),a&&a.length){var o={type:t.type,frag:e,part:r,chunkMeta:i,parent:e.type,data:a};this.hls.trigger(l.Events.BUFFER_APPENDING,o),t.dropped&&t.independent&&!r&&this.flushBufferGap(e)}}},w.flushBufferGap=function(t){var e=this.media;if(e)if(a.BufferHelper.isBuffered(e,e.currentTime)){var r=e.currentTime,i=a.BufferHelper.bufferInfo(e,r,0),n=t.duration,s=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),o=Math.max(Math.min(t.start-s,i.end-s),r+s);t.start-o>s&&this.flushMainBuffer(o,t.start)}else this.flushMainBuffer(0,t.start)},w.getFwdBufferInfo=function(t,e){var r=this.config,n=this.getLoadPosition();if(!(0,i.isFiniteNumber)(n))return null;var s=a.BufferHelper.bufferInfo(t,n,r.maxBufferHole);if(0===s.len&&void 0!==s.nextStart){var o=this.fragmentTracker.getBufferedFrag(n,e);if(o&&s.nextStart<o.end)return a.BufferHelper.bufferInfo(t,n,Math.max(s.nextStart,r.maxBufferHole))}return s},w.getMaxBufferLength=function(t){var e,r=this.config;return e=t?Math.max(8*r.maxBufferSize/t,r.maxBufferLength):r.maxBufferLength,Math.min(e,r.maxMaxBufferLength)},w.reduceMaxBufferLength=function(t){var e=this.config,r=t||e.maxBufferLength;return e.maxMaxBufferLength>=r&&(e.maxMaxBufferLength/=2,this.warn("Reduce max buffer length to "+e.maxMaxBufferLength+"s"),!0)},w.getNextFragment=function(t,e){var r=e.fragments,i=r.length;if(!i)return null;var n,s=this.config,a=r[0].start;if(e.live){var o=s.initialLiveManifestSize;if(i<o)return this.warn("Not enough fragments to start playback (have: "+i+", need: "+o+")"),null;e.PTSKnown||this.startFragRequested||-1!==this.startPosition||(n=this.getInitialLiveFragment(e,r),this.startPosition=n?this.hls.liveSyncPosition||n.start:t)}else t<=a&&(n=r[0]);if(!n){var l=s.lowLatencyMode?e.partEnd:e.fragmentEnd;n=this.getFragmentAtPosition(t,l,e)}return this.mapToInitFragWhenRequired(n)},w.mapToInitFragWhenRequired=function(t){return null==t||!t.initSegment||null!=t&&t.initSegment.data||this.bitrateTest?t:t.initSegment},w.getNextPart=function(t,e,r){for(var i=-1,n=!1,s=!0,a=0,o=t.length;a<o;a++){var l=t[a];if(s=s&&!l.independent,i>-1&&r<l.start)break;var d=l.loaded;!d&&(n||l.independent||s)&&l.fragment===e&&(i=a),n=d}return i},w.loadedEndOfParts=function(t,e){var r=t[t.length-1];return r&&e>r.start&&r.loaded},w.getInitialLiveFragment=function(t,e){var r=this.fragPrevious,i=null;if(r){if(t.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime),i=(0,f.findFragmentByPDT)(e,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){var n=r.sn+1;if(n>=t.startSN&&n<=t.endSN){var s=e[n-t.startSN];r.cc===s.cc&&(i=s,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=(0,f.findFragWithCC)(e,r.cc))&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn)}}else{var a=this.hls.liveSyncPosition;null!==a&&(i=this.getFragmentAtPosition(a,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i},w.getFragmentAtPosition=function(t,e,r){var i,n=this.config,a=this.fragPrevious,o=r.fragments,l=r.endSN,d=r.fragmentHint,u=n.maxFragLookUpTolerance,c=!!(n.lowLatencyMode&&r.partList&&d);if(c&&d&&!this.bitrateTest&&(o=o.concat(d),l=d.sn),t<e){var h=t>e-u?0:u;i=(0,f.findFragmentByPTS)(a,o,t,h)}else i=o[o.length-1];if(i){var p=i.sn-r.startSN;if(this.fragmentTracker.getState(i)===s.FragmentState.OK&&(a=i),a&&i.sn===a.sn&&!c&&a&&i.level===a.level){var g=o[p+1];i.sn<l&&this.fragmentTracker.getState(g)!==s.FragmentState.OK?(this.log("SN "+i.sn+" just loaded, load next one: "+g.sn),i=g):i=null}}return i},w.synchronizeToLiveEdge=function(t){var e=this.config,r=this.media;if(r){var i=this.hls.liveSyncPosition,n=r.currentTime,s=t.fragments[0].start,a=t.edge,o=n>=s-e.maxFragLookUpTolerance&&n<=a;if(null!==i&&r.duration>i&&(n<i||!o)){var l=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;(!o&&r.readyState<4||n<a-l)&&(this.loadedmetadata||(this.nextLoadPosition=i),r.readyState&&(this.warn("Playback: "+n.toFixed(3)+" is located too far from the end of live sliding playlist: "+a+", reset currentTime to : "+i.toFixed(3)),r.currentTime=i))}}},w.alignPlaylists=function(t,e){var r=this.levels,n=this.levelLastLoaded,s=this.fragPrevious,a=null!==n?r[n]:null,o=t.fragments.length;if(!o)return this.warn("No fragments in live playlist"),0;var l=t.fragments[0].start,d=!e,u=t.alignedSliding&&(0,i.isFiniteNumber)(l);if(d||!u&&!l){(0,h.alignStream)(s,a,t);var c=t.fragments[0].start;return this.log("Live playlist sliding: "+c.toFixed(2)+" start-sn: "+(e?e.startSN:"na")+"->"+t.startSN+" prev-sn: "+(s?s.sn:"na")+" fragments: "+o),c}return l},w.waitForCdnTuneIn=function(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)},w.setStartPosition=function(t,e){var r=this.startPosition;if(r<e&&(r=-1),-1===r||-1===this.lastCurrentTime){var n=t.startTimeOffset;(0,i.isFiniteNumber)(n)?(r=e+n,n<0&&(r+=t.totalduration),r=Math.min(Math.max(e,r),e+t.totalduration),this.log("Start time offset "+n+" found in playlist, adjust startPosition to "+r),this.startPosition=r):t.live?r=this.hls.liveSyncPosition||e:this.startPosition=r=0,this.lastCurrentTime=r}this.nextLoadPosition=r},w.getLoadPosition=function(){var t=this.media,e=0;return this.loadedmetadata&&t?e=t.currentTime:this.nextLoadPosition&&(e=this.nextLoadPosition),e},w.handleFragLoadAborted=function(t,e){this.transmuxer&&"initSegment"!==t.sn&&t.stats.aborted&&(this.warn("Fragment "+t.sn+(e?" part"+e.index:"")+" of level "+t.level+" was aborted"),this.resetFragmentLoading(t))},w.resetFragmentLoading=function(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===S.FRAG_LOADING_WAITING_RETRY)||(this.state=S.IDLE)},w.onFragmentOrKeyLoadError=function(t,e){if(!e.fatal){var r=e.frag;if(r&&r.type===t){var i=this.fragCurrent;console.assert(i&&r.sn===i.sn&&r.level===i.level&&r.urlId===i.urlId,"Frag load error must match current frag to retry");var n=this.config;if(this.fragLoadError+1<=n.fragLoadingMaxRetry){this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition);var s=Math.min(Math.pow(2,this.fragLoadError)*n.fragLoadingRetryDelay,n.fragLoadingMaxRetryTimeout);this.warn("Fragment "+r.sn+" of "+t+" "+r.level+" failed to load, retrying in "+s+"ms"),this.retryDate=self.performance.now()+s,this.fragLoadError++,this.state=S.FRAG_LOADING_WAITING_RETRY}else e.levelRetry?(t===y.PlaylistLevelType.AUDIO&&(this.fragCurrent=null),this.fragLoadError=0,this.state=S.IDLE):(o.logger.error(e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.hls.stopLoad(),this.state=S.ERROR)}}},w.afterBufferFlushed=function(t,e,r){if(t){var i=a.BufferHelper.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,r),this.state===S.ENDED&&this.resetLoadingState()}},w.resetLoadingState=function(){this.fragCurrent=null,this.fragPrevious=null,this.state=S.IDLE},w.resetStartWhenNotLoaded=function(t){if(!this.loadedmetadata){this.startFragRequested=!1;var e=this.levels?this.levels[t].details:null;null!=e&&e.live?(this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}},w.updateLevelTiming=function(t,e,r,i){var n=this,s=r.details;console.assert(!!s,"level.details must be defined"),Object.keys(t.elementaryStreams).reduce((function(e,a){var o=t.elementaryStreams[a];if(o){var d=o.endPTS-o.startPTS;if(d<=0)return n.warn("Could not parse fragment "+t.sn+" "+a+" duration reliably ("+d+")"),e||!1;var u=i?0:(0,p.updateFragPTSDTS)(s,t,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return n.hls.trigger(l.Events.LEVEL_PTS_UPDATED,{details:s,level:r,drift:u,type:a,frag:t,start:o.startPTS,end:o.endPTS}),!0}return e}),!1)||(this.warn("Found no media in fragment "+t.sn+" of level "+r.id+" resetting transmuxer to fallback to playlist timing"),this.resetTransmuxer()),this.state=S.PARSED,this.hls.trigger(l.Events.FRAG_PARSED,{frag:t,part:e})},w.resetTransmuxer=function(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)},b=n,(A=[{key:"state",get:function(){return this._state},set:function(t){var e=this._state;e!==t&&(this._state=t,this.log(e+"->"+t))}}])&&E(b.prototype,A),L&&E(b,L),Object.defineProperty(b,"prototype",{writable:!1}),n}(n.default)},"./src/controller/buffer-controller.ts":
|
|
20
|
-
/*!*********************************************!*\
|
|
21
|
-
!*** ./src/controller/buffer-controller.ts ***!
|
|
22
|
-
\*********************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>f});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../events */"./src/events.ts"),s=r(/*! ../utils/logger */"./src/utils/logger.ts"),a=r(/*! ../errors */"./src/errors.ts"),o=r(/*! ../utils/buffer-helper */"./src/utils/buffer-helper.ts"),l=r(/*! ../utils/mediasource-helper */"./src/utils/mediasource-helper.ts"),d=r(/*! ../loader/fragment */"./src/loader/fragment.ts"),u=r(/*! ./buffer-operation-queue */"./src/controller/buffer-operation-queue.ts"),c=(0,l.getMediaSource)(),h=/([ha]vc.)(?:\.[^.,]+)+/,f=function(){function t(t){var e=this;this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=function(){var t=e.hls,r=e.media,i=e.mediaSource;s.logger.log("[buffer-controller]: Media source opened"),r&&(e.updateMediaElementDuration(),t.trigger(n.Events.MEDIA_ATTACHED,{media:r})),i&&i.removeEventListener("sourceopen",e._onMediaSourceOpen),e.checkPendingTracks()},this._onMediaSourceClose=function(){s.logger.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=function(){s.logger.log("[buffer-controller]: Media source ended")},this.hls=t,this._initSourceBuffer(),this.registerListeners()}var e=t.prototype;return e.hasSourceTypes=function(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0},e.destroy=function(){this.unregisterListeners(),this.details=null},e.registerListeners=function(){var t=this.hls;t.on(n.Events.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(n.Events.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(n.Events.MANIFEST_PARSED,this.onManifestParsed,this),t.on(n.Events.BUFFER_RESET,this.onBufferReset,this),t.on(n.Events.BUFFER_APPENDING,this.onBufferAppending,this),t.on(n.Events.BUFFER_CODECS,this.onBufferCodecs,this),t.on(n.Events.BUFFER_EOS,this.onBufferEos,this),t.on(n.Events.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(n.Events.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(n.Events.FRAG_PARSED,this.onFragParsed,this),t.on(n.Events.FRAG_CHANGED,this.onFragChanged,this)},e.unregisterListeners=function(){var t=this.hls;t.off(n.Events.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(n.Events.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(n.Events.MANIFEST_PARSED,this.onManifestParsed,this),t.off(n.Events.BUFFER_RESET,this.onBufferReset,this),t.off(n.Events.BUFFER_APPENDING,this.onBufferAppending,this),t.off(n.Events.BUFFER_CODECS,this.onBufferCodecs,this),t.off(n.Events.BUFFER_EOS,this.onBufferEos,this),t.off(n.Events.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(n.Events.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(n.Events.FRAG_PARSED,this.onFragParsed,this),t.off(n.Events.FRAG_CHANGED,this.onFragChanged,this)},e._initSourceBuffer=function(){this.sourceBuffer={},this.operationQueue=new u.default(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]}},e.onManifestParsed=function(t,e){var r=2;(e.audio&&!e.video||!e.altAudio)&&(r=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,this.details=null,s.logger.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},e.onMediaAttaching=function(t,e){var r=this.media=e.media;if(r&&c){var i=this.mediaSource=new c;i.addEventListener("sourceopen",this._onMediaSourceOpen),i.addEventListener("sourceended",this._onMediaSourceEnded),i.addEventListener("sourceclose",this._onMediaSourceClose),r.src=self.URL.createObjectURL(i),this._objectUrl=r.src}},e.onMediaDetaching=function(){var t=this.media,e=this.mediaSource,r=this._objectUrl;if(e){if(s.logger.log("[buffer-controller]: media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){s.logger.warn("[buffer-controller]: onMediaDetaching: "+t.message+" while calling endOfStream")}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),t&&(r&&self.URL.revokeObjectURL(r),t.src===r?(t.removeAttribute("src"),t.load()):s.logger.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(n.Events.MEDIA_DETACHED,void 0)},e.onBufferReset=function(){var t=this;this.getSourceBufferTypes().forEach((function(e){var r=t.sourceBuffer[e];try{r&&(t.removeBufferListeners(e),t.mediaSource&&t.mediaSource.removeSourceBuffer(r),t.sourceBuffer[e]=void 0)}catch(t){s.logger.warn("[buffer-controller]: Failed to reset the "+e+" buffer",t)}})),this._initSourceBuffer()},e.onBufferCodecs=function(t,e){var r=this,i=this.getSourceBufferTypes().length;Object.keys(e).forEach((function(t){if(i){var n=r.tracks[t];if(n&&"function"==typeof n.buffer.changeType){var a=e[t],o=a.id,l=a.codec,d=a.levelCodec,u=a.container,c=a.metadata,f=(n.levelCodec||n.codec).replace(h,"$1"),p=(d||l).replace(h,"$1");if(f!==p){var g=u+";codecs="+(d||l);r.appendChangeType(t,g),s.logger.log("[buffer-controller]: switching codec "+f+" to "+p),r.tracks[t]={buffer:n.buffer,codec:l,container:u,levelCodec:d,metadata:c,id:o}}}}else r.pendingTracks[t]=e[t]})),i||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())},e.appendChangeType=function(t,e){var r=this,i=this.operationQueue,n={execute:function(){var n=r.sourceBuffer[t];n&&(s.logger.log("[buffer-controller]: changing "+t+" sourceBuffer type to "+e),n.changeType(e)),i.shiftAndExecuteNext(t)},onStart:function(){},onComplete:function(){},onError:function(e){s.logger.warn("[buffer-controller]: Failed to change "+t+" SourceBuffer type",e)}};i.append(n,t)},e.onBufferAppending=function(t,e){var r=this,i=this.hls,l=this.operationQueue,d=this.tracks,u=e.data,c=e.type,h=e.frag,f=e.part,p=e.chunkMeta,g=p.buffering[c],v=self.performance.now();g.start=v;var m=h.stats.buffering,y=f?f.stats.buffering:null;0===m.start&&(m.start=v),y&&0===y.start&&(y.start=v);var E=d.audio,T="audio"===c&&1===p.id&&"audio/mpeg"===(null==E?void 0:E.container),_={execute:function(){if(g.executeStart=self.performance.now(),T){var t=r.sourceBuffer[c];if(t){var e=h.start-t.timestampOffset;Math.abs(e)>=.1&&(s.logger.log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to "+h.start+" (delta: "+e+") sn: "+h.sn+")"),t.timestampOffset=h.start)}}r.appendExecutor(u,c)},onStart:function(){},onComplete:function(){var t=self.performance.now();g.executeEnd=g.end=t,0===m.first&&(m.first=t),y&&0===y.first&&(y.first=t);var e=r.sourceBuffer,i={};for(var s in e)i[s]=o.BufferHelper.getBuffered(e[s]);r.appendError=0,r.hls.trigger(n.Events.BUFFER_APPENDED,{type:c,frag:h,part:f,chunkMeta:p,parent:h.type,timeRanges:i})},onError:function(t){s.logger.error("[buffer-controller]: Error encountered while trying to append to the "+c+" SourceBuffer",t);var e={type:a.ErrorTypes.MEDIA_ERROR,parent:h.type,details:a.ErrorDetails.BUFFER_APPEND_ERROR,err:t,fatal:!1};t.code===DOMException.QUOTA_EXCEEDED_ERR?e.details=a.ErrorDetails.BUFFER_FULL_ERROR:(r.appendError++,e.details=a.ErrorDetails.BUFFER_APPEND_ERROR,r.appendError>i.config.appendErrorMaxRetry&&(s.logger.error("[buffer-controller]: Failed "+i.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),e.fatal=!0,i.stopLoad())),i.trigger(n.Events.ERROR,e)}};l.append(_,c)},e.onBufferFlushing=function(t,e){var r=this,i=this.operationQueue,a=function(t){return{execute:r.removeExecutor.bind(r,t,e.startOffset,e.endOffset),onStart:function(){},onComplete:function(){r.hls.trigger(n.Events.BUFFER_FLUSHED,{type:t})},onError:function(e){s.logger.warn("[buffer-controller]: Failed to remove from "+t+" SourceBuffer",e)}}};e.type?i.append(a(e.type),e.type):this.getSourceBufferTypes().forEach((function(t){i.append(a(t),t)}))},e.onFragParsed=function(t,e){var r=this,i=e.frag,a=e.part,o=[],l=a?a.elementaryStreams:i.elementaryStreams;l[d.ElementaryStreamTypes.AUDIOVIDEO]?o.push("audiovideo"):(l[d.ElementaryStreamTypes.AUDIO]&&o.push("audio"),l[d.ElementaryStreamTypes.VIDEO]&&o.push("video")),0===o.length&&s.logger.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function(){var t=self.performance.now();i.stats.buffering.end=t,a&&(a.stats.buffering.end=t);var e=a?a.stats:i.stats;r.hls.trigger(n.Events.FRAG_BUFFERED,{frag:i,part:a,stats:e,id:i.type})}),o)},e.onFragChanged=function(t,e){this.flushBackBuffer()},e.onBufferEos=function(t,e){var r=this;this.getSourceBufferTypes().reduce((function(t,i){var n=r.sourceBuffer[i];return e.type&&e.type!==i||n&&!n.ended&&(n.ended=!0,s.logger.log("[buffer-controller]: "+i+" sourceBuffer now EOS")),t&&!(n&&!n.ended)}),!0)&&this.blockBuffers((function(){var t=r.mediaSource;t&&"open"===t.readyState&&t.endOfStream()}))},e.onLevelUpdated=function(t,e){var r=e.details;r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},e.flushBackBuffer=function(){var t=this.hls,e=this.details,r=this.media,s=this.sourceBuffer;if(r&&null!==e){var a=this.getSourceBufferTypes();if(a.length){var l=e.live&&null!==t.config.liveBackBufferLength?t.config.liveBackBufferLength:t.config.backBufferLength;if((0,i.isFiniteNumber)(l)&&!(l<0)){var d=r.currentTime,u=e.levelTargetDuration,c=Math.max(l,u),h=Math.floor(d/u)*u-c;a.forEach((function(r){var i=s[r];if(i){var a=o.BufferHelper.getBuffered(i);a.length>0&&h>a.start(0)&&(t.trigger(n.Events.BACK_BUFFER_REACHED,{bufferEnd:h}),e.live&&t.trigger(n.Events.LIVE_BACK_BUFFER_REACHED,{bufferEnd:h}),t.trigger(n.Events.BUFFER_FLUSHING,{startOffset:0,endOffset:h,type:r}))}}))}}}},e.updateMediaElementDuration=function(){if(this.details&&this.media&&this.mediaSource&&"open"===this.mediaSource.readyState){var t=this.details,e=this.hls,r=this.media,n=this.mediaSource,a=t.fragments[0].start+t.totalduration,o=r.duration,l=(0,i.isFiniteNumber)(n.duration)?n.duration:0;t.live&&e.config.liveDurationInfinity?(s.logger.log("[buffer-controller]: Media Source duration is set to Infinity"),n.duration=1/0,this.updateSeekableRange(t)):(a>l&&a>o||!(0,i.isFiniteNumber)(o))&&(s.logger.log("[buffer-controller]: Updating Media Source duration to "+a.toFixed(3)),n.duration=a)}},e.updateSeekableRange=function(t){var e=this.mediaSource,r=t.fragments;if(r.length&&t.live&&null!=e&&e.setLiveSeekableRange){var i=Math.max(0,r[0].start),n=Math.max(i,i+t.totalduration);e.setLiveSeekableRange(i,n)}},e.checkPendingTracks=function(){var t=this.bufferCodecEventsExpected,e=this.operationQueue,r=this.pendingTracks,i=Object.keys(r).length;if(i&&!t||2===i){this.createSourceBuffers(r),this.pendingTracks={};var s=this.getSourceBufferTypes();if(0===s.length)return void this.hls.trigger(n.Events.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,reason:"could not create source buffer for media codec(s)"});s.forEach((function(t){e.executeNext(t)}))}},e.createSourceBuffers=function(t){var e=this.sourceBuffer,r=this.mediaSource;if(!r)throw Error("createSourceBuffers called when mediaSource was null");var i=0;for(var o in t)if(!e[o]){var l=t[o];if(!l)throw Error("source buffer exists for track "+o+", however track does not");var d=l.levelCodec||l.codec,u=l.container+";codecs="+d;s.logger.log("[buffer-controller]: creating sourceBuffer("+u+")");try{var c=e[o]=r.addSourceBuffer(u),h=o;this.addBufferListener(h,"updatestart",this._onSBUpdateStart),this.addBufferListener(h,"updateend",this._onSBUpdateEnd),this.addBufferListener(h,"error",this._onSBUpdateError),this.tracks[o]={buffer:c,codec:d,container:l.container,levelCodec:l.levelCodec,metadata:l.metadata,id:l.id},i++}catch(t){s.logger.error("[buffer-controller]: error while trying to add sourceBuffer: "+t.message),this.hls.trigger(n.Events.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,mimeType:u})}}i&&this.hls.trigger(n.Events.BUFFER_CREATED,{tracks:this.tracks})},e._onSBUpdateStart=function(t){this.operationQueue.current(t).onStart()},e._onSBUpdateEnd=function(t){var e=this.operationQueue;e.current(t).onComplete(),e.shiftAndExecuteNext(t)},e._onSBUpdateError=function(t,e){s.logger.error("[buffer-controller]: "+t+" SourceBuffer error",e),this.hls.trigger(n.Events.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_APPENDING_ERROR,fatal:!1});var r=this.operationQueue.current(t);r&&r.onError(e)},e.removeExecutor=function(t,e,r){var n=this.media,a=this.mediaSource,o=this.operationQueue,l=this.sourceBuffer[t];if(!n||!a||!l)return s.logger.warn("[buffer-controller]: Attempting to remove from the "+t+" SourceBuffer, but it does not exist"),void o.shiftAndExecuteNext(t);var d=(0,i.isFiniteNumber)(n.duration)?n.duration:1/0,u=(0,i.isFiniteNumber)(a.duration)?a.duration:1/0,c=Math.max(0,e),h=Math.min(r,d,u);h>c?(s.logger.log("[buffer-controller]: Removing ["+c+","+h+"] from the "+t+" SourceBuffer"),console.assert(!l.updating,t+" sourceBuffer must not be updating"),l.remove(c,h)):o.shiftAndExecuteNext(t)},e.appendExecutor=function(t,e){var r=this.operationQueue,i=this.sourceBuffer[e];if(!i)return s.logger.warn("[buffer-controller]: Attempting to append to the "+e+" SourceBuffer, but it does not exist"),void r.shiftAndExecuteNext(e);i.ended=!1,console.assert(!i.updating,e+" sourceBuffer must not be updating"),i.appendBuffer(t)},e.blockBuffers=function(t,e){var r=this;if(void 0===e&&(e=this.getSourceBufferTypes()),!e.length)return s.logger.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(t);var i=this.operationQueue,n=e.map((function(t){return i.appendBlocker(t)}));Promise.all(n).then((function(){t(),e.forEach((function(t){var e=r.sourceBuffer[t];e&&e.updating||i.shiftAndExecuteNext(t)}))}))},e.getSourceBufferTypes=function(){return Object.keys(this.sourceBuffer)},e.addBufferListener=function(t,e,r){var i=this.sourceBuffer[t];if(i){var n=r.bind(this,t);this.listeners[t].push({event:e,listener:n}),i.addEventListener(e,n)}},e.removeBufferListeners=function(t){var e=this.sourceBuffer[t];e&&this.listeners[t].forEach((function(t){e.removeEventListener(t.event,t.listener)}))},t}()},"./src/controller/buffer-operation-queue.ts":
|
|
23
|
-
/*!**************************************************!*\
|
|
24
|
-
!*** ./src/controller/buffer-operation-queue.ts ***!
|
|
25
|
-
\**************************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>n});var i=r(/*! ../utils/logger */"./src/utils/logger.ts"),n=function(){function t(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}var e=t.prototype;return e.append=function(t,e){var r=this.queues[e];r.push(t),1===r.length&&this.buffers[e]&&this.executeNext(e)},e.insertAbort=function(t,e){this.queues[e].unshift(t),this.executeNext(e)},e.appendBlocker=function(t){var e,r=new Promise((function(t){e=t})),i={execute:e,onStart:function(){},onComplete:function(){},onError:function(){}};return this.append(i,t),r},e.executeNext=function(t){var e=this.buffers,r=this.queues,n=e[t],s=r[t];if(s.length){var a=s[0];try{a.execute()}catch(e){i.logger.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),a.onError(e),n&&n.updating||(s.shift(),this.executeNext(t))}}},e.shiftAndExecuteNext=function(t){this.queues[t].shift(),this.executeNext(t)},e.current=function(t){return this.queues[t][0]},t}()},"./src/controller/cap-level-controller.ts":
|
|
26
|
-
/*!************************************************!*\
|
|
27
|
-
!*** ./src/controller/cap-level-controller.ts ***!
|
|
28
|
-
\************************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>s});var i=r(/*! ../events */"./src/events.ts");function n(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}const s=function(){function t(t){this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.hls=void 0,this.streamController=void 0,this.clientRect=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}var e,r,s,a=t.prototype;return a.setStreamController=function(t){this.streamController=t},a.destroy=function(){this.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null},a.registerListeners=function(){var t=this.hls;t.on(i.Events.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(i.Events.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(i.Events.MANIFEST_PARSED,this.onManifestParsed,this),t.on(i.Events.BUFFER_CODECS,this.onBufferCodecs,this),t.on(i.Events.MEDIA_DETACHING,this.onMediaDetaching,this)},a.unregisterListener=function(){var t=this.hls;t.off(i.Events.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(i.Events.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(i.Events.MANIFEST_PARSED,this.onManifestParsed,this),t.off(i.Events.BUFFER_CODECS,this.onBufferCodecs,this),t.off(i.Events.MEDIA_DETACHING,this.onMediaDetaching,this)},a.onFpsDropLevelCapping=function(e,r){t.isLevelAllowed(r.droppedLevel,this.restrictedLevels)&&this.restrictedLevels.push(r.droppedLevel)},a.onMediaAttaching=function(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null},a.onManifestParsed=function(t,e){var r=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,r.config.capLevelToPlayerSize&&e.video&&this.startCapping()},a.onBufferCodecs=function(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()},a.onMediaDetaching=function(){this.stopCapping()},a.detectPlayerSize=function(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){var t=this.hls.levels;if(t.length){var e=this.hls;e.autoLevelCapping=this.getMaxLevel(t.length-1),e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}},a.getMaxLevel=function(e){var r=this,i=this.hls.levels;if(!i.length)return-1;var n=i.filter((function(i,n){return t.isLevelAllowed(n,r.restrictedLevels)&&n<=e}));return this.clientRect=null,t.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)},a.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},a.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},a.getDimensions=function(){if(this.clientRect)return this.clientRect;var t=this.media,e={width:0,height:0};if(t){var r=t.getBoundingClientRect();e.width=r.width,e.height=r.height,e.width||e.height||(e.width=r.right-r.left||t.width||0,e.height=r.bottom-r.top||t.height||0)}return this.clientRect=e,e},t.isLevelAllowed=function(t,e){return void 0===e&&(e=[]),-1===e.indexOf(t)},t.getMaxLevelByMediaSize=function(t,e,r){if(!t||!t.length)return-1;for(var i,n,s=t.length-1,a=0;a<t.length;a+=1){var o=t[a];if((o.width>=e||o.height>=r)&&(i=o,!(n=t[a+1])||i.width!==n.width||i.height!==n.height)){s=a;break}}return s},e=t,(r=[{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return t}}])&&n(e.prototype,r),s&&n(e,s),Object.defineProperty(e,"prototype",{writable:!1}),t}()},"./src/controller/cmcd-controller.ts":
|
|
29
|
-
/*!*******************************************!*\
|
|
30
|
-
!*** ./src/controller/cmcd-controller.ts ***!
|
|
31
|
-
\*******************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>h});var i=r(/*! ../events */"./src/events.ts"),n=r(/*! ../types/cmcd */"./src/types/cmcd.ts"),s=r(/*! ../utils/buffer-helper */"./src/utils/buffer-helper.ts"),a=r(/*! ../utils/logger */"./src/utils/logger.ts");function o(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function l(t,e,r){return e&&o(t.prototype,e),r&&o(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function d(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,e){if(t){if("string"==typeof t)return u(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?u(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var i=0;return function(){return i>=t.length?{done:!0}:{done:!1,value:t[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function u(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,i=new Array(e);r<e;r++)i[r]=t[r];return i}function c(){return(c=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t}).apply(this,arguments)}var h=function(){function t(e){var r=this;this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=function(){r.initialized&&(r.starved=!0),r.buffering=!0},this.onPlaying=function(){r.initialized||(r.initialized=!0),r.buffering=!1},this.applyPlaylistData=function(t){try{r.apply(t,{ot:n.CMCDObjectType.MANIFEST,su:!r.initialized})}catch(t){a.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=function(t){try{var e=t.frag,i=r.hls.levels[e.level],s=r.getObjectType(e),o={d:1e3*e.duration,ot:s};s!==n.CMCDObjectType.VIDEO&&s!==n.CMCDObjectType.AUDIO&&s!=n.CMCDObjectType.MUXED||(o.br=i.bitrate/1e3,o.tb=r.getTopBandwidth(s)/1e3,o.bl=r.getBufferLength(s)),r.apply(t,o)}catch(t){a.logger.warn("Could not generate segment CMCD data.",t)}},this.hls=e;var i=this.config=e.config,s=i.cmcd;null!=s&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||t.uuid(),this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.registerListeners())}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(i.Events.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(i.Events.MEDIA_DETACHED,this.onMediaDetached,this),t.on(i.Events.BUFFER_CREATED,this.onBufferCreated,this)},e.unregisterListeners=function(){var t=this.hls;t.off(i.Events.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(i.Events.MEDIA_DETACHED,this.onMediaDetached,this),t.off(i.Events.BUFFER_CREATED,this.onBufferCreated,this),this.onMediaDetached()},e.destroy=function(){this.unregisterListeners(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null},e.onMediaAttached=function(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)},e.onMediaDetached=function(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)},e.onBufferCreated=function(t,e){var r,i;this.audioBuffer=null===(r=e.tracks.audio)||void 0===r?void 0:r.buffer,this.videoBuffer=null===(i=e.tracks.video)||void 0===i?void 0:i.buffer},e.createData=function(){var t;return{v:n.CMCDVersion,sf:n.CMCDStreamingFormat.HLS,sid:this.sid,cid:this.cid,pr:null===(t=this.media)||void 0===t?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}},e.apply=function(e,r){void 0===r&&(r={}),c(r,this.createData());var i=r.ot===n.CMCDObjectType.INIT||r.ot===n.CMCDObjectType.VIDEO||r.ot===n.CMCDObjectType.MUXED;if(this.starved&&i&&(r.bs=!0,r.su=!0,this.starved=!1),null==r.su&&(r.su=this.buffering),this.useHeaders){var s=t.toHeaders(r);if(!Object.keys(s).length)return;e.headers||(e.headers={}),c(e.headers,s)}else{var a=t.toQuery(r);if(!a)return;e.url=t.appendQueryToUri(e.url,a)}},e.getObjectType=function(t){var e=t.type;return"subtitle"===e?n.CMCDObjectType.TIMED_TEXT:"initSegment"===t.sn?n.CMCDObjectType.INIT:"audio"===e?n.CMCDObjectType.AUDIO:"main"===e?this.hls.audioTracks.length?n.CMCDObjectType.VIDEO:n.CMCDObjectType.MUXED:void 0},e.getTopBandwidth=function(t){var e,r=0,i=this.hls;if(t===n.CMCDObjectType.AUDIO)e=i.audioTracks;else{var s=i.maxAutoLevel,a=s>-1?s+1:i.levels.length;e=i.levels.slice(0,a)}for(var o,l=d(e);!(o=l()).done;){var u=o.value;u.bitrate>r&&(r=u.bitrate)}return r>0?r:NaN},e.getBufferLength=function(t){var e=this.hls.media,r=t===n.CMCDObjectType.AUDIO?this.audioBuffer:this.videoBuffer;return r&&e?1e3*s.BufferHelper.bufferInfo(r,e.currentTime,this.config.maxBufferHole).len:NaN},e.createPlaylistLoader=function(){var t=this.config.pLoader,e=this.applyPlaylistData,r=t||this.config.loader;return function(){function t(t){this.loader=void 0,this.loader=new r(t)}var i=t.prototype;return i.destroy=function(){this.loader.destroy()},i.abort=function(){this.loader.abort()},i.load=function(t,r,i){e(t),this.loader.load(t,r,i)},l(t,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}]),t}()},e.createFragmentLoader=function(){var t=this.config.fLoader,e=this.applyFragmentData,r=t||this.config.loader;return function(){function t(t){this.loader=void 0,this.loader=new r(t)}var i=t.prototype;return i.destroy=function(){this.loader.destroy()},i.abort=function(){this.loader.abort()},i.load=function(t,r,i){e(t),this.loader.load(t,r,i)},l(t,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}]),t}()},t.uuid=function(){var t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)},t.serialize=function(t){for(var e,r=[],i=function(t){return!Number.isNaN(t)&&null!=t&&""!==t&&!1!==t},n=function(t){return Math.round(t)},s=function(t){return 100*n(t/100)},a={br:n,d:n,bl:s,dl:s,mtp:s,nor:function(t){return encodeURIComponent(t)},rtp:s,tb:n},o=d(Object.keys(t||{}).sort());!(e=o()).done;){var l=e.value,u=t[l];if(i(u)&&!("v"===l&&1===u||"pr"==l&&1===u)){var c=a[l];c&&(u=c(u));var h=typeof u,f=void 0;f="ot"===l||"sf"===l||"st"===l?l+"="+u:"boolean"===h?l:"number"===h?l+"="+u:l+"="+JSON.stringify(u),r.push(f)}}return r.join(",")},t.toHeaders=function(e){for(var r={},i=["Object","Request","Session","Status"],n=[{},{},{},{}],s={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3},a=0,o=Object.keys(e);a<o.length;a++){var l=o[a];n[null!=s[l]?s[l]:1][l]=e[l]}for(var d=0;d<n.length;d++){var u=t.serialize(n[d]);u&&(r["CMCD-"+i[d]]=u)}return r},t.toQuery=function(e){return"CMCD="+encodeURIComponent(t.serialize(e))},t.appendQueryToUri=function(t,e){if(!e)return t;var r=t.includes("?")?"&":"?";return""+t+r+e},t}()},"./src/controller/eme-controller.ts":
|
|
32
|
-
/*!******************************************!*\
|
|
33
|
-
!*** ./src/controller/eme-controller.ts ***!
|
|
34
|
-
\******************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>l});var i=r(/*! ../events */"./src/events.ts"),n=r(/*! ../errors */"./src/errors.ts"),s=r(/*! ../utils/logger */"./src/utils/logger.ts"),a=r(/*! ../utils/mediakeys-helper */"./src/utils/mediakeys-helper.ts");function o(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}const l=function(){function t(t){this.hls=void 0,this._widevineLicenseUrl=void 0,this._licenseXhrSetup=void 0,this._licenseResponseCallback=void 0,this._emeEnabled=void 0,this._requestMediaKeySystemAccess=void 0,this._drmSystemOptions=void 0,this._config=void 0,this._mediaKeysList=[],this._media=null,this._hasSetMediaKeys=!1,this._requestLicenseFailureCount=0,this.mediaKeysPromise=null,this._onMediaEncrypted=this.onMediaEncrypted.bind(this),this.hls=t,this._config=t.config,this._widevineLicenseUrl=this._config.widevineLicenseUrl,this._licenseXhrSetup=this._config.licenseXhrSetup,this._licenseResponseCallback=this._config.licenseResponseCallback,this._emeEnabled=this._config.emeEnabled,this._requestMediaKeySystemAccess=this._config.requestMediaKeySystemAccessFunc,this._drmSystemOptions=this._config.drmSystemOptions,this._registerListeners()}var e,r,l,d=t.prototype;return d.destroy=function(){this._unregisterListeners(),this.hls=this._onMediaEncrypted=null,this._requestMediaKeySystemAccess=null},d._registerListeners=function(){this.hls.on(i.Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(i.Events.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(i.Events.MANIFEST_PARSED,this.onManifestParsed,this)},d._unregisterListeners=function(){this.hls.off(i.Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(i.Events.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(i.Events.MANIFEST_PARSED,this.onManifestParsed,this)},d.getLicenseServerUrl=function(t){switch(t){case a.KeySystems.WIDEVINE:if(!this._widevineLicenseUrl)break;return this._widevineLicenseUrl}throw new Error('no license server URL configured for key-system "'+t+'"')},d._attemptKeySystemAccess=function(t,e,r){var i=this,n=function(t,e,r,i){switch(t){case a.KeySystems.WIDEVINE:return function(t,e,r){var i={audioCapabilities:[],videoCapabilities:[]};return t.forEach((function(t){i.audioCapabilities.push({contentType:'audio/mp4; codecs="'+t+'"',robustness:r.audioRobustness||""})})),e.forEach((function(t){i.videoCapabilities.push({contentType:'video/mp4; codecs="'+t+'"',robustness:r.videoRobustness||""})})),[i]}(e,r,i);default:throw new Error("Unknown key-system: "+t)}}(t,e,r,this._drmSystemOptions);s.logger.log("Requesting encrypted media key-system access");var o=this.requestMediaKeySystemAccess(t,n);this.mediaKeysPromise=o.then((function(e){return i._onMediaKeySystemAccessObtained(t,e)})),o.catch((function(e){s.logger.error('Failed to obtain key-system "'+t+'" access:',e)}))},d._onMediaKeySystemAccessObtained=function(t,e){var r=this;s.logger.log('Access for key-system "'+t+'" obtained');var i={mediaKeysSessionInitialized:!1,mediaKeySystemAccess:e,mediaKeySystemDomain:t};this._mediaKeysList.push(i);var n=Promise.resolve().then((function(){return e.createMediaKeys()})).then((function(e){return i.mediaKeys=e,s.logger.log('Media-keys created for key-system "'+t+'"'),r._onMediaKeysCreated(),e}));return n.catch((function(t){s.logger.error("Failed to create media-keys:",t)})),n},d._onMediaKeysCreated=function(){var t=this;this._mediaKeysList.forEach((function(e){e.mediaKeysSession||(e.mediaKeysSession=e.mediaKeys.createSession(),t._onNewMediaKeySession(e.mediaKeysSession))}))},d._onNewMediaKeySession=function(t){var e=this;s.logger.log("New key-system session "+t.sessionId),t.addEventListener("message",(function(r){e._onKeySessionMessage(t,r.message)}),!1)},d._onKeySessionMessage=function(t,e){s.logger.log("Got EME message event, creating license request"),this._requestLicense(e,(function(e){s.logger.log("Received license data (length: "+(e?e.byteLength:e)+"), updating key-session"),t.update(e).catch((function(t){s.logger.warn("Updating key-session failed: "+t)}))}))},d.onMediaEncrypted=function(t){var e=this;if(s.logger.log('Media is encrypted using "'+t.initDataType+'" init data type'),!this.mediaKeysPromise)return s.logger.error("Fatal: Media is encrypted but no CDM access or no keys have been requested"),void this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_NO_KEYS,fatal:!0});var r=function(r){e._media&&(e._attemptSetMediaKeys(r),e._generateRequestWithPreferredKeySession(t.initDataType,t.initData))};this.mediaKeysPromise.then(r).catch(r)},d._attemptSetMediaKeys=function(t){if(!this._media)throw new Error("Attempted to set mediaKeys without first attaching a media element");if(!this._hasSetMediaKeys){var e=this._mediaKeysList[0];if(!e||!e.mediaKeys)return s.logger.error("Fatal: Media is encrypted but no CDM access or no keys have been obtained yet"),void this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_NO_KEYS,fatal:!0});s.logger.log("Setting keys for encrypted media"),this._media.setMediaKeys(e.mediaKeys),this._hasSetMediaKeys=!0}},d._generateRequestWithPreferredKeySession=function(t,e){var r=this,a=this._mediaKeysList[0];if(!a)return s.logger.error("Fatal: Media is encrypted but not any key-system access has been obtained yet"),void this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_NO_ACCESS,fatal:!0});if(a.mediaKeysSessionInitialized)s.logger.warn("Key-Session already initialized but requested again");else{var o=a.mediaKeysSession;if(!o)return s.logger.error("Fatal: Media is encrypted but no key-session existing"),void this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_NO_SESSION,fatal:!0});if(!e)return s.logger.warn("Fatal: initData required for generating a key session is null"),void this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_NO_INIT_DATA,fatal:!0});s.logger.log('Generating key-session request for "'+t+'" init data type'),a.mediaKeysSessionInitialized=!0,o.generateRequest(t,e).then((function(){s.logger.debug("Key-session generation succeeded")})).catch((function(t){s.logger.error("Error generating key-session request:",t),r.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_NO_SESSION,fatal:!1})}))}},d._createLicenseXhr=function(t,e,r){var i=new XMLHttpRequest;i.responseType="arraybuffer",i.onreadystatechange=this._onLicenseRequestReadyStageChange.bind(this,i,t,e,r);var n=this._licenseXhrSetup;if(n)try{n.call(this.hls,i,t),n=void 0}catch(t){s.logger.error(t)}try{i.readyState||i.open("POST",t,!0),n&&n.call(this.hls,i,t)}catch(t){throw new Error("issue setting up KeySystem license XHR "+t)}return i},d._onLicenseRequestReadyStageChange=function(t,e,r,a){switch(t.readyState){case 4:if(200===t.status){this._requestLicenseFailureCount=0,s.logger.log("License request succeeded");var o=t.response,l=this._licenseResponseCallback;if(l)try{o=l.call(this.hls,t,e)}catch(t){s.logger.error(t)}a(o)}else{if(s.logger.error("License Request XHR failed ("+e+"). Status: "+t.status+" ("+t.statusText+")"),this._requestLicenseFailureCount++,this._requestLicenseFailureCount>3)return void this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0});var d=3-this._requestLicenseFailureCount+1;s.logger.warn("Retrying license request, "+d+" attempts left"),this._requestLicense(r,a)}}},d._generateLicenseRequestChallenge=function(t,e){switch(t.mediaKeySystemDomain){case a.KeySystems.WIDEVINE:return e}throw new Error("unsupported key-system: "+t.mediaKeySystemDomain)},d._requestLicense=function(t,e){s.logger.log("Requesting content license for key-system");var r=this._mediaKeysList[0];if(!r)return s.logger.error("Fatal error: Media is encrypted but no key-system access has been obtained yet"),void this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_NO_ACCESS,fatal:!0});try{var a=this.getLicenseServerUrl(r.mediaKeySystemDomain),o=this._createLicenseXhr(a,t,e);s.logger.log("Sending license request to URL: "+a);var l=this._generateLicenseRequestChallenge(r,t);o.send(l)}catch(t){s.logger.error("Failure requesting DRM license: "+t),this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0})}},d.onMediaAttached=function(t,e){if(this._emeEnabled){var r=e.media;this._media=r,r.addEventListener("encrypted",this._onMediaEncrypted)}},d.onMediaDetached=function(){var t=this._media,e=this._mediaKeysList;t&&(t.removeEventListener("encrypted",this._onMediaEncrypted),this._media=null,this._mediaKeysList=[],Promise.all(e.map((function(t){if(t.mediaKeysSession)return t.mediaKeysSession.close().catch((function(){}))}))).then((function(){return t.setMediaKeys(null)})).catch((function(){})))},d.onManifestParsed=function(t,e){if(this._emeEnabled){var r=e.levels.map((function(t){return t.audioCodec})).filter((function(t){return!!t})),i=e.levels.map((function(t){return t.videoCodec})).filter((function(t){return!!t}));this._attemptKeySystemAccess(a.KeySystems.WIDEVINE,r,i)}},e=t,(r=[{key:"requestMediaKeySystemAccess",get:function(){if(!this._requestMediaKeySystemAccess)throw new Error("No requestMediaKeySystemAccess function configured");return this._requestMediaKeySystemAccess}}])&&o(e.prototype,r),l&&o(e,l),Object.defineProperty(e,"prototype",{writable:!1}),t}()},"./src/controller/fps-controller.ts":
|
|
35
|
-
/*!******************************************!*\
|
|
36
|
-
!*** ./src/controller/fps-controller.ts ***!
|
|
37
|
-
\******************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>s});var i=r(/*! ../events */"./src/events.ts"),n=r(/*! ../utils/logger */"./src/utils/logger.ts");const s=function(){function t(t){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=t,this.registerListeners()}var e=t.prototype;return e.setStreamController=function(t){this.streamController=t},e.registerListeners=function(){this.hls.on(i.Events.MEDIA_ATTACHING,this.onMediaAttaching,this)},e.unregisterListeners=function(){this.hls.off(i.Events.MEDIA_ATTACHING,this.onMediaAttaching)},e.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},e.onMediaAttaching=function(t,e){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},e.checkFPS=function(t,e,r){var s=performance.now();if(e){if(this.lastTime){var a=s-this.lastTime,o=r-this.lastDroppedFrames,l=e-this.lastDecodedFrames,d=1e3*o/a,u=this.hls;if(u.trigger(i.Events.FPS_DROP,{currentDropped:o,currentDecoded:l,totalDroppedFrames:r}),d>0&&o>u.config.fpsDroppedMonitoringThreshold*l){var c=u.currentLevel;n.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(-1===u.autoLevelCapping||u.autoLevelCapping>=c)&&(c-=1,u.trigger(i.Events.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:u.currentLevel}),u.autoLevelCapping=c,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=r,this.lastDecodedFrames=e}},e.checkFPSInterval=function(){var t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){var e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)},t}()},"./src/controller/fragment-finders.ts":
|
|
38
|
-
/*!********************************************!*\
|
|
39
|
-
!*** ./src/controller/fragment-finders.ts ***!
|
|
40
|
-
\********************************************/(t,e,r)=>{r.r(e),r.d(e,{findFragWithCC:()=>d,findFragmentByPDT:()=>s,findFragmentByPTS:()=>a,fragmentWithinToleranceTest:()=>o,pdtWithinToleranceTest:()=>l});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../utils/binary-search */"./src/utils/binary-search.ts");function s(t,e,r){if(null===e||!Array.isArray(t)||!t.length||!(0,i.isFiniteNumber)(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;r=r||0;for(var n=0;n<t.length;++n){var s=t[n];if(l(e,r,s))return s}return null}function a(t,e,r,i){void 0===r&&(r=0),void 0===i&&(i=0);var s=null;if(t?s=e[t.sn-e[0].sn+1]||null:0===r&&0===e[0].start&&(s=e[0]),s&&0===o(r,i,s))return s;var a=n.default.search(e,o.bind(null,r,i));return a||s}function o(t,e,r){void 0===t&&(t=0),void 0===e&&(e=0);var i=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=t?1:r.start-i>t&&r.start?-1:0}function l(t,e,r){var i=1e3*Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>t}function d(t,e){return n.default.search(t,(function(t){return t.cc<e?1:t.cc>e?-1:0}))}},"./src/controller/fragment-tracker.ts":
|
|
41
|
-
/*!********************************************!*\
|
|
42
|
-
!*** ./src/controller/fragment-tracker.ts ***!
|
|
43
|
-
\********************************************/(t,e,r)=>{r.r(e),r.d(e,{FragmentState:()=>i,FragmentTracker:()=>a});var i,n=r(/*! ../events */"./src/events.ts"),s=r(/*! ../types/loader */"./src/types/loader.ts");!function(t){t.NOT_LOADED="NOT_LOADED",t.APPENDING="APPENDING",t.PARTIAL="PARTIAL",t.OK="OK"}(i||(i={}));var a=function(){function t(t){this.activeFragment=null,this.activeParts=null,this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hls=t,this._registerListeners()}var e=t.prototype;return e._registerListeners=function(){var t=this.hls;t.on(n.Events.BUFFER_APPENDED,this.onBufferAppended,this),t.on(n.Events.FRAG_BUFFERED,this.onFragBuffered,this),t.on(n.Events.FRAG_LOADED,this.onFragLoaded,this)},e._unregisterListeners=function(){var t=this.hls;t.off(n.Events.BUFFER_APPENDED,this.onBufferAppended,this),t.off(n.Events.FRAG_BUFFERED,this.onFragBuffered,this),t.off(n.Events.FRAG_LOADED,this.onFragLoaded,this)},e.destroy=function(){this._unregisterListeners(),this.fragments=this.timeRanges=null},e.getAppendedFrag=function(t,e){if(e===s.PlaylistLevelType.MAIN){var r=this.activeFragment,i=this.activeParts;if(!r)return null;if(i)for(var n=i.length;n--;){var a=i[n],o=a?a.end:r.appendedPTS;if(a.start<=t&&void 0!==o&&t<=o)return n>9&&(this.activeParts=i.slice(n-9)),a}else if(r.start<=t&&void 0!==r.appendedPTS&&t<=r.appendedPTS)return r}return this.getBufferedFrag(t,e)},e.getBufferedFrag=function(t,e){for(var r=this.fragments,i=Object.keys(r),n=i.length;n--;){var s=r[i[n]];if((null==s?void 0:s.body.type)===e&&s.buffered){var a=s.body;if(a.start<=t&&t<=a.end)return a}}return null},e.detectEvictedFragments=function(t,e,r){var i=this;Object.keys(this.fragments).forEach((function(n){var s=i.fragments[n];if(s)if(s.buffered){var a=s.range[t];a&&a.time.some((function(t){var r=!i.isTimeBuffered(t.startPTS,t.endPTS,e);return r&&i.removeFragment(s.body),r}))}else s.body.type===r&&i.removeFragment(s.body)}))},e.detectPartialFragments=function(t){var e=this,r=this.timeRanges,i=t.frag,n=t.part;if(r&&"initSegment"!==i.sn){var s=l(i),a=this.fragments[s];a&&(Object.keys(r).forEach((function(t){var s=i.elementaryStreams[t];if(s){var o=r[t],l=null!==n||!0===s.partial;a.range[t]=e.getBufferedTimes(i,n,l,o)}})),a.loaded=null,Object.keys(a.range).length?a.buffered=!0:this.removeFragment(a.body))}},e.fragBuffered=function(t){var e=l(t),r=this.fragments[e];r&&(r.loaded=null,r.buffered=!0)},e.getBufferedTimes=function(t,e,r,i){for(var n={time:[],partial:r},s=e?e.start:t.start,a=e?e.end:t.end,o=t.minEndPTS||a,l=t.maxStartPTS||s,d=0;d<i.length;d++){var u=i.start(d)-this.bufferPadding,c=i.end(d)+this.bufferPadding;if(l>=u&&o<=c){n.time.push({startPTS:Math.max(s,i.start(d)),endPTS:Math.min(a,i.end(d))});break}if(s<c&&a>u)n.partial=!0,n.time.push({startPTS:Math.max(s,i.start(d)),endPTS:Math.min(a,i.end(d))});else if(a<=u)break}return n},e.getPartialFragment=function(t){var e,r,i,n=null,s=0,a=this.bufferPadding,l=this.fragments;return Object.keys(l).forEach((function(d){var u=l[d];u&&o(u)&&(r=u.body.start-a,i=u.body.end+a,t>=r&&t<=i&&(e=Math.min(t-r,i-t),s<=e&&(n=u.body,s=e)))})),n},e.getState=function(t){var e=l(t),r=this.fragments[e];return r?r.buffered?o(r)?i.PARTIAL:i.OK:i.APPENDING:i.NOT_LOADED},e.isTimeBuffered=function(t,e,r){for(var i,n,s=0;s<r.length;s++){if(i=r.start(s)-this.bufferPadding,n=r.end(s)+this.bufferPadding,t>=i&&e<=n)return!0;if(e<=i)return!1}return!1},e.onFragLoaded=function(t,e){var r=e.frag,i=e.part;if("initSegment"!==r.sn&&!r.bitrateTest&&!i){var n=l(r);this.fragments[n]={body:r,loaded:e,buffered:!1,range:Object.create(null)}}},e.onBufferAppended=function(t,e){var r=this,i=e.frag,n=e.part,a=e.timeRanges;if(i.type===s.PlaylistLevelType.MAIN)if(this.activeFragment=i,n){var o=this.activeParts;o||(this.activeParts=o=[]),o.push(n)}else this.activeParts=null;this.timeRanges=a,Object.keys(a).forEach((function(t){var e=a[t];if(r.detectEvictedFragments(t,e),!n)for(var s=0;s<e.length;s++)i.appendedPTS=Math.max(e.end(s),i.appendedPTS||0)}))},e.onFragBuffered=function(t,e){this.detectPartialFragments(e)},e.hasFragment=function(t){var e=l(t);return!!this.fragments[e]},e.removeFragmentsInRange=function(t,e,r){var i=this;Object.keys(this.fragments).forEach((function(n){var s=i.fragments[n];if(s&&s.buffered){var a=s.body;a.type===r&&a.start<e&&a.end>t&&i.removeFragment(a)}}))},e.removeFragment=function(t){var e=l(t);t.stats.loaded=0,t.clearElementaryStreamInfo(),delete this.fragments[e]},e.removeAllFragments=function(){this.fragments=Object.create(null),this.activeFragment=null,this.activeParts=null},t}();function o(t){var e,r;return t.buffered&&((null===(e=t.range.video)||void 0===e?void 0:e.partial)||(null===(r=t.range.audio)||void 0===r?void 0:r.partial))}function l(t){return t.type+"_"+t.level+"_"+t.urlId+"_"+t.sn}},"./src/controller/gap-controller.ts":
|
|
44
|
-
/*!******************************************!*\
|
|
45
|
-
!*** ./src/controller/gap-controller.ts ***!
|
|
46
|
-
\******************************************/(t,e,r)=>{r.r(e),r.d(e,{MAX_START_GAP_JUMP:()=>l,SKIP_BUFFER_HOLE_STEP_SECONDS:()=>d,SKIP_BUFFER_RANGE_START:()=>u,STALL_MINIMUM_DURATION_MS:()=>o,default:()=>c});var i=r(/*! ../utils/buffer-helper */"./src/utils/buffer-helper.ts"),n=r(/*! ../errors */"./src/errors.ts"),s=r(/*! ../events */"./src/events.ts"),a=r(/*! ../utils/logger */"./src/utils/logger.ts"),o=250,l=2,d=.1,u=.05,c=function(){function t(t,e,r,i){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=r,this.hls=i}var e=t.prototype;return e.destroy=function(){this.media=null,this.hls=this.fragmentTracker=null},e.poll=function(t,e){var r=this.config,n=this.media,s=this.stalled;if(null!==n){var d=n.currentTime,u=n.seeking,c=this.seeking&&!u,h=!this.seeking&&u;if(this.seeking=u,d===t){if((h||c)&&(this.stalled=null),!(n.paused&&!u||n.ended||0===n.playbackRate)&&i.BufferHelper.getBuffered(n).length){var f=i.BufferHelper.bufferInfo(n,d,0),p=f.len>0,g=f.nextStart||0;if(p||g){if(u){var v=f.len>l,m=!g||e&&e.start<=d||g-d>l&&!this.fragmentTracker.getPartialFragment(d);if(v||m)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var y,E=Math.max(g,f.start||0)-d,T=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,_=(null==T||null===(y=T.details)||void 0===y?void 0:y.live)?2*T.details.targetduration:l;if(E>0&&E<=_)return void this._trySkipBufferHole(null)}var S=self.performance.now();if(null!==s){var b=S-s;if(u||!(b>=o)||(this._reportStall(f),this.media)){var A=i.BufferHelper.bufferInfo(n,d,r.maxBufferHole);this._tryFixBufferStall(A,b)}}else this.stalled=S}}}else if(this.moved=!0,null!==s){if(this.stallReported){var L=self.performance.now()-s;a.logger.warn("playback not stuck anymore @"+d+", after "+Math.round(L)+"ms"),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}}},e._tryFixBufferStall=function(t,e){var r=this.config,i=this.fragmentTracker,n=this.media;if(null!==n){var s=n.currentTime,o=i.getPartialFragment(s);if(o&&(this._trySkipBufferHole(o)||!this.media))return;t.len>r.maxBufferHole&&e>1e3*r.highBufferWatchdogPeriod&&(a.logger.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}},e._reportStall=function(t){var e=this.hls,r=this.media;!this.stallReported&&r&&(this.stallReported=!0,a.logger.warn("Playback stalling at @"+r.currentTime+" due to low buffer ("+JSON.stringify(t)+")"),e.trigger(s.Events.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,buffer:t.len}))},e._trySkipBufferHole=function(t){var e=this.config,r=this.hls,o=this.media;if(null===o)return 0;for(var l=o.currentTime,c=0,h=i.BufferHelper.getBuffered(o),f=0;f<h.length;f++){var p=h.start(f);if(l+e.maxBufferHole>=c&&l<p){var g=Math.max(p+u,o.currentTime+d);return a.logger.warn("skipping hole, adjusting currentTime from "+l+" to "+g),this.moved=!0,this.stalled=null,o.currentTime=g,t&&r.trigger(s.Events.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,reason:"fragment loaded with buffer holes, seeking from "+l+" to "+g,frag:t}),g}c=h.end(f)}return 0},e._tryNudgeBuffer=function(){var t=this.config,e=this.hls,r=this.media,i=this.nudgeRetry;if(null!==r){var o=r.currentTime;if(this.nudgeRetry++,i<t.nudgeMaxRetry){var l=o+(i+1)*t.nudgeOffset;a.logger.warn("Nudging 'currentTime' from "+o+" to "+l),r.currentTime=l,e.trigger(s.Events.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.BUFFER_NUDGE_ON_STALL,fatal:!1})}else a.logger.error("Playhead still not moving while enough data buffered @"+o+" after "+t.nudgeMaxRetry+" nudges"),e.trigger(s.Events.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!0})}},t}()},"./src/controller/id3-track-controller.ts":
|
|
47
|
-
/*!************************************************!*\
|
|
48
|
-
!*** ./src/controller/id3-track-controller.ts ***!
|
|
49
|
-
\************************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>h});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../events */"./src/events.ts"),s=r(/*! ../utils/texttrack-utils */"./src/utils/texttrack-utils.ts"),a=r(/*! ../demux/id3 */"./src/demux/id3.ts"),o=r(/*! ../loader/date-range */"./src/loader/date-range.ts"),l=r(/*! ../types/demuxer */"./src/types/demuxer.ts");function d(){return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}var u=function(){var t=d();try{new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}();function c(t,e){return t.getTime()/1e3-e}const h=function(){function t(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=t,this._registerListeners()}var e=t.prototype;return e.destroy=function(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null},e._registerListeners=function(){var t=this.hls;t.on(n.Events.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(n.Events.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(n.Events.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(n.Events.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(n.Events.LEVEL_UPDATED,this.onLevelUpdated,this)},e._unregisterListeners=function(){var t=this.hls;t.off(n.Events.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(n.Events.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(n.Events.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(n.Events.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(n.Events.LEVEL_UPDATED,this.onLevelUpdated,this)},e.onMediaAttached=function(t,e){this.media=e.media},e.onMediaDetaching=function(){this.id3Track&&((0,s.clearCurrentCues)(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})},e.onManifestLoading=function(){this.dateRangeCuesAppended={}},e.createTrack=function(t){var e=this.getID3Track(t.textTracks);return e.mode="hidden",e},e.getID3Track=function(t){if(this.media){for(var e=0;e<t.length;e++){var r=t[e];if("metadata"===r.kind&&"id3"===r.label)return(0,s.sendAddTrackEvent)(r,this.media),r}return this.media.addTextTrack("metadata","id3")}},e.onFragParsingMetadata=function(t,e){if(this.media){var r=this.hls.config,i=r.enableEmsgMetadataCues,n=r.enableID3MetadataCues;if(i||n){e.frag;var s=e.samples;e.details,this.id3Track||(this.id3Track=this.createTrack(this.media));for(var o=d(),c=0;c<s.length;c++){var h=s[c].type;if((h!==l.MetadataSchema.emsg||i)&&n){var f=a.getID3Frames(s[c].data);if(f){var p=s[c].pts,g=p+s[c].duration;g>u&&(g=u),g-p<=0&&(g=p+.25);for(var v=0;v<f.length;v++){var m=f[v];if(!a.isTimeStampFrame(m)){this.updateId3CueEnds(p);var y=new o(p,g,"");y.value=m,h&&(y.type=h),this.id3Track.addCue(y)}}}}}}}},e.updateId3CueEnds=function(t){var e,r=null===(e=this.id3Track)||void 0===e?void 0:e.cues;if(r)for(var i=r.length;i--;){var n=r[i];n.startTime<t&&n.endTime===u&&(n.endTime=t)}},e.onBufferFlushing=function(t,e){var r=e.startOffset,i=e.endOffset,n=e.type,a=this.id3Track,o=this.hls;if(o){var d,u=o.config,c=u.enableEmsgMetadataCues,h=u.enableID3MetadataCues;a&&(c||h)&&(d="audio"===n?function(t){return t.type===l.MetadataSchema.audioId3&&h}:"video"===n?function(t){return t.type===l.MetadataSchema.emsg&&c}:function(t){return t.type===l.MetadataSchema.audioId3&&h||t.type===l.MetadataSchema.emsg&&c},(0,s.removeCuesInRange)(a,r,i,d))}},e.onLevelUpdated=function(t,e){var r=this,n=e.details;if(this.media&&n.hasProgramDateTime&&this.hls.config.enableDateRangeMetadataCues){var s=this.dateRangeCuesAppended,a=this.id3Track,h=n.dateRanges,f=Object.keys(h);if(a)for(var p=Object.keys(s).filter((function(t){return!f.includes(t)})),g=function(t){var e=p[t];Object.keys(s[e].cues).forEach((function(t){a.removeCue(s[e].cues[t])})),delete s[e]},v=p.length;v--;)g(v);var m=n.fragments[n.fragments.length-1];if(0!==f.length&&(0,i.isFiniteNumber)(null==m?void 0:m.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var y=m.programDateTime/1e3-m.start,E=d(),T=function(t){var e=f[t],i=h[e],n=s[e],a=(null==n?void 0:n.cues)||{},d=(null==n?void 0:n.durationKnown)||!1,p=c(i.startDate,y),g=u,v=i.endDate;if(v)g=c(v,y),d=!0;else if(i.endOnNext&&!d){var m=f.reduce((function(t,e){var r=h[e];return r.class===i.class&&r.id!==e&&r.startDate>i.startDate&&t.push(r),t}),[]).sort((function(t,e){return t.startDate.getTime()-e.startDate.getTime()}))[0];m&&(g=c(m.startDate,y),d=!0)}for(var T,_=Object.keys(i.attr),S=0;S<_.length;S++){var b=_[S];if(b!==o.DateRangeAttribute.ID&&b!==o.DateRangeAttribute.CLASS&&b!==o.DateRangeAttribute.START_DATE&&b!==o.DateRangeAttribute.DURATION&&b!==o.DateRangeAttribute.END_DATE&&b!==o.DateRangeAttribute.END_ON_NEXT){var A=a[b];if(A)d&&!n.durationKnown&&(A.endTime=g);else{var L=i.attr[b];A=new E(p,g,""),b!==o.DateRangeAttribute.SCTE35_OUT&&b!==o.DateRangeAttribute.SCTE35_IN||(T=L,L=Uint8Array.from(T.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer),A.value={key:b,data:L},A.type=l.MetadataSchema.dateRange,r.id3Track.addCue(A),a[b]=A}}}s[e]={cues:a,dateRange:i,durationKnown:d}},_=0;_<f.length;_++)T(_)}}},t}()},"./src/controller/latency-controller.ts":
|
|
50
|
-
/*!**********************************************!*\
|
|
51
|
-
!*** ./src/controller/latency-controller.ts ***!
|
|
52
|
-
\**********************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>o});var i=r(/*! ../errors */"./src/errors.ts"),n=r(/*! ../events */"./src/events.ts"),s=r(/*! ../utils/logger */"./src/utils/logger.ts");function a(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}var o=function(){function t(t){var e=this;this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=function(){return e.timeupdate()},this.hls=t,this.config=t.config,this.registerListeners()}var e,r,o,l=t.prototype;return l.destroy=function(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null},l.registerListeners=function(){this.hls.on(n.Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(n.Events.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(n.Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(n.Events.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(n.Events.ERROR,this.onError,this)},l.unregisterListeners=function(){this.hls.off(n.Events.MEDIA_ATTACHED,this.onMediaAttached),this.hls.off(n.Events.MEDIA_DETACHING,this.onMediaDetaching),this.hls.off(n.Events.MANIFEST_LOADING,this.onManifestLoading),this.hls.off(n.Events.LEVEL_UPDATED,this.onLevelUpdated),this.hls.off(n.Events.ERROR,this.onError)},l.onMediaAttached=function(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)},l.onMediaDetaching=function(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)},l.onManifestLoading=function(){this.levelDetails=null,this._latency=null,this.stallCount=0},l.onLevelUpdated=function(t,e){var r=e.details;this.levelDetails=r,r.advanced&&this.timeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)},l.onError=function(t,e){e.details===i.ErrorDetails.BUFFER_STALLED_ERROR&&(this.stallCount++,s.logger.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))},l.timeupdate=function(){var t=this.media,e=this.levelDetails;if(t&&e){this.currentTime=t.currentTime;var r=this.computeLatency();if(null!==r){this._latency=r;var i=this.config,n=i.lowLatencyMode,s=i.maxLiveSyncPlaybackRate;if(n&&1!==s){var a=this.targetLatency;if(null!==a){var o=r-a,l=o<Math.min(this.maxLatency,a+e.targetduration);if(e.live&&l&&o>.05&&this.forwardBufferLength>1){var d=Math.min(2,Math.max(1,s)),u=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;t.playbackRate=Math.min(d,Math.max(1,u))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}}}}},l.estimateLiveEdge=function(){var t=this.levelDetails;return null===t?null:t.edge+t.age},l.computeLatency=function(){var t=this.estimateLiveEdge();return null===t?null:t-this.currentTime},e=t,(r=[{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var t=this.config,e=this.levelDetails;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}},{key:"targetLatency",get:function(){var t=this.levelDetails;if(null===t)return null;var e=t.holdBack,r=t.partHoldBack,i=t.targetduration,n=this.config,s=n.liveSyncDuration,a=n.liveSyncDurationCount,o=n.lowLatencyMode,l=this.hls.userConfig,d=o&&r||e;(l.liveSyncDuration||l.liveSyncDurationCount||0===d)&&(d=void 0!==s?s:a*i);var u=i;return d+Math.min(1*this.stallCount,u)}},{key:"liveSyncPosition",get:function(){var t=this.estimateLiveEdge(),e=this.targetLatency,r=this.levelDetails;if(null===t||null===e||null===r)return null;var i=r.edge,n=t-e-this.edgeStalled,s=i-r.totalduration,a=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(s,n),a)}},{key:"drift",get:function(){var t=this.levelDetails;return null===t?1:t.drift}},{key:"edgeStalled",get:function(){var t=this.levelDetails;if(null===t)return 0;var e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}},{key:"forwardBufferLength",get:function(){var t=this.media,e=this.levelDetails;if(!t||!e)return 0;var r=t.buffered.length;return(r?t.buffered.end(r-1):e.edge)-this.currentTime}}])&&a(e.prototype,r),o&&a(e,o),Object.defineProperty(e,"prototype",{writable:!1}),t}()},"./src/controller/level-controller.ts":
|
|
53
|
-
/*!********************************************!*\
|
|
54
|
-
!*** ./src/controller/level-controller.ts ***!
|
|
55
|
-
\********************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>p});var i=r(/*! ../types/level */"./src/types/level.ts"),n=r(/*! ../events */"./src/events.ts"),s=r(/*! ../errors */"./src/errors.ts"),a=r(/*! ../utils/codecs */"./src/utils/codecs.ts"),o=r(/*! ./level-helper */"./src/controller/level-helper.ts"),l=r(/*! ./base-playlist-controller */"./src/controller/base-playlist-controller.ts"),d=r(/*! ../types/loader */"./src/types/loader.ts");function u(){return(u=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t}).apply(this,arguments)}function c(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function h(t,e){return(h=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}var f=/chrome|firefox/.test(navigator.userAgent.toLowerCase()),p=function(t){var e,r;function l(e){var r;return(r=t.call(this,e,"[level-controller]")||this)._levels=[],r._firstLevel=-1,r._startLevel=void 0,r.currentLevelIndex=-1,r.manualLevelIndex=-1,r.onParsedComplete=void 0,r._registerListeners(),r}r=t,(e=l).prototype=Object.create(r.prototype),e.prototype.constructor=e,h(e,r);var p,g,v,m=l.prototype;return m._registerListeners=function(){var t=this.hls;t.on(n.Events.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(n.Events.LEVEL_LOADED,this.onLevelLoaded,this),t.on(n.Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(n.Events.FRAG_LOADED,this.onFragLoaded,this),t.on(n.Events.ERROR,this.onError,this)},m._unregisterListeners=function(){var t=this.hls;t.off(n.Events.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(n.Events.LEVEL_LOADED,this.onLevelLoaded,this),t.off(n.Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(n.Events.FRAG_LOADED,this.onFragLoaded,this),t.off(n.Events.ERROR,this.onError,this)},m.destroy=function(){this._unregisterListeners(),this.manualLevelIndex=-1,this._levels.length=0,t.prototype.destroy.call(this)},m.startLoad=function(){this._levels.forEach((function(t){t.loadError=0})),t.prototype.startLoad.call(this)},m.onManifestLoaded=function(t,e){var r,l,d=[],u=[],c=[],h={},p=!1,g=!1,v=!1;if(e.levels.forEach((function(t){var e=t.attrs;p=p||!(!t.width||!t.height),g=g||!!t.videoCodec,v=v||!!t.audioCodec,f&&t.audioCodec&&-1!==t.audioCodec.indexOf("mp4a.40.34")&&(t.audioCodec=void 0);var r=t.bitrate+"-"+t.attrs.RESOLUTION+"-"+t.attrs.CODECS;(l=h[r])?l.url.push(t.url):(l=new i.Level(t),h[r]=l,d.push(l)),e&&(e.AUDIO&&(0,o.addGroupId)(l,"audio",e.AUDIO),e.SUBTITLES&&(0,o.addGroupId)(l,"text",e.SUBTITLES))})),(p||g)&&v&&(d=d.filter((function(t){var e=t.videoCodec,r=t.width,i=t.height;return!!e||!(!r||!i)}))),d=d.filter((function(t){var e=t.audioCodec,r=t.videoCodec;return(!e||(0,a.isCodecSupportedInMp4)(e,"audio"))&&(!r||(0,a.isCodecSupportedInMp4)(r,"video"))})),e.audioTracks&&(u=e.audioTracks.filter((function(t){return!t.audioCodec||(0,a.isCodecSupportedInMp4)(t.audioCodec,"audio")})),(0,o.assignTrackIdsByGroup)(u)),e.subtitles&&(c=e.subtitles,(0,o.assignTrackIdsByGroup)(c)),d.length>0){r=d[0].bitrate,d.sort((function(t,e){return t.bitrate-e.bitrate})),this._levels=d;for(var m=0;m<d.length;m++)if(d[m].bitrate===r){this._firstLevel=m,this.log("manifest loaded, "+d.length+" level(s) found, first bitrate: "+r);break}var y=v&&!g,E={levels:d,audioTracks:u,subtitleTracks:c,firstLevel:this._firstLevel,stats:e.stats,audio:v,video:g,altAudio:!y&&u.some((function(t){return!!t.url}))};this.hls.trigger(n.Events.MANIFEST_PARSED,E),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}else this.hls.trigger(n.Events.ERROR,{type:s.ErrorTypes.MEDIA_ERROR,details:s.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,reason:"no level with compatible codecs found in manifest"})},m.onError=function(e,r){var i;if(t.prototype.onError.call(this,e,r),!r.fatal){var n=r.context,a=this._levels[this.currentLevelIndex];if(n&&(n.type===d.PlaylistContextType.AUDIO_TRACK&&a.audioGroupIds&&n.groupId===a.audioGroupIds[a.urlId]||n.type===d.PlaylistContextType.SUBTITLE_TRACK&&a.textGroupIds&&n.groupId===a.textGroupIds[a.urlId]))this.redundantFailover(this.currentLevelIndex);else{var o,l=!1,u=!0;switch(r.details){case s.ErrorDetails.FRAG_LOAD_ERROR:case s.ErrorDetails.FRAG_LOAD_TIMEOUT:case s.ErrorDetails.KEY_LOAD_ERROR:case s.ErrorDetails.KEY_LOAD_TIMEOUT:if(r.frag){var c=r.frag.type===d.PlaylistLevelType.MAIN?r.frag.level:this.currentLevelIndex,h=this._levels[c];h?(h.fragmentError++,h.fragmentError>this.hls.config.fragLoadingMaxRetry&&(o=c)):o=c}break;case s.ErrorDetails.LEVEL_LOAD_ERROR:case s.ErrorDetails.LEVEL_LOAD_TIMEOUT:n&&(n.deliveryDirectives&&(u=!1),o=n.level),l=!0;break;case s.ErrorDetails.REMUX_ALLOC_ERROR:o=null!=(i=r.level)?i:this.currentLevelIndex,l=!0}void 0!==o&&this.recoverLevel(r,o,l,u)}}},m.recoverLevel=function(t,e,r,i){var n=t.details,s=this._levels[e];if(s.loadError++,r){if(!this.retryLoadingOrFail(t))return void(this.currentLevelIndex=-1);t.levelRetry=!0}if(i){var a=s.url.length;if(a>1&&s.loadError<a)t.levelRetry=!0,this.redundantFailover(e);else if(-1===this.manualLevelIndex){for(var o=-1,l=this._levels,d=l.length;d--;){var u=(d+this.currentLevelIndex)%l.length;if(u!==this.currentLevelIndex&&0===l[u].loadError){o=u;break}}o>-1&&this.currentLevelIndex!==o&&(this.warn(n+": switch to "+o),t.levelRetry=!0,this.hls.nextAutoLevel=o)}}},m.redundantFailover=function(t){var e=this._levels[t],r=e.url.length;if(r>1){var i=(e.urlId+1)%r;this.warn("Switching to redundant URL-id "+i),this._levels.forEach((function(t){t.urlId=i})),this.level=t}},m.onFragLoaded=function(t,e){var r=e.frag;if(void 0!==r&&r.type===d.PlaylistLevelType.MAIN){var i=this._levels[r.level];void 0!==i&&(i.fragmentError=0,i.loadError=0)}},m.onLevelLoaded=function(t,e){var r,i,n=e.level,s=e.details,a=this._levels[n];if(!a)return this.warn("Invalid level index "+n),void(null!==(i=e.deliveryDirectives)&&void 0!==i&&i.skip&&(s.deltaUpdateFailed=!0));n===this.currentLevelIndex?(0===a.fragmentError&&(a.loadError=0,this.retryCount=0),this.playlistLoaded(n,e,a.details)):null!==(r=e.deliveryDirectives)&&void 0!==r&&r.skip&&(s.deltaUpdateFailed=!0)},m.onAudioTrackSwitched=function(t,e){var r=this.hls.levels[this.currentLevelIndex];if(r&&r.audioGroupIds){for(var i=-1,n=this.hls.audioTracks[e.id].groupId,s=0;s<r.audioGroupIds.length;s++)if(r.audioGroupIds[s]===n){i=s;break}i!==r.urlId&&(r.urlId=i,this.startLoad())}},m.loadPlaylist=function(t){var e=this.currentLevelIndex,r=this._levels[e];if(this.canLoad&&r&&r.url.length>0){var i=r.urlId,s=r.url[i];if(t)try{s=t.addDirectives(s)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}this.log("Attempt loading level index "+e+(t?" at sn "+t.msn+" part "+t.part:"")+" with URL-id "+i+" "+s),this.clearTimer(),this.hls.trigger(n.Events.LEVEL_LOADING,{url:s,level:e,id:i,deliveryDirectives:t||null})}},m.removeLevel=function(t,e){var r=function(t,r){return r!==e},i=this._levels.filter((function(i,n){return n!==t||i.url.length>1&&void 0!==e&&(i.url=i.url.filter(r),i.audioGroupIds&&(i.audioGroupIds=i.audioGroupIds.filter(r)),i.textGroupIds&&(i.textGroupIds=i.textGroupIds.filter(r)),i.urlId=0,!0)})).map((function(t,e){var r=t.details;return null!=r&&r.fragments&&r.fragments.forEach((function(t){t.level=e})),t}));this._levels=i,this.hls.trigger(n.Events.LEVELS_UPDATED,{levels:i})},p=l,(g=[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(t){var e,r=this._levels;if(0!==r.length&&(this.currentLevelIndex!==t||null===(e=r[t])||void 0===e||!e.details)){if(t<0||t>=r.length){var i=t<0;if(this.hls.trigger(n.Events.ERROR,{type:s.ErrorTypes.OTHER_ERROR,details:s.ErrorDetails.LEVEL_SWITCH_ERROR,level:t,fatal:i,reason:"invalid level idx"}),i)return;t=Math.min(t,r.length-1)}this.clearTimer();var a=this.currentLevelIndex,o=r[a],l=r[t];this.log("switching to level "+t+" from "+a),this.currentLevelIndex=t;var d=u({},l,{level:t,maxBitrate:l.maxBitrate,uri:l.uri,urlId:l.urlId});delete d._urlId,this.hls.trigger(n.Events.LEVEL_SWITCHING,d);var c=l.details;if(!c||c.live){var h=this.switchParams(l.uri,null==o?void 0:o.details);this.loadPlaylist(h)}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(t){this._firstLevel=t}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var t=this.hls.config.startLevel;return void 0!==t?t:this._firstLevel}return this._startLevel},set:function(t){this._startLevel=t}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}}])&&c(p.prototype,g),v&&c(p,v),Object.defineProperty(p,"prototype",{writable:!1}),l}(l.default)},"./src/controller/level-helper.ts":
|
|
56
|
-
/*!****************************************!*\
|
|
57
|
-
!*** ./src/controller/level-helper.ts ***!
|
|
58
|
-
\****************************************/(t,e,r)=>{r.r(e),r.d(e,{addGroupId:()=>o,addSliding:()=>v,adjustSliding:()=>g,assignTrackIdsByGroup:()=>l,computeReloadInterval:()=>m,getFragmentWithSN:()=>y,getPartWith:()=>E,mapFragmentIntersection:()=>p,mapPartIntersection:()=>f,mergeDetails:()=>h,updateFragPTSDTS:()=>c,updatePTS:()=>d});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../utils/logger */"./src/utils/logger.ts"),s=r(/*! ../loader/date-range */"./src/loader/date-range.ts");function a(){return(a=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t}).apply(this,arguments)}function o(t,e,r){switch(e){case"audio":t.audioGroupIds||(t.audioGroupIds=[]),t.audioGroupIds.push(r);break;case"text":t.textGroupIds||(t.textGroupIds=[]),t.textGroupIds.push(r)}}function l(t){var e={};t.forEach((function(t){var r=t.groupId||"";t.id=e[r]=e[r]||0,e[r]++}))}function d(t,e,r){u(t[e],t[r])}function u(t,e){var r=e.startPTS;if((0,i.isFiniteNumber)(r)){var n,s=0;e.sn>t.sn?(s=r-t.start,n=t):(s=t.start-r,n=e),n.duration!==s&&(n.duration=s)}else e.sn>t.sn?t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration:e.start=Math.max(t.start-e.duration,0)}function c(t,e,r,s,a,o){s-r<=0&&(n.logger.warn("Fragment should have a positive duration",e),s=r+e.duration,o=a+e.duration);var l=r,d=s,c=e.startPTS,h=e.endPTS;if((0,i.isFiniteNumber)(c)){var f=Math.abs(c-r);(0,i.isFiniteNumber)(e.deltaPTS)?e.deltaPTS=Math.max(f,e.deltaPTS):e.deltaPTS=f,l=Math.max(r,c),r=Math.min(r,c),a=Math.min(a,e.startDTS),d=Math.min(s,h),s=Math.max(s,h),o=Math.max(o,e.endDTS)}e.duration=s-r;var p=r-e.start;e.appendedPTS=s,e.start=e.startPTS=r,e.maxStartPTS=l,e.startDTS=a,e.endPTS=s,e.minEndPTS=d,e.endDTS=o;var g,v=e.sn;if(!t||v<t.startSN||v>t.endSN)return 0;var m=v-t.startSN,y=t.fragments;for(y[m]=e,g=m;g>0;g--)u(y[g],y[g-1]);for(g=m;g<y.length-1;g++)u(y[g],y[g+1]);return t.fragmentHint&&u(y[y.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,p}function h(t,e){for(var r=null,o=t.fragments,l=o.length-1;l>=0;l--){var d=o[l].initSegment;if(d){r=d;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;var u,h,v,m,y,E=0;if(p(t,e,(function(t,n){t.relurl&&(E=t.cc-n.cc),(0,i.isFiniteNumber)(t.startPTS)&&(0,i.isFiniteNumber)(t.endPTS)&&(n.start=n.startPTS=t.startPTS,n.startDTS=t.startDTS,n.appendedPTS=t.appendedPTS,n.maxStartPTS=t.maxStartPTS,n.endPTS=t.endPTS,n.endDTS=t.endDTS,n.minEndPTS=t.minEndPTS,n.duration=t.endPTS-t.startPTS,n.duration&&(u=n),e.PTSKnown=e.alignedSliding=!0),n.elementaryStreams=t.elementaryStreams,n.loader=t.loader,n.stats=t.stats,n.urlId=t.urlId,t.initSegment&&(n.initSegment=t.initSegment,r=t.initSegment)})),r&&(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach((function(t){var e;t.initSegment&&t.initSegment.relurl!==(null===(e=r)||void 0===e?void 0:e.relurl)||(t.initSegment=r)})),e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some((function(t){return!t})),e.deltaUpdateFailed){n.logger.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var T=e.skippedSegments;T--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=(h=t.dateRanges,v=e.dateRanges,m=e.recentlyRemovedDateranges,y=a({},h),m&&m.forEach((function(t){delete y[t]})),Object.keys(v).forEach((function(t){var e=new s.DateRange(v[t].attr,y[t]);e.isValid?y[t]=e:n.logger.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'+JSON.stringify(v[t].attr)+'"')})),y));var _=e.fragments;if(E){n.logger.warn("discontinuity sliding from playlist, take drift into account");for(var S=0;S<_.length;S++)_[S].cc+=E}e.skippedSegments&&(e.startCC=e.fragments[0].cc),f(t.partList,e.partList,(function(t,e){e.elementaryStreams=t.elementaryStreams,e.stats=t.stats})),u?c(e,u,u.startPTS,u.endPTS,u.startDTS,u.endDTS):g(t,e),_.length&&(e.totalduration=e.edge-_[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;var b=e.advancedDateTime;if(e.advanced&&b){var A=e.edge;e.driftStart||(e.driftStartTime=b,e.driftStart=A),e.driftEndTime=b,e.driftEnd=A}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime}function f(t,e,r){if(t&&e)for(var i=0,n=0,s=t.length;n<=s;n++){var a=t[n],o=e[n+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?r(a,o):i--}}function p(t,e,r){for(var i=e.skippedSegments,n=Math.max(t.startSN,e.startSN)-e.startSN,s=(t.fragmentHint?1:0)+(i?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,d=n;d<=s;d++){var u=l[a+d],c=o[d];i&&!c&&d<i&&(c=e.fragments[d]=u),u&&c&&r(u,c)}}function g(t,e){var r=e.startSN+e.skippedSegments-t.startSN,i=t.fragments;r<0||r>=i.length||v(e,i[r].start)}function v(t,e){if(e){for(var r=t.fragments,i=t.skippedSegments;i<r.length;i++)r[i].start+=e;t.fragmentHint&&(t.fragmentHint.start+=e)}}function m(t,e){var r,i=1e3*t.levelTargetDuration,n=i/2,s=t.age,a=s>0&&s<3*i,o=e.loading.end-e.loading.start,l=t.availabilityDelay;if(!1===t.updated)if(a){var d=333*t.misses;r=Math.max(Math.min(n,2*o),d),t.availabilityDelay=(t.availabilityDelay||0)+r}else r=n;else a?(l=Math.min(l||i/2,s),t.availabilityDelay=l,r=l+i-s):r=i-o;return Math.round(r)}function y(t,e,r){if(!t||!t.details)return null;var i=t.details,n=i.fragments[e-i.startSN];return n||((n=i.fragmentHint)&&n.sn===e?n:e<i.startSN&&r&&r.sn===e?r:null)}function E(t,e,r){if(!t||!t.details)return null;var i=t.details.partList;if(i)for(var n=i.length;n--;){var s=i[n];if(s.index===r&&s.fragment.sn===e)return s}return null}},"./src/controller/stream-controller.ts":
|
|
59
|
-
/*!*********************************************!*\
|
|
60
|
-
!*** ./src/controller/stream-controller.ts ***!
|
|
61
|
-
\*********************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>m});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ./base-stream-controller */"./src/controller/base-stream-controller.ts"),s=r(/*! ../is-supported */"./src/is-supported.ts"),a=r(/*! ../events */"./src/events.ts"),o=r(/*! ../utils/buffer-helper */"./src/utils/buffer-helper.ts"),l=r(/*! ./fragment-tracker */"./src/controller/fragment-tracker.ts"),d=r(/*! ../types/loader */"./src/types/loader.ts"),u=r(/*! ../loader/fragment */"./src/loader/fragment.ts"),c=r(/*! ../demux/transmuxer-interface */"./src/demux/transmuxer-interface.ts"),h=r(/*! ../types/transmuxer */"./src/types/transmuxer.ts"),f=r(/*! ./gap-controller */"./src/controller/gap-controller.ts"),p=r(/*! ../errors */"./src/errors.ts");function g(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function v(t,e){return(v=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}var m=function(t){var e,r;function m(e,r){var i;return(i=t.call(this,e,r,"[stream-controller]")||this).audioCodecSwap=!1,i.gapController=null,i.level=-1,i._forceStartLoad=!1,i.altAudio=!1,i.audioOnly=!1,i.fragPlaying=null,i.onvplaying=null,i.onvseeked=null,i.fragLastKbps=0,i.couldBacktrack=!1,i.backtrackFragment=null,i.audioCodecSwitch=!1,i.videoBuffer=null,i._registerListeners(),i}r=t,(e=m).prototype=Object.create(r.prototype),e.prototype.constructor=e,v(e,r);var y,E,T,_=m.prototype;return _._registerListeners=function(){var t=this.hls;t.on(a.Events.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.Events.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.Events.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.Events.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.Events.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.Events.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(a.Events.ERROR,this.onError,this),t.on(a.Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(a.Events.BUFFER_CREATED,this.onBufferCreated,this),t.on(a.Events.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.Events.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.Events.FRAG_BUFFERED,this.onFragBuffered,this)},_._unregisterListeners=function(){var t=this.hls;t.off(a.Events.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.Events.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.Events.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.Events.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.Events.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(a.Events.ERROR,this.onError,this),t.off(a.Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(a.Events.BUFFER_CREATED,this.onBufferCreated,this),t.off(a.Events.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.Events.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.Events.FRAG_BUFFERED,this.onFragBuffered,this)},_.onHandlerDestroying=function(){this._unregisterListeners(),this.onMediaDetaching()},_.startLoad=function(t){if(this.levels){var e=this.lastCurrentTime,r=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,this.fragLoadError=0,!this.startFragRequested){var i=r.startLevel;-1===i&&(r.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=r.nextAutoLevel),this.level=r.nextLoadLevel=i,this.loadedmetadata=!1}e>0&&-1===t&&(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=n.State.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=n.State.STOPPED},_.stopLoad=function(){this._forceStartLoad=!1,t.prototype.stopLoad.call(this)},_.doTick=function(){switch(this.state){case n.State.IDLE:this.doTickIdle();break;case n.State.WAITING_LEVEL:var t,e=this.levels,r=this.level,i=null==e||null===(t=e[r])||void 0===t?void 0:t.details;if(i&&(!i.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(i))break;this.state=n.State.IDLE;break}break;case n.State.FRAG_LOADING_WAITING_RETRY:var s,a=self.performance.now(),o=this.retryDate;(!o||a>=o||null!==(s=this.media)&&void 0!==s&&s.seeking)&&(this.log("retryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.level),this.state=n.State.IDLE)}this.onTickEnd()},_.onTickEnd=function(){t.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},_.doTickIdle=function(){var t,e,r=this.hls,i=this.levelLastLoaded,s=this.levels,o=this.media,c=r.config,h=r.nextLoadLevel;if(null!==i&&(o||!this.startFragRequested&&c.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)&&s&&s[h]){var f=s[h];this.level=r.nextLoadLevel=h;var p=f.details;if(!p||this.state===n.State.WAITING_LEVEL||p.live&&this.levelLastLoaded!==h)this.state=n.State.WAITING_LEVEL;else{var g=this.getMainFwdBufferInfo();if(null!==g&&!(g.len>=this.getMaxBufferLength(f.maxBitrate))){if(this._streamEnded(g,p)){var v={};return this.altAudio&&(v.type="video"),this.hls.trigger(a.Events.BUFFER_EOS,v),void(this.state=n.State.ENDED)}this.backtrackFragment&&this.backtrackFragment.start>g.end&&(this.backtrackFragment=null);var m=this.backtrackFragment?this.backtrackFragment.start:g.end,y=this.getNextFragment(m,p);if(this.couldBacktrack&&!this.fragPrevious&&y&&"initSegment"!==y.sn&&this.fragmentTracker.getState(y)!==l.FragmentState.OK){var E,T=(null!=(E=this.backtrackFragment)?E:y).sn-p.startSN,_=p.fragments[T-1];_&&y.cc===_.cc&&(y=_,this.fragmentTracker.removeFragment(_))}else this.backtrackFragment&&g.len&&(this.backtrackFragment=null);if(y&&this.fragmentTracker.getState(y)===l.FragmentState.OK&&this.nextLoadPosition>m){var S=this.audioOnly&&!this.altAudio?u.ElementaryStreamTypes.AUDIO:u.ElementaryStreamTypes.VIDEO;o&&this.afterBufferFlushed(o,S,d.PlaylistLevelType.MAIN),y=this.getNextFragment(this.nextLoadPosition,p)}y&&(!y.initSegment||y.initSegment.data||this.bitrateTest||(y=y.initSegment),"identity"!==(null===(t=y.decryptdata)||void 0===t?void 0:t.keyFormat)||null!==(e=y.decryptdata)&&void 0!==e&&e.key?this.loadFragment(y,p,m):this.loadKey(y,p))}}}},_.loadFragment=function(e,r,i){var n,s=this.fragmentTracker.getState(e);this.fragCurrent=e,s===l.FragmentState.NOT_LOADED?"initSegment"===e.sn?this._loadInitSegment(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)):(this.startFragRequested=!0,t.prototype.loadFragment.call(this,e,r,i)):s===l.FragmentState.APPENDING?this.reduceMaxBufferLength(e.duration)&&this.fragmentTracker.removeFragment(e):0===(null===(n=this.media)||void 0===n?void 0:n.buffered.length)&&this.fragmentTracker.removeAllFragments()},_.getAppendedFrag=function(t){var e=this.fragmentTracker.getAppendedFrag(t,d.PlaylistLevelType.MAIN);return e&&"fragment"in e?e.fragment:e},_.getBufferedFrag=function(t){return this.fragmentTracker.getBufferedFrag(t,d.PlaylistLevelType.MAIN)},_.followingBufferedFrag=function(t){return t?this.getBufferedFrag(t.end+.5):null},_.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},_.nextLevelSwitch=function(){var t=this.levels,e=this.media;if(null!=e&&e.readyState){var r,i=this.getAppendedFrag(e.currentTime);if(i&&i.start>1&&this.flushMainBuffer(0,i.start-1),!e.paused&&t){var n=t[this.hls.nextLoadLevel],s=this.fragLastKbps;r=s&&this.fragCurrent?this.fragCurrent.duration*n.maxBitrate/(1e3*s)+1:0}else r=0;var a=this.getBufferedFrag(e.currentTime+r);if(a){var o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();var l=o.maxStartPTS?o.maxStartPTS:o.start,d=o.duration,u=Math.max(a.end,l+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,.5*d),.75*d));this.flushMainBuffer(u,Number.POSITIVE_INFINITY)}}}},_.abortCurrentFrag=function(){var t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,null!=t&&t.loader&&t.loader.abort(),this.state){case n.State.KEY_LOADING:case n.State.FRAG_LOADING:case n.State.FRAG_LOADING_WAITING_RETRY:case n.State.PARSING:case n.State.PARSED:this.state=n.State.IDLE}this.nextLoadPosition=this.getLoadPosition()},_.flushMainBuffer=function(e,r){t.prototype.flushMainBuffer.call(this,e,r,this.altAudio?"video":null)},_.onMediaAttached=function(e,r){t.prototype.onMediaAttached.call(this,e,r);var i=r.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new f.default(this.config,i,this.fragmentTracker,this.hls)},_.onMediaDetaching=function(){var e=this.media;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),t.prototype.onMediaDetaching.call(this)},_.onMediaPlaying=function(){this.tick()},_.onMediaSeeked=function(){var t=this.media,e=t?t.currentTime:null;(0,i.isFiniteNumber)(e)&&this.log("Media seeked to "+e.toFixed(3)),this.tick()},_.onManifestLoading=function(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(a.Events.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.fragPlaying=null,this.backtrackFragment=null},_.onManifestParsed=function(t,e){var r,i=!1,n=!1;e.levels.forEach((function(t){(r=t.audioCodec)&&(-1!==r.indexOf("mp4a.40.2")&&(i=!0),-1!==r.indexOf("mp4a.40.5")&&(n=!0))})),this.audioCodecSwitch=i&&n&&!(0,s.changeTypeSupported)(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1},_.onLevelLoading=function(t,e){var r=this.levels;if(r&&this.state===n.State.IDLE){var i=r[e.level];(!i.details||i.details.live&&this.levelLastLoaded!==e.level||this.waitForCdnTuneIn(i.details))&&(this.state=n.State.WAITING_LEVEL)}},_.onLevelLoaded=function(t,e){var r,i=this.levels,s=e.level,o=e.details,l=o.totalduration;if(i){this.log("Level "+s+" loaded ["+o.startSN+","+o.endSN+"], cc ["+o.startCC+", "+o.endCC+"] duration:"+l);var d=this.fragCurrent;!d||this.state!==n.State.FRAG_LOADING&&this.state!==n.State.FRAG_LOADING_WAITING_RETRY||d.level!==e.level&&d.loader&&(this.state=n.State.IDLE,this.backtrackFragment=null,d.loader.abort());var u=i[s],c=0;if(o.live||null!==(r=u.details)&&void 0!==r&&r.live){if(o.fragments[0]||(o.deltaUpdateFailed=!0),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,u.details)}if(u.details=o,this.levelLastLoaded=s,this.hls.trigger(a.Events.LEVEL_UPDATED,{details:o,level:s}),this.state===n.State.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=n.State.IDLE}this.startFragRequested?o.live&&this.synchronizeToLiveEdge(o):this.setStartPosition(o,c),this.tick()}else this.warn("Levels were reset while loading level "+s)},_._handleFragmentLoadProgress=function(t){var e,r=t.frag,i=t.part,n=t.payload,s=this.levels;if(s){var a=s[r.level],o=a.details;if(o){var l=a.videoCodec,u=o.PTSKnown||!o.live,f=null===(e=r.initSegment)||void 0===e?void 0:e.data,p=this._getAudioCodec(a),g=this.transmuxer=this.transmuxer||new c.default(this.hls,d.PlaylistLevelType.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),v=i?i.index:-1,m=-1!==v,y=new h.ChunkMetadata(r.level,r.sn,r.stats.chunkCount,n.byteLength,v,m),E=this.initPTS[r.cc];g.push(n,f,p,l,r,i,o.totalduration,u,y,E)}else this.warn("Dropping fragment "+r.sn+" of level "+r.level+" after level details were reset")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},_.onAudioTrackSwitching=function(t,e){var r=this.altAudio,i=!!e.url,n=e.id;if(!i){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var s=this.fragCurrent;null!=s&&s.loader&&(this.log("Switching to main audio track, cancel main fragment load"),s.loader.abort()),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var o=this.hls;r&&o.trigger(a.Events.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),o.trigger(a.Events.AUDIO_TRACK_SWITCHED,{id:n})}},_.onAudioTrackSwitched=function(t,e){var r=e.id,i=!!this.hls.audioTracks[r].url;if(i){var n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=i,this.tick()},_.onBufferCreated=function(t,e){var r,i,n=e.tracks,s=!1;for(var a in n){var o=n[a];if("main"===o.id){if(i=a,r=o,"video"===a){var l=n[a];l&&(this.videoBuffer=l.buffer)}}else s=!0}s&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},_.onFragBuffered=function(t,e){var r=e.frag,i=e.part;if(!r||r.type===d.PlaylistLevelType.MAIN){if(this.fragContextChanged(r))return this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===n.State.PARSED&&(this.state=n.State.IDLE));var s=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}},_.onError=function(t,e){switch(e.details){case p.ErrorDetails.FRAG_LOAD_ERROR:case p.ErrorDetails.FRAG_LOAD_TIMEOUT:case p.ErrorDetails.KEY_LOAD_ERROR:case p.ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(d.PlaylistLevelType.MAIN,e);break;case p.ErrorDetails.LEVEL_LOAD_ERROR:case p.ErrorDetails.LEVEL_LOAD_TIMEOUT:this.state!==n.State.ERROR&&(e.fatal?(this.warn(""+e.details),this.state=n.State.ERROR):e.levelRetry||this.state!==n.State.WAITING_LEVEL||(this.state=n.State.IDLE));break;case p.ErrorDetails.BUFFER_FULL_ERROR:if("main"===e.parent&&(this.state===n.State.PARSING||this.state===n.State.PARSED)){var r=!0,i=this.getFwdBufferInfo(this.media,d.PlaylistLevelType.MAIN);i&&i.len>.5&&(r=!this.reduceMaxBufferLength(i.len)),r&&(this.warn("buffer full error also media.currentTime is not buffered, flush main"),this.immediateLevelSwitch()),this.resetLoadingState()}}},_.checkBuffer=function(){var t=this.media,e=this.gapController;if(t&&e&&t.readyState){if(this.loadedmetadata||!o.BufferHelper.getBuffered(t).length){var r=this.state!==n.State.IDLE?this.fragCurrent:null;e.poll(this.lastCurrentTime,r)}this.lastCurrentTime=t.currentTime}},_.onFragLoadEmergencyAborted=function(){this.state=n.State.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()},_.onBufferFlushed=function(t,e){var r=e.type;if(r!==u.ElementaryStreamTypes.AUDIO||this.audioOnly&&!this.altAudio){var i=(r===u.ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,r,d.PlaylistLevelType.MAIN)}},_.onLevelsUpdated=function(t,e){this.levels=e.levels},_.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},_.seekToStartPos=function(){var t=this.media;if(t){var e=t.currentTime,r=this.startPosition;if(r>=0&&e<r){if(t.seeking)return void this.log("could not seek to "+r+", already seeking at "+e);var i=o.BufferHelper.getBuffered(t),n=(i.length?i.start(0):0)-r;n>0&&(n<this.config.maxBufferHole||n<this.config.maxFragLookUpTolerance)&&(this.log("adjusting start position by "+n+" to match buffer start"),r+=n,this.startPosition=r),this.log("seek to target start position "+r+" from current time "+e),t.currentTime=r}}},_._getAudioCodec=function(t){var e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e},_._loadBitrateTestFrag=function(t){var e=this;t.bitrateTest=!0,this._doFragLoad(t).then((function(r){var i=e.hls;if(r&&!i.nextLoadLevel&&!e.fragContextChanged(t)){e.fragLoadError=0,e.state=n.State.IDLE,e.startFragRequested=!1,e.bitrateTest=!1;var s=t.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),i.trigger(a.Events.FRAG_LOADED,r),t.bitrateTest=!1}}))},_._handleTransmuxComplete=function(t){var e,r="main",s=this.hls,o=t.remuxResult,l=t.chunkMeta,d=this.getCurrentContext(l);if(!d)return this.warn("The loading context changed while buffering fragment "+l.sn+" of level "+l.level+". This chunk will not be buffered."),void this.resetStartWhenNotLoaded(l.level);var c=d.frag,h=d.part,f=d.level,p=o.video,g=o.text,v=o.id3,m=o.initSegment,y=f.details,E=this.altAudio?void 0:o.audio;if(!this.fragContextChanged(c)){if(this.state=n.State.PARSING,m){m.tracks&&(this._bufferInitSegment(f,m.tracks,c,l),s.trigger(a.Events.FRAG_PARSING_INIT_SEGMENT,{frag:c,id:r,tracks:m.tracks}));var T=m.initPTS,_=m.timescale;(0,i.isFiniteNumber)(T)&&(this.initPTS[c.cc]=T,s.trigger(a.Events.INIT_PTS_FOUND,{frag:c,id:r,initPTS:T,timescale:_}))}if(p&&!1!==o.independent){if(y){var S=p.startPTS,b=p.endPTS,A=p.startDTS,L=p.endDTS;if(h)h.elementaryStreams[p.type]={startPTS:S,endPTS:b,startDTS:A,endDTS:L};else if(p.firstKeyFrame&&p.independent&&(this.couldBacktrack=!0),p.dropped&&p.independent){var w=this.getMainFwdBufferInfo();if((w?w.end:this.getLoadPosition())+this.config.maxBufferHole<(p.firstKeyFramePTS?p.firstKeyFramePTS:S)-this.config.maxBufferHole)return void this.backtrack(c);c.setElementaryStreamInfo(p.type,c.start,b,c.start,L,!0)}c.setElementaryStreamInfo(p.type,S,b,A,L),this.backtrackFragment&&(this.backtrackFragment=c),this.bufferFragmentData(p,c,h,l)}}else if(!1===o.independent)return void this.backtrack(c);if(E){var D=E.startPTS,R=E.endPTS,I=E.startDTS,k=E.endDTS;h&&(h.elementaryStreams[u.ElementaryStreamTypes.AUDIO]={startPTS:D,endPTS:R,startDTS:I,endDTS:k}),c.setElementaryStreamInfo(u.ElementaryStreamTypes.AUDIO,D,R,I,k),this.bufferFragmentData(E,c,h,l)}if(y&&null!=v&&null!==(e=v.samples)&&void 0!==e&&e.length){var O={id:r,frag:c,details:y,samples:v.samples};s.trigger(a.Events.FRAG_PARSING_METADATA,O)}if(y&&g){var C={id:r,frag:c,details:y,samples:g.samples};s.trigger(a.Events.FRAG_PARSING_USERDATA,C)}}},_._bufferInitSegment=function(t,e,r,i){var s=this;if(this.state===n.State.PARSING){this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;var o=e.audio,l=e.video,d=e.audiovideo;if(o){var u=t.audioCodec,c=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(u&&(u=-1!==u.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),1!==o.metadata.channelCount&&-1===c.indexOf("firefox")&&(u="mp4a.40.5")),-1!==c.indexOf("android")&&"audio/mpeg"!==o.container&&(u="mp4a.40.2",this.log("Android: force audio codec to "+u)),t.audioCodec&&t.audioCodec!==u&&this.log('Swapping manifest audio codec "'+t.audioCodec+'" for "'+u+'"'),o.levelCodec=u,o.id="main",this.log("Init audio buffer, container:"+o.container+", codecs[selected/level/parsed]=["+(u||"")+"/"+(t.audioCodec||"")+"/"+o.codec+"]")}l&&(l.levelCodec=t.videoCodec,l.id="main",this.log("Init video buffer, container:"+l.container+", codecs[level/parsed]=["+(t.videoCodec||"")+"/"+l.codec+"]")),d&&this.log("Init audiovideo buffer, container:"+d.container+", codecs[level/parsed]=["+(t.attrs.CODECS||"")+"/"+d.codec+"]"),this.hls.trigger(a.Events.BUFFER_CODECS,e),Object.keys(e).forEach((function(t){var n=e[t].initSegment;null!=n&&n.byteLength&&s.hls.trigger(a.Events.BUFFER_APPENDING,{type:t,data:n,frag:r,part:null,chunkMeta:i,parent:r.type})})),this.tick()}},_.getMainFwdBufferInfo=function(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,d.PlaylistLevelType.MAIN)},_.backtrack=function(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=n.State.IDLE},_.checkFragmentChanged=function(){var t=this.media,e=null;if(t&&t.readyState>1&&!1===t.seeking){var r=t.currentTime;if(o.BufferHelper.isBuffered(t,r)?e=this.getAppendedFrag(r):o.BufferHelper.isBuffered(t,r+.1)&&(e=this.getAppendedFrag(r+.1)),e){this.backtrackFragment=null;var i=this.fragPlaying,n=e.level;i&&e.sn===i.sn&&i.level===n&&e.urlId===i.urlId||(this.hls.trigger(a.Events.FRAG_CHANGED,{frag:e}),i&&i.level===n||this.hls.trigger(a.Events.LEVEL_SWITCHED,{level:n}),this.fragPlaying=e)}}},y=m,(E=[{key:"nextLevel",get:function(){var t=this.nextBufferedFrag;return t?t.level:-1}},{key:"currentFrag",get:function(){var t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}},{key:"currentProgramDateTime",get:function(){var t=this.media;if(t){var e=t.currentTime,r=this.currentFrag;if(r&&(0,i.isFiniteNumber)(e)&&(0,i.isFiniteNumber)(r.programDateTime)){var n=r.programDateTime+1e3*(e-r.start);return new Date(n)}}return null}},{key:"currentLevel",get:function(){var t=this.currentFrag;return t?t.level:-1}},{key:"nextBufferedFrag",get:function(){var t=this.currentFrag;return t?this.followingBufferedFrag(t):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])&&g(y.prototype,E),T&&g(y,T),Object.defineProperty(y,"prototype",{writable:!1}),m}(n.default)},"./src/controller/subtitle-stream-controller.ts":
|
|
62
|
-
/*!******************************************************!*\
|
|
63
|
-
!*** ./src/controller/subtitle-stream-controller.ts ***!
|
|
64
|
-
\******************************************************/(t,e,r)=>{r.r(e),r.d(e,{SubtitleStreamController:()=>p});var i=r(/*! ../events */"./src/events.ts"),n=r(/*! ../utils/buffer-helper */"./src/utils/buffer-helper.ts"),s=r(/*! ./fragment-finders */"./src/controller/fragment-finders.ts"),a=r(/*! ../utils/discontinuities */"./src/utils/discontinuities.ts"),o=r(/*! ./level-helper */"./src/controller/level-helper.ts"),l=r(/*! ./fragment-tracker */"./src/controller/fragment-tracker.ts"),d=r(/*! ./base-stream-controller */"./src/controller/base-stream-controller.ts"),u=r(/*! ../types/loader */"./src/types/loader.ts"),c=r(/*! ../types/level */"./src/types/level.ts");function h(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function f(t,e){return(f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}var p=function(t){var e,r;function p(e,r){var i;return(i=t.call(this,e,r,"[subtitle-stream-controller]")||this).levels=[],i.currentTrackId=-1,i.tracksBuffered=[],i.mainDetails=null,i._registerListeners(),i}r=t,(e=p).prototype=Object.create(r.prototype),e.prototype.constructor=e,f(e,r);var v,m,y,E=p.prototype;return E.onHandlerDestroying=function(){this._unregisterListeners(),this.mainDetails=null},E._registerListeners=function(){var t=this.hls;t.on(i.Events.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(i.Events.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(i.Events.MANIFEST_LOADING,this.onManifestLoading,this),t.on(i.Events.LEVEL_LOADED,this.onLevelLoaded,this),t.on(i.Events.ERROR,this.onError,this),t.on(i.Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(i.Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(i.Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(i.Events.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(i.Events.BUFFER_FLUSHING,this.onBufferFlushing,this)},E._unregisterListeners=function(){var t=this.hls;t.off(i.Events.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(i.Events.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(i.Events.MANIFEST_LOADING,this.onManifestLoading,this),t.off(i.Events.LEVEL_LOADED,this.onLevelLoaded,this),t.off(i.Events.ERROR,this.onError,this),t.off(i.Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(i.Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(i.Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(i.Events.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(i.Events.BUFFER_FLUSHING,this.onBufferFlushing,this)},E.startLoad=function(){this.stopLoad(),this.state=d.State.IDLE,this.setInterval(500),this.tick()},E.onManifestLoading=function(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()},E.onLevelLoaded=function(t,e){this.mainDetails=e.details},E.onSubtitleFragProcessed=function(t,e){var r=e.frag,i=e.success;if(this.fragPrevious=r,this.state=d.State.IDLE,i){var n=this.tracksBuffered[this.currentTrackId];if(n){for(var s,a=r.start,o=0;o<n.length;o++)if(a>=n[o].start&&a<=n[o].end){s=n[o];break}var l=r.start+r.duration;s?s.end=l:(s={start:a,end:l},n.push(s)),this.fragmentTracker.fragBuffered(r)}}},E.onBufferFlushing=function(t,e){var r=e.startOffset,i=e.endOffset;if(0===r&&i!==Number.POSITIVE_INFINITY){var n=this.currentTrackId,s=this.levels;if(!s.length||!s[n]||!s[n].details)return;var a=i-s[n].details.targetduration;if(a<=0)return;e.endOffsetSubtitles=Math.max(0,a),this.tracksBuffered.forEach((function(t){for(var e=0;e<t.length;)if(t[e].end<=a)t.shift();else{if(!(t[e].start<a))break;t[e].start=a,e++}})),this.fragmentTracker.removeFragmentsInRange(r,a,u.PlaylistLevelType.SUBTITLE)}},E.onError=function(t,e){var r,i=e.frag;i&&i.type===u.PlaylistLevelType.SUBTITLE&&(null!==(r=this.fragCurrent)&&void 0!==r&&r.loader&&this.fragCurrent.loader.abort(),this.state=d.State.IDLE)},E.onSubtitleTracksUpdated=function(t,e){var r=this,i=e.subtitleTracks;this.tracksBuffered=[],this.levels=i.map((function(t){return new c.Level(t)})),this.fragmentTracker.removeAllFragments(),this.fragPrevious=null,this.levels.forEach((function(t){r.tracksBuffered[t.id]=[]})),this.mediaBuffer=null},E.onSubtitleTrackSwitch=function(t,e){if(this.currentTrackId=e.id,this.levels.length&&-1!==this.currentTrackId){var r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.setInterval(500)}else this.clearInterval()},E.onSubtitleTrackLoaded=function(t,e){var r,i=e.details,n=e.id,l=this.currentTrackId,u=this.levels;if(u.length){var c=u[l];if(!(n>=u.length||n!==l)&&c){if(this.mediaBuffer=this.mediaBufferTimeRanges,i.live||null!==(r=c.details)&&void 0!==r&&r.live){var h=this.mainDetails;if(i.deltaUpdateFailed||!h)return;var f=h.fragments[0];c.details?0===this.alignPlaylists(i,c.details)&&f&&(0,o.addSliding)(i,f.start):i.hasProgramDateTime&&h.hasProgramDateTime?(0,a.alignMediaPlaylistByPDT)(i,h):f&&(0,o.addSliding)(i,f.start)}c.details=i,this.levelLastLoaded=n,this.tick(),i.live&&!this.fragCurrent&&this.media&&this.state===d.State.IDLE&&((0,s.findFragmentByPTS)(null,i.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0))}}},E._handleFragmentLoadComplete=function(t){var e=t.frag,r=t.payload,n=e.decryptdata,s=this.hls;if(!this.fragContextChanged(e)&&r&&r.byteLength>0&&n&&n.key&&n.iv&&"AES-128"===n.method){var a=performance.now();this.decrypter.webCryptoDecrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer).then((function(t){var r=performance.now();s.trigger(i.Events.FRAG_DECRYPTED,{frag:e,payload:t,stats:{tstart:a,tdecrypt:r}})}))}},E.doTick=function(){if(this.media){if(this.state===d.State.IDLE){var t=this.currentTrackId,e=this.levels;if(!e.length||!e[t]||!e[t].details)return;var r=e[t].details,i=r.targetduration,a=this.config,o=this.media,u=n.BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],o.currentTime-i,a.maxBufferHole),c=u.end;if(u.len>this.getMaxBufferLength()+i)return;console.assert(r,"Subtitle track details are defined on idle subtitle stream controller tick");var h,f=r.fragments,p=f.length,g=r.edge,v=this.fragPrevious;if(c<g){var m=a.maxFragLookUpTolerance;!(h=(0,s.findFragmentByPTS)(v,f,Math.max(f[0].start,c),m))&&v&&v.start<f[0].start&&(h=f[0])}else h=f[p-1];if(!(h=this.mapToInitFragWhenRequired(h)))return;if(this.fragmentTracker.getState(h)!==l.FragmentState.NOT_LOADED)return;h.encrypted?this.loadKey(h,r):this.loadFragment(h,r,c)}}else this.state=d.State.IDLE},E.loadFragment=function(e,r,i){this.fragCurrent=e,"initSegment"===e.sn?this._loadInitSegment(e):t.prototype.loadFragment.call(this,e,r,i)},v=p,(m=[{key:"mediaBufferTimeRanges",get:function(){return new g(this.tracksBuffered[this.currentTrackId]||[])}}])&&h(v.prototype,m),y&&h(v,y),Object.defineProperty(v,"prototype",{writable:!1}),p}(d.default),g=function(t){this.buffered=void 0;var e=function(e,r,i){if((r>>>=0)>i-1)throw new DOMException("Failed to execute '"+e+"' on 'TimeRanges': The index provided ("+r+") is greater than the maximum bound ("+i+")");return t[r][e]};this.buffered={get length(){return t.length},end:function(r){return e("end",r,t.length)},start:function(r){return e("start",r,t.length)}}}},"./src/controller/subtitle-track-controller.ts":
|
|
65
|
-
/*!*****************************************************!*\
|
|
66
|
-
!*** ./src/controller/subtitle-track-controller.ts ***!
|
|
67
|
-
\*****************************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>u});var i=r(/*! ../events */"./src/events.ts"),n=r(/*! ../utils/texttrack-utils */"./src/utils/texttrack-utils.ts"),s=r(/*! ./base-playlist-controller */"./src/controller/base-playlist-controller.ts"),a=r(/*! ../types/loader */"./src/types/loader.ts");function o(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function l(t,e){return(l=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}function d(t){for(var e=[],r=0;r<t.length;r++){var i=t[r];"subtitles"===i.kind&&i.label&&e.push(t[r])}return e}const u=function(t){var e,r;function s(e){var r;return(r=t.call(this,e,"[subtitle-track-controller]")||this).media=null,r.tracks=[],r.groupId=null,r.tracksInGroup=[],r.trackId=-1,r.selectDefaultTrack=!0,r.queuedDefaultTrack=-1,r.trackChangeListener=function(){return r.onTextTracksChanged()},r.asyncPollTrackChange=function(){return r.pollTrackChange(0)},r.useTextTrackPolling=!1,r.subtitlePollingInterval=-1,r._subtitleDisplay=!0,r.registerListeners(),r}r=t,(e=s).prototype=Object.create(r.prototype),e.prototype.constructor=e,l(e,r);var u,c,h,f=s.prototype;return f.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,t.prototype.destroy.call(this)},f.registerListeners=function(){var t=this.hls;t.on(i.Events.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(i.Events.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(i.Events.MANIFEST_LOADING,this.onManifestLoading,this),t.on(i.Events.MANIFEST_PARSED,this.onManifestParsed,this),t.on(i.Events.LEVEL_LOADING,this.onLevelLoading,this),t.on(i.Events.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(i.Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(i.Events.ERROR,this.onError,this)},f.unregisterListeners=function(){var t=this.hls;t.off(i.Events.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(i.Events.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(i.Events.MANIFEST_LOADING,this.onManifestLoading,this),t.off(i.Events.MANIFEST_PARSED,this.onManifestParsed,this),t.off(i.Events.LEVEL_LOADING,this.onLevelLoading,this),t.off(i.Events.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(i.Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(i.Events.ERROR,this.onError,this)},f.onMediaAttached=function(t,e){this.media=e.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))},f.pollTrackChange=function(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,t)},f.onMediaDetaching=function(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),d(this.media.textTracks).forEach((function(t){(0,n.clearCurrentCues)(t)})),this.subtitleTrack=-1,this.media=null)},f.onManifestLoading=function(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0},f.onManifestParsed=function(t,e){this.tracks=e.subtitleTracks},f.onSubtitleTrackLoaded=function(t,e){var r=e.id,i=e.details,n=this.trackId,s=this.tracksInGroup[n];if(s){var a=s.details;s.details=e.details,this.log("subtitle track "+r+" loaded ["+i.startSN+"-"+i.endSN+"]"),r===this.trackId&&(this.retryCount=0,this.playlistLoaded(r,e,a))}else this.warn("Invalid subtitle track id "+r)},f.onLevelLoading=function(t,e){this.switchLevel(e.level)},f.onLevelSwitching=function(t,e){this.switchLevel(e.level)},f.switchLevel=function(t){var e=this.hls.levels[t];if(null!=e&&e.textGroupIds){var r=e.textGroupIds[e.urlId];if(this.groupId!==r){var n=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0,s=this.tracks.filter((function(t){return!r||t.groupId===r}));this.tracksInGroup=s;var a=this.findTrackId(null==n?void 0:n.name)||this.findTrackId();this.groupId=r;var o={subtitleTracks:s};this.log("Updating subtitle tracks, "+s.length+' track(s) found in "'+r+'" group-id'),this.hls.trigger(i.Events.SUBTITLE_TRACKS_UPDATED,o),-1!==a&&this.setSubtitleTrack(a,n)}}},f.findTrackId=function(t){for(var e=this.tracksInGroup,r=0;r<e.length;r++){var i=e[r];if((!this.selectDefaultTrack||i.default)&&(!t||t===i.name))return i.id}return-1},f.onError=function(e,r){t.prototype.onError.call(this,e,r),!r.fatal&&r.context&&r.context.type===a.PlaylistContextType.SUBTITLE_TRACK&&r.context.id===this.trackId&&r.context.groupId===this.groupId&&this.retryLoadingOrFail(r)},f.loadPlaylist=function(t){var e=this.tracksInGroup[this.trackId];if(this.shouldLoadTrack(e)){var r=e.id,n=e.groupId,s=e.url;if(t)try{s=t.addDirectives(s)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}this.log("Loading subtitle playlist for id "+r),this.hls.trigger(i.Events.SUBTITLE_TRACK_LOADING,{url:s,id:r,groupId:n,deliveryDirectives:t||null})}},f.toggleTrackModes=function(t){var e=this,r=this.media,i=this.trackId;if(r){var n=d(r.textTracks),s=n.filter((function(t){return t.groupId===e.groupId}));if(-1===t)[].slice.call(n).forEach((function(t){t.mode="disabled"}));else{var a=s[i];a&&(a.mode="disabled")}var o=s[t];o&&(o.mode=this.subtitleDisplay?"showing":"hidden")}},f.setSubtitleTrack=function(t,e){var r,n=this.tracksInGroup;if(this.media){if(this.trackId!==t&&this.toggleTrackModes(t),!(this.trackId===t&&(-1===t||null!==(r=n[t])&&void 0!==r&&r.details)||t<-1||t>=n.length)){this.clearTimer();var s=n[t];if(this.log("Switching to subtitle track "+t),this.trackId=t,s){var a=s.id,o=s.groupId,l=void 0===o?"":o,d=s.name,u=s.type,c=s.url;this.hls.trigger(i.Events.SUBTITLE_TRACK_SWITCH,{id:a,groupId:l,name:d,type:u,url:c});var h=this.switchParams(s.url,null==e?void 0:e.details);this.loadPlaylist(h)}else this.hls.trigger(i.Events.SUBTITLE_TRACK_SWITCH,{id:t})}}else this.queuedDefaultTrack=t},f.onTextTracksChanged=function(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),this.media&&this.hls.config.renderTextTracksNatively){for(var t=-1,e=d(this.media.textTracks),r=0;r<e.length;r++)if("hidden"===e[r].mode)t=r;else if("showing"===e[r].mode){t=r;break}this.subtitleTrack!==t&&(this.subtitleTrack=t)}},u=s,(c=[{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes(this.trackId)}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(t){this.selectDefaultTrack=!1;var e=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(t,e)}}])&&o(u.prototype,c),h&&o(u,h),Object.defineProperty(u,"prototype",{writable:!1}),s}(s.default)},"./src/controller/timeline-controller.ts":
|
|
68
|
-
/*!***********************************************!*\
|
|
69
|
-
!*** ./src/controller/timeline-controller.ts ***!
|
|
70
|
-
\***********************************************/(t,e,r)=>{r.r(e),r.d(e,{TimelineController:()=>f});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../events */"./src/events.ts"),s=r(/*! ../utils/cea-608-parser */"./src/utils/cea-608-parser.ts"),a=r(/*! ../utils/output-filter */"./src/utils/output-filter.ts"),o=r(/*! ../utils/webvtt-parser */"./src/utils/webvtt-parser.ts"),l=r(/*! ../utils/texttrack-utils */"./src/utils/texttrack-utils.ts"),d=r(/*! ../utils/imsc1-ttml-parser */"./src/utils/imsc1-ttml-parser.ts"),u=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts"),c=r(/*! ../types/loader */"./src/types/loader.ts"),h=r(/*! ../utils/logger */"./src/utils/logger.ts"),f=function(){function t(t){if(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.timescale=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,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=t,this.config=t.config,this.Cues=t.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}},this.config.enableCEA708Captions){var e=new a.default(this,"textTrack1"),r=new a.default(this,"textTrack2"),i=new a.default(this,"textTrack3"),o=new a.default(this,"textTrack4");this.cea608Parser1=new s.default(1,e,r),this.cea608Parser2=new s.default(3,i,o)}t.on(n.Events.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(n.Events.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(n.Events.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.Events.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(n.Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(n.Events.FRAG_LOADING,this.onFragLoading,this),t.on(n.Events.FRAG_LOADED,this.onFragLoaded,this),t.on(n.Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(n.Events.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(n.Events.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(n.Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(n.Events.BUFFER_FLUSHING,this.onBufferFlushing,this)}var e=t.prototype;return e.destroy=function(){var t=this.hls;t.off(n.Events.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(n.Events.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(n.Events.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.Events.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(n.Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(n.Events.FRAG_LOADING,this.onFragLoading,this),t.off(n.Events.FRAG_LOADED,this.onFragLoaded,this),t.off(n.Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(n.Events.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(n.Events.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(n.Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(n.Events.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null},e.addCues=function(t,e,r,i,s){for(var a,o,l,d,u=!1,c=s.length;c--;){var h=s[c],f=(a=h[0],o=h[1],l=e,d=r,Math.min(o,d)-Math.max(a,l));if(f>=0&&(h[0]=Math.min(h[0],e),h[1]=Math.max(h[1],r),u=!0,f/(r-e)>.5))return}if(u||s.push([e,r]),this.config.renderTextTracksNatively){var p=this.captionsTracks[t];this.Cues.newCue(p,e,r,i)}else{var g=this.Cues.newCue(null,e,r,i);this.hls.trigger(n.Events.CUES_PARSED,{type:"captions",cues:g,track:t})}},e.onInitPtsFound=function(t,e){var r=this,i=e.frag,s=e.id,a=e.initPTS,o=e.timescale,l=this.unparsedVttFrags;"main"===s&&(this.initPTS[i.cc]=a,this.timescale[i.cc]=o),l.length&&(this.unparsedVttFrags=[],l.forEach((function(t){r.onFragLoaded(n.Events.FRAG_LOADED,t)})))},e.getExistingTrack=function(t){var e=this.media;if(e)for(var r=0;r<e.textTracks.length;r++){var i=e.textTracks[r];if(i[t])return i}return null},e.createCaptionsTrack=function(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)},e.createNativeTrack=function(t){if(!this.captionsTracks[t]){var e=this.captionsProperties,r=this.captionsTracks,i=this.media,n=e[t],s=n.label,a=n.languageCode,o=this.getExistingTrack(t);if(o)r[t]=o,(0,l.clearCurrentCues)(r[t]),(0,l.sendAddTrackEvent)(r[t],i);else{var d=this.createTextTrack("captions",s,a);d&&(d[t]=!0,r[t]=d)}}},e.createNonNativeTrack=function(t){if(!this.nonNativeCaptionsTracks[t]){var e=this.captionsProperties[t];if(e){var r={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=r,this.hls.trigger(n.Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}}},e.createTextTrack=function(t,e,r){var i=this.media;if(i)return i.addTextTrack(t,e,r)},e.onMediaAttaching=function(t,e){this.media=e.media,this._cleanTracks()},e.onMediaDetaching=function(){var t=this.captionsTracks;Object.keys(t).forEach((function(e){(0,l.clearCurrentCues)(t[e]),delete t[e]})),this.nonNativeCaptionsTracks={}},e.onManifestLoading=function(){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.unparsedVttFrags||[],this.initPTS=[],this.timescale=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())},e._cleanTracks=function(){var t=this.media;if(t){var e=t.textTracks;if(e)for(var r=0;r<e.length;r++)(0,l.clearCurrentCues)(e[r])}},e.onSubtitleTracksUpdated=function(t,e){var r=this;this.textTracks=[];var i=e.subtitleTracks||[],s=i.some((function(t){return t.textCodec===d.IMSC1_CODEC}));if(this.config.enableWebVTT||s&&this.config.enableIMSC1){var a=this.tracks&&i&&this.tracks.length===i.length;if(this.tracks=i||[],this.config.renderTextTracksNatively){var o=this.media?this.media.textTracks:[];this.tracks.forEach((function(t,e){var i;if(e<o.length){for(var n=null,s=0;s<o.length;s++)if(p(o[s],t)){n=o[s];break}n&&(i=n)}if(i)(0,l.clearCurrentCues)(i);else{var a=r._captionsOrSubtitlesFromCharacteristics(t);(i=r.createTextTrack(a,t.name,t.lang))&&(i.mode="disabled")}i&&(i.groupId=t.groupId,r.textTracks.push(i))}))}else if(!a&&this.tracks&&this.tracks.length){var u=this.tracks.map((function(t){return{label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}}));this.hls.trigger(n.Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:u})}}},e._captionsOrSubtitlesFromCharacteristics=function(t){var e;if(null!==(e=t.attrs)&&void 0!==e&&e.CHARACTERISTICS){var r=/transcribes-spoken-dialog/gi.test(t.attrs.CHARACTERISTICS),i=/describes-music-and-sound/gi.test(t.attrs.CHARACTERISTICS);if(r&&i)return"captions"}return"subtitles"},e.onManifestLoaded=function(t,e){var r=this;this.config.enableCEA708Captions&&e.captions&&e.captions.forEach((function(t){var e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(e){var i="textTrack"+e[1],n=r.captionsProperties[i];n&&(n.label=t.name,t.lang&&(n.languageCode=t.lang),n.media=t)}}))},e.closedCaptionsForLevel=function(t){var e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]},e.onFragLoading=function(t,e){var r=this.cea608Parser1,i=this.cea608Parser2,n=this.lastSn,s=this.lastPartIndex;if(this.enabled&&r&&i&&e.frag.type===c.PlaylistLevelType.MAIN){var a,o,l=e.frag.sn,d=null!=(a=null==e||null===(o=e.part)||void 0===o?void 0:o.index)?a:-1;l===n+1||l===n&&d===s+1||(r.reset(),i.reset()),this.lastSn=l,this.lastPartIndex=d}},e.onFragLoaded=function(t,e){var r=e.frag,s=e.payload,a=this.initPTS,o=this.unparsedVttFrags;if(r.type===c.PlaylistLevelType.SUBTITLE)if(s.byteLength){if(!(0,i.isFiniteNumber)(a[r.cc]))return o.push(e),void(a.length&&this.hls.trigger(n.Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Missing initial subtitle PTS")}));var l=r.decryptdata,u="stats"in e;if(null==l||null==l.key||"AES-128"!==l.method||u){var h=this.tracks[r.level],f=this.vttCCs;f[r.cc]||(f[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),h&&h.textCodec===d.IMSC1_CODEC?this._parseIMSC1(r,s):this._parseVTTs(r,s,f)}}else this.hls.trigger(n.Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})},e._parseIMSC1=function(t,e){var r=this,i=this.hls;(0,d.parseIMSC1)(e,this.initPTS[t.cc],this.timescale[t.cc],(function(e){r._appendCues(e,t.level),i.trigger(n.Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(function(e){h.logger.log("Failed to parse IMSC1: "+e),i.trigger(n.Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})}))},e._parseVTTs=function(t,e,r){var i,s=this,a=this.hls,l=null!==(i=t.initSegment)&&void 0!==i&&i.data?(0,u.appendUint8Array)(t.initSegment.data,new Uint8Array(e)):e;(0,o.parseWebVTT)(l,this.initPTS[t.cc],this.timescale[t.cc],r,t.cc,t.start,(function(e){s._appendCues(e,t.level),a.trigger(n.Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(function(r){s._fallbackToIMSC1(t,e),h.logger.log("Failed to parse VTT cue: "+r),a.trigger(n.Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:r})}))},e._fallbackToIMSC1=function(t,e){var r=this,i=this.tracks[t.level];i.textCodec||(0,d.parseIMSC1)(e,this.initPTS[t.cc],this.timescale[t.cc],(function(){i.textCodec=d.IMSC1_CODEC,r._parseIMSC1(t,e)}),(function(){i.textCodec="wvtt"}))},e._appendCues=function(t,e){var r=this.hls;if(this.config.renderTextTracksNatively){var i=this.textTracks[e];if(!i||"disabled"===i.mode)return;t.forEach((function(t){return(0,l.addCueToTrack)(i,t)}))}else{var s=this.tracks[e];if(!s)return;var a=s.default?"default":"subtitles"+e;r.trigger(n.Events.CUES_PARSED,{type:"subtitles",cues:t,track:a})}},e.onFragDecrypted=function(t,e){var r=e.frag;if(r.type===c.PlaylistLevelType.SUBTITLE){if(!(0,i.isFiniteNumber)(this.initPTS[r.cc]))return void this.unparsedVttFrags.push(e);this.onFragLoaded(n.Events.FRAG_LOADED,e)}},e.onSubtitleTracksCleared=function(){this.tracks=[],this.captionsTracks={}},e.onFragParsingUserdata=function(t,e){var r=this.cea608Parser1,i=this.cea608Parser2;if(this.enabled&&r&&i){var n=e.frag,s=e.samples;if(n.type!==c.PlaylistLevelType.MAIN||"NONE"!==this.closedCaptionsForLevel(n))for(var a=0;a<s.length;a++){var o=s[a].bytes;if(o){var l=this.extractCea608Data(o);r.addData(s[a].pts,l[0]),i.addData(s[a].pts,l[1])}}}},e.onBufferFlushing=function(t,e){var r=e.startOffset,i=e.endOffset,n=e.endOffsetSubtitles,s=e.type,a=this.media;if(a&&!(a.currentTime<i)){if(!s||"video"===s){var o=this.captionsTracks;Object.keys(o).forEach((function(t){return(0,l.removeCuesInRange)(o[t],r,i)}))}if(this.config.renderTextTracksNatively&&0===r&&void 0!==n){var d=this.textTracks;Object.keys(d).forEach((function(t){return(0,l.removeCuesInRange)(d[t],r,n)}))}}},e.extractCea608Data=function(t){for(var e=[[],[]],r=31&t[0],i=2,n=0;n<r;n++){var s=t[i++],a=127&t[i++],o=127&t[i++];if((0!==a||0!==o)&&0!=(4&s)){var l=3&s;0!==l&&1!==l||(e[l].push(a),e[l].push(o))}}return e},t}();function p(t,e){return t&&t.label===e.name&&!(t.textTrack1||t.textTrack2)}},"./src/crypt/aes-crypto.ts":
|
|
71
|
-
/*!*********************************!*\
|
|
72
|
-
!*** ./src/crypt/aes-crypto.ts ***!
|
|
73
|
-
\*********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>i});var i=function(){function t(t,e){this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=e}return t.prototype.decrypt=function(t,e){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t)},t}()},"./src/crypt/aes-decryptor.ts":
|
|
74
|
-
/*!************************************!*\
|
|
75
|
-
!*** ./src/crypt/aes-decryptor.ts ***!
|
|
76
|
-
\************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>s,removePadding:()=>n});var i=r(/*! ../utils/typed-array */"./src/utils/typed-array.ts");function n(t){var e=t.byteLength,r=e&&new DataView(t.buffer).getUint8(e-1);return r?(0,i.sliceUint8)(t,0,e-r):t}var s=function(){function t(){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()}var e=t.prototype;return e.uint8ArrayToUint32Array_=function(t){for(var e=new DataView(t),r=new Uint32Array(4),i=0;i<4;i++)r[i]=e.getUint32(4*i);return r},e.initTable=function(){var t=this.sBox,e=this.invSBox,r=this.subMix,i=r[0],n=r[1],s=r[2],a=r[3],o=this.invSubMix,l=o[0],d=o[1],u=o[2],c=o[3],h=new Uint32Array(256),f=0,p=0,g=0;for(g=0;g<256;g++)h[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){var v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^255&v^99,t[f]=v,e[v]=f;var m=h[f],y=h[m],E=h[y],T=257*h[v]^16843008*v;i[f]=T<<24|T>>>8,n[f]=T<<16|T>>>16,s[f]=T<<8|T>>>24,a[f]=T,T=16843009*E^65537*y^257*m^16843008*f,l[v]=T<<24|T>>>8,d[v]=T<<16|T>>>16,u[v]=T<<8|T>>>24,c[v]=T,f?(f=m^h[h[h[E^m]]],p^=h[h[p]]):f=p=1}},e.expandKey=function(t){for(var e=this.uint8ArrayToUint32Array_(t),r=!0,i=0;i<e.length&&r;)r=e[i]===this.key[i],i++;if(!r){this.key=e;var n=this.keySize=e.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);var s,a,o,l,d=this.ksRows=4*(n+6+1),u=this.keySchedule=new Uint32Array(d),c=this.invKeySchedule=new Uint32Array(d),h=this.sBox,f=this.rcon,p=this.invSubMix,g=p[0],v=p[1],m=p[2],y=p[3];for(s=0;s<d;s++)s<n?o=u[s]=e[s]:(l=o,s%n==0?(l=h[(l=l<<8|l>>>24)>>>24]<<24|h[l>>>16&255]<<16|h[l>>>8&255]<<8|h[255&l],l^=f[s/n|0]<<24):n>6&&s%n==4&&(l=h[l>>>24]<<24|h[l>>>16&255]<<16|h[l>>>8&255]<<8|h[255&l]),u[s]=o=(u[s-n]^l)>>>0);for(a=0;a<d;a++)s=d-a,l=3&a?u[s]:u[s-4],c[a]=a<4||s<=4?l:g[h[l>>>24]]^v[h[l>>>16&255]]^m[h[l>>>8&255]]^y[h[255&l]],c[a]=c[a]>>>0}},e.networkToHostOrderSwap=function(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24},e.decrypt=function(t,e,r){for(var i,n,s,a,o,l,d,u,c,h,f,p,g,v,m=this.keySize+6,y=this.invKeySchedule,E=this.invSBox,T=this.invSubMix,_=T[0],S=T[1],b=T[2],A=T[3],L=this.uint8ArrayToUint32Array_(r),w=L[0],D=L[1],R=L[2],I=L[3],k=new Int32Array(t),O=new Int32Array(k.length),C=this.networkToHostOrderSwap;e<k.length;){for(c=C(k[e]),h=C(k[e+1]),f=C(k[e+2]),p=C(k[e+3]),o=c^y[0],l=p^y[1],d=f^y[2],u=h^y[3],g=4,v=1;v<m;v++)i=_[o>>>24]^S[l>>16&255]^b[d>>8&255]^A[255&u]^y[g],n=_[l>>>24]^S[d>>16&255]^b[u>>8&255]^A[255&o]^y[g+1],s=_[d>>>24]^S[u>>16&255]^b[o>>8&255]^A[255&l]^y[g+2],a=_[u>>>24]^S[o>>16&255]^b[l>>8&255]^A[255&d]^y[g+3],o=i,l=n,d=s,u=a,g+=4;i=E[o>>>24]<<24^E[l>>16&255]<<16^E[d>>8&255]<<8^E[255&u]^y[g],n=E[l>>>24]<<24^E[d>>16&255]<<16^E[u>>8&255]<<8^E[255&o]^y[g+1],s=E[d>>>24]<<24^E[u>>16&255]<<16^E[o>>8&255]<<8^E[255&l]^y[g+2],a=E[u>>>24]<<24^E[o>>16&255]<<16^E[l>>8&255]<<8^E[255&d]^y[g+3],O[e]=C(i^w),O[e+1]=C(a^D),O[e+2]=C(s^R),O[e+3]=C(n^I),w=c,D=h,R=f,I=p,e+=4}return O.buffer},t}()},"./src/crypt/decrypter.ts":
|
|
77
|
-
/*!********************************!*\
|
|
78
|
-
!*** ./src/crypt/decrypter.ts ***!
|
|
79
|
-
\********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>d});var i=r(/*! ./aes-crypto */"./src/crypt/aes-crypto.ts"),n=r(/*! ./fast-aes-key */"./src/crypt/fast-aes-key.ts"),s=r(/*! ./aes-decryptor */"./src/crypt/aes-decryptor.ts"),a=r(/*! ../utils/logger */"./src/utils/logger.ts"),o=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts"),l=r(/*! ../utils/typed-array */"./src/utils/typed-array.ts"),d=function(){function t(t,e,r){var i=(void 0===r?{}:r).removePKCS7Padding,n=void 0===i||i;if(this.logEnabled=!0,this.observer=void 0,this.config=void 0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.observer=t,this.config=e,this.removePKCS7Padding=n,n)try{var s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch(t){}null===this.subtle&&(this.config.enableSoftwareAES=!0)}var e=t.prototype;return e.destroy=function(){this.observer=null},e.isSync=function(){return this.config.enableSoftwareAES},e.flush=function(){var t=this.currentResult;if(t){var e=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?(0,s.removePadding)(e):e}this.reset()},e.reset=function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)},e.decrypt=function(t,e,r,i){if(this.config.enableSoftwareAES){this.softwareDecrypt(new Uint8Array(t),e,r);var n=this.flush();n&&i(n.buffer)}else this.webCryptoDecrypt(new Uint8Array(t),e,r).then(i)},e.softwareDecrypt=function(t,e,r){var i=this.currentIV,n=this.currentResult,a=this.remainderData;this.logOnce("JS AES decrypt"),a&&(t=(0,o.appendUint8Array)(a,t),this.remainderData=null);var d=this.getValidChunk(t);if(!d.length)return null;i&&(r=i);var u=this.softwareDecrypter;u||(u=this.softwareDecrypter=new s.default),u.expandKey(e);var c=n;return this.currentResult=u.decrypt(d.buffer,0,r),this.currentIV=(0,l.sliceUint8)(d,-16).buffer,c||null},e.webCryptoDecrypt=function(t,e,r){var s=this,a=this.subtle;return this.key===e&&this.fastAesKey||(this.key=e,this.fastAesKey=new n.default(a,e)),this.fastAesKey.expandKey().then((function(e){return a?new i.default(a,r).decrypt(t.buffer,e):Promise.reject(new Error("web crypto not initialized"))})).catch((function(i){return s.onWebCryptoError(i,t,e,r)}))},e.onWebCryptoError=function(t,e,r,i){return a.logger.warn("[decrypter.ts]: WebCrypto Error, disable WebCrypto API:",t),this.config.enableSoftwareAES=!0,this.logEnabled=!0,this.softwareDecrypt(e,r,i)},e.getValidChunk=function(t){var e=t,r=t.length-t.length%16;return r!==t.length&&(e=(0,l.sliceUint8)(t,0,r),this.remainderData=(0,l.sliceUint8)(t,r)),e},e.logOnce=function(t){this.logEnabled&&(a.logger.log("[decrypter.ts]: "+t),this.logEnabled=!1)},t}()},"./src/crypt/fast-aes-key.ts":
|
|
80
|
-
/*!***********************************!*\
|
|
81
|
-
!*** ./src/crypt/fast-aes-key.ts ***!
|
|
82
|
-
\***********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>i});var i=function(){function t(t,e){this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=e}return t.prototype.expandKey=function(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])},t}()},"./src/demux/aacdemuxer.ts":
|
|
83
|
-
/*!*********************************!*\
|
|
84
|
-
!*** ./src/demux/aacdemuxer.ts ***!
|
|
85
|
-
\*********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>l});var i=r(/*! ./base-audio-demuxer */"./src/demux/base-audio-demuxer.ts"),n=r(/*! ./adts */"./src/demux/adts.ts"),s=r(/*! ../utils/logger */"./src/utils/logger.ts"),a=r(/*! ../demux/id3 */"./src/demux/id3.ts");function o(t,e){return(o=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}const l=function(t){var e,r;function i(e,r){var i;return(i=t.call(this)||this).observer=void 0,i.config=void 0,i.observer=e,i.config=r,i}r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,o(e,r);var l=i.prototype;return l.resetInitSegment=function(e,r,i,n){t.prototype.resetInitSegment.call(this,e,r,i,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}},i.probe=function(t){if(!t)return!1;for(var e=(a.getID3Data(t,0)||[]).length,r=t.length;e<r;e++)if(n.probe(t,e))return s.logger.log("ADTS sync word found !"),!0;return!1},l.canParse=function(t,e){return n.canParse(t,e)},l.appendFrame=function(t,e,r){n.initTrackConfig(t,this.observer,e,r,t.manifestCodec);var i=n.appendFrame(t,e,r,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i},i}(i.default)},"./src/demux/adts.ts":
|
|
86
|
-
/*!***************************!*\
|
|
87
|
-
!*** ./src/demux/adts.ts ***!
|
|
88
|
-
\***************************/(t,e,r)=>{r.r(e),r.d(e,{appendFrame:()=>m,canGetFrameLength:()=>u,canParse:()=>h,getAudioConfig:()=>a,getFrameDuration:()=>g,getFullFrameLength:()=>d,getHeaderLength:()=>l,initTrackConfig:()=>p,isHeader:()=>c,isHeaderPattern:()=>o,parseFrameHeader:()=>v,probe:()=>f});var i=r(/*! ../utils/logger */"./src/utils/logger.ts"),n=r(/*! ../errors */"./src/errors.ts"),s=r(/*! ../events */"./src/events.ts");function a(t,e,r,a){var o,l,d,u,c=navigator.userAgent.toLowerCase(),h=a,f=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];o=1+((192&e[r+2])>>>6);var p=(60&e[r+2])>>>2;if(!(p>f.length-1))return d=(1&e[r+2])<<2,d|=(192&e[r+3])>>>6,i.logger.log("manifest codec:"+a+", ADTS type:"+o+", samplingIndex:"+p),/firefox/i.test(c)?p>=6?(o=5,u=new Array(4),l=p-3):(o=2,u=new Array(2),l=p):-1!==c.indexOf("android")?(o=2,u=new Array(2),l=p):(o=5,u=new Array(4),a&&(-1!==a.indexOf("mp4a.40.29")||-1!==a.indexOf("mp4a.40.5"))||!a&&p>=6?l=p-3:((a&&-1!==a.indexOf("mp4a.40.2")&&(p>=6&&1===d||/vivaldi/i.test(c))||!a&&1===d)&&(o=2,u=new Array(2)),l=p)),u[0]=o<<3,u[0]|=(14&p)>>1,u[1]|=(1&p)<<7,u[1]|=d<<3,5===o&&(u[1]|=(14&l)>>1,u[2]=(1&l)<<7,u[2]|=8,u[3]=0),{config:u,samplerate:f[p],channelCount:d,codec:"mp4a.40."+o,manifestCodec:h};t.trigger(s.Events.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+p})}function o(t,e){return 255===t[e]&&240==(246&t[e+1])}function l(t,e){return 1&t[e+1]?7:9}function d(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function u(t,e){return e+5<t.length}function c(t,e){return e+1<t.length&&o(t,e)}function h(t,e){return u(t,e)&&o(t,e)&&d(t,e)<=t.length-e}function f(t,e){if(c(t,e)){var r=l(t,e);if(e+r>=t.length)return!1;var i=d(t,e);if(i<=r)return!1;var n=e+i;return n===t.length||c(t,n)}return!1}function p(t,e,r,n,s){if(!t.samplerate){var o=a(e,r,n,s);if(!o)return;t.config=o.config,t.samplerate=o.samplerate,t.channelCount=o.channelCount,t.codec=o.codec,t.manifestCodec=o.manifestCodec,i.logger.log("parsed codec:"+t.codec+", rate:"+o.samplerate+", channels:"+o.channelCount)}}function g(t){return 9216e4/t}function v(t,e){var r=l(t,e);if(e+r<=t.length){var i=d(t,e)-r;if(i>0)return{headerLength:r,frameLength:i}}}function m(t,e,r,i,n){var s,a=i+n*g(t.samplerate),o=v(e,r);if(o){var l=o.frameLength,d=o.headerLength,u=d+l,c=Math.max(0,r+u-e.length);c?(s=new Uint8Array(u-d)).set(e.subarray(r+d,e.length),0):s=e.subarray(r+d,r+u);var h={unit:s,pts:a};return c||t.samples.push(h),{sample:h,length:u,missing:c}}var f=e.length-r;return(s=new Uint8Array(f)).set(e.subarray(r,e.length),0),{sample:{unit:s,pts:a},length:f,missing:-1}}},"./src/demux/base-audio-demuxer.ts":
|
|
89
|
-
/*!*****************************************!*\
|
|
90
|
-
!*** ./src/demux/base-audio-demuxer.ts ***!
|
|
91
|
-
\*****************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>c,initPTSFn:()=>u});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../demux/id3 */"./src/demux/id3.ts"),s=r(/*! ../types/demuxer */"./src/types/demuxer.ts"),a=r(/*! ./dummy-demuxed-track */"./src/demux/dummy-demuxed-track.ts"),o=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts"),l=r(/*! ../utils/typed-array */"./src/utils/typed-array.ts"),d=function(){function t(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}var e=t.prototype;return e.resetInitSegment=function(t,e,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},e.resetTimeStamp=function(t){this.initPTS=t,this.resetContiguity()},e.resetContiguity=function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0},e.canParse=function(t,e){return!1},e.appendFrame=function(t,e,r){},e.demux=function(t,e){this.cachedData&&(t=(0,o.appendUint8Array)(this.cachedData,t),this.cachedData=null);var r,d=n.getID3Data(t,0),c=d?d.length:0,h=this._audioTrack,f=this._id3Track,p=d?n.getTimeStamp(d):void 0,g=t.length;for((null===this.basePTS||0===this.frameIndex&&(0,i.isFiniteNumber)(p))&&(this.basePTS=u(p,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),d&&d.length>0&&f.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:d,type:s.MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY});c<g;){if(this.canParse(t,c)){var v=this.appendFrame(h,t,c);v?(this.frameIndex++,this.lastPTS=v.sample.pts,r=c+=v.length):c=g}else n.canParse(t,c)?(d=n.getID3Data(t,c),f.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:d,type:s.MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY}),r=c+=d.length):c++;if(c===g&&r!==g){var m=(0,l.sliceUint8)(t,r);this.cachedData?this.cachedData=(0,o.appendUint8Array)(this.cachedData,m):this.cachedData=m}}return{audioTrack:h,videoTrack:(0,a.dummyTrack)(),id3Track:f,textTrack:(0,a.dummyTrack)()}},e.demuxSampleAes=function(t,e,r){return Promise.reject(new Error("["+this+"] This demuxer does not support Sample-AES decryption"))},e.flush=function(t){var e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:(0,a.dummyTrack)(),id3Track:this._id3Track,textTrack:(0,a.dummyTrack)()}},e.destroy=function(){},t}(),u=function(t,e,r){return(0,i.isFiniteNumber)(t)?90*t:9e4*e+(r||0)};const c=d},"./src/demux/chunk-cache.ts":
|
|
92
|
-
/*!**********************************!*\
|
|
93
|
-
!*** ./src/demux/chunk-cache.ts ***!
|
|
94
|
-
\**********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>i});var i=function(){function t(){this.chunks=[],this.dataLength=0}var e=t.prototype;return e.push=function(t){this.chunks.push(t),this.dataLength+=t.length},e.flush=function(){var t,e=this.chunks,r=this.dataLength;return e.length?(t=1===e.length?e[0]:function(t,e){for(var r=new Uint8Array(e),i=0,n=0;n<t.length;n++){var s=t[n];r.set(s,i),i+=s.length}return r}(e,r),this.reset(),t):new Uint8Array(0)},e.reset=function(){this.chunks.length=0,this.dataLength=0},t}()},"./src/demux/dummy-demuxed-track.ts":
|
|
95
|
-
/*!******************************************!*\
|
|
96
|
-
!*** ./src/demux/dummy-demuxed-track.ts ***!
|
|
97
|
-
\******************************************/(t,e,r)=>{function i(t,e){return void 0===t&&(t=""),void 0===e&&(e=9e4),{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}r.r(e),r.d(e,{dummyTrack:()=>i})},"./src/demux/exp-golomb.ts":
|
|
98
|
-
/*!*********************************!*\
|
|
99
|
-
!*** ./src/demux/exp-golomb.ts ***!
|
|
100
|
-
\*********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>n});var i=r(/*! ../utils/logger */"./src/utils/logger.ts");const n=function(){function t(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}var e=t.prototype;return e.loadWord=function(){var t=this.data,e=this.bytesAvailable,r=t.byteLength-e,i=new Uint8Array(4),n=Math.min(4,e);if(0===n)throw new Error("no bytes available");i.set(t.subarray(r,r+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n},e.skipBits=function(t){var e;this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,t-=(e=t>>3)>>3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)},e.readBits=function(t){var e=Math.min(this.bitsAvailable,t),r=this.word>>>32-e;return t>32&&i.logger.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0?this.word<<=e:this.bytesAvailable>0&&this.loadWord(),(e=t-e)>0&&this.bitsAvailable?r<<e|this.readBits(e):r},e.skipLZ=function(){var t;for(t=0;t<this.bitsAvailable;++t)if(0!=(this.word&2147483648>>>t))return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()},e.skipUEG=function(){this.skipBits(1+this.skipLZ())},e.skipEG=function(){this.skipBits(1+this.skipLZ())},e.readUEG=function(){var t=this.skipLZ();return this.readBits(t+1)-1},e.readEG=function(){var t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)},e.readBoolean=function(){return 1===this.readBits(1)},e.readUByte=function(){return this.readBits(8)},e.readUShort=function(){return this.readBits(16)},e.readUInt=function(){return this.readBits(32)},e.skipScalingList=function(t){for(var e=8,r=8,i=0;i<t;i++)0!==r&&(r=(e+this.readEG()+256)%256),e=0===r?e:r},e.readSPS=function(){var t,e,r,i=0,n=0,s=0,a=0,o=this.readUByte.bind(this),l=this.readBits.bind(this),d=this.readUEG.bind(this),u=this.readBoolean.bind(this),c=this.skipBits.bind(this),h=this.skipEG.bind(this),f=this.skipUEG.bind(this),p=this.skipScalingList.bind(this);o();var g=o();if(l(5),c(3),o(),f(),100===g||110===g||122===g||244===g||44===g||83===g||86===g||118===g||128===g){var v=d();if(3===v&&c(1),f(),f(),c(1),u())for(e=3!==v?8:12,r=0;r<e;r++)u()&&p(r<6?16:64)}f();var m=d();if(0===m)d();else if(1===m)for(c(1),h(),h(),t=d(),r=0;r<t;r++)h();f(),c(1);var y=d(),E=d(),T=l(1);0===T&&c(1),c(1),u()&&(i=d(),n=d(),s=d(),a=d());var _=[1,1];if(u()&&u())switch(o()){case 1:_=[1,1];break;case 2:_=[12,11];break;case 3:_=[10,11];break;case 4:_=[16,11];break;case 5:_=[40,33];break;case 6:_=[24,11];break;case 7:_=[20,11];break;case 8:_=[32,11];break;case 9:_=[80,33];break;case 10:_=[18,11];break;case 11:_=[15,11];break;case 12:_=[64,33];break;case 13:_=[160,99];break;case 14:_=[4,3];break;case 15:_=[3,2];break;case 16:_=[2,1];break;case 255:_=[o()<<8|o(),o()<<8|o()]}return{width:Math.ceil(16*(y+1)-2*i-2*n),height:(2-T)*(E+1)*16-(T?2:4)*(s+a),pixelRatio:_}},e.readSliceType=function(){return this.readUByte(),this.readUEG(),this.readUEG()},t}()},"./src/demux/id3.ts":
|
|
101
|
-
/*!**************************!*\
|
|
102
|
-
!*** ./src/demux/id3.ts ***!
|
|
103
|
-
\**************************/(t,e,r)=>{r.r(e),r.d(e,{canParse:()=>l,decodeFrame:()=>f,getID3Data:()=>a,getID3Frames:()=>h,getTimeStamp:()=>d,isFooter:()=>s,isHeader:()=>n,isTimeStampFrame:()=>u,testables:()=>E,utf8ArrayToStr:()=>y});var i,n=function(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128},s=function(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128},a=function(t,e){for(var r=e,i=0;n(t,e);)i+=10,i+=o(t,e+6),s(t,e+10)&&(i+=10),e+=i;if(i>0)return t.subarray(r,r+i)},o=function(t,e){var r=0;return r=(127&t[e])<<21,r|=(127&t[e+1])<<14,r|=(127&t[e+2])<<7,r|=127&t[e+3]},l=function(t,e){return n(t,e)&&o(t,e+6)+10<=t.length-e},d=function(t){for(var e=h(t),r=0;r<e.length;r++){var i=e[r];if(u(i))return m(i)}},u=function(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info},c=function(t){var e=String.fromCharCode(t[0],t[1],t[2],t[3]),r=o(t,4);return{type:e,size:r,data:t.subarray(10,10+r)}},h=function(t){for(var e=0,r=[];n(t,e);){for(var i=o(t,e+6),a=(e+=10)+i;e+8<a;){var l=c(t.subarray(e)),d=f(l);d&&r.push(d),e+=l.size+10}s(t,e)&&(e+=10)}return r},f=function(t){return"PRIV"===t.type?p(t):"W"===t.type[0]?v(t):g(t)},p=function(t){if(!(t.size<2)){var e=y(t.data,!0),r=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:r.buffer}}},g=function(t){if(!(t.size<2)){if("TXXX"===t.type){var e=1,r=y(t.data.subarray(e),!0);e+=r.length+1;var i=y(t.data.subarray(e));return{key:t.type,info:r,data:i}}var n=y(t.data.subarray(1));return{key:t.type,data:n}}},v=function(t){if("WXXX"===t.type){if(t.size<2)return;var e=1,r=y(t.data.subarray(e),!0);e+=r.length+1;var i=y(t.data.subarray(e));return{key:t.type,info:r,data:i}}var n=y(t.data);return{key:t.type,data:n}},m=function(t){if(8===t.data.byteLength){var e=new Uint8Array(t.data),r=1&e[3],i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}},y=function(t,e){void 0===e&&(e=!1);var r=T();if(r){var i=r.decode(t);if(e){var n=i.indexOf("\0");return-1!==n?i.substring(0,n):i}return i.replace(/\0/g,"")}for(var s,a,o,l=t.length,d="",u=0;u<l;){if(0===(s=t[u++])&&e)return d;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:d+=String.fromCharCode(s);break;case 12:case 13:a=t[u++],d+=String.fromCharCode((31&s)<<6|63&a);break;case 14:a=t[u++],o=t[u++],d+=String.fromCharCode((15&s)<<12|(63&a)<<6|(63&o)<<0)}}return d},E={decodeTextFrame:g};function T(){return i||void 0===self.TextDecoder||(i=new self.TextDecoder("utf-8")),i}},"./src/demux/mp3demuxer.ts":
|
|
104
|
-
/*!*********************************!*\
|
|
105
|
-
!*** ./src/demux/mp3demuxer.ts ***!
|
|
106
|
-
\*********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>l});var i=r(/*! ./base-audio-demuxer */"./src/demux/base-audio-demuxer.ts"),n=r(/*! ../demux/id3 */"./src/demux/id3.ts"),s=r(/*! ../utils/logger */"./src/utils/logger.ts"),a=r(/*! ./mpegaudio */"./src/demux/mpegaudio.ts");function o(t,e){return(o=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}const l=function(t){var e,r;function i(){return t.apply(this,arguments)||this}r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,o(e,r);var l=i.prototype;return l.resetInitSegment=function(e,r,i,n){t.prototype.resetInitSegment.call(this,e,r,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}},i.probe=function(t){if(!t)return!1;for(var e=(n.getID3Data(t,0)||[]).length,r=t.length;e<r;e++)if(a.probe(t,e))return s.logger.log("MPEG Audio sync word found !"),!0;return!1},l.canParse=function(t,e){return a.canParse(t,e)},l.appendFrame=function(t,e,r){if(null!==this.basePTS)return a.appendFrame(t,e,r,this.basePTS,this.frameIndex)},i}(i.default)},"./src/demux/mp4demuxer.ts":
|
|
107
|
-
/*!*********************************!*\
|
|
108
|
-
!*** ./src/demux/mp4demuxer.ts ***!
|
|
109
|
-
\*********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>l});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../types/demuxer */"./src/types/demuxer.ts"),s=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts"),a=r(/*! ./dummy-demuxed-track */"./src/demux/dummy-demuxed-track.ts"),o=/\/emsg[-/]ID3/i;const l=function(){function t(t,e){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=e}var e=t.prototype;return e.resetTimeStamp=function(){},e.resetInitSegment=function(t,e,r,i){var n=(0,s.parseInitSegment)(t),o=this.videoTrack=(0,a.dummyTrack)("video",1),l=this.audioTrack=(0,a.dummyTrack)("audio",1),d=this.txtTrack=(0,a.dummyTrack)("text",1);if(this.id3Track=(0,a.dummyTrack)("id3",1),this.timeOffset=0,n.video){var u=n.video,c=u.id,h=u.timescale,f=u.codec;o.id=c,o.timescale=d.timescale=h,o.codec=f}if(n.audio){var p=n.audio,g=p.id,v=p.timescale,m=p.codec;l.id=g,l.timescale=v,l.codec=m}d.id=s.RemuxerTrackIdConfig.text,o.sampleDuration=0,o.duration=l.duration=i},e.resetContiguity=function(){},t.probe=function(t){return t=t.length>16384?t.subarray(0,16384):t,(0,s.findBox)(t,["moof"]).length>0},e.demux=function(t,e){this.timeOffset=e;var r=t,i=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=(0,s.appendUint8Array)(this.remainderData,t));var a=(0,s.segmentValidRange)(r);this.remainderData=a.remainder,i.samples=a.valid||new Uint8Array}else i.samples=r;var o=this.extractID3Track(i,e);return n.samples=(0,s.parseSamples)(e,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack}},e.flush=function(){var t=this.timeOffset,e=this.videoTrack,r=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;var i=this.extractID3Track(e,this.timeOffset);return r.samples=(0,s.parseSamples)(t,e),{videoTrack:e,audioTrack:(0,a.dummyTrack)(),id3Track:i,textTrack:(0,a.dummyTrack)()}},e.extractID3Track=function(t,e){var r=this.id3Track;if(t.samples.length){var a=(0,s.findBox)(t.samples,["emsg"]);a&&a.forEach((function(t){var a=(0,s.parseEmsg)(t);if(o.test(a.schemeIdUri)){var l=(0,i.isFiniteNumber)(a.presentationTime)?a.presentationTime/a.timeScale:e+a.presentationTimeDelta/a.timeScale,d=4294967295===a.eventDuration?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;d<=.001&&(d=Number.POSITIVE_INFINITY);var u=a.payload;r.samples.push({data:u,len:u.byteLength,dts:l,pts:l,type:n.MetadataSchema.emsg,duration:d})}}))}return r},e.demuxSampleAes=function(t,e,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},e.destroy=function(){},t}()},"./src/demux/mpegaudio.ts":
|
|
110
|
-
/*!********************************!*\
|
|
111
|
-
!*** ./src/demux/mpegaudio.ts ***!
|
|
112
|
-
\********************************/(t,e,r)=>{r.r(e),r.d(e,{appendFrame:()=>l,canParse:()=>h,isHeader:()=>c,isHeaderPattern:()=>u,parseHeader:()=>d,probe:()=>f});var i=null,n=[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],s=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],a=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],o=[0,1,1,4];function l(t,e,r,i,n){if(!(r+24>e.length)){var s=d(e,r);if(s&&r+s.frameLength<=e.length){var a=i+n*(9e4*s.samplesPerFrame/s.sampleRate),o={unit:e.subarray(r,r+s.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=s.channelCount,t.samplerate=s.sampleRate,t.samples.push(o),{sample:o,length:s.frameLength,missing:0}}}}function d(t,e){var r=t[e+1]>>3&3,l=t[e+1]>>1&3,d=t[e+2]>>4&15,u=t[e+2]>>2&3;if(1!==r&&0!==d&&15!==d&&3!==u){var c=t[e+2]>>1&1,h=t[e+3]>>6,f=1e3*n[14*(3===r?3-l:3===l?3:4)+d-1],p=s[3*(3===r?0:2===r?1:2)+u],g=3===h?1:2,v=a[r][l],m=o[l],y=8*v*m,E=Math.floor(v*f/p+c)*m;if(null===i){var T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);i=T?parseInt(T[1]):0}return!!i&&i<=87&&2===l&&f>=224e3&&0===h&&(t[e+3]=128|t[e+3]),{sampleRate:p,channelCount:g,frameLength:E,samplesPerFrame:y}}}function u(t,e){return 255===t[e]&&224==(224&t[e+1])&&0!=(6&t[e+1])}function c(t,e){return e+1<t.length&&u(t,e)}function h(t,e){return u(t,e)&&4<=t.length-e}function f(t,e){if(e+1<t.length&&u(t,e)){var r=d(t,e),i=4;null!=r&&r.frameLength&&(i=r.frameLength);var n=e+i;return n===t.length||c(t,n)}return!1}},"./src/demux/sample-aes.ts":
|
|
113
|
-
/*!*********************************!*\
|
|
114
|
-
!*** ./src/demux/sample-aes.ts ***!
|
|
115
|
-
\*********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>s});var i=r(/*! ../crypt/decrypter */"./src/crypt/decrypter.ts"),n=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts");const s=function(){function t(t,e,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new i.default(t,e,{removePKCS7Padding:!1})}var e=t.prototype;return e.decryptBuffer=function(t,e){this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,e)},e.decryptAacSample=function(t,e,r,i){var n=t[e].unit;if(!(n.length<=16)){var s=n.subarray(16,n.length-n.length%16),a=s.buffer.slice(s.byteOffset,s.byteOffset+s.length),o=this;this.decryptBuffer(a,(function(s){var a=new Uint8Array(s);n.set(a,16),i||o.decryptAacSamples(t,e+1,r)}))}},e.decryptAacSamples=function(t,e,r){for(;;e++){if(e>=t.length)return void r();if(!(t[e].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(t,e,r,i),!i)return}}},e.getAvcEncryptedData=function(t){for(var e=16*Math.floor((t.length-48)/160)+16,r=new Int8Array(e),i=0,n=32;n<t.length-16;n+=160,i+=16)r.set(t.subarray(n,n+16),i);return r},e.getAvcDecryptedUnit=function(t,e){for(var r=new Uint8Array(e),i=0,n=32;n<t.length-16;n+=160,i+=16)t.set(r.subarray(i,i+16),n);return t},e.decryptAvcSample=function(t,e,r,i,s,a){var o=(0,n.discardEPB)(s.data),l=this.getAvcEncryptedData(o),d=this;this.decryptBuffer(l.buffer,(function(n){s.data=d.getAvcDecryptedUnit(o,n),a||d.decryptAvcSamples(t,e,r+1,i)}))},e.decryptAvcSamples=function(t,e,r,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,r=0){if(e>=t.length)return void i();for(var n=t[e].units;!(r>=n.length);r++){var s=n[r];if(!(s.data.length<=48||1!==s.type&&5!==s.type)){var a=this.decrypter.isSync();if(this.decryptAvcSample(t,e,r,i,s,a),!a)return}}}},t}()},"./src/demux/transmuxer-interface.ts":
|
|
116
|
-
/*!*******************************************!*\
|
|
117
|
-
!*** ./src/demux/transmuxer-interface.ts ***!
|
|
118
|
-
\*******************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>c});var i=r(/*! ./webworkify-webpack */"./src/demux/webworkify-webpack.js"),n=r(/*! ../events */"./src/events.ts"),s=r(/*! ../demux/transmuxer */"./src/demux/transmuxer.ts"),a=r(/*! ../utils/logger */"./src/utils/logger.ts"),o=r(/*! ../errors */"./src/errors.ts"),l=r(/*! ../utils/mediasource-helper */"./src/utils/mediasource-helper.ts"),d=r(/*! eventemitter3 */"./node_modules/eventemitter3/index.js"),u=(0,l.getMediaSource)()||{isTypeSupported:function(){return!1}},c=function(){function t(t,e,r,l){var c=this;this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.worker=void 0,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;var h=t.config;this.hls=t,this.id=e,this.useWorker=!!h.enableWorker,this.onTransmuxComplete=r,this.onFlush=l;var f=function(t,e){(e=e||{}).frag=c.frag,e.id=c.id,c.hls.trigger(t,e)};this.observer=new d.EventEmitter,this.observer.on(n.Events.FRAG_DECRYPTED,f),this.observer.on(n.Events.ERROR,f);var p={mp4:u.isTypeSupported("video/mp4"),mpeg:u.isTypeSupported("audio/mpeg"),mp3:u.isTypeSupported('audio/mp4; codecs="mp3"')},g=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){var v;a.logger.log("demuxing in webworker");try{v=this.worker=(0,i.default)(/*! ../demux/transmuxer-worker.ts */"./src/demux/transmuxer-worker.ts"),this.onwmsg=this.onWorkerMessage.bind(this),v.addEventListener("message",this.onwmsg),v.onerror=function(t){c.useWorker=!1,a.logger.warn("Exception in webworker, fallback to inline"),c.hls.trigger(n.Events.ERROR,{type:o.ErrorTypes.OTHER_ERROR,details:o.ErrorDetails.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:new Error(t.message+" ("+t.filename+":"+t.lineno+")")})},v.postMessage({cmd:"init",typeSupported:p,vendor:g,id:e,config:JSON.stringify(h)})}catch(t){a.logger.warn("Error in worker:",t),a.logger.error("Error while initializing DemuxerWorker, fallback to inline"),v&&self.URL.revokeObjectURL(v.objectURL),this.transmuxer=new s.default(this.observer,p,h,g,e),this.worker=null}}else this.transmuxer=new s.default(this.observer,p,h,g,e)}var e=t.prototype;return e.destroy=function(){var t=this.worker;if(t)t.removeEventListener("message",this.onwmsg),t.terminate(),this.worker=null,this.onwmsg=void 0;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var r=this.observer;r&&r.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null},e.push=function(t,e,r,i,n,o,l,d,u,c){var h,f,p=this;u.transmuxing.start=self.performance.now();var g=this.transmuxer,v=this.worker,m=o?o.start:n.start,y=n.decryptdata,E=this.frag,T=!(E&&n.cc===E.cc),_=!(E&&u.level===E.level),S=E?u.sn-E.sn:-1,b=this.part?u.part-this.part.index:-1,A=0===S&&u.id>1&&u.id===(null==E?void 0:E.stats.chunkCount),L=!_&&(1===S||0===S&&(1===b||A&&b<=0)),w=self.performance.now();(_||S||0===n.stats.parsing.start)&&(n.stats.parsing.start=w),!o||!b&&L||(o.stats.parsing.start=w);var D=!(E&&(null===(h=n.initSegment)||void 0===h?void 0:h.url)===(null===(f=E.initSegment)||void 0===f?void 0:f.url)),R=new s.TransmuxState(T,L,d,_,m,D);if(!L||T||D){a.logger.log("[transmuxer-interface, "+n.type+"]: Starting new transmux session for sn: "+u.sn+" p: "+u.part+" level: "+u.level+" id: "+u.id+"\n discontinuity: "+T+"\n trackSwitch: "+_+"\n contiguous: "+L+"\n accurateTimeOffset: "+d+"\n timeOffset: "+m+"\n initSegmentChange: "+D);var I=new s.TransmuxConfig(r,i,e,l,c);this.configureTransmuxer(I)}if(this.frag=n,this.part=o,v)v.postMessage({cmd:"demux",data:t,decryptdata:y,chunkMeta:u,state:R},t instanceof ArrayBuffer?[t]:[]);else if(g){var k=g.push(t,y,u,R);(0,s.isPromise)(k)?k.then((function(t){p.handleTransmuxComplete(t)})):this.handleTransmuxComplete(k)}},e.flush=function(t){var e=this;t.transmuxing.start=self.performance.now();var r=this.transmuxer,i=this.worker;if(i)i.postMessage({cmd:"flush",chunkMeta:t});else if(r){var n=r.flush(t);(0,s.isPromise)(n)?n.then((function(r){e.handleFlushResult(r,t)})):this.handleFlushResult(n,t)}},e.handleFlushResult=function(t,e){var r=this;t.forEach((function(t){r.handleTransmuxComplete(t)})),this.onFlush(e)},e.onWorkerMessage=function(t){var e=t.data,r=this.hls;switch(e.event){case"init":self.URL.revokeObjectURL(this.worker.objectURL);break;case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":a.logger[e.data.logType]&&a.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,r.trigger(e.event,e.data)}},e.configureTransmuxer=function(t){var e=this.worker,r=this.transmuxer;e?e.postMessage({cmd:"configure",config:t}):r&&r.configure(t)},e.handleTransmuxComplete=function(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)},t}()},"./src/demux/transmuxer-worker.ts":
|
|
119
|
-
/*!****************************************!*\
|
|
120
|
-
!*** ./src/demux/transmuxer-worker.ts ***!
|
|
121
|
-
\****************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>o});var i=r(/*! ../demux/transmuxer */"./src/demux/transmuxer.ts"),n=r(/*! ../events */"./src/events.ts"),s=r(/*! ../utils/logger */"./src/utils/logger.ts"),a=r(/*! eventemitter3 */"./node_modules/eventemitter3/index.js");function o(t){var e=new a.EventEmitter,r=function(e,r){t.postMessage({event:e,data:r})};e.on(n.Events.FRAG_DECRYPTED,r),e.on(n.Events.ERROR,r),t.addEventListener("message",(function(n){var a=n.data;switch(a.cmd){case"init":var o=JSON.parse(a.config);t.transmuxer=new i.default(e,a.typeSupported,o,a.vendor,a.id),(0,s.enableLogs)(o.debug,a.id),function(){var t=function(t){s.logger[t]=function(e){r("workerLog",{logType:t,message:e})}};for(var e in s.logger)t(e)}(),r("init",null);break;case"configure":t.transmuxer.configure(a.config);break;case"demux":var d=t.transmuxer.push(a.data,a.decryptdata,a.chunkMeta,a.state);(0,i.isPromise)(d)?d.then((function(e){l(t,e)})):l(t,d);break;case"flush":var c=a.chunkMeta,h=t.transmuxer.flush(c);(0,i.isPromise)(h)?h.then((function(e){u(t,e,c)})):u(t,h,c)}}))}function l(t,e){if(!((r=e.remuxResult).audio||r.video||r.text||r.id3||r.initSegment))return!1;var r,i=[],n=e.remuxResult,s=n.audio,a=n.video;return s&&d(i,s),a&&d(i,a),t.postMessage({event:"transmuxComplete",data:e},i),!0}function d(t,e){e.data1&&t.push(e.data1.buffer),e.data2&&t.push(e.data2.buffer)}function u(t,e,r){e.reduce((function(e,r){return l(t,r)||e}),!1)||t.postMessage({event:"transmuxComplete",data:e[0]}),t.postMessage({event:"flush",data:r})}},"./src/demux/transmuxer.ts":
|
|
122
|
-
/*!*********************************!*\
|
|
123
|
-
!*** ./src/demux/transmuxer.ts ***!
|
|
124
|
-
\*********************************/(t,e,r)=>{r.r(e),r.d(e,{TransmuxConfig:()=>y,TransmuxState:()=>E,default:()=>g,isPromise:()=>m});var i,n=r(/*! ../events */"./src/events.ts"),s=r(/*! ../errors */"./src/errors.ts"),a=r(/*! ../crypt/decrypter */"./src/crypt/decrypter.ts"),o=r(/*! ../demux/aacdemuxer */"./src/demux/aacdemuxer.ts"),l=r(/*! ../demux/mp4demuxer */"./src/demux/mp4demuxer.ts"),d=r(/*! ../demux/tsdemuxer */"./src/demux/tsdemuxer.ts"),u=r(/*! ../demux/mp3demuxer */"./src/demux/mp3demuxer.ts"),c=r(/*! ../remux/mp4-remuxer */"./src/remux/mp4-remuxer.ts"),h=r(/*! ../remux/passthrough-remuxer */"./src/remux/passthrough-remuxer.ts"),f=r(/*! ../utils/logger */"./src/utils/logger.ts");try{i=self.performance.now.bind(self.performance)}catch(t){f.logger.debug("Unable to use Performance API on this environment"),i=self.Date.now}var p=[{demux:d.default,remux:c.default},{demux:l.default,remux:h.default},{demux:o.default,remux:c.default},{demux:u.default,remux:c.default}],g=function(){function t(t,e,r,i,n){this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=e,this.config=r,this.vendor=i,this.id=n}var e=t.prototype;return e.configure=function(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()},e.push=function(t,e,r,n){var s=this,a=r.transmuxing;a.executeStart=i();var o=new Uint8Array(t),l=this.config,d=this.currentTransmuxState,u=this.transmuxConfig;n&&(this.currentTransmuxState=n);var c=n||d,h=c.contiguous,f=c.discontinuity,p=c.trackSwitch,g=c.accurateTimeOffset,m=c.timeOffset,y=c.initSegmentChange,E=u.audioCodec,T=u.videoCodec,_=u.defaultInitPts,S=u.duration,b=u.initSegmentData;(f||p||y)&&this.resetInitSegment(b,E,T,S),(f||y)&&this.resetInitialTimestamp(_),h||this.resetContiguity();var A=function(t,e){var r=null;return t.byteLength>0&&null!=e&&null!=e.key&&null!==e.iv&&null!=e.method&&(r=e),r}(o,e);if(A&&"AES-128"===A.method){var L=this.getDecrypter();if(!l.enableSoftwareAES)return this.decryptionPromise=L.webCryptoDecrypt(o,A.key.buffer,A.iv.buffer).then((function(t){var e=s.push(t,null,r);return s.decryptionPromise=null,e})),this.decryptionPromise;var w=L.softwareDecrypt(o,A.key.buffer,A.iv.buffer);if(!w)return a.executeEnd=i(),v(r);o=new Uint8Array(w)}this.needsProbing(o,f,p)&&this.configureTransmuxer(o,u);var D=this.transmux(o,A,m,g,r),R=this.currentTransmuxState;return R.contiguous=!0,R.discontinuity=!1,R.trackSwitch=!1,a.executeEnd=i(),D},e.flush=function(t){var e=this,r=t.transmuxing;r.executeStart=i();var a=this.decrypter,o=this.currentTransmuxState,l=this.decryptionPromise;if(l)return l.then((function(){return e.flush(t)}));var d=[],u=o.timeOffset;if(a){var c=a.flush();c&&d.push(this.push(c,null,t))}var h=this.demuxer,f=this.remuxer;if(!h||!f)return this.observer.emit(n.Events.ERROR,n.Events.ERROR,{type:s.ErrorTypes.MEDIA_ERROR,details:s.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"}),r.executeEnd=i(),[v(t)];var p=h.flush(u);return m(p)?p.then((function(r){return e.flushRemux(d,r,t),d})):(this.flushRemux(d,p,t),d)},e.flushRemux=function(t,e,r){var n=e.audioTrack,s=e.videoTrack,a=e.id3Track,o=e.textTrack,l=this.currentTransmuxState,d=l.accurateTimeOffset,u=l.timeOffset;f.logger.log("[transmuxer.ts]: Flushed fragment "+r.sn+(r.part>-1?" p: "+r.part:"")+" of level "+r.level);var c=this.remuxer.remux(n,s,a,o,u,d,!0,this.id);t.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=i()},e.resetInitialTimestamp=function(t){var e=this.demuxer,r=this.remuxer;e&&r&&(e.resetTimeStamp(t),r.resetTimeStamp(t))},e.resetContiguity=function(){var t=this.demuxer,e=this.remuxer;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())},e.resetInitSegment=function(t,e,r,i){var n=this.demuxer,s=this.remuxer;n&&s&&(n.resetInitSegment(t,e,r,i),s.resetInitSegment(t,e,r))},e.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},e.transmux=function(t,e,r,i,n){return e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,r,i,n):this.transmuxUnencrypted(t,r,i,n)},e.transmuxUnencrypted=function(t,e,r,i){var n=this.demuxer.demux(t,e,!1,!this.config.progressive),s=n.audioTrack,a=n.videoTrack,o=n.id3Track,l=n.textTrack;return{remuxResult:this.remuxer.remux(s,a,o,l,e,r,!1,this.id),chunkMeta:i}},e.transmuxSampleAes=function(t,e,r,i,n){var s=this;return this.demuxer.demuxSampleAes(t,e,r).then((function(t){return{remuxResult:s.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,r,i,!1,s.id),chunkMeta:n}}))},e.configureTransmuxer=function(t,e){for(var r,i=this.config,n=this.observer,s=this.typeSupported,a=this.vendor,o=e.audioCodec,d=e.defaultInitPts,u=e.duration,c=e.initSegmentData,g=e.videoCodec,v=0,m=p.length;v<m;v++)if(p[v].demux.probe(t)){r=p[v];break}r||(f.logger.warn("Failed to find demuxer by probing frag, treating as mp4 passthrough"),r={demux:l.default,remux:h.default});var y=this.demuxer,E=this.remuxer,T=r.remux,_=r.demux;E&&E instanceof T||(this.remuxer=new T(n,i,s,a)),y&&y instanceof _||(this.demuxer=new _(n,i,s),this.probe=_.probe),this.resetInitSegment(c,o,g,u),this.resetInitialTimestamp(d)},e.needsProbing=function(t,e,r){return!this.demuxer||!this.remuxer||e||r},e.getDecrypter=function(){var t=this.decrypter;return t||(t=this.decrypter=new a.default(this.observer,this.config)),t},t}(),v=function(t){return{remuxResult:{},chunkMeta:t}};function m(t){return"then"in t&&t.then instanceof Function}var y=function(t,e,r,i,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=r,this.duration=i,this.defaultInitPts=n},E=function(t,e,r,i,n,s){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=t,this.contiguous=e,this.accurateTimeOffset=r,this.trackSwitch=i,this.timeOffset=n,this.initSegmentChange=s}},"./src/demux/tsdemuxer.ts":
|
|
125
|
-
/*!********************************!*\
|
|
126
|
-
!*** ./src/demux/tsdemuxer.ts ***!
|
|
127
|
-
\********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>y});var i=r(/*! ./adts */"./src/demux/adts.ts"),n=r(/*! ./mpegaudio */"./src/demux/mpegaudio.ts"),s=r(/*! ./exp-golomb */"./src/demux/exp-golomb.ts"),a=r(/*! ./sample-aes */"./src/demux/sample-aes.ts"),o=r(/*! ../events */"./src/events.ts"),l=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts"),d=r(/*! ../utils/logger */"./src/utils/logger.ts"),u=r(/*! ../errors */"./src/errors.ts"),c=r(/*! ../types/demuxer */"./src/types/demuxer.ts");function h(){return(h=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t}).apply(this,arguments)}function f(t,e,r,i){return{key:t,frame:!1,pts:e,dts:r,units:[],debug:i,length:0}}function p(t,e){return(31&t[e+10])<<8|t[e+11]}function g(t,e,r,i){var n={audio:-1,avc:-1,id3:-1,segmentCodec:"aac"},s=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<s;){var a=(31&t[e+1])<<8|t[e+2];switch(t[e]){case 207:if(!i){d.logger.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:-1===n.audio&&(n.audio=a);break;case 21:-1===n.id3&&(n.id3=a);break;case 219:if(!i){d.logger.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:-1===n.avc&&(n.avc=a);break;case 3:case 4:!0!==r.mpeg&&!0!==r.mp3?d.logger.log("MPEG audio found, not supported in this browser"):-1===n.audio&&(n.audio=a,n.segmentCodec="mp3");break;case 36:d.logger.warn("Unsupported HEVC stream type found")}e+=5+((15&t[e+3])<<8|t[e+4])}return n}function v(t){var e,r,i,n,s,a=0,o=t.data;if(!t||0===t.size)return null;for(;o[0].length<19&&o.length>1;){var l=new Uint8Array(o[0].length+o[1].length);l.set(o[0]),l.set(o[1],o[0].length),o[0]=l,o.splice(1,1)}if(1===((e=o[0])[0]<<16)+(e[1]<<8)+e[2]){if((r=(e[4]<<8)+e[5])&&r>t.size-6)return null;var u=e[7];192&u&&(n=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&u?n-(s=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2)>54e5&&(d.logger.warn(Math.round((n-s)/9e4)+"s delta between PTS and DTS, align them"),n=s):s=n);var c=(i=e[8])+9;if(t.size<=c)return null;t.size-=c;for(var h=new Uint8Array(t.size),f=0,p=o.length;f<p;f++){var g=(e=o[f]).byteLength;if(c){if(c>g){c-=g;continue}e=e.subarray(c),g-=c,c=0}h.set(e,a),a+=g}return r&&(r-=i+3),{data:h,pts:n,dts:s,len:r}}return null}function m(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){var r=e.samples,i=r.length;if(!i)return void e.dropped++;var n=r[i-1];t.pts=n.pts,t.dts=n.dts}e.samples.push(t)}t.debug.length&&d.logger.log(t.pts+"/"+t.dts+":"+t.debug)}const y=function(){function t(t,e,r){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=t,this.config=e,this.typeSupported=r}t.probe=function(e){var r=t.syncOffset(e);return r>0&&d.logger.warn("MPEG2-TS detected but first sync word found @ offset "+r),-1!==r},t.syncOffset=function(t){for(var e=Math.min(940,t.length-376)+1,r=0;r<e;){if(71===t[r]&&71===t[r+188])return r;r++}return-1},t.createTrack=function(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:l.RemuxerTrackIdConfig[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}};var e=t.prototype;return e.resetInitSegment=function(e,r,i,n){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=t.createTrack("video"),this._audioTrack=t.createTrack("audio",n),this._id3Track=t.createTrack("id3"),this._txtTrack=t.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=i,this._duration=n},e.resetTimeStamp=function(){},e.resetContiguity=function(){var t=this._audioTrack,e=this._avcTrack,r=this._id3Track;t&&(t.pesData=null),e&&(e.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null},e.demux=function(e,r,i,n){var s;void 0===i&&(i=!1),void 0===n&&(n=!1),i||(this.sampleAes=null);var a=this._avcTrack,c=this._audioTrack,h=this._id3Track,f=this._txtTrack,m=a.pid,y=a.pesData,E=c.pid,T=h.pid,_=c.pesData,S=h.pesData,b=null,A=this.pmtParsed,L=this._pmtId,w=e.length;if(this.remainderData&&(w=(e=(0,l.appendUint8Array)(this.remainderData,e)).length,this.remainderData=null),w<188&&!n)return this.remainderData=e,{audioTrack:c,videoTrack:a,id3Track:h,textTrack:f};var D=Math.max(0,t.syncOffset(e));(w-=(w-D)%188)<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,w,e.buffer.byteLength-w));for(var R=0,I=D;I<w;I+=188)if(71===e[I]){var k=!!(64&e[I+1]),O=((31&e[I+1])<<8)+e[I+2],C=void 0;if((48&e[I+3])>>4>1){if((C=I+5+e[I+4])===I+188)continue}else C=I+4;switch(O){case m:k&&(y&&(s=v(y))&&this.parseAVCPES(a,f,s,!1),y={data:[],size:0}),y&&(y.data.push(e.subarray(C,I+188)),y.size+=I+188-C);break;case E:if(k){if(_&&(s=v(_)))switch(c.segmentCodec){case"aac":this.parseAACPES(c,s);break;case"mp3":this.parseMPEGPES(c,s)}_={data:[],size:0}}_&&(_.data.push(e.subarray(C,I+188)),_.size+=I+188-C);break;case T:k&&(S&&(s=v(S))&&this.parseID3PES(h,s),S={data:[],size:0}),S&&(S.data.push(e.subarray(C,I+188)),S.size+=I+188-C);break;case 0:k&&(C+=e[C]+1),L=this._pmtId=p(e,C);break;case L:k&&(C+=e[C]+1);var P=g(e,C,this.typeSupported,i);(m=P.avc)>0&&(a.pid=m),(E=P.audio)>0&&(c.pid=E,c.segmentCodec=P.segmentCodec),(T=P.id3)>0&&(h.pid=T),null===b||A||(d.logger.log("unknown PID '"+b+"' in TS found"),b=null,I=D-188),A=this.pmtParsed=!0;break;case 17:case 8191:break;default:b=O}}else R++;R>0&&this.observer.emit(o.Events.ERROR,o.Events.ERROR,{type:u.ErrorTypes.MEDIA_ERROR,details:u.ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,reason:"Found "+R+" TS packet/s that do not start with 0x47"}),a.pesData=y,c.pesData=_,h.pesData=S;var x={audioTrack:c,videoTrack:a,id3Track:h,textTrack:f};return n&&this.extractRemainingSamples(x),x},e.flush=function(){var t,e=this.remainderData;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._avcTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t},e.extractRemainingSamples=function(t){var e,r=t.audioTrack,i=t.videoTrack,n=t.id3Track,s=t.textTrack,a=i.pesData,o=r.pesData,l=n.pesData;if(a&&(e=v(a))?(this.parseAVCPES(i,s,e,!0),i.pesData=null):i.pesData=a,o&&(e=v(o))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,e);break;case"mp3":this.parseMPEGPES(r,e)}r.pesData=null}else null!=o&&o.size&&d.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;l&&(e=v(l))?(this.parseID3PES(n,e),n.pesData=null):n.pesData=l},e.demuxSampleAes=function(t,e,r){var i=this.demux(t,r,!0,!this.config.progressive),n=this.sampleAes=new a.default(this.observer,this.config,e);return this.decrypt(i,n)},e.decrypt=function(t,e){return new Promise((function(r){var i=t.audioTrack,n=t.videoTrack;i.samples&&"aac"===i.segmentCodec?e.decryptAacSamples(i.samples,0,(function(){n.samples?e.decryptAvcSamples(n.samples,0,0,(function(){r(t)})):r(t)})):n.samples&&e.decryptAvcSamples(n.samples,0,0,(function(){r(t)}))}))},e.destroy=function(){this._duration=0},e.parseAVCPES=function(t,e,r,i){var n,a=this,o=this.parseAVCNALu(t,r.data),d=this.avcSample,u=!1;r.data=null,d&&o.length&&!t.audFound&&(m(d,t),d=this.avcSample=f(!1,r.pts,r.dts,"")),o.forEach((function(i){switch(i.type){case 1:n=!0,d||(d=a.avcSample=f(!0,r.pts,r.dts,"")),d.frame=!0;var o=i.data;if(u&&o.length>4){var c=new s.default(o).readSliceType();2!==c&&4!==c&&7!==c&&9!==c||(d.key=!0)}break;case 5:n=!0,d||(d=a.avcSample=f(!0,r.pts,r.dts,"")),d.key=!0,d.frame=!0;break;case 6:n=!0,(0,l.parseSEIMessageFromNALu)(i.data,1,r.pts,e.samples);break;case 7:if(n=!0,u=!0,!t.sps){var h=new s.default(i.data).readSPS();t.width=h.width,t.height=h.height,t.pixelRatio=h.pixelRatio,t.sps=[i.data],t.duration=a._duration;for(var p=i.data.subarray(1,4),g="avc1.",v=0;v<3;v++){var y=p[v].toString(16);y.length<2&&(y="0"+y),g+=y}t.codec=g}break;case 8:n=!0,t.pps||(t.pps=[i.data]);break;case 9:n=!1,t.audFound=!0,d&&m(d,t),d=a.avcSample=f(!1,r.pts,r.dts,"");break;case 12:n=!0;break;default:n=!1,d&&(d.debug+="unknown NAL "+i.type+" ")}d&&n&&d.units.push(i)})),i&&d&&(m(d,t),this.avcSample=null)},e.getLastNalUnit=function(t){var e,r,i=this.avcSample;if(i&&0!==i.units.length||(i=t[t.length-1]),null!==(e=i)&&void 0!==e&&e.units){var n=i.units;r=n[n.length-1]}return r},e.parseAVCNALu=function(t,e){var r,i,n=e.byteLength,s=t.naluState||0,a=s,o=[],l=0,d=-1,u=0;for(-1===s&&(d=0,u=31&e[0],s=0,l=1);l<n;)if(r=e[l++],s)if(1!==s)if(r)if(1===r){if(d>=0){var c={data:e.subarray(d,l-s-1),type:u};o.push(c)}else{var h=this.getLastNalUnit(t.samples);if(h&&(a&&l<=4-a&&h.state&&(h.data=h.data.subarray(0,h.data.byteLength-a)),(i=l-s-1)>0)){var f=new Uint8Array(h.data.byteLength+i);f.set(h.data,0),f.set(e.subarray(0,i),h.data.byteLength),h.data=f,h.state=0}}l<n?(d=l,u=31&e[l],s=0):s=-1}else s=0;else s=3;else s=r?0:2;else s=r?0:1;if(d>=0&&s>=0){var p={data:e.subarray(d,n),type:u,state:s};o.push(p)}if(0===o.length){var g=this.getLastNalUnit(t.samples);if(g){var v=new Uint8Array(g.data.byteLength+e.byteLength);v.set(g.data,0),v.set(e,g.data.byteLength),g.data=v}}return t.naluState=s,o},e.parseAACPES=function(t,e){var r,n,s,a,l,c=0,h=this.aacOverFlow,f=e.data;if(h){this.aacOverFlow=null;var p=h.missing,g=h.sample.unit.byteLength;if(-1===p){var v=new Uint8Array(g+f.byteLength);v.set(h.sample.unit,0),v.set(f,g),f=v}else{var m=g-p;h.sample.unit.set(f.subarray(0,p),m),t.samples.push(h.sample),c=h.missing}}for(r=c,n=f.length;r<n-1&&!i.isHeader(f,r);r++);if(r===c||(r<n-1?(s="AAC PES did not start with ADTS header,offset:"+r,a=!1):(s="no ADTS header found in AAC PES",a=!0),d.logger.warn("parsing error:"+s),this.observer.emit(o.Events.ERROR,o.Events.ERROR,{type:u.ErrorTypes.MEDIA_ERROR,details:u.ErrorDetails.FRAG_PARSING_ERROR,fatal:a,reason:s}),!a)){if(i.initTrackConfig(t,this.observer,f,r,this.audioCodec),void 0!==e.pts)l=e.pts;else{if(!h)return void d.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var y=i.getFrameDuration(t.samplerate);l=h.sample.pts+y}for(var E,T=0;r<n;){if(r+=(E=i.appendFrame(t,f,r,l,T)).length,E.missing){this.aacOverFlow=E;break}for(T++;r<n-1&&!i.isHeader(f,r);r++);}}},e.parseMPEGPES=function(t,e){var r=e.data,i=r.length,s=0,a=0,o=e.pts;if(void 0!==o)for(;a<i;)if(n.isHeader(r,a)){var l=n.appendFrame(t,r,a,o,s);if(!l)break;a+=l.length,s++}else a++;else d.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")},e.parseID3PES=function(t,e){if(void 0!==e.pts){var r=h({},e,{type:this._avcTrack?c.MetadataSchema.emsg:c.MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(r)}else d.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")},t}()},"./src/demux/webworkify-webpack.js":
|
|
128
|
-
/*!*****************************************!*\
|
|
129
|
-
!*** ./src/demux/webworkify-webpack.js ***!
|
|
130
|
-
\*****************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>l});var i=function(){var t=ENTRY_MODULE,e={};function r(i){var n=e[i];if(void 0!==n)return n.exports;var s=e[i]={exports:{}};return t[i].call(s.exports,s,s.exports,r),s.exports}r.m=t,r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,{a:e}),e},r.d=function(t,e){for(var i in e)r.o(e,i)&&!r.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var i=r(ENTRY_MODULE);return i.default||i};function n(t){return(t+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function s(t,e,i){var s={};s[i]=[];var a=e.toString(),o=a.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/)||a.match(/^\(\w+,\s*\w+,\s*(\w+)\)\s?\=\s?\>/);if(!o)return s;for(var l,d=o[1],u=new RegExp("(\\\\n|\\W)"+n(d)+"\\(\\s*(/\\*.*?\\*/)?\\s*.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)","g");l=u.exec(a);)"dll-reference"!==l[3]&&s[i].push(l[3]);for(u=new RegExp("\\("+n(d)+'\\("(dll-reference\\s([\\.|\\-|\\+|\\w|/|@]+))"\\)\\)\\(\\s*(/\\*.*?\\*/)?\\s*.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)',"g");l=u.exec(a);)t[l[2]]||(s[i].push(l[1]),t[l[2]]=r(l[1]).m),s[l[2]]=s[l[2]]||[],s[l[2]].push(l[4]);for(var c,h=Object.keys(s),f=0;f<h.length;f++)for(var p=0;p<s[h[f]].length;p++)c=s[h[f]][p],isNaN(1*c)||(s[h[f]][p]=1*s[h[f]][p]);return s}function a(t){return Object.keys(t).reduce((function(e,r){return e||t[r].length>0}),!1)}function o(t,e,r,n){var s=t[n].map((function(t){return'"'+t+'": '+e[n][t].toString()})).join(","),a=i.toString().split("ENTRY_MODULE");return a[0]+"{"+s+"}"+a[1]+'"'+r+'"'+a[2]}function l(t,e){e=e||{};var i={main:r.m},n=e.all?{main:Object.keys(i.main)}:function(t,e){for(var r={main:[e]},i={main:[]},n={main:{}};a(r);)for(var o=Object.keys(r),l=0;l<o.length;l++){var d=o[l],u=r[d].pop();if(n[d]=n[d]||{},!n[d][u]&&t[d][u]){n[d][u]=!0,i[d]=i[d]||[],i[d].push(u);for(var c=s(t,t[d][u],d),h=Object.keys(c),f=0;f<h.length;f++)r[h[f]]=r[h[f]]||[],r[h[f]]=r[h[f]].concat(c[h[f]])}}return i}(i,t),l="";Object.keys(n).filter((function(t){return"main"!==t})).forEach((function(t){for(var e=0;n[t][e];)e++;n[t].push(e),i[t][e]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",l=l+"var "+t+" = ("+o(n,i,e,modules)+")();\n"})),l=l+"(("+o(n,i,t,"main")+")())(self);";var d=new window.Blob([l],{type:"text/javascript"}),u=(window.URL||window.webkitURL||window.mozURL||window.msURL).createObjectURL(d),c=new window.Worker(u);return c.objectURL=u,c}i.toString()},"./src/errors.ts":
|
|
131
|
-
/*!***********************!*\
|
|
132
|
-
!*** ./src/errors.ts ***!
|
|
133
|
-
\***********************/(t,e,r)=>{var i,n;r.r(e),r.d(e,{ErrorDetails:()=>n,ErrorTypes:()=>i}),function(t){t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError"}(i||(i={})),function(t){t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_NO_INIT_DATA="keySystemNoInitData",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.UNKNOWN="unknown"}(n||(n={}))},"./src/events.ts":
|
|
134
|
-
/*!***********************!*\
|
|
135
|
-
!*** ./src/events.ts ***!
|
|
136
|
-
\***********************/(t,e,r)=>{var i;r.r(e),r.d(e,{Events:()=>i}),function(t){t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached"}(i||(i={}))},"./src/hls.ts":
|
|
137
|
-
/*!********************!*\
|
|
138
|
-
!*** ./src/hls.ts ***!
|
|
139
|
-
\********************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>y});var i=r(/*! url-toolkit */"./node_modules/url-toolkit/src/url-toolkit.js"),n=r(/*! ./loader/playlist-loader */"./src/loader/playlist-loader.ts"),s=r(/*! ./loader/key-loader */"./src/loader/key-loader.ts"),a=r(/*! ./controller/id3-track-controller */"./src/controller/id3-track-controller.ts"),o=r(/*! ./controller/latency-controller */"./src/controller/latency-controller.ts"),l=r(/*! ./controller/level-controller */"./src/controller/level-controller.ts"),d=r(/*! ./controller/fragment-tracker */"./src/controller/fragment-tracker.ts"),u=r(/*! ./controller/stream-controller */"./src/controller/stream-controller.ts"),c=r(/*! ./is-supported */"./src/is-supported.ts"),h=r(/*! ./utils/logger */"./src/utils/logger.ts"),f=r(/*! ./config */"./src/config.ts"),p=r(/*! eventemitter3 */"./node_modules/eventemitter3/index.js"),g=r(/*! ./events */"./src/events.ts"),v=r(/*! ./errors */"./src/errors.ts");function m(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}var y=function(){function t(e){void 0===e&&(e={}),this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new p.EventEmitter,this._autoLevelCapping=void 0,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null;var r=this.config=(0,f.mergeConfig)(t.DefaultConfig,e);this.userConfig=e,(0,h.enableLogs)(r.debug,"Hls instance"),this._autoLevelCapping=-1,r.progressive&&(0,f.enableStreamingMode)(r);var i=r.abrController,c=r.bufferController,g=r.capLevelController,v=r.fpsController,m=this.abrController=new i(this),y=this.bufferController=new c(this),E=this.capLevelController=new g(this),T=new v(this),_=new n.default(this),S=new s.default(this),b=new a.default(this),A=this.levelController=new l.default(this),L=new d.FragmentTracker(this),w=this.streamController=new u.default(this,L);E.setStreamController(w),T.setStreamController(w);var D=[_,S,A,w];this.networkControllers=D;var R=[m,y,E,T,b,L];this.audioTrackController=this.createController(r.audioTrackController,null,D),this.createController(r.audioStreamController,L,D),this.subtitleTrackController=this.createController(r.subtitleTrackController,null,D),this.createController(r.subtitleStreamController,L,D),this.createController(r.timelineController,null,R),this.emeController=this.createController(r.emeController,null,R),this.cmcdController=this.createController(r.cmcdController,null,R),this.latencyController=this.createController(o.default,null,R),this.coreComponents=R}t.isSupported=function(){return(0,c.isSupported)()};var e,r,y,E=t.prototype;return E.createController=function(t,e,r){if(t){var i=e?new t(this,e):new t(this);return r&&r.push(i),i}return null},E.on=function(t,e,r){void 0===r&&(r=this),this._emitter.on(t,e,r)},E.once=function(t,e,r){void 0===r&&(r=this),this._emitter.once(t,e,r)},E.removeAllListeners=function(t){this._emitter.removeAllListeners(t)},E.off=function(t,e,r,i){void 0===r&&(r=this),this._emitter.off(t,e,r,i)},E.listeners=function(t){return this._emitter.listeners(t)},E.emit=function(t,e,r){return this._emitter.emit(t,e,r)},E.trigger=function(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){h.logger.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),this.trigger(g.Events.ERROR,{type:v.ErrorTypes.OTHER_ERROR,details:v.ErrorDetails.INTERNAL_EXCEPTION,fatal:!1,event:t,error:e})}return!1},E.listenerCount=function(t){return this._emitter.listenerCount(t)},E.destroy=function(){h.logger.log("destroy"),this.trigger(g.Events.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((function(t){return t.destroy()})),this.networkControllers.length=0,this.coreComponents.forEach((function(t){return t.destroy()})),this.coreComponents.length=0},E.attachMedia=function(t){h.logger.log("attachMedia"),this._media=t,this.trigger(g.Events.MEDIA_ATTACHING,{media:t})},E.detachMedia=function(){h.logger.log("detachMedia"),this.trigger(g.Events.MEDIA_DETACHING,void 0),this._media=null},E.loadSource=function(t){this.stopLoad();var e=this.media,r=this.url,n=this.url=i.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});h.logger.log("loadSource:"+n),e&&r&&r!==n&&this.bufferController.hasSourceTypes()&&(this.detachMedia(),this.attachMedia(e)),this.trigger(g.Events.MANIFEST_LOADING,{url:t})},E.startLoad=function(t){void 0===t&&(t=-1),h.logger.log("startLoad("+t+")"),this.networkControllers.forEach((function(e){e.startLoad(t)}))},E.stopLoad=function(){h.logger.log("stopLoad"),this.networkControllers.forEach((function(t){t.stopLoad()}))},E.swapAudioCodec=function(){h.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()},E.recoverMediaError=function(){h.logger.log("recoverMediaError");var t=this._media;this.detachMedia(),t&&this.attachMedia(t)},E.removeLevel=function(t,e){void 0===e&&(e=0),this.levelController.removeLevel(t,e)},e=t,y=[{key:"version",get:function(){return"1.2.7"}},{key:"Events",get:function(){return g.Events}},{key:"ErrorTypes",get:function(){return v.ErrorTypes}},{key:"ErrorDetails",get:function(){return v.ErrorDetails}},{key:"DefaultConfig",get:function(){return t.defaultConfig?t.defaultConfig:f.hlsDefaultConfig},set:function(e){t.defaultConfig=e}}],(r=[{key:"levels",get:function(){var t=this.levelController.levels;return t||[]}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(t){h.logger.log("set currentLevel:"+t),this.loadLevel=t,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(t){h.logger.log("set nextLevel:"+t),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(t){h.logger.log("set loadLevel:"+t),this.levelController.manualLevel=t}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(t){this.levelController.nextLoadLevel=t}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(t){h.logger.log("set firstLevel:"+t),this.levelController.firstLevel=t}},{key:"startLevel",get:function(){return this.levelController.startLevel},set:function(t){h.logger.log("set startLevel:"+t),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(t){var e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(t){this._autoLevelCapping!==t&&(h.logger.log("set autoLevelCapping:"+t),this._autoLevelCapping=t)}},{key:"bandwidthEstimate",get:function(){var t=this.abrController.bwEstimator;return t?t.getEstimate():NaN}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var t=this.levels,e=this.config.minAutoBitrate;if(!t)return 0;for(var r=t.length,i=0;i<r;i++)if(t[i].maxBitrate>=e)return i;return 0}},{key:"maxAutoLevel",get:function(){var t=this.levels,e=this.autoLevelCapping;return-1===e&&t&&t.length?t.length-1:e}},{key:"nextAutoLevel",get:function(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},set:function(t){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,t)}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"audioTracks",get:function(){var t=this.audioTrackController;return t?t.audioTracks:[]}},{key:"audioTrack",get:function(){var t=this.audioTrackController;return t?t.audioTrack:-1},set:function(t){var e=this.audioTrackController;e&&(e.audioTrack=t)}},{key:"subtitleTracks",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTrack:-1},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var t=this.subtitleTrackController;return!!t&&t.subtitleDisplay},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(t){this.config.lowLatencyMode=t}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}}])&&m(e.prototype,r),y&&m(e,y),Object.defineProperty(e,"prototype",{writable:!1}),t}();y.defaultConfig=void 0},"./src/is-supported.ts":
|
|
140
|
-
/*!*****************************!*\
|
|
141
|
-
!*** ./src/is-supported.ts ***!
|
|
142
|
-
\*****************************/(t,e,r)=>{r.r(e),r.d(e,{changeTypeSupported:()=>a,isSupported:()=>s});var i=r(/*! ./utils/mediasource-helper */"./src/utils/mediasource-helper.ts");function n(){return self.SourceBuffer||self.WebKitSourceBuffer}function s(){var t=(0,i.getMediaSource)();if(!t)return!1;var e=n(),r=t&&"function"==typeof t.isTypeSupported&&t.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),s=!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove;return!!r&&!!s}function a(){var t,e=n();return"function"==typeof(null==e||null===(t=e.prototype)||void 0===t?void 0:t.changeType)}},"./src/loader/date-range.ts":
|
|
143
|
-
/*!**********************************!*\
|
|
144
|
-
!*** ./src/loader/date-range.ts ***!
|
|
145
|
-
\**********************************/(t,e,r)=>{r.r(e),r.d(e,{DateRange:()=>d,DateRangeAttribute:()=>i});var i,n=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),s=r(/*! ../utils/attr-list */"./src/utils/attr-list.ts"),a=r(/*! ../utils/logger */"./src/utils/logger.ts");function o(){return(o=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t}).apply(this,arguments)}function l(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}!function(t){t.ID="ID",t.CLASS="CLASS",t.START_DATE="START-DATE",t.DURATION="DURATION",t.END_DATE="END-DATE",t.END_ON_NEXT="END-ON-NEXT",t.PLANNED_DURATION="PLANNED-DURATION",t.SCTE35_OUT="SCTE35-OUT",t.SCTE35_IN="SCTE35-IN"}(i||(i={}));var d=function(){function t(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){var r=e.attr;for(var l in r)if(Object.prototype.hasOwnProperty.call(t,l)&&t[l]!==r[l]){a.logger.warn('DATERANGE tag attribute: "'+l+'" does not match for tags with ID: "'+t.ID+'"'),this._badValueForSameId=l;break}t=o(new s.AttrList({}),r,t)}if(this.attr=t,this._startDate=new Date(t[i.START_DATE]),i.END_DATE in this.attr){var d=new Date(this.attr[i.END_DATE]);(0,n.isFiniteNumber)(d.getTime())&&(this._endDate=d)}}var e,r,d;return e=t,(r=[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){if(this._endDate)return this._endDate;var t=this.duration;return null!==t?new Date(this._startDate.getTime()+1e3*t):null}},{key:"duration",get:function(){if(i.DURATION in this.attr){var t=this.attr.decimalFloatingPoint(i.DURATION);if((0,n.isFiniteNumber)(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:"plannedDuration",get:function(){return i.PLANNED_DURATION in this.attr?this.attr.decimalFloatingPoint(i.PLANNED_DURATION):null}},{key:"endOnNext",get:function(){return this.attr.bool(i.END_ON_NEXT)}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&(0,n.isFiniteNumber)(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}])&&l(e.prototype,r),d&&l(e,d),Object.defineProperty(e,"prototype",{writable:!1}),t}()},"./src/loader/fragment-loader.ts":
|
|
146
|
-
/*!***************************************!*\
|
|
147
|
-
!*** ./src/loader/fragment-loader.ts ***!
|
|
148
|
-
\***************************************/(t,e,r)=>{r.r(e),r.d(e,{LoadError:()=>f,default:()=>c});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../errors */"./src/errors.ts");function s(t){var e="function"==typeof Map?new Map:void 0;return(s=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return a(t,arguments,d(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),l(i,t)})(t)}function a(t,e,r){return(a=o()?Reflect.construct.bind():function(t,e,r){var i=[null];i.push.apply(i,e);var n=new(Function.bind.apply(t,i));return r&&l(n,r.prototype),n}).apply(null,arguments)}function o(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function l(t,e){return(l=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}function d(t){return(d=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var u=Math.pow(2,17),c=function(){function t(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}var e=t.prototype;return e.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},e.abort=function(){this.loader&&this.loader.abort()},e.load=function(t,e){var r=this,i=t.url;if(!i)return Promise.reject(new f({type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:t,networkDetails:null},"Fragment does not have a "+(i?"part list":"url")));this.abort();var s=this.config,a=s.fLoader,o=s.loader;return new Promise((function(i,l){r.loader&&r.loader.destroy();var d=r.loader=t.loader=a?new a(s):new o(s),c=h(t),p={timeout:s.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:s.fragLoadingMaxRetryTimeout,highWaterMark:"initSegment"===t.sn?1/0:u};t.stats=d.stats,d.load(c,p,{onSuccess:function(e,n,s,a){r.resetLoader(t,d),i({frag:t,part:null,payload:e.data,networkDetails:a})},onError:function(e,i,s){r.resetLoader(t,d),l(new f({type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:e,networkDetails:s}))},onAbort:function(e,i,s){r.resetLoader(t,d),l(new f({type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:t,networkDetails:s}))},onTimeout:function(e,i,s){r.resetLoader(t,d),l(new f({type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,networkDetails:s}))},onProgress:function(r,i,n,s){e&&e({frag:t,part:null,payload:n,networkDetails:s})}})}))},e.loadPart=function(t,e,r){var i=this;this.abort();var s=this.config,a=s.fLoader,o=s.loader;return new Promise((function(l,d){i.loader&&i.loader.destroy();var c=i.loader=t.loader=a?new a(s):new o(s),p=h(t,e),g={timeout:s.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:s.fragLoadingMaxRetryTimeout,highWaterMark:u};e.stats=c.stats,c.load(p,g,{onSuccess:function(n,s,a,o){i.resetLoader(t,c),i.updateStatsFromPart(t,e);var d={frag:t,part:e,payload:n.data,networkDetails:o};r(d),l(d)},onError:function(r,s,a){i.resetLoader(t,c),d(new f({type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:r,networkDetails:a}))},onAbort:function(r,s,a){t.stats.aborted=e.stats.aborted,i.resetLoader(t,c),d(new f({type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,networkDetails:a}))},onTimeout:function(r,s,a){i.resetLoader(t,c),d(new f({type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,networkDetails:a}))}})}))},e.updateStatsFromPart=function(t,e){var r=t.stats,i=e.stats,n=i.total;if(r.loaded+=i.loaded,n){var s=Math.round(t.duration/e.duration),a=Math.min(Math.round(r.loaded/n),s),o=(s-a)*Math.round(r.loaded/a);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,d=i.loading;l.start?l.first+=d.first-d.start:(l.start=d.start,l.first=d.first),l.end=d.end},e.resetLoader=function(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()},t}();function h(t,e){void 0===e&&(e=null);var r=e||t,n={frag:t,part:e,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},s=r.byteRangeStartOffset,a=r.byteRangeEndOffset;return(0,i.isFiniteNumber)(s)&&(0,i.isFiniteNumber)(a)&&(n.rangeStart=s,n.rangeEnd=a),n}var f=function(t){var e,r;function i(e){for(var r,i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return(r=t.call.apply(t,[this].concat(n))||this).data=void 0,r.data=e,r}return r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,l(e,r),i}(s(Error))},"./src/loader/fragment.ts":
|
|
149
|
-
/*!********************************!*\
|
|
150
|
-
!*** ./src/loader/fragment.ts ***!
|
|
151
|
-
\********************************/(t,e,r)=>{r.r(e),r.d(e,{BaseSegment:()=>f,ElementaryStreamTypes:()=>i,Fragment:()=>p,Part:()=>g});var i,n=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),s=r(/*! url-toolkit */"./node_modules/url-toolkit/src/url-toolkit.js"),a=r(/*! ../utils/logger */"./src/utils/logger.ts"),o=r(/*! ./level-key */"./src/loader/level-key.ts"),l=r(/*! ./load-stats */"./src/loader/load-stats.ts");function d(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,u(t,e)}function u(t,e){return(u=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}function c(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function h(t,e,r){return e&&c(t.prototype,e),r&&c(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}!function(t){t.AUDIO="audio",t.VIDEO="video",t.AUDIOVIDEO="audiovideo"}(i||(i={}));var f=function(){function t(t){var e;this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams=((e={})[i.AUDIO]=null,e[i.VIDEO]=null,e[i.AUDIOVIDEO]=null,e),this.baseurl=t}return t.prototype.setByteRange=function(t,e){var r=t.split("@",2),i=[];1===r.length?i[0]=e?e.byteRangeEndOffset:0:i[0]=parseInt(r[1]),i[1]=parseInt(r[0])+i[0],this._byteRange=i},h(t,[{key:"byteRange",get:function(){return this._byteRange?this._byteRange:[]}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=(0,s.buildAbsoluteURL)(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(t){this._url=t}}]),t}(),p=function(t){function e(e,r){var i;return(i=t.call(this,r)||this)._decryptdata=null,i.rawProgramDateTime=null,i.programDateTime=null,i.tagList=[],i.duration=0,i.sn=0,i.levelkey=void 0,i.type=void 0,i.loader=null,i.level=-1,i.cc=0,i.startPTS=void 0,i.endPTS=void 0,i.appendedPTS=void 0,i.startDTS=void 0,i.endDTS=void 0,i.start=0,i.deltaPTS=void 0,i.maxStartPTS=void 0,i.minEndPTS=void 0,i.stats=new l.LoadStats,i.urlId=0,i.data=void 0,i.bitrateTest=!1,i.title=null,i.initSegment=null,i.type=e,i}d(e,t);var r=e.prototype;return r.createInitializationVector=function(t){for(var e=new Uint8Array(16),r=12;r<16;r++)e[r]=t>>8*(15-r)&255;return e},r.setDecryptDataFromLevelKey=function(t,e){var r=t;return"AES-128"===(null==t?void 0:t.method)&&t.uri&&!t.iv&&((r=o.LevelKey.fromURI(t.uri)).method=t.method,r.iv=this.createInitializationVector(e),r.keyFormat="identity"),r},r.setElementaryStreamInfo=function(t,e,r,i,n,s){void 0===s&&(s=!1);var a=this.elementaryStreams,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,n)):a[t]={startPTS:e,endPTS:r,startDTS:i,endDTS:n,partial:s}},r.clearElementaryStreamInfo=function(){var t=this.elementaryStreams;t[i.AUDIO]=null,t[i.VIDEO]=null,t[i.AUDIOVIDEO]=null},h(e,[{key:"decryptdata",get:function(){if(!this.levelkey&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkey){var t=this.sn;"number"!=typeof t&&(this.levelkey&&"AES-128"===this.levelkey.method&&!this.levelkey.iv&&a.logger.warn('missing IV for initialization segment with method="'+this.levelkey.method+'" - compliance issue'),t=0),this._decryptdata=this.setDecryptDataFromLevelKey(this.levelkey,t)}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!(0,n.isFiniteNumber)(this.programDateTime))return null;var t=(0,n.isFiniteNumber)(this.duration)?this.duration:0;return this.programDateTime+1e3*t}},{key:"encrypted",get:function(){var t;return!(null===(t=this.decryptdata)||void 0===t||!t.keyFormat||!this.decryptdata.uri)}}]),e}(f),g=function(t){function e(e,r,i,n,s){var a;(a=t.call(this,i)||this).fragOffset=0,a.duration=0,a.gap=!1,a.independent=!1,a.relurl=void 0,a.fragment=void 0,a.index=void 0,a.stats=new l.LoadStats,a.duration=e.decimalFloatingPoint("DURATION"),a.gap=e.bool("GAP"),a.independent=e.bool("INDEPENDENT"),a.relurl=e.enumeratedString("URI"),a.fragment=r,a.index=n;var o=e.enumeratedString("BYTERANGE");return o&&a.setByteRange(o,s),s&&(a.fragOffset=s.fragOffset+s.duration),a}return d(e,t),h(e,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var t=this.elementaryStreams;return!!(t.audio||t.video||t.audiovideo)}}]),e}(f)},"./src/loader/key-loader.ts":
|
|
152
|
-
/*!**********************************!*\
|
|
153
|
-
!*** ./src/loader/key-loader.ts ***!
|
|
154
|
-
\**********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>a});var i=r(/*! ../events */"./src/events.ts"),n=r(/*! ../errors */"./src/errors.ts"),s=r(/*! ../utils/logger */"./src/utils/logger.ts"),a=function(){function t(t){this.hls=void 0,this.loaders={},this.decryptkey=null,this.decrypturl=null,this.hls=t,this.registerListeners()}var e=t.prototype;return e.startLoad=function(t){},e.stopLoad=function(){this.destroyInternalLoaders()},e.registerListeners=function(){this.hls.on(i.Events.KEY_LOADING,this.onKeyLoading,this)},e.unregisterListeners=function(){this.hls.off(i.Events.KEY_LOADING,this.onKeyLoading)},e.destroyInternalLoaders=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy()}this.loaders={}},e.destroy=function(){this.unregisterListeners(),this.destroyInternalLoaders()},e.onKeyLoading=function(t,e){var r=e.frag,n=r.type,a=this.loaders[n];if(r.decryptdata){var o=r.decryptdata.uri;if(o!==this.decrypturl||null===this.decryptkey){var l=this.hls.config;if(a&&(s.logger.warn("abort previous key loader for type:"+n),a.abort()),!o)return void s.logger.warn("key uri is falsy");var d=l.loader,u=r.loader=this.loaders[n]=new d(l);this.decrypturl=o,this.decryptkey=null;var c={url:o,frag:r,responseType:"arraybuffer"},h={timeout:l.fragLoadingTimeOut,maxRetry:0,retryDelay:l.fragLoadingRetryDelay,maxRetryDelay:l.fragLoadingMaxRetryTimeout,highWaterMark:0},f={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};u.load(c,h,f)}else this.decryptkey&&(r.decryptdata.key=this.decryptkey,this.hls.trigger(i.Events.KEY_LOADED,{frag:r}))}else s.logger.warn("Missing decryption data on fragment in onKeyLoading")},e.loadsuccess=function(t,e,r){var n=r.frag;n.decryptdata?(this.decryptkey=n.decryptdata.key=new Uint8Array(t.data),n.loader=null,delete this.loaders[n.type],this.hls.trigger(i.Events.KEY_LOADED,{frag:n})):s.logger.error("after key load, decryptdata unset")},e.loaderror=function(t,e){var r=e.frag,s=r.loader;s&&s.abort(),delete this.loaders[r.type],this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.KEY_LOAD_ERROR,fatal:!1,frag:r,response:t})},e.loadtimeout=function(t,e){var r=e.frag,s=r.loader;s&&s.abort(),delete this.loaders[r.type],this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},t}()},"./src/loader/level-details.ts":
|
|
155
|
-
/*!*************************************!*\
|
|
156
|
-
!*** ./src/loader/level-details.ts ***!
|
|
157
|
-
\*************************************/(t,e,r)=>{r.r(e),r.d(e,{LevelDetails:()=>s});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts");function n(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}var s=function(){function t(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.needSidxRanges=!1,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.fragments=[],this.dateRanges={},this.url=t}var e,r,s;return t.prototype.reloaded=function(t){if(!t)return this.advanced=!0,void(this.updated=!0);var e=this.lastPartSn-t.lastPartSn,r=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!r||!!e,this.advanced=this.endSN>t.endSN||e>0||0===e&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay},e=t,(r=[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&(0,i.isFiniteNumber)(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){var t;return null!==(t=this.fragments)&&void 0!==t&&t.length?this.fragments[this.fragments.length-1].end:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].index:-1}},{key:"lastPartSn",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}])&&n(e.prototype,r),s&&n(e,s),Object.defineProperty(e,"prototype",{writable:!1}),t}()},"./src/loader/level-key.ts":
|
|
158
|
-
/*!*********************************!*\
|
|
159
|
-
!*** ./src/loader/level-key.ts ***!
|
|
160
|
-
\*********************************/(t,e,r)=>{r.r(e),r.d(e,{LevelKey:()=>s});var i=r(/*! url-toolkit */"./node_modules/url-toolkit/src/url-toolkit.js");function n(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}var s=function(){function t(t,e){this._uri=null,this.method=null,this.keyFormat=null,this.keyFormatVersions=null,this.keyID=null,this.key=null,this.iv=null,this._uri=e?(0,i.buildAbsoluteURL)(t,e,{alwaysNormalize:!0}):t}var e,r,s;return t.fromURL=function(e,r){return new t(e,r)},t.fromURI=function(e){return new t(e)},e=t,(r=[{key:"uri",get:function(){return this._uri}}])&&n(e.prototype,r),s&&n(e,s),Object.defineProperty(e,"prototype",{writable:!1}),t}()},"./src/loader/load-stats.ts":
|
|
161
|
-
/*!**********************************!*\
|
|
162
|
-
!*** ./src/loader/load-stats.ts ***!
|
|
163
|
-
\**********************************/(t,e,r)=>{r.r(e),r.d(e,{LoadStats:()=>i});var i=function(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}},"./src/loader/m3u8-parser.ts":
|
|
164
|
-
/*!***********************************!*\
|
|
165
|
-
!*** ./src/loader/m3u8-parser.ts ***!
|
|
166
|
-
\***********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>m});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! url-toolkit */"./node_modules/url-toolkit/src/url-toolkit.js"),s=r(/*! ./date-range */"./src/loader/date-range.ts"),a=r(/*! ./fragment */"./src/loader/fragment.ts"),o=r(/*! ./level-details */"./src/loader/level-details.ts"),l=r(/*! ./level-key */"./src/loader/level-key.ts"),d=r(/*! ../utils/attr-list */"./src/utils/attr-list.ts"),u=r(/*! ../utils/logger */"./src/utils/logger.ts"),c=r(/*! ../utils/codecs */"./src/utils/codecs.ts"),h=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g,f=/#EXT-X-MEDIA:(.*)/g,p=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),g=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),v=/\.(mp4|m4s|m4v|m4a)$/i,m=function(){function t(){}return t.findGroup=function(t,e){for(var r=0;r<t.length;r++){var i=t[r];if(i.id===e)return i}},t.convertAVC1ToAVCOTI=function(t){var e=t.split(".");if(e.length>2){var r=e.shift()+".";return r+=parseInt(e.shift()).toString(16),r+=("000"+parseInt(e.shift()).toString(16)).slice(-4)}return t},t.resolve=function(t,e){return n.buildAbsoluteURL(e,t,{alwaysNormalize:!0})},t.parseMasterPlaylist=function(e,r){var i,n=[],s=[],a={},o=!1;for(h.lastIndex=0;null!=(i=h.exec(e));)if(i[1]){var l,u=new d.AttrList(i[1]),c={attrs:u,bitrate:u.decimalInteger("AVERAGE-BANDWIDTH")||u.decimalInteger("BANDWIDTH"),name:u.NAME,url:t.resolve(i[2],r)},f=u.decimalResolution("RESOLUTION");f&&(c.width=f.width,c.height=f.height),y((u.CODECS||"").split(/[ ,]+/).filter((function(t){return t})),c),c.videoCodec&&-1!==c.videoCodec.indexOf("avc1")&&(c.videoCodec=t.convertAVC1ToAVCOTI(c.videoCodec)),null!==(l=c.unknownCodecs)&&void 0!==l&&l.length||s.push(c),n.push(c)}else if(i[3]){var p=new d.AttrList(i[3]);p["DATA-ID"]&&(o=!0,a[p["DATA-ID"]]=p)}return{levels:s.length>0&&s.length<n.length?s:n,sessionData:o?a:null}},t.parseMasterPlaylistMedia=function(e,r,i,n){var s;void 0===n&&(n=[]);var a=[],o=0;for(f.lastIndex=0;null!==(s=f.exec(e));){var l=new d.AttrList(s[1]);if(l.TYPE===i){var u={attrs:l,bitrate:0,id:o++,groupId:l["GROUP-ID"],instreamId:l["INSTREAM-ID"],name:l.NAME||l.LANGUAGE||"",type:i,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:l.LANGUAGE,url:l.URI?t.resolve(l.URI,r):""};if(n.length){var c=t.findGroup(n,u.groupId)||n[0];E(u,c,"audioCodec"),E(u,c,"textCodec")}a.push(u)}}return a},t.parseLevelPlaylist=function(t,e,r,c,h){var f,m,y,E=new o.LevelDetails(e),S=E.fragments,b=null,A=0,L=0,w=0,D=0,R=null,I=new a.Fragment(c,e),k=-1,O=!1;for(p.lastIndex=0,E.m3u8=t;null!==(f=p.exec(t));){O&&(O=!1,(I=new a.Fragment(c,e)).start=w,I.sn=A,I.cc=D,I.level=r,b&&(I.initSegment=b,I.rawProgramDateTime=b.rawProgramDateTime,b.rawProgramDateTime=null));var C=f[1];if(C){I.duration=parseFloat(C);var P=(" "+f[2]).slice(1);I.title=P||null,I.tagList.push(P?["INF",C,P]:["INF",C])}else if(f[3])(0,i.isFiniteNumber)(I.duration)&&(I.start=w,y&&(I.levelkey=y),I.sn=A,I.level=r,I.cc=D,I.urlId=h,S.push(I),I.relurl=(" "+f[3]).slice(1),T(I,R),R=I,w+=I.duration,A++,L=0,O=!0);else if(f[4]){var x=(" "+f[4]).slice(1);R?I.setByteRange(x,R):I.setByteRange(x)}else if(f[5])I.rawProgramDateTime=(" "+f[5]).slice(1),I.tagList.push(["PROGRAM-DATE-TIME",I.rawProgramDateTime]),-1===k&&(k=S.length);else{if(!(f=f[0].match(g))){u.logger.warn("No matches on slow regex match for level playlist!");continue}for(m=1;m<f.length&&void 0===f[m];m++);var M=(" "+f[m]).slice(1),N=(" "+f[m+1]).slice(1),F=f[m+2]?(" "+f[m+2]).slice(1):"";switch(M){case"PLAYLIST-TYPE":E.type=N.toUpperCase();break;case"MEDIA-SEQUENCE":A=E.startSN=parseInt(N);break;case"SKIP":var U=new d.AttrList(N),B=U.decimalInteger("SKIPPED-SEGMENTS");if((0,i.isFiniteNumber)(B)){E.skippedSegments=B;for(var G=B;G--;)S.unshift(null);A+=B}var H=U.enumeratedString("RECENTLY-REMOVED-DATERANGES");H&&(E.recentlyRemovedDateranges=H.split("\t"));break;case"TARGETDURATION":E.targetduration=parseFloat(N);break;case"VERSION":E.version=parseInt(N);break;case"EXTM3U":break;case"ENDLIST":E.live=!1;break;case"#":(N||F)&&I.tagList.push(F?[N,F]:[N]);break;case"DISCONTINUITY":D++,I.tagList.push(["DIS"]);break;case"GAP":I.tagList.push([M]);break;case"BITRATE":I.tagList.push([M,N]);break;case"DATERANGE":var j=new d.AttrList(N),V=new s.DateRange(j,E.dateRanges[j.ID]);V.isValid||E.skippedSegments?E.dateRanges[V.id]=V:u.logger.warn('Ignoring invalid DATERANGE tag: "'+N+'"'),I.tagList.push(["EXT-X-DATERANGE",N]);break;case"DISCONTINUITY-SEQUENCE":D=parseInt(N);break;case"KEY":var K,q=new d.AttrList(N),W=q.enumeratedString("METHOD"),z=q.URI,Y=q.hexadecimalInteger("IV"),X=q.enumeratedString("KEYFORMATVERSIONS"),Q=q.enumeratedString("KEYID"),$=null!=(K=q.enumeratedString("KEYFORMAT"))?K:"identity";if(["com.apple.streamingkeydelivery","com.microsoft.playready","urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed","com.widevine"].indexOf($)>-1){u.logger.warn("Keyformat "+$+" is not supported from the manifest");continue}if("identity"!==$)continue;W&&(y=l.LevelKey.fromURL(e,z),z&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(W)>=0&&(y.method=W,y.keyFormat=$,Q&&(y.keyID=Q),X&&(y.keyFormatVersions=X),y.iv=Y));break;case"START":var Z=new d.AttrList(N).decimalFloatingPoint("TIME-OFFSET");(0,i.isFiniteNumber)(Z)&&(E.startTimeOffset=Z);break;case"MAP":var J=new d.AttrList(N);if(I.duration){var tt=new a.Fragment(c,e);_(tt,J,r,y),b=tt,I.initSegment=b,b.rawProgramDateTime&&!I.rawProgramDateTime&&(I.rawProgramDateTime=b.rawProgramDateTime)}else _(I,J,r,y),b=I,O=!0;break;case"SERVER-CONTROL":var et=new d.AttrList(N);E.canBlockReload=et.bool("CAN-BLOCK-RELOAD"),E.canSkipUntil=et.optionalFloat("CAN-SKIP-UNTIL",0),E.canSkipDateRanges=E.canSkipUntil>0&&et.bool("CAN-SKIP-DATERANGES"),E.partHoldBack=et.optionalFloat("PART-HOLD-BACK",0),E.holdBack=et.optionalFloat("HOLD-BACK",0);break;case"PART-INF":var rt=new d.AttrList(N);E.partTarget=rt.decimalFloatingPoint("PART-TARGET");break;case"PART":var it=E.partList;it||(it=E.partList=[]);var nt=L>0?it[it.length-1]:void 0,st=L++,at=new a.Part(new d.AttrList(N),I,e,st,nt);it.push(at),I.duration+=at.duration;break;case"PRELOAD-HINT":var ot=new d.AttrList(N);E.preloadHint=ot;break;case"RENDITION-REPORT":var lt=new d.AttrList(N);E.renditionReports=E.renditionReports||[],E.renditionReports.push(lt);break;default:u.logger.warn("line parsed but not handled: "+f)}}}R&&!R.relurl?(S.pop(),w-=R.duration,E.partList&&(E.fragmentHint=R)):E.partList&&(T(I,R),I.cc=D,E.fragmentHint=I);var dt=S.length,ut=S[0],ct=S[dt-1];if((w+=E.skippedSegments*E.targetduration)>0&&dt&&ct){E.averagetargetduration=w/dt;var ht=ct.sn;E.endSN="initSegment"!==ht?ht:0,ut&&(E.startCC=ut.cc,ut.initSegment||E.fragments.every((function(t){return t.relurl&&function(t){var e,r;return v.test(null!=(e=null===(r=n.parseURL(t))||void 0===r?void 0:r.path)?e:"")}(t.relurl)}))&&(u.logger.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),(I=new a.Fragment(c,e)).relurl=ct.relurl,I.level=r,I.sn="initSegment",ut.initSegment=I,E.needSidxRanges=!0))}else E.endSN=0,E.startCC=0;return E.fragmentHint&&(w+=E.fragmentHint.duration),E.totalduration=w,E.endCC=D,k>0&&function(t,e){for(var r=t[e],i=e;i--;){var n=t[i];if(!n)return;n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(S,k),E},t}();function y(t,e){["video","audio","text"].forEach((function(r){var i=t.filter((function(t){return(0,c.isCodecType)(t,r)}));if(i.length){var n=i.filter((function(t){return 0===t.lastIndexOf("avc1",0)||0===t.lastIndexOf("mp4a",0)}));e[r+"Codec"]=n.length>0?n[0]:i[0],t=t.filter((function(t){return-1===i.indexOf(t)}))}})),e.unknownCodecs=t}function E(t,e,r){var i=e[r];i&&(t[r]=i)}function T(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),(0,i.isFiniteNumber)(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function _(t,e,r,i){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=r,t.sn="initSegment",i&&(t.levelkey=i),t.initSegment=null}},"./src/loader/playlist-loader.ts":
|
|
167
|
-
/*!***************************************!*\
|
|
168
|
-
!*** ./src/loader/playlist-loader.ts ***!
|
|
169
|
-
\***************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>h});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../events */"./src/events.ts"),s=r(/*! ../errors */"./src/errors.ts"),a=r(/*! ../utils/logger */"./src/utils/logger.ts"),o=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts"),l=r(/*! ./m3u8-parser */"./src/loader/m3u8-parser.ts"),d=r(/*! ../types/loader */"./src/types/loader.ts"),u=r(/*! ../utils/attr-list */"./src/utils/attr-list.ts");function c(t,e){var r=t.url;return void 0!==r&&0!==r.indexOf("data:")||(r=e.url),r}const h=function(){function t(t){this.hls=void 0,this.loaders=Object.create(null),this.hls=t,this.registerListeners()}var e=t.prototype;return e.startLoad=function(t){},e.stopLoad=function(){this.destroyInternalLoaders()},e.registerListeners=function(){var t=this.hls;t.on(n.Events.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.Events.LEVEL_LOADING,this.onLevelLoading,this),t.on(n.Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(n.Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.unregisterListeners=function(){var t=this.hls;t.off(n.Events.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.Events.LEVEL_LOADING,this.onLevelLoading,this),t.off(n.Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(n.Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.createInternalLoader=function(t){var e=this.hls.config,r=e.pLoader,i=e.loader,n=new(r||i)(e);return t.loader=n,this.loaders[t.type]=n,n},e.getInternalLoader=function(t){return this.loaders[t.type]},e.resetInternalLoader=function(t){this.loaders[t]&&delete this.loaders[t]},e.destroyInternalLoaders=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}},e.destroy=function(){this.unregisterListeners(),this.destroyInternalLoaders()},e.onManifestLoading=function(t,e){var r=e.url;this.load({id:null,groupId:null,level:0,responseType:"text",type:d.PlaylistContextType.MANIFEST,url:r,deliveryDirectives:null})},e.onLevelLoading=function(t,e){var r=e.id,i=e.level,n=e.url,s=e.deliveryDirectives;this.load({id:r,groupId:null,level:i,responseType:"text",type:d.PlaylistContextType.LEVEL,url:n,deliveryDirectives:s})},e.onAudioTrackLoading=function(t,e){var r=e.id,i=e.groupId,n=e.url,s=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:d.PlaylistContextType.AUDIO_TRACK,url:n,deliveryDirectives:s})},e.onSubtitleTrackLoading=function(t,e){var r=e.id,i=e.groupId,n=e.url,s=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:d.PlaylistContextType.SUBTITLE_TRACK,url:n,deliveryDirectives:s})},e.load=function(t){var e,r,i,n,s,o,l=this.hls.config,u=this.getInternalLoader(t);if(u){var c=u.context;if(c&&c.url===t.url)return void a.logger.trace("[playlist-loader]: playlist request ongoing");a.logger.log("[playlist-loader]: aborting previous loader for type: "+t.type),u.abort()}switch(t.type){case d.PlaylistContextType.MANIFEST:r=l.manifestLoadingMaxRetry,i=l.manifestLoadingTimeOut,n=l.manifestLoadingRetryDelay,s=l.manifestLoadingMaxRetryTimeout;break;case d.PlaylistContextType.LEVEL:case d.PlaylistContextType.AUDIO_TRACK:case d.PlaylistContextType.SUBTITLE_TRACK:r=0,i=l.levelLoadingTimeOut;break;default:r=l.levelLoadingMaxRetry,i=l.levelLoadingTimeOut,n=l.levelLoadingRetryDelay,s=l.levelLoadingMaxRetryTimeout}if(u=this.createInternalLoader(t),null!==(e=t.deliveryDirectives)&&void 0!==e&&e.part&&(t.type===d.PlaylistContextType.LEVEL&&null!==t.level?o=this.hls.levels[t.level].details:t.type===d.PlaylistContextType.AUDIO_TRACK&&null!==t.id?o=this.hls.audioTracks[t.id].details:t.type===d.PlaylistContextType.SUBTITLE_TRACK&&null!==t.id&&(o=this.hls.subtitleTracks[t.id].details),o)){var h=o.partTarget,f=o.targetduration;h&&f&&(i=Math.min(1e3*Math.max(3*h,.8*f),i))}var p={timeout:i,maxRetry:r,retryDelay:n,maxRetryDelay:s,highWaterMark:0},g={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};u.load(t,p,g)},e.loadsuccess=function(t,e,r,i){if(void 0===i&&(i=null),r.isSidxRequest)return this.handleSidxRequest(t,r),void this.handlePlaylistLoaded(t,e,r,i);this.resetInternalLoader(r.type);var n=t.data;0===n.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),n.indexOf("#EXTINF:")>0||n.indexOf("#EXT-X-TARGETDURATION:")>0?this.handleTrackOrLevelPlaylist(t,e,r,i):this.handleMasterPlaylist(t,e,r,i)):this.handleManifestParsingError(t,r,"no EXTM3U delimiter",i)},e.loaderror=function(t,e,r){void 0===r&&(r=null),this.handleNetworkError(e,r,!1,t)},e.loadtimeout=function(t,e,r){void 0===r&&(r=null),this.handleNetworkError(e,r,!0)},e.handleMasterPlaylist=function(t,e,r,i){var s=this.hls,o=t.data,d=c(t,r),h=l.default.parseMasterPlaylist(o,d),f=h.levels,p=h.sessionData;if(f.length){var g=f.map((function(t){return{id:t.attrs.AUDIO,audioCodec:t.audioCodec}})),v=f.map((function(t){return{id:t.attrs.SUBTITLES,textCodec:t.textCodec}})),m=l.default.parseMasterPlaylistMedia(o,d,"AUDIO",g),y=l.default.parseMasterPlaylistMedia(o,d,"SUBTITLES",v),E=l.default.parseMasterPlaylistMedia(o,d,"CLOSED-CAPTIONS");m.length&&(m.some((function(t){return!t.url}))||!f[0].audioCodec||f[0].attrs.AUDIO||(a.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new u.AttrList({}),bitrate:0,url:""}))),s.trigger(n.Events.MANIFEST_LOADED,{levels:f,audioTracks:m,subtitles:y,captions:E,url:d,stats:e,networkDetails:i,sessionData:p})}else this.handleManifestParsingError(t,r,"no level found in manifest",i)},e.handleTrackOrLevelPlaylist=function(t,e,r,a){var o=this.hls,h=r.id,f=r.level,p=r.type,g=c(t,r),v=(0,i.isFiniteNumber)(h)?h:0,m=(0,i.isFiniteNumber)(f)?f:v,y=function(t){switch(t.type){case d.PlaylistContextType.AUDIO_TRACK:return d.PlaylistLevelType.AUDIO;case d.PlaylistContextType.SUBTITLE_TRACK:return d.PlaylistLevelType.SUBTITLE;default:return d.PlaylistLevelType.MAIN}}(r),E=l.default.parseLevelPlaylist(t.data,g,m,y,v);if(E.fragments.length){if(p===d.PlaylistContextType.MANIFEST){var T={attrs:new u.AttrList({}),bitrate:0,details:E,name:"",url:g};o.trigger(n.Events.MANIFEST_LOADED,{levels:[T],audioTracks:[],url:g,stats:e,networkDetails:a,sessionData:null})}if(e.parsing.end=performance.now(),E.needSidxRanges){var _,S=null===(_=E.fragments[0].initSegment)||void 0===_?void 0:_.url;this.load({url:S,isSidxRequest:!0,type:p,level:f,levelDetails:E,id:h,groupId:null,rangeStart:0,rangeEnd:2048,responseType:"arraybuffer",deliveryDirectives:null})}else r.levelDetails=E,this.handlePlaylistLoaded(t,e,r,a)}else o.trigger(n.Events.ERROR,{type:s.ErrorTypes.NETWORK_ERROR,details:s.ErrorDetails.LEVEL_EMPTY_ERROR,fatal:!1,url:g,reason:"no fragments found in level",level:"number"==typeof r.level?r.level:void 0})},e.handleSidxRequest=function(t,e){var r=new Uint8Array(t.data),i=(0,o.findBox)(r,["sidx"])[0];if(i){var n=(0,o.parseSegmentIndex)(i);if(n){var s=n.references,a=e.levelDetails;s.forEach((function(t,e){var i=t.info,n=a.fragments[e];if(0===n.byteRange.length&&n.setByteRange(String(1+i.end-i.start)+"@"+String(i.start)),n.initSegment){var s=(0,o.findBox)(r,["moov"])[0],l=s?s.length:null;n.initSegment.setByteRange(String(l)+"@0")}}))}}},e.handleManifestParsingError=function(t,e,r,i){this.hls.trigger(n.Events.ERROR,{type:s.ErrorTypes.NETWORK_ERROR,details:s.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:e.type===d.PlaylistContextType.MANIFEST,url:t.url,reason:r,response:t,context:e,networkDetails:i})},e.handleNetworkError=function(t,e,r,i){void 0===r&&(r=!1),a.logger.warn("[playlist-loader]: A network "+(r?"timeout":"error")+" occurred while loading "+t.type+" level: "+t.level+" id: "+t.id+' group-id: "'+t.groupId+'"');var o=s.ErrorDetails.UNKNOWN,l=!1,u=this.getInternalLoader(t);switch(t.type){case d.PlaylistContextType.MANIFEST:o=r?s.ErrorDetails.MANIFEST_LOAD_TIMEOUT:s.ErrorDetails.MANIFEST_LOAD_ERROR,l=!0;break;case d.PlaylistContextType.LEVEL:o=r?s.ErrorDetails.LEVEL_LOAD_TIMEOUT:s.ErrorDetails.LEVEL_LOAD_ERROR,l=!1;break;case d.PlaylistContextType.AUDIO_TRACK:o=r?s.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:s.ErrorDetails.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case d.PlaylistContextType.SUBTITLE_TRACK:o=r?s.ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:s.ErrorDetails.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(t.type);var c={type:s.ErrorTypes.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:u,context:t,networkDetails:e};i&&(c.response=i),this.hls.trigger(n.Events.ERROR,c)},e.handlePlaylistLoaded=function(t,e,r,i){var s=r.type,a=r.level,o=r.id,l=r.groupId,u=r.loader,c=r.levelDetails,h=r.deliveryDirectives;if(null!=c&&c.targetduration){if(u)switch(c.live&&(u.getCacheAge&&(c.ageHeader=u.getCacheAge()||0),u.getCacheAge&&!isNaN(c.ageHeader)||(c.ageHeader=0)),s){case d.PlaylistContextType.MANIFEST:case d.PlaylistContextType.LEVEL:this.hls.trigger(n.Events.LEVEL_LOADED,{details:c,level:a||0,id:o||0,stats:e,networkDetails:i,deliveryDirectives:h});break;case d.PlaylistContextType.AUDIO_TRACK:this.hls.trigger(n.Events.AUDIO_TRACK_LOADED,{details:c,id:o||0,groupId:l||"",stats:e,networkDetails:i,deliveryDirectives:h});break;case d.PlaylistContextType.SUBTITLE_TRACK:this.hls.trigger(n.Events.SUBTITLE_TRACK_LOADED,{details:c,id:o||0,groupId:l||"",stats:e,networkDetails:i,deliveryDirectives:h})}}else this.handleManifestParsingError(t,r,"invalid target duration",i)},t}()},"./src/polyfills/number.ts":
|
|
170
|
-
/*!*********************************!*\
|
|
171
|
-
!*** ./src/polyfills/number.ts ***!
|
|
172
|
-
\*********************************/(t,e,r)=>{r.r(e),r.d(e,{MAX_SAFE_INTEGER:()=>n,isFiniteNumber:()=>i});var i=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},n=Number.MAX_SAFE_INTEGER||9007199254740991},"./src/remux/aac-helper.ts":
|
|
173
|
-
/*!*********************************!*\
|
|
174
|
-
!*** ./src/remux/aac-helper.ts ***!
|
|
175
|
-
\*********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>i});const i=function(){function t(){}return t.getSilentFrame=function(t,e){switch(t){case"mp4a.40.2":if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)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===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(1===e)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===e)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===e)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])}},t}()},"./src/remux/mp4-generator.ts":
|
|
176
|
-
/*!************************************!*\
|
|
177
|
-
!*** ./src/remux/mp4-generator.ts ***!
|
|
178
|
-
\************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>s});var i=Math.pow(2,32)-1,n=function(){function t(){}return t.init=function(){var e;for(e in t.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},t.types)t.types.hasOwnProperty(e)&&(t.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);var r=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]);t.HDLR_TYPES={video:r,audio:i};var n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);t.STTS=t.STSC=t.STCO=s,t.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),t.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),t.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),t.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);t.FTYP=t.box(t.types.ftyp,a,l,a,o),t.DINF=t.box(t.types.dinf,t.box(t.types.dref,n))},t.box=function(t){for(var e=8,r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];for(var s=i.length,a=s;s--;)e+=i[s].byteLength;var o=new Uint8Array(e);for(o[0]=e>>24&255,o[1]=e>>16&255,o[2]=e>>8&255,o[3]=255&e,o.set(t,4),s=0,e=8;s<a;s++)o.set(i[s],e),e+=i[s].byteLength;return o},t.hdlr=function(e){return t.box(t.types.hdlr,t.HDLR_TYPES[e])},t.mdat=function(e){return t.box(t.types.mdat,e)},t.mdhd=function(e,r){r*=e;var n=Math.floor(r/(i+1)),s=Math.floor(r%(i+1));return t.box(t.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,n>>24,n>>16&255,n>>8&255,255&n,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))},t.mdia=function(e){return t.box(t.types.mdia,t.mdhd(e.timescale,e.duration),t.hdlr(e.type),t.minf(e))},t.mfhd=function(e){return t.box(t.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))},t.minf=function(e){return"audio"===e.type?t.box(t.types.minf,t.box(t.types.smhd,t.SMHD),t.DINF,t.stbl(e)):t.box(t.types.minf,t.box(t.types.vmhd,t.VMHD),t.DINF,t.stbl(e))},t.moof=function(e,r,i){return t.box(t.types.moof,t.mfhd(e),t.traf(i,r))},t.moov=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trak(e[r]);return t.box.apply(null,[t.types.moov,t.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(t.mvex(e)))},t.mvex=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trex(e[r]);return t.box.apply(null,[t.types.mvex].concat(i))},t.mvhd=function(e,r){r*=e;var n=Math.floor(r/(i+1)),s=Math.floor(r%(i+1)),a=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,n>>24,n>>16&255,n>>8&255,255&n,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 t.box(t.types.mvhd,a)},t.sdtp=function(e){var r,i,n=e.samples||[],s=new Uint8Array(4+n.length);for(r=0;r<n.length;r++)i=n[r].flags,s[r+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return t.box(t.types.sdtp,s)},t.stbl=function(e){return t.box(t.types.stbl,t.stsd(e),t.box(t.types.stts,t.STTS),t.box(t.types.stsc,t.STSC),t.box(t.types.stsz,t.STSZ),t.box(t.types.stco,t.STCO))},t.avc1=function(e){var r,i,n,s=[],a=[];for(r=0;r<e.sps.length;r++)n=(i=e.sps[r]).byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));for(r=0;r<e.pps.length;r++)n=(i=e.pps[r]).byteLength,a.push(n>>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));var o=t.box(t.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(a))),l=e.width,d=e.height,u=e.pixelRatio[0],c=e.pixelRatio[1];return t.box(t.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,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]),o,t.box(t.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),t.box(t.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,c>>24,c>>16&255,c>>8&255,255&c])))},t.esds=function(t){var e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))},t.mp4a=function(e){var r=e.samplerate;return t.box(t.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),t.box(t.types.esds,t.esds(e)))},t.mp3=function(e){var r=e.samplerate;return t.box(t.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))},t.stsd=function(e){return"audio"===e.type?"mp3"===e.segmentCodec&&"mp3"===e.codec?t.box(t.types.stsd,t.STSD,t.mp3(e)):t.box(t.types.stsd,t.STSD,t.mp4a(e)):t.box(t.types.stsd,t.STSD,t.avc1(e))},t.tkhd=function(e){var r=e.id,n=e.duration*e.timescale,s=e.width,a=e.height,o=Math.floor(n/(i+1)),l=Math.floor(n%(i+1));return t.box(t.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,o>>24,o>>16&255,o>>8&255,255&o,l>>24,l>>16&255,l>>8&255,255&l,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,a>>8&255,255&a,0,0]))},t.traf=function(e,r){var n=t.sdtp(e),s=e.id,a=Math.floor(r/(i+1)),o=Math.floor(r%(i+1));return t.box(t.types.traf,t.box(t.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),t.box(t.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o])),t.trun(e,n.length+16+20+8+16+8+8),n)},t.trak=function(e){return e.duration=e.duration||4294967295,t.box(t.types.trak,t.tkhd(e),t.mdia(e))},t.trex=function(e){var r=e.id;return t.box(t.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},t.trun=function(e,r){var i,n,s,a,o,l,d=e.samples||[],u=d.length,c=12+16*u,h=new Uint8Array(c);for(r+=8+c,h.set(["video"===e.type?1:0,0,15,1,u>>>24&255,u>>>16&255,u>>>8&255,255&u,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i<u;i++)s=(n=d[i]).duration,a=n.size,o=n.flags,l=n.cts,h.set([s>>>24&255,s>>>16&255,s>>>8&255,255&s,a>>>24&255,a>>>16&255,a>>>8&255,255&a,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return t.box(t.types.trun,h)},t.initSegment=function(e){t.types||t.init();var r=t.moov(e),i=new Uint8Array(t.FTYP.byteLength+r.byteLength);return i.set(t.FTYP),i.set(r,t.FTYP.byteLength),i},t}();n.types=void 0,n.HDLR_TYPES=void 0,n.STTS=void 0,n.STSC=void 0,n.STCO=void 0,n.STSZ=void 0,n.VMHD=void 0,n.SMHD=void 0,n.STSD=void 0,n.FTYP=void 0,n.DINF=void 0;const s=n},"./src/remux/mp4-remuxer.ts":
|
|
179
|
-
/*!**********************************!*\
|
|
180
|
-
!*** ./src/remux/mp4-remuxer.ts ***!
|
|
181
|
-
\**********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>p,flushTextTrackMetadataCueSamples:()=>v,flushTextTrackUserdataCueSamples:()=>m,normalizePts:()=>g});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ./aac-helper */"./src/remux/aac-helper.ts"),s=r(/*! ./mp4-generator */"./src/remux/mp4-generator.ts"),a=r(/*! ../events */"./src/events.ts"),o=r(/*! ../errors */"./src/errors.ts"),l=r(/*! ../utils/logger */"./src/utils/logger.ts"),d=r(/*! ../types/loader */"./src/types/loader.ts"),u=r(/*! ../utils/timescale-conversion */"./src/utils/timescale-conversion.ts");function c(){return(c=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t}).apply(this,arguments)}var h=null,f=null,p=function(){function t(t,e,r,i){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=void 0,this._initDTS=void 0,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=t,this.config=e,this.typeSupported=r,this.ISGenerated=!1,null===h){var n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);h=n?parseInt(n[1]):0}if(null===f){var s=navigator.userAgent.match(/Safari\/(\d+)/i);f=s?parseInt(s[1]):0}}var e=t.prototype;return e.destroy=function(){},e.resetTimeStamp=function(t){l.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t},e.resetNextTimestamp=function(){l.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},e.resetInitSegment=function(){l.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1},e.getVideoStartPts=function(t){var e=!1,r=t.reduce((function(t,r){var i=r.pts-t;return i<-4294967296?(e=!0,g(t,r.pts)):i>0?t:r.pts}),t[0].pts);return e&&l.logger.debug("PTS rollover detected"),r},e.remux=function(t,e,r,i,n,s,a,o){var u,c,h,f,p,y,E=n,T=n,_=t.pid>-1,S=e.pid>-1,b=e.samples.length,A=t.samples.length>0,L=a&&b>0||b>1;if((!_||A)&&(!S||L)||this.ISGenerated||a){this.ISGenerated||(h=this.generateIS(t,e,n));var w,D=this.isVideoContiguous,R=-1;if(L&&(R=function(t){for(var e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!D&&this.config.forceKeyFrameOnDiscontinuity))if(y=!0,R>0){l.logger.warn("[mp4-remuxer]: Dropped "+R+" out of "+b+" video samples due to a missing keyframe");var I=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(R),e.dropped+=R,w=T+=(e.samples[0].pts-I)/e.inputTimeScale}else-1===R&&(l.logger.warn("[mp4-remuxer]: No keyframe found out of "+b+" video samples"),y=!1);if(this.ISGenerated){if(A&&L){var k=this.getVideoStartPts(e.samples),O=(g(t.samples[0].pts,k)-k)/e.inputTimeScale;E+=Math.max(0,O),T+=Math.max(0,-O)}if(A){if(t.samplerate||(l.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),h=this.generateIS(t,e,n)),c=this.remuxAudio(t,E,this.isAudioContiguous,s,S||L||o===d.PlaylistLevelType.AUDIO?T:void 0),L){var C=c?c.endPTS-c.startPTS:0;e.inputTimeScale||(l.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),h=this.generateIS(t,e,n)),u=this.remuxVideo(e,T,D,C)}}else L&&(u=this.remuxVideo(e,T,D,0));u&&(u.firstKeyFrame=R,u.independent=-1!==R,u.firstKeyFramePTS=w)}}return this.ISGenerated&&(r.samples.length&&(p=v(r,n,this._initPTS,this._initDTS)),i.samples.length&&(f=m(i,n,this._initPTS))),{audio:c,video:u,initSegment:h,independent:y,text:f,id3:p}},e.generateIS=function(t,e,r){var n,a,o,l=t.samples,d=e.samples,u=this.typeSupported,c={},h=!(0,i.isFiniteNumber)(this._initPTS),f="audio/mp4";if(h&&(n=a=1/0),t.config&&l.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":u.mpeg?(f="audio/mpeg",t.codec=""):u.mp3&&(t.codec="mp3")}c.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&u.mpeg?new Uint8Array(0):s.default.initSegment([t]),metadata:{channelCount:t.channelCount}},h&&(o=t.inputTimeScale,n=a=l[0].pts-Math.round(o*r))}if(e.sps&&e.pps&&d.length&&(e.timescale=e.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:s.default.initSegment([e]),metadata:{width:e.width,height:e.height}},h)){o=e.inputTimeScale;var p=this.getVideoStartPts(d),v=Math.round(o*r);a=Math.min(a,g(d[0].dts,p)-v),n=Math.min(n,p-v)}if(Object.keys(c).length)return this.ISGenerated=!0,h&&(this._initPTS=n,this._initDTS=a),{tracks:c,initPTS:n,timescale:o}},e.remuxVideo=function(t,e,r,i){var n,d,p=t.inputTimeScale,v=t.samples,m=[],E=v.length,T=this._initPTS,_=this.nextAvcDts,S=8,b=this.videoSampleDuration,A=Number.POSITIVE_INFINITY,L=Number.NEGATIVE_INFINITY,w=!1;r&&null!==_||(_=e*p-(v[0].pts-g(v[0].dts,v[0].pts)));for(var D=0;D<E;D++){var R=v[D];R.pts=g(R.pts-T,_),R.dts=g(R.dts-T,_),R.dts<v[D>0?D-1:D].dts&&(w=!0)}w&&v.sort((function(t,e){var r=t.dts-e.dts,i=t.pts-e.pts;return r||i})),n=v[0].dts;var I=(d=v[v.length-1].dts)-n,k=I?Math.round(I/(E-1)):b||t.inputTimeScale/30;if(r){var O=n-_,C=O>k,P=O<-1;if((C||P)&&(C?l.logger.warn("AVC: "+(0,u.toMsFromMpegTsClock)(O,!0)+" ms ("+O+"dts) hole between fragments detected, filling it"):l.logger.warn("AVC: "+(0,u.toMsFromMpegTsClock)(-O,!0)+" ms ("+O+"dts) overlapping between fragments detected"),!P||_>v[0].pts)){n=_;var x=v[0].pts-O;v[0].dts=n,v[0].pts=x,l.logger.log("Video: First PTS/DTS adjusted: "+(0,u.toMsFromMpegTsClock)(x,!0)+"/"+(0,u.toMsFromMpegTsClock)(n,!0)+", delta: "+(0,u.toMsFromMpegTsClock)(O,!0)+" ms")}}n=Math.max(0,n);for(var M=0,N=0,F=0;F<E;F++){for(var U=v[F],B=U.units,G=B.length,H=0,j=0;j<G;j++)H+=B[j].data.length;N+=H,M+=G,U.length=H,U.dts=Math.max(U.dts,n),A=Math.min(U.pts,A),L=Math.max(U.pts,L)}d=v[E-1].dts;var V,K=N+4*M+8;try{V=new Uint8Array(K)}catch(t){return void this.observer.emit(a.Events.ERROR,a.Events.ERROR,{type:o.ErrorTypes.MUX_ERROR,details:o.ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,bytes:K,reason:"fail allocating video mdat "+K})}var q=new DataView(V.buffer);q.setUint32(0,K),V.set(s.default.types.mdat,4);for(var W=!1,z=Number.POSITIVE_INFINITY,Y=Number.POSITIVE_INFINITY,X=Number.NEGATIVE_INFINITY,Q=Number.NEGATIVE_INFINITY,$=0;$<E;$++){for(var Z=v[$],J=Z.units,tt=0,et=0,rt=J.length;et<rt;et++){var it=J[et],nt=it.data,st=it.data.byteLength;q.setUint32(S,st),S+=4,V.set(nt,S),S+=st,tt+=4+st}var at=void 0;if($<E-1)b=v[$+1].dts-Z.dts,at=v[$+1].pts-Z.pts;else{var ot=this.config,lt=$>0?Z.dts-v[$-1].dts:k;if(at=$>0?Z.pts-v[$-1].pts:k,ot.stretchShortVideoTrack&&null!==this.nextAudioPts){var dt=Math.floor(ot.maxBufferHole*p),ut=(i?A+i*p:this.nextAudioPts)-Z.pts;ut>dt?((b=ut-lt)<0?b=lt:W=!0,l.logger.log("[mp4-remuxer]: It is approximately "+ut/90+" ms to the next segment; using duration "+b/90+" ms for the last video frame.")):b=lt}else b=lt}var ct=Math.round(Z.pts-Z.dts);z=Math.min(z,b),X=Math.max(X,b),Y=Math.min(Y,at),Q=Math.max(Q,at),m.push(new y(Z.key,b,tt,ct))}if(m.length)if(h){if(h<70){var ht=m[0].flags;ht.dependsOn=2,ht.isNonSync=0}}else if(f&&Q-Y<X-z&&k/X<.025&&0===m[0].cts){l.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var ft=n,pt=0,gt=m.length;pt<gt;pt++){var vt=ft+m[pt].duration,mt=ft+m[pt].cts;if(pt<gt-1){var yt=vt+m[pt+1].cts;m[pt].duration=yt-mt}else m[pt].duration=pt?m[pt-1].duration:k;m[pt].cts=0,ft=vt}}console.assert(null!==b,"mp4SampleDuration must be computed"),b=W||!b?k:b,this.nextAvcDts=_=d+b,this.videoSampleDuration=b,this.isVideoContiguous=!0;var Et={data1:s.default.moof(t.sequenceNumber++,n,c({},t,{samples:m})),data2:V,startPTS:A/p,endPTS:(L+b)/p,startDTS:n/p,endDTS:_/p,type:"video",hasAudio:!1,hasVideo:!0,nb:m.length,dropped:t.dropped};return t.samples=[],t.dropped=0,console.assert(V.length,"MDAT length must not be zero"),Et},e.remuxAudio=function(t,e,r,i,d){var u=t.inputTimeScale,h=u/(t.samplerate?t.samplerate:u),f="aac"===t.segmentCodec?1024:1152,p=f*h,v=this._initPTS,m="mp3"===t.segmentCodec&&this.typeSupported.mpeg,E=[],T=void 0!==d,_=t.samples,S=m?0:8,b=this.nextAudioPts||-1,A=e*u;if(this.isAudioContiguous=r=r||_.length&&b>0&&(i&&Math.abs(A-b)<9e3||Math.abs(g(_[0].pts-v,A)-b)<20*p),_.forEach((function(t){t.pts=g(t.pts-v,A)})),!r||b<0){if(!(_=_.filter((function(t){return t.pts>=0}))).length)return;b=0===d?0:i&&!T?Math.max(0,A):_[0].pts}if("aac"===t.segmentCodec)for(var L=this.config.maxAudioFramesDrift,w=0,D=b;w<_.length;w++){var R=_[w],I=R.pts,k=I-D,O=Math.abs(1e3*k/u);if(k<=-L*p&&T)0===w&&(l.logger.warn("Audio frame @ "+(I/u).toFixed(3)+"s overlaps nextAudioPts by "+Math.round(1e3*k/u)+" ms."),this.nextAudioPts=b=D=I);else if(k>=L*p&&O<1e4&&T){var C=Math.round(k/p);(D=I-C*p)<0&&(C--,D+=p),0===w&&(this.nextAudioPts=b=D),l.logger.warn("[mp4-remuxer]: Injecting "+C+" audio frame @ "+(D/u).toFixed(3)+"s due to "+Math.round(1e3*k/u)+" ms gap.");for(var P=0;P<C;P++){var x=Math.max(D,0),M=n.default.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);M||(l.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),M=R.unit.subarray()),_.splice(w,0,{unit:M,pts:x}),D+=p,w++}}R.pts=D,D+=p}for(var N,F=null,U=null,B=0,G=_.length;G--;)B+=_[G].unit.byteLength;for(var H=0,j=_.length;H<j;H++){var V=_[H],K=V.unit,q=V.pts;if(null!==U)E[H-1].duration=Math.round((q-U)/h);else{if(r&&"aac"===t.segmentCodec&&(q=b),F=q,!(B>0))return;B+=S;try{N=new Uint8Array(B)}catch(t){return void this.observer.emit(a.Events.ERROR,a.Events.ERROR,{type:o.ErrorTypes.MUX_ERROR,details:o.ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,bytes:B,reason:"fail allocating audio mdat "+B})}m||(new DataView(N.buffer).setUint32(0,B),N.set(s.default.types.mdat,4))}N.set(K,S);var W=K.byteLength;S+=W,E.push(new y(!0,f,W,0)),U=q}var z=E.length;if(z){var Y=E[E.length-1];this.nextAudioPts=b=U+h*Y.duration;var X=m?new Uint8Array(0):s.default.moof(t.sequenceNumber++,F/h,c({},t,{samples:E}));t.samples=[];var Q=F/u,$=b/u,Z={data1:X,data2:N,startPTS:Q,endPTS:$,startDTS:Q,endDTS:$,type:"audio",hasAudio:!0,hasVideo:!1,nb:z};return this.isAudioContiguous=!0,console.assert(N.length,"MDAT length must not be zero"),Z}},e.remuxEmptyAudio=function(t,e,r,i){var s=t.inputTimeScale,a=s/(t.samplerate?t.samplerate:s),o=this.nextAudioPts,d=(null!==o?o:i.startDTS*s)+this._initDTS,u=i.endDTS*s+this._initDTS,c=1024*a,h=Math.ceil((u-d)/c),f=n.default.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(l.logger.warn("[mp4-remuxer]: remux empty Audio"),f){for(var p=[],g=0;g<h;g++){var v=d+g*c;p.push({unit:f,pts:v,dts:v})}return t.samples=p,this.remuxAudio(t,e,r,!1)}l.logger.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec")},t}();function g(t,e){var r;if(null===e)return t;for(r=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=r;return t}function v(t,e,r,i){var n=t.samples.length;if(n){for(var s=t.inputTimeScale,a=0;a<n;a++){var o=t.samples[a];o.pts=g(o.pts-r,e*s)/s,o.dts=g(o.dts-i,e*s)/s}var l=t.samples;return t.samples=[],{samples:l}}}function m(t,e,r){var i=t.samples.length;if(i){for(var n=t.inputTimeScale,s=0;s<i;s++){var a=t.samples[s];a.pts=g(a.pts-r,e*n)/n}t.samples.sort((function(t,e){return t.pts-e.pts}));var o=t.samples;return t.samples=[],{samples:o}}}var y=function(t,e,r,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=r,this.cts=i,this.flags=new E(t)},E=function(t){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=t?2:1,this.isNonSync=t?0:1}},"./src/remux/passthrough-remuxer.ts":
|
|
182
|
-
/*!******************************************!*\
|
|
183
|
-
!*** ./src/remux/passthrough-remuxer.ts ***!
|
|
184
|
-
\******************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>d});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ./mp4-remuxer */"./src/remux/mp4-remuxer.ts"),s=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts"),a=r(/*! ../loader/fragment */"./src/loader/fragment.ts"),o=r(/*! ../utils/logger */"./src/utils/logger.ts");function l(t,e){var r=null==t?void 0:t.codec;return r&&r.length>4?r:"hvc1"===r||"hev1"===r?"hvc1.1.c.L120.90":"av01"===r?"av01.0.04M.08":"avc1"===r||e===a.ElementaryStreamTypes.VIDEO?"avc1.42e01e":"mp4a.40.5"}const d=function(){function t(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=void 0,this.initTracks=void 0,this.lastEndTime=null}var e=t.prototype;return e.destroy=function(){},e.resetTimeStamp=function(t){this.initPTS=t,this.lastEndTime=null},e.resetNextTimestamp=function(){this.lastEndTime=null},e.resetInitSegment=function(t,e,r){this.audioCodec=e,this.videoCodec=r,this.generateInitSegment(t),this.emitInitSegment=!0},e.generateInitSegment=function(t){var e=this.audioCodec,r=this.videoCodec;if(!t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var i=this.initData=(0,s.parseInitSegment)(t);e||(e=l(i.audio,a.ElementaryStreamTypes.AUDIO)),r||(r=l(i.video,a.ElementaryStreamTypes.VIDEO));var n={};i.audio&&i.video?n.audiovideo={container:"video/mp4",codec:e+","+r,initSegment:t,id:"main"}:i.audio?n.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:i.video?n.video={container:"video/mp4",codec:r,initSegment:t,id:"main"}:o.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n},e.remux=function(t,e,r,a,l){var d,u=this.initPTS,c=this.lastEndTime,h={audio:void 0,video:void 0,text:a,id3:r,initSegment:void 0};(0,i.isFiniteNumber)(c)||(c=this.lastEndTime=l||0);var f=e.samples;if(!f||!f.length)return h;var p={initPTS:void 0,timescale:1},g=this.initData;if(g&&g.length||(this.generateInitSegment(f),g=this.initData),!g||!g.length)return o.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),h;this.emitInitSegment&&(p.tracks=this.initTracks,this.emitInitSegment=!1);var v=(0,s.getStartDTS)(g,f);(0,i.isFiniteNumber)(u)||(this.initPTS=p.initPTS=u=v-l);var m=(0,s.getDuration)(f,g),y=t?v-u:c,E=y+m;(0,s.offsetStartDTS)(g,f,u),m>0?this.lastEndTime=E:(o.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var T=!!g.audio,_=!!g.video,S="";T&&(S+="audio"),_&&(S+="video");var b={data1:f,startPTS:y,startDTS:y,endPTS:E,endDTS:E,type:S,hasAudio:T,hasVideo:_,nb:1,dropped:0};h.audio="audio"===b.type?b:void 0,h.video="audio"!==b.type?b:void 0,h.initSegment=p;var A=null!=(d=this.initPTS)?d:0;return h.id3=(0,n.flushTextTrackMetadataCueSamples)(r,l,A,A),a.samples.length&&(h.text=(0,n.flushTextTrackUserdataCueSamples)(a,l,A)),h},t}()},"./src/task-loop.ts":
|
|
185
|
-
/*!**************************!*\
|
|
186
|
-
!*** ./src/task-loop.ts ***!
|
|
187
|
-
\**************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>i});var i=function(){function t(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}var e=t.prototype;return e.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},e.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},e.onHandlerDestroyed=function(){},e.hasInterval=function(){return!!this._tickInterval},e.hasNextTick=function(){return!!this._tickTimer},e.setInterval=function(t){return!this._tickInterval&&(this._tickInterval=self.setInterval(this._boundTick,t),!0)},e.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},e.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},e.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},e.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},e.doTick=function(){},t}()},"./src/types/cmcd.ts":
|
|
188
|
-
/*!***************************!*\
|
|
189
|
-
!*** ./src/types/cmcd.ts ***!
|
|
190
|
-
\***************************/(t,e,r)=>{r.r(e),r.d(e,{CMCDObjectType:()=>i,CMCDStreamType:()=>s,CMCDStreamingFormat:()=>n,CMCDVersion:()=>a});var i,n,s,a=1;!function(t){t.MANIFEST="m",t.AUDIO="a",t.VIDEO="v",t.MUXED="av",t.INIT="i",t.CAPTION="c",t.TIMED_TEXT="tt",t.KEY="k",t.OTHER="o"}(i||(i={})),function(t){t.DASH="d",t.HLS="h",t.SMOOTH="s",t.OTHER="o"}(n||(n={})),function(t){t.VOD="v",t.LIVE="l"}(s||(s={}))},"./src/types/demuxer.ts":
|
|
191
|
-
/*!******************************!*\
|
|
192
|
-
!*** ./src/types/demuxer.ts ***!
|
|
193
|
-
\******************************/(t,e,r)=>{var i;r.r(e),r.d(e,{MetadataSchema:()=>i}),function(t){t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3"}(i||(i={}))},"./src/types/level.ts":
|
|
194
|
-
/*!****************************!*\
|
|
195
|
-
!*** ./src/types/level.ts ***!
|
|
196
|
-
\****************************/(t,e,r)=>{function i(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}var n;function s(t,e){var r=t.canSkipUntil,i=t.canSkipDateRanges,s=t.endSN;return r&&(void 0!==e?e-s:0)<r?i?n.v2:n.Yes:n.No}r.r(e),r.d(e,{HlsSkip:()=>n,HlsUrlParameters:()=>a,Level:()=>o,getSkipValue:()=>s}),function(t){t.No="",t.Yes="YES",t.v2="v2"}(n||(n={}));var a=function(){function t(t,e,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=r}return t.prototype.addDirectives=function(t){var e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.toString()},t}(),o=function(){function t(t){this.attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=void 0,this._urlId=0,this.url=[t.url],this.attrs=t.attrs,this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.unknownCodecs=t.unknownCodecs,this.codecSet=[t.videoCodec,t.audioCodec].filter((function(t){return t})).join(",").replace(/\.[^.,]+/g,"")}var e,r,n;return e=t,(r=[{key:"maxBitrate",get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:"uri",get:function(){return this.url[this._urlId]||""}},{key:"urlId",get:function(){return this._urlId},set:function(t){var e=t%this.url.length;this._urlId!==e&&(this.details=void 0,this._urlId=e)}}])&&i(e.prototype,r),n&&i(e,n),Object.defineProperty(e,"prototype",{writable:!1}),t}()},"./src/types/loader.ts":
|
|
197
|
-
/*!*****************************!*\
|
|
198
|
-
!*** ./src/types/loader.ts ***!
|
|
199
|
-
\*****************************/(t,e,r)=>{var i,n;r.r(e),r.d(e,{PlaylistContextType:()=>i,PlaylistLevelType:()=>n}),function(t){t.MANIFEST="manifest",t.LEVEL="level",t.AUDIO_TRACK="audioTrack",t.SUBTITLE_TRACK="subtitleTrack"}(i||(i={})),function(t){t.MAIN="main",t.AUDIO="audio",t.SUBTITLE="subtitle"}(n||(n={}))},"./src/types/transmuxer.ts":
|
|
200
|
-
/*!*********************************!*\
|
|
201
|
-
!*** ./src/types/transmuxer.ts ***!
|
|
202
|
-
\*********************************/(t,e,r)=>{r.r(e),r.d(e,{ChunkMetadata:()=>i});var i=function(t,e,r,i,n,s){void 0===i&&(i=0),void 0===n&&(n=-1),void 0===s&&(s=!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=t,this.sn=e,this.id=r,this.size=i,this.part=n,this.partial=s}},"./src/utils/attr-list.ts":
|
|
203
|
-
/*!********************************!*\
|
|
204
|
-
!*** ./src/utils/attr-list.ts ***!
|
|
205
|
-
\********************************/(t,e,r)=>{r.r(e),r.d(e,{AttrList:()=>s});var i=/^(\d+)x(\d+)$/,n=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,s=function(){function t(e){for(var r in"string"==typeof e&&(e=t.parseAttrList(e)),e)e.hasOwnProperty(r)&&(this[r]=e[r])}var e=t.prototype;return e.decimalInteger=function(t){var e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e},e.hexadecimalInteger=function(t){if(this[t]){var e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;for(var r=new Uint8Array(e.length/2),i=0;i<e.length/2;i++)r[i]=parseInt(e.slice(2*i,2*i+2),16);return r}return null},e.hexadecimalIntegerAsNumber=function(t){var e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e},e.decimalFloatingPoint=function(t){return parseFloat(this[t])},e.optionalFloat=function(t,e){var r=this[t];return r?parseFloat(r):e},e.enumeratedString=function(t){return this[t]},e.bool=function(t){return"YES"===this[t]},e.decimalResolution=function(t){var e=i.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}},t.parseAttrList=function(t){var e,r={};for(n.lastIndex=0;null!==(e=n.exec(t));){var i=e[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[e[1]]=i}return r},t}()},"./src/utils/binary-search.ts":
|
|
206
|
-
/*!************************************!*\
|
|
207
|
-
!*** ./src/utils/binary-search.ts ***!
|
|
208
|
-
\************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>i});const i={search:function(t,e){for(var r=0,i=t.length-1,n=null,s=null;r<=i;){var a=e(s=t[n=(r+i)/2|0]);if(a>0)r=n+1;else{if(!(a<0))return s;i=n-1}}return null}}},"./src/utils/buffer-helper.ts":
|
|
209
|
-
/*!************************************!*\
|
|
210
|
-
!*** ./src/utils/buffer-helper.ts ***!
|
|
211
|
-
\************************************/(t,e,r)=>{r.r(e),r.d(e,{BufferHelper:()=>s});var i=r(/*! ./logger */"./src/utils/logger.ts"),n={length:0,start:function(){return 0},end:function(){return 0}},s=function(){function t(){}return t.isBuffered=function(e,r){try{if(e)for(var i=t.getBuffered(e),n=0;n<i.length;n++)if(r>=i.start(n)&&r<=i.end(n))return!0}catch(t){}return!1},t.bufferInfo=function(e,r,i){try{if(e){var n,s=t.getBuffered(e),a=[];for(n=0;n<s.length;n++)a.push({start:s.start(n),end:s.end(n)});return this.bufferedInfo(a,r,i)}}catch(t){}return{len:0,start:r,end:r,nextStart:void 0}},t.bufferedInfo=function(t,e,r){e=Math.max(0,e),t.sort((function(t,e){var r=t.start-e.start;return r||e.end-t.end}));var i=[];if(r)for(var n=0;n<t.length;n++){var s=i.length;if(s){var a=i[s-1].end;t[n].start-a<r?t[n].end>a&&(i[s-1].end=t[n].end):i.push(t[n])}else i.push(t[n])}else i=t;for(var o,l=0,d=e,u=e,c=0;c<i.length;c++){var h=i[c].start,f=i[c].end;if(e+r>=h&&e<f)d=h,l=(u=f)-e;else if(e+r<h){o=h;break}}return{len:l,start:d||0,end:u||0,nextStart:o}},t.getBuffered=function(t){try{return t.buffered}catch(t){return i.logger.log("failed to get media.buffered",t),n}},t}()},"./src/utils/cea-608-parser.ts":
|
|
212
|
-
/*!*************************************!*\
|
|
213
|
-
!*** ./src/utils/cea-608-parser.ts ***!
|
|
214
|
-
\*************************************/(t,e,r)=>{r.r(e),r.d(e,{CaptionScreen:()=>m,Row:()=>v,default:()=>_});var i,n=r(/*! ../utils/logger */"./src/utils/logger.ts"),s={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},a=function(t){var e=t;return s.hasOwnProperty(t)&&(e=s[t]),String.fromCharCode(e)},o={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},l={17:2,18:4,21:6,22:8,23:10,19:13,20:15},d={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},u={25:2,26:4,29:6,30:8,31:10,27:13,28:15},c=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];!function(t){t[t.ERROR=0]="ERROR",t[t.TEXT=1]="TEXT",t[t.WARNING=2]="WARNING",t[t.INFO=2]="INFO",t[t.DEBUG=3]="DEBUG",t[t.DATA=3]="DATA"}(i||(i={}));var h=function(){function t(){this.time=null,this.verboseLevel=i.ERROR}return t.prototype.log=function(t,e){this.verboseLevel>=t&&n.logger.log(this.time+" ["+t+"] "+e)},t}(),f=function(t){for(var e=[],r=0;r<t.length;r++)e.push(t[r].toString(16));return e},p=function(){function t(t,e,r,i,n){this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=t||"white",this.underline=e||!1,this.italics=r||!1,this.background=i||"black",this.flash=n||!1}var e=t.prototype;return e.reset=function(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1},e.setStyles=function(t){for(var e=["foreground","underline","italics","background","flash"],r=0;r<e.length;r++){var i=e[r];t.hasOwnProperty(i)&&(this[i]=t[i])}},e.isDefault=function(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash},e.equals=function(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash},e.copy=function(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash},e.toString=function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash},t}(),g=function(){function t(t,e,r,i,n,s){this.uchar=void 0,this.penState=void 0,this.uchar=t||" ",this.penState=new p(e,r,i,n,s)}var e=t.prototype;return e.reset=function(){this.uchar=" ",this.penState.reset()},e.setChar=function(t,e){this.uchar=t,this.penState.copy(e)},e.setPenState=function(t){this.penState.copy(t)},e.equals=function(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)},e.copy=function(t){this.uchar=t.uchar,this.penState.copy(t.penState)},e.isEmpty=function(){return" "===this.uchar&&this.penState.isDefault()},t}(),v=function(){function t(t){this.chars=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(var e=0;e<100;e++)this.chars.push(new g);this.logger=t,this.pos=0,this.currPenState=new p}var e=t.prototype;return e.equals=function(t){for(var e=!0,r=0;r<100;r++)if(!this.chars[r].equals(t.chars[r])){e=!1;break}return e},e.copy=function(t){for(var e=0;e<100;e++)this.chars[e].copy(t.chars[e])},e.isEmpty=function(){for(var t=!0,e=0;e<100;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t},e.setCursor=function(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(i.DEBUG,"Negative cursor position "+this.pos),this.pos=0):this.pos>100&&(this.logger.log(i.DEBUG,"Too large cursor position "+this.pos),this.pos=100)},e.moveCursor=function(t){var e=this.pos+t;if(t>1)for(var r=this.pos+1;r<e+1;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(e)},e.backSpace=function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)},e.insertChar=function(t){t>=144&&this.backSpace();var e=a(t);this.pos>=100?this.logger.log(i.ERROR,"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))},e.clearFromPos=function(t){var e;for(e=t;e<100;e++)this.chars[e].reset()},e.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},e.clearToEndOfRow=function(){this.clearFromPos(this.pos)},e.getTextString=function(){for(var t=[],e=!0,r=0;r<100;r++){var i=this.chars[r].uchar;" "!==i&&(e=!1),t.push(i)}return e?"":t.join("")},e.setPenStyles=function(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)},t}(),m=function(){function t(t){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(var e=0;e<15;e++)this.rows.push(new v(t));this.logger=t,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}var e=t.prototype;return e.reset=function(){for(var t=0;t<15;t++)this.rows[t].clear();this.currRow=14},e.equals=function(t){for(var e=!0,r=0;r<15;r++)if(!this.rows[r].equals(t.rows[r])){e=!1;break}return e},e.copy=function(t){for(var e=0;e<15;e++)this.rows[e].copy(t.rows[e])},e.isEmpty=function(){for(var t=!0,e=0;e<15;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t},e.backSpace=function(){this.rows[this.currRow].backSpace()},e.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},e.insertChar=function(t){this.rows[this.currRow].insertChar(t)},e.setPen=function(t){this.rows[this.currRow].setPenStyles(t)},e.moveCursor=function(t){this.rows[this.currRow].moveCursor(t)},e.setCursor=function(t){this.logger.log(i.INFO,"setCursor: "+t),this.rows[this.currRow].setCursor(t)},e.setPAC=function(t){this.logger.log(i.INFO,"pacData = "+JSON.stringify(t));var e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(var r=0;r<15;r++)this.rows[r].clear();var n=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){var a=s.rows[n].cueStartTime,o=this.logger.time;if(a&&null!==o&&a<o)for(var l=0;l<this.nrRollUpRows;l++)this.rows[e-this.nrRollUpRows+l+1].copy(s.rows[n+l])}}this.currRow=e;var d=this.rows[this.currRow];if(null!==t.indent){var u=t.indent,c=Math.max(u-1,0);d.setCursor(t.indent),t.color=d.chars[c].penState.foreground}var h={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(h)},e.setBkgData=function(t){this.logger.log(i.INFO,"bkgData = "+JSON.stringify(t)),this.backSpace(),this.setPen(t),this.insertChar(32)},e.setRollUpRows=function(t){this.nrRollUpRows=t},e.rollUp=function(){if(null!==this.nrRollUpRows){this.logger.log(i.TEXT,this.getDisplayText());var t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(i.INFO,"Rolling up")}else this.logger.log(i.DEBUG,"roll_up but nrRollUpRows not set yet")},e.getDisplayText=function(t){t=t||!1;for(var e=[],r="",i=-1,n=0;n<15;n++){var s=this.rows[n].getTextString();s&&(i=n+1,t?e.push("Row "+i+": '"+s+"'"):e.push(s.trim()))}return e.length>0&&(r=t?"["+e.join(" | ")+"]":e.join("\n")),r},e.getTextAndFormat=function(){return this.rows},t}(),y=function(){function t(t,e,r){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=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new m(r),this.nonDisplayedMemory=new m(r),this.lastOutputScreen=new m(r),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}var e=t.prototype;return e.reset=function(){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},e.getHandler=function(){return this.outputFilter},e.setHandler=function(t){this.outputFilter=t},e.setPAC=function(t){this.writeScreen.setPAC(t)},e.setBkgData=function(t){this.writeScreen.setBkgData(t)},e.setMode=function(t){t!==this.mode&&(this.mode=t,this.logger.log(i.INFO,"MODE="+t),"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=t)},e.insertChars=function(t){for(var e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);var r=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(i.INFO,r+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(i.TEXT,"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())},e.ccRCL=function(){this.logger.log(i.INFO,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")},e.ccBS=function(){this.logger.log(i.INFO,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())},e.ccAOF=function(){},e.ccAON=function(){},e.ccDER=function(){this.logger.log(i.INFO,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()},e.ccRU=function(t){this.logger.log(i.INFO,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)},e.ccFON=function(){this.logger.log(i.INFO,"FON - Flash On"),this.writeScreen.setPen({flash:!0})},e.ccRDC=function(){this.logger.log(i.INFO,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")},e.ccTR=function(){this.logger.log(i.INFO,"TR"),this.setMode("MODE_TEXT")},e.ccRTD=function(){this.logger.log(i.INFO,"RTD"),this.setMode("MODE_TEXT")},e.ccEDM=function(){this.logger.log(i.INFO,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)},e.ccCR=function(){this.logger.log(i.INFO,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)},e.ccENM=function(){this.logger.log(i.INFO,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()},e.ccEOC=function(){if(this.logger.log(i.INFO,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(i.TEXT,"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)},e.ccTO=function(t){this.logger.log(i.INFO,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)},e.ccMIDROW=function(t){var e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{var r=Math.floor(t/2)-16;e.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(i.INFO,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)},e.outputDataUpdate=function(t){void 0===t&&(t=!1);var e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))},e.cueSplitAtTime=function(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))},t}();function E(t,e,r){r.a=t,r.b=e}function T(t,e,r){return r.a===t&&r.b===e}const _=function(){function t(t,e,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;var i=new h;this.channels=[null,new y(t,e,i),new y(t+1,r,i)],this.cmdHistory={a:null,b:null},this.logger=i}var e=t.prototype;return e.getHandler=function(t){return this.channels[t].getHandler()},e.setHandler=function(t,e){this.channels[t].setHandler(e)},e.addData=function(t,e){var r,n,s,a=!1;this.logger.time=t;for(var o=0;o<e.length;o+=2)if(n=127&e[o],s=127&e[o+1],0!==n||0!==s){if(this.logger.log(i.DATA,"["+f([e[o],e[o+1]])+"] -> ("+f([n,s])+")"),(r=this.parseCmd(n,s))||(r=this.parseMidrow(n,s)),r||(r=this.parsePAC(n,s)),r||(r=this.parseBackgroundAttributes(n,s)),!r&&(a=this.parseChars(n,s))){var l=this.currentChannel;l&&l>0?this.channels[l].insertChars(a):this.logger.log(i.WARNING,"No channel found yet. TEXT-MODE?")}r||a||this.logger.log(i.WARNING,"Couldn't parse cleaned data "+f([n,s])+" orig: "+f([e[o],e[o+1]]))}},e.parseCmd=function(t,e){var r=this.cmdHistory;if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47||(23===t||31===t)&&e>=33&&e<=35))return!1;if(T(t,e,r))return E(null,null,r),this.logger.log(i.DEBUG,"Repeated command ("+f([t,e])+") is dropped"),!0;var n=20===t||21===t||23===t?1:2,s=this.channels[n];return 20===t||21===t||28===t||29===t?32===e?s.ccRCL():33===e?s.ccBS():34===e?s.ccAOF():35===e?s.ccAON():36===e?s.ccDER():37===e?s.ccRU(2):38===e?s.ccRU(3):39===e?s.ccRU(4):40===e?s.ccFON():41===e?s.ccRDC():42===e?s.ccTR():43===e?s.ccRTD():44===e?s.ccEDM():45===e?s.ccCR():46===e?s.ccENM():47===e&&s.ccEOC():s.ccTO(e-32),E(t,e,r),this.currentChannel=n,!0},e.parseMidrow=function(t,e){var r=0;if((17===t||25===t)&&e>=32&&e<=47){if((r=17===t?1:2)!==this.currentChannel)return this.logger.log(i.ERROR,"Mismatch channel in midrow parsing"),!1;var n=this.channels[r];return!!n&&(n.ccMIDROW(e),this.logger.log(i.DEBUG,"MIDROW ("+f([t,e])+")"),!0)}return!1},e.parsePAC=function(t,e){var r,i=this.cmdHistory;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127||(16===t||24===t)&&e>=64&&e<=95))return!1;if(T(t,e,i))return E(null,null,i),!0;var n=t<=23?1:2;r=e>=64&&e<=95?1===n?o[t]:d[t]:1===n?l[t]:u[t];var s=this.channels[n];return!!s&&(s.setPAC(this.interpretPAC(r,e)),E(t,e,i),this.currentChannel=n,!0)},e.interpretPAC=function(t,e){var r,i={color:null,italics:!1,indent:null,underline:!1,row:t};return r=e>95?e-96:e-64,i.underline=1==(1&r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i},e.parseChars=function(t,e){var r,n,s=null,o=null;if(t>=25?(r=2,o=t-8):(r=1,o=t),o>=17&&o<=19?(n=17===o?e+80:18===o?e+112:e+144,this.logger.log(i.INFO,"Special char '"+a(n)+"' in channel "+r),s=[n]):t>=32&&t<=127&&(s=0===e?[t]:[t,e]),s){var l=f(s);this.logger.log(i.DEBUG,"Char codes = "+l.join(",")),E(t,e,this.cmdHistory)}return s},e.parseBackgroundAttributes=function(t,e){var r;if(!((16===t||24===t)&&e>=32&&e<=47||(23===t||31===t)&&e>=45&&e<=47))return!1;var i={};16===t||24===t?(r=Math.floor((e-32)/2),i.background=c[r],e%2==1&&(i.background=i.background+"_semi")):45===e?i.background="transparent":(i.foreground="black",47===e&&(i.underline=!0));var n=t<=23?1:2;return this.channels[n].setBkgData(i),E(t,e,this.cmdHistory),!0},e.reset=function(){for(var t=0;t<Object.keys(this.channels).length;t++){var e=this.channels[t];e&&e.reset()}this.cmdHistory={a:null,b:null}},e.cueSplitAtTime=function(t){for(var e=0;e<this.channels.length;e++){var r=this.channels[e];r&&r.cueSplitAtTime(t)}},t}()},"./src/utils/codecs.ts":
|
|
215
|
-
/*!*****************************!*\
|
|
216
|
-
!*** ./src/utils/codecs.ts ***!
|
|
217
|
-
\*****************************/(t,e,r)=>{r.r(e),r.d(e,{isCodecSupportedInMp4:()=>s,isCodecType:()=>n});var i={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}};function n(t,e){var r=i[e];return!!r&&!0===r[t.slice(0,4)]}function s(t,e){return MediaSource.isTypeSupported((e||"video")+'/mp4;codecs="'+t+'"')}},"./src/utils/cues.ts":
|
|
218
|
-
/*!***************************!*\
|
|
219
|
-
!*** ./src/utils/cues.ts ***!
|
|
220
|
-
\***************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>o});var i=r(/*! ./vttparser */"./src/utils/vttparser.ts"),n=r(/*! ./webvtt-parser */"./src/utils/webvtt-parser.ts"),s=r(/*! ./texttrack-utils */"./src/utils/texttrack-utils.ts"),a=/\s/;const o={newCue:function(t,e,r,o){for(var l,d,u,c,h,f=[],p=self.VTTCue||self.TextTrackCue,g=0;g<o.rows.length;g++)if(u=!0,c=0,h="",!(l=o.rows[g]).isEmpty()){for(var v=0;v<l.chars.length;v++)a.test(l.chars[v].uchar)&&u?c++:(h+=l.chars[v].uchar,u=!1);l.cueStartTime=e,e===r&&(r+=1e-4),c>=16?c--:c++;var m=(0,i.fixLineBreaks)(h.trim()),y=(0,n.generateCueId)(e,r,m);t&&t.cues&&t.cues.getCueById(y)||((d=new p(e,r,m)).id=y,d.line=g+1,d.align="left",d.position=10+Math.min(80,10*Math.floor(8*c/32)),f.push(d))}return t&&f.length&&(f.sort((function(t,e){return"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line})),f.forEach((function(e){return(0,s.addCueToTrack)(t,e)}))),f}}},"./src/utils/discontinuities.ts":
|
|
221
|
-
/*!**************************************!*\
|
|
222
|
-
!*** ./src/utils/discontinuities.ts ***!
|
|
223
|
-
\**************************************/(t,e,r)=>{r.r(e),r.d(e,{adjustSlidingStart:()=>u,alignMediaPlaylistByPDT:()=>f,alignPDT:()=>h,alignStream:()=>c,findDiscontinuousReferenceFrag:()=>l,findFirstFragWithCC:()=>a,shouldAlignOnDiscontinuities:()=>o});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ./logger */"./src/utils/logger.ts"),s=r(/*! ../controller/level-helper */"./src/controller/level-helper.ts");function a(t,e){for(var r=null,i=0,n=t.length;i<n;i++){var s=t[i];if(s&&s.cc===e){r=s;break}}return r}function o(t,e,r){return!(!e.details||!(r.endCC>r.startCC||t&&t.cc<r.startCC))}function l(t,e,r){var i=t.fragments,s=e.fragments;if(s.length&&i.length){var o=a(i,s[0].cc);if(o&&(!o||o.startPTS))return o;n.logger.log("No frag in previous level to align on")}else n.logger.log("No fragments to align")}function d(t,e){if(t){var r=t.start+e;t.start=t.startPTS=r,t.endPTS=r+t.duration}}function u(t,e){for(var r=e.fragments,i=0,n=r.length;i<n;i++)d(r[i],t);e.fragmentHint&&d(e.fragmentHint,t),e.alignedSliding=!0}function c(t,e,r){e&&(function(t,e,r){if(o(t,r,e)){var s=l(r.details,e);s&&(0,i.isFiniteNumber)(s.start)&&(n.logger.log("Adjusting PTS using last level due to CC increase within current level "+e.url),u(s.start,e))}}(t,r,e),!r.alignedSliding&&e.details&&h(r,e.details),r.alignedSliding||!e.details||r.skippedSegments||(0,s.adjustSliding)(e.details,r))}function h(t,e){if(e.fragments.length&&t.hasProgramDateTime&&e.hasProgramDateTime){var r=e.fragments[0].programDateTime,s=t.fragments[0].programDateTime,a=(s-r)/1e3+e.fragments[0].start;a&&(0,i.isFiniteNumber)(a)&&(n.logger.log("Adjusting PTS using programDateTime delta "+(s-r)+"ms, sliding:"+a.toFixed(3)+" "+t.url+" "),u(a,t))}}function f(t,e){if(t.hasProgramDateTime&&e.hasProgramDateTime){var r=t.fragments,i=e.fragments;if(r.length&&i.length){var n=i[Math.round(i.length/2)-1],s=a(r,n.cc)||r[Math.round(r.length/2)-1],o=n.programDateTime,l=s.programDateTime;null!==o&&null!==l&&u((l-o)/1e3-(s.start-n.start),t)}}}},"./src/utils/ewma-bandwidth-estimator.ts":
|
|
224
|
-
/*!***********************************************!*\
|
|
225
|
-
!*** ./src/utils/ewma-bandwidth-estimator.ts ***!
|
|
226
|
-
\***********************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>n});var i=r(/*! ../utils/ewma */"./src/utils/ewma.ts");const n=function(){function t(t,e,r){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new i.default(t),this.fast_=new i.default(e)}var e=t.prototype;return e.update=function(t,e){var r=this.slow_,n=this.fast_;this.slow_.halfLife!==t&&(this.slow_=new i.default(t,r.getEstimate(),r.getTotalWeight())),this.fast_.halfLife!==e&&(this.fast_=new i.default(e,n.getEstimate(),n.getTotalWeight()))},e.sample=function(t,e){var r=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},e.canEstimate=function(){var t=this.fast_;return t&&t.getTotalWeight()>=this.minWeight_},e.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},e.destroy=function(){},t}()},"./src/utils/ewma.ts":
|
|
227
|
-
/*!***************************!*\
|
|
228
|
-
!*** ./src/utils/ewma.ts ***!
|
|
229
|
-
\***************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>i});const i=function(){function t(t,e,r){void 0===e&&(e=0),void 0===r&&(r=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=r}var e=t.prototype;return e.sample=function(t,e){var r=Math.pow(this.alpha_,t);this.estimate_=e*(1-r)+r*this.estimate_,this.totalWeight_+=t},e.getTotalWeight=function(){return this.totalWeight_},e.getEstimate=function(){if(this.alpha_){var t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_},t}()},"./src/utils/fetch-loader.ts":
|
|
230
|
-
/*!***********************************!*\
|
|
231
|
-
!*** ./src/utils/fetch-loader.ts ***!
|
|
232
|
-
\***********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>v,fetchSupported:()=>h});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../loader/load-stats */"./src/loader/load-stats.ts"),s=r(/*! ../demux/chunk-cache */"./src/demux/chunk-cache.ts");function a(t){var e="function"==typeof Map?new Map:void 0;return(a=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return o(t,arguments,u(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),d(i,t)})(t)}function o(t,e,r){return(o=l()?Reflect.construct.bind():function(t,e,r){var i=[null];i.push.apply(i,e);var n=new(Function.bind.apply(t,i));return r&&d(n,r.prototype),n}).apply(null,arguments)}function l(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function d(t,e){return(d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}function u(t){return(u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function c(){return(c=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t}).apply(this,arguments)}function h(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}var f=function(){function t(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||p,this.controller=new self.AbortController,this.stats=new n.LoadStats}var e=t.prototype;return e.destroy=function(){this.loader=this.callbacks=null,this.abortInternal()},e.abortInternal=function(){var t=this.response;t&&t.ok||(this.stats.aborted=!0,this.controller.abort())},e.abort=function(){var t;this.abortInternal(),null!==(t=this.callbacks)&&void 0!==t&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},e.load=function(t,e,r){var n=this,s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();var a=function(t,e){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(c({},t.headers))};return t.rangeEnd&&r.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),r}(t,this.controller.signal),o=r.onProgress,l="arraybuffer"===t.responseType,d=l?"byteLength":"length";this.context=t,this.config=e,this.callbacks=r,this.request=this.fetchSetup(t,a),self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout((function(){n.abortInternal(),r.onTimeout(s,t,n.response)}),e.timeout),self.fetch(this.request).then((function(r){if(n.response=n.loader=r,!r.ok){var a=r.status,d=r.statusText;throw new g(d||"fetch, bad network response",a,r)}return s.loading.first=Math.max(self.performance.now(),s.loading.start),s.total=parseInt(r.headers.get("Content-Length")||"0"),o&&(0,i.isFiniteNumber)(e.highWaterMark)?n.loadProgressively(r,s,t,e.highWaterMark,o):l?r.arrayBuffer():r.text()})).then((function(a){var l=n.response;self.clearTimeout(n.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first),s.loaded=s.total=a[d];var u={url:l.url,data:a};o&&!(0,i.isFiniteNumber)(e.highWaterMark)&&o(s,t,a,l),r.onSuccess(u,s,t,l)})).catch((function(e){if(self.clearTimeout(n.requestTimeout),!s.aborted){var i=e&&e.code||0,a=e?e.message:null;r.onError({code:i,text:a},t,e?e.details:null)}}))},e.getCacheAge=function(){var t=null;if(this.response){var e=this.response.headers.get("age");t=e?parseFloat(e):null}return t},e.loadProgressively=function(t,e,r,i,n){void 0===i&&(i=0);var a=new s.default,o=t.body.getReader();return function s(){return o.read().then((function(o){if(o.done)return a.dataLength&&n(e,r,a.flush(),t),Promise.resolve(new ArrayBuffer(0));var l=o.value,d=l.length;return e.loaded+=d,d<i||a.dataLength?(a.push(l),a.dataLength>=i&&n(e,r,a.flush(),t)):n(e,r,l,t),s()})).catch((function(){return Promise.reject()}))}()},t}();function p(t,e){return new self.Request(t.url,e)}var g=function(t){var e,r;function i(e,r,i){var n;return(n=t.call(this,e)||this).code=void 0,n.details=void 0,n.code=r,n.details=i,n}return r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,d(e,r),i}(a(Error));const v=f},"./src/utils/imsc1-ttml-parser.ts":
|
|
233
|
-
/*!****************************************!*\
|
|
234
|
-
!*** ./src/utils/imsc1-ttml-parser.ts ***!
|
|
235
|
-
\****************************************/(t,e,r)=>{r.r(e),r.d(e,{IMSC1_CODEC:()=>u,parseIMSC1:()=>p});var i=r(/*! ./mp4-tools */"./src/utils/mp4-tools.ts"),n=r(/*! ./vttparser */"./src/utils/vttparser.ts"),s=r(/*! ./vttcue */"./src/utils/vttcue.ts"),a=r(/*! ../demux/id3 */"./src/demux/id3.ts"),o=r(/*! ./timescale-conversion */"./src/utils/timescale-conversion.ts"),l=r(/*! ./webvtt-parser */"./src/utils/webvtt-parser.ts");function d(){return(d=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t}).apply(this,arguments)}var u="stpp.ttml.im1t",c=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,h=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,f={left:"start",center:"center",right:"end",start:"start",end:"end"};function p(t,e,r,n,u){var c=(0,i.findBox)(new Uint8Array(t),["mdat"]);if(0!==c.length){var h=c.map((function(t){return(0,a.utf8ArrayToStr)(t)})),p=(0,o.toTimescaleFromScale)(e,1,r);try{h.forEach((function(t){return n(function(t,e){var r=(new DOMParser).parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");var i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(i).reduce((function(t,e){return t[e]=r.getAttribute("ttp:"+e)||i[e],t}),{}),a="preserve"!==r.getAttribute("xml:space"),o=v(g(r,"styling","style")),u=v(g(r,"layout","region")),c=g(r,"body","[begin]");return[].map.call(c,(function(t){var r=function t(e,r){return[].slice.call(e.childNodes).reduce((function(e,i,n){var s;return"br"===i.nodeName&&n?e+"\n":null!==(s=i.childNodes)&&void 0!==s&&s.length?t(i,r):r?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent}),"")}(t,a);if(!r||!t.hasAttribute("begin"))return null;var i=E(t.getAttribute("begin"),n),c=E(t.getAttribute("dur"),n),h=E(t.getAttribute("end"),n);if(null===i)throw y(t);if(null===h){if(null===c)throw y(t);h=i+c}var p=new s.default(i-e,h-e,r);p.id=(0,l.generateCueId)(p.startTime,p.endTime,p.text);var g=u[t.getAttribute("region")],v=o[t.getAttribute("style")];p.position=10,p.size=80;var T=function(t,e,r){var i="http://www.w3.org/ns/ttml#styling",n=null,s=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;return s&&r.hasOwnProperty(s)&&(n=r[s]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((function(r,s){var a=m(e,i,s)||m(t,i,s)||m(n,i,s);return a&&(r[s]=a),r}),{})}(g,v,o),_=T.textAlign;if(_){var S=f[_];S&&(p.lineAlign=S),p.align=_}return d(p,T),p})).filter((function(t){return null!==t}))}(t,p))}))}catch(t){u(t)}}else u(new Error("Could not parse IMSC1 mdat"))}function g(t,e,r){var i=t.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(r)):[]}function v(t){return t.reduce((function(t,e){var r=e.getAttribute("xml:id");return r&&(t[r]=e),t}),{})}function m(t,e,r){return t&&t.hasAttributeNS(e,r)?t.getAttributeNS(e,r):null}function y(t){return new Error("Could not parse ttml timestamp "+t)}function E(t,e){if(!t)return null;var r=(0,n.parseTimeStamp)(t);return null===r&&(c.test(t)?r=function(t,e){var r=c.exec(t),i=(0|r[4])+(0|r[5])/e.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+i/e.frameRate}(t,e):h.test(t)&&(r=function(t,e){var r=h.exec(t),i=Number(r[1]);switch(r[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}(t,e))),r}},"./src/utils/logger.ts":
|
|
236
|
-
/*!*****************************!*\
|
|
237
|
-
!*** ./src/utils/logger.ts ***!
|
|
238
|
-
\*****************************/(t,e,r)=>{r.r(e),r.d(e,{enableLogs:()=>o,logger:()=>l});var i=function(){},n={trace:i,debug:i,log:i,warn:i,info:i,error:i},s=n;function a(t){var e=self.console[t];return e?e.bind(self.console,"["+t+"] >"):i}function o(t,e){if(self.console&&!0===t||"object"==typeof t){!function(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i<e;i++)r[i-1]=arguments[i];r.forEach((function(e){s[e]=t[e]?t[e].bind(t):a(e)}))}(t,"debug","log","info","warn","error");try{s.log('Debug logs enabled for "'+e+'"')}catch(t){s=n}}else s=n}var l=n},"./src/utils/mediakeys-helper.ts":
|
|
239
|
-
/*!***************************************!*\
|
|
240
|
-
!*** ./src/utils/mediakeys-helper.ts ***!
|
|
241
|
-
\***************************************/(t,e,r)=>{var i;r.r(e),r.d(e,{KeySystems:()=>i,requestMediaKeySystemAccess:()=>n}),function(t){t.WIDEVINE="com.widevine.alpha",t.PLAYREADY="com.microsoft.playready"}(i||(i={}));var n="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null},"./src/utils/mediasource-helper.ts":
|
|
242
|
-
/*!*****************************************!*\
|
|
243
|
-
!*** ./src/utils/mediasource-helper.ts ***!
|
|
244
|
-
\*****************************************/(t,e,r)=>{function i(){return self.MediaSource||self.WebKitMediaSource}r.r(e),r.d(e,{getMediaSource:()=>i})},"./src/utils/mp4-tools.ts":
|
|
245
|
-
/*!********************************!*\
|
|
246
|
-
!*** ./src/utils/mp4-tools.ts ***!
|
|
247
|
-
\********************************/(t,e,r)=>{r.r(e),r.d(e,{RemuxerTrackIdConfig:()=>l,appendUint8Array:()=>S,bin2str:()=>d,computeRawDurationFromSamples:()=>E,discardEPB:()=>w,findBox:()=>p,getDuration:()=>y,getStartDTS:()=>m,offsetStartDTS:()=>T,parseEmsg:()=>D,parseInitSegment:()=>v,parseSEIMessageFromNALu:()=>L,parseSamples:()=>b,parseSegmentIndex:()=>g,readSint32:()=>h,readUint16:()=>u,readUint32:()=>c,segmentValidRange:()=>_,writeUint32:()=>f});var i=r(/*! ./typed-array */"./src/utils/typed-array.ts"),n=r(/*! ../loader/fragment */"./src/loader/fragment.ts"),s=r(/*! ../demux/id3 */"./src/demux/id3.ts"),a=Math.pow(2,32)-1,o=[].push,l={video:1,audio:2,id3:3,text:4};function d(t){return String.fromCharCode.apply(null,t)}function u(t,e){var r=t[e]<<8|t[e+1];return r<0?65536+r:r}function c(t,e){var r=h(t,e);return r<0?4294967296+r:r}function h(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function f(t,e,r){t[e]=r>>24,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=255&r}function p(t,e){var r=[];if(!e.length)return r;for(var i=t.byteLength,n=0;n<i;){var s=c(t,n),a=s>1?n+s:i;if(d(t.subarray(n+4,n+8))===e[0])if(1===e.length)r.push(t.subarray(n+8,a));else{var l=p(t.subarray(n+8,a),e.slice(1));l.length&&o.apply(r,l)}n=a}return r}function g(t){var e=[],r=t[0],i=8,n=c(t,i);i+=4,i+=0===r?8:16,i+=2;var s=t.length+0,a=u(t,i);i+=2;for(var o=0;o<a;o++){var l=i,d=c(t,l);l+=4;var h=2147483647&d;if(1==(2147483648&d)>>>31)return console.warn("SIDX has hierarchical references (not supported)"),null;var f=c(t,l);l+=4,e.push({referenceSize:h,subsegmentDuration:f,info:{duration:f/n,start:s,end:s+h-1}}),s+=h,i=l+=4}return{earliestPresentationTime:0,timescale:n,version:r,referencesCount:a,references:e}}function v(t){for(var e=[],r=p(t,["moov","trak"]),i=0;i<r.length;i++){var s=r[i],a=p(s,["tkhd"])[0];if(a){var o=a[0],l=0===o?12:20,u=c(a,l),h=p(s,["mdia","mdhd"])[0];if(h){var f=c(h,l=0===(o=h[0])?12:20),g=p(s,["mdia","hdlr"])[0];if(g){var v=d(g.subarray(8,12)),m={soun:n.ElementaryStreamTypes.AUDIO,vide:n.ElementaryStreamTypes.VIDEO}[v];if(m){var y=p(s,["mdia","minf","stbl","stsd"])[0],E=void 0;y&&(E=d(y.subarray(12,16))),e[u]={timescale:f,type:m},e[m]={timescale:f,id:u,codec:E}}}}}}return p(t,["moov","mvex","trex"]).forEach((function(t){var r=c(t,4),i=e[r];i&&(i.default={duration:c(t,12),flags:c(t,20)})})),e}function m(t,e){return p(e,["moof","traf"]).reduce((function(e,r){var i=p(r,["tfdt"])[0],n=i[0],s=p(r,["tfhd"]).reduce((function(e,r){var s=c(r,4),a=t[s];if(a){var o=c(i,4);1===n&&(o*=Math.pow(2,32),o+=c(i,8));var l=o/(a.timescale||9e4);if(isFinite(l)&&(null===e||l<e))return l}return e}),null);return null!==s&&isFinite(s)&&(null===e||s<e)?s:e}),null)||0}function y(t,e){for(var r=0,i=0,s=0,a=p(t,["moof","traf"]),o=0;o<a.length;o++){var l=a[o],d=p(l,["tfhd"])[0],u=e[c(d,4)];if(u){var h=u.default,f=c(d,0)|(null==h?void 0:h.flags),v=null==h?void 0:h.duration;8&f&&(v=c(d,2&f?12:8));for(var m=u.timescale||9e4,y=p(l,["trun"]),T=0;T<y.length;T++)!(r=E(y[T]))&&v&&(r=v*c(y[T],4)),u.type===n.ElementaryStreamTypes.VIDEO?i+=r/m:u.type===n.ElementaryStreamTypes.AUDIO&&(s+=r/m)}}if(0===i&&0===s){for(var _=0,S=p(t,["sidx"]),b=0;b<S.length;b++){var A=g(S[b]);null!=A&&A.references&&(_+=A.references.reduce((function(t,e){return t+e.info.duration||0}),0))}return _}return i||s}function E(t){var e=c(t,0),r=8;1&e&&(r+=4),4&e&&(r+=4);for(var i=0,n=c(t,4),s=0;s<n;s++)256&e&&(i+=c(t,r),r+=4),512&e&&(r+=4),1024&e&&(r+=4),2048&e&&(r+=4);return i}function T(t,e,r){p(e,["moof","traf"]).forEach((function(e){p(e,["tfhd"]).forEach((function(i){var n=c(i,4),s=t[n];if(s){var o=s.timescale||9e4;p(e,["tfdt"]).forEach((function(t){var e=t[0],i=c(t,4);if(0===e)i-=r*o,f(t,4,i=Math.max(i,0));else{i*=Math.pow(2,32),i+=c(t,8),i-=r*o,i=Math.max(i,0);var n=Math.floor(i/(a+1)),s=Math.floor(i%(a+1));f(t,4,n),f(t,8,s)}}))}}))}))}function _(t){var e={valid:null,remainder:null},r=p(t,["moof"]);if(!r)return e;if(r.length<2)return e.remainder=t,e;var n=r[r.length-1];return e.valid=(0,i.sliceUint8)(t,0,n.byteOffset-8),e.remainder=(0,i.sliceUint8)(t,n.byteOffset-8),e}function S(t,e){var r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}function b(t,e){var r=[],i=e.samples,s=e.timescale,a=e.id,o=!1;return p(i,["moof"]).map((function(l){var d=l.byteOffset-8;p(l,["traf"]).map((function(l){var u=p(l,["tfdt"]).map((function(t){var e=t[0],r=c(t,4);return 1===e&&(r*=Math.pow(2,32),r+=c(t,8)),r/s}))[0];return void 0!==u&&(t=u),p(l,["tfhd"]).map((function(u){var f=c(u,4),g=16777215&c(u,0),v=0,m=0!=(16&g),y=0,E=0!=(32&g),T=8;f===a&&(0!=(1&g)&&(T+=8),0!=(2&g)&&(T+=4),0!=(8&g)&&(v=c(u,T),T+=4),m&&(y=c(u,T),T+=4),E&&(T+=4),"video"===e.type&&(o=function(t){if(!t)return!1;var e=t.indexOf("."),r=e<0?t:t.substring(0,e);return"hvc1"===r||"hev1"===r||"dvh1"===r||"dvhe"===r}(e.codec)),p(l,["trun"]).map((function(a){var l=a[0],u=16777215&c(a,0),f=0!=(1&u),p=0,g=0!=(4&u),m=0!=(256&u),E=0,T=0!=(512&u),_=0,S=0!=(1024&u),b=0!=(2048&u),w=0,D=c(a,4),R=8;f&&(p=c(a,R),R+=4),g&&(R+=4);for(var I=p+d,k=0;k<D;k++){if(m?(E=c(a,R),R+=4):E=v,T?(_=c(a,R),R+=4):_=y,S&&(R+=4),b&&(w=0===l?c(a,R):h(a,R),R+=4),e.type===n.ElementaryStreamTypes.VIDEO)for(var O=0;O<_;){var C=c(i,I);A(o,i[I+=4])&&L(i.subarray(I,I+C),o?2:1,t+w/s,r),I+=C,O+=C+4}t+=E/s}})))}))}))})),r}function A(t,e){if(t){var r=e>>1&63;return 39===r||40===r}return 6==(31&e)}function L(t,e,r,i){var n=w(t),a=0;a+=e;for(var o=0,l=0,d=!1,h=0;a<n.length;){o=0;do{if(a>=n.length)break;o+=h=n[a++]}while(255===h);l=0;do{if(a>=n.length)break;l+=h=n[a++]}while(255===h);var f=n.length-a;if(!d&&4===o&&a<n.length){if(d=!0,181===n[a++]){var p=u(n,a);if(a+=2,49===p){var g=c(n,a);if(a+=4,1195456820===g){var v=n[a++];if(3===v){var m=n[a++],y=64&m,E=y?2+3*(31&m):0,T=new Uint8Array(E);if(y){T[0]=m;for(var _=1;_<E;_++)T[_]=n[a++]}i.push({type:v,payloadType:o,pts:r,bytes:T})}}}}}else if(5===o&&l<f){if(d=!0,l>16){for(var S=[],b=0;b<16;b++){var A=n[a++].toString(16);S.push(1==A.length?"0"+A:A),3!==b&&5!==b&&7!==b&&9!==b||S.push("-")}for(var L=l-16,D=new Uint8Array(L),R=0;R<L;R++)D[R]=n[a++];i.push({payloadType:o,pts:r,uuid:S.join(""),userData:(0,s.utf8ArrayToStr)(D),userDataBytes:D})}}else if(l<f)a+=l;else if(l>f)break}}function w(t){for(var e=t.byteLength,r=[],i=1;i<e-2;)0===t[i]&&0===t[i+1]&&3===t[i+2]?(r.push(i+2),i+=2):i++;if(0===r.length)return t;var n=e-r.length,s=new Uint8Array(n),a=0;for(i=0;i<n;a++,i++)a===r[0]&&(a++,r.shift()),s[i]=t[a];return s}function D(t){var e=t[0],r="",i="",n=0,s=0,a=0,o=0,l=0,u=0;if(0===e){for(;"\0"!==d(t.subarray(u,u+1));)r+=d(t.subarray(u,u+1)),u+=1;for(r+=d(t.subarray(u,u+1)),u+=1;"\0"!==d(t.subarray(u,u+1));)i+=d(t.subarray(u,u+1)),u+=1;i+=d(t.subarray(u,u+1)),u+=1,n=c(t,12),s=c(t,16),o=c(t,20),l=c(t,24),u=28}else if(1===e){n=c(t,u+=4);var h=c(t,u+=4),f=c(t,u+=4);for(u+=4,a=Math.pow(2,32)*h+f,Number.isSafeInteger(a)||(a=Number.MAX_SAFE_INTEGER,console.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=c(t,u),l=c(t,u+=4),u+=4;"\0"!==d(t.subarray(u,u+1));)r+=d(t.subarray(u,u+1)),u+=1;for(r+=d(t.subarray(u,u+1)),u+=1;"\0"!==d(t.subarray(u,u+1));)i+=d(t.subarray(u,u+1)),u+=1;i+=d(t.subarray(u,u+1)),u+=1}return{schemeIdUri:r,value:i,timeScale:n,presentationTime:a,presentationTimeDelta:s,eventDuration:o,id:l,payload:t.subarray(u,t.byteLength)}}},"./src/utils/output-filter.ts":
|
|
248
|
-
/*!************************************!*\
|
|
249
|
-
!*** ./src/utils/output-filter.ts ***!
|
|
250
|
-
\************************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>i});var i=function(){function t(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}var e=t.prototype;return e.dispatchCue=function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)},e.newCue=function(t,e,r){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)},e.reset=function(){this.cueRanges=[],this.startTime=null},t}()},"./src/utils/texttrack-utils.ts":
|
|
251
|
-
/*!**************************************!*\
|
|
252
|
-
!*** ./src/utils/texttrack-utils.ts ***!
|
|
253
|
-
\**************************************/(t,e,r)=>{r.r(e),r.d(e,{addCueToTrack:()=>s,clearCurrentCues:()=>a,getCuesInRange:()=>l,removeCuesInRange:()=>o,sendAddTrackEvent:()=>n});var i=r(/*! ./logger */"./src/utils/logger.ts");function n(t,e){var r;try{r=new Event("addtrack")}catch(t){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)}function s(t,e){var r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error("addCue is failed for: "+e)}catch(r){i.logger.debug("[texttrack-utils]: "+r);var n=new self.TextTrackCue(e.startTime,e.endTime,e.text);n.id=e.id,t.addCue(n)}"disabled"===r&&(t.mode=r)}function a(t){var e=t.mode;if("disabled"===e&&(t.mode="hidden"),t.cues)for(var r=t.cues.length;r--;)t.removeCue(t.cues[r]);"disabled"===e&&(t.mode=e)}function o(t,e,r,i){var n=t.mode;if("disabled"===n&&(t.mode="hidden"),t.cues&&t.cues.length>0)for(var s=l(t.cues,e,r),a=0;a<s.length;a++)i&&!i(s[a])||t.removeCue(s[a]);"disabled"===n&&(t.mode=n)}function l(t,e,r){var i=[],n=function(t,e){if(e<t[0].startTime)return 0;var r=t.length-1;if(e>t[r].endTime)return-1;for(var i=0,n=r;i<=n;){var s=Math.floor((n+i)/2);if(e<t[s].startTime)n=s-1;else{if(!(e>t[s].startTime&&i<r))return s;i=s+1}}return t[i].startTime-e<e-t[n].startTime?i:n}(t,e);if(n>-1)for(var s=n,a=t.length;s<a;s++){var o=t[s];if(o.startTime>=e&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}},"./src/utils/time-ranges.ts":
|
|
254
|
-
/*!**********************************!*\
|
|
255
|
-
!*** ./src/utils/time-ranges.ts ***!
|
|
256
|
-
\**********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>i});const i={toString:function(t){for(var e="",r=t.length,i=0;i<r;i++)e+="["+t.start(i).toFixed(3)+","+t.end(i).toFixed(3)+"]";return e}}},"./src/utils/timescale-conversion.ts":
|
|
257
|
-
/*!*******************************************!*\
|
|
258
|
-
!*** ./src/utils/timescale-conversion.ts ***!
|
|
259
|
-
\*******************************************/(t,e,r)=>{function i(t,e,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var n=t*e*r;return i?Math.round(n):n}function n(t,e,r,n){return void 0===r&&(r=1),void 0===n&&(n=!1),i(t,e,1/r,n)}function s(t,e){return void 0===e&&(e=!1),i(t,1e3,1/9e4,e)}function a(t,e){return void 0===e&&(e=1),i(t,9e4,1/e)}r.r(e),r.d(e,{toMpegTsClockFromTimescale:()=>a,toMsFromMpegTsClock:()=>s,toTimescaleFromBase:()=>i,toTimescaleFromScale:()=>n})},"./src/utils/typed-array.ts":
|
|
260
|
-
/*!**********************************!*\
|
|
261
|
-
!*** ./src/utils/typed-array.ts ***!
|
|
262
|
-
\**********************************/(t,e,r)=>{function i(t,e,r){return Uint8Array.prototype.slice?t.slice(e,r):new Uint8Array(Array.prototype.slice.call(t,e,r))}r.r(e),r.d(e,{sliceUint8:()=>i})},"./src/utils/vttcue.ts":
|
|
263
|
-
/*!*****************************!*\
|
|
264
|
-
!*** ./src/utils/vttcue.ts ***!
|
|
265
|
-
\*****************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>i});const i=function(){if("undefined"!=typeof self&&self.VTTCue)return self.VTTCue;var t=["","lr","rl"],e=["start","middle","end","left","right"];function r(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;var r=e.toLowerCase();return!!~t.indexOf(r)&&r}function i(t){return r(e,t)}function n(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i<e;i++)r[i-1]=arguments[i];for(var n=1;n<arguments.length;n++){var s=arguments[n];for(var a in s)t[a]=s[a]}return t}function s(e,s,a){var o=this,l={enumerable:!0};o.hasBeenReset=!1;var d="",u=!1,c=e,h=s,f=a,p=null,g="",v=!0,m="auto",y="start",E=50,T="middle",_=50,S="middle";Object.defineProperty(o,"id",n({},l,{get:function(){return d},set:function(t){d=""+t}})),Object.defineProperty(o,"pauseOnExit",n({},l,{get:function(){return u},set:function(t){u=!!t}})),Object.defineProperty(o,"startTime",n({},l,{get:function(){return c},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");c=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",n({},l,{get:function(){return h},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");h=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",n({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",n({},l,{get:function(){return p},set:function(t){p=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",n({},l,{get:function(){return g},set:function(e){var i=function(e){return r(t,e)}(e);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");g=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},l,{get:function(){return v},set:function(t){v=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",n({},l,{get:function(){return m},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");m=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",n({},l,{get:function(){return y},set:function(t){var e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",n({},l,{get:function(){return E},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},l,{get:function(){return T},set:function(t){var e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return _},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");_=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return S},set:function(t){var e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");S=e,this.hasBeenReset=!0}})),o.displayState=void 0}return s.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},s}()},"./src/utils/vttparser.ts":
|
|
266
|
-
/*!********************************!*\
|
|
267
|
-
!*** ./src/utils/vttparser.ts ***!
|
|
268
|
-
\********************************/(t,e,r)=>{r.r(e),r.d(e,{VTTParser:()=>h,fixLineBreaks:()=>c,parseTimeStamp:()=>s});var i=r(/*! ./vttcue */"./src/utils/vttcue.ts"),n=function(){function t(){}return t.prototype.decode=function(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))},t}();function s(t){function e(t,e,r,i){return 3600*(0|t)+60*(0|e)+(0|r)+parseFloat(i||0)}var r=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?e(r[2],r[3],0,r[4]):e(r[1],r[2],r[3],r[4]):null}var a=function(){function t(){this.values=Object.create(null)}var e=t.prototype;return e.set=function(t,e){this.get(t)||""===e||(this.values[t]=e)},e.get=function(t,e,r){return r?this.has(t)?this.values[t]:e[r]:this.has(t)?this.values[t]:e},e.has=function(t){return t in this.values},e.alt=function(t,e,r){for(var i=0;i<r.length;++i)if(e===r[i]){this.set(t,e);break}},e.integer=function(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))},e.percent=function(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){var r=parseFloat(e);if(r>=0&&r<=100)return this.set(t,r),!0}return!1},t}();function o(t,e,r,i){var n=i?t.split(i):[t];for(var s in n)if("string"==typeof n[s]){var a=n[s].split(r);2===a.length&&e(a[0],a[1])}}var l=new i.default(0,0,""),d="middle"===l.align?"middle":"center";function u(t,e,r){var i=t;function n(){var e=s(t);if(null===e)throw new Error("Malformed timestamp: "+i);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function u(){t=t.replace(/^\s+/,"")}if(u(),e.startTime=n(),u(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);t=t.slice(3),u(),e.endTime=n(),u(),function(t,e){var i=new a;o(t,(function(t,e){var n;switch(t){case"region":for(var s=r.length-1;s>=0;s--)if(r[s].id===e){i.set(t,r[s].region);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":n=e.split(","),i.integer(t,n[0]),i.percent(t,n[0])&&i.set("snapToLines",!1),i.alt(t,n[0],["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",d,"end"]);break;case"position":n=e.split(","),i.percent(t,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",d,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",d,"end","left","right"])}}),/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===l.line&&(n=-1),e.line=n,e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100),e.align=i.get("align",d);var s=i.get("position","auto");"auto"===s&&50===l.position&&(s="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=s}(t,e)}function c(t){return t.replace(/<br(?: \/)?>/gi,"\n")}var h=function(){function t(){this.state="INITIAL",this.buffer="",this.decoder=new n,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var e=t.prototype;return e.parse=function(t){var e=this;function r(){var t=e.buffer,r=0;for(t=c(t);r<t.length&&"\r"!==t[r]&&"\n"!==t[r];)++r;var i=t.slice(0,r);return"\r"===t[r]&&++r,"\n"===t[r]&&++r,e.buffer=t.slice(r),i}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{var n="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;var s=(n=r()).match(/^()?WEBVTT([ \t].*)?$/);if(!s||!s[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}for(var a=!1;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(a?a=!1:n=r(),e.state){case"HEADER":/:/.test(n)?o(n,(function(t,e){}),/:/):n||(e.state="ID");continue;case"NOTE":n||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){e.state="NOTE";break}if(!n)continue;if(e.cue=new i.default(0,0,""),e.state="CUE",-1===n.indexOf("--\x3e")){e.cue.id=n;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{u(n,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":var l=-1!==n.indexOf("--\x3e");if(!n||l&&(a=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=n;continue;case"BADCUE":n||(e.state="ID")}}}catch(t){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this},e.flush=function(){try{if((this.cue||"HEADER"===this.state)&&(this.buffer+="\n\n",this.parse()),"INITIAL"===this.state||"BADWEBVTT"===this.state)throw new Error("Malformed WebVTT signature.")}catch(t){this.onparsingerror&&this.onparsingerror(t)}return this.onflush&&this.onflush(),this},t}()},"./src/utils/webvtt-parser.ts":
|
|
269
|
-
/*!************************************!*\
|
|
270
|
-
!*** ./src/utils/webvtt-parser.ts ***!
|
|
271
|
-
\************************************/(t,e,r)=>{r.r(e),r.d(e,{generateCueId:()=>c,parseWebVTT:()=>h});var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ./vttparser */"./src/utils/vttparser.ts"),s=r(/*! ../demux/id3 */"./src/demux/id3.ts"),a=r(/*! ./timescale-conversion */"./src/utils/timescale-conversion.ts"),o=r(/*! ../remux/mp4-remuxer */"./src/remux/mp4-remuxer.ts"),l=/\r\n|\n\r|\n|\r/g,d=function(t,e,r){return void 0===r&&(r=0),t.slice(r,r+e.length)===e},u=function(t){for(var e=5381,r=t.length;r;)e=33*e^t.charCodeAt(--r);return(e>>>0).toString()};function c(t,e,r){return u(t.toString())+u(e.toString())+u(r)}function h(t,e,r,u,h,f,p,g){var v,m=new n.VTTParser,y=(0,s.utf8ArrayToStr)(new Uint8Array(t)).trim().replace(l,"\n").split("\n"),E=[],T=(0,a.toMpegTsClockFromTimescale)(e,r),_="00:00.000",S=0,b=0,A=!0;m.oncue=function(t){var e=u[h],r=u.ccOffset,i=(S-T)/9e4;null!=e&&e.new&&(void 0!==b?r=u.ccOffset=e.start:function(t,e,r){var i=t[e],n=t[i.prevCC];if(!n||!n.new&&i.new)return t.ccOffset=t.presentationOffset=i.start,void(i.new=!1);for(;null!==(s=n)&&void 0!==s&&s.new;){var s;t.ccOffset+=i.start-n.start,i.new=!1,n=t[(i=n).prevCC]}t.presentationOffset=r}(u,h,i)),i&&(r=i-u.presentationOffset);var n=t.endTime-t.startTime,s=(0,o.normalizePts)(9e4*(t.startTime+r-b),9e4*f)/9e4;t.startTime=Math.max(s,0),t.endTime=Math.max(s+n,0);var a=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(a)),t.id||(t.id=c(t.startTime,t.endTime,a)),t.endTime>0&&E.push(t)},m.onparsingerror=function(t){v=t},m.onflush=function(){v?g(v):p(E)},y.forEach((function(t){if(A){if(d(t,"X-TIMESTAMP-MAP=")){A=!1,t.slice(16).split(",").forEach((function(t){d(t,"LOCAL:")?_=t.slice(6):d(t,"MPEGTS:")&&(S=parseInt(t.slice(7)))}));try{b=function(t){var e=parseInt(t.slice(-3)),r=parseInt(t.slice(-6,-4)),n=parseInt(t.slice(-9,-7)),s=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!((0,i.isFiniteNumber)(e)&&(0,i.isFiniteNumber)(r)&&(0,i.isFiniteNumber)(n)&&(0,i.isFiniteNumber)(s)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+t);return e+=1e3*r,e+=6e4*n,e+=36e5*s}(_)/1e3}catch(t){v=t}return}""===t&&(A=!1)}m.parse(t+"\n")})),m.flush()}},"./src/utils/xhr-loader.ts":
|
|
272
|
-
/*!*********************************!*\
|
|
273
|
-
!*** ./src/utils/xhr-loader.ts ***!
|
|
274
|
-
\*********************************/(t,e,r)=>{r.r(e),r.d(e,{default:()=>a});var i=r(/*! ../utils/logger */"./src/utils/logger.ts"),n=r(/*! ../loader/load-stats */"./src/loader/load-stats.ts"),s=/^age:\s*[\d.]+\s*$/m;const a=function(){function t(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=t?t.xhrSetup:null,this.stats=new n.LoadStats,this.retryDelay=0}var e=t.prototype;return e.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null},e.abortInternal=function(){var t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))},e.abort=function(){var t;this.abortInternal(),null!==(t=this.callbacks)&&void 0!==t&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},e.load=function(t,e,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=r,this.retryDelay=e.retryDelay,this.loadInternal()},e.loadInternal=function(){var t=this.config,e=this.context;if(t){var r=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0;var n=this.xhrSetup;try{if(n)try{n(r,e.url)}catch(t){r.open("GET",e.url,!0),n(r,e.url)}r.readyState||r.open("GET",e.url,!0);var s=this.context.headers;if(s)for(var a in s)r.setRequestHeader(a,s[a])}catch(t){return void this.callbacks.onError({code:r.status,text:t.message},e,r)}e.rangeEnd&&r.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),r.onreadystatechange=this.readystatechange.bind(this),r.onprogress=this.loadprogress.bind(this),r.responseType=e.responseType,self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),t.timeout),r.send()}},e.readystatechange=function(){var t=this.context,e=this.loader,r=this.stats;if(t&&e){var n=e.readyState,s=this.config;if(!r.aborted&&n>=2)if(self.clearTimeout(this.requestTimeout),0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start)),4===n){e.onreadystatechange=null,e.onprogress=null;var a=e.status,o="arraybuffer"===e.responseType;if(a>=200&&a<300&&(o&&e.response||null!==e.responseText)){var l,d;if(r.loading.end=Math.max(self.performance.now(),r.loading.first),d=o?(l=e.response).byteLength:(l=e.responseText).length,r.loaded=r.total=d,!this.callbacks)return;var u=this.callbacks.onProgress;if(u&&u(r,t,l,e),!this.callbacks)return;var c={url:e.responseURL,data:l};this.callbacks.onSuccess(c,r,t,e)}else r.retry>=s.maxRetry||a>=400&&a<499?(i.logger.error(a+" while loading "+t.url),this.callbacks.onError({code:a,text:e.statusText},t,e)):(i.logger.warn(a+" while loading "+t.url+", retrying in "+this.retryDelay+"..."),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,s.maxRetryDelay),r.retry++)}else self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout)}},e.loadtimeout=function(){i.logger.warn("timeout while loading "+this.context.url);var t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))},e.loadprogress=function(t){var e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)},e.getCacheAge=function(){var t=null;if(this.loader&&s.test(this.loader.getAllResponseHeaders())){var e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t},t}()},"./node_modules/eventemitter3/index.js":
|
|
275
|
-
/*!*********************************************!*\
|
|
276
|
-
!*** ./node_modules/eventemitter3/index.js ***!
|
|
277
|
-
\*********************************************/t=>{var e=Object.prototype.hasOwnProperty,r="~";function i(){}function n(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function s(t,e,i,s,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new n(i,s||t,a),l=r?r+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0==--t._eventsCount?t._events=new i:delete t._events[e]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),o.prototype.eventNames=function(){var t,i,n=[];if(0===this._eventsCount)return n;for(i in t=this._events)e.call(t,i)&&n.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(t)):n},o.prototype.listeners=function(t){var e=r?r+t:t,i=this._events[e];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,s=i.length,a=new Array(s);n<s;n++)a[n]=i[n].fn;return a},o.prototype.listenerCount=function(t){var e=r?r+t:t,i=this._events[e];return i?i.fn?1:i.length:0},o.prototype.emit=function(t,e,i,n,s,a){var o=r?r+t:t;if(!this._events[o])return!1;var l,d,u=this._events[o],c=arguments.length;if(u.fn){switch(u.once&&this.removeListener(t,u.fn,void 0,!0),c){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,e),!0;case 3:return u.fn.call(u.context,e,i),!0;case 4:return u.fn.call(u.context,e,i,n),!0;case 5:return u.fn.call(u.context,e,i,n,s),!0;case 6:return u.fn.call(u.context,e,i,n,s,a),!0}for(d=1,l=new Array(c-1);d<c;d++)l[d-1]=arguments[d];u.fn.apply(u.context,l)}else{var h,f=u.length;for(d=0;d<f;d++)switch(u[d].once&&this.removeListener(t,u[d].fn,void 0,!0),c){case 1:u[d].fn.call(u[d].context);break;case 2:u[d].fn.call(u[d].context,e);break;case 3:u[d].fn.call(u[d].context,e,i);break;case 4:u[d].fn.call(u[d].context,e,i,n);break;default:if(!l)for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];u[d].fn.apply(u[d].context,l)}}return!0},o.prototype.on=function(t,e,r){return s(this,t,e,r,!1)},o.prototype.once=function(t,e,r){return s(this,t,e,r,!0)},o.prototype.removeListener=function(t,e,i,n){var s=r?r+t:t;if(!this._events[s])return this;if(!e)return a(this,s),this;var o=this._events[s];if(o.fn)o.fn!==e||n&&!o.once||i&&o.context!==i||a(this,s);else{for(var l=0,d=[],u=o.length;l<u;l++)(o[l].fn!==e||n&&!o[l].once||i&&o[l].context!==i)&&d.push(o[l]);d.length?this._events[s]=1===d.length?d[0]:d:a(this,s)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=r?r+t:t,this._events[e]&&a(this,e)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,t.exports=o},"./node_modules/url-toolkit/src/url-toolkit.js":
|
|
278
|
-
/*!*****************************************************!*\
|
|
279
|
-
!*** ./node_modules/url-toolkit/src/url-toolkit.js ***!
|
|
280
|
-
\*****************************************************/function(t){var e,r,i,n,s;e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,s={buildAbsoluteURL:function(t,e,i){if(i=i||{},t=t.trim(),!(e=e.trim())){if(!i.alwaysNormalize)return t;var n=s.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");return n.path=s.normalizePath(n.path),s.buildURLFromParts(n)}var a=s.parseURL(e);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return i.alwaysNormalize?(a.path=s.normalizePath(a.path),s.buildURLFromParts(a)):e;var o=s.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var d={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(d.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var u=o.path,c=u.substring(0,u.lastIndexOf("/")+1)+a.path;d.path=s.normalizePath(c)}else d.path=o.path,a.params||(d.params=o.params,a.query||(d.query=o.query));return null===d.path&&(d.path=i.alwaysNormalize?s.normalizePath(a.path):a.path),s.buildURLFromParts(d)},parseURL:function(t){var r=e.exec(t);return r?{scheme:r[1]||"",netLoc:r[2]||"",path:r[3]||"",params:r[4]||"",query:r[5]||"",fragment:r[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(i,"");t.length!==(t=t.replace(n,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=s}},e={};function r(i){var n=e[i];if(void 0!==n)return n.exports;var s=e[i]={exports:{}};return t[i].call(s.exports,s,s.exports,r),s.exports}r.m=t,r.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return r.d(e,{a:e}),e},r.d=(t,e)=>{for(var i in e)r.o(e,i)&&!r.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var i=r("./src/hls.ts");return i=i.default})(),t.exports=r())})));var Li=Object.freeze({__proto__:null,ATTACHED:"hls:attached"});const wi="com.widevine.alpha";const Di="application/vnd.apple.mpegURL",Ri=[Di,"application/x-mpegurl"],Ii=document.createElement("video").canPlayType(Di);function ki({src:t="",type:e="",drm:r},i){const n=(null==i?void 0:i.hls)||{},s="native"in n&&n.native;return(!Ii||!s)&&(!(r&&!Object.keys(r).find(t=>{return e=t,[wi].filter((function(t){return t===e})).length;var e}))&&(!(!e||!Ri.includes(e))||function(t){const{pathname:e}=gr(t);return e.endsWith(".m3u8")}(t)))}const Oi=window&&window.Hls||Ai;var Ci="audio:set",Pi="audio:update",xi="audio:tracks";var Mi=Object.assign(Object.assign({},{"http.404":"the video was not found","http.403":"access to this video was denied","http.410":"the video no longer exists","http.live.404":"stream is offline","http.0":"no internet connection detected"}),{keySystemNoKeys:"no keys",keySystemNoAccess:"no access to key system",keySystemNoSession:"no session for key system",keySystemLicenseRequestFailed:"license request failed",keyLoadError:"decrypt key load failed",keyLoadTimeOut:"decrypt key load timed outs"});var Ni;!function(t){t[t.FRAGMENT_ERRORS=0]="FRAGMENT_ERRORS",t[t.STALE_MANIFEST=1]="STALE_MANIFEST"}(Ni||(Ni={}));const Fi=Pe("hls:failover");class FailoverLoaderController{constructor(){this.playlistCounts={},this.fragmentFailures={},this.ttlMilliseconds=3e3}setHls(t){this.hls=t}reset(){return this.playlistCounts={},this.fragmentFailures={},this}failover(t){var e;this.reset();const r=this.hls;if(!r)return;const i=r.levels[r.currentLevel];if(!i)return;if(i.url.length<2)return;const n=r.levels[r.currentLevel].details;r.levelController.redundantFailover(r.currentLevel),null===(e=r.media)||void 0===e||e.dispatchEvent(new CustomEvent("hls/failover",{detail:{reason:t,from:null==n?void 0:n.url}}))}currentLevel(){var t;return null===(t=this.hls)||void 0===t?void 0:t.levels[this.hls.currentLevel]}nextTTL(){var t;const e=Date.now()+this.ttlMilliseconds,r=this.currentLevel();if(!r)return e;const i=null===(t=r.details)||void 0===t?void 0:t.averagetargetduration;return i?Date.now()+500*i:e}ensurePlaylistUpdating(t,e){this.playlistCounts[t]||(this.playlistCounts[t]={checksum:e,count:0,ttl:this.nextTTL()});const r=this.playlistCounts[t];Date.now()<r.ttl||(r.count=r.checksum===e?r.count+1:0,r.ttl=this.nextTTL(),r.checksum=e,r.count<3||(Fi(`${t} / no change in ${r.count} tries`,this.playlistCounts),this.failover(Ni.STALE_MANIFEST)))}trackFragmentError(t){const e=this.fragmentFailures[t]||0;this.fragmentFailures[t]=e+1,this.fragmentFailures[t]>2&&this.failover(Ni.FRAGMENT_ERRORS)}createPlaylistLoader(t){const e=this;return class extends Ai.DefaultConfig.loader{load(r,i,n){const s=n.onSuccess;n.onSuccess=({data:i,url:n},...a)=>{"manifest"===(null==r?void 0:r.type)&&(t.manifest=i),e.ensurePlaylistUpdating(n,i),s({data:i,url:n},...a)},super.load(r,i,n)}}}createFragmentLoader(){const t=this;return class extends Ai.DefaultConfig.loader{load(e,r,i){const n=i.onError;i.onError=e=>{t.trackFragmentError(e.url),n(...arguments)},super.load(e,r,i)}}}}const Ui=Pe("hls");function Bi(t,e,r,n){if(!t.reaper||!r.src)return;t.hls&&t.hls.destroy();const s="live"in e==0,a={is_audio_only:!1,fragDuration:-1,media_recovers:0,audio_swaps:0};if(r.drm&&!pr()&&"localhost"!==location.hostname&&"127.0.0.1"!==location.hostname)return t.emit(i,{message:"Secure page required for DRM"});const o=new FailoverLoaderController,l=function(t){return Object.assign(Object.assign({autoStartLoad:!1,levelLoadingMaxRetry:1},t.hls),{startPosition:t.start_time||-1})}(e);l.renderTextTracksNatively=!1,l.pLoader=o.createPlaylistLoader(n),l.fLoader=o.createFragmentLoader();const d=t.hls=new Oi(l);o.setHls(d),d.subtitleDisplay=!1,d.attachMedia(t),d.loadSource(r.src),t.emit("hls:attached",{hls:d}),function(t,e){t.on(Ai.Events.AUDIO_TRACKS_UPDATED,(function(t,r){e.emit(xi,r.audioTracks)})),t.on(Ai.Events.AUDIO_TRACK_SWITCHING,(function(t,r){e.emit(Pi,r)})),t.on(Ai.Events.MANIFEST_PARSED,(function(t,r){r.audioTracks&&e.emit(xi,r.audioTracks)})),t.on(Ai.Events.LEVEL_SWITCHED,(function(r,i){const n=t.levels[i.level];n&&e.emit(xi,t.audioTracks.filter((function(t){return t.groupId&&~(n.audioGroupIds||[]).indexOf(t.groupId)})))}))}(d,t),function(t,e){t.on(Ai.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(r,i)=>{t.subtitleTracks.length||e.emit("tracks:text:all",i)}),t.on(Ai.Events.SUBTITLE_TRACKS_UPDATED,(t,r)=>{e.emit("tracks:text:all",{tracks:r.subtitleTracks.map(t=>Object.assign({},{subtitleTrack:t}))})}),t.on(Ai.Events.CUES_PARSED,(t,r)=>{e.emit("cues:parsed",r)})}(d,t);const u=function(t){var e;const r=null===(e=t.data)||void 0===e?void 0:e.level;"number"==typeof r&&(d.levels[r]||-1===r?d.nextLevel=r:console.error(new Error("skipping invalid quality: "+t.data)))},c=function(t){var e;const r=null===(e=t.data)||void 0===e?void 0:e.id;"number"==typeof r&&r!=d.audioTrack&&setTimeout((function(){d.audioTrack=r}),0)};t.on("quality:set",u),t.on(Ci,c),t.on("src",(function(){t.off("quality:set",u),t.off(Ci,c),t.hls&&(t.hls.destroy(),delete t.hls,n.manifest=void 0)}));let h=0;t.on(i,e=>{var r;++h,h>=5||!t.hls||(null===(r=null==t?void 0:t.error)||void 0===r?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE||(e.preventDefault(),d.config.autoStartLoad=!0,d.recoverMediaError())}),t.on(_,()=>h=0),t.on("beforeplay",()=>{if(t.hls&&!t.hasState("is-casting")&&!t.hasState(tt)&&"none"===e.preload&&!e.autoplay)return t.hls.levels.length?Gi(t,e.start_time||-1):void t.hls.once(Oi.Events.MANIFEST_PARSED,()=>{setTimeout(()=>{Gi(t,e.start_time||-1)},0)})}),t.on("tracks:video:select",(function(e){var r;const i=e.detail.track,n=null===(r=t.tracks)||void 0===r?void 0:r.find(t=>t.selected&&t!==i),s=t.hls;if(!n||!i||!s)return;n.selected=!1;const a=i.data.slice(0).map(t=>(t.details=void 0,t));s.stopLoad(),s.levelController._levels=s.streamController.levels=a,s.currentLevel=-1,s.levelController.currentLevelIndex=-1,t.emit("qualities",Hi(a)),t.hasState(rt)&&!t.hasState(et)||s.startLoad()})),t.on("audioonlysource",(function(){a.is_audio_only=!0})),t.on(w,(function(){d&&d.destroy()})),t.on("remotesession:started",()=>{t.hls&&t.hls.stopLoad()}),t.on("remotesession:ended",()=>{t.hls&&Gi(t)}),t.on(k,i=>{if(t.hls){if(i.preventDefault(),r.src&&d.loadSource(t.original_src),e.autoplay)return t.togglePlay(!0);t.setState(at,!1),t.emit("retry/done")}}),s&&d.on(Oi.Events.LEVEL_LOADED,(function(e,r){t.setOpts({live:r.details.live})})),d.on(Oi.Events.MANIFEST_PARSED,(function(i,s){const a=Hi(s.levels);t.emit("qualities",a),t.emit("parse:video:tracks",{url:r.src,manifest:n.manifest}),function(t,e,r){var i,n;if(!t.hls)return;Ui("Initializer::maybe_start_load_with_quality (start_quality, preload): (%d, %s)",e.start_quality,e.preload),void 0!==e.start_quality&&(bt.HIGH&e.start_quality&&(t.hls.startLevel=r[0].level),bt.LOW&e.start_quality&&(t.hls.startLevel=r[r.length-1].level),bt.MEDIUM&e.start_quality&&(t.hls.startLevel=r[Math.ceil(r.length/2)-1].level));const s=(null===(i=e.hls)||void 0===i?void 0:i.maxBufferSize)||1024,a=(null===(n=e.hls)||void 0===n?void 0:n.maxBufferLength)||30;Ui("Setting maxBufferSize to %d",s),t.hls.config.maxBufferSize=s,"metadata"===e.preload&&Ui("preload === metadata, setting maxBufferLength to 1sec");t.hls.config.maxBufferLength="metadata"===e.preload?1:a,t.once(E,()=>{Ui("Playback started, set maxBufferLenght to %d",a),t.hls&&(t.hls.config.maxBufferLength=a)}),("none"!==e.preload||e.autoplay)&&Gi(t,e.start_time||-1)}(t,e,a.slice(0,-1));const o=a.find(t=>!!t.videoCodec);o||t.emit("audioonlysource"),!t.opt("ratio")&&o&&0!=o.width&&0!=o.height&&t.setOpts({ratio:o.width+":"+o.height})})),d.on(Oi.Events.INIT_PTS_FOUND,(function(t,e){a.fragDuration=e.frag.duration})),d.on(Oi.Events.ERROR,(function(e,r){!function(t,e,r){var n,s,a,o;if(0==t.reaper)return;if(0==e.fatal)return;switch(e.type){case Oi.ErrorTypes.MEDIA_ERROR:return Ui("recovering from "+e.type),r.media_recovers+5e3>Date.now()&&0==r.audio_swaps?(null===(n=t.hls)||void 0===n||n.swapAudioCodec(),Ui(`calling swapAudioCodec() : {count=${r.audio_swaps}}`),r.audio_swaps++,r.media_recovers=Date.now(),null===(s=t.hls)||void 0===s?void 0:s.recoverMediaError()):(r.media_recovers=Date.now(),r.audio_swaps=0,null===(a=t.hls)||void 0===a?void 0:a.recoverMediaError());case Oi.ErrorTypes.NETWORK_ERROR:return function(t,e){var r;const n=(null===(r=e.networkDetails)||void 0===r?void 0:r.status)||e.details;let s=t.opts.live?"http.live.":"http.";s+=n.toString();const a=t.i18n("error."+s,Mi[s]||"an error occurred while loading this video");t.emit(i,{code:s,message:a,fatal:!0})}(t,e);case Oi.ErrorTypes.KEY_SYSTEM_ERROR:return function(t,e){var r;t.emit(i,{fatal:!0,message:Mi[e.details]||"an error occurred while accessing this video"}),null===(r=t.hls)||void 0===r||r.destroy()}(t,e);default:null===(o=t.hls)||void 0===o||o.destroy()}}(t,r,a)})),d.on(Oi.Events.LEVEL_PTS_UPDATED,(function(e,r){var i;if("video"!==r.type&&(!a.is_audio_only||"audio"!==r.type))return;const n=null===(i=null==r?void 0:r.details)||void 0===i?void 0:i.fragments;if(!n)return;const s=n[0].start||0,o=(d.liveSyncPosition||n[n.length-1].start)+n[n.length-1].duration;t.emit("dvr/window",o-s)})),d.on(Oi.Events.LEVEL_SWITCHING,(e,r)=>{const i=d.levels[d.currentLevel],n=d.levels[r.level];t.emit("qualitychange",{before:i,after:n,kind:"hls"})});const f=t.opt("start_time");f&&t.once(p,(function(){t.currentTime=f}))}function Gi(t,e){var r;!t.hasState(tt)&&t.setState(et,!0),null===(r=t.hls)||void 0===r||r.startLoad(e)}function Hi(t){const e=t.map((t,e)=>({level:e,text:t.name||t.width+"",width:t.width,height:t.height,videoCodec:t.videoCodec||""})).sort((t,e)=>e.width-t.width);return t.length>1&&t.every(t=>void 0!==t.bitrate)&&e.push({text:"AUTO",level:-1,width:0,height:0,videoCodec:""}),e}class HLS{init(){}onload(t,e,r,i){Bi(r,t,i,this)}wants(t,e,r){return Ai.isSupported()&&ki(e,r)}}HLS.events=Li,HLS.version=Ai.version,HLS.failover={Reasons:Ni},ue(window,HLS);const ji=t=>"object"==typeof t&&null!==t&&!Array.isArray(t),Vi=(...t)=>t.reduce((t,e)=>ji(e)?(Object.keys(e).forEach(r=>{if(ji(t[r])&&ji(e[r]))return t[r]=Vi(t[r],e[r]);t[r]=e[r]}),t):t,{});class Pipe{constructor(t){this.data=t}static of(t){return new Pipe(t)}static maybe(t,e,...r){return null==t?t:e.apply(t,[t,...r])}tap(t,...e){return t.apply(this,[this.data,...e]),new Pipe(this.data)}fmap(t,...e){const r=t.apply(this,[this.data,...e]);return new Pipe(r)}unwrap(){return this.data}}function Ki(t){return fetch(t).then(t=>t.json())}function qi(){let t=[].join.call(arguments,"/");return"/"!==t[0]&&(t="/"+t),Wi()+"/web/public/native/config"+t}const Wi=()=>"https://ljsp.lwcdn.com";function zi(t){return~t.indexOf("/")?t:"/media/"+t}var Yi={404:"media not found",402:"invalid subscription",400:"bad request",415:"unsupported media type"};function Xi(t,e){var r,i;e="object"==typeof e?e:{};const n={title:null===(r=null==t?void 0:t.metadata)||void 0===r?void 0:r.title,description:null===(i=null==t?void 0:t.metadata)||void 0===i?void 0:i.description},s={ima:{parameters:function({media_id:t,duration:e,title:r,tags:i,category_name:n,ad_keywords:s}){return{ad_keywords:s||"",media_id:t||"",category:n||"",media_name:r||"",media_tags:i||"",media_duration:e||-1}}((null==t?void 0:t.metadata)||{})}},a=e.embed||{};return delete a.src,Vi(s,n,t,(delete(o=e).src,delete o.metadata,delete o.title,delete o.description,delete o.duration,delete o.poster,o),a);var o}const Qi=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/;function $i(t){return"object"==typeof t&&"ovp/base64"==t.type}function Zi(t,e){return function(t,e){return!t.startsWith("blob:")&&(!(~t.indexOf(".")||!Qi.test(t))&&(e.type="video/ovp",!0))}(t,e)||$i(e)}function Ji(t){try{return function(t){return null===t?{}:JSON.parse(t)}(decodeURIComponent(atob(t).split("").map((function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)})).join("")))}catch(t){return{err:t.message}}}function tn(t){const e=t.split(/[^0-9]/).map(t=>parseInt(t,10));return Date.UTC(e[0],e[1]-1,e[2],e[3],e[4],e[5])}function en(t){return t.live}var rn=Object.freeze({__proto__:null,OVP_ERROR:"ovp:error",OVP_MEDIA_REQUEST_START:"ovp:request:start",OVP_MEDIA_REQUEST_COMPLETE:"ovp:request:media:complete",OVP_PLAYLIST_REQUEST_COMPLETE:"ovp:request:playlist:complete",LIVE_COUNTDOWN_TICK:"ovp:live:countdown:tick",LIVE_COUNTDOWN_START:"ovp:live:countdown:start",LIVE_COUNTDOWN_COMPLETE:"ovp:live:countdown:complete",OVP_MEDIA_CHANGED:"ovp:media:changed",OVP_REALTIME_MESSAGE:"ovp:message:realtime"});function nn(t,e){const r=null==e?void 0:e.src;if($i(e))return function(t,e){const r=Ji(e.src||"");if(function(t){return"string"==typeof t.err}(r))return console.error(r.err);sn(t,r)}(t,e);r&&(t.setState(ft,!0),Pipe.of(r).fmap(zi).fmap(qi).fmap(t=>fetch(t)).fmap(e=>e.then(t=>Promise.all([t.status,t.json()])).then(([e,r])=>200==e?sn(t,r):function(t,e){return t.setState(ft,!1),e.message?t.emit("ovp:error",e):e.status?t.emit("ovp:error",new Error(Yi[e.status])):t.emit("ovp:error",e)}(t,r))))}function sn(t,e){return t.emit("ovp:media:changed",e),function(t){return Array.isArray(t.playlist)}(e)?function(t,e){t.emit("ovp:request:playlist:complete",function(t,e){const r=Object.assign({},t),i=(null==t?void 0:t.playlist)||{},n=Vi(e,i),s=((null==n?void 0:n.playlist)||[]).map(t=>{e.ima&&Object.assign(t,{ima:e.ima});const i=Xi(t,r);return delete i.playlist,i});return delete n.ima,Object.assign(n,{playlist:s})}(t.opts,e))}(t,e):en(e)?function(t,e){var r,i;const n=(null===(r=null==e?void 0:e.metadata)||void 0===r?void 0:r.live_start_time)||(null===(i=null==e?void 0:e.metadata)||void 0===i?void 0:i.starttime);n&&(e.live_start_time=Pipe.of(n).fmap(tn).unwrap());t.emit("ovp:live:countdown:start",Pipe.of(e).fmap(Xi,t.opts).unwrap())}(t,e):function(t,e){t.emit("ovp:request:media:complete",Pipe.of(e).fmap(Xi,t.opts).unwrap())}(t,e)}const an={};function on(t,e,r){"object"!=typeof an[e]&&(an[e]=r);const i=t.opts,n=(null==i?void 0:i.metadata)||{};n.player_id=e,i.metadata=n,r.title&&delete r.title,r.description&&delete r.description;const s=Object.assign(i,r);t.setOpts(s),r.autoplay&&t.togglePlay(!0)}let ln=!1;function dn(t,e,r){un()||Pipe.of("recommendation").fmap(qi,e,r).fmap(Ki).fmap(e=>e.then(e=>function(t,e){const r=e.playlist;if(t.opts.recommendations=r,!r.length)return;t.emit("recommendationsready",{playlist:r.map((function(t){var e,r;return{poster:t.poster,src:t.src,title:null===(e=null==t?void 0:t.metadata)||void 0===e?void 0:e.title,description:null===(r=null==t?void 0:t.metadata)||void 0===r?void 0:r.description,metadata:t.metadata||{},chapters:t.chapters,thumbnails:t.thumbnails,subtitles:t.subtitles}}))})}(t,e)).catch(cn))}function un(){return ln}function cn(t){ln=!0,console.error("Failed to load recommendations: %j",t)}function hn(t){const e=Date.now()-(t.server_time_offset||0);return Math.floor(((t.live_start_time||0)-e)/1e3)}function fn(t,e){let r=0;function i(){const i=hn(e);if(i<0||isNaN(i)||0===t.reaper||void 0===e.live_start_time)return clearInterval(r),function(t,e,r){t.emit("ovp:live:countdown:complete");const i=Ht(t,Q);if(i&&i.remove(),t.root.classList.remove("is-livecountdown"),r)return t.setState(ft,!1);t.emit("ovp:request:media:complete",e)}(t,e,void 0===e.live_start_time);!function(t,e,r,i){r.classList.add("is-livecountdown"),e.emit("ovp:live:countdown:tick",{remaining_time:pn(i+1)}),e.hasState(rt)||e.setState(rt,!0)}(0,t,t.root,i)}var n;n=e,jr().then(t=>Object.assign(n,{server_time_offset:t})),i(),r=setInterval(i,250)}function pn(t){const e=function(t){"number"!=typeof t&&(t=parseInt(t,10)),t=Math.round(t);const e=Math.floor(t/86400);t-=86400*e;const r=Math.floor(t/3600);t-=3600*r;const i=Math.floor(t/60);return{days:e,hours:r,minutes:i,seconds:t-=60*i}}(t);let r="";return e.days&&(r+=e.days+":"),r+qt(e.hours)+":"+qt(e.minutes)+":"+qt(e.seconds)}class WebsocketBridge{constructor(t){this.manualDisconnect=!1,this.video=t,this.onClose=this.onClose.bind(this),this.onMessage=this.onMessage.bind(this)}static of(t){return new WebsocketBridge(t)}connect(t){this.client=new WebSocket("wss://player.ws.flowplayer.com?mediaId="+t),this.current_media_id=t,this.wireup()}onClose(){this.manualDisconnect?this.manualDisconnect=!1:this.current_media_id&&this.reconnect(this.current_media_id)}onMessage(t){JSON.parse(t.data).forEach(t=>{this.video.emit("ovp:message:realtime",t)})}reconnect(t){this.cleanup(),this.connect(t)}wireup(){this.client&&(this.client.addEventListener("message",this.onMessage),this.client.addEventListener("close",this.onClose))}cleanup(){this.client&&(this.client.removeEventListener("message",this.onMessage),this.client.removeEventListener("close",this.onClose),this.client=void 0)}disconnect(){this.client&&(this.manualDisconnect=!0,this.client.close())}}class FlowplayerLiveCountdown extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-livecountdown");const e=Vt("fp-inner");this.append(e);const r=document.createElement("p");r.innerText=t.i18n("ovp.starting_in"),e.append(r);const i=document.createElement("p");i.classList.add("fp-countdown"),e.append(i),t.on("ovp:live:countdown:tick",e=>{const r=e.detail.remaining_time;t.root.classList.add("is-livecountdown"),i.innerText=r})}}const gn=["*.lwcdn.com","*.flowplayer.com"];class OVP{constructor(t){St(t,Q,FlowplayerLiveCountdown)}onload(t,e,r,i){if("string"==typeof i.src)return"string"!=typeof t.player_id||0===i.src.indexOf(t.player_id)||$i(i)||(i.src=[t.player_id,i.src].join("/")),nn(r,i)}wants(t,e,r){return Zi(t,e)}init(t,e,r){const n=new WebsocketBridge(r);let s=Object.assign({},t);const a=function(t){return s?(delete s.src,Vi(t,s)):t};r.on("src",()=>{(r.currentSrc||r.root.classList.contains("is-livecountdown"))&&(s=!1)}),r.on("ovp:error",(function(t){r.emit(i,t.data)})),r.on("ovp:request:start",(function(){r.setState(at,!0),t.recommendations&&(t.recommendations=!1)})),r.on("ovp:media:changed",(function({data:t}){var e;const r=null===(e=null==t?void 0:t.metadata)||void 0===e?void 0:e.media_id;(null==t?void 0:t.live)&&r&&(n.disconnect(),n.connect(r))})),r.on("ovp:message:realtime",(function({data:e}){var i;const n=null==e?void 0:e.event,s=null==e?void 0:e.value,a=r.opt("metadata",{live_start_time:""});switch(n){case"METADATA":{const e=Object.assign(a,s),n=Object.assign(t,{metadata:e});n.live&&(null===(i=null==n?void 0:n.metadata)||void 0===i?void 0:i.live_start_time)&&(n.live_start_time=tn(n.metadata.live_start_time)),r.setOpts(n);break}}})),r.on("beforeplay",(function(e){const r=t;if(en(r)){if(vn(r))return;e.preventDefault()}})),r.on("ovp:request:media:complete",(function(t){const e=t.data;if(!e)return;if(e.src&&(e.src=Nt(e.src).map(t=>(t.src&&t.src.startsWith("//")&&(t.src="https:"+t.src),t))),0==r.reaper||"object"!=typeof e||hn(e)>0)return;const i=a(e);r.setOpts(i),r.setAttrs(i),i.src&&r.setSrc(i.src),r.setState(ft,!1)})),r.on(D,(function({data:i}){var n,s;if("string"==typeof t.src&&Zi(t.src,{}))return;if(t.src&&mn(t.src))return;if((null==i?void 0:i.domains)&&(null==i?void 0:i.domains.length)&&!((t,e)=>{const r=t.split(".").reverse();return e.concat(gn).some(t=>{const e=t.split(".").reverse(),i="*"===e[e.length-1];return i&&e.pop(),(i||e.length===r.length)&&e.every((t,e)=>r[e]===t)})})(function(){try{return window.location.hostname!==window.parent.location.hostname?gr(document.referrer).hostname:document.location.hostname}catch(t){return window.location.hostname}}(),i.domains))return Ee({root:e,video:r,data:{details:`Hostname ${window.location.hostname} is not allowed to load player ${null===(n=i.metadata)||void 0===n?void 0:n.player_id}.`,reason:"domain"}});const a=null==i?void 0:i.brand_color;return a&&r.root.style.setProperty("--fp-brand-color","#"==a[0]?a:"#"+a),"string"==typeof t.player_id&&(null===(s=null==t?void 0:t.metadata)||void 0===s?void 0:s.player_id)!==t.player_id?function(t,e){if("object"==typeof an[e])return console.debug("using Cache(%s)",e),on(t,e,an[e]);Pipe.of(e).fmap(qi).fmap(Ki).fmap(r=>r.then(r=>on(t,e,r)).catch(console.error))}(r,t.player_id):void 0})),r.on("ovp:request:playlist:complete",(function(t){const e=t.data;if(!e||0==r.reaper)return;const{playlist:i}=e,n=Rt(e,["playlist"]),s=a(n);Array.isArray(s.playlist)&&(s.playlist=n),r.setOpts(s),r.setAttrs(s);const o={type:"flowplayer/playlist",items:i};r.setSrc(o),r.setState(ft,!1)})),r.on("ovp:live:countdown:start",(function(i){const n=i.data;if(!n||0==r.reaper)return;const s=a(n);if(r.setOpts(s),r.setAttrs(s),hn(n)<=0)return r.emit("ovp:request:media:complete",n);Ht(r,Q)||(e.appendChild(_t(r,Q)),fn(r,t))})),r.on("timeupdate",(function(){var e,i,n;const s=t;en(s)?vn(s)||(r.togglePlay(!1),r.emit(S)):t.recommendations&&(null===(e=null==t?void 0:t.metadata)||void 0===e?void 0:e.media_id)&&(Array.isArray(t.recommendations)||r.currentTime/r.duration<.8||un()||(null===(i=null==t?void 0:t.metadata)||void 0===i?void 0:i.media_id)&&(null===(n=null==t?void 0:t.metadata)||void 0===n?void 0:n.player_id)&&dn(r,t.metadata.media_id,t.metadata.player_id))})),r.on(w,(function(){n.disconnect()}))}}function vn(t){var e,r;const i=null===(e=null==t?void 0:t.metadata)||void 0===e?void 0:e.live_stop_time;if(!i)return!0;return!!(null===(r=null==t?void 0:t.metadata)||void 0===r?void 0:r.allow_after_stop_time)||tn(i)>Date.now()}OVP.events=rn;const mn=t=>{var e;if(t&&Array.isArray(t))return"object"==typeof t[0]&&"ovp/base64"===(null===(e=t[0])||void 0===e?void 0:e.type)};function yn(t){return{width:t.clientWidth,height:t.clientHeight}}function En(t,e,r){return"number"==typeof r&&(r+="px"),t.style.setProperty(e,r),t}ue(window,OVP);const Tn="ad-initialized";var _n=Object.freeze({__proto__:null,AD_INIT:Tn,AD_PLAYBACK_ERROR:"ad-playback-error",AD_TEARDOWN:"ad-teardown",AD_VIDEOTAG_ATTACHED:"ad-videotag-attached",AD_BLOCKED:"ad-blocked",AD_REQUEST_ERROR:"ad-request-error",AD_REQUESTED:"ad-requested",AD_REQUEST_COMPLETED:"ad-request-completed",AD_PAUSE_CONTENT:"ad-pause-content",AD_STARTED:"ad-started",AD_COMPLETED:"ad-completed",AD_PAUSED:"ad-paused",AD_RESUMED:"ad-resumed",AD_WAITING:"ad-waiting",AD_PROGRESS:"ad-progress",AD_SKIPPED:"ad-skipped",AD_MUTED:"ad-muted",AD_VOLUME_CHANGED:"ad-volume-changed",AD_FULLSCREEN:"ad-fullscreen",AD_TIMEOUT:"ad-timeout",AD_BREAK_COMPLETED:"ad-break-completed",AD_POSTROLL_FINISHED:"ad-postroll-finished",AD_PREROLL_FINSIHED:"ad-preroll-finished",AD_MIDROLL_FINISHED:"ad-midroll-finished",VPAID_INIT:"vpaid-init",IMA_ADAPTER_INIT:"ad-ima-adapter-init",IMA_BEFORE_ADS_REQUEST:"ad-ima-before-ads-request",IMA_ADS_RENDERING_SETTINGS:"ad-ima-rendering-settings",ADAPTER_INIT_FAILED:"ad-adapter-init-failed",AD_PLAY_REQUESTED:"ad-play-requested",RELOAD_AD_REQUESTED:"reload-ad-requested",AD_ERROR:"ad-error",REQUEST_AD_PAUSE:"request/ad/pause",REQUEST_AD_PLAY:"request/ad/play",REQUEST_AD_MUTE_UNMUTE:"request/ad/muteunmute",AD_HIDE_FIRST_FRAME:"ad/hide-first-frame",AD_SHOW_FIRST_FRAME:"ad/show-first-frame",AD_RESIZE:"ad/resize",AD_SET_UI_FLAGS:"ad/set-ui-flags"});const Sn="undefined"!=typeof document&&"undefined"!=typeof window&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,bn="flowplayer-ad-ui",An=Pe("ads/lifecycle"),Ln=["ad-playback-error","ad-teardown","ad-break-completed"];async function wn({config:t,root:e,content:r,ads:i,ima:n}){var s;An("LifeCycle::initLifeCycle",t,e,r,i,n),r.autoplay=!1;const a=t.autoplay===At.AUDIO_REQUIRED,o=function(t,e){return{muted:!(e||!t.muted),volume:t.volume}}(r,a);r.on("volumechange",()=>{o.volume=r.volume,o.muted=r.muted});const l=_t(r,bn),d=l.adContainer;r.emit("ad/set-ui-flags",{ui_flags:null===(s=t.ads)||void 0===s?void 0:s.ui}),r.renderPlugin(l);const u={listening:!1,preload:null==n?void 0:n.preload_ads};if(An("initial",o),i.setVideoTag(r),t.autoplay){An("Trying to autoplay"),r.emit("ad/hide-first-frame",{root:e});await async function t(e,r){const[i,n]=[e.muted,e.volume];An("Lifecycle::peek_content(:muted => %s, :volume => %s)",i,n);const s=()=>new Promise(t=>setTimeout(t,0,!1));r&&(e.muted=!1,e.volume=e.volume?e.volume:1);try{return await async function(t){return An("Lifecycle::wait_for_source"),new Promise((e,r)=>{let i=0;const n=setInterval(()=>{if(++i>40)return clearInterval(n),r(new Error("No source in 2000ms, giving up"));t.currentSrc&&(e(null),clearInterval(n))},50)})}(e),e.volume&&(e.volume=.01),An("Lifecycle::peek_content::play"),await new Promise(t=>setTimeout(()=>t(e.togglePlay(!0)))),An("Lifecycle::peek_content::pause"),await new Promise(t=>setTimeout(()=>t(e.togglePlay(!1)))),e.volume=n,An("Lifecycle::peek_content::true"),!0}catch(a){return e.volume=n,r?(e.muted=!1,0==e.volume&&(e.volume=1),await s()):i||!n?(An("Lifecycle::peek_content::false"),await s()):(An("Lifecycle::peek_content::recover"),e.muted=!0,!!await t(e)||(e.muted=i,An("Lifecycle::peek_content::false"),await s()))}}(r,a)?(An("Can autoplay, start ad"),r.opts.autoplay=1,Dn({ads:i,content:r,state:u,adContainer:d,ima:n,config:t})):(An("cannot autoplay(audioRequired: %s), fallback to poster state",a),t.autoplay=0,r.emit("ad/show-first-frame",{root:e}),r.setState("is-starting",!0))}t.autoplay||i.hasPreroll()&&function({content:t,ads:e,config:r,state:i,initial:n,adContainer:s,ima:a}){t.once("beforeplay",(async function(o){(t.hasState(ht)||"touchend"!=o.type)&&e.shallPlayAd(0)&&(Sn&&(t.muted=!1),o.preventDefault(),On({ads:e,content:t,state:i}),An("user_gesture(:intercept) -> shallPlayAd(0: %s)",e.shallPlayAd(0)),r.muted=n.muted,await Dn({ads:e,content:t,state:i,adContainer:s,ima:a,config:r}),Cn({ads:e,content:t}))}))}({content:r,ads:i,config:t,state:u,initial:o,adContainer:d,ima:n}),!t.autoplay&&i.hasPreroll()&&u.preload&&Dn({ads:i,content:r,state:u,adContainer:d,ima:n,config:t}),kn({config:t,root:e,content:r,ads:i,state:u,adContainer:d,ui:l,ima:n,initial:o});const c=async t=>{r.removeEventListener("beforeplay",c),i.resetScheduleCounter(),i.adapter&&(t.preventDefault(),await i.setCurrentTime(0),i.adapter.isAdPod()||i.trigger("ad-teardown"))};r.on("src",()=>{u.started&&(r.removeEventListener("beforeplay",c),r.addEventListener("beforeplay",c))}),r.on("beforeplay",t=>{(i.adBreak||i.adPlaying||i.adRequesting)&&(i.adBreak&&!i.adLinear||(An("prevented content from starting because ad break is active"),t.preventDefault()))})}async function Dn(t){t.state.started||(t.content.hasState(ht)?await Rn(t):t.content.once("viewenter",async()=>{await Rn(t)}))}async function Rn({ads:t,content:e,adContainer:r,ima:i,state:n,config:s}){var a;n.started=!0;const o=Rt(i,["ads"]),l=yn(e.root),d=(null==s?void 0:s.muted)||e.muted,u=Object.assign(Object.assign(Object.assign({container:r,volume:d?0:e.volume,muted:d,autoplay:(null==s?void 0:s.autoplay)||!1,video_source:e.original_src,DisableCustomPlaybackForIOS10Plus:Sn,preload_ads:null===(a=null==s?void 0:s.ima)||void 0===a?void 0:a.preload_ads},o),l));An("start():",u,n),await t.initialize(!1,u,n.preload)}function In(t,e){var r,i;return{content_width:t.clientWidth||(null===(r=t.parentNode)||void 0===r?void 0:r.clientWidth)||e.clientWidth,content_height:t.clientHeight||(null===(i=t.parentNode)||void 0===i?void 0:i.clientHeight)||e.clientHeight}}function kn({config:t,root:e,content:r,ads:i,initial:n,adContainer:s,state:a,ui:o,ima:l}){An("addUIListeners()"),r.once(E,async n=>{if(i){if(An("addUIListeners() -> content started playing"),On({ads:i,content:r,state:a}),!i.shallPlayAd(0)||!i.adapter.isLinearAd())return An("addUIListeners() -> no more preroll ads -> resume content"),r.emit("ad/show-first-frame",{root:e}),await Dn({ads:i,content:r,state:a,adContainer:s,ima:l,config:t});r.togglePlay(!1),await Dn({ads:i,content:r,state:a,adContainer:s,ima:l,config:t}),i.shallPlayAd(0)&&i.adapter.isLinearAd()&&(o.classList.add("on","linear"),e.classList.add(at),Cn({ads:i,content:r}))}}),r.on([I,R],(function(){if(!i)return;const{content_width:t,content_height:n}=In(r,e);i.resize({height:n,width:t})})),r.on("resize",t=>{if(!i||!t.detail)return;const{width:e,height:r}=t.detail.contentRect;i.resize({width:e,height:r})}),r.on(S,t=>{var e;i&&(An("ui_listeners(:%s, event: %o)",t.type,t.detail),(null===(e=null==t?void 0:t.detail)||void 0===e?void 0:e.from)!==i&&(t.preventDefault(),Object.assign(t,{prevented_from_ads:!0}),i.finished((function(){r.emit(S,{from:i})}))))}),i.on("ad-requested",()=>{e.classList.toggle(at,!0)}),i.once("ad-started",()=>{r.on(["beforeplay","beforepause"],t=>{var e;if(!i.adBreak||!i.adapter.isLinearAd())return;t.preventDefault();const r=(null===(e=t.detail)||void 0===e?void 0:e.forced)?"beforeplay"===t.type:!i.adPlaying;r&&i.paused&&i.resume(),r||i.paused||i.pause()})}),i.on("ad-started",t=>{const s=t.detail,{linear:a,ad:l,ad_type:d}=s;let u;if(An(`Ad[linear: ${a}, currentTime: ${r.currentTime}] starting`,l),"preroll"==d&&!a&&r.paused&&r.togglePlay(!0),a&&(u=In(r,e)),i.resize({width:u?u.content_width:l.width,height:u?u.content_height:l.height,linear:a,resize_non_linear:!0}),r.emit("ad/resize",{opts:{linear:a,resizeContainerAlso:!0,width:a?void 0:l.width,height:a?void 0:l.height}}),e.classList.remove(at),o.classList.add("on"),o.classList.toggle("linear",a),o.classList.toggle("non-linear",!a),!a){An("non-linear ad / restarting content");try{r.togglePlay(!0),r.volume=n.volume,r.muted=n.muted}catch(t){An(t)}}r.hasState(ht)||r.hasState("is-popped-out")||!a||i.pause()}),i.on("ad-pause-content",()=>{r.emit("ad/resize",{opts:{linear:!0,width:0,height:0}})}),r.on(Ln,t=>async function({root:t,content:e,ads:r,ui:i,eventName:n,err:s={reason:""}}){An("teardown(event: %s)",n),t.classList.add("is-seamless"),i.classList.remove("is-vpaid"),t.classList.remove(at),s.reason&&An("teardown(:err, reason: %s) %o",s.reason);i.classList.remove("on");const a=r.getLastAd();if(e.emit("ad/show-first-frame",{root:t}),!r.shouldRestartContent())return An("Lifecycle.teardown(:skip_restart, reason: %s)","Ad prevented restarting content"),Pn(t);if(e.currentTime>0&&e.currentTime>=e.duration||"postroll"==r.ad_type||!1===(null==a?void 0:a.restart))return An("Lifecycle.teardown(:skip_restart, reason: %s)","was a postroll ad"),Pn(t);""===e.currentSrc&&e.setSrc(e.original_src);e.paused&&r.shouldRestartContent()&&(An("Lifecycle.teardown(:toggle_play, %s)","attempting to restart content"),await e.togglePlay(!0));if(!e.paused)return An("Lifecycle.teardown(:ok)","restarted video content"),Pn(t)}({root:e,content:r,ads:i,ui:o,err:t.detail,eventName:t.type}));let d=!!t.autoplay;r.on("viewenter",()=>{d&&!1!==l.autopause&&i.resume()}),r.on("viewleave",xe(()=>{!1!==l.autopause&&(d=!i.paused,i.pause())}))}function On({ads:t,content:e,state:r}){r.listening||(e.on(["timeupdate",b,E,A],r=>{t.adPlaying&&t.adapter.isLinearAd()&&!t.adapter.isSharedVideoTag()&&!e.paused&&e.pause(),Cn({ads:t,content:e,seek:r.type===A})}),r.listening=!0)}function Cn({ads:t,content:e,seek:r=!1}){t&&t.setCurrentTime(e.currentTime,void 0,r)}function Pn(t){t.classList.remove("is-seamless")}const xn=Pe("ads/timers");class TimerRegistry{constructor(t={},e={}){this.intervals=t,this.timers=e}}let Mn=-1;function Nn(t,e,r){const i=setInterval(r,e);if(xn("TimerRegistry.createInterval() -> "+i,t.intervals),"object"==typeof i){const e=++Mn;return t.intervals[e]=e,e}return t.intervals[i]=i,i}function Fn(t){if(t)return xn("TimerRegistry.empty()",Object.keys(t.timers),Object.keys(t.intervals)),Object.keys(t.intervals).forEach(e=>function(t,e){return xn("TimerRegistry.removeInterval() -> "+e,t.intervals),clearInterval(t.intervals[e]),delete t.intervals[e],t}(t,e)),Object.keys(t.timers).forEach(e=>function(t,e){return xn("TimerRegistry.removeTimeout() -> "+e,t.timers),clearTimeout(t.timers[e]),delete t.timers[e],t}(t,e)),t}function Un(t){try{return t.getAdPodInfo().getPodIndex()}catch(t){return}}class IMA{constructor(t){this.eventHandler=t,this.log=Pe("ads/adapter/ima"),this.google=window.google,this._adHandlers=[],this._timers=new TimerRegistry,this._started=!1,this._volumeLevel=0,this._adLoaded=!1,this._paused=!1,this._all_ads_completed=!1,this._currentDuration=0,this._currentRemaining=0,this._currentDisplayTs=0,this._iosPlaysInline=!1,this.sharedVideoTag=!1,this._isInitialized=!1,this._prepared=!1,this.opts={}}async init(t){this.log("init",this.videoTag,t),this.opts=t,this._dimensions={width:t.width,height:t.height,linear:t.linear},this._prepared=!0,!this._isInitialized&&this.videoTag&&await this.initAdapter()}async initAdapter(){this.log("initAdapter",this.opts);try{await this.initialize(this.opts),this._isInitialized=!0}catch(t){this.log("initAdapter failed:",t),this._prepared=!1,this.eventHandler.trigger("ad-adapter-init-failed")}}isReady(){return!!this._isInitialized}setIOSPlaysInline(t){this.log("setIOSPlaysInline",t),this.sharedVideoTag=!t,this.initialize(Object.assign(Object.assign({},this.opts),{DisableCustomPlaybackForIOS10Plus:t}))}getIOSPlaysInline(){return this._iosPlaysInline}setVideoTag(t){this.videoTag=t}isLinearAd(){return!!this._adLinear}isSharedVideoTag(){return!!this.sharedVideoTag}getVideoTag(){return this.videoTag}getDimensions(){return this._dimensions||{}}getOpts(){return this.opts}isPaused(){return this._paused}destroy(){Fn(this._timers),this._adHandlers&&this._adHandlers.forEach(t=>t()),this._adHandlers=void 0,this._adDisplayContainer&&this._adDisplayContainer.destroy(),this._adDisplayContainer=void 0,this._adsLoader&&this._adsLoader.destroy(),this._adsLoader=void 0,this._adsManager&&this._adsManager.destroy(),this._adsManager=void 0}stop(){this._adsManager&&this._adsManager.stop()}initialize(t){const e=this.isAdPod(),i=this._adLoaded||e;if(this.cleanup(),!this.videoTag)return console.warn("videoTag not set during initialization");this.opts=t,this._volumeLevel=t.volume;const n=this.google.ima.settings;t.NumRedirects=t.NumRedirects||t.redirects;const s={VpaidMode:this.google.ima.ImaSdkSettings.VpaidMode.INSECURE,DisableCustomPlaybackForIOS10Plus:!0};if(n.setVpaidMode(t.VpaidMode||s.VpaidMode),n.setDisableCustomPlaybackForIOS10Plus(t.DisableCustomPlaybackForIOS10Plus||s.DisableCustomPlaybackForIOS10Plus),"NumRedirects"in t&&n.setNumRedirects(t.NumRedirects),"AutoPlayAdBreaks"in t&&n.setAutoPlayAdBreaks(t.AutoPlayAdBreaks),"Locale"in t&&n.setLocale(t.Locale),"Ppid"in t&&n.setPpid(t.Ppid),!document.body.contains(t.container))throw new Error("AdDisplayContainer was not found in the document.body");this._adDisplayContainer=new this.google.ima.AdDisplayContainer(t.container,r().tizen||r().webOS?void 0:this.videoTag),this._adDisplayContainer.initialize(),this._adsLoader=new this.google.ima.AdsLoader(this._adDisplayContainer),this.log("ima.initialise(:wait -> ADS_MANAGER_LOADED)",Object.assign(Object.assign({},t),{volume:this.videoTag.volume,muted:this.videoTag.muted})),this._adsLoader.addEventListener(this.google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,e=>{if(!this.videoTag)return;this.log("ima.initialise(:done -> ADS_MANAGER_LOADED)\n%o",Object.assign(Object.assign({},t),{volume:this.videoTag.volume,muted:this.videoTag.muted}));const r=new this.google.ima.AdsRenderingSettings;this.log("ima.rendering(preload: %s)",!!t.preload_ads),r.useStyledNonLinearAds=!0,r.enablePreloading=!!t.preload_ads,"number"==typeof t.media_timeout&&(r.loadVideoTimeout=t.media_timeout),r.restoreCustomPlaybackStateOnAdBreakComplete=!t.DisableCustomPlaybackForIOS10Plus,this.sharedVideoTag&&(r.playAdsAfterTime=this.videoTag.currentTime),this.eventHandler.trigger("ad-ima-rendering-settings",r);const i=this._adsManager=e.getAdsManager(this.videoTag,r);this.eventHandler.trigger("ad-ima-adapter-init",i),i.addEventListener(this.google.ima.AdEvent.Type.LOADED,()=>{this.log("debug(ima.adsManager): google.ima.AdEvent.Type.LOADED")}),i.addEventListener(this.google.ima.AdErrorEvent.Type.AD_ERROR,()=>{this.log("debug(ima.adsManager): google.ima.AdErrorEvent.Type.AD_ERROR")}),i.addEventListener(this.google.ima.AdEvent.Type.STARTED,()=>{this.log("debug(ima.adsManager): google.ima.AdEvent.Type.STARTED")}),i.addEventListener(this.google.ima.AdEvent.Type.AD_PROGRESS,t=>{var e,r;const i=null===(e=t.getAdData())||void 0===e?void 0:e.duration,n=null===(r=t.getAdData())||void 0===r?void 0:r.currentTime;isNaN(i)||isNaN(n)||(this._currentRemaining=i-n,this.eventHandler.trigger("ad-progress",{remaining:this._currentRemaining,duration:i}))}),i.addEventListener(this.google.ima.AdEvent.Type.STARTED,t=>{this._currentRemaining=-1,this.debugEvent(t);const e=t.getAd();e&&(this._currentDuration=e.getDuration(),this._currentDisplayTs=Date.now(),this.emitWithAd("ad-started",e),e.isLinear()&&IMA.pollRemaining({ima:this,adsManager:i}))}),i.addEventListener(this.google.ima.AdEvent.Type.COMPLETE,t=>{this.debugEvent(t);const e=t.getAd();e&&this.emitWithAd("ad-completed",e),Fn(this._timers)}),i.addEventListener(this.google.ima.AdEvent.Type.SKIPPED,t=>{this.debugEvent(t);const e=t.getAd();e&&this.emitWithAd("ad-skipped",e)}),i.addEventListener(this.google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,t=>{this.debugEvent(t);const e=t.getAd();e&&this.emitWithAd("ad-pause-content",e)});const n=()=>{this._started=!1,this._currentDisplayTs=0,this.eventHandler.trigger("ad-break-completed")};i.addEventListener(this.google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,t=>{this.debugEvent(t),n()}),i.addEventListener(this.google.ima.AdEvent.Type.VOLUME_CHANGED,t=>{this.log("IMA::volume(type: %s, event: %o)",t);const e=i.getVolume();this._volumeLevel=e,this.eventHandler.trigger("ad-volume-changed",e)});const s=t=>{this._paused=t,this.eventHandler.trigger(t?"ad-paused":"ad-resumed")};i.addEventListener(this.google.ima.AdEvent.Type.PAUSED,()=>s(!0)),i.addEventListener(this.google.ima.AdEvent.Type.RESUMED,()=>s(!1)),i.addEventListener(this.google.ima.AdEvent.Type.STARTED,()=>s(!1)),i.addEventListener(this.google.ima.AdEvent.Type.VOLUME_MUTED,t=>{this.log("IMA::volume(type: %s, event: %o)","mute",t),this.eventHandler.trigger("ad-muted")});const{width:a,height:o}=t;a&&o&&(i.init(a,o,this.google.ima.ViewMode.NORMAL),this.log("ima.initialise: done initializing"))}),i&&(this.log("Event(reload: %s)","reload-ad-requested"),this.eventHandler.trigger("reload-ad-requested",e)),this.eventHandler.trigger(Tn,this)}destroyManager(t="unknown"){if(!this._adsManager)return this.log("ima::destroyManager(:skip, label: %s)",t);this.log("ima::destroyManager(:ok, label: %s)",t),this._adsManager.destroy()}reset(){this.destroyManager("reset"),Fn(this._timers),this.clearAdHandlers(),this._started=!1,this._adLoaded=!1}cleanup(){this.destroyManager("cleanup"),this._adsLoader&&this._adsLoader.destroy(),this._adDisplayContainer&&this._adDisplayContainer.destroy(),this._adLoaded=!1}waitForAdsManager(){return new Promise(t=>{this.log("ima.waitForAdsManager:",this._adsManager),this.once(this._adsLoader,this.google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,()=>{this.log("ima.waitForAdsManager(:ok)",this._adsManager),t(this._adsManager)})})}async initAd(t,e=5e3){this.log(`ima.initAd(adTag: ${t}, timeout: ${e})`);try{await this.requestAd(t,e),this._adLoaded=!0}catch(t){throw this.log("ima.initAd:",t),this._adLoaded=!1,t}finally{Fn(this._timers)}}async requestAd(t,e){if(this.destroyManager("requestAd"),!this.videoTag)return;const{autoplay:r=!1}=this.opts,i=Date.now(),n=this.videoTag.muted;this._volumeLevel=this.videoTag.volume;const s=n||0==this._volumeLevel;this._all_ads_completed=!1,this.log("ima.requestAd(%o)",Object.assign(Object.assign({},this.opts),{autoplay:r,muted:n,timeout:e,adTag:t,_volumeLevel:this._volumeLevel,manager:this._adsManager})),this.clearAdHandlers();const a=new this.google.ima.AdsRequest;a.adTagUrl=t;const{height:o,width:l}=this.opts;if(l&&(a.linearAdSlotWidth=l),o&&(a.linearAdSlotHeight=o),!this.opts.disable_non_linear_ads&&l&&(a.nonLinearAdSlotWidth=l),!this.opts.disable_non_linear_ads&&o&&(a.nonLinearAdSlotHeight=o-50),a.setAdWillAutoPlay(r),a.setAdWillPlayMuted(s),a.vastLoadTimeout=e,this.eventHandler.trigger("ad-ima-before-ads-request",{request:a}),!this._adsLoader)return;this._adsLoader.requestAds(a);return new Promise(async(t,r)=>{const n=e=>{clearTimeout(o),t(e)},a=t=>{clearTimeout(o),r(t)};this.once(this._adsLoader,this.google.ima.AdErrorEvent.Type.AD_ERROR,t=>{this.emitError("ad-request-error",t),a(new Error("Ad load failed"))});const o=setTimeout(()=>{const t=new Error("Ad internal timeout reached");this.eventHandler.trigger("ad-timeout",t),r(t)},1.5*(e+(this.opts.media_timeout||5e3))),l=await this.waitForAdsManager();this.volume(s?0:this._volumeLevel),this.eventHandler.trigger("ad-volume-changed",this._volumeLevel);const d=this.cuepoints();if(d&&d.length&&0!==d[0])return n({ad:!1,adsManager:l});this.once(l,this.google.ima.AdErrorEvent.Type.AD_ERROR,t=>{this.emitError("ad-playback-error",t),a(t)}),this.once(l,this.google.ima.AdEvent.Type.ALL_ADS_COMPLETED,()=>{this._all_ads_completed=!0,n(null)}),this.once(l,this.google.ima.AdEvent.Type.LOADED,t=>{this.eventHandler.trigger("ad-request-completed",{request_load_time:Date.now()-i});const e=t.getAd();e&&(this.log("ima.requestAd: AD_REQUEST_COMPLETED",e.getContentType()),"application/javascript"==e.getContentType()&&this.eventHandler.trigger("vpaid-init",e),n(null))}),this.once(l,this.google.ima.AdEvent.Type.CLICK,()=>{this.log("ima.requestAd: click event"),this.pause()})})}async playAd(){if(this.log("ima.playAd()",this),!this._adsManager||!this._adLoaded)return;const t=this.currentAd();if(t&&(!this.sharedVideoTag||t.isLinear()))try{await this.startAndWaitForAdCompletion(this._adsManager,t.isLinear())}catch(t){throw this.log("ima.playAd",t),t}finally{this._adLoaded=!1,Fn(this._timers)}}startAndWaitForAdCompletion(t,e){if(!this._started)return this.log("ima.startAndWaitForAdCompletion(manager: %o)",{volume:t.getVolume()}),new Promise((r,i)=>{let n=!1;this.once(t,this.google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,()=>{if(this.log("ima.startAndWaitForAdCompletion: CONTENT_RESUME_REQUESTED <<< happened"),this._started=!1,n)return this.log("ima.startAndWaitForAdCompletion: Content resume requested, but trying to recover from ad error");r()}),this.once(t,this.google.ima.AdErrorEvent.Type.AD_ERROR,async t=>{this.log("ima.startAndWaitForAdCompletion: beginning error recovery ->",t),n=!0;try{const{ok:e}=await IMA.pollForFatalError({err:t,ima:this});e&&(n=!1)}catch(e){this._started=!1,i(t)}});const s=this.getVideoTag();if(!s)return;const a=()=>{e&&(this._started=!0),t.start(),this.eventHandler.trigger("ad-play-requested")};if(!e||s.hasState(ht)||s.hasState("is-popped-out"))return a();s.paused||s.pause(),s.once("viewenter",()=>a())})}pause(){this.log("ima.pause()"),this._adsManager&&this._adsManager.pause()}resume(){this.log("ima.resume()"),this._adsManager&&this._adsManager.resume()}volume(t){if(this._adsManager)try{return arguments.length>0&&"number"==typeof t&&this._adsManager.setVolume(t),this._volumeLevel=this._adsManager.getVolume()}catch(t){this.log("ima.volume() failed (%o)",t)}}onResize({width:t,height:e,linear:r,silent:i,resize_non_linear:n}){this._adsManager&&(this._adLinear=void 0===r?this._adLinear:r,this.opts&&(t||e)&&(!1===r&&(t+=10,e+=10),this._dimensions={width:t,height:e,linear:r},r&&(this.opts.width=t,this.opts.height=e),(this._adLinear||n)&&(i||this.log("ima.onResize %s x %s",t,e),this._adsManager.resize(t,e,this.google.ima.ViewMode.NORMAL))))}getAdInfo(){const t=this.currentAd();if(t)return{duration:t.getDuration(),currentTime:this._currentRemaining}}currentAd(){const t=this._adsManager;if(t)return t.getCurrentAd()}isAdPod(){const t=this.cuepoints();return!!(t&&t.length>1)}cuepoints(){return this._adsManager&&this._adsManager.getCuePoints()}async contentComplete(){this.log("ima.contentComplete() -> ",this),this._adsLoader&&this._adsLoader.contentComplete();const t=this.cuepoints();t&&-1!==t.indexOf(-1)&&await new Promise(t=>{IMA.race(this.eventHandler,["ad-break-completed","ad-error"],t)})}isUiDisabled(){try{const t=this.currentAd();return t&&t.isUiDisabled()}catch(t){return null}}getAdPodInfo(){try{const t=this.currentAd();return t&&t.getAdPodInfo()}catch(t){return null}}canDismissNonLinear(){const t=this.currentAd();if(!t||t.isLinear()||!this._adsManager||!this._currentDisplayTs)return!0;const e=Date.now(),r=t.getMinSuggestedDuration();return e-this._currentDisplayTs>1e3*r}static unwrapError(t,e){if(!t)return"";if("function"==typeof t.getMessage){return t.getMessage()}return t.message?t.message:e||""}static pollForFatalError({err:t,ima:e}){let r;try{const e=t.getError(),i=e.getInnerError(),n=i?IMA.unwrapError(i,e.message):"";r={reason:n,type:e.getType(),code:e.getErrorCode()}}catch(t){}const i=e._currentRemaining;return new Promise((t,n)=>{const s=setTimeout(()=>{e.eventHandler&&e.eventHandler.trigger("ad-playback-error",r),n(new Error("Ad not progressing"))},2500);e.eventHandler.once("ad-progress",e=>{const r=e.detail.remaining;-1!==r&&r<i&&(clearTimeout(s),t({ok:1}))})})}static pollRemaining({ima:t,adsManager:e}){let r=-1;return Nn(t._timers,250,(function(){const i=e.getRemainingTime();-1!=t._currentRemaining&&t._currentRemaining<=i||(t._currentRemaining=e.getRemainingTime(),r!=t._currentRemaining&&(r=t._currentRemaining,t.eventHandler.trigger("ad-progress",{remaining:t._currentRemaining,duration:t._currentDuration})))}))}once(t,e,r){this._adHandlers.push(function(t,e,r){const i=n=>{r(n),t.removeEventListener(e,i)};return t.addEventListener(e,i),()=>t.removeEventListener(e,i)}(t,e,r))}static race(t,e,r){e.forEach(i=>{const n=(...i)=>{e.forEach(e=>t.removeListener(e,n)),r(i)};t.on(i,n)})}clearAdHandlers(){this.log("ima.clearAdHandlers"),this._adHandlers.forEach(t=>t()),this._adHandlers=[]}emitWithAd(t,e){if(this.log("ima.emitWithAd",t,e),!this._adsManager)return;const r=function(t){try{return t.getAdPodInfo().getAdPosition()}catch(t){return}}(e),i=function(t){try{return t.getAdPodInfo().getTotalAds()}catch(t){return}}(e),n={ad:{duration:e.getDuration(),width:e.getWidth(),height:e.getHeight(),position:r,totals:i},volume:this._adsManager.getVolume(),vast_ad_id:e.getAdId(),linear:e.isLinear(),mime_type:e.getContentType(),ima_event:!0};this.log(`emitWithAd::event(name: ${t}, data: %o, ad: %o)`,n,e),this.eventHandler.trigger(t,n)}emitError(t,e){const r={vast_error_type:e.getError().getType(),reason:e.getError().getMessage(),vast_error:e.getError().getErrorCode()};this.log(`ima.error(${t})`,r),this.eventHandler.trigger(t,r)}debugEvent(t){try{const e=t.getAd();if(!e)return;this.log(`ima.event.${t.type} ->`,{event:t,data:t.getAdData(),position:Un(e),ad:e})}catch(t){}}}var Bn=He((function(t,e){var r=function(){for(var t=new Array(256),e=0;e<256;++e)t[e]="%"+((e<16?"0":"")+e.toString(16)).toUpperCase();return t}(),i=Object.prototype.hasOwnProperty;e.arrayToObject=function(t,e){for(var r=e.plainObjects?Object.create(null):{},i=0;i<t.length;++i)void 0!==t[i]&&(r[i]=t[i]);return r},e.merge=function(t,r,n){if(!r)return t;if("object"!=typeof r){if(Array.isArray(t))t.push(r);else{if("object"!=typeof t)return[t,r];(n.plainObjects||n.allowPrototypes||!i.call(Object.prototype,r))&&(t[r]=!0)}return t}if("object"!=typeof t)return[t].concat(r);var s=t;return Array.isArray(t)&&!Array.isArray(r)&&(s=e.arrayToObject(t,n)),Object.keys(r).reduce((function(t,s){var a=r[s];return i.call(t,s)?t[s]=e.merge(t[s],a,n):t[s]=a,t}),s)},e.decode=function(t){try{return decodeURIComponent(t.replace(/\+/g," "))}catch(e){return t}},e.encode=function(t){if(0===t.length)return t;for(var e="string"==typeof t?t:String(t),i="",n=0;n<e.length;++n){var s=e.charCodeAt(n);45===s||46===s||95===s||126===s||s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122?i+=e.charAt(n):s<128?i+=r[s]:s<2048?i+=r[192|s>>6]+r[128|63&s]:s<55296||s>=57344?i+=r[224|s>>12]+r[128|s>>6&63]+r[128|63&s]:(n+=1,s=65536+((1023&s)<<10|1023&e.charCodeAt(n)),i+=r[240|s>>18]+r[128|s>>12&63]+r[128|s>>6&63]+r[128|63&s])}return i},e.compact=function(t,r){if("object"!=typeof t||null===t)return t;var i=r||[],n=i.indexOf(t);if(-1!==n)return i[n];if(i.push(t),Array.isArray(t)){for(var s=[],a=0;a<t.length;++a)t[a]&&"object"==typeof t[a]?s.push(e.compact(t[a],i)):void 0!==t[a]&&s.push(t[a]);return s}for(var o=Object.keys(t),l=0;l<o.length;++l){var d=o[l];t[d]=e.compact(t[d],i)}return t},e.isRegExp=function(t){return"[object RegExp]"===Object.prototype.toString.call(t)},e.isBuffer=function(t){return null!=t&&!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}})),Gn={brackets:function(t){return t+"[]"},indices:function(t,e){return t+"["+e+"]"},repeat:function(t){return t}},Hn={delimiter:"&",strictNullHandling:!1,skipNulls:!1,encode:!0,encoder:Bn.encode},jn=function t(e,r,i,n,s,a,o,l,d){var u=e;if("function"==typeof o)u=o(r,u);else if(u instanceof Date)u=u.toISOString();else if(null===u){if(n)return a?a(r):r;u=""}if("string"==typeof u||"number"==typeof u||"boolean"==typeof u||Bn.isBuffer(u))return a?[a(r)+"="+a(u)]:[r+"="+String(u)];var c,h=[];if(void 0===u)return h;if(Array.isArray(o))c=o;else{var f=Object.keys(u);c=l?f.sort(l):f}for(var p=0;p<c.length;++p){var g=c[p];s&&null===u[g]||(h=Array.isArray(u)?h.concat(t(u[g],i(r,g),i,n,s,a,o,l,d)):h.concat(t(u[g],r+(d?"."+g:"["+g+"]"),i,n,s,a,o,l,d)))}return h},Vn=Object.prototype.hasOwnProperty,Kn={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3,strictNullHandling:!1,plainObjects:!1,allowPrototypes:!1,allowDots:!1,decoder:Bn.decode},qn=function(t,e,r){if(t){var i=r.allowDots?t.replace(/\.([^.[]+)/g,"[$1]"):t,n=/(\[[^[\]]*])/g,s=/(\[[^[\]]*])/.exec(i),a=s?i.slice(0,s.index):i,o=[];if(a){if(!r.plainObjects&&Vn.call(Object.prototype,a)&&!r.allowPrototypes)return;o.push(a)}for(var l=0;null!==(s=n.exec(i))&&l<r.depth;){if(l+=1,!r.plainObjects&&Vn.call(Object.prototype,s[1].slice(1,-1))&&!r.allowPrototypes)return;o.push(s[1])}return s&&o.push("["+i.slice(s.index)+"]"),function t(e,r,i){if(!e.length)return r;var n,s=e.shift();if("[]"===s)n=(n=[]).concat(t(e,r,i));else{n=i.plainObjects?Object.create(null):{};var a="["===s.charAt(0)&&"]"===s.charAt(s.length-1)?s.slice(1,-1):s,o=parseInt(a,10);!isNaN(o)&&s!==a&&String(o)===a&&o>=0&&i.parseArrays&&o<=i.arrayLimit?(n=[])[o]=t(e,r,i):n[a]=t(e,r,i)}return n}(o,e,r)}},Wn=function(t,e){var r,i,n=t,s=e||{},a=void 0===s.delimiter?Hn.delimiter:s.delimiter,o="boolean"==typeof s.strictNullHandling?s.strictNullHandling:Hn.strictNullHandling,l="boolean"==typeof s.skipNulls?s.skipNulls:Hn.skipNulls,d=("boolean"==typeof s.encode?s.encode:Hn.encode)?"function"==typeof s.encoder?s.encoder:Hn.encoder:null,u="function"==typeof s.sort?s.sort:null,c=void 0!==s.allowDots&&s.allowDots;if(null!==s.encoder&&void 0!==s.encoder&&"function"!=typeof s.encoder)throw new TypeError("Encoder has to be a function.");"function"==typeof s.filter?n=(i=s.filter)("",n):Array.isArray(s.filter)&&(r=i=s.filter);var h,f=[];if("object"!=typeof n||null===n)return"";h=s.arrayFormat in Gn?s.arrayFormat:"indices"in s?s.indices?"indices":"repeat":"indices";var p=Gn[h];r||(r=Object.keys(n)),u&&r.sort(u);for(var g=0;g<r.length;++g){var v=r[g];l&&null===n[v]||(f=f.concat(jn(n[v],v,p,o,l,d,i,u,c)))}return f.join(a)},zn=function(t,e){var r=e||{};if(null!==r.decoder&&void 0!==r.decoder&&"function"!=typeof r.decoder)throw new TypeError("Decoder has to be a function.");if(r.delimiter="string"==typeof r.delimiter||Bn.isRegExp(r.delimiter)?r.delimiter:Kn.delimiter,r.depth="number"==typeof r.depth?r.depth:Kn.depth,r.arrayLimit="number"==typeof r.arrayLimit?r.arrayLimit:Kn.arrayLimit,r.parseArrays=!1!==r.parseArrays,r.decoder="function"==typeof r.decoder?r.decoder:Kn.decoder,r.allowDots="boolean"==typeof r.allowDots?r.allowDots:Kn.allowDots,r.plainObjects="boolean"==typeof r.plainObjects?r.plainObjects:Kn.plainObjects,r.allowPrototypes="boolean"==typeof r.allowPrototypes?r.allowPrototypes:Kn.allowPrototypes,r.parameterLimit="number"==typeof r.parameterLimit?r.parameterLimit:Kn.parameterLimit,r.strictNullHandling="boolean"==typeof r.strictNullHandling?r.strictNullHandling:Kn.strictNullHandling,""===t||null==t)return r.plainObjects?Object.create(null):{};for(var i="string"==typeof t?function(t,e){for(var r={},i=t.split(e.delimiter,e.parameterLimit===1/0?void 0:e.parameterLimit),n=0;n<i.length;++n){var s,a,o=i[n],l=-1===o.indexOf("]=")?o.indexOf("="):o.indexOf("]=")+1;-1===l?(s=e.decoder(o),a=e.strictNullHandling?null:""):(s=e.decoder(o.slice(0,l)),a=e.decoder(o.slice(l+1))),Vn.call(r,s)?r[s]=[].concat(r[s]).concat(a):r[s]=a}return r}(t,r):t,n=r.plainObjects?Object.create(null):{},s=Object.keys(i),a=0;a<s.length;++a){var o=s[a],l=qn(o,i[o],r);n=Bn.merge(n,l,r)}return Bn.compact(n)};const Yn=Pe("fpads:macros"),Xn=/\[([\s\S]+?)\]/g;class Macros{constructor(t={},e=Xn){this.vars=t,this.pattern=e}static run(t){try{return t()}catch(t){return void console.error(t)}}static merge(...t){return t.reduce((t,e)=>Object.assign(t,e),{})}static cast(t){return void 0===t?"":"function"==typeof t?encodeURIComponent(Macros.run(t)||""):"string"==typeof t?encodeURIComponent(t):"number"==typeof t||"boolean"==typeof t?t.toString():""}static normalize(t){return t.trim()}static process_obj(t,e,r){return Object.keys(t).reduce((i,n)=>{const s=Macros.process_str(n,e,r,!0),a=t[n];return null===a?(i[s]=a,i):"object"==typeof a?(i[s]=Macros.process_obj(a,e,r),i):"string"==typeof a?(i[s]=Macros.process_str(a,e,r),i):(console.error(new Error(`${a} at ${n} not a handled Macro type`)),i)},{})}static process_str(t,e,r,i=!1){return t.replace(e.pattern,(t,e)=>{const n=Macros.normalize(e);if(!(n in r)||void 0===r[n])return t;const s=r[n],a=i?s:Macros.cast(s);return Yn("Macro.replace(raw: %s, macro: %s, value: %s)",i,e,a),a})}fork(t={},e=this.pattern){const r=Macros.merge(this.vars,t);return new Macros(r,e)}compile(t,e={}){const r=Macros.merge(this.vars,e),[i,n]=t.split("?"),s=zn(n||"",{strictNullHandling:!0,decoder:t=>t}),a=Wn(Macros.process_obj(s,this,r),{encode:!1,strictNullHandling:!0});return Macros.process_str(i,this,r,!0)+"?"+a}}function Qn(t,e={width:0,height:0}){let r,i;try{const t=document.createElement("a");t.href=r=window.location!=window.parent.location?document.referrer:document.location.href,i=t.hostname}catch(t){console.error(t)}const{width:n,height:s}=e,{video_source:a}=t||{},o=function(){const t=window;return"object"==typeof t.__flowplayerAdParameters?t.__flowplayerAdParameters:{}}();return Object.assign({random:Date.now(),page_url:r,domain:i,player_width:n,player_height:s,video_url:a,videourl:a},o)}Macros.patterns={BRACKETS:Xn,CURLY:/\{([\s\S]+?)\}/g,UNDERSCORE:/__([\s\S]+?)__/g};const $n=/^flowplayer:\/\/(.+)/;async function Zn(t){if("string"==typeof t&&$n.test(t)){const e=$n.exec(t),r=e&&window[e[1]];if(r)return Zn(r)}if("function"!=typeof t)return t;try{return await t()}catch(t){return""}}class Schedule{constructor(t,e={}){this._ads=t,this._opts=e,this._nextIndex=0,this._postroll=void 0,this._loadPending=!1,this._postrollActive=!1,this.reset(this._ads)}toJSON(){const t=(this._ads||[]).slice(this._nextIndex);return this._postroll&&t.push(this._postroll),t}reset(t){this.setAds(t),this._nextIndex=0,this._postrollActive=!1}resetCounter(){this._nextIndex=0,this._postrollActive=!1}setAds(t){this._ads=t||[],this.sort()}getAds(){return this._ads}getNextAd(t){return this._ads[this._nextIndex]||t}getCurrentAd(){return this._postrollActive?this._postroll:this._loadPending?0:this._ads[this._nextIndex-1]}getPostroll(){return this._postroll}isDrained(){return this._nextIndex+1>this._ads.length}setPostrollActive(){this._postrollActive=!0}updateContentDuration(t){this._opts.content_duration=t}increment(){++this._nextIndex}decrement(){this._nextIndex>0&&--this._nextIndex}getNextIndex(){return this._nextIndex}getCurrentType(){const t=this.getCurrentAd();if(t)return Schedule.kindOf(t.time)}sort(){this._postroll=this._ads.find(t=>-1===t.time),this._ads=this._ads.filter(t=>t!==this._postroll).sort((t,e)=>t.time===e.time?this._ads.indexOf(t)-this._ads.indexOf(e):t.time-e.time)}shallPlayAd(t){if(this._loadPending)return!1;const e=this.getCurrentAd()||this.getNextAd();return!!(e&&e.time<=t&&-1!==e.time)}shallPlayNext(){const t=this.getNextAd(),e=this.getCurrentAd();return!(!t||!e||t.time!==e.time)}waitForLoad(t,e,r){if(this._loadPending=!1,!e)return!1;const i=r?this._opts.preload_advance:0;return e.time>=0?this._loadPending=t<e.time-i:-1===e.time&&(this._loadPending=this._opts.content_duration>0&&-1!==t?t<this._opts.content_duration-i:-1!==t),this._loadPending}static hasPreroll(t){return!!t.find(t=>0===t.time)}static isOutstream(t){return Schedule.hasPreroll(t)&&!!t[0].outstream}static kindOf(t){switch(t){case 0:return"preroll";case-1:return"postroll";default:return"midroll"}}}const Jn=Object.prototype,ts=Object.getPrototypeOf;const es=Pe("fpads:ads:state");var rs;!function(t){t[t.IDLE=0]="IDLE",t[t.INITIALIZING=1]="INITIALIZING",t[t.FETCHING_AD=2]="FETCHING_AD",t[t.AD_AVAILABLE=4]="AD_AVAILABLE",t[t.BREAK_ACTIVE=8]="BREAK_ACTIVE",t[t.PLAYING=16]="PLAYING",t[t.FATAL_ERROR=32]="FATAL_ERROR"}(rs||(rs={}));class AdsState{constructor(t=0){this._state=t}static of(){return new AdsState}reset(){this._state=0}toggleState(t,e){return void 0===t&&es(new Error("AdState cannot toggleState for `undefined`")),null==typeof e?this._state^=t:e?void(this._state|=t):this._state&=~t}hasAll(t){return this._state==(this._state|t)}hasAny(t){return!!(this._state&t)}get state(){return this._state}}const is={ok:Pe("fpads:analytics:request-queue"),err:Pe("fpads:analytics:request-queue:err"),warn:Pe("fpads:analytics:request-queue:warn")};class RequestQueue{constructor(t=[],e=[],r={failures:0,ttl:0}){this.pending=t,this.open=e,this.stats=r}static of(){return new RequestQueue}static is_empty(t){return 0==t.pending.length}static is_high_water(t){return t.open.length==RequestQueue.MAX_OPEN_REQUESTS}static maybe_spawn_req(t){if(RequestQueue.is_empty(t))return is.ok("maybe_spawn_req called Queue that is EMPTY"),t;if(RequestQueue.is_high_water(t))return is.warn("maybe_spawn_req called on Queue that is HIGH_WATER"),t;try{const e=RequestQueue.lpop(t);e&&RequestQueue.request(t,e)}catch(t){is.err(t)}}static increment_failures(t){return t.stats.failures++,t.stats.failures>RequestQueue.MAX_FAILURE_COUNT&&(t.stats.ttl=Date.now()+RequestQueue.REQUEST_TTL_MS),t}static handle_error(t,e){RequestQueue.rm(t,e),RequestQueue.increment_failures(t)}static request(t,[e,r,i]){if(is.ok(`Request[${i.event_type}] request`,i,t.stats),Date.now()<t.stats.ttl)return is.warn(`Request[${i.event_type}] skipping because too many errors too quickly`,t.stats);const n=new XMLHttpRequest;t.open.push(n),n.timeout=RequestQueue.REQUEST_TIMEOUT_MS,n.ontimeout=function(){RequestQueue.handle_error(t,n),is.warn(`Request[${i.event_type}] timed out in ${n.timeout}ms`,t.stats)},n.onerror=function(e){RequestQueue.handle_error(t,n),e&&is.err(e),is.warn(`Request[${i.event_type}] encountered an Error`,n.responseText,t.stats)},n.onreadystatechange=function(){n.readyState==XMLHttpRequest.DONE&&RequestQueue.rm(t,n),Math.floor(n.status/100)},n.onload=function(){RequestQueue.rm(t,n),t.stats.failures&&t.stats.failures--,is.ok(`Request[${i.event_type}] :ok`,n.status)},n.open(r,e),n.setRequestHeader("Content-Type","text/plain;charset=UTF-8");try{n.send(JSON.stringify(i))}catch(t){is.err(t)}}static rpush(t,...e){return e.forEach(e=>{if(RequestQueue.is_high_water(t))return is.warn("Too many open requests, skipping",t.stats);t.pending.push(e),RequestQueue.maybe_spawn_req(t)}),t}static lpop(t){return t.pending.shift()}static rm(t,e){const r=t.open.lastIndexOf(e);return~r&&t.open.splice(r,1),t}}RequestQueue.MAX_OPEN_REQUESTS=3,RequestQueue.REQUEST_TIMEOUT_MS=4e3,RequestQueue.REQUEST_TTL_MS=5e3,RequestQueue.MAX_FAILURE_COUNT=3;const ns={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},ss={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},as={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},os={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},ls={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class Utils{static getFirstMatch(t,e){const r=e.match(t);return r&&r.length>0&&r[1]||""}static getSecondMatch(t,e){const r=e.match(t);return r&&r.length>1&&r[2]||""}static matchAndReturnConst(t,e,r){if(t.test(e))return r}static getWindowsVersionName(t){switch(t){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(t){const e=t.split(".").splice(0,2).map(t=>parseInt(t,10)||0);if(e.push(0),10===e[0])switch(e[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(t){const e=t.split(".").splice(0,2).map(t=>parseInt(t,10)||0);if(e.push(0),!(1===e[0]&&e[1]<5))return 1===e[0]&&e[1]<6?"Cupcake":1===e[0]&&e[1]>=6?"Donut":2===e[0]&&e[1]<2?"Eclair":2===e[0]&&2===e[1]?"Froyo":2===e[0]&&e[1]>2?"Gingerbread":3===e[0]?"Honeycomb":4===e[0]&&e[1]<1?"Ice Cream Sandwich":4===e[0]&&e[1]<4?"Jelly Bean":4===e[0]&&e[1]>=4?"KitKat":5===e[0]?"Lollipop":6===e[0]?"Marshmallow":7===e[0]?"Nougat":8===e[0]?"Oreo":9===e[0]?"Pie":void 0}static getVersionPrecision(t){return t.split(".").length}static compareVersions(t,e,r=!1){const i=Utils.getVersionPrecision(t),n=Utils.getVersionPrecision(e);let s=Math.max(i,n),a=0;const o=Utils.map([t,e],t=>{const e=s-Utils.getVersionPrecision(t),r=t+new Array(e+1).join(".0");return Utils.map(r.split("."),t=>new Array(20-t.length).join("0")+t).reverse()});for(r&&(a=s-Math.min(i,n)),s-=1;s>=a;){if(o[0][s]>o[1][s])return 1;if(o[0][s]===o[1][s]){if(s===a)return 0;s-=1}else if(o[0][s]<o[1][s])return-1}}static map(t,e){const r=[];let i;if(Array.prototype.map)return Array.prototype.map.call(t,e);for(i=0;i<t.length;i+=1)r.push(e(t[i]));return r}static find(t,e){let r,i;if(Array.prototype.find)return Array.prototype.find.call(t,e);for(r=0,i=t.length;r<i;r+=1){const i=t[r];if(e(i,r))return i}}static assign(t,...e){const r=t;let i,n;if(Object.assign)return Object.assign(t,...e);for(i=0,n=e.length;i<n;i+=1){const t=e[i];if("object"==typeof t&&null!==t){Object.keys(t).forEach(e=>{r[e]=t[e]})}}return t}static getBrowserAlias(t){return ns[t]}static getBrowserTypeByAlias(t){return ss[t]||""}}const ds=/version\/(\d+(\.?_?\d+)+)/i,us=[{test:[/googlebot/i],describe(t){const e={name:"Googlebot"},r=Utils.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,t)||Utils.getFirstMatch(ds,t);return r&&(e.version=r),e}},{test:[/opera/i],describe(t){const e={name:"Opera"},r=Utils.getFirstMatch(ds,t)||Utils.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/opr\/|opios/i],describe(t){const e={name:"Opera"},r=Utils.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,t)||Utils.getFirstMatch(ds,t);return r&&(e.version=r),e}},{test:[/SamsungBrowser/i],describe(t){const e={name:"Samsung Internet for Android"},r=Utils.getFirstMatch(ds,t)||Utils.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/Whale/i],describe(t){const e={name:"NAVER Whale Browser"},r=Utils.getFirstMatch(ds,t)||Utils.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/MZBrowser/i],describe(t){const e={name:"MZ Browser"},r=Utils.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,t)||Utils.getFirstMatch(ds,t);return r&&(e.version=r),e}},{test:[/focus/i],describe(t){const e={name:"Focus"},r=Utils.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,t)||Utils.getFirstMatch(ds,t);return r&&(e.version=r),e}},{test:[/swing/i],describe(t){const e={name:"Swing"},r=Utils.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,t)||Utils.getFirstMatch(ds,t);return r&&(e.version=r),e}},{test:[/coast/i],describe(t){const e={name:"Opera Coast"},r=Utils.getFirstMatch(ds,t)||Utils.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(t){const e={name:"Opera Touch"},r=Utils.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,t)||Utils.getFirstMatch(ds,t);return r&&(e.version=r),e}},{test:[/yabrowser/i],describe(t){const e={name:"Yandex Browser"},r=Utils.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,t)||Utils.getFirstMatch(ds,t);return r&&(e.version=r),e}},{test:[/ucbrowser/i],describe(t){const e={name:"UC Browser"},r=Utils.getFirstMatch(ds,t)||Utils.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/Maxthon|mxios/i],describe(t){const e={name:"Maxthon"},r=Utils.getFirstMatch(ds,t)||Utils.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/epiphany/i],describe(t){const e={name:"Epiphany"},r=Utils.getFirstMatch(ds,t)||Utils.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/puffin/i],describe(t){const e={name:"Puffin"},r=Utils.getFirstMatch(ds,t)||Utils.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/sleipnir/i],describe(t){const e={name:"Sleipnir"},r=Utils.getFirstMatch(ds,t)||Utils.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/k-meleon/i],describe(t){const e={name:"K-Meleon"},r=Utils.getFirstMatch(ds,t)||Utils.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/micromessenger/i],describe(t){const e={name:"WeChat"},r=Utils.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,t)||Utils.getFirstMatch(ds,t);return r&&(e.version=r),e}},{test:[/qqbrowser/i],describe(t){const e={name:/qqbrowserlite/i.test(t)?"QQ Browser Lite":"QQ Browser"},r=Utils.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,t)||Utils.getFirstMatch(ds,t);return r&&(e.version=r),e}},{test:[/msie|trident/i],describe(t){const e={name:"Internet Explorer"},r=Utils.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/\sedg\//i],describe(t){const e={name:"Microsoft Edge"},r=Utils.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/edg([ea]|ios)/i],describe(t){const e={name:"Microsoft Edge"},r=Utils.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/vivaldi/i],describe(t){const e={name:"Vivaldi"},r=Utils.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/seamonkey/i],describe(t){const e={name:"SeaMonkey"},r=Utils.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/sailfish/i],describe(t){const e={name:"Sailfish"},r=Utils.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,t);return r&&(e.version=r),e}},{test:[/silk/i],describe(t){const e={name:"Amazon Silk"},r=Utils.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/phantom/i],describe(t){const e={name:"PhantomJS"},r=Utils.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/slimerjs/i],describe(t){const e={name:"SlimerJS"},r=Utils.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e={name:"BlackBerry"},r=Utils.getFirstMatch(ds,t)||Utils.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/(web|hpw)[o0]s/i],describe(t){const e={name:"WebOS Browser"},r=Utils.getFirstMatch(ds,t)||Utils.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/bada/i],describe(t){const e={name:"Bada"},r=Utils.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/tizen/i],describe(t){const e={name:"Tizen"},r=Utils.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,t)||Utils.getFirstMatch(ds,t);return r&&(e.version=r),e}},{test:[/qupzilla/i],describe(t){const e={name:"QupZilla"},r=Utils.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,t)||Utils.getFirstMatch(ds,t);return r&&(e.version=r),e}},{test:[/firefox|iceweasel|fxios/i],describe(t){const e={name:"Firefox"},r=Utils.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/electron/i],describe(t){const e={name:"Electron"},r=Utils.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/MiuiBrowser/i],describe(t){const e={name:"Miui"},r=Utils.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/chromium/i],describe(t){const e={name:"Chromium"},r=Utils.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,t)||Utils.getFirstMatch(ds,t);return r&&(e.version=r),e}},{test:[/chrome|crios|crmo/i],describe(t){const e={name:"Chrome"},r=Utils.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/GSA/i],describe(t){const e={name:"Google Search"},r=Utils.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){const e=!t.test(/like android/i),r=t.test(/android/i);return e&&r},describe(t){const e={name:"Android Browser"},r=Utils.getFirstMatch(ds,t);return r&&(e.version=r),e}},{test:[/playstation 4/i],describe(t){const e={name:"PlayStation 4"},r=Utils.getFirstMatch(ds,t);return r&&(e.version=r),e}},{test:[/safari|applewebkit/i],describe(t){const e={name:"Safari"},r=Utils.getFirstMatch(ds,t);return r&&(e.version=r),e}},{test:[/.*/i],describe(t){const e=-1!==t.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:Utils.getFirstMatch(e,t),version:Utils.getSecondMatch(e,t)}}}];var cs=[{test:[/Roku\/DVP/],describe(t){const e=Utils.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,t);return{name:os.Roku,version:e}}},{test:[/windows phone/i],describe(t){const e=Utils.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,t);return{name:os.WindowsPhone,version:e}}},{test:[/windows /i],describe(t){const e=Utils.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,t),r=Utils.getWindowsVersionName(e);return{name:os.Windows,version:e,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(t){const e={name:os.iOS},r=Utils.getSecondMatch(/(Version\/)(\d[\d.]+)/,t);return r&&(e.version=r),e}},{test:[/macintosh/i],describe(t){const e=Utils.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,t).replace(/[_\s]/g,"."),r=Utils.getMacOSVersionName(e),i={name:os.MacOS,version:e};return r&&(i.versionName=r),i}},{test:[/(ipod|iphone|ipad)/i],describe(t){const e=Utils.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,t).replace(/[_\s]/g,".");return{name:os.iOS,version:e}}},{test(t){const e=!t.test(/like android/i),r=t.test(/android/i);return e&&r},describe(t){const e=Utils.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,t),r=Utils.getAndroidVersionName(e),i={name:os.Android,version:e};return r&&(i.versionName=r),i}},{test:[/(web|hpw)[o0]s/i],describe(t){const e=Utils.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,t),r={name:os.WebOS};return e&&e.length&&(r.version=e),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e=Utils.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,t)||Utils.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,t)||Utils.getFirstMatch(/\bbb(\d+)/i,t);return{name:os.BlackBerry,version:e}}},{test:[/bada/i],describe(t){const e=Utils.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,t);return{name:os.Bada,version:e}}},{test:[/tizen/i],describe(t){const e=Utils.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,t);return{name:os.Tizen,version:e}}},{test:[/linux/i],describe:()=>({name:os.Linux})},{test:[/CrOS/],describe:()=>({name:os.ChromeOS})},{test:[/PlayStation 4/],describe(t){const e=Utils.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,t);return{name:os.PlayStation4,version:e}}}],hs=[{test:[/googlebot/i],describe:()=>({type:"bot",vendor:"Google"})},{test:[/huawei/i],describe(t){const e=Utils.getFirstMatch(/(can-l01)/i,t)&&"Nova",r={type:as.mobile,vendor:"Huawei"};return e&&(r.model=e),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:()=>({type:as.tablet,vendor:"Nexus"})},{test:[/ipad/i],describe:()=>({type:as.tablet,vendor:"Apple",model:"iPad"})},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:()=>({type:as.tablet,vendor:"Apple",model:"iPad"})},{test:[/kftt build/i],describe:()=>({type:as.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"})},{test:[/silk/i],describe:()=>({type:as.tablet,vendor:"Amazon"})},{test:[/tablet(?! pc)/i],describe:()=>({type:as.tablet})},{test(t){const e=t.test(/ipod|iphone/i),r=t.test(/like (ipod|iphone)/i);return e&&!r},describe(t){const e=Utils.getFirstMatch(/(ipod|iphone)/i,t);return{type:as.mobile,vendor:"Apple",model:e}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:()=>({type:as.mobile,vendor:"Nexus"})},{test:[/[^-]mobi/i],describe:()=>({type:as.mobile})},{test:t=>"blackberry"===t.getBrowserName(!0),describe:()=>({type:as.mobile,vendor:"BlackBerry"})},{test:t=>"bada"===t.getBrowserName(!0),describe:()=>({type:as.mobile})},{test:t=>"windows phone"===t.getBrowserName(),describe:()=>({type:as.mobile,vendor:"Microsoft"})},{test(t){const e=Number(String(t.getOSVersion()).split(".")[0]);return"android"===t.getOSName(!0)&&e>=3},describe:()=>({type:as.tablet})},{test:t=>"android"===t.getOSName(!0),describe:()=>({type:as.mobile})},{test:t=>"macos"===t.getOSName(!0),describe:()=>({type:as.desktop,vendor:"Apple"})},{test:t=>"windows"===t.getOSName(!0),describe:()=>({type:as.desktop})},{test:t=>"linux"===t.getOSName(!0),describe:()=>({type:as.desktop})},{test:t=>"playstation 4"===t.getOSName(!0),describe:()=>({type:as.tv})},{test:t=>"roku"===t.getOSName(!0),describe:()=>({type:as.tv})}],fs=[{test:t=>"microsoft edge"===t.getBrowserName(!0),describe(t){if(/\sedg\//i.test(t))return{name:ls.Blink};const e=Utils.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,t);return{name:ls.EdgeHTML,version:e}}},{test:[/trident/i],describe(t){const e={name:ls.Trident},r=Utils.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:t=>t.test(/presto/i),describe(t){const e={name:ls.Presto},r=Utils.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){const e=t.test(/gecko/i),r=t.test(/like gecko/i);return e&&!r},describe(t){const e={name:ls.Gecko},r=Utils.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:ls.Blink})},{test:[/(apple)?webkit/i],describe(t){const e={name:ls.WebKit},r=Utils.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}}];class Parser{constructor(t,e=!1){if(null==t||""===t)throw new Error("UserAgent parameter can't be empty");this._ua=t,this.parsedResult={},!0!==e&&this.parse()}getUA(){return this._ua}test(t){return t.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const t=Utils.find(us,t=>{if("function"==typeof t.test)return t.test(this);if(t.test instanceof Array)return t.test.some(t=>this.test(t));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.browser=t.describe(this.getUA())),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(t){return t?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const t=Utils.find(cs,t=>{if("function"==typeof t.test)return t.test(this);if(t.test instanceof Array)return t.test.some(t=>this.test(t));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os}getOSName(t){const{name:e}=this.getOS();return t?String(e).toLowerCase()||"":e||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(t=!1){const{type:e}=this.getPlatform();return t?String(e).toLowerCase()||"":e||""}parsePlatform(){this.parsedResult.platform={};const t=Utils.find(hs,t=>{if("function"==typeof t.test)return t.test(this);if(t.test instanceof Array)return t.test.some(t=>this.test(t));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(t){return t?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const t=Utils.find(fs,t=>{if("function"==typeof t.test)return t.test(this);if(t.test instanceof Array)return t.test.some(t=>this.test(t));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return Utils.assign({},this.parsedResult)}satisfies(t){const e={};let r=0;const i={};let n=0;if(Object.keys(t).forEach(s=>{const a=t[s];"string"==typeof a?(i[s]=a,n+=1):"object"==typeof a&&(e[s]=a,r+=1)}),r>0){const t=Object.keys(e),r=Utils.find(t,t=>this.isOS(t));if(r){const t=this.satisfies(e[r]);if(void 0!==t)return t}const i=Utils.find(t,t=>this.isPlatform(t));if(i){const t=this.satisfies(e[i]);if(void 0!==t)return t}}if(n>0){const t=Object.keys(i),e=Utils.find(t,t=>this.isBrowser(t,!0));if(void 0!==e)return this.compareVersion(i[e])}}isBrowser(t,e=!1){const r=this.getBrowserName().toLowerCase();let i=t.toLowerCase();const n=Utils.getBrowserTypeByAlias(i);return e&&n&&(i=n.toLowerCase()),i===r}compareVersion(t){let e=[0],r=t,i=!1;const n=this.getBrowserVersion();if("string"==typeof n)return">"===t[0]||"<"===t[0]?(r=t.substr(1),"="===t[1]?(i=!0,r=t.substr(2)):e=[],">"===t[0]?e.push(1):e.push(-1)):"="===t[0]?r=t.substr(1):"~"===t[0]&&(i=!0,r=t.substr(1)),e.indexOf(Utils.compareVersions(n,r,i))>-1}isOS(t){return this.getOSName(!0)===String(t).toLowerCase()}isPlatform(t){return this.getPlatformType(!0)===String(t).toLowerCase()}isEngine(t){return this.getEngineName(!0)===String(t).toLowerCase()}is(t,e=!1){return this.isBrowser(t,e)||this.isOS(t)||this.isPlatform(t)}some(t=[]){return t.some(t=>this.is(t))}}
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).flowplayer=e()}(this,(function(){"use strict";const t=[],e=[];function s(){const t="undefined"!=typeof document&&"undefined"!=typeof window,e=t?navigator.userAgent:"",s=/iP(hone|od)/i.test(e)&&!/iPad/.test(e)&&!/IEMobile/i.test(e),r=/Android/.test(e)&&!/Firefox/.test(e),i=/^((?!chrome|android).)*safari/i.test(e),n=/SamsungBrowser/.test(e),a=n&&/SMART-TV/.test(e);return{controls:!s,video:function(e){return t&&document.createElement("video").canPlayType(e)},lang:t&&window.navigator.language,android:r,iphone:s,safari:i,ios:t&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,samsung:n,samsung_tv:n&&a,touch:"ontouchstart"in window,tizen:"tizen"in window,webOS:"webos"in window}}const r="error",i="click",n="dblclick",a="load",o="mouseenter",l="mouseleave",d="mousemove",c="touchmove",u="touchend",h="fullscreenenter",f="fullscreenexit",g="loadedmetadata",p="loadeddata",m="progress",y="loadstart",v="pause",E="playing",T="waiting",_="canplay",S="ended",A="seeked",L="seeking",b="recover",w="reap",R="config",k="landscape",I="portrait",D="retry";var C=Object.freeze({__proto__:null,MOUNT:"mount",ERROR:r,CONTEXT_MENU:"contextmenu",CLICK:i,DBL_CLICK:n,KEYUP:"keyup",KEYDOWN:"keydown",LOAD:a,MOUSE_ENTER:o,MOUSE_LEAVE:l,MOUSE_UP:"mouseup",MOUSE_DOWN:"mousedown",MOUSE_MOVE:d,TOUCH_START:"touchstart",TOUCH_MOVE:c,TOUCH_END:u,TOUCH_CANCEL:"touchcancel",RESIZE:"resize",SCROLL:"scroll",FULLSCREEN_ENTER:h,FULLSCREEN_EXIT:f,FULLSCREEN_CHANGE:"fullscreenchange",WEBKIT_NEEDKEY:"webkitneedkey",METADATA:g,DATA:p,PROGRESS:m,TIME_UPDATE:"timeupdate",LOAD_START:y,VOLUME_CHANGE:"volumechange",PAUSE:v,PLAYING:E,PLAY:"play",WAITING:T,CAN_PLAY:_,ENDED:S,SEEKED:A,SEEKING:L,DURATION_CHANGE:"durationchange",BEFORE_PLAY:"beforeplay",BEFORE_PAUSE:"beforepause",STATE:"state",CUEPOINTS:"cuepoints",CUEPOINT_START:"cuepointstart",CUEPOINT_END:"cuepointend",VIEW_ENTER:"viewenter",VIEW_LEAVE:"viewleave",SOURCE:"src",RECOVER:b,REAP:w,CONFIG:R,QUALITIES:"qualities",VIDEO_TRACKS:"videoTracks",SET_QUALITY:"quality:set",VIDEO_TRACK_SELECT:"tracks:video:select",NON_RECOVERABLE_ERROR:"error:fatal",RECOMMENDATIONS_READY:"recommendationsready",AUDIO_ONLY_SOURCE:"audioonlysource",LANDSCAPE:k,PORTRAIT:I,RENDER_PLUGIN:"renderplugin",DVR:"dvr",LIVE:"live",SEEK_QUEUED:"seek:queued",SEEK_CANCEL:"seek:cancel",PLUGIN_REGISTERED:"plugin:registered",REMOTE_SESSION_STARTED:"remotesession:started",REMOTE_SESSION_ENDED:"remotesession:ended",INTERSECTIONCHANGE:"intersectionchange",RETRY:D});const P="flowplayer-ui",O="flowplayer-logo",M="flowplayer-control",x="flowplayer-live-status",F="flowplayer-elapsed-time",N="flowplayer-timeline-bar",U="flowplayer-volume-bar",B="flowplayer-header",G="flowplayer-header-right-zone",$="flowplayer-middle",H="flowplayer-middle-zone",K="flowplayer-wait",V="flowplayer-small-play-icon",q="flowplayer-small-pause-icon",j="flowplayer-play-icon",W="flowplayer-pause-icon",Y="flowplayer-rewind-icon",z="flowplayer-volume-icon",X="flowplayer-live-countdown";var Q=Object.freeze({__proto__:null,SUBTITLES_MENU:"flowplayer-subtitles-menu",SHARE_MENU:"flowplayer-share-menu",SPEED_MENU:"flowplayer-speed-menu",QUALITY_MENU:"flowplayer-quality-menu",AUDIO_MENU:"flowplayer-audio-menu",VIDEO_MENU:"flowplayer-video-menu",UI:P,LOGO:O,CONTROL:M,CONTROL_BUTTONS:"flowplayer-control-buttons",LIVE_STATUS:x,ELAPSED:F,TIMELINE:N,CONTROL_DURATION:"flowplayer-control-duration",VOLUME_CONTROL:"flowplayer-volume-control",VOLUME_BAR:U,HEADER:B,HEADER_LEFT_ZONE:"flowplayer-header-left-zone",HEADER_RIGHT_ZONE:G,HEADER_DURATION:"flowplayer-header-duration",MIDDLE:$,MIDDLE_ZONE:H,WAIT:K,MIDDLE_BUTTONS:"flowplayer-middle-buttons",MIDDLE_LEFT_ZONE:"flowplayer-middle-left-zone",MIDDLE_RIGHT_ZONE:"flowplayer-middle-right-zone",ENDSCREEN_INTERSTITIAL:"flowplayer-endscreen-interstitial",ENDSCREEN_UP_NEXT:"flowplayer-endscreen-up-next",ENDSCREEN_GRID:"flowplayer-endscreen-grid",PLAYLIST_INTERSTITIAL:"flowplayer-playlist-interstitial",AIRPLAY_ICON:"flowplayer-airplay-icon",CHROMECAST_ICON:"flowplayer-chromecast-icon",SMALL_PLAY_ICON:V,SMALL_PAUSE_ICON:q,PLAY_ICON:j,PAUSE_ICON:W,FULLSCREEN_ENTER_ICON:"flowplayer-fullscreen-enter-icon",FULLSCREEN_EXIT_ICON:"flowplayer-fullscreen-exit-icon",SKIP_NEXT_ICON:"flowplayer-skip-next-icon",SKIP_PREVIOUS_ICON:"flowplayer-skip-previous-icon",FAST_FORWARD_ICON:"flowplayer-fast-forward-icon",REWIND_ICON:Y,SHARE_ICON:"flowplayer-share-icon",VOLUME_ICON:z,MUTE_ICON:"flowplayer-mute-icon",UNMUTE_ICON:"flowplayer-unmute-icon",CLOSE_ICON:"flowplayer-close-icon",FACEBOOK_ICON:"flowplayer-facebook-icon",TWITTER_ICON:"flowplayer-twitter-icon",LINK_ICON:"flowplayer-link-icon",EMBED_ICON:"flowplayer-embed-icon",LIVE_COUNTDOWN:X,PLAYLIST_CONTROLS:"flowplayer-playlist-controls",THUMBNAILS_CAROUSEL:"flowplayer-thumbnails-carousel",ERROR_COMPONENT:"flowplayer-error",TV_MENU:"flowplayer-tv-menu",CUE_COMPONENT:"flowplayer-cue"});const Z="is-playing",J="is-paused",tt="is-loaded",et="is-loading",st="is-starting",rt="is-seeking",it="is-ended",nt="is-live",at="is-waiting",ot="is-live-seeked",lt="no-timeline",dt="will-play",ct="will-pause",ut="is-touched",ht="is-in-viewport",ft="is-source-processing";var gt=Object.freeze({__proto__:null,PLAYING:Z,FULLSCREEN:"is-fullscreen",PAUSED:J,MUTED:"is-muted",LOADED:tt,LOADING:et,STARTING:st,SEEKING:rt,GRABBING:"is-grabbing",DISABLED:"is-disabled",SMALL:"is-small",TINY:"is-tiny",RTL:"is-rtl",TV:"is-tv",ENDED:it,LIVE:nt,ERRORED:"is-error",WAITING:at,AUTOPLAY:"is-autoplay",NO_AUTOPLAY:"no-autoplay",SEAMLESS:"is-seamless",TOGGLING:"is-toggling",LIVE_SEEKED:ot,NO_DVR:lt,HAS_POSTER:"has-poster",WILL_PLAY:dt,WILL_PAUSE:ct,MENU_OPENED:"has-menu-opened",TOUCHED:ut,HOVERED:"is-hovered",TOUCH_DEVICE:"is-touch-device",WILL_SEEK:"will-seek",SEEKABLE:"is-seekable",IN_VIEWPORT:ht,NO_CONTROLS:"no-controls",DESTROYED:"is-destroyed",IS_SOURCE_PROCESSING:ft});function pt(t){this.message=t}pt.prototype=new Error,pt.prototype.name="InvalidCharacterError";var mt="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new pt("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,r,i=0,n=0,a="";r=e.charAt(n++);~r&&(s=i%4?64*s+r:r,i++%4)?a+=String.fromCharCode(255&s>>(-2*i&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return a};var yt=function(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(mt(t).replace(/(.)/g,(function(t,e){var s=e.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s})))}(e)}catch(t){return mt(e)}};function vt(t){this.message=t}vt.prototype=new Error,vt.prototype.name="InvalidTokenError";var Et=function(t,e){if("string"!=typeof t)throw new vt("Invalid token specified");var s=!0===(e=e||{}).header?0:1;try{return JSON.parse(yt(t.split(".")[s]))}catch(t){throw new vt("Invalid token specified: "+t.message)}};Et.InvalidTokenError=vt;const Tt=new Map,_t=(t,e)=>new(((t,e)=>{const s=t.get(e);if(!s)throw new Error(`no flowplayer component with the name ${e} exists`);const r=window.customElements.get(e);if(!r)throw new Error(`no default flowplayer component with the name ${e} exists`);const i=window.customElements.get(s);return"function"!=typeof i?r:i})(t._customElements,e))(t),St=(t,e,s)=>{window.customElements.get(e)||window.customElements.define(e,s),t.customElements.get(e)||t.customElements.set(e,e)};var At,Lt;!function(t){t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=4]="HIGH"}(At||(At={})),function(t){t[t.OFF=0]="OFF",t[t.ON=1]="ON",t[t.AUDIO_REQUIRED=2]="AUDIO_REQUIRED"}(Lt||(Lt={}));function bt(t,e,s){const r="boolean"==typeof s;if("boolean"!=typeof s&&(s=!!t.hasState(ct)||t.paused),function(t,e,s){const r=t.poll(e?"beforeplay":"beforepause",{forced:s});return r&&r.defaultPrevented}(t,s,r))return Promise.resolve();if(!s)return t.hasState(dt)?(t.setState(ct,!0),t.setState(dt,!1),Promise.resolve()):Promise.resolve(t.pause());if(0==t.reaper)return Promise.resolve();const i=t.reaper.get("__pending_play");return t.paused||i?i?(i.src!==Rt(t.original_src)&&wt(t),i):(function(t){return(0==t.networkState||0==t.readyState)&&t.currentSrc==Rt(t.original_src)}(t)&&wt(t),(t=>t.autoplay&&Lt.AUDIO_REQUIRED&t.autoplay)(e)?function(t){t.muted=!1,0==t.volume&&(t.volume=1);return t.play().catch(t=>{console.warn("[flowplayer/play] autoplay audio required\n%s",t.message)})}(t):t.play().then(()=>{t.hasState(ct)&&t.togglePlay(!1)}).catch(e=>(console.warn("[flowplayer/play] attempting muted autoplay\n%s",e.message),t.muted=!0,t.volume=0,t.play()))):(t.setState(ct,!1),!t.hasState(Z)&&t.setState(dt,!0),Promise.resolve())}function wt(t){t.currentSrc.match(/^blob:/)||t.load()}function Rt(t){const e=document.createElement("a");return e.href=t,e.href}function kt(t,e){var s={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(s[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(s[r[i]]=t[r[i]])}return s}function It(t){const e=document.createElement("a");e.href=t;const s=e.pathname&&e.pathname.split(".");return s.length>1&&s[s.length-1]}function Dt(t){switch(t){case"video/mpd":return"application/dash+xml";case"video/m3u8":return"application/x-mpegurl";default:return t}}const Ct=t=>{var{src:e}=t,s=kt(t,["src"]);return[Object.assign({src:e,type:e?Dt("video/"+It(e)):""},s)]};function Pt(t){return Ct({src:t})}function Ot(t){var{src:e,type:s}=t,r=kt(t,["src","type"]);return e&&s?[Object.assign({src:e,type:s},r)]:s&&!e?[Object.assign({type:s},r)]:Ct(Object.assign({src:e},r))}var Mt;function xt(t,e,s,r={safari:!1}){const i=Ft(s);return function(t){[rt,ct,dt,Z,J,et,tt,ot].forEach(e=>t.setState(e,!1)),t.setState(st,!0)}(t),Array(...Array(i.length)).map((t,e)=>e).some(s=>{const n=i[s];if(Mt.Ok==function(t,e,s){t.emit("src",s),"string"==typeof s.src&&(t.original_src=s.src);const r=function(t,e,s){return t.plugins.filter(t=>{return(e=t)&&"wants"in e;var e}).find(t=>t.wants(s.src||"",s,e))}(t,e,s);return t.setOpts({is_native:!r}),r?(r.onload(e,t.root,t,s),Mt.Ok):Mt.Err}(t,e,n)||Mt.Ok==function(t,e,s,r={safari:!1}){var i;/^audio\//.test(s.type||"")&&t.emit("audioonlysource");e.start_time&&(s.src=s.src+"#t="+e.start_time);if(""==t.canPlayType(s.type||""))return Mt.Err;if(s.drm&&(!s.drm["com.apple.fps.1_0"]||!r.safari))return Mt.Err;"string"==typeof s.src&&(t.preload=e.autoplay?"auto":null!==(i=e.preload)&&void 0!==i?i:"auto",t.src=s.src,e.autoplay&&r.safari&&t.load(),"none"!==t.preload&&t.setState(et,!0));return Mt.Ok}(t,e,n,r))return!0;s==i.length-1&&"string"==typeof n.src&&(t.src=n.src)}),function(t,e){!function(t,e){if(!t.currentSrc)return;if("none"==t.opt("preload"))return;if(e.autoplay&&e.autoplay>0)return;t.load()}(t,e)}(t,e),t}function Ft(t){return"string"==typeof t?Pt(t):Array.isArray(t)||"object"!=typeof t?t.reduce((function(t,e){return"string"==typeof e&&(e=Pt(e)),"object"!=typeof e||Array.isArray(e)||(e=Ot(e)),t.concat(e)}),[]):Ot(t)}!function(t){t[t.Err=0]="Err",t[t.Ok=1]="Ok"}(Mt||(Mt={}));const Nt=[w,L,"src","seek:cancel"];var Ut;function Bt(t,e,s){return isNaN(t.duration)||isNaN(t.currentTime)?{}:(e.offset+=s,0==e.offset?Gt(t,e):(e.timer&&clearTimeout(e.timer),e.timer=setTimeout((function(){0!=t.reaper&&(t.currentTime=function(t,e,s=0){return Math.max(Math.min(e,t),s)}(t.currentTime+e.offset,t.duration),e.timer=0,Gt(t,e))}),1e3),function(t,e){t.setState("will-seek",!0),t.setState(Ut.BACKWARD,e.offset<0),t.setState(Ut.FORWARD,e.offset>0)}(t,e),t.emit("seek:queued",e),e))}function Gt(t,e){e.timer&&clearTimeout(e.timer),e.timer=e.offset=0,function(t){t.setState(Ut.FORWARD,!1),t.setState(Ut.BACKWARD,!1),t.setState("will-seek",!1)}(t)}function $t(t,e){const s=t._customElements.get(e);return s&&t.root.querySelector(s)||void 0}function Ht(){if("undefined"==typeof document)return!1;const t=document.documentElement;return t&&"rtl"==t.getAttribute("dir")}function Kt(...t){const e=document.createElement("div");return 0==t.length||e.classList.add(...t),e}function Vt(t,e,s){const r=function(t){return Array.isArray(t)?t.slice(0):t.split(".")}(e);for(;r.length;){if(null==t)return s;const e=r.shift();if("string"!=typeof e)return s;t=t[e]}return null==t?s:t}function qt(t){const e="number"==typeof t?t:parseInt(t,10);return(e>9?"":"0")+e}function jt(t){if(isNaN(t)||t>=Number.MAX_SAFE_INTEGER)return"";const e=t<0?"-":"";t=Math.round(Math.abs(t));const s=Math.floor(t/3600);let r=Math.floor(t/60);return t-=60*r,s>=1?(r-=60*s,e+s+":"+qt(r)+":"+qt(t)):e+qt(r)+":"+qt(t)}!function(t){t.FORWARD="forward",t.BACKWARD="backward"}(Ut||(Ut={}));const Wt=navigator.languages||[navigator.language];function Yt(t,e,s){const r={};return s=e.lang||s,t[s]&&(r[s]=t[s]),function(){try{return Wt.reduce((t,e)=>~e.indexOf("-")?t.concat(e,e.split("-")[0]):t.concat(e),[])}catch(t){return[]}}().forEach((function(e){t[e]&&!r[e]&&(r[e]=t[e])})),Object.values(r)}const zt=[1e7]+""+-1e3+-4e3+-8e3+-1e11,Xt=()=>"undefined"==typeof crypto?"":zt.replace(/[018]/g,t=>(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16));let Qt="";!function(){let t=!1;try{const e=Object.defineProperty({},"passive",{get:function(){t=!0}});window.addEventListener("testPassive",null,e),window.removeEventListener("testPassive",null,e)}catch(t){}}();const Zt=["touchstart","touchmove"];function Jt(t,e){const s=new CustomEvent(t,{detail:e,cancelable:!0});return e&&Object.defineProperty(s,"data",{get:()=>e}),s}function te(t,e,s){const r=Jt(e,s);return t.dispatchEvent(r),t}function ee(t,e,s){const r=Jt(e,s);return t.dispatchEvent(r),r}function se(t,e,s,r){Array.isArray(e)?e.forEach(e=>re(t,e,s,r)):re(t,e,s,r)}function re(t,e,s,r){if(i=e,!~Zt.indexOf(i))return t.addEventListener(e,s,r),t;var i;const n=Object.assign(r||{},{passive:!0});return t.addEventListener(e,s,n),t}function ie(t,e,s,r){return se(t,e,s,Object.assign(r||{},{once:!0}))}class PlayerStorage{constructor(t,e){this.implementation=t,e&&e.keys().forEach(t=>{"string"==typeof e.implementation[t]&&this.implementation.setItem(t,e.implementation[t])})}keys(){var t;const e=[];for(var s=0;s<this.implementation.length;s++)(null===(t=this.implementation.key(s))||void 0===t?void 0:t.startsWith("flowplayer/"))&&e.push(this.implementation.key(s));return e}removeItem(t){try{this.implementation.removeItem("flowplayer/"+t)}catch(t){}}getItem(t){try{return this.implementation.getItem("flowplayer/"+t)}catch(t){return null}}setItem(t,e){try{this.implementation.setItem("flowplayer/"+t,e)}catch(t){}}clear(){try{this.keys().forEach(t=>this.implementation.removeItem(t))}catch(t){}}get length(){try{return this.keys().length}catch(t){return 0}}key(t){try{return this.implementation.key(t)}catch(t){return null}}}class InMemoryStorage{constructor(){this.pairs=[]}get length(){return this.pairs.length}clear(){this.pairs=[]}getItem(t){var e;return(null===(e=this.pairs.find(e=>e[0]===t))||void 0===e?void 0:e[1])||null}key(t){return this.pairs[t][0]||null}removeItem(t){this.pairs=this.pairs.filter(e=>e[0]!==t)}setItem(t,e){this.removeItem(t),this.pairs.push([t,e])}}const ne={preload:"none",rtl:!1,controls:!0},ae=["loop","muted","preload"];function oe(t,r,i){let n;i.live_state={dvr_window:void 0,get dvr(){return n},set dvr(e){n=e;const s=!(!t.live||e);i.hasState(lt)!=s&&i.setState(lt,s)}},i._storage=new PlayerStorage(["localStorage","sessionStorage"].map(t=>{try{const e=window[t];return e.getItem(""),e}catch(e){return console.debug(`Access to window.${t} denied, trying next option`),null}}).find(t=>!!t)||new InMemoryStorage),i.toJSON=function(){return{duration:i.duration,volume:i.volume,currentTime:i.currentTime,states:i.root.className}},i.setSrc=function(e){return xt(i,t,e,s())},i.playerState=i.playerState||{},i.setState=function(t,e){if(i.playerState[t]===!!e)return i;const s=Object.assign({},i.playerState,{[t]:e});return i.playerState=s,te(i,"state",i.playerState),i},i.createComponents=function(...t){return Array.from({length:t.length}).map((e,s)=>_t(this,t[s]))},i.hasState=function(t){return!!i.playerState[t]},i.transitionState=function(t,e,s){!i.hasState(t)&&i.hasState(e)||(s=0),s&&i.setState("is-toggling",!0),i.setState(e,!1),i.setState(t,!0),s&&setTimeout((function(){i.setState("is-toggling",!1)}),s)},i.emit=(t,e)=>(te(i,t,e),i),i.on=(t,e)=>(se(i,t,e),i),i.once=(t,e)=>(ie(i,t,e),i),i.off=(t,e)=>{var s,r;return s=t,r=e,i.removeEventListener(s,r),i},i.poll=(t,e)=>ee(i,t,e),i.togglePlay=function(e){return bt(i,t,e)},i.toggleMute=function(t){t=null==t?!i.muted:!!t,i.muted=t,i.muted||i.volume||(i.volume=1),te(i,"volumechange")},i.toggleDisable=function(t){t=null==t?!i.disabled:!!t,i.setState("is-disabled",t),i.disabled=t},i.destroy=function(){i.pause();const t=e.indexOf(i);~t&&e.splice(t,1),setTimeout((function(){i.setSrc([]),i.reaper&&i.reaper.clear(),te(i,w),i.setState("is-destroyed",!0)}),0)},i.setAttrs=function(t){return ae.forEach(e=>{if(!(e in t))return;const s=t[e];s?i.setAttribute(e,s.toString()):i.removeAttribute(e)}),i},i.opt=function(e,s){return s=void 0===s?Vt(ne,e):s,Vt(t,e,s)},i.i18n=function(t,e){if(!i.reaper)return"";const s=i.reaper.get("translations");return s?function t(e,s,r,i){return(i=i||0)>=e.length?r:Vt(e[i],s,t(e,s,r,i+1))}(s,t,e||""):e||""},i.setOpts=function(e){Object.assign(t,e),t.live&&!i.hasState(nt)&&(i.setState(lt,!0),te(i,"live")),"disabled"in e&&void 0!==e.disabled&&i.toggleDisable(e.disabled),"muted"in e&&void 0!==e.muted&&i.toggleMute(e.muted),"dvr"in t&&(i.live_state.dvr=i.opt("dvr"));const s=!!t.autoplay&&!i.hasState("no-autoplay");i.setState("is-autoplay",s),i.setState("is-rtl",i.opt("rtl",function(t){if(!t)return Ht();const e=t.getAttribute("dir");return e?"rtl"==e:Ht()}(r))),i.setState(nt,!!t.live),i.setState("has-poster","string"==typeof t.poster&&t.poster.length>0),i.setState("is-seekable",!!t.seekable),i.setState("no-controls",0==t.controls),r.style.backgroundImage=i.hasState("has-poster")?"url('"+t.poster+"')":"",te(i,R,t)},i.renderPlugin=function(t){ee(i,"renderplugin",t).defaultPrevented||i.root.appendChild(t)};const a={offset:0,timer:0};var o,l;l=a,(o=i).on(Nt,(function(){Gt(o,l)})),i.enqueueSeek=function(t){if(0!=i.opts.seekable&&!(1==i.opts.disabled&&t>0))return Bt(i,a,t)},i.deviceId=function(){return function(t){if(Qt)return Qt;try{const e=t.getItem("flowplayer/uuid");if(e)return e;const s=Xt();return t.setItem("flowplayer/uuid",s),s}catch(t){return Qt=Xt()}}(i._storage)}}function le(t,e){const s=e.querySelector("video"),r=s||(t._video_element_callback?t._video_element_callback(t):document.createElement("video"));return r.classList.add("fp-engine"),r.playsInline=!0,s||e.append(r),r}var de="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function ce(t,e){if("object"==typeof exports&&"undefined"!=typeof module)return e;if(null===document.currentScript)return e;"flowplayer"in t||(t.flowplayer={extensions:[]});const s=t.flowplayer;return"function"==typeof s?(s(e),e):(Array.isArray(s.extensions)||(s.extensions=[]),~s.extensions.indexOf(e)||s.extensions.push(e),e)}function ue(){return"undefined"!=typeof window?window:void 0!==de?de:{}}const he=["localhost","127.0.0.1","0.0.0.0","s.codepen.io","cdpn.io","try.flowplayer.com"];function fe(t,e){return!!~he.indexOf(t)||t.indexOf(e)===t.length-e.length}fe.check_whitelist=function(t){return!!~he.indexOf(t)};const ge="production";function pe(t,e){const s={valid_jwt:!1,raw:"",data:{acl:0},exp:0};let r={c:"{}",exp:0};e=e||{};try{r=Et(t),s.valid_jwt=!0}catch(t){}return s.raw=t,s.data=JSON.parse(r.c),s.exp=r.exp,e.require_valid_token&&pe.validate(s),s}function me(t){try{return pe.validate(t),{success:!0,message:""}}catch(t){return{success:!1,message:t.message}}}var ye;function ve(t){return{grant:t,is_granted:e=>(t&e)===e}}function Ee({root:t,video:e,data:s}){e&&e.destroy(),console.error(new Error(s.details||s.reason)),t.innerHTML="",t.classList.remove("flowplayer"),t.classList.add("flowplayer-fatal"),t.style.removeProperty("background-image");const r=document.createElement("h2");r.textContent="Playback Error";const i=document.createElement("p");i.textContent="Are you the site owner?";const n=document.createElement("a");n.classList.add("troubleshoot"),n.target="_blank",n.href="https://docs.flowplayer.com/troubleshooting/player#"+s.reason,n.textContent="Troubleshoot?";const a=document.createElement("img");a.src="https://flowplayer.com/user/pages/images/logo-white.png",t.append(r,i,n,a)}pe.validate=function(t){if("string"==typeof t&&(t=pe(t)),!t||!t.raw){if(fe.check_whitelist(window.location.hostname)||"dev"===ge.toString())return!0;throw new Error("No token provided in configuration")}if(!t.valid_jwt)throw new Error("Invalid token provided");const e=window.location.hostname,s=fe.bind(null,e);if("dev"!==ge.toString()&&t.data.domain&&t.data.domain.length&&!t.data.domain.some(s))throw new Error("Domain not allowed");if("dev"!==ge.toString()&&1e3*t.exp-Date.now()<0)throw new Error("Expired token");return!0},pe.id=function(t){if(t)return"string"==typeof t&&(t=pe(t)),t.data.id},function(t){t[t.ADS=2]="ADS",t[t.ANALYTICS=4]="ANALYTICS",t[t.NO_METERING=8]="NO_METERING",t[t.DEVELOPER_PLAN=16]="DEVELOPER_PLAN",t[t.WOWZA_VIDEO=32]="WOWZA_VIDEO"}(ye||(ye={})),ve.of=ve,ve.from_token=function(t){const e=pe(t,{require_valid_token:!0});return ve.of(e.data.acl)},ve.permissions=ye;function Te(t,e){const s=e.clientWidth;e.classList.toggle("is-small",s<600),e.classList.toggle("is-tiny",s<400)}function _e(t,e,r){let i=!0;e.classList.add("flowplayer"),Te(0,e),se(r,[y,"resize"],(function(){Te(0,e)})),se(r,"state",(function(){Object.entries(r.playerState).forEach((function([t,s]){e.classList.toggle(t,s)}))})),se(r,"timeupdate",(function(){r.setState(at,!r.hasState("is-casting")&&!r.hasState(st)&&r.readyState<3)})),se(r,S,(function(e){setTimeout((function(){if(!e.defaultPrevented){if(t.rewind&&!r.loop){const e=r.src;t.autoplay&&(t.autoplay=0,r.setState("is-autoplay",!1)),r.setState(rt,!0),ie(r,A,(function(){e===r.src&&(r.setState(rt,!1),r.pause(),r.setState(st,!0))})),r.currentTime=0}ie(r,"timeupdate",(function(){r.setState(it,!1)})),r.transitionState(it,Z,t.loop||t.rewind?0:300)}}),0)})),se(r,[L,A],(function(t){r.setState(rt,t.type==L)})),se(r,"remotesession:ended",(function(t){setTimeout(()=>r.currentTime=t.detail.currentTime,0)})),se(r,S,(function(){r.setState(Z,!1),i=!0})),se(r,m,()=>{if(!r.opts.live||!r.opts.is_native)return;const t=r.seekable;0!=t.length&&r.emit("dvr/window",t.end(t.length-1)-t.start(0))}),se(r,s().ios?g:p,(function(){var t,e;r.setState(tt,!0),r.setState(et,!1);const s=r;0===(null===(t=s.videoTracks)||void 0===t?void 0:t.length)&&(null===(e=s.audioTracks)||void 0===e?void 0:e.length)>0&&r.emit("audioonlysource")})),se(r,"play",()=>{r.setState(dt,!0)}),se(r,[T,_,y],(function(e){if(!r.hasState(rt)&&(e.type!=_||t.autoplay||r.setState(at,!1),e.type!=y||"none"!=r.opt("preload")||t.autoplay)){if(e.type==y&&t.autoplay)return ie(r,E,(function(){r.setState(at,!1)}));e.type!=T||r.hasState(tt)||r.setState(et,!0),r.setState(it,!1),r.setState(at,e.type==T)}})),se(r,[E,v],(function(e){setTimeout(()=>{const t=new CustomEvent("flowplayer/"+e.type,{detail:r});document.dispatchEvent(t)},0);const s=e.type==E,n=r.currentTime==r.duration,a=s&&i&&t.autoplay||r.hasState(at);if(s&&(r.started=!0,i=!1),r.setState(at,!1).setState(st,!1).setState(dt,!1),!s&&r.setState(ct,!1),n)return;const o=s?Z:J,l=s?J:Z;r.transitionState(o,l,a?0:300),s&&r.setState("no-autoplay",!1)}))}const Se=[0].concat(Array.from({length:100}).map((t,e)=>(e+1)/100));function Ae(t,e,s){if(!window.IntersectionObserver)return;const r={should_resume:!!t.autoplay,has_user_gesture:!1,locked:!1};[u,i].forEach(t=>ie(s,t,()=>r.has_user_gesture=!0)),se(s,"play",(function(){r.locked||(r.should_resume=!0)})),se(s,"src",(function(){r.should_resume=!!t.autoplay})),se(s,v,(function(){r.locked||(r.should_resume=!1)}));const n=()=>{setTimeout(()=>{s.setState(st,!0),s.setState("is-autoplay",!1)},100)};se(s,_,()=>{if(t.autoplay)return s.hasState(ht)&&r.should_resume?s.togglePlay(!0).catch(n):void(t.autopause||s.hasState(ht)||!r.should_resume||ie(s,"viewenter",()=>{t.autoplay&&r.should_resume&&s.togglePlay(!0).catch(n)}))});const a=new IntersectionObserver(t=>{t.forEach(t=>{setTimeout(()=>{const e=t.intersectionRatio,r=s.hasState(ht);if(s.setState(ht,e>=.2),s.emit("intersectionchange",{ratio:e}),r===s.hasState(ht))return;const i=s.hasState(ht)?"viewenter":"viewleave";s.emit(i)},0)})},{threshold:Se});a.observe(e),s.on(w,()=>a.disconnect()),se(s,"viewenter",(function(){r.should_resume&&t.autopause&&!Le()&&s.togglePlay(!0)})),se(s,"viewleave",(function(){if(!t.autopause||Le())return;const e=!s.paused;r.locked=!0,s.pause(),setTimeout((function(){r.should_resume=e,r.locked=!1}),0)}))}function Le(){return e.find(t=>t.hasState("is-casting"))}function be(t,e){if(!window.ResizeObserver)return;const s=new ResizeObserver(t=>{const s=t[t.length-1];e.emit("resize",s)});s.observe(t),e.on(w,()=>s.disconnect())}function we(t){if("number"==typeof t&&!isNaN(t))return Number(t);if("string"==typeof t){const e=t.split(":");return Number(e[1])/Number(e[0])}return t}function Re(t,e,s){const r=!!t.ratio,i=document.createElement("div");i.classList.add("fp-ratio"),e.append(i);let n=we(t.ratio||.5625);i.style.paddingTop=100*n+"%";const a=[p,g];s.on(a,(function(){if(r)return;const t=s.videoHeight&&s.videoWidth&&s.videoHeight/s.videoWidth;t&&s.setOpts({ratio:t})})),s.on(R,(function(){const e=s.videoHeight&&s.videoWidth&&s.videoHeight/s.videoWidth,r=we((null==t?void 0:t.ratio)||e||.5625);n!==r&&(n=r,i.style.paddingTop=100*r+"%")}))}class ExplorerPlan{constructor(){this.cleanUp=this.cleanUp.bind(this),this.render=this.render.bind(this),this.wireUp=this.wireUp.bind(this)}init(t,e,s){this.root=e,this.player=s,this.wireUp()}wireUp(){var t,e;this.cleanUp(),null===(t=this.player)||void 0===t||t.once(E,this.render),null===(e=this.player)||void 0===e||e.once(S,this.wireUp)}cleanUp(){var t,e,s,r;null===(e=null===(t=this._logo)||void 0===t?void 0:t.parentElement)||void 0===e||e.removeChild(this._logo),null===(s=this.player)||void 0===s||s.off(E,this.render),null===(r=this.player)||void 0===r||r.off(S,this.wireUp)}render(){var t,e,s;null===(e=null===(t=this._logo)||void 0===t?void 0:t.parentElement)||void 0===e||e.removeChild(this._logo);const r=(null===(s=this.root)||void 0===s?void 0:s.querySelector(".fp-ui"))||this.root;if(!r)return;const i=this._logo=document.createElement("a");i.href="https://explorer.flowplayer.com",i.target="_blank",Object.entries(ke).forEach(([t,e])=>{i.style.setProperty(t,e,"important")}),r.appendChild(i)}}const ke={display:"block",opacity:"1",visibility:"visible",width:"33%","padding-top":"9%",position:"absolute","z-index":"9999",bottom:"25%",left:"10%","background-size":"cover","background-image":"url(https://static.flowplayer.com/explorer/explorer.svg)"},Ie="flowplayer/"+E;function De(t){const e=e=>{e.detail!==t&&!1===t.opt("multiplay")&&t.togglePlay(!1)};t.on(w,()=>document.removeEventListener(Ie,e)),document.addEventListener(Ie,e)}function Ce(t,e){const s=[];t.addEventListener("contextmenu",r=>{const i=r.timeStamp;for(s.push(i);s.length>3;)s.shift();s.length>=3&&s.every(t=>t-i<3e3)&&(console.debug("flowplayer/debug rendering info"),function(t,e){var s;!function(t){const e=t.querySelector(".debug-info");null==e||e.remove()}(t);const r=document.createElement("div");r.classList.add("debug-info");const i=Pe("flowplayer.version","3.8.0");r.append(i);const n=null===(s=null==e?void 0:e.hls)||void 0===s?void 0:s.constructor;if(n&&n.version){const t=Pe("hls.version",n.version);r.append(t)}t.appendChild(r)}(t,e))})}const Pe=(t,e)=>{const s=document.createElement("div");s.classList.add("row",t);const r=document.createElement("span");r.classList.add("attr"),r.textContent=t;const i=document.createElement("span");return i.textContent=e,i.classList.add("value"),s.append(r,i),s};function Oe(t,e){const s=function(){try{return localStorage.getItem("flowplayer/debug")}catch(t){return""}}(),r=(r,...i)=>{try{const n=(null==e?void 0:e.debug)||s;n&&t.match(n)&&console.log(`flowplayer/${t} -- ${r}`,...i)}catch(t){console.warn(t)}};return r.log=r,r}function Me(t){return e=>{setTimeout((function(){if(!e.defaultPrevented)return t(e)}),0)}}const xe=Oe("core/retry");function Fe(t,e){const s={pending:void 0,count:0};t.on(r,r=>{e.retry&&void 0===s.pending&&(++s.count,s.pending=function(t,e){return setTimeout(()=>{t.hasState("is-destroyed")||(e.pending=void 0,[b,D].forEach(e=>t.emit(e)),xe("%s try",e.count))},3e3*e.count)}(t,s))}),t.on(E,()=>{s.count=0}),t.on(["src",b],()=>{s.pending&&(clearTimeout(s.pending),s.pending=void 0)}),t.on(D,Me(e=>{e.defaultPrevented||t.load()}))}const Ne=function(){const t=ue(),e=t.flowplayer?t.flowplayer:{extensions:[]};return Array.isArray(e.extensions)||(e.extensions=[]),e}();function Ue(s,r){if("function"==typeof s)return t.push(...[...arguments].filter(t=>"function"==typeof t)),Ue;"string"==typeof r&&(r={src:r}),r||(r={}),r.token||"string"!=typeof window.__FLOWPLAYER_TOKEN||(r.token=window.__FLOWPLAYER_TOKEN);const i="string"==typeof s?document.querySelector(s):s;if(!i)return console.error(new Error("Flowplayer: '"+s.toString()+"' not found"));const n=i.querySelector("video.fp-engine");if(n)return n;const a=me(r.token);if(!a.success)return Ee({root:i,data:{reason:"token",details:a.message}});const o=new Map,l=le(r,i);l.reaper=o,l._customElements=Tt,Object.defineProperty(l,"token",{value:"string"==typeof r.token?pe.id(r.token):"",writable:!1}),l.addEventListener(w,()=>{o.clear(),l.reaper=0,delete l.root}),l.root=i,r.token&&ve.from_token(r.token).is_granted(ve.permissions.DEVELOPER_PLAN)&&t.push(ExplorerPlan),!~e.indexOf(l)&&e.push(l),oe(r,i,l),l.setAttrs(r),l.plugins=Ue.extensions.map(t=>new t(Ue,l)),_e(r,i,l),Ae(r,i,l),be(i,l),Re(r,i,l),De(l),Ce(i,l),Fe(l,r),l.plugins.forEach(t=>{try{t.init(r,i,l)}catch(e){console.log("Error(plugin/%s)",t.constructor.name,e)}}),l.setOpts(r),l.opts=r,r.src&&l.setSrc(r.src);const d=l.readyState;return d>0&&l.currentSrc&&l.emit(g),d>2&&l.currentSrc&&l.emit(_),l.emit("mount"),l.on("error:fatal",(function(t){Ee({root:i,video:l,data:t.data||{}})})),setTimeout(te,0,document,"flowplayer:player:created",l),l}Object.assign(Ue,Ne),function(r){Array.isArray(r.extensions)&&r.extensions.forEach(e=>t.push(e)),r.customElements=Tt,r.defaultElements=Q,r.version="3.8.0",r.commit="c8d588bc6eb9d5019caf438eece44601ab45298a",r.instances=e,r.extensions=t,r.support=s,r.events=C,r.states=gt,r.jwt=Et,r.autoplay=Lt,r.quality=At}(Ue),"object"==typeof document&&setTimeout(te,0,document,"flowplayer:umd",Ue);var Be="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Ge(t){var e={exports:{}};return t(e,e.exports),e.exports}var $e=Ge((function(t,e){var s=Be&&Be.__assign||function(){return(s=Object.assign||function(t){for(var e,s=1,r=arguments.length;s<r;s++)for(var i in e=arguments[s])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};e.__esModule=!0,e.remove=e.downcase=e.pluck=e.merge=void 0,e.merge=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return t.reduce((function(t,e){return s(s({},t),e)}),{})},e.pluck=function(t){for(var s=[],r=1;r<arguments.length;r++)s[r-1]=arguments[r];return Object.keys(t).filter((function(t){return~s.indexOf(t)})).reduce((function(s,r){var i;return e.merge(s,((i={})[r]=t[r],i))}),{})},e.downcase=function(t){return(t||"").toString().toLowerCase()},e.remove=function(t,e){var s=t.lastIndexOf(e);return~s&&t.splice(s,1),t}})),He=Ge((function(t,e){var s=Be&&Be.__createBinding||(Object.create?function(t,e,s,r){void 0===r&&(r=s),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[s]}})}:function(t,e,s,r){void 0===r&&(r=s),t[r]=e[s]}),r=Be&&Be.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=Be&&Be.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var i in t)"default"!==i&&Object.hasOwnProperty.call(t,i)&&s(e,t,i);return r(e,t),e};e.__esModule=!0;var n=i($e),a=function(){function t(){this.pending=[],this.open=[],this.stats={failures:0,ttl:0}}return t.of=function(){return new t},t.is_empty=function(t){return 0==t.pending.length},t.is_high_water=function(e){return e.open.length==t.MAX_OPEN_REQUESTS},t.maybe_spawn_req=function(e){if(t.is_empty(e))return e;if(t.is_high_water(e))return e;try{var s=t.lpop(e);s&&t.request(e,s)}catch(t){}},t.increment_failures=function(e){return e.stats.failures++,e.stats.failures>t.MAX_FAILURE_COUNT&&(e.stats.ttl=Date.now()+t.REQUEST_TTL_MS),e},t.handle_error=function(e,s){t.rm(e,s),t.increment_failures(e)},t.request=function(e,s){var r=s[0],i=s[1],n=s[2];if(!(Date.now()<e.stats.ttl)){var a=new XMLHttpRequest;e.open.push(a),a.timeout=t.REQUEST_TIMEOUT_MS,a.ontimeout=function(){t.handle_error(e,a)},a.onerror=function(s){t.handle_error(e,a)},a.onreadystatechange=function(){a.readyState==XMLHttpRequest.DONE&&t.rm(e,a),Math.floor(a.status/100)},a.onload=function(){t.rm(e,a),e.stats.failures&&e.stats.failures--},a.open(i,r),a.setRequestHeader("Content-Type","text/plain;charset=UTF-8");try{a.send(JSON.stringify(n))}catch(t){}}},t.rpush=function(e){for(var s=[],r=1;r<arguments.length;r++)s[r-1]=arguments[r];return s.forEach((function(s){e.pending.length>=t.MAX_PENDING||(e.pending.push(s),t.maybe_spawn_req(e))})),e},t.lpop=function(t){return t.pending.shift()},t.rm=function(t,e){return n.remove(t.open,e),t},t.MAX_OPEN_REQUESTS=3,t.MAX_PENDING=5,t.REQUEST_TIMEOUT_MS=4e3,t.REQUEST_TTL_MS=5e3,t.MAX_FAILURE_COUNT=3,t}();e.default=a})),Ke=Ge((function(t,e){var s=Be&&Be.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};e.__esModule=!0;var r=s(He);e.default=r.default.of()})),Ve=Ge((function(t,e){e.__esModule=!0,e.prepare_url=e.URL_PARAM=void 0,e.URL_PARAM=/:([a-zA-Z_]+)/g,e.prepare_url=function(t,s){return t.url.replace(e.URL_PARAM,(function(e){if((e=e.slice(1,e.length))in s)return s[e].toString();t.log.error(new Error("\n preparing url["+t.url+"] failed\n \n parameter["+e+"] not detected in params:\n \n "+JSON.stringify(s,null,2)+"\n "))}))}})),qe=Ge((function(t,e){e.__esModule=!0,e.Log=void 0;var s=function(){function t(t){this.emitter=t}return t.prepare=function(t,e){var s=document.createEvent("Event");return s.initEvent(t,!1,!0),s.ns=t,s.data=e,s},t.of=function(e){return new t(e)},t.prototype.info=function(e){this.emitter.dispatchEvent(t.prepare(t.NAMESPACE.INFO,e))},t.prototype.error=function(e){this.emitter.dispatchEvent(t.prepare(t.NAMESPACE.ERROR,e))},t.prototype.warn=function(e){this.emitter.dispatchEvent(t.prepare(t.NAMESPACE.WARN,e))},t.NAMESPACE={INFO:"tracker:info",ERROR:"tracker:err",WARN:"tracker:warn"},t}();e.Log=s})),je=Ge((function(t,e){var s;e.__esModule=!0,e.Verb=void 0,(s=e.Verb||(e.Verb={})).POST="POST",s.PUT="PUT",s.GET="GET"})),We=Ge((function(t,e){var s=Be&&Be.__createBinding||(Object.create?function(t,e,s,r){void 0===r&&(r=s),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[s]}})}:function(t,e,s,r){void 0===r&&(r=s),t[r]=e[s]}),r=Be&&Be.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=Be&&Be.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var i in t)"default"!==i&&Object.hasOwnProperty.call(t,i)&&s(e,t,i);return r(e,t),e},n=Be&&Be.__spreadArrays||function(){for(var t=0,e=0,s=arguments.length;e<s;e++)t+=arguments[e].length;var r=Array(t),i=0;for(e=0;e<s;e++)for(var n=arguments[e],a=0,o=n.length;a<o;a++,i++)r[i]=n[a];return r},a=Be&&Be.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};e.__esModule=!0;var o=a(Ke),l=a(He),d=i(Ve),c=i($e),u=function(){function t(e,s){var r=this;void 0===s&&(s={});var i=this;if(this.emitter=e,this.url=s.url,this.log=qe.Log.of(this.emitter),this.verb=s.verb,this.metadata=c.merge({},s.metadata||{}),this.rq=s.rq||o.default,this.events=s.events||[],this.required_keys=s.required_keys||[],this.optional_keys=s.optional_keys||[],this.listeners=[],this.valid_keys=this.required_keys.slice(0).concat(this.optional_keys),t.assert_emitter_api(this.emitter),void 0===t.verb[this.verb])throw new Error("invalid HTTP verb["+this.verb+"] passed");if("string"!=typeof this.url)throw new Error("invalid API url["+this.url+"] passed");t.TRACKERS.push(this),i.events.forEach((function(e){t.create_listener(r,e,(function(s){void 0===s&&(s={});var n=c.merge(i.metadata,{event_type:e},s.data||s),a=d.prepare_url(i,n),o=t.pluck_valid_keys(i,n),u=t.ensure_required_keys(i,o);if(u.length)return i.log.error("Tracker.validate_metadata() failed for \n Event["+e+"]\n missing keys: "+u+"\n payload:\n "+JSON.stringify(o,null,2));l.default.rpush(r.rq,[a,r.verb,o])}))}))}return t.of=function(e,s){return new t(e,s)},t.ensure_required_keys=function(t,e){return t.required_keys.filter((function(t){return!(t in e)}))},t.pluck_valid_keys=function(t,e){return c.pluck.apply(c,n([e],t.valid_keys))},t.merge_metadata=function(e,s){return void 0===s&&(s={}),e.metadata=t.pluck_valid_keys(e,c.merge(e.metadata,s)),e},t.assert_emitter_api=function(t){if("function"!=typeof(t||{}).addEventListener)throw new Error("Tracker() received an emitter that does not implement the addEventListener method");if("function"!=typeof(t||{}).removeEventListener)throw new Error("Tracker() received an emitter that does not implement the removeEventListener method")},t.create_listener=function(t,e,s){t.listeners.push([e,s]),t.emitter.addEventListener(e,s)},t.prototype.destroy=function(){var e=this;this.listeners.forEach((function(t){var s=t[0],r=t[1];return e.emitter.removeEventListener(s,r)})),delete this.rq,delete this.emitter,c.remove(t.TRACKERS,this)},t.prototype.put=function(e){return void 0===e&&(e={}),t.merge_metadata(this,e),this},t.TRACKERS=[],t.QUEUE=o.default,t.verb=je.Verb,t}();e.default=u})),Ye=Ge((function(t,e){var s=Be&&Be.__createBinding||(Object.create?function(t,e,s,r){void 0===r&&(r=s),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[s]}})}:function(t,e,s,r){void 0===r&&(r=s),t[r]=e[s]}),r=Be&&Be.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=Be&&Be.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var i in t)"default"!==i&&Object.hasOwnProperty.call(t,i)&&s(e,t,i);return r(e,t),e},n=Be&&Be.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};e.__esModule=!0,e.API=e.Tracker=void 0;var a=n(We);e.Tracker=a.default;var o=i(Ve);e.API=o})),ze="ping",Xe="display",Qe="view";const Ze=["sitegroup_id","session_id","media_id","site_id","player_id","video_type"],Je=["created","position"],ts=["player_version","created","source","category","category_id","autoplay","muted","customer_user_id"];function es(t,e){return t.duration/1===t.duration&&Object.assign(e,function(t){const e=t/100;return{segment_duration:e,breakpoints:Array(...Array(100)).map((function(t,s){return Math.floor(s*e*1e3)/1e3}))}}(t.duration))}function ss(t,e,s){if(!e.segment_duration&&!es(t,e))return;const r=function(t,e,s){const r=e.last_idx,i=s?99:rs(t,e);return e.last_idx=i,i<=r?[]:e.breakpoints.slice(r,99==i?100:i).map((function(t){return e.breakpoints.indexOf(t)}))}(t,e,s);0!=r.length&&t.emit(ze,{position:r})}function rs(t,e){return Math.min(Math.floor(t.currentTime/e.segment_duration),99)}function is(){try{return window.location!==window.parent.location?document.referrer:document.location.href}catch(t){return!1}}const ns="vod",as="live",os=[Xe,ze,Qe];function ls(t,e,s){switch(null==e?void 0:e.kind){case"live":return function(t,e){const s=Date.now();s-e.last_tracked_ts<6e4||(e.last_tracked_ts=s,++e.ticks,t.emit(ze,{position:60*e.ticks}))}(t,e);case"vod":return ss(t,e,"boolean"==typeof s&&s)}}function ds(t){const e=t.ads;return void 0!==e&&(void 0!==e.schedule&&("function"==typeof e.hasPreroll&&(e.currentRequests?e.currentRequests:!!e.adPlaying||!(!e.hasPreroll()||0!=e.nextIndex))))}class Analytics$1{init(t,e,s){if(!ve.from_token(t.token||"").is_granted(ve.permissions.ANALYTICS))return;if(s.hasState("consent-no-tracking"))return;if(s.analytics)return;const r=s.analytics={ticker:void 0,last_media_id:"",ended:!1},i={locked:!1,ttl:6e3,task:()=>{ls(s,r.ticker)}};const n={session_id:s.deviceId(),autoplay:s.autoplay,muted:s.muted,player_id:t.player_id,customer_user_id:t.customer_user_id,player_version:"3.8.0"},a=Ye.Tracker.of(s,{verb:Ye.Tracker.verb.POST,url:"https://ptm.flowplayer.com/:video_type/:sitegroup_id/:event_type",events:os,required_keys:Ze,optional_keys:ts.concat(Je).slice(0),metadata:n});s.on(w,(function(){a&&a.destroy()})),s.on(R,(function(e){if(!a)return;const i=Vt(e,"data.metadata",{});if(!i.media_id)return;const n=Vt(a,"metadata.media_id");if(n&&i.media_id==n)return;const o=Vt(t,"analytics",{});a.put(i),a.put(o);const l=Vt(t,"metadata.live_start_time",t.live)?as:ns;a.put({video_type:l,source:t.source||is()||""}),r.ticker=t.live?{ticks:0,last_tracked_ts:Date.now(),kind:"live"}:{last_idx:0,segment_duration:0,breakpoints:[],kind:"vod"},r.ended=!1,s.emit(Xe)}));let o=0;s.on(E,(function(){if(!a)return;if(o||function(t,e){return t.metadata.media_id&&t.metadata.media_id==e.last_media_id}(a,r))return;a.put({muted:s.muted});const t=ds(s);if(t)return o=Promise.resolve(t).then((function(){r.last_media_id=a.metadata.media_id,s.emit(Qe),o=0})).catch((function(){o=0}));r.last_media_id=a.metadata.media_id,s.emit(Qe)})),s.on("timeupdate",(function(){var e;a&&(o||ds(s)||r.ended||(!t.live&&s.currentTime+.25>=s.duration&&ls(s,r.ticker,!0),(e=i).locked||(e.locked=setTimeout((function(){return e.task(),function(t){return t.locked=!1,t}(e)}),e.ttl))))})),s.on(A,(function(){a&&r.ticker&&"vod"==r.ticker.kind&&function(t,e){es(t,e),e.last_idx=rs(t,e)}(s,r.ticker)})),s.on(S,(function(){a&&function(t,e){e.ended||(e.ended=!0,ls(t,e.ticker))}(s,r)}))}}var cs;function us(t){switch(t){case cs.MEDIA_PLAYBACK_ABORTED:return"media playback was aborted";case cs.MEDIA_ERR_NETWORK:return"a network error occurred";case cs.MEDIA_ERR_DECODE:return"unable to decode media content";case cs.MEDIA_ERR_SRC_NOT_SUPPORTED:return"unsupported media type";case cs.NO_INTERNET:return"no internet connection detected";case cs.MIXED_CONTENT:return"cannot load insecure content in a secure context";default:return"an unknown error occurred"}}function hs(){}function fs(){return"https:"===location.protocol}function gs(t){const e=document.createElement("a");return e.href=t,e}function ps(t){try{return!!new URL(t)}catch(t){return!1}}ce(ue(),Analytics$1),"undefined"!=typeof window&&window.matchMedia&&[k,I].forEach((function(t){window.matchMedia("(orientation: "+t+")").addListener((function(s){e.length&&e.forEach((function(e){s.matches&&e.emit(t)}))}))})),function(t){t[t.UNKNOWN=-1]="UNKNOWN",t[t.MEDIA_PLAYBACK_ABORTED=1]="MEDIA_PLAYBACK_ABORTED",t[t.MEDIA_ERR_NETWORK=2]="MEDIA_ERR_NETWORK",t[t.MEDIA_ERR_DECODE=3]="MEDIA_ERR_DECODE",t[t.MEDIA_ERR_SRC_NOT_SUPPORTED=4]="MEDIA_ERR_SRC_NOT_SUPPORTED",t[t.MIXED_CONTENT=1001]="MIXED_CONTENT",t[t.NO_INTERNET=1002]="NO_INTERNET"}(cs||(cs={}));function ms(t,e){if(e.message)return e.message;if(e.stack)return e.stack;const s=e.code||-1,r=us(s);return t.i18n("media_errors."+s,r)}const ys=()=>!0===(navigator||{}).onLine;function vs(t,e,s){const i=s.togglePlay;s.on(r,(function(t){const e=t.data||s.error,n="Error: %s\n"+(null===(a=(new Error).stack)||void 0===a?void 0:a.split("\n").slice(2).join("\n"));var a;setTimeout((function(){const a=$t(s,P);if(t.defaultPrevented||!a||s.root.querySelector("#qul_error"))return;if("AbortError"==e.name)return;s.setState("is-error",!0),s.togglePlay=hs;const o=function(t,e){return{code:"http:0"===e.code?Ts(t):e.code,message:ms(t,e)}}(s,e);console.error(n,o.message);let l=$t(s,"flowplayer-error");l||(l=_t(s,"flowplayer-error"),a.append(l)),te(l,r,{data:e,formatted_data:o}),s.once(y,()=>{Es(s,i)})}))})),s.on(b,()=>Es(s,i))}function Es(t,e){const s=$t(t,"flowplayer-error");t.togglePlay=e,t.opt("retry")&&t.setState(at,!0),t.setState("is-error",!1),null==s||s.remove()}function Ts(t){return function(t){try{return fs()&&"http:"==gs(t).protocol}catch(t){return!1}}(t.original_src)?{code:cs.MIXED_CONTENT}:ys()?{code:cs.MEDIA_ERR_NETWORK}:ys()?{code:cs.UNKNOWN}:{code:cs.NO_INTERNET}}var _s=Object.freeze({__proto__:null,NO_FULLSCREEN:1,NO_VOLUME_CONTROL:2,NO_MUTE:4,LOGO_ON_RIGHT:8,USE_DRAG_HANDLE:16,USE_PLAY_2:32,USE_PLAY_3:64,USE_THIN_CONTROLBAR:128,NO_TITLE:256,NO_DESCRIPTION:512,NO_CONTROLS:1024,NO_DURATION:2048,NO_HEADER:4096,AUDIO_ONLY:8192,NO_TOUCH_ZONES:16384,LOGO_ON_BOTTOM:32768});function Ss(t,e,s){let r=()=>document.fullscreenElement,i="fullscreenchange";if(!Element.prototype.requestFullscreen){const t=Element.prototype,e=document;t.webkitRequestFullScreen&&(t.requestFullscreen=t.webkitRequestFullScreen,e.fullscreenEnabled=!0),e.webkitCancelFullScreen&&(document.exitFullscreen=e.webkitCancelFullScreen),i="webkit"+i,r=()=>e.webkitCurrentFullScreenElement}const a=()=>s.getFullsceenTarget?s.getFullsceenTarget():e;s.toggleFullScreen=function(t,e){if(s.ios_fullscreen_disabled)return;if("boolean"!=typeof t&&(t=!s.hasState("is-fullscreen")),As(s)&&(t?function(t){t.getAttribute("playsinline")&&t.removeAttribute("playsinline");t.getAttribute("webkit-playsinline")&&t.removeAttribute("webkit-playsinline");t.webkitEnterFullScreen()}(s):function(t,e){t.getAttribute("playsinline")||t.setAttribute("playsinline","");t.getAttribute("webkit-playsinline")||t.setAttribute("webkit-playsinline","");e||t.webkitExitFullScreen();t.togglePlay(!1),t.hasState(ut)||t.setState(ut,!0)}(s,e)),!document.fullscreenEnabled)return;const i=a();if(t)return i.requestFullscreen();r()===i&&document.exitFullscreen()},As(s)&&(s.ios_fullscreen_disabled=!0,s.once("beforeplay",(function(){s.ios_fullscreen_disabled=!1})),s.on("webkitendfullscreen",(function(){s.toggleFullScreen(!1,!0)}))),setTimeout(()=>{const t=a();t.addEventListener(i,(function(){const e=r(),i=e===t||e==s;s.emit(i?h:f),s.setState("is-fullscreen",i)}))},0),!1!==t.doubleclick&&e.addEventListener(n,(function(t){var e;t.target&&(null===(e=t.target)||void 0===e?void 0:e.classList.contains("fp-ui"))&&s.toggleFullScreen()}))}function As(t){return s().ios&&"function"==typeof t.webkitEnterFullScreen&&"function"==typeof t.webkitExitFullScreen}function Ls(t,e){const s=t.seekable;if("object"!=typeof t.opts||0==s.length)return{head:0,tail:0};const r=Rs(t),i=e||t.live_state.dvr_window;return{head:r,tail:"number"!=typeof i||r-i<0?s.start(0):r-i}}function bs(t){return t.opt("live",!1)||t.duration>=Number.MAX_SAFE_INTEGER}function ws(t){return isFinite(t.duration)?t.duration:0==t.seekable.length?0:Ls(t).head}function Rs(t){var e;const s=t.seekable;return s.length?t.hasState("is-chromecast-playing")||!(null===(e=t.hls)||void 0===e?void 0:e.liveSyncPosition)?s.end(s.length-1):t.hls.liveSyncPosition:0}function ks(t,e,s){if(!s.reaper)return;const r=document.createDocumentFragment(),i=_t(s,P),n=_t(s,O);e.append(n),r.append(i),s.reaper.set("ui",i),~e.className.indexOf("use-play-")||e.classList.add("use-play-1"),function(t,e,s){const r=Kt("fp-footer");e.append(r),s.on(R,(function(t){var e,s;const i=null===(e=t.data)||void 0===e?void 0:e.description,n=null===(s=t.data)||void 0===s?void 0:s.title;if(r.innerHTML="","string"==typeof n){const t=Kt("fp-title");t.innerText=n,r.append(t)}if("string"==typeof i){const t=i.split(" "),e=Kt("fp-desc");for(e.innerText=t.join(" "),r.append(e);t.length>1&&e.scrollHeight>e.offsetHeight;)t.pop(),e.innerText=t.join(" ")+"..."}}))}(0,e,s),vs(0,0,s),e.appendChild(r),[o,l].forEach(t=>{e.addEventListener(t,(function(t){s.setState("is-hovered",t.type==o),s.setState("is-accessibility",!1)}))}),Ss(t,e,s),s.on("volumechange",(function(){const t=0==s.volume||s.muted;s.setState("is-muted",t),s._storage.setItem("mute",t.toString())})),"true"==s._storage.getItem("mute")&&(s.muted=!0,s.setState("is-muted",s.muted));const a=s._storage.getItem("volume");a&&!isNaN(Number(a))&&(s.volume=Number(a)),s.emit("volumechange"),s.on("dvr/window",e=>{t.live&&(s.live_state.dvr=s.seekable.length>0&&function(t,e,s){if(0==e)return!0;const r=Ls(t,s);return r.head-r.tail>=e}(s,t.seconds_to_dvr||60,e.detail),s.live_state.dvr_window=e.detail)}),s.on("live",()=>{const t=setInterval(()=>{if(s.opts.live&&!s.hasState("is-error")&&0!=s.reaper||(s.setState(nt,!1),clearInterval(t)),0==s.seekable.length)return;const e=function(t){const e=t.currentTime,s=Ls(t);return{progress:Math.min(100,Math.max(0,(e-s.tail)/(s.head-s.tail)*100)),is_live:e-s.head>=-10}}(s);s.hasState(ot)==e.is_live&&s.setState(ot,!e.is_live),s.live_state.dvr&&s.emit("dvr",e.progress)},200)}),s.on(g,(function(){s.setOpts({live:bs(s)})})),s.on("durationchange",(function(t){const e=bs(s),r=e?ws(s):t.data||s.duration;isNaN(r)||s.setOpts({live:e,duration:r})})),s.on(["playlist/advance","src"],e=>{if(s.root.classList.contains("is-livecountdown"))return Is(s,t);s.currentSrc&&("src"===e.type&&["is-playlist",ft].some(t=>s.root.classList.contains(t))||Is(s,t))}),s.on(R,(function(s){var r,i;t.seekable=void 0===(null===(r=null==s?void 0:s.data)||void 0===r?void 0:r.seekable)||s.data.seekable;const n=null===(i=s.data)||void 0===i?void 0:i.ui;if("number"!=typeof n)return;const a=e.classList;a.toggle("use-play-1",!(32&n||64&n)),a.toggle("use-play-2",(32&n)>0),a.toggle("use-play-3",(64&n)>0),a.toggle("use-thin-controlbar",(128&n)>0),a.toggle("no-title",(256&n)>0),a.toggle("no-description",(512&n)>0),a.toggle("logo-on-right",(8&n)>0),a.toggle("logo-on-bottom",(32768&n)>0),a.toggle("use-drag-handle",(16&n)>0),a.toggle("no-controls",(1024&n)>0),a.toggle("no-duration",(2048&n)>0),a.toggle("no-header",(4096&n)>0),a.toggle("no-mute",(4&n)>0),a.toggle("no-volume",(2&n)>0),a.toggle("no-fullscreen",(1&n)>0),a.toggle("no-touch-zones",(16384&n)>0)}));let u=null;[d,c].forEach(t=>i.addEventListener(t,(function(t){s.hasState("is-touch-device")&&t.type===d||("number"==typeof u&&clearTimeout(u),s.setState("is-hovered",!0),u=0==s.paused&&setTimeout((function(){s.setState("is-hovered",!1)}),2e3))})))}function Is(t,e){delete e.live_start_time,t.setOpts({live:!1}),t.live_state.dvr=void 0,t.live_state.dvr_window=void 0,delete e.live,delete e.poster,delete e.duration,delete e.title,delete e.description}function Ds(t,e,s){if(ve.from_token(t.token||"").is_granted(ve.permissions.NO_METERING))return;pe.id(t.token||"")&&s.once(E,async()=>await async function t(e,s){const r=pe.id(s||"");e.once("src",()=>{e.once(E,()=>t(e,s))}),function(t,e){if(!function(t){return ve.from_token(t).is_granted(ve.permissions.WOWZA_VIDEO)}(e))return;if(function(t){try{return new URL(t).hostname.endsWith(".wowza.com")}catch(t){return!1}}(t.original_src))return;t.emit("error:fatal",{reason:"token",details:"This token only allows wowza video sources"})}(e,s);if(401==(await fetch("https://pmi.flowplayer.com/in",{method:"POST",body:JSON.stringify({token_id:r,factor:1,rnd:Math.random().toString(36).substring(2)})})).status)return e.emit("error:fatal",{reason:"token",details:"The token online validation failed"})}(s,t.token||""))}var Cs={ads:{ad:"Ad",ads:"Ads",advertisement:"Advertisement"},audio:{button_txt:"Audio",menu_title:"Audio"},core:{exit_fullscreen:"Exit fullscreen",fullscreen:"Fullscreen",mute:"Mute",pause:"Pause",play:"Play",unmute:"Unmute",volume:"Volume"},ovp:{starting_in:"Countdown"},playlist:{cancel:"Cancel",up_next:"Up next"},qsel:{menu_title:"Quality"},share:{clipboard_failure:"Access to clipboard failed",clipboard_success:"The text is now on your clipboard",embed:"Embed",link:"Link",menu_title:"Share"},speed:{menu_title:"Speed"}};class I18n{init(t,e,s){s.reaper&&s.reaper.set("translations",Yt(I18n,t,"en"))}}I18n.en=Cs;const Ps="health:record",Os="rebuffer";var Ms=Object.freeze({__proto__:null,RECORD:Ps,REBUFFER:Os,DISPLAY:"display"});const xs=navigator;function Fs(t){var e,s;const r=null===(e=t.hls)||void 0===e?void 0:e.bandwidthEstimate;return r?1e-6*r:(null===(s=xs.connection)||void 0===s?void 0:s.downlink)||-1}function Ns(t,e){return async function(t,e){try{await fetch(t,{body:e,method:"POST",mode:"no-cors"})}catch(t){}}(t,JSON.stringify({events:e}))}const Us="https://ljsp.lwcdn.com".concat("/web/public/countdown/time.json"),Bs=window,Gs=Bs._flowplayerTimekeeper||(Bs._flowplayerTimekeeper={});async function $s(){const t=Gs.cachedServerOffset;if(t)return t;const e=Gs.pendingRequest||(Gs.pendingRequest=fetch(Us)),s=await e,r=parseInt(s.headers.get("age")||"0"),i=await s.json(),n=Date.now()-i.millisUtc-1e3*r;return Gs.cachedServerOffset=n,Gs.cachedServerOffset}const Hs=t=>{switch(t){case!0:return Lt.ON;case!1:return Lt.OFF;default:return t}},Ks=[],Vs="https://ihi.flowplayer.com/v1/health/events";function qs(t){if(t.suspended)return;const e=Ks.slice(0);Ks.length=0,0!=e.length&&(t.logger.log(`:dispatch events={${e.length}}`),Ns(function(){try{return"undefined"==typeof window?Vs:window.__FLOWPLAYER_INSIGHTS_URL?window.__FLOWPLAYER_INSIGHTS_URL:Vs}catch(t){return Vs}}(),e))}async function js(t,e,s){const r=await Ys();Ks.push(Object.assign(e,r)),t.logger.log(":enqueue",e.event,e),Ks.length<10&&!s||qs(t)}const Ws=()=>{var t,e;try{const s=window;return null===(e=null===(t=null==s?void 0:s.google)||void 0===t?void 0:t.ima)||void 0===e?void 0:e.VERSION}catch(t){return}},Ys=async()=>{const t=Date.now();try{return{adjusted_time:t-await $s(),client_time:t}}catch(e){return{client_time:t}}},zs=(t,e)=>Object.assign(t,{detail:e}),Xs=(t,{event:e,media_session_id:s,session_id:r,play_range_id:i})=>({event:e,media_session_id:s,session_id:r,play_range_id:i,device_id:t.deviceId(),version:"3.8.0",commit:"c8d588bc6eb9d5019caf438eece44601ab45298a",ima_sdk_version:Ws(),preload:t.opt("preload"),autoplay:Hs(t.opt("autoplay")),live:t.opt("live"),dvr:!!t.live_state.dvr,source:t.original_src,downlink_mbs:Fs(t),page_url:is(),player_id:t.opt("metadata.player_id"),media_id:t.opt("metadata.media_id"),site_id:t.opt("metadata.site_id"),category_id:t.opt("metadata.category_id"),sitegroup_id:t.opt("metadata.sitegroup_id"),token:t.token,plugins:t.plugins.map(t=>t.constructor.name).sort((t,e)=>t.localeCompare(e)),current_time:t.currentTime,external_media_id:t.opt("external_media_id")}),Qs=t=>({bitrate:null==t?void 0:t.bitrate,resolution:null==t?void 0:t.attrs.RESOLUTION,frame_rate:null==t?void 0:t.attrs["FRAME-RATE"]});function Zs(t,e,s,r){const i=Xs(e,t.eventInfo(s)),{before:n,after:a}=r;js(t,((t,e,s)=>Object.assign(t,{state:{before:e,after:s}}))(i,Qs(n),Qs(a)))}const Js=(t,e)=>{let s=null;return(...r)=>{null!==s&&(clearTimeout(s),s=null),s=setTimeout(()=>e(...r),t)}},tr=Xt();class Health{constructor(t,e){this.session_id=tr,this.suspended=!1,this.logger=Oe("health",e.opts),this.media_session_id=Xt(),this.play_range_id=Xt(),this.analyticsLoop=setInterval(()=>qs(this),2e3),e.on(w,()=>clearInterval(this.analyticsLoop)),e.on(E,()=>{this.play_range_id=Xt()});const s=this;if(e.health={get media_session_id(){return s.media_session_id},set media_session_id(t){s.media_session_id=t},get session_id(){return s.session_id},set session_id(t){s.session_id=t},toggle(t){t?s.resume():s.suspend()}},!Health._UNLOAD_SUBSCRIBED){Health._UNLOAD_SUBSCRIBED=!0;const e=e=>t.instances.forEach(t=>t.emit(e.type));document.addEventListener("visibilitychange",t=>{"hidden"==document.visibilityState&&e(t)}),window.addEventListener("pagehide",e)}}eventInfo(t){return{event:t,media_session_id:this.media_session_id,session_id:this.session_id,play_range_id:this.play_range_id}}suspend(){this.suspended=!0,clearInterval(this.analyticsLoop)}resume(){this.suspended=!1,this.analyticsLoop=setInterval(()=>qs(this),2e3)}init(t,e,s){!function(t){t.on(T,(function(e){t.seeking||t.networkState===t.NETWORK_LOADING&&t.readyState!==t.HAVE_NOTHING&&t.emit(Os)}))}(s),s.on("display",t=>{js(this,Xs(s,this.eventInfo(t.type)),!0)}),s.on(Ps,({detail:t})=>{const e=Xs(s,this.eventInfo(t.event));Object.assign(e,t.detail||{}),js(this,e)}),[_,y,a,g,p,m,T,Os].forEach(t=>{s.on(t,t=>{js(this,Xs(s,this.eventInfo(t.type)))})}),[E,v,L,A,S,h,f].forEach(t=>{s.on(t,t=>{js(this,Xs(s,this.eventInfo(t.type)))})}),s.on("volumechange",Js(800,t=>{const e=Xs(s,this.eventInfo(t.type));js(this,zs(e,{volume:parseFloat(s.volume.toFixed(2)),muted:s.muted}))})),s.on("resize",Js(800,t=>{const r=Xs(s,this.eventInfo(t.type));js(this,zs(r,{height:e.clientHeight,width:e.clientWidth}))})),s.on("hls/failover",t=>{const e=Xs(s,this.eventInfo(t.type)),r=t.detail,{reason:i,from:n}=r;js(this,zs(e,{reason:i,from:n}))}),s.on("qualitychange",({type:t,detail:e})=>{switch(e.kind){case"hls":return Zs(this,s,t,e)}});let i=Date.now()+5e3;s.on("timeupdate",t=>{if(Date.now()<i)return;i=Date.now()+5e3;const e=Xs(s,this.eventInfo(t.type));var r;js(this,zs(e,{duration:(r=s.duration,Number.isFinite(r)?r:r===1/0?-1:void 0)}))}),s.addEventListener(r,t=>{const e=Xs(s,this.eventInfo(t.type)),r=t.error||s.error;if(!r)return js(this,e,!0);const i=r.code,n={error_message:r.message||us(i),error_code:i,error_stack:r.stack||""};return js(this,zs(e,n),!0)}),s.on("src",t=>{var e;const r=null===(e=t.detail)||void 0===e?void 0:e.src;if("string"!=typeof r)return;if(!ps(s.original_src))return;if(!ps(r))return;if(r==s.original_src)return;this.media_session_id=Xt();js(this,Xs(s,this.eventInfo(t.type))),qs(this)}),s.on("visibilitychange",t=>{js(this,Xs(s,this.eventInfo(t.type))),qs(this)})}}Health.events=Ms,Health._UNLOAD_SUBSCRIBED=!1,ce(window,Health);class FlowplayerComponent extends HTMLElement{constructor(t){super(),this.player=t}}class FlowplayerLogo extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-logo");const e={logo:""};t.on(R,t=>{var s;const r=e.logo,i=(null===(s=null==t?void 0:t.data)||void 0===s?void 0:s.logo)||"";r!=i&&(e.logo=i,this.set_logo(i,t.detail.logo_alt_text,t.detail.logo_href))})}set_logo(t,e,s){this.innerHTML="";const r=document.createElement("img");if(!t)return;if(r.src=t,e&&(r.alt=e),!s)return this.append(r);const i=document.createElement("a");i.href=s,i.append(r),this.append(i)}}class FlowplayerHeaderDuration extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-duration"),t.on(R,t=>{var e;const s=(null===(e=null==t?void 0:t.data)||void 0===e?void 0:e.duration)||NaN;this.innerText=isFinite(s)?jt(s):""})}}const er={name:"fp-fullscreen",translation_key:"core.fullscreen"},sr={name:"fp-fullscreen-exit",translation_key:"core.exit_fullscreen"},rr={name:"fp-play",translation_key:"core.play"},ir={name:"fp-pause",translation_key:"core.pause"},nr={translation_key:"core.mute",name:"fp-volume-mute-unmute"},ar={translation_key:"core.play",name:"fp-small-play"},or={translation_key:"core.pause",name:"fp-small-pause"},lr={name:"fp-fast-forward"},dr={name:"fp-rewind"};class FlowplayerIcon extends FlowplayerComponent{constructor(t,e){super(t),this.classList.add("fp-icon",e.name),e.title&&this.setAttribute("title",e.title),e.title&&this.setAttribute("aria-label",e.title),e.translation_key&&this.setAttribute("aria-label",t.i18n(e.translation_key)),this.setAttribute("tabindex","0"),this.setAttribute("focusable","true")}}document.addEventListener(i,(function(t){this.active_menu&&!t.composedPath().includes(this.active_menu)&&(Array.from(document.querySelectorAll(".fp-engine")).forEach(t=>{var e;const s=t.root.querySelector("details[open].fp-menu-container");s&&(s.open=!1,null===(e=s.querySelector("summary"))||void 0===e||e.removeAttribute("aria-expanded"),t.root.classList.toggle("has-menu-opened",!1))}),this.active_menu=void 0)}));const cr={passive:!0};var ur;function hr(t,e){let s=0,r=-1,i=-1;const n=Math.random().toString(36).replace(/[^a-z]+/g,"").substr(0,5),a=t.classList;t.id=n,a.remove(ur.GRABBING),a.remove(ur.TOUCHING);const o=e.onseek||hs,l=e.onstart||hs,h=e.onend||hs,f=e.onmouse||hs,g=e.ontouch||hs,p=e.ontouchend||hs;function m(e){!function(){const e=t.getBoundingClientRect();s=e.left,r=e.width}();let i=(function(t){return"function"==typeof window.TouchEvent&&t instanceof TouchEvent}(e)?e.changedTouches[0].pageX:e.pageX)-s;return i>r&&(i=r),i<0&&(i=0),i/r*100}function y(e){const s=m(e);s!=i&&(o(t,s),i=s)}return t.addEventListener("touchstart",(function(e){fr(t,e)&&(a.add(ur.TOUCHING),gr(t.parentElement)&&(a.add(ur.GRABBING),g(t,m(e)),l(t,m(e)),y(e)))}),cr),t.addEventListener(c,(function(e){y(e),f(t,m(e))}),cr),t.addEventListener(u,(function(e){setTimeout((function(){a.remove(ur.TOUCHING)}),500),fr(t,e)&&(a.remove(ur.GRABBING),p(t,m(e)),h(t,m(e)),r=0)}),cr),t.addEventListener("touchcancel",(function(){a.remove(ur.GRABBING,ur.TOUCHING),r=0}),cr),t.addEventListener("mousedown",(function(e){a.contains(ur.TOUCHING)||(document.addEventListener(d,y),a.add(ur.GRABBING),l(t,m(e)),e.preventDefault(),y(e))})),t.addEventListener(d,(function(e){a.contains(ur.TOUCHING)||f(t,m(e))})),document.addEventListener("mouseup",(function(e){a.contains(ur.TOUCHING)||(document.removeEventListener(d,y),a.contains(ur.GRABBING)&&(a.remove(ur.GRABBING),h(t,m(e)),r=0))})),t}function fr(t,e){const s=e.target;return!!s&&(s&&!s.closest(t.id)||!gr(t.parentElement)||!t.classList.contains(ur.TOUCHING))}function gr(t){if(!t)return!1;const e=window.getComputedStyle(t);return"0"!==e.width&&"0"!==e.height&&"0"!==e.opacity&&"none"!==e.display&&"hidden"!==e.visibility}!function(t){t.GRABBING="has-grab",t.TOUCHING="has-touch"}(ur||(ur={}));class FlowplayerVolumeBar extends FlowplayerComponent{constructor(t){super(t),this.className="fp-volume";const e=t.root.classList,s=e.contains("is-tiny")?6:e.contains("is-small")?8:10,r=Array.from({length:s}).map(()=>{const t=document.createElement("i");return t.className="fp-tick",t});this.append(...r),hr(this,{onseek:(e,s)=>{s>0&&(t.muted=!1,t._storage.removeItem("mute")),t._storage.setItem("volume",(t.volume=s/100).toString()),this.adjustVolumeSlider(t.volume)}}),this.setAttribute("tabindex","0"),this.setAttribute("role","slider"),this.setAttribute("aria-valuemin","0"),this.setAttribute("aria-valuemax","1"),this.setAttribute("aria-label",t.i18n("core.volume","volume")),t.on("volumechange",()=>{const e=0==t.volume||t.muted;e&&this.adjustVolumeSlider(0);const s=t.opt("ui");this.classList.contains(ur.GRABBING)||e&&"number"==typeof s&&(4&s)>0||this.adjustVolumeSlider(t.volume)})}adjustVolumeSlider(t){this.setAttribute("aria-valuenow",t.toString()),this.setAttribute("aria-valuetext",Math.round(100*t)+"%");const e=Array.from(this.querySelectorAll(".fp-tick")),s=Math.round(t*e.length);e.forEach((t,e)=>{t.classList.toggle("fp-color",e<s)})}}function pr(t,e){if(!t.parentElement)return;const s=t.clientWidth/t.parentElement.clientWidth*100/2;t.style.left=e-s+"%",t.style.display="block"}function mr(t,e){if(isNaN(t.duration))return;const s=t.buffered;s.length&&(e.style.width=Math.min(s.end(s.length-1)/t.duration*100,100)+"%")}function yr(t,e){t.style.width="0",e.style.display="none"}function vr(t,e,s){if(!e.seekable||0==e.seekable.length)return;pr(s,t);const r=Ls(e),i=(100-Math.max(0,Math.min(t,100)))/100*(r.head-r.tail);s.innerText="-"+jt(i)}function Er(t){try{t.dvr_offset=0,t.currentTime=Rs(t)}catch(t){console.warn("failed to seek to now: %j",t)}}function Tr(t,e){t/=100,e.currentTime=function(t,e){if(e>1||e<0)return console.warn("cannot calculate a percent outside of range(0..1)"),0;const s=Ls(t);return s.tail+e*(s.head-s.tail)}(e,t)}function _r(t,e){t.style.width="0",e.style.display="none"}class FlowplayerTimelineBar extends FlowplayerComponent{constructor(t){let e;super(t),this.bufferEle=Kt("fp-buffer"),this.progress=Kt("fp-progress","fp-color"),this.tooltipEle=Kt("fp-timestamp"),this.proposedSeekBar=Kt("fp-hover"),this.dragger=Kt("fp-dragger","fp-color"),this.classList.add("fp-timeline","fp-bar"),this.tooltipEle.style.display="none",this.setAttribute("role","slider"),this.setAttribute("tabindex","0"),this.setAttribute("aria-label",t.i18n("timeline","Timeline")),this.setAttribute("aria-valuenow","0"),this.progress.append(this.dragger),this.append(this.bufferEle,this.progress,this.proposedSeekBar,this.tooltipEle);const s=requestAnimationFrame;let r=void 0;const i=()=>{0==t.reaper||e.live||(!function(t,e){e.style.width=t.currentTime/t.duration*100+"%"}(t,this.progress),r=void 0,t.paused||this.classList.contains(ur.GRABBING)||r||(r=setTimeout(i,200)))},n=()=>!!this.player.opt("seekable",!0)&&!isNaN(this.player.duration);hr(this,{onseek:(s,r)=>{if(n())switch(!!e.live){case!0:vr(r,t,this.tooltipEle);break;case!1:!function(t,e,s){const r=e.duration*(t/100);if(e.disabled&&r>e.currentTime)return!1;s.style.width=t+"%",e.currentTime=r}(r,t,this.progress),pr(this.tooltipEle,r)}},onstart:()=>{n()&&(t.emit("timeline/gesture/start"),!t.hasState("is-casting")&&t.setState(rt,!0),e.live||function(t){t.style.display="block"}(this.tooltipEle))},onend:function(r,n){s(i),0!=e.seekable&&e.live&&Tr(n,t)},ontouchend:()=>{e.live?_r(this.proposedSeekBar,this.tooltipEle):yr(this.proposedSeekBar,this.tooltipEle),setTimeout(()=>t.emit("timeline/gesture/end"),0)},onmouse:(s,r)=>{if(n()&&(t.emit("timeline/gesture/move",{percent:r}),!this.classList.contains(ur.GRABBING)))switch(!!e.live){case!0:!function(t,e){e.style.width=t+"%"}(r,this.proposedSeekBar),vr(r,t,this.tooltipEle);break;case!1:!function(t,e){e.style.width=t+"%"}(r,this.proposedSeekBar),function(t,e,s){if(isNaN(t)||isNaN(e.duration))return;pr(s,t),s.innerHTML="";const r=document.createElement("span");r.innerText=jt(t/100*e.duration),s.append(r)}(r,t,this.tooltipEle)}}}),t.on(R,(function(t){t.data&&(e=t.data)})),t.on(E,()=>s(i)),t.on(m,()=>{0==t.reaper||e.live||mr(t,this.bufferEle)}),t.on("dvr",t=>{this.progress.style.width=t.detail+"%"}),t.on("timeupdate",()=>{0!=t.reaper&&(s(i),this.setAttribute("aria-valuenow",t.currentTime+""),this.setAttribute("aria-valuetext",Math.round(t.currentTime)+t.i18n("core.sec","sec")),e.live||mr(t,this.bufferEle))}),t.on(g,()=>{0!=t.reaper&&(e.live||mr(t,this.bufferEle))}),t.on("durationchange",e=>{if(0==t.reaper)return;const s=bs(t)?ws(t):e.data||t.duration;isNaN(s)||(this.setAttribute("aria-valuemax",s+""),this.setAttribute("aria-valuemin","0"))}),this.addEventListener(l,()=>{t.emit("timeline/gesture/end"),e.live?_r(this.proposedSeekBar,this.tooltipEle):yr(this.proposedSeekBar,this.tooltipEle)})}}class FlowplayerChaptersTimelineBar extends FlowplayerTimelineBar{constructor(t){super(t),this.handleChapters(t)}handleChapters(t){const e=document.createElement("div");let s;this.addEventListener("chapters:new",t=>{e.innerText="",this.querySelectorAll(".fp-chapter").forEach(t=>this.removeChild(t)),t.data&&t.data.forEach(t=>{const r=document.createElement("div");r.className="fp-chapter",r.style.left=t.left,r.style.bottom=r.style.top="0",r.style.width=t.width,r.title=t.title,r.onmouseover=()=>{e.innerText=t.title},r.onmouseleave=()=>{e.innerText=s||""},this.appendChild(r)})}),this.addEventListener("chapter:changed",r=>{var i;const n=r.data;n&&(e.parentNode||(null===(i=$t(t,M))||void 0===i||i.insertAdjacentElement("beforebegin",e),e.classList.toggle("fp-togglable",!0),e.classList.toggle("fp-chapter-info",!0)),s=n,e.innerText=n)})}}class FlowplayerLiveStatus extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-live-status");const e=Kt("fp-live-text"),s=Kt("fp-live-indicator","fp-color");e.textContent="live",this.setAttribute("tabindex","0"),this.setAttribute("role","button"),this.append(s,e),this.addEventListener(i,(function(){Er(t)}))}}class FlowplayerDuration extends FlowplayerComponent{constructor(t){let e;super(t),this.classList.add("fp-duration"),this.setAttribute("aria-hidden","true"),t.on(R,s=>{if(0==t.reaper||!s.data)return;e=s.data;const r=bs(t)?NaN:s.data.duration||0;if(isNaN(r)||r>=Number.MAX_SAFE_INTEGER)return this.style.display="none";this.style.display="inline-block",this.innerText=jt(r)}),t.on(g,()=>{0==t.reaper||e.live||function(t,e){t.duration&&(e.innerText=jt(t.duration))}(t,this)})}}class FlowplayerElapsedTime extends FlowplayerComponent{constructor(t){let e;super(t),this.classList.add("fp-elapsed"),this.innerText=jt(0),this.setAttribute("aria-hidden","true"),t.on(R,t=>{t.data&&(e=t.data)}),t.on("timeupdate",()=>{0!=t.reaper&&(e.live?function(t,e){e.innerText=jt(t.currentTime)}(t,this):function(t,e){e.innerText=jt(t.currentTime)}(t,this))})}}class FlowplayerControlButtons extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-btns","fp-small-switch");const e=_t(t,q),s=_t(t,V);e.addEventListener("click",(function(){t.togglePlay(),setTimeout((function(){s.focus&&s.focus()}),100)})),s.addEventListener("click",(function(){t.togglePlay(),setTimeout((function(){e.focus&&e.focus()}),100)})),this.append(e,s)}}class FlowplayerLeftRightZone extends FlowplayerComponent{constructor(t,e){super(t),this.classList.add(e);const s=this.classList.contains("fp-left-zone")?-1:1,r=document.createElement("span"),i=_t(t,this.classList.contains("fp-left-zone")?Y:"flowplayer-fast-forward-icon");i.removeAttribute("tabindex"),r.classList.add("fp-zone-seconds"),this.append(r,i);t.on(A,()=>{r.innerText=""}),t.on("seek:queued",t=>{const e=t.data;if(!e)return;if("number"!=typeof e.offset)return;const s=e.offset;if(0==s)return this.reset_zone();s>0&&this.classList.contains("fp-right-zone")||s<0&&!this.classList.contains("fp-right-zone")?this.render_zone_state(s):this.reset_zone()}),t.on("seek:cancel",()=>{this.reset_zone()}),this.reset_zone(),this.addEventListener(u,(function(e){isNaN(t.duration)||isNaN(t.currentTime)||16384&t.opt("ui")||t.hasState(lt)||!t.hasState("will-seek")&&!t.hasState(ut)||t.enqueueSeek(5*s)&&(e.stopPropagation(),e.preventDefault())}))}reset_zone(){const t=this.querySelector(".fp-zone-seconds");t&&(t.innerText="")}render_zone_state(t){const e=this.querySelector(".fp-zone-seconds");e&&(e.innerText=Math.abs(t)+"")}}class FlowplayerError extends FlowplayerComponent{constructor(t){super(t),this.className="fp-error",this.message=document.createElement("p"),this.message.className="error-message",this.append(this.message),this.addEventListener("error",t=>{const e=t.detail;e&&(this.message.textContent=e.formatted_data.message)})}}class FlowplayerHeaderLeftRight extends FlowplayerComponent{constructor(t,e,...s){super(t),this.className=e;const r=t.createComponents(...s);this.append(...r),"fp-left"!==e&&r.forEach(e=>{e.addEventListener(i,()=>t.toggleFullScreen())})}}class FlowplayerMiddleWait extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-wait"),Array(...Array(4)).map((t,e)=>e).forEach(()=>{this.append(document.createElement("b"))})}}class FlowplayerMiddleZone extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-middle-zone");const e=t.createComponents(K,"flowplayer-middle-buttons");this.append(...e)}}class FlowplayerMiddleButtons extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-switch"),[j,W].forEach(e=>{const s=_t(t,e);s.removeAttribute("tabindex"),this.append(s)})}}class FlowplayerVolumeControl extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-volume-control");const e=_t(t,z);this.append(e),!s().ios&&this.append(_t(t,U)),e instanceof FlowplayerIcon&&e.addEventListener(i,(function(){t.toggleMute()}))}}class FlowplayerHeader extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-header"),this.append(...t.createComponents("flowplayer-header-left-zone",G)),t.reaper&&t.reaper.set("header",this)}}class FlowplayerControls extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-controls","fp-togglable"),this.append(...t.createComponents("flowplayer-control-buttons",x,F,N,"flowplayer-control-duration","flowplayer-volume-control"))}}class FullscreenIcon extends FlowplayerIcon{constructor(t,e){super(t,e),this.setAttribute("role","button")}}class FlowplayerMiddle extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-middle"),this.append(...t.createComponents("flowplayer-middle-left-zone",H,"flowplayer-middle-right-zone")),this.setAttribute("tabindex","0"),t.reaper&&t.reaper.set("middle",this),this.handleClick(t),this.handleTouch(t),t.once("beforeplay",()=>{this.removeAttribute("tabindex"),this.removeAttribute("role"),this.removeAttribute("aria-label")})}handleClick(t){[i,n].forEach(e=>this.addEventListener(e,(function(s){if(!(s.defaultPrevented||t.root.classList.contains("is-endscreen")||e===n&&t.root.classList.contains("no-fullscreen")))return s.preventDefault(),t.emit(s.type),!1}))),t.on(i,(function(e){setTimeout((function(){e.defaultPrevented||t.togglePlay()}),0)})),t.on(n,(function(e){setTimeout((function(){e.defaultPrevented||t.toggleFullScreen()}),0)}))}handleTouch(t){let e=!1;this.addEventListener(u,(function(e){e.cancelable&&!t.hasState("is-endscreen")&&(e.preventDefault(),t.emit(e.type,{source:e}))})),t.on(u,(function(s){setTimeout((function(){if(s.defaultPrevented)return;if(t.ended)return t.togglePlay(!0);const r=t.hasState(st);e&&clearTimeout(e),(r||t.hasState(ut)||t.hasState("no-autoplay"))&&(t.hasState(ut)&&(t.setState(ut,!1),t.setState("is-hovered",!1)),t.togglePlay(),r)||(t.setState(ut,!0),t.paused||(e=setTimeout((function(){e=!1,t.setState(ut,!1),t.setState("is-hovered",!1)}),2e3)))}),0)}))}}class FlowplayerUi extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-ui"),this.append(...t.createComponents(B,$,M))}}Ue.extensions.unshift.apply(Ue.extensions,[I18n,Analytics$1,Health,class Default{constructor(t){St(t,P,FlowplayerUi),St(t,"flowplayer-error",FlowplayerError),St(t,M,FlowplayerControls),St(t,x,FlowplayerLiveStatus),St(t,"flowplayer-control-duration",FlowplayerDuration),St(t,N,t.extensions.find(t=>"Chapters"===t.name)?FlowplayerChaptersTimelineBar:FlowplayerTimelineBar),St(t,F,FlowplayerElapsedTime),St(t,U,FlowplayerVolumeBar),St(t,"flowplayer-volume-control",FlowplayerVolumeControl),St(t,"flowplayer-control-buttons",FlowplayerControlButtons),St(t,B,FlowplayerHeader),St(t,O,FlowplayerLogo),St(t,"flowplayer-header-duration",FlowplayerHeaderDuration),St(t,"flowplayer-header-left-zone",class extends FlowplayerHeaderLeftRight{constructor(t){super(t,"fp-left","flowplayer-header-duration")}}),St(t,G,class extends FlowplayerHeaderLeftRight{constructor(t){super(t,"fp-right fp-togglable","flowplayer-fullscreen-enter-icon","flowplayer-fullscreen-exit-icon")}}),St(t,$,FlowplayerMiddle),St(t,H,FlowplayerMiddleZone),St(t,K,FlowplayerMiddleWait),St(t,"flowplayer-middle-buttons",FlowplayerMiddleButtons),St(t,"flowplayer-middle-right-zone",class extends FlowplayerLeftRightZone{constructor(t){super(t,"fp-right-zone")}}),St(t,"flowplayer-middle-left-zone",class extends FlowplayerLeftRightZone{constructor(t){super(t,"fp-left-zone")}}),St(t,V,class extends FlowplayerIcon{constructor(t){super(t,ar),this.setAttribute("role","button")}}),St(t,q,class extends FlowplayerIcon{constructor(t){super(t,or),this.setAttribute("role","button")}}),St(t,j,class extends FlowplayerIcon{constructor(t){super(t,rr),this.setAttribute("role","button")}}),St(t,W,class extends FlowplayerIcon{constructor(t){super(t,ir),this.setAttribute("role","button")}}),St(t,"flowplayer-fullscreen-enter-icon",class extends FullscreenIcon{constructor(t){super(t,er)}}),St(t,"flowplayer-fullscreen-exit-icon",class extends FullscreenIcon{constructor(t){super(t,sr)}}),St(t,"flowplayer-fast-forward-icon",class extends FlowplayerIcon{constructor(t){super(t,lr)}}),St(t,Y,class extends FlowplayerIcon{constructor(t){super(t,dr)}}),St(t,z,class extends FlowplayerIcon{constructor(t){super(t,nr),this.classList.add("fp-volumebtn"),this.setAttribute("role","switch"),t.on("volumechange",()=>{const e=0==t.volume||t.muted;this.setAttribute("aria-label",t.i18n("core.muted","Muted")),this.setAttribute("aria-checked",e?"true":"false")})}})}init(t,e,s){Ds(t,0,s),ks(t,e,s),function(t,e,s){"undefined"!=typeof window&&"ontouchstart"in window&&s.setState("is-touch-device",!0),s.setState("is-accessibility",!1)}(0,0,s)}}]);var Sr=Object.assign(Ue,{ui:_s,i18n:I18n}),Ar={};function Lr(t,e){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),s.push.apply(s,r)}return s}function br(t){for(var e=1;e<arguments.length;e++){var s=null!=arguments[e]?arguments[e]:{};e%2?Lr(Object(s),!0).forEach((function(e){wr(t,e,s[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):Lr(Object(s)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(s,e))}))}return t}function wr(t,e,s){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var s=t[Symbol.toPrimitive];if(void 0!==s){var r=s.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function Rr(){return(Rr=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var s=arguments[e];for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&(t[r]=s[r])}return t}).apply(this,arguments)}!function(t,e){var s,r,i,n,a;s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(t,e,s){if(s=s||{},t=t.trim(),!(e=e.trim())){if(!s.alwaysNormalize)return t;var i=a.parseURL(t);if(!i)throw new Error("Error trying to parse base URL.");return i.path=a.normalizePath(i.path),a.buildURLFromParts(i)}var n=a.parseURL(e);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return s.alwaysNormalize?(n.path=a.normalizePath(n.path),a.buildURLFromParts(n)):e;var o=a.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var d={scheme:o.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(d.netLoc=o.netLoc,"/"!==n.path[0]))if(n.path){var c=o.path,u=c.substring(0,c.lastIndexOf("/")+1)+n.path;d.path=a.normalizePath(u)}else d.path=o.path,n.params||(d.params=o.params,n.query||(d.query=o.query));return null===d.path&&(d.path=s.alwaysNormalize?a.normalizePath(n.path):n.path),a.buildURLFromParts(d)},parseURL:function(t){var e=s.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(i,"");t.length!==(t=t.replace(n,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=a}({get exports(){return Ar},set exports(t){Ar=t}});const kr=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)};let Ir=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t}({}),Dr=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),Cr=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.UNKNOWN="unknown",t}({});const Pr=function(){},Or={trace:Pr,debug:Pr,log:Pr,warn:Pr,info:Pr,error:Pr};let Mr=Or;function xr(t,...e){e.forEach((function(e){Mr[e]=t[e]?t[e].bind(t):function(t){const e=self.console[t];return e?e.bind(self.console,`[${t}] >`):Pr}(e)}))}const Fr=Mr,Nr=/^(\d+)x(\d+)$/,Ur=/(.+?)=(".*?"|.*?)(?:,|$)/g;class AttrList{constructor(t){"string"==typeof t&&(t=AttrList.parseAttrList(t));for(const e in t)t.hasOwnProperty(e)&&("X-"===e.substring(0,2)&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(e)),this[e]=t[e])}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const s=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)s[t]=parseInt(e.slice(2*t,2*t+2),16);return s}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const s=this[t];return s?parseFloat(s):e}enumeratedString(t){return this[t]}bool(t){return"YES"===this[t]}decimalResolution(t){const e=Nr.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t){let e;const s={};for(Ur.lastIndex=0;null!==(e=Ur.exec(t));){let t=e[2];0===t.indexOf('"')&&t.lastIndexOf('"')===t.length-1&&(t=t.slice(1,-1));s[e[1].trim()]=t}return s}}function Br(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t}class DateRange{constructor(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){const s=e.attr;for(const e in s)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==s[e]){Fr.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=Rr(new AttrList({}),s,t)}if(this.attr=t,this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=new Date(this.attr["END-DATE"]);kr(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const t=this.duration;return null!==t?new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(kr(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&kr(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class LoadStats{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var Gr="audio",$r="video",Hr="audiovideo";class BaseSegment{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[Gr]:null,[$r]:null,[Hr]:null},this.baseurl=t}setByteRange(t,e){const s=t.split("@",2),r=[];1===s.length?r[0]=e?e.byteRangeEndOffset:0:r[0]=parseInt(s[1]),r[1]=parseInt(s[0])+r[0],this._byteRange=r}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Ar.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}}class Fragment extends BaseSegment{constructor(t,e){super(e),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new LoadStats,this.urlId=0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.type=t}get decryptdata(){const{levelkeys:t}=this;if(!t&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const t=Object.keys(this.levelkeys);if(1===t.length)return this._decryptdata=this.levelkeys[t[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;if(!kr(this.programDateTime))return null;const t=kr(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),e=t.length;if(e>1||1===e&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(t){if(this.levelkeys){const e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,s,r,i,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,i)):a[t]={startPTS:e,endPTS:s,startDTS:r,endDTS:i,partial:n}}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[Gr]=null,t[$r]=null,t[Hr]=null}}class Part extends BaseSegment{constructor(t,e,s,r,i){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new LoadStats,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=r;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}class LevelDetails{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,s=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!s||!!e,this.advanced=this.endSN>t.endSN||e>0||0===e&&s>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&kr(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var t;return null!=(t=this.fragments)&&t.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function Kr(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function Vr(t){const e=t.split(":");let s=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),r=t[t.length-1].split(",");if(2===r.length){const e="base64"===r[0],i=r[1];e?(t.splice(-1,1),s=Kr(i)):s=function(t){const e=qr(t).subarray(0,16),s=new Uint8Array(16);return s.set(e,16-e.length),s}(i)}}return s}function qr(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}var jr={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Wr="org.w3.clearkey",Yr="com.apple.streamingkeydelivery",zr="com.microsoft.playready",Xr="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Qr(t){switch(t){case Yr:return jr.FAIRPLAY;case zr:return jr.PLAYREADY;case Xr:return jr.WIDEVINE;case Wr:return jr.CLEARKEY}}var Zr="edef8ba979d64acea3c827dcd51d21ed";function Jr(t){switch(t){case jr.FAIRPLAY:return Yr;case jr.PLAYREADY:return zr;case jr.WIDEVINE:return Xr;case jr.CLEARKEY:return Wr}}function ti(t){const{drmSystems:e,widevineLicenseUrl:s}=t,r=e?[jr.FAIRPLAY,jr.WIDEVINE,jr.PLAYREADY,jr.CLEARKEY].filter(t=>!!e[t]):[];return!r[jr.WIDEVINE]&&s&&r.push(jr.WIDEVINE),r}const ei="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function si(t,e,s){return Uint8Array.prototype.slice?t.slice(e,s):new Uint8Array(Array.prototype.slice.call(t,e,s))}const ri=(t,e)=>e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,ii=(t,e)=>e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,ni=(t,e)=>{const s=e;let r=0;for(;ri(t,e);){r+=10;r+=ai(t,e+6),ii(t,e+10)&&(r+=10),e+=r}if(r>0)return t.subarray(s,s+r)},ai=(t,e)=>{let s=0;return s=(127&t[e])<<21,s|=(127&t[e+1])<<14,s|=(127&t[e+2])<<7,s|=127&t[e+3],s},oi=(t,e)=>ri(t,e)&&ai(t,e+6)+10<=t.length-e,li=t=>t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info,di=t=>{const e=String.fromCharCode(t[0],t[1],t[2],t[3]),s=ai(t,4);return{type:e,size:s,data:t.subarray(10,10+s)}},ci=t=>{let e=0;const s=[];for(;ri(t,e);){const r=ai(t,e+6);e+=10;const i=e+r;for(;e+8<i;){const r=di(t.subarray(e)),i=ui(r);i&&s.push(i),e+=r.size+10}ii(t,e)&&(e+=10)}return s},ui=t=>"PRIV"===t.type?hi(t):"W"===t.type[0]?gi(t):fi(t),hi=t=>{if(t.size<2)return;const e=mi(t.data,!0),s=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:s.buffer}},fi=t=>{if(t.size<2)return;if("TXXX"===t.type){let e=1;const s=mi(t.data.subarray(e),!0);e+=s.length+1;const r=mi(t.data.subarray(e));return{key:t.type,info:s,data:r}}const e=mi(t.data.subarray(1));return{key:t.type,data:e}},gi=t=>{if("WXXX"===t.type){if(t.size<2)return;let e=1;const s=mi(t.data.subarray(e),!0);e+=s.length+1;const r=mi(t.data.subarray(e));return{key:t.type,info:s,data:r}}const e=mi(t.data);return{key:t.type,data:e}},pi=t=>{if(8===t.data.byteLength){const e=new Uint8Array(t.data),s=1&e[3];let r=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return r/=45,s&&(r+=47721858.84),Math.round(r)}},mi=(t,e=!1)=>{const s=vi();if(s){const r=s.decode(t);if(e){const t=r.indexOf("\0");return-1!==t?r.substring(0,t):r}return r.replace(/\0/g,"")}const r=t.length;let i,n,a,o="",l=0;for(;l<r;){if(i=t[l++],0===i&&e)return o;if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:n=t[l++],o+=String.fromCharCode((31&i)<<6|63&n);break;case 14:n=t[l++],a=t[l++],o+=String.fromCharCode((15&i)<<12|(63&n)<<6|(63&a)<<0)}}return o};let yi;function vi(){return yi||void 0===self.TextDecoder||(yi=new self.TextDecoder("utf-8")),yi}const Ei=function(t){let e="";for(let s=0;s<t.length;s++){let r=t[s].toString(16);r.length<2&&(r="0"+r),e+=r}return e},Ti=Math.pow(2,32)-1,_i=[].push,Si={video:1,audio:2,id3:3,text:4};function Ai(t){return String.fromCharCode.apply(null,t)}function Li(t,e){const s=t[e]<<8|t[e+1];return s<0?65536+s:s}function bi(t,e){const s=wi(t,e);return s<0?4294967296+s:s}function wi(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function Ri(t,e,s){t[e]=s>>24,t[e+1]=s>>16&255,t[e+2]=s>>8&255,t[e+3]=255&s}function ki(t,e){const s=[];if(!e.length)return s;const r=t.byteLength;for(let i=0;i<r;){const n=bi(t,i),a=n>1?i+n:r;if(Ai(t.subarray(i+4,i+8))===e[0])if(1===e.length)s.push(t.subarray(i+8,a));else{const r=ki(t.subarray(i+8,a),e.slice(1));r.length&&_i.apply(s,r)}i=a}return s}function Ii(t){const e=[],s=t[0];let r=8;const i=bi(t,r);r+=4;r+=0===s?8:16,r+=2;let n=t.length+0;const a=Li(t,r);r+=2;for(let s=0;s<a;s++){let s=r;const a=bi(t,s);s+=4;const o=2147483647&a;if(1===(2147483648&a)>>>31)return Fr.warn("SIDX has hierarchical references (not supported)"),null;const l=bi(t,s);s+=4,e.push({referenceSize:o,subsegmentDuration:l,info:{duration:l/i,start:n,end:n+o-1}}),n+=o,s+=4,r=s}return{earliestPresentationTime:0,timescale:i,version:s,referencesCount:a,references:e}}function Di(t){const e=[],s=ki(t,["moov","trak"]);for(let t=0;t<s.length;t++){const r=s[t],i=ki(r,["tkhd"])[0];if(i){let t=i[0],s=0===t?12:20;const n=bi(i,s),a=ki(r,["mdia","mdhd"])[0];if(a){t=a[0],s=0===t?12:20;const i=bi(a,s),o=ki(r,["mdia","hdlr"])[0];if(o){const t=Ai(o.subarray(8,12)),s={soun:Gr,vide:$r}[t];if(s){const t=ki(r,["mdia","minf","stbl","stsd"])[0];let a;t&&(a=Ai(t.subarray(12,16))),e[n]={timescale:i,type:s},e[s]={timescale:i,id:n,codec:a}}}}}}return ki(t,["moov","mvex","trex"]).forEach(t=>{const s=bi(t,4),r=e[s];r&&(r.default={duration:bi(t,12),flags:bi(t,20)})}),e}function Ci(t){const e=ki(t,["schm"])[0];if(e){const s=Ai(e.subarray(4,8));if("cbcs"===s||"cenc"===s)return ki(t,["schi","tenc"])[0]}return Fr.error("[eme] missing 'schm' box"),null}function Pi(t){const e=bi(t,0);let s=8;1&e&&(s+=4),4&e&&(s+=4);let r=0;const i=bi(t,4);for(let n=0;n<i;n++){if(256&e){r+=bi(t,s),s+=4}512&e&&(s+=4),1024&e&&(s+=4),2048&e&&(s+=4)}return r}function Oi(t,e){const s=new Uint8Array(t.length+e.length);return s.set(t),s.set(e,t.length),s}function Mi(t,e){const s=[],r=e.samples,i=e.timescale,n=e.id;let a=!1;return ki(r,["moof"]).map(o=>{const l=o.byteOffset-8;ki(o,["traf"]).map(o=>{const d=ki(o,["tfdt"]).map(t=>{const e=t[0];let s=bi(t,4);return 1===e&&(s*=Math.pow(2,32),s+=bi(t,8)),s/i})[0];return void 0!==d&&(t=d),ki(o,["tfhd"]).map(d=>{const c=bi(d,4),u=16777215&bi(d,0);let h=0;const f=0!=(16&u);let g=0;const p=0!=(32&u);let m=8;c===n&&(0!=(1&u)&&(m+=8),0!=(2&u)&&(m+=4),0!=(8&u)&&(h=bi(d,m),m+=4),f&&(g=bi(d,m),m+=4),p&&(m+=4),"video"===e.type&&(a=function(t){if(!t)return!1;const e=t.indexOf("."),s=e<0?t:t.substring(0,e);return"hvc1"===s||"hev1"===s||"dvh1"===s||"dvhe"===s}(e.codec)),ki(o,["trun"]).map(n=>{const o=n[0],d=16777215&bi(n,0),c=0!=(1&d);let u=0;const f=0!=(4&d),p=0!=(256&d);let m=0;const y=0!=(512&d);let v=0;const E=0!=(1024&d),T=0!=(2048&d);let _=0;const S=bi(n,4);let A=8;c&&(u=bi(n,A),A+=4),f&&(A+=4);let L=u+l;for(let l=0;l<S;l++){if(p?(m=bi(n,A),A+=4):m=h,y?(v=bi(n,A),A+=4):v=g,E&&(A+=4),T&&(_=0===o?bi(n,A):wi(n,A),A+=4),e.type===$r){let e=0;for(;e<v;){const n=bi(r,L);if(L+=4,xi(a,r[L])){Fi(r.subarray(L,L+n),a?2:1,t+_/i,s)}L+=n,e+=n+4}}t+=m/i}}))})})}),s}function xi(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function Fi(t,e,s,r){const i=Ni(t);let n=0;n+=e;let a=0,o=0,l=!1,d=0;for(;n<i.length;){a=0;do{if(n>=i.length)break;d=i[n++],a+=d}while(255===d);o=0;do{if(n>=i.length)break;d=i[n++],o+=d}while(255===d);const t=i.length-n;if(!l&&4===a&&n<i.length){l=!0;if(181===i[n++]){const t=Li(i,n);if(n+=2,49===t){const t=bi(i,n);if(n+=4,1195456820===t){const t=i[n++];if(3===t){const e=i[n++],o=31&e,l=64&e,d=l?2+3*o:0,c=new Uint8Array(d);if(l){c[0]=e;for(let t=1;t<d;t++)c[t]=i[n++]}r.push({type:t,payloadType:a,pts:s,bytes:c})}}}}}else if(5===a&&o<t){if(l=!0,o>16){const t=[];for(let e=0;e<16;e++){const s=i[n++].toString(16);t.push(1==s.length?"0"+s:s),3!==e&&5!==e&&7!==e&&9!==e||t.push("-")}const e=o-16,l=new Uint8Array(e);for(let t=0;t<e;t++)l[t]=i[n++];r.push({payloadType:a,pts:s,uuid:t.join(""),userData:mi(l),userDataBytes:l})}}else if(o<t)n+=o;else if(o>t)break}}function Ni(t){const e=t.byteLength,s=[];let r=1;for(;r<e-2;)0===t[r]&&0===t[r+1]&&3===t[r+2]?(s.push(r+2),r+=2):r++;if(0===s.length)return t;const i=e-s.length,n=new Uint8Array(i);let a=0;for(r=0;r<i;a++,r++)a===s[0]&&(a++,s.shift()),n[r]=t[a];return n}function Ui(t,e,s){if(16!==t.byteLength)throw new RangeError("Invalid system id");let r,i,n;if(e){r=1,i=new Uint8Array(16*e.length);for(let t=0;t<e.length;t++){const s=e[t];if(16!==s.byteLength)throw new RangeError("Invalid key");i.set(s,16*t)}}else r=0,i=new Uint8Array;r>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return s&&s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),function(t,...e){const s=e.length;let r=8,i=s;for(;i--;)r+=e[i].byteLength;const n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(t,4),i=0,r=8;i<s;i++)n.set(e[i],r),r+=e[i].byteLength;return n}([112,115,115,104],new Uint8Array([r,0,0,0]),t,n,i,a,s||new Uint8Array)}let Bi={};class LevelKey{static clearKeyUriToKeyIdMap(){Bi={}}constructor(t,e,s,r=[1],i=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=t,this.uri=e,this.keyFormat=s,this.keyFormatVersions=r,this.iv=i,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&"AES-128"!==t}isSupported(){if(this.method){if("AES-128"===this.method||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Yr:case Xr:case zr:case Wr:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof t&&("AES-128"!==this.method||this.iv||Fr.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);const e=function(t){const e=new Uint8Array(16);for(let s=12;s<16;s++)e[s]=t>>8*(15-s)&255;return e}(t);return new LevelKey(this.method,this.uri,"identity",this.keyFormatVersions,e)}const e=Vr(this.uri);if(e)switch(this.keyFormat){case Xr:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case zr:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Ui(t,null,e);const s=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),r=String.fromCharCode.apply(null,Array.from(s)),i=r.substring(r.indexOf("<"),r.length),n=(new DOMParser).parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(n){const t=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(t){const e=Kr(t).subarray(0,16);!function(t){const e=function(t,e,s){const r=t[e];t[e]=t[s],t[s]=r};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}(e),this.keyId=e}}break}default:{let t=e.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let t=Bi[this.uri];if(!t){const e=Object.keys(Bi).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16);new DataView(t.buffer,12,4).setUint32(0,e),Bi[this.uri]=t}this.keyId=t}return this}}const Gi=/\{\$([a-zA-Z0-9-_]+)\}/g;function $i(t){return Gi.test(t)}function Hi(t,e,s){if(null!==t.variableList||t.hasVariableRefs)for(let r=s.length;r--;){const i=s[r],n=e[i];n&&(e[i]=Ki(t,n))}}function Ki(t,e){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return e.replace(Gi,e=>{const r=e.substring(2,e.length-1),i=null==s?void 0:s[r];return void 0===i?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),e):i})}return e}function Vi(t,e,s){let r,i,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){r=e.QUERYPARAM;try{const t=new self.URL(s).searchParams;if(!t.has(r))throw new Error(`"${r}" does not match any query parameter in URI: "${s}"`);i=t.get(r)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: "+e.message))}}else r=e.NAME,i=e.VALUE;r in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):n[r]=i||""}function qi(t,e,s){const r=e.IMPORT;if(s&&r in s){let e=t.variableList;e||(t.variableList=e={}),e[r]=s[r]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}const ji={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}};function Wi(t,e){return MediaSource.isTypeSupported(`${e||"video"}/mp4;codecs="${t}"`)}const Yi=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,zi=/#EXT-X-MEDIA:(.*)/g,Xi=/^#EXT(?:INF|-X-TARGETDURATION):/m,Qi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Zi=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class M3U8Parser{static findGroup(t,e){for(let s=0;s<t.length;s++){const r=t[s];if(r.id===e)return r}}static convertAVC1ToAVCOTI(t){const e=t.split(".");if(e.length>2){let t=e.shift()+".";return t+=parseInt(e.shift()).toString(16),t+=("000"+parseInt(e.shift()).toString(16)).slice(-4),t}return t}static resolve(t,e){return Ar.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Xi.test(t)}static parseMasterPlaylist(t,e){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:$i(t)},r=[];let i;for(Yi.lastIndex=0;null!=(i=Yi.exec(t));)if(i[1]){var n;const t=new AttrList(i[1]);Hi(s,t,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const a=Ki(s,i[2]),o={attrs:t,bitrate:t.decimalInteger("AVERAGE-BANDWIDTH")||t.decimalInteger("BANDWIDTH"),name:t.NAME,url:M3U8Parser.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),en((t.CODECS||"").split(/[ ,]+/).filter(t=>t),o),o.videoCodec&&-1!==o.videoCodec.indexOf("avc1")&&(o.videoCodec=M3U8Parser.convertAVC1ToAVCOTI(o.videoCodec)),null!=(n=o.unknownCodecs)&&n.length||r.push(o),s.levels.push(o)}else if(i[3]){const t=i[3],r=i[4];switch(t){case"SESSION-DATA":{const t=new AttrList(r);Hi(s,t,["DATA-ID","LANGUAGE","VALUE","URI"]);const e=t["DATA-ID"];e&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[e]=t);break}case"SESSION-KEY":{const t=Ji(r,e,s);t.encrypted&&t.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(t)):Fr.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":{const t=new AttrList(r);Hi(s,t,["NAME","VALUE","QUERYPARAM"]),Vi(s,t,e)}break;case"CONTENT-STEERING":{const t=new AttrList(r);Hi(s,t,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:M3U8Parser.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=tn(r)}}const a=r.length>0&&r.length<s.levels.length;return s.levels=a?r:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,e,s){let r;const i={},n=s.levels,a={AUDIO:n.map(t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec})),SUBTITLES:n.map(t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(zi.lastIndex=0;null!==(r=zi.exec(t));){const t=new AttrList(r[1]),n=t.TYPE;if(n){const r=a[n],l=i[n]||[];i[n]=l,Hi(s,t,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const d={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",instreamId:t["INSTREAM-ID"],name:t.NAME||t.LANGUAGE||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:t.LANGUAGE,url:t.URI?M3U8Parser.resolve(t.URI,e):""};if(null!=r&&r.length){const t=M3U8Parser.findGroup(r,d.groupId)||r[0];sn(d,t,"audioCodec"),sn(d,t,"textCodec")}l.push(d)}}return i}static parseLevelPlaylist(t,e,s,r,i,n){const a=new LevelDetails(e),o=a.fragments;let l,d,c,u=null,h=0,f=0,g=0,p=0,m=null,y=new Fragment(r,e),v=-1,E=!1;for(Qi.lastIndex=0,a.m3u8=t,a.hasVariableRefs=$i(t);null!==(l=Qi.exec(t));){E&&(E=!1,y=new Fragment(r,e),y.start=g,y.sn=h,y.cc=p,y.level=s,u&&(y.initSegment=u,y.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null));const t=l[1];if(t){y.duration=parseFloat(t);const e=(" "+l[2]).slice(1);y.title=e||null,y.tagList.push(e?["INF",t,e]:["INF",t])}else if(l[3]){if(kr(y.duration)){y.start=g,c&&an(y,c,a),y.sn=h,y.level=s,y.cc=p,y.urlId=i,o.push(y);const t=(" "+l[3]).slice(1);y.relurl=Ki(a,t),rn(y,m),m=y,g+=y.duration,h++,f=0,E=!0}}else if(l[4]){const t=(" "+l[4]).slice(1);m?y.setByteRange(t,m):y.setByteRange(t)}else if(l[5])y.rawProgramDateTime=(" "+l[5]).slice(1),y.tagList.push(["PROGRAM-DATE-TIME",y.rawProgramDateTime]),-1===v&&(v=o.length);else{if(l=l[0].match(Zi),!l){Fr.warn("No matches on slow regex match for level playlist!");continue}for(d=1;d<l.length&&void 0===l[d];d++);const t=(" "+l[d]).slice(1),i=(" "+l[d+1]).slice(1),g=l[d+2]?(" "+l[d+2]).slice(1):"";switch(t){case"PLAYLIST-TYPE":a.type=i.toUpperCase();break;case"MEDIA-SEQUENCE":h=a.startSN=parseInt(i);break;case"SKIP":{const t=new AttrList(i);Hi(a,t,["RECENTLY-REMOVED-DATERANGES"]);const e=t.decimalInteger("SKIPPED-SEGMENTS");if(kr(e)){a.skippedSegments=e;for(let t=e;t--;)o.unshift(null);h+=e}const s=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(a.recentlyRemovedDateranges=s.split("\t"));break}case"TARGETDURATION":a.targetduration=Math.max(parseInt(i),1);break;case"VERSION":a.version=parseInt(i);break;case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"#":(i||g)&&y.tagList.push(g?[i,g]:[i]);break;case"DISCONTINUITY":p++,y.tagList.push(["DIS"]);break;case"GAP":y.gap=!0,y.tagList.push([t]);break;case"BITRATE":y.tagList.push([t,i]);break;case"DATERANGE":{const t=new AttrList(i);Hi(a,t,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),Hi(a,t,t.clientAttrs);const e=new DateRange(t,a.dateRanges[t.ID]);e.isValid||a.skippedSegments?a.dateRanges[e.id]=e:Fr.warn(`Ignoring invalid DATERANGE tag: "${i}"`),y.tagList.push(["EXT-X-DATERANGE",i]);break}case"DEFINE":{const t=new AttrList(i);Hi(a,t,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in t?qi(a,t,n):Vi(a,t,e)}break;case"DISCONTINUITY-SEQUENCE":p=parseInt(i);break;case"KEY":{const t=Ji(i,e,a);if(t.isSupported()){if("NONE"===t.method){c=void 0;break}c||(c={}),c[t.keyFormat]&&(c=Rr({},c)),c[t.keyFormat]=t}else Fr.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${i}"`);break}case"START":a.startTimeOffset=tn(i);break;case"MAP":{const t=new AttrList(i);if(Hi(a,t,["BYTERANGE","URI"]),y.duration){const i=new Fragment(r,e);nn(i,t,s,c),u=i,y.initSegment=u,u.rawProgramDateTime&&!y.rawProgramDateTime&&(y.rawProgramDateTime=u.rawProgramDateTime)}else nn(y,t,s,c),u=y,E=!0;break}case"SERVER-CONTROL":{const t=new AttrList(i);a.canBlockReload=t.bool("CAN-BLOCK-RELOAD"),a.canSkipUntil=t.optionalFloat("CAN-SKIP-UNTIL",0),a.canSkipDateRanges=a.canSkipUntil>0&&t.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=t.optionalFloat("PART-HOLD-BACK",0),a.holdBack=t.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const t=new AttrList(i);a.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=a.partList;t||(t=a.partList=[]);const s=f>0?t[t.length-1]:void 0,r=f++,n=new AttrList(i);Hi(a,n,["BYTERANGE","URI"]);const o=new Part(n,y,e,r,s);t.push(o),y.duration+=o.duration;break}case"PRELOAD-HINT":{const t=new AttrList(i);Hi(a,t,["URI"]),a.preloadHint=t;break}case"RENDITION-REPORT":{const t=new AttrList(i);Hi(a,t,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(t);break}default:Fr.warn("line parsed but not handled: "+l)}}}m&&!m.relurl?(o.pop(),g-=m.duration,a.partList&&(a.fragmentHint=m)):a.partList&&(rn(y,m),y.cc=p,a.fragmentHint=y,c&&an(y,c,a));const T=o.length,_=o[0],S=o[T-1];if(g+=a.skippedSegments*a.targetduration,g>0&&T&&S){a.averagetargetduration=g/T;const t=S.sn;a.endSN="initSegment"!==t?t:0,a.live||(S.endList=!0),_&&(a.startCC=_.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(g+=a.fragmentHint.duration),a.totalduration=g,a.endCC=p,v>0&&function(t,e){let s=t[e];for(let r=e;r--;){const e=t[r];if(!e)return;e.programDateTime=s.programDateTime-1e3*e.duration,s=e}}(o,v),a}}function Ji(t,e,s){var r,i;const n=new AttrList(t);Hi(s,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,c=null!=(i=n.KEYFORMAT)?i:"identity";o&&n.IV&&!l&&Fr.error("Invalid IV: "+n.IV);const u=o?M3U8Parser.resolve(o,e):"",h=(d||"1").split("/").map(Number).filter(Number.isFinite);return new LevelKey(a,u,c,h,l)}function tn(t){const e=new AttrList(t).decimalFloatingPoint("TIME-OFFSET");return kr(e)?e:null}function en(t,e){["video","audio","text"].forEach(s=>{const r=t.filter(t=>function(t,e){const s=ji[e];return!!s&&!0===s[t.slice(0,4)]}(t,s));if(r.length){const i=r.filter(t=>0===t.lastIndexOf("avc1",0)||0===t.lastIndexOf("mp4a",0));e[s+"Codec"]=i.length>0?i[0]:r[0],t=t.filter(t=>-1===r.indexOf(t))}}),e.unknownCodecs=t}function sn(t,e,s){const r=e[s];r&&(t[s]=r)}function rn(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),kr(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function nn(t,e,s,r){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=s,t.sn="initSegment",r&&(t.levelkeys=r),t.initSegment=null}function an(t,e,s){t.levelkeys=e;const{encryptedFragments:r}=s;r.length&&r[r.length-1].levelkeys===e||!Object.keys(e).some(t=>e[t].isCommonEncryption)||r.push(t)}var on="manifest",ln="level",dn="audioTrack",cn="subtitleTrack",un="main",hn="audio",fn="subtitle";function gn(t){const{type:e}=t;switch(e){case dn:return hn;case cn:return fn;default:return un}}function pn(t,e){let s=t.url;return void 0!==s&&0!==s.indexOf("data:")||(s=e.url),s}class PlaylistLoader{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ir.LEVEL_LOADING,this.onLevelLoading,this),t.on(Ir.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(Ir.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ir.LEVEL_LOADING,this.onLevelLoading,this),t.off(Ir.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(Ir.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(t){const e=this.hls.config,s=e.pLoader,r=e.loader,i=new(s||r)(e);return this.loaders[t.type]=i,i}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:s}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:on,url:s,deliveryDirectives:null})}onLevelLoading(t,e){const{id:s,level:r,url:i,deliveryDirectives:n}=e;this.load({id:s,level:r,responseType:"text",type:ln,url:i,deliveryDirectives:n})}onAudioTrackLoading(t,e){const{id:s,groupId:r,url:i,deliveryDirectives:n}=e;this.load({id:s,groupId:r,level:null,responseType:"text",type:dn,url:i,deliveryDirectives:n})}onSubtitleTrackLoading(t,e){const{id:s,groupId:r,url:i,deliveryDirectives:n}=e;this.load({id:s,groupId:r,level:null,responseType:"text",type:cn,url:i,deliveryDirectives:n})}load(t){var e;const s=this.hls.config;let r,i=this.getInternalLoader(t);if(i){const e=i.context;if(e&&e.url===t.url)return void Fr.trace("[playlist-loader]: playlist request ongoing");Fr.log("[playlist-loader]: aborting previous loader for type: "+t.type),i.abort()}if(r=t.type===on?s.manifestLoadPolicy.default:Rr({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(t),null!=(e=t.deliveryDirectives)&&e.part){let e;if(t.type===ln&&null!==t.level?e=this.hls.levels[t.level].details:t.type===dn&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===cn&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,s=e.targetduration;if(t&&s){const e=1e3*Math.max(3*t,.8*s);r=Rr({},r,{maxTimeToFirstByteMs:Math.min(e,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(t,e,s,r)=>{const i=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=t.data;0===n.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),M3U8Parser.isMediaPlaylist(n)?this.handleTrackOrLevelPlaylist(t,e,s,r||null,i):this.handleMasterPlaylist(t,e,s,r)):this.handleManifestParsingError(t,s,new Error("no EXTM3U delimiter"),r||null,e)},onError:(t,e,s,r)=>{this.handleNetworkError(e,s,!1,t,r)},onTimeout:(t,e,s)=>{this.handleNetworkError(e,s,!0,void 0,t)}};i.load(t,a,o)}handleMasterPlaylist(t,e,s,r){const i=this.hls,n=t.data,a=pn(t,s),o=M3U8Parser.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(t,s,o.playlistParsingError,r,e);const{contentSteering:l,levels:d,sessionData:c,sessionKeys:u,startTimeOffset:h,variableList:f}=o;this.variableList=f;const{AUDIO:g=[],SUBTITLES:p,"CLOSED-CAPTIONS":m}=M3U8Parser.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some(t=>!t.url)||!d[0].audioCodec||d[0].attrs.AUDIO||(Fr.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new AttrList({}),bitrate:0,url:""}))}i.trigger(Ir.MANIFEST_LOADED,{levels:d,audioTracks:g,subtitles:p,captions:m,contentSteering:l,url:a,stats:e,networkDetails:r,sessionData:c,sessionKeys:u,startTimeOffset:h,variableList:f})}handleTrackOrLevelPlaylist(t,e,s,r,i){const n=this.hls,{id:a,level:o,type:l}=s,d=pn(t,s),c=kr(a)?a:0,u=kr(o)?o:c,h=gn(s),f=M3U8Parser.parseLevelPlaylist(t.data,d,u,h,c,this.variableList);if(l===on){const t={attrs:new AttrList({}),bitrate:0,details:f,name:"",url:d};n.trigger(Ir.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:d,stats:e,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,t,e,s,r,i)}handleManifestParsingError(t,e,s,r,i){this.hls.trigger(Ir.ERROR,{type:Dr.NETWORK_ERROR,details:Cr.MANIFEST_PARSING_ERROR,fatal:e.type===on,url:t.url,err:s,error:s,reason:s.message,response:t,context:e,networkDetails:r,stats:i})}handleNetworkError(t,e,s=!1,r,i){let n=`A network ${s?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${t.type}`;t.type===ln?n+=`: ${t.level} id: ${t.id}`:t.type!==dn&&t.type!==cn||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(n);Fr.warn("[playlist-loader]: "+n);let o=Cr.UNKNOWN,l=!1;const d=this.getInternalLoader(t);switch(t.type){case on:o=s?Cr.MANIFEST_LOAD_TIMEOUT:Cr.MANIFEST_LOAD_ERROR,l=!0;break;case ln:o=s?Cr.LEVEL_LOAD_TIMEOUT:Cr.LEVEL_LOAD_ERROR,l=!1;break;case dn:o=s?Cr.AUDIO_TRACK_LOAD_TIMEOUT:Cr.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case cn:o=s?Cr.SUBTITLE_TRACK_LOAD_TIMEOUT:Cr.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(t.type);const c={type:Dr.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:d,context:t,error:a,networkDetails:e,stats:i};if(r){const s=(null==e?void 0:e.url)||t.url;c.response=br({url:s,data:void 0},r)}this.hls.trigger(Ir.ERROR,c)}handlePlaylistLoaded(t,e,s,r,i,n){const a=this.hls,{type:o,level:l,id:d,groupId:c,deliveryDirectives:u}=r,h=pn(e,r),f=gn(r),g="number"==typeof r.level&&f===un?l:void 0;if(!t.fragments.length){const t=new Error("No Segments found in Playlist");return void a.trigger(Ir.ERROR,{type:Dr.NETWORK_ERROR,details:Cr.LEVEL_EMPTY_ERROR,fatal:!1,url:h,error:t,reason:t.message,response:e,context:r,level:g,parent:f,networkDetails:i,stats:s})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const p=t.playlistParsingError;if(p)a.trigger(Ir.ERROR,{type:Dr.NETWORK_ERROR,details:Cr.LEVEL_PARSING_ERROR,fatal:!1,url:h,error:p,reason:p.message,response:e,context:r,level:g,parent:f,networkDetails:i,stats:s});else switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case on:case ln:a.trigger(Ir.LEVEL_LOADED,{details:t,level:g||0,id:d||0,stats:s,networkDetails:i,deliveryDirectives:u});break;case dn:a.trigger(Ir.AUDIO_TRACK_LOADED,{details:t,id:d||0,groupId:c||"",stats:s,networkDetails:i,deliveryDirectives:u});break;case cn:a.trigger(Ir.SUBTITLE_TRACK_LOADED,{details:t,id:d||0,groupId:c||"",stats:s,networkDetails:i,deliveryDirectives:u})}}}function mn(t,e){let s;try{s=new Event("addtrack")}catch(t){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=t,e.dispatchEvent(s)}function yn(t,e){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error("addCue is failed for: "+e)}catch(s){Fr.debug("[texttrack-utils]: "+s);const r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,t.addCue(r)}"disabled"===s&&(t.mode=s)}function vn(t){const e=t.mode;if("disabled"===e&&(t.mode="hidden"),t.cues)for(let e=t.cues.length;e--;)t.removeCue(t.cues[e]);"disabled"===e&&(t.mode=e)}function En(t,e,s,r){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&t.cues.length>0){const i=function(t,e,s){const r=[],i=function(t,e){if(e<t[0].startTime)return 0;const s=t.length-1;if(e>t[s].endTime)return-1;let r=0,i=s;for(;r<=i;){const n=Math.floor((i+r)/2);if(e<t[n].startTime)i=n-1;else{if(!(e>t[n].startTime&&r<s))return n;r=n+1}}return t[r].startTime-e<e-t[i].startTime?r:i}(t,e);if(i>-1)for(let n=i,a=t.length;n<a;n++){const i=t[n];if(i.startTime>=e&&i.endTime<=s)r.push(i);else if(i.startTime>s)return r}return r}(t.cues,e,s);for(let e=0;e<i.length;e++)r&&!r(i[e])||t.removeCue(i[e])}"disabled"===i&&(t.mode=i)}var Tn="org.id3",_n="com.apple.quicktime.HLS",Sn="https://aomedia.org/emsg/ID3";function An(){if("undefined"!=typeof self)return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const Ln=(()=>{const t=An();try{new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function bn(t,e){return t.getTime()/1e3-e}class ID3TrackController{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:t}=this;t.on(Ir.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Ir.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ir.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(Ir.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Ir.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(Ir.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Ir.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ir.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(Ir.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Ir.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,e){this.media=e.media}onMediaDetaching(){this.id3Track&&(vn(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){const s=t[e];if("metadata"===s.kind&&"id3"===s.label)return mn(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:s,enableID3MetadataCues:r}}}=this;if(!s&&!r)return;const{samples:i}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=An();for(let t=0;t<i.length;t++){const e=i[t].type;if(e===Sn&&!s||!r)continue;const a=ci(i[t].data);if(a){const s=i[t].pts;let r=s+i[t].duration;r>Ln&&(r=Ln);r-s<=0&&(r=s+.25);for(let t=0;t<a.length;t++){const i=a[t];if(!li(i)){this.updateId3CueEnds(s);const t=new n(s,r,"");t.value=i,e&&(t.type=e),this.id3Track.addCue(t)}}}}}updateId3CueEnds(t){var e;const s=null==(e=this.id3Track)?void 0:e.cues;if(s)for(let e=s.length;e--;){const r=s[e];r.startTime<t&&r.endTime===Ln&&(r.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:s,type:r}){const{id3Track:i,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(i&&(a||o)){let t;t="audio"===r?t=>t.type===Tn&&o:"video"===r?t=>t.type===Sn&&a:t=>t.type===Tn&&o||t.type===Sn&&a,En(i,e,s,t)}}onLevelUpdated(t,{details:e}){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:s,id3Track:r}=this,{dateRanges:i}=e,n=Object.keys(i);if(r){const t=Object.keys(s).filter(t=>!n.includes(t));for(let e=t.length;e--;){const i=t[e];Object.keys(s[i].cues).forEach(t=>{r.removeCue(s[i].cues[t])}),delete s[i]}}const a=e.fragments[e.fragments.length-1];if(0===n.length||!kr(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,l=An();for(let t=0;t<n.length;t++){const e=n[t],r=i[e],a=s[e],u=(null==a?void 0:a.cues)||{};let h=(null==a?void 0:a.durationKnown)||!1;const f=bn(r.startDate,o);let g=Ln;const p=r.endDate;if(p)g=bn(p,o),h=!0;else if(r.endOnNext&&!h){const t=n.reduce((t,e)=>{const s=i[e];return s.class===r.class&&s.id!==e&&s.startDate>r.startDate&&t.push(s),t},[]).sort((t,e)=>t.startDate.getTime()-e.startDate.getTime())[0];t&&(g=bn(t.startDate,o),h=!0)}const m=Object.keys(r.attr);for(let t=0;t<m.length;t++){const s=m[t];if("ID"===(c=s)||"CLASS"===c||"START-DATE"===c||"DURATION"===c||"END-DATE"===c||"END-ON-NEXT"===c)continue;let i=u[s];if(i)h&&!a.durationKnown&&(i.endTime=g);else{let t=r.attr[s];i=new l(f,g,""),Br(s)&&(d=t,t=Uint8Array.from(d.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer),i.value={key:s,data:t},i.type=_n,i.id=e,this.id3Track.addCue(i),u[s]=i}}s[e]={cues:u,dateRange:r,durationKnown:h}}var d,c}}class LatencyController{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=t,this.config=t.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:t,levelDetails:e}=this;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const{levelDetails:t}=this;if(null===t)return null;const{holdBack:e,partHoldBack:s,targetduration:r}=t,{liveSyncDuration:i,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||e;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==i?i:n*r);const d=r;return l+Math.min(1*this.stallCount,d)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency,s=this.levelDetails;if(null===t||null===e||null===s)return null;const r=s.edge,i=t-e-this.edgeStalled,n=r-s.totalduration,a=r-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,i),a)}get drift(){const{levelDetails:t}=this;return null===t?1:t.drift}get edgeStalled(){const{levelDetails:t}=this;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t,levelDetails:e}=this;if(!t||!e)return 0;const s=t.buffered.length;return(s?t.buffered.end(s-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(Ir.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Ir.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(Ir.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Ir.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(Ir.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(Ir.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Ir.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(Ir.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Ir.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(Ir.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){this.levelDetails=e,e.advanced&&this.timeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(t,e){var s;e.details===Cr.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(s=this.levelDetails)&&s.live&&Fr.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:t,levelDetails:e}=this;if(!t||!e)return;this.currentTime=t.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:i}=this.config;if(!r||1===i)return;const n=this.targetLatency;if(null===n)return;const a=s-n,o=a<Math.min(this.maxLatency,n+e.targetduration);if(e.live&&o&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,i)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;t.playbackRate=Math.min(e,Math.max(1,s))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}estimateLiveEdge(){const{levelDetails:t}=this;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}const wn=["NONE","TYPE-0","TYPE-1",null];var Rn="",kn="YES",In="v2";class HlsUrlParameters{constructor(t,e,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=s}addDirectives(t){const e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}}class Level{constructor(t){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.unknownCodecs=t.unknownCodecs,this.codecSet=[t.videoCodec,t.audioCodec].filter(t=>t).join(",").replace(/\.[^.,]+/g,"")}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get attrs(){return this._attrs[this._urlId]}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get uri(){return this.url[this._urlId]||""}get urlId(){return this._urlId}set urlId(t){const e=t%this.url.length;this._urlId!==e&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=e)}get audioGroupId(){var t;return null==(t=this.audioGroupIds)?void 0:t[this.urlId]}get textGroupId(){var t;return null==(t=this.textGroupIds)?void 0:t[this.urlId]}addFallback(t){this.url.push(t.url),this._attrs.push(t.attrs)}}function Dn(t,e){const s=e.startPTS;if(kr(s)){let r,i=0;e.sn>t.sn?(i=s-t.start,r=t):(i=t.start-s,r=e),r.duration!==i&&(r.duration=i)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration}else e.start=Math.max(t.start-e.duration,0)}function Cn(t,e,s,r,i,n){r-s<=0&&(Fr.warn("Fragment should have a positive duration",e),r=s+e.duration,n=i+e.duration);let a=s,o=r;const l=e.startPTS,d=e.endPTS;if(kr(l)){const t=Math.abs(l-s);kr(e.deltaPTS)?e.deltaPTS=Math.max(t,e.deltaPTS):e.deltaPTS=t,a=Math.max(s,l),s=Math.min(s,l),i=Math.min(i,e.startDTS),o=Math.min(r,d),r=Math.max(r,d),n=Math.max(n,e.endDTS)}const c=s-e.start;0!==e.start&&(e.start=s),e.duration=r-e.start,e.startPTS=s,e.maxStartPTS=a,e.startDTS=i,e.endPTS=r,e.minEndPTS=o,e.endDTS=n;const u=e.sn;if(!t||u<t.startSN||u>t.endSN)return 0;let h;const f=u-t.startSN,g=t.fragments;for(g[f]=e,h=f;h>0;h--)Dn(g[h],g[h-1]);for(h=f;h<g.length-1;h++)Dn(g[h],g[h+1]);return t.fragmentHint&&Dn(g[g.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,c}function Pn(t,e){let s=null;const r=t.fragments;for(let t=r.length-1;t>=0;t--){const e=r[t].initSegment;if(e){s=e;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let i,n=0;if(function(t,e,s){const r=e.skippedSegments,i=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(r?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let t=i;t<=n;t++){const i=l[a+t];let n=o[t];r&&!n&&t<r&&(n=e.fragments[t]=i),i&&n&&s(i,n)}}(t,e,(t,r)=>{t.relurl&&(n=t.cc-r.cc),kr(t.startPTS)&&kr(t.endPTS)&&(r.start=r.startPTS=t.startPTS,r.startDTS=t.startDTS,r.maxStartPTS=t.maxStartPTS,r.endPTS=t.endPTS,r.endDTS=t.endDTS,r.minEndPTS=t.minEndPTS,r.duration=t.endPTS-t.startPTS,r.duration&&(i=r),e.PTSKnown=e.alignedSliding=!0),r.elementaryStreams=t.elementaryStreams,r.loader=t.loader,r.stats=t.stats,r.urlId=t.urlId,t.initSegment&&(r.initSegment=t.initSegment,s=t.initSegment)}),s){(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(t=>{var e;t.initSegment&&t.initSegment.relurl!==(null==(e=s)?void 0:e.relurl)||(t.initSegment=s)})}if(e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some(t=>!t),e.deltaUpdateFailed){Fr.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=function(t,e,s){const r=Rr({},t);s&&s.forEach(t=>{delete r[t]});return Object.keys(e).forEach(t=>{const s=new DateRange(e[t].attr,r[t]);s.isValid?r[t]=s:Fr.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[t].attr)}"`)}),r}(t.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(n){Fr.warn("discontinuity sliding from playlist, take drift into account");for(let t=0;t<a.length;t++)a[t].cc+=n}e.skippedSegments&&(e.startCC=e.fragments[0].cc),function(t,e,s){if(t&&e){let r=0;for(let i=0,n=t.length;i<=n;i++){const n=t[i],a=e[i+r];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):r--}}}(t.partList,e.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats}),i?Cn(e,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS):On(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const t=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=t),e.driftEndTime=o,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime}function On(t,e){const s=e.startSN+e.skippedSegments-t.startSN,r=t.fragments;s<0||s>=r.length||Mn(e,r[s].start)}function Mn(t,e){if(e){const s=t.fragments;for(let r=t.skippedSegments;r<s.length;r++)s[r].start+=e;t.fragmentHint&&(t.fragmentHint.start+=e)}}function xn(t,e,s){var r;return null!=t&&t.details?Fn(null==(r=t.details)?void 0:r.partList,e,s):null}function Fn(t,e,s){if(t)for(let r=t.length;r--;){const i=t[r];if(i.index===s&&i.fragment.sn===e)return i}return null}function Nn(t){switch(t.details){case Cr.FRAG_LOAD_TIMEOUT:case Cr.KEY_LOAD_TIMEOUT:case Cr.LEVEL_LOAD_TIMEOUT:case Cr.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Un(t,e){const s=Nn(e);return t.default[(s?"timeout":"error")+"Retry"]}function Bn(t,e){const s="linear"===t.backoff?1:Math.pow(2,e);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function Gn(t){return br(br({},t),{errorRetry:null,timeoutRetry:null})}function $n(t,e,s,r){return!!t&&e<t.maxNumRetry&&(function(t){return 0===t&&!1===navigator.onLine||!!t&&(t<400||t>499)}(r)||!!s)}const Hn=function(t,e){let s=0,r=t.length-1,i=null,n=null;for(;s<=r;){i=(s+r)/2|0,n=t[i];const a=e(n);if(a>0)s=i+1;else{if(!(a<0))return n;r=i-1}}return null};function Kn(t,e,s=0,r=0){let i=null;if(t?i=e[t.sn-e[0].sn+1]||null:0===s&&0===e[0].start&&(i=e[0]),i&&0===Vn(s,r,i))return i;const n=Hn(e,Vn.bind(null,s,r));return!n||n===t&&i?i:n}function Vn(t=0,e=0,s){if(s.start<=t&&s.start+s.duration>t)return 0;const r=Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-r<=t?1:s.start-r>t&&s.start?-1:0}function qn(t,e,s){const r=1e3*Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-r>t}var jn=0,Wn=2,Yn=5,zn=0,Xn=1,Qn=2;function Zn(t,e,s){if(performance.now()-t.lastErrorPerfMs>3e5)return!0;const r=t.details;if(e.details===Cr.FRAG_GAP&&r&&e.frag){const t=e.frag.start,s=Kn(null,r.fragments,t);if(s&&!s.gap)return!0}if(s&&t.errors.length<s.errors.length){const s=t.errors[t.errors.length-1];if(r&&s.frag&&e.frag&&Math.abs(s.frag.start-e.frag.start)>3*r.targetduration)return!0}return!1}class BasePlaylistController{constructor(t,e){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=Fr.log.bind(Fr,e+":"),this.warn=Fr.warn.bind(Fr,e+":"),this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){clearTimeout(this.timer),this.timer=-1}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e){const s=null==e?void 0:e.renditionReports;if(s){let r=-1;for(let i=0;i<s.length;i++){const n=s[i];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){Fr.warn("Could not construct new URL for Rendition Report: "+t),a=n.URI||""}if(a===t){r=i;break}a===t.substring(0,a.length)&&(r=i)}if(-1!==r){const t=s[r],i=parseInt(t["LAST-MSN"])||(null==e?void 0:e.lastPartSn);let n=parseInt(t["LAST-PART"])||(null==e?void 0:e.lastPartIndex);if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);n>=0&&t>e.partTarget&&(n+=1)}return new HlsUrlParameters(i,n>=0?n:void 0,Rn)}}}loadPlaylist(t){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}shouldReloadPlaylist(t){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(t)}playlistLoaded(t,e,s){const{details:r,stats:i}=e,n=self.performance.now(),a=i.loading.first?Math.max(0,n-i.loading.first):0;if(r.advancedDateTime=Date.now()-a,r.live||null!=s&&s.live){if(r.reloaded(s),s&&this.log(`live playlist ${t} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:"MISSED"}`),s&&r.fragments.length>0&&Pn(s,r),!this.canLoad||!r.live)return;let a,o=void 0,l=void 0;if(r.canBlockReload&&r.endSN&&r.advanced){const t=this.hls.config.lowLatencyMode,i=r.lastPartSn,n=r.endSN,d=r.lastPartIndex,c=i===n,u=t?0:d;-1!==d?(o=c?n+1:i,l=c?u:d+1):o=n+1;const h=r.age,f=h+r.ageHeader;let g=Math.min(f-r.partTarget,1.5*r.targetduration);if(g>0){if(s&&g>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${g} with playlist age: ${r.age}`),g=0;else{const t=Math.floor(g/r.targetduration);if(o+=t,void 0!==l){l+=Math.round(g%r.targetduration/r.partTarget)}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${h.toFixed(2)}s goal: ${g} skip sn ${t} to part ${l}`)}r.tuneInGoal=g}if(a=this.getDeliveryDirectives(r,e.deliveryDirectives,o,l),t||!c)return void this.loadPlaylist(a)}else r.canBlockReload&&(a=this.getDeliveryDirectives(r,e.deliveryDirectives,o,l));const d=this.hls.mainForwardBufferInfo,c=d?d.end-d.len:0,u=function(t,e=1/0){let s=1e3*t.targetduration;if(t.updated){const r=t.fragments,i=4;if(r.length&&s*i>e){const t=1e3*r[r.length-1].duration;t<s&&(s=t)}}else s/=2;return Math.round(s)}(r,1e3*(r.edge-c));r.updated&&n>this.requestScheduled+u&&(this.requestScheduled=i.loading.start),void 0!==o&&r.canBlockReload?this.requestScheduled=i.loading.first+u-(1e3*r.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+u<n?this.requestScheduled=n:this.requestScheduled-n<=0&&(this.requestScheduled+=u);let h=this.requestScheduled-n;h=Math.max(0,h),this.log(`reload live playlist ${t} in ${Math.round(h)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(a),h)}else this.clearTimer()}getDeliveryDirectives(t,e,s,r){let i=function(t,e){const{canSkipUntil:s,canSkipDateRanges:r,endSN:i}=t;return s&&(void 0!==e?e-i:0)<s?r?In:kn:Rn}(t,s);return null!=e&&e.skip&&t.deltaUpdateFailed&&(s=e.msn,r=e.part,i=Rn),new HlsUrlParameters(s,r,i)}checkRetry(t){const e=t.details,s=Nn(t),r=t.errorAction,{action:i,retryCount:n=0,retryConfig:a}=r||{},o=i===Yn&&!!r&&!!a;if(o){var l;if(this.requestScheduled=-1,s&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=Bn(a,n);this.timer=self.setTimeout(()=>this.loadPlaylist(),t),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,r.resolved=!0}return o}}let Jn;class LevelController extends BasePlaylistController{constructor(t,e){super(t,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ir.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Ir.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Ir.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Ir.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(Ir.FRAG_LOADED,this.onFragLoaded,this),t.on(Ir.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ir.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Ir.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Ir.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Ir.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(Ir.FRAG_LOADED,this.onFragLoaded,this),t.off(Ir.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}startLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.startLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const s=[],r={};let i;e.levels.forEach(t=>{var e;const n=t.attrs;-1!==(null==(e=t.audioCodec)?void 0:e.indexOf("mp4a.40.34"))&&(Jn||(Jn=/chrome|firefox/i.test(navigator.userAgent)),Jn&&(t.audioCodec=void 0));const{AUDIO:a,CODECS:o,"FRAME-RATE":l,"PATHWAY-ID":d,RESOLUTION:c,SUBTITLES:u}=n,h=`${(d||".")+"-"}${t.bitrate}-${c}-${l}-${o}`;i=r[h],i?i.addFallback(t):(i=new Level(t),r[h]=i,s.push(i)),ta(i,"audio",a),ta(i,"text",u)}),this.filterAndSortMediaOptions(s,e)}filterAndSortMediaOptions(t,e){let s=[],r=[],i=!1,n=!1,a=!1,o=t.filter(({audioCodec:t,videoCodec:e,width:s,height:r,unknownCodecs:o})=>(i||(i=!(!s||!r)),n||(n=!!e),a||(a=!!t),!(null!=o&&o.length)&&(!t||Wi(t,"audio"))&&(!e||Wi(e,"video"))));if((i||n)&&a&&(o=o.filter(({videoCodec:t,width:e,height:s})=>!!t||!(!e||!s))),0===o.length)return void Promise.resolve().then(()=>{if(this.hls){const t=new Error("no level with compatible codecs found in manifest");this.hls.trigger(Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:t,reason:t.message})}});e.audioTracks&&(s=e.audioTracks.filter(t=>!t.audioCodec||Wi(t.audioCodec,"audio")),ea(s)),e.subtitles&&(r=e.subtitles,ea(r));const l=o.slice(0);o.sort((t,e)=>t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"]?(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1:t.bitrate!==e.bitrate?t.bitrate-e.bitrate:t.attrs["FRAME-RATE"]!==e.attrs["FRAME-RATE"]?t.attrs.decimalFloatingPoint("FRAME-RATE")-e.attrs.decimalFloatingPoint("FRAME-RATE"):t.attrs.SCORE!==e.attrs.SCORE?t.attrs.decimalFloatingPoint("SCORE")-e.attrs.decimalFloatingPoint("SCORE"):i&&t.height!==e.height?t.height-e.height:0);let d=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let t=0;t<l.length;t++)if(l[t].pathwayId===o[0].pathwayId){d=l[t];break}this._levels=o;for(let t=0;t<o.length;t++)if(o[t]===d){this._firstLevel=t,this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${d.bitrate}`);break}const c=a&&!n,u={levels:o,audioTracks:s,subtitleTracks:r,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:a,video:n,altAudio:!c&&s.some(t=>!!t.url)};this.hls.trigger(Ir.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const s=new Error("invalid level idx"),r=t<0;if(this.hls.trigger(Ir.ERROR,{type:Dr.OTHER_ERROR,details:Cr.LEVEL_SWITCH_ERROR,level:t,fatal:r,error:s,reason:s.message}),r)return;t=Math.min(t,e.length-1)}const s=this.currentLevelIndex,r=this.currentLevel,i=r?r.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,s===t&&n.details&&r&&i===a)return;this.log(`Switching to level ${t}${a?" with Pathway "+a:""} from level ${s}${i?" with Pathway "+i:""}`);const o=Rr({},n,{level:t,maxBitrate:n.maxBitrate,attrs:n.attrs,uri:n.uri,urlId:n.urlId});delete o._attrs,delete o._urlId,this.hls.trigger(Ir.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==r?void 0:r.details);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this._firstLevel}return this._startLevel}set startLevel(t){this._startLevel=t}onError(t,e){!e.fatal&&e.context&&e.context.type===ln&&e.context.level===this.level&&this.checkRetry(e)}onFragLoaded(t,{frag:e}){if(void 0!==e&&e.type===un){const t=this._levels[e.level];void 0!==t&&(t.loadError=0)}}onLevelLoaded(t,e){var s;const{level:r,details:i}=e,n=this._levels[r];var a;if(!n)return this.warn("Invalid level index "+r),void(null!=(a=e.deliveryDirectives)&&a.skip&&(i.deltaUpdateFailed=!0));r===this.currentLevelIndex?(0===n.fragmentError&&(n.loadError=0),this.playlistLoaded(r,e,n.details)):null!=(s=e.deliveryDirectives)&&s.skip&&(i.deltaUpdateFailed=!0)}onAudioTrackSwitched(t,e){const s=this.currentLevel;if(!s)return;const r=this.hls.audioTracks[e.id].groupId;if(s.audioGroupIds&&s.audioGroupId!==r){let t=-1;for(let e=0;e<s.audioGroupIds.length;e++)if(s.audioGroupIds[e]===r){t=e;break}-1!==t&&t!==s.urlId&&(s.urlId=t,this.canLoad&&this.startLoad())}}loadPlaylist(t){super.loadPlaylist();const e=this.currentLevelIndex,s=this.currentLevel;if(s&&this.shouldLoadPlaylist(s)){const r=s.urlId;let i=s.uri;if(t)try{i=t.addDirectives(i)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}const n=s.attrs["PATHWAY-ID"];this.log(`Loading level index ${e}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""} with${n?" Pathway "+n:""} URI ${r+1}/${s.url.length} ${i}`),this.clearTimer(),this.hls.trigger(Ir.LEVEL_LOADING,{url:i,level:e,id:r,deliveryDirectives:t||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t,e){const s=(t,s)=>s!==e,r=this._levels.filter((r,i)=>i!==t||(r.url.length>1&&void 0!==e?(r.url=r.url.filter(s),r.audioGroupIds&&(r.audioGroupIds=r.audioGroupIds.filter(s)),r.textGroupIds&&(r.textGroupIds=r.textGroupIds.filter(s)),r.urlId=0,!0):(this.steering&&this.steering.removeLevel(r),!1)));this.hls.trigger(Ir.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(t,{levels:e}){e.forEach((t,e)=>{const{details:s}=t;null!=s&&s.fragments&&s.fragments.forEach(t=>{t.level=e})}),this._levels=e}}function ta(t,e,s){s&&("audio"===e?(t.audioGroupIds||(t.audioGroupIds=[]),t.audioGroupIds[t.url.length-1]=s):"text"===e&&(t.textGroupIds||(t.textGroupIds=[]),t.textGroupIds[t.url.length-1]=s))}function ea(t){const e={};t.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}var sa="NOT_LOADED",ra="APPENDING",ia="PARTIAL",na="OK";class FragmentTracker{constructor(t){this.mainFragEntity=null,this.activeParts=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=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(Ir.BUFFER_APPENDED,this.onBufferAppended,this),t.on(Ir.FRAG_BUFFERED,this.onFragBuffered,this),t.on(Ir.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(Ir.BUFFER_APPENDED,this.onBufferAppended,this),t.off(Ir.FRAG_BUFFERED,this.onFragBuffered,this),t.off(Ir.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.endListFragments=this.timeRanges=this.mainFragEntity=this.activeParts=null}getAppendedFrag(t,e){if(e===un){const{mainFragEntity:e,activeParts:s}=this;if(e)if(e&&s)for(let r=s.length;r--;){const i=s[r],n=i?i.end:e.appendedPTS;if(i.start<=t&&null!==n&&t<=n)return r>9&&(this.activeParts=s.slice(r-9)),i}else if(e.body.start<=t&&null!==e.appendedPTS&&t<=e.appendedPTS)return e.body}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){const{fragments:s}=this,r=Object.keys(s);for(let i=r.length;i--;){const n=s[r[i]];if((null==n?void 0:n.body.type)===e&&n.buffered){const e=n.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,s){this.timeRanges&&(this.timeRanges[t]=e),Object.keys(this.fragments).forEach(r=>{const i=this.fragments[r];if(!i)return;if(!i.buffered&&!i.loaded)return void(i.body.type===s&&this.removeFragment(i.body));const n=i.range[t];n&&n.time.some(t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return s&&this.removeFragment(i.body),s})})}detectPartialFragments(t){const e=this.timeRanges,{frag:s,part:r}=t;if(!e||"initSegment"===s.sn)return;const i=oa(s),n=this.fragments[i];n&&(Object.keys(e).forEach(t=>{const i=s.elementaryStreams[t];if(!i)return;const a=e[t],o=null!==r||!0===i.partial;n.range[t]=this.getBufferedTimes(s,r,o,a)}),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,n.body.endList&&(this.endListFragments[n.body.type]=n)):this.removeFragment(n.body))}fragBuffered(t,e){const s=oa(t);let r=this.fragments[s];!r&&e&&(r=this.fragments[s]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(t,e,s,r){const i={time:[],partial:s},n=e?e.start:t.start,a=e?e.end:t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<r.length;t++){const e=r.start(t)-this.bufferPadding,s=r.end(t)+this.bufferPadding;if(l>=e&&o<=s){i.time.push({startPTS:Math.max(n,r.start(t)),endPTS:Math.min(a,r.end(t))});break}if(n<s&&a>e)i.partial=!0,i.time.push({startPTS:Math.max(n,r.start(t)),endPTS:Math.min(a,r.end(t))});else if(a<=e)break}return i}getPartialFragment(t){let e,s,r,i=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&aa(d)&&(s=d.body.start-a,r=d.body.end+a,t>=s&&t<=r&&(e=Math.min(t-s,r-t),n<=e&&(i=d.body,n=e)))}),i}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||aa(e))}getState(t){const e=oa(t),s=this.fragments[e];return s?s.buffered?aa(s)?ia:na:ra:sa}isTimeBuffered(t,e,s){let r,i;for(let n=0;n<s.length;n++){if(r=s.start(n)-this.bufferPadding,i=s.end(n)+this.bufferPadding,t>=r&&e<=i)return!0;if(e<=r)return!1}return!1}onFragLoaded(t,e){const{frag:s,part:r}=e;if("initSegment"===s.sn||s.bitrateTest||r)return;const i=oa(s);this.fragments[i]={body:s,appendedPTS:null,loaded:e,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:s,part:r,timeRanges:i}=e;let n=this.mainFragEntity;if(s.type===un){const t=n?n.body:null;if(t!==s){n&&t&&t.sn!==s.sn&&(n.buffered=!0,this.fragments[oa(t)]=n);const e=oa(s);n=this.mainFragEntity=this.fragments[e]||{body:s,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)}}if(r){let t=this.activeParts;t||(this.activeParts=t=[]),t.push(r)}else this.activeParts=null}this.timeRanges=i,Object.keys(i).forEach(t=>{const e=i[t];if(this.detectEvictedFragments(t,e),!r&&n){const r=s.elementaryStreams[t];if(!r)return;for(let t=0;t<e.length;t++){const s=e.end(t);s<=r.endPTS&&s>r.startPTS?n.appendedPTS=Math.max(s,n.appendedPTS||0):n.appendedPTS=r.endPTS}}})}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=oa(t);return!!this.fragments[e]}removeFragmentsInRange(t,e,s,r,i){r&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||r&&!o.gap||o.start<e&&o.end>t&&(a.buffered||i)&&this.removeFragment(o)})}removeFragment(t){const e=oa(t);t.stats.loaded=0,t.clearElementaryStreamInfo(),this.mainFragEntity===this.fragments[e]&&(this.mainFragEntity=null),delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.mainFragEntity=null,this.activeParts=null,this.hasGaps=!1}}function aa(t){var e,s;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(s=t.range.audio)?void 0:s.partial))}function oa(t){return`${t.type}_${t.level}_${t.urlId}_${t.sn}`}const la=Math.pow(2,17);class FragmentLoader{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const s=t.url;if(!s)return Promise.reject(new LoadError({type:Dr.NETWORK_ERROR,details:Cr.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const r=this.config,i=r.fLoader,n=r.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap)return void o(ca(t));const l=this.loader=t.loader=i?new i(r):new n(r),d=da(t),c=Gn(r.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:la};t.stats=l.stats,l.load(d,u,{onSuccess:(e,s,r,i)=>{this.resetLoader(t,l);let n=e.data;r.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:t,part:null,payload:n,networkDetails:i})},onError:(e,r,i,n)=>{this.resetLoader(t,l),o(new LoadError({type:Dr.NETWORK_ERROR,details:Cr.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:br({url:s,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:i,stats:n}))},onAbort:(e,s,r)=>{this.resetLoader(t,l),o(new LoadError({type:Dr.NETWORK_ERROR,details:Cr.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:r,stats:e}))},onTimeout:(e,s,r)=>{this.resetLoader(t,l),o(new LoadError({type:Dr.NETWORK_ERROR,details:Cr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:r,stats:e}))},onProgress:(s,r,i,n)=>{e&&e({frag:t,part:null,payload:i,networkDetails:n})}})})}loadPart(t,e,s){this.abort();const r=this.config,i=r.fLoader,n=r.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(ca(t,e));const l=this.loader=t.loader=i?new i(r):new n(r),d=da(t,e),c=Gn(r.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:la};e.stats=l.stats,l.load(d,u,{onSuccess:(r,i,n,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const d={frag:t,part:e,payload:r.data,networkDetails:o};s(d),a(d)},onError:(s,r,i,n)=>{this.resetLoader(t,l),o(new LoadError({type:Dr.NETWORK_ERROR,details:Cr.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:br({url:d.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:i,stats:n}))},onAbort:(s,r,i)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new LoadError({type:Dr.NETWORK_ERROR,details:Cr.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:i,stats:s}))},onTimeout:(s,r,i)=>{this.resetLoader(t,l),o(new LoadError({type:Dr.NETWORK_ERROR,details:Cr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:i,stats:s}))}})})}updateStatsFromPart(t,e){const s=t.stats,r=e.stats,i=r.total;if(s.loaded+=r.loaded,i){const r=Math.round(t.duration/e.duration),n=Math.min(Math.round(s.loaded/i),r),a=(r-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=r.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function da(t,e=null){const s=e||t,r={frag:t,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},i=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(kr(i)&&kr(n)){var a;let e=i,s=n;if("initSegment"===t.sn&&"AES-128"===(null==(a=t.decryptdata)?void 0:a.method)){const t=n-i;t%16&&(s=n+(16-t%16)),0!==i&&(r.resetIV=!0,e=i-16)}r.rangeStart=e,r.rangeEnd=s}return r}function ca(t,e){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),r={type:Dr.MEDIA_ERROR,details:Cr.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return e&&(r.part=e),(e||t).stats.aborted=!0,new LoadError(r)}class LoadError extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class KeyLoader{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.abort()}}detach(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(t,e=Cr.KEY_LOAD_ERROR,s,r,i){return new LoadError({type:Dr.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:i,error:s,networkDetails:r})}loadClear(t,e){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:r}=t;for(let t=0;t<e.length;t++){const i=e[t];if(r<=i.cc&&("initSegment"===s||"initSegment"===i.sn||s<i.sn)){this.emeController.selectKeySystemFormat(i).then(t=>{i.setKeyFormat(t)});break}}}}load(t){return!t.decryptdata&&t.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(t).then(e=>this.loadInternal(t,e)):this.loadInternal(t)}loadInternal(t,e){var s,r;e&&t.setKeyFormat(e);const i=t.decryptdata;if(!i){const s=new Error(e?"Expected frag.decryptdata to be defined after setting format "+e:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,Cr.KEY_LOAD_ERROR,s))}const n=i.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,Cr.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(s=a)&&s.decryptdata.key)return i.key=a.decryptdata.key,Promise.resolve({frag:t,keyInfo:a});var o;if(null!=(r=a)&&r.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then(e=>(i.key=e.keyInfo.decryptdata.key,{frag:t,keyInfo:a}))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:i,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},i.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===i.keyFormat?this.loadKeyHTTP(a,t):this.loadKeyEME(a,t);case"AES-128":return this.loadKeyHTTP(a,t);default:return Promise.reject(this.createKeyLoadError(t,Cr.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(t,e){const s={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const e=this.emeController.loadKey(s);if(e)return(t.keyLoadPromise=e.then(e=>(t.mediaKeySessionContext=e,s))).catch(e=>{throw t.keyLoadPromise=null,e})}return Promise.resolve(s)}loadKeyHTTP(t,e){const s=this.config,r=new(0,s.loader)(s);return e.keyLoader=t.loader=r,t.keyLoadPromise=new Promise((i,n)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},o=s.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,e,s,r)=>{const{frag:a,keyInfo:o,url:l}=s;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,Cr.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,o.loader=null,i({frag:a,keyInfo:o})},onError:(t,s,r,i)=>{this.resetLoader(s),n(this.createKeyLoadError(e,Cr.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),r,br({url:a.url,data:void 0},t)))},onTimeout:(t,s,r)=>{this.resetLoader(s),n(this.createKeyLoadError(e,Cr.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(t,s,r)=>{this.resetLoader(s),n(this.createKeyLoadError(e,Cr.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(a,l,d)})}resetLoader(t){const{frag:e,keyInfo:s,url:r}=t,i=s.loader;e.keyLoader===i&&(e.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[r],i&&i.destroy()}}const ua={length:0,start:()=>0,end:()=>0};class BufferHelper{static isBuffered(t,e){try{if(t){const s=BufferHelper.getBuffered(t);for(let t=0;t<s.length;t++)if(e>=s.start(t)&&e<=s.end(t))return!0}}catch(t){}return!1}static bufferInfo(t,e,s){try{if(t){const r=BufferHelper.getBuffered(t),i=[];let n;for(n=0;n<r.length;n++)i.push({start:r.start(n),end:r.end(n)});return this.bufferedInfo(i,e,s)}}catch(t){}return{len:0,start:e,end:e,nextStart:void 0}}static bufferedInfo(t,e,s){e=Math.max(0,e),t.sort((function(t,e){const s=t.start-e.start;return s||e.end-t.end}));let r=[];if(s)for(let e=0;e<t.length;e++){const i=r.length;if(i){const n=r[i-1].end;t[e].start-n<s?t[e].end>n&&(r[i-1].end=t[e].end):r.push(t[e])}else r.push(t[e])}else r=t;let i,n=0,a=e,o=e;for(let t=0;t<r.length;t++){const l=r[t].start,d=r[t].end;if(e+s>=l&&e<d)a=l,o=d,n=o-e;else if(e+s<l){i=l;break}}return{len:n,start:a||0,end:o||0,nextStart:i}}static getBuffered(t){try{return t.buffered}catch(t){return Fr.log("failed to get media.buffered",t),ua}}}class ChunkMetadata{constructor(t,e,s,r=0,i=-1,n=!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=t,this.sn=e,this.id=s,this.size=r,this.part=i,this.partial=n}}function ha(t,e){let s=null;for(let r=0,i=t.length;r<i;r++){const i=t[r];if(i&&i.cc===e){s=i;break}}return s}function fa(t,e){if(t){const s=t.start+e;t.start=t.startPTS=s,t.endPTS=s+t.duration}}function ga(t,e){const s=e.fragments;for(let e=0,r=s.length;e<r;e++)fa(s[e],t);e.fragmentHint&&fa(e.fragmentHint,t),e.alignedSliding=!0}function pa(t,e,s){e&&(!function(t,e,s){if(function(t,e,s){return!(!e.details||!(s.endCC>s.startCC||t&&t.cc<s.startCC))}(t,s,e)){const t=function(t,e,s=0){const r=t.fragments,i=e.fragments;if(!i.length||!r.length)return void Fr.log("No fragments to align");const n=ha(r,i[0].cc);if(n&&(!n||n.startPTS))return n;Fr.log("No frag in previous level to align on")}(s.details,e);t&&kr(t.start)&&(Fr.log("Adjusting PTS using last level due to CC increase within current level "+e.url),ga(t.start,e))}}(t,s,e),!s.alignedSliding&&e.details&&function(t,e){if(!e.fragments.length||!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=e.fragments[0].programDateTime,r=t.fragments[0].programDateTime,i=(r-s)/1e3+e.fragments[0].start;i&&kr(i)&&(Fr.log(`Adjusting PTS using programDateTime delta ${r-s}ms, sliding:${i.toFixed(3)} ${t.url} `),ga(i,t))}(s,e.details),s.alignedSliding||!e.details||s.skippedSegments||On(e.details,s))}function ma(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=t.fragments,r=e.fragments;if(!s.length||!r.length)return;const i=r[Math.round(r.length/2)-1],n=ha(s,i.cc)||s[Math.round(s.length/2)-1],a=i.programDateTime,o=n.programDateTime;if(null===a||null===o)return;ga((o-a)/1e3-(n.start-i.start),t)}class AESCrypto{constructor(t,e){this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=e}decrypt(t,e){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t)}}class FastAESKey{constructor(t,e){this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=e}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class AESDecryptor{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_(t){const e=new DataView(t),s=new Uint32Array(4);for(let t=0;t<4;t++)s[t]=e.getUint32(4*t);return s}initTable(){const t=this.sBox,e=this.invSBox,s=this.subMix,r=s[0],i=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],d=o[1],c=o[2],u=o[3],h=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)h[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,t[f]=s,e[s]=f;const o=h[f],p=h[o],m=h[p];let y=257*h[s]^16843008*s;r[f]=y<<24|y>>>8,i[f]=y<<16|y>>>16,n[f]=y<<8|y>>>24,a[f]=y,y=16843009*m^65537*p^257*o^16843008*f,l[s]=y<<24|y>>>8,d[s]=y<<16|y>>>16,c[s]=y<<8|y>>>24,u[s]=y,f?(f=o^h[h[h[m^o]]],g^=h[h[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let s=!0,r=0;for(;r<e.length&&s;)s=e[r]===this.key[r],r++;if(s)return;this.key=e;const i=this.keySize=e.length;if(4!==i&&6!==i&&8!==i)throw new Error("Invalid aes key size="+i);const n=this.ksRows=4*(i+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),c=this.sBox,u=this.rcon,h=this.invSubMix,f=h[0],g=h[1],p=h[2],m=h[3];let y,v;for(a=0;a<n;a++)a<i?y=l[a]=e[a]:(v=y,a%i==0?(v=v<<8|v>>>24,v=c[v>>>24]<<24|c[v>>>16&255]<<16|c[v>>>8&255]<<8|c[255&v],v^=u[a/i|0]<<24):i>6&&a%i==4&&(v=c[v>>>24]<<24|c[v>>>16&255]<<16|c[v>>>8&255]<<8|c[255&v]),l[a]=y=(l[a-i]^v)>>>0);for(o=0;o<n;o++)a=n-o,v=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?v:f[c[v>>>24]]^g[c[v>>>16&255]]^p[c[v>>>8&255]]^m[c[255&v]],d[o]=d[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,s){const r=this.keySize+6,i=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],c=a[3],u=this.uint8ArrayToUint32Array_(s);let h=u[0],f=u[1],g=u[2],p=u[3];const m=new Int32Array(t),y=new Int32Array(m.length);let v,E,T,_,S,A,L,b,w,R,k,I,D,C;const P=this.networkToHostOrderSwap;for(;e<m.length;){for(w=P(m[e]),R=P(m[e+1]),k=P(m[e+2]),I=P(m[e+3]),S=w^i[0],A=I^i[1],L=k^i[2],b=R^i[3],D=4,C=1;C<r;C++)v=o[S>>>24]^l[A>>16&255]^d[L>>8&255]^c[255&b]^i[D],E=o[A>>>24]^l[L>>16&255]^d[b>>8&255]^c[255&S]^i[D+1],T=o[L>>>24]^l[b>>16&255]^d[S>>8&255]^c[255&A]^i[D+2],_=o[b>>>24]^l[S>>16&255]^d[A>>8&255]^c[255&L]^i[D+3],S=v,A=E,L=T,b=_,D+=4;v=n[S>>>24]<<24^n[A>>16&255]<<16^n[L>>8&255]<<8^n[255&b]^i[D],E=n[A>>>24]<<24^n[L>>16&255]<<16^n[b>>8&255]<<8^n[255&S]^i[D+1],T=n[L>>>24]<<24^n[b>>16&255]<<16^n[S>>8&255]<<8^n[255&A]^i[D+2],_=n[b>>>24]<<24^n[S>>16&255]<<16^n[A>>8&255]<<8^n[255&L]^i[D+3],y[e]=P(v^h),y[e+1]=P(_^f),y[e+2]=P(T^g),y[e+3]=P(E^p),h=w,f=R,g=k,p=I,e+=4}return y.buffer}}class Decrypter{constructor(t,{removePKCS7Padding:e=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}null===this.subtle&&(this.useSoftware=!0)}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const s=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,s=e&&new DataView(t.buffer).getUint8(e-1);return s?si(t,0,e-s):t}(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,s){return this.useSoftware?new Promise((r,i)=>{this.softwareDecrypt(new Uint8Array(t),e,s);const n=this.flush();n?r(n.buffer):i(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,s)}softwareDecrypt(t,e,s){const{currentIV:r,currentResult:i,remainderData:n}=this;this.logOnce("JS AES decrypt"),n&&(t=Oi(n,t),this.remainderData=null);const a=this.getValidChunk(t);if(!a.length)return null;r&&(s=r);let o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new AESDecryptor),o.expandKey(e);const l=i;return this.currentResult=o.decrypt(a.buffer,0,s),this.currentIV=si(a,-16).buffer,l||null}webCryptoDecrypt(t,e,s){const r=this.subtle;return this.key===e&&this.fastAesKey||(this.key=e,this.fastAesKey=new FastAESKey(r,e)),this.fastAesKey.expandKey().then(e=>{if(!r)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new AESCrypto(r,new Uint8Array(s)).decrypt(t.buffer,e)}).catch(r=>(Fr.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,s)))}onWebCryptoError(t,e,s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,s);const r=this.flush();if(r)return r.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(t){let e=t;const s=t.length-t.length%16;return s!==t.length&&(e=si(t,0,s),this.remainderData=si(t,s)),e}logOnce(t){this.logEnabled&&(Fr.log("[decrypter]: "+t),this.logEnabled=!1)}}const ya=function(t){let e="";const s=t.length;for(let r=0;r<s;r++)e+=`[${t.start(r).toFixed(3)}-${t.end(r).toFixed(3)}]`;return e},va="STOPPED",Ea="IDLE",Ta="KEY_LOADING",_a="FRAG_LOADING",Sa="FRAG_LOADING_WAITING_RETRY",Aa="WAITING_TRACK",La="PARSING",ba="PARSED",wa="ENDED",Ra="ERROR",ka="WAITING_INIT_PTS",Ia="WAITING_LEVEL";class BaseStreamController extends class TaskLoop{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!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(){}}{constructor(t,e,s,r,i){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=va,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=i,this.logPrefix=r,this.log=Fr.log.bind(Fr,r+":"),this.warn=Fr.warn.bind(Fr,r+":"),this.hls=t,this.fragmentLoader=new FragmentLoader(t.config),this.keyLoader=s,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Decrypter(t.config),t.on(Ir.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort();const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=va}_streamEnded(t,e){if(e.live||t.nextStart||!t.end||!this.media)return!1;const s=e.partList;if(null!=s&&s.length){const t=s[s.length-1];return BufferHelper.isBuffered(this.media,t.start+t.duration/2)}const r=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(r)}getLevelDetails(){var t;if(this.levels&&null!==this.levelLastLoaded)return null==(t=this.levels[this.levelLastLoaded])?void 0:t.details}onMediaAttached(t,e){const s=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),s.addEventListener("seeking",this.onvseeking),s.addEventListener("ended",this.onvended);const r=this.config;this.levels&&r.autoStartLoad&&this.state===va&&this.startLoad(r.startPosition)}onMediaDetaching(){const t=this.media;null!=t&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&this.onvseeking&&this.onvended&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:t,fragCurrent:e,media:s,mediaBuffer:r,state:i}=this,n=s?s.currentTime:0,a=BufferHelper.bufferInfo(r||s,n,t.maxBufferHole);if(this.log(`media seeking to ${kr(n)?n.toFixed(3):n}, state: ${i}`),this.state===wa)this.resetLoadingState();else if(e){const s=t.maxFragLookUpTolerance,r=e.start-s,i=e.start+e.duration+s;if(!a.len||i<a.start||r>a.end){const t=n>i;(n<r||t)&&(t&&e.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),e.abortRequests()),this.resetLoadingState())}}s&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0),this.lastCurrentTime=n),this.loadedmetadata||a.len||(this.nextLoadPosition=this.startPosition=n),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.stopLoad(),super.onHandlerDestroying()}onHandlerDestroyed(){this.state=va,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,s){this._loadFragForPlayback(t,e,s)}_loadFragForPlayback(t,e,s){this._doFragLoad(t,e,s,e=>{if(this.fragContextChanged(t))return this.warn(`Fragment ${t.sn}${e.part?" p: "+e.part.index:""} of level ${t.level} was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;const s=this.state;this.fragContextChanged(t)?(s===_a||!this.fragCurrent&&s===La)&&(this.fragmentTracker.removeFragment(t),this.state=Ea):("payload"in e&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(Ir.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))}).catch(e=>{this.state!==va&&this.state!==Ra&&(this.warn(e),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;if(this.fragmentTracker.getState(t)===ra){const e=t.type,s=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,s?s.len:this.config.maxBufferLength);this.reduceMaxBufferLength(r)&&this.fragmentTracker.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)&&this.fragmentTracker.removeAllFragments()}flushMainBuffer(t,e,s=null){if(!(t-e))return;const r={startOffset:t,endOffset:e,type:s};this.hls.trigger(Ir.BUFFER_FLUSHING,r)}_loadInitSegment(t,e){this._doFragLoad(t,e).then(e=>{if(!e||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e}).then(e=>{const{hls:s}=this,{payload:r}=e,i=t.decryptdata;if(r&&r.byteLength>0&&i&&i.key&&i.iv&&"AES-128"===i.method){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),i.key.buffer,i.iv.buffer).catch(e=>{throw s.trigger(Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(r=>{const i=self.performance.now();return s.trigger(Ir.FRAG_DECRYPTED,{frag:t,payload:r,stats:{tstart:n,tdecrypt:i}}),e.payload=r,e})}return e}).then(s=>{const{fragCurrent:r,hls:i,levels:n}=this;if(!n)throw new Error("init load aborted, missing levels");const a=t.stats;this.state=Ea,e.fragmentError=0,t.data=new Uint8Array(s.payload),a.parsing.start=a.buffering.start=self.performance.now(),a.parsing.end=a.buffering.end=self.performance.now(),s.frag===r&&i.trigger(Ir.FRAG_BUFFERED,{stats:a,frag:r,part:null,id:t.type}),this.tick()}).catch(e=>{this.state!==va&&this.state!==Ra&&(this.warn(e),this.resetFragmentLoading(t))})}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.level!==e.level||t.sn!==e.sn||t.urlId!==e.urlId}fragBufferedComplete(t,e){var s,r,i,n;const a=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${"[stream-controller]"===this.logPrefix?"level":"track"} ${t.level} (frag:[${(null!=(s=t.startPTS)?s:NaN).toFixed(3)}-${(null!=(r=t.endPTS)?r:NaN).toFixed(3)}] > buffer:${a?ya(BufferHelper.getBuffered(a)):"(detached)"})`),this.state=Ea,a&&(!this.loadedmetadata&&t.type==un&&a.buffered.length&&(null==(i=this.fragCurrent)?void 0:i.sn)===(null==(n=this.fragPrevious)?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:s,part:r,partsLoaded:i}=t,n=!i||0===i.length||i.some(t=>!t),a=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount+1,0,r?r.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,s=null,r){var i;const n=null==e?void 0:e.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!t.encrypted||null!=(i=t.decryptdata)&&i.key?!t.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(t,n.encryptedFragments):(this.log(`Loading key for ${t.sn} of [${n.startSN}-${n.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${t.level}`),this.state=Ta,this.fragCurrent=t,a=this.keyLoader.load(t).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(Ir.KEY_LOADED,t),this.state===Ta&&(this.state=Ea),t}),this.hls.trigger(Ir.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),s=Math.max(t.start,s||0),this.config.lowLatencyMode){const i=n.partList;if(i&&r){s>t.end&&n.fragmentHint&&(t=n.fragmentHint);const o=this.getNextPart(i,t,s);if(o>-1){const l=i[o];let d;return this.log(`Loading part sn: ${t.sn} p: ${l.index} cc: ${t.cc} of playlist [${n.startSN}-${n.endSN}] parts [0-${o}-${i.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=_a,d=a?a.then(s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(t,l,e,r)).catch(t=>this.handleFragLoadError(t)):this.doFragPartsLoad(t,l,e,r).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(Ir.FRAG_LOADING,{frag:t,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!t.url||this.loadedEndOfParts(i,s))return Promise.resolve(null)}}this.log(`Loading fragment ${t.sn} cc: ${t.cc} ${n?"of ["+n.startSN+"-"+n.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),kr(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=_a;const o=this.config.progressive;let l;return l=o&&a?a.then(e=>!e||this.fragContextChanged(null==e?void 0:e.frag)?null:this.fragmentLoader.load(t,r)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,o?r:void 0),a]).then(([t])=>(!o&&t&&r&&r(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(Ir.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(t,e,s,r){return new Promise((i,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,d=e=>{this.fragmentLoader.loadPart(t,e,r).then(r=>{o[e.index]=r;const n=r.part;this.hls.trigger(Ir.FRAG_LOADED,r);const a=xn(s,t.sn,e.index+1)||Fn(l,t.sn,e.index+1);if(!a)return i({frag:t,part:n,partsLoaded:o});d(a)}).catch(n)};d(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===Cr.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(Ir.ERROR,e)}else this.hls.trigger(Ir.ERROR,{type:Dr.OTHER_ERROR,details:Cr.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==La)return void(this.fragCurrent||this.state===va||this.state===Ra||(this.state=Ea));const{frag:s,part:r,level:i}=e,n=self.performance.now();s.stats.parsing.end=n,r&&(r.stats.parsing.end=n),this.updateLevelTiming(s,r,i,t.partial)}getCurrentContext(t){const{levels:e,fragCurrent:s}=this,{level:r,sn:i,part:n}=t;if(null==e||!e[r])return this.warn(`Levels object was unset while buffering fragment ${i} of level ${r}. The current chunk will not be buffered.`),null;const a=e[r],o=n>-1?xn(a,i,n):null,l=o?o.fragment:function(t,e,s){if(null==t||!t.details)return null;const r=t.details;let i=r.fragments[e-r.startSN];return i||(i=r.fragmentHint,i&&i.sn===e?i:e<r.startSN&&s&&s.sn===e?s:null)}(a,i,s);return l?(s&&s!==l&&(l.stats=s.stats),{frag:l,part:o,level:a}):null}bufferFragmentData(t,e,s,r){var i;if(!t||this.state!==La)return;const{data1:n,data2:a}=t;let o=n;if(n&&a&&(o=Oi(n,a)),null==(i=o)||!i.length)return;const l={type:t.type,frag:e,part:s,chunkMeta:r,parent:e.type,data:o};this.hls.trigger(Ir.BUFFER_APPENDING,l),t.dropped&&t.independent&&!s&&this.flushBufferGap(e)}flushBufferGap(t){const e=this.media;if(!e)return;if(!BufferHelper.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const s=e.currentTime,r=BufferHelper.bufferInfo(e,s,0),i=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*i),a=Math.max(Math.min(t.start-n,r.end-n),s+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){const s=this.getLoadPosition();return kr(s)?this.getFwdBufferInfoAtPos(t,s,e):null}getFwdBufferInfoAtPos(t,e,s){const{config:{maxBufferHole:r}}=this,i=BufferHelper.bufferInfo(t,e,r);if(0===i.len&&void 0!==i.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,s);if(n&&i.nextStart<n.end)return BufferHelper.bufferInfo(t,e,Math.max(i.nextStart,r))}return i}getMaxBufferLength(t){const{config:e}=this;let s;return s=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(s,e.maxMaxBufferLength)}reduceMaxBufferLength(t){const e=this.config,s=t||e.maxBufferLength;return e.maxMaxBufferLength>=s&&(e.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${e.maxMaxBufferLength}s`),!0)}getNextFragment(t,e){const s=e.fragments,r=s.length;if(!r)return null;const{config:i}=this,n=s[0].start;let a;if(e.live){const n=i.initialLiveManifestSize;if(r<n)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${n})`),null;e.PTSKnown||this.startFragRequested||-1!==this.startPosition||(a=this.getInitialLiveFragment(e,s),this.startPosition=a?this.hls.liveSyncPosition||a.start:t)}else t<=n&&(a=s[0]);if(!a){const s=i.lowLatencyMode?e.partEnd:e.fragmentEnd;a=this.getFragmentAtPosition(t,s,e)}return this.mapToInitFragWhenRequired(a)}isLoopLoading(t,e){const s=this.fragmentTracker.getState(t);return(s===na||s===ia&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,s,r,i){const n=t.gap,a=this.getNextFragment(this.nextLoadPosition,e);if(null===a)return a;if(t=a,n&&t&&!t.gap&&s.nextStart){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,r);if(null!==e&&s.len+e.len>=i)return this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${t.sn}`),null}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||null!=t&&t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,s){let r=-1,i=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,r>-1&&s<o.start)break;const l=o.loaded;l?r=-1:(i||o.independent||n)&&o.fragment===e&&(r=a),i=l}return r}loadedEndOfParts(t,e){const s=t[t.length-1];return s&&e>s.start&&s.loaded}getInitialLiveFragment(t,e){const s=this.fragPrevious;let r=null;if(s){if(t.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+s.programDateTime),r=function(t,e,s){if(null===e||!Array.isArray(t)||!t.length||!kr(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;s=s||0;for(let r=0;r<t.length;++r){const i=t[r];if(qn(e,s,i))return i}return null}(e,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const i=s.sn+1;if(i>=t.startSN&&i<=t.endSN){const n=e[i-t.startSN];s.cc===n.cc&&(r=n,this.log("Live playlist, switching playlist, load frag with next SN: "+r.sn))}r||(r=function(t,e){return Hn(t,t=>t.cc<e?1:t.cc>e?-1:0)}(e,s.cc),r&&this.log("Live playlist, switching playlist, load frag with same CC: "+r.sn))}}else{const e=this.hls.liveSyncPosition;null!==e&&(r=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return r}getFragmentAtPosition(t,e,s){const{config:r}=this;let{fragPrevious:i}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,l=r.maxFragLookUpTolerance,d=!!(r.lowLatencyMode&&s.partList&&o);let c;if(d&&o&&!this.bitrateTest&&(n=n.concat(o),a=o.sn),t<e){c=Kn(i,n,t,t>e-l?0:l)}else c=n[n.length-1];if(c){const t=c.sn-s.startSN,e=this.fragmentTracker.getState(c);if((e===na||e===ia&&c.gap)&&(i=c),i&&c.sn===i.sn&&!d){if(i&&c.level===i.level){const e=n[t+1];c=c.sn<a&&this.fragmentTracker.getState(e)!==na?e:null}}}return c}synchronizeToLiveEdge(t){const{config:e,media:s}=this;if(!s)return;const r=this.hls.liveSyncPosition,i=s.currentTime,n=t.fragments[0].start,a=t.edge,o=i>=n-e.maxFragLookUpTolerance&&i<=a;if(null!==r&&s.duration>r&&(i<r||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;(!o&&s.readyState<4||i<a-n)&&(this.loadedmetadata||(this.nextLoadPosition=r),s.readyState&&(this.warn(`Playback: ${i.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${r.toFixed(3)}`),s.currentTime=r))}}alignPlaylists(t,e){const{levels:s,levelLastLoaded:r,fragPrevious:i}=this,n=null!==r?s[r]:null,a=t.fragments.length;if(!a)return this.warn("No fragments in live playlist"),0;const o=t.fragments[0].start,l=!e,d=t.alignedSliding&&kr(o);if(l||!d&&!o){pa(i,n,t);const s=t.fragments[0].start;return this.log(`Live playlist sliding: ${s.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} prev-sn: ${i?i.sn:"na"} fragments: ${a}`),s}return o}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let s=this.startPosition;if(s<e&&(s=-1),-1===s||-1===this.lastCurrentTime){const r=null!==this.startTimeOffset,i=r?this.startTimeOffset:t.startTimeOffset;null!==i&&kr(i)?(s=e+i,i<0&&(s+=t.totalduration),s=Math.min(Math.max(e,s),e+t.totalduration),this.log(`Start time offset ${i} found in ${r?"multivariant":"media"} playlist, adjust startPosition to ${s}`),this.startPosition=s):t.live?s=this.hls.liveSyncPosition||e:this.startPosition=s=0,this.lastCurrentTime=s}this.nextLoadPosition=s}getLoadPosition(){const{media:t}=this;let e=0;return this.loadedmetadata&&t?e=t.currentTime:this.nextLoadPosition&&(e=this.nextLoadPosition),e}handleFragLoadAborted(t,e){this.transmuxer&&"initSegment"!==t.sn&&t.stats.aborted&&(this.warn(`Fragment ${t.sn}${e?" part"+e.index:""} of level ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===Sa)||(this.state=Ea)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const s=e.frag;if(!s||s.type!==t||!this.levels)return;var r;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const i=e.details===Cr.FRAG_GAP;i&&this.fragmentTracker.fragBuffered(s,!0);const n=e.errorAction,{action:a,retryCount:o=0,retryConfig:l}=n||{};if(n&&a===Yn&&l){this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition);const r=Bn(l,o);this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${r}ms`),n.resolved=!0,this.retryDate=self.performance.now()+r,this.state=Sa}else l&&n?(this.resetFragmentErrors(t),o<l.maxNumRetry?i||(n.resolved=!0):Fr.warn(`${e.details} reached or exceeded max retry (${o})`)):this.state=Ra;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===La||this.state===ba){const e=t.parent,s=this.getFwdBufferInfo(this.mediaBuffer,e),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len);const i=!r;return i&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${e} buffer`),t.frag&&(this.fragmentTracker.removeFragment(t.frag),this.nextLoadPosition=t.frag.start),this.resetLoadingState(),i}return!1}resetFragmentErrors(t){t===hn&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==va&&(this.state=Ea)}afterBufferFlushed(t,e,s){if(!t)return;const r=BufferHelper.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,r,s),this.state===wa&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=Ea}resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=!1;const e=this.levels?this.levels[t].details:null;null!=e&&e.live?(this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.warn(`The loading context changed while buffering fragment ${t.sn} of level ${t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(t.level),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,s,r){var i;const n=s.details;if(!n)return void this.warn("level.details undefined");if(Object.keys(t.elementaryStreams).reduce((e,i)=>{const a=t.elementaryStreams[i];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${i} duration reliably (${o})`),e||!1;const l=r?0:Cn(n,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(Ir.LEVEL_PTS_UPDATED,{details:n,level:s,drift:l,type:i,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e},!1))s.fragmentError=0;else if(null===(null==(i=this.transmuxer)?void 0:i.error)){const e=new Error(`Found no media in fragment ${t.sn} of level ${s.id} resetting transmuxer to fallback to playlist timing`);if(this.warn(e.message),this.hls.trigger(Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of level "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=ba,this.hls.trigger(Ir.FRAG_PARSED,{frag:t,part:e})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.resetTransmuxer(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}function Da(){if("undefined"!=typeof self)return self.MediaSource||self.WebKitMediaSource}function Ca(){return self.SourceBuffer||self.WebKitSourceBuffer}function Pa(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class BaseAudioDemuxer{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,e,s,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,s){}demux(t,e){this.cachedData&&(t=Oi(this.cachedData,t),this.cachedData=null);let s,r=ni(t,0),i=r?r.length:0;const n=this._audioTrack,a=this._id3Track,o=r?(t=>{const e=ci(t);for(let t=0;t<e.length;t++){const s=e[t];if(li(s))return pi(s)}})(r):void 0,l=t.length;for((null===this.basePTS||0===this.frameIndex&&kr(o))&&(this.basePTS=Oa(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Tn,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(t,i)){const e=this.appendFrame(n,t,i);e?(this.frameIndex++,this.lastPTS=e.sample.pts,i+=e.length,s=i):i=l}else oi(t,i)?(r=ni(t,i),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Tn,duration:Number.POSITIVE_INFINITY}),i+=r.length,s=i):i++;if(i===l&&s!==l){const e=si(t,s);this.cachedData?this.cachedData=Oi(this.cachedData,e):this.cachedData=e}}return{audioTrack:n,videoTrack:Pa(),id3Track:a,textTrack:Pa()}}demuxSampleAes(t,e,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:Pa(),id3Track:this._id3Track,textTrack:Pa()}}destroy(){}}const Oa=(t,e,s)=>{if(kr(t))return 90*t;return 9e4*e+(s?9e4*s.baseTime/s.timescale:0)};function Ma(t,e){return 255===t[e]&&240==(246&t[e+1])}function xa(t,e){return 1&t[e+1]?7:9}function Fa(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Na(t,e){return e+1<t.length&&Ma(t,e)}function Ua(t,e){if(Na(t,e)){const s=xa(t,e);if(e+s>=t.length)return!1;const r=Fa(t,e);if(r<=s)return!1;const i=e+r;return i===t.length||Na(t,i)}return!1}function Ba(t,e,s,r,i){if(!t.samplerate){const n=function(t,e,s,r){let i,n,a,o;const l=navigator.userAgent.toLowerCase(),d=r,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];i=1+((192&e[s+2])>>>6);const u=(60&e[s+2])>>>2;if(!(u>c.length-1))return a=(1&e[s+2])<<2,a|=(192&e[s+3])>>>6,Fr.log(`manifest codec:${r}, ADTS type:${i}, samplingIndex:${u}`),/firefox/i.test(l)?u>=6?(i=5,o=new Array(4),n=u-3):(i=2,o=new Array(2),n=u):-1!==l.indexOf("android")?(i=2,o=new Array(2),n=u):(i=5,o=new Array(4),r&&(-1!==r.indexOf("mp4a.40.29")||-1!==r.indexOf("mp4a.40.5"))||!r&&u>=6?n=u-3:((r&&-1!==r.indexOf("mp4a.40.2")&&(u>=6&&1===a||/vivaldi/i.test(l))||!r&&1===a)&&(i=2,o=new Array(2)),n=u)),o[0]=i<<3,o[0]|=(14&u)>>1,o[1]|=(1&u)<<7,o[1]|=a<<3,5===i&&(o[1]|=(14&n)>>1,o[2]=(1&n)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:c[u],channelCount:a,codec:"mp4a.40."+i,manifestCodec:d};t.trigger(Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+u})}(e,s,r,i);if(!n)return;t.config=n.config,t.samplerate=n.samplerate,t.channelCount=n.channelCount,t.codec=n.codec,t.manifestCodec=n.manifestCodec,Fr.log(`parsed codec:${t.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function Ga(t){return 9216e4/t}function $a(t,e,s,r,i){const n=r+i*Ga(t.samplerate),a=function(t,e){const s=xa(t,e);if(e+s<=t.length){const r=Fa(t,e)-s;if(r>0)return{headerLength:s,frameLength:r}}}(e,s);let o;if(a){const{frameLength:r,headerLength:i}=a,l=i+r,d=Math.max(0,s+l-e.length);d?(o=new Uint8Array(l-i),o.set(e.subarray(s+i,e.length),0)):o=e.subarray(s+i,s+l);const c={unit:o,pts:n};return d||t.samples.push(c),{sample:c,length:l,missing:d}}const l=e.length-s;o=new Uint8Array(l),o.set(e.subarray(s,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}const Ha=/\/emsg[-/]ID3/i;let Ka=null;const Va=[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],qa=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ja=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Wa=[0,1,1,4];function Ya(t,e,s,r,i){if(s+24>e.length)return;const n=za(e,s);if(n&&s+n.frameLength<=e.length){const a=r+i*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(s,s+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function za(t,e){const s=t[e+1]>>3&3,r=t[e+1]>>1&3,i=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==s&&0!==i&&15!==i&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*Va[14*(3===s?3-r:3===r?3:4)+i-1],d=qa[3*(3===s?0:2===s?1:2)+n],c=3===o?1:2,u=ja[s][r],h=Wa[r],f=8*u*h,g=Math.floor(u*l/d+a)*h;if(null===Ka){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ka=t?parseInt(t[1]):0}return!!Ka&&Ka<=87&&2===r&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:d,channelCount:c,frameLength:g,samplesPerFrame:f}}}function Xa(t,e){return 255===t[e]&&224==(224&t[e+1])&&0!=(6&t[e+1])}function Qa(t,e){return e+1<t.length&&Xa(t,e)}function Za(t,e){if(e+1<t.length&&Xa(t,e)){const s=4,r=za(t,e);let i=s;null!=r&&r.frameLength&&(i=r.frameLength);const n=e+i;return n===t.length||Qa(t,n)}return!1}class ExpGolomb{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,s=t.byteLength-e,r=new Uint8Array(4),i=Math.min(4,e);if(0===i)throw new Error("no bytes available");r.set(t.subarray(s,s+i)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*i,this.bytesAvailable-=i}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const s=this.word>>>32-e;if(t>32&&Fr.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?s<<e|this.readBits(e):s}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(0!=(this.word&2147483648>>>t))return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(t){let e,s=8,r=8;for(let i=0;i<t;i++)0!==r&&(e=this.readEG(),r=(s+e+256)%256),s=0===r?s:r}readSPS(){let t,e,s,r=0,i=0,n=0,a=0;const o=this.readUByte.bind(this),l=this.readBits.bind(this),d=this.readUEG.bind(this),c=this.readBoolean.bind(this),u=this.skipBits.bind(this),h=this.skipEG.bind(this),f=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);o();const p=o();if(l(5),u(3),o(),f(),100===p||110===p||122===p||244===p||44===p||83===p||86===p||118===p||128===p){const t=d();if(3===t&&u(1),f(),f(),u(1),c())for(e=3!==t?8:12,s=0;s<e;s++)c()&&g(s<6?16:64)}f();const m=d();if(0===m)d();else if(1===m)for(u(1),h(),h(),t=d(),s=0;s<t;s++)h();f(),u(1);const y=d(),v=d(),E=l(1);0===E&&u(1),u(1),c()&&(r=d(),i=d(),n=d(),a=d());let T=[1,1];if(c()&&c()){switch(o()){case 1:T=[1,1];break;case 2:T=[12,11];break;case 3:T=[10,11];break;case 4:T=[16,11];break;case 5:T=[40,33];break;case 6:T=[24,11];break;case 7:T=[20,11];break;case 8:T=[32,11];break;case 9:T=[80,33];break;case 10:T=[18,11];break;case 11:T=[15,11];break;case 12:T=[64,33];break;case 13:T=[160,99];break;case 14:T=[4,3];break;case 15:T=[3,2];break;case 16:T=[2,1];break;case 255:T=[o()<<8|o(),o()<<8|o()]}}return{width:Math.ceil(16*(y+1)-2*r-2*i),height:(2-E)*(v+1)*16-(E?2:4)*(n+a),pixelRatio:T}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class SampleAesDecrypter{constructor(t,e,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Decrypter(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(t,e,s){const r=t[e].unit;if(r.length<=16)return;const i=r.subarray(16,r.length-r.length%16),n=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(n).then(i=>{const n=new Uint8Array(i);r.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,s)})}decryptAacSamples(t,e,s){for(;;e++){if(e>=t.length)return void s();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,s=new Int8Array(e);let r=0;for(let e=32;e<t.length-16;e+=160,r+=16)s.set(t.subarray(e,e+16),r);return s}getAvcDecryptedUnit(t,e){const s=new Uint8Array(e);let r=0;for(let e=32;e<t.length-16;e+=160,r+=16)t.set(s.subarray(r,r+16),e);return t}decryptAvcSample(t,e,s,r,i){const n=Ni(i.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{i.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,s+1,r)})}decryptAvcSamples(t,e,s,r){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,s=0){if(e>=t.length)return void r();const i=t[e].units;for(;!(s>=i.length);s++){const n=i[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,s,r,n),this.decrypter.isSync())))return}}}}class TSDemuxer{constructor(t,e,s){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=t,this.config=e,this.typeSupported=s}static probe(t){const e=TSDemuxer.syncOffset(t);return e>0&&Fr.warn("MPEG2-TS detected but first sync word found @ offset "+e),-1!==e}static syncOffset(t){const e=t.length,s=Math.min(940,t.length-188)+1;let r=0;for(;r<s;){let i=!1;for(let n=r;n<e&&71===t[n];n+=188)if(i||0!==to(t,n)||(i=!0),i&&n+188>s)return r;r++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:Si[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,s,r){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=TSDemuxer.createTrack("video"),this._audioTrack=TSDemuxer.createTrack("audio",r),this._id3Track=TSDemuxer.createTrack("id3"),this._txtTrack=TSDemuxer.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=s,this._duration=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_avcTrack:e,_id3Track:s}=this;t&&(t.pesData=null),e&&(e.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}demux(t,e,s=!1,r=!1){let i;s||(this.sampleAes=null);const n=this._avcTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let d=n.pid,c=n.pesData,u=a.pid,h=o.pid,f=a.pesData,g=o.pesData,p=null,m=this.pmtParsed,y=this._pmtId,v=t.length;if(this.remainderData&&(v=(t=Oi(this.remainderData,t)).length,this.remainderData=null),v<188&&!r)return this.remainderData=t,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const E=Math.max(0,TSDemuxer.syncOffset(t));v-=(v-E)%188,v<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,v,t.buffer.byteLength-v));let T=0;for(let e=E;e<v;e+=188)if(71===t[e]){const r=!!(64&t[e+1]),v=to(t,e);let T;if((48&t[e+3])>>4>1){if(T=e+5+t[e+4],T===e+188)continue}else T=e+4;switch(v){case d:r&&(c&&(i=ro(c))&&this.parseAVCPES(n,l,i,!1),c={data:[],size:0}),c&&(c.data.push(t.subarray(T,e+188)),c.size+=e+188-T);break;case u:if(r){if(f&&(i=ro(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,i);break;case"mp3":this.parseMPEGPES(a,i)}f={data:[],size:0}}f&&(f.data.push(t.subarray(T,e+188)),f.size+=e+188-T);break;case h:r&&(g&&(i=ro(g))&&this.parseID3PES(o,i),g={data:[],size:0}),g&&(g.data.push(t.subarray(T,e+188)),g.size+=e+188-T);break;case 0:r&&(T+=t[T]+1),y=this._pmtId=eo(t,T);break;case y:{r&&(T+=t[T]+1);const i=so(t,T,this.typeSupported,s);d=i.avc,d>0&&(n.pid=d),u=i.audio,u>0&&(a.pid=u,a.segmentCodec=i.segmentCodec),h=i.id3,h>0&&(o.pid=h),null===p||m||(Fr.warn(`MPEG-TS PMT found at ${e} after unknown PID '${p}'. Backtracking to sync byte @${E} to parse all TS packets.`),p=null,e=E-188),m=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=v}}else T++;if(T>0){const t=new Error(`Found ${T} TS packet/s that do not start with 0x47`);this.observer.emit(Ir.ERROR,Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message})}n.pesData=c,a.pesData=f,o.pesData=g;const _={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return r&&this.extractRemainingSamples(_),_}flush(){const{remainderData:t}=this;let e;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._avcTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:s,id3Track:r,textTrack:i}=t,n=s.pesData,a=e.pesData,o=r.pesData;let l;if(n&&(l=ro(n))?(this.parseAVCPES(s,i,l,!0),s.pesData=null):s.pesData=n,a&&(l=ro(a))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l)}e.pesData=null}else null!=a&&a.size&&Fr.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=ro(o))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=o}demuxSampleAes(t,e,s){const r=this.demux(t,s,!0,!this.config.progressive),i=this.sampleAes=new SampleAesDecrypter(this.observer,this.config,e);return this.decrypt(r,i)}decrypt(t,e){return new Promise(s=>{const{audioTrack:r,videoTrack:i}=t;r.samples&&"aac"===r.segmentCodec?e.decryptAacSamples(r.samples,0,()=>{i.samples?e.decryptAvcSamples(i.samples,0,0,()=>{s(t)}):s(t)}):i.samples&&e.decryptAvcSamples(i.samples,0,0,()=>{s(t)})})}destroy(){this._duration=0}parseAVCPES(t,e,s,r){const i=this.parseAVCNALu(t,s.data);let n,a=this.avcSample,o=!1;s.data=null,a&&i.length&&!t.audFound&&(io(a,t),a=this.avcSample=Ja(!1,s.pts,s.dts,"")),i.forEach(r=>{switch(r.type){case 1:{n=!0,a||(a=this.avcSample=Ja(!0,s.pts,s.dts,"")),a.frame=!0;const t=r.data;if(o&&t.length>4){const e=new ExpGolomb(t).readSliceType();2!==e&&4!==e&&7!==e&&9!==e||(a.key=!0)}break}case 5:n=!0,a||(a=this.avcSample=Ja(!0,s.pts,s.dts,"")),a.key=!0,a.frame=!0;break;case 6:n=!0,Fi(r.data,1,s.pts,e.samples);break;case 7:if(n=!0,o=!0,!t.sps){const e=r.data,s=new ExpGolomb(e).readSPS();t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[e],t.duration=this._duration;const i=e.subarray(1,4);let n="avc1.";for(let t=0;t<3;t++){let e=i[t].toString(16);e.length<2&&(e="0"+e),n+=e}t.codec=n}break;case 8:n=!0,t.pps||(t.pps=[r.data]);break;case 9:n=!1,t.audFound=!0,a&&io(a,t),a=this.avcSample=Ja(!1,s.pts,s.dts,"");break;case 12:n=!0;break;default:n=!1,a&&(a.debug+="unknown NAL "+r.type+" ")}if(a&&n){a.units.push(r)}}),r&&a&&(io(a,t),this.avcSample=null)}getLastNalUnit(t){var e;let s,r=this.avcSample;if(r&&0!==r.units.length||(r=t[t.length-1]),null!=(e=r)&&e.units){const t=r.units;s=t[t.length-1]}return s}parseAVCNALu(t,e){const s=e.byteLength;let r=t.naluState||0;const i=r,n=[];let a,o,l,d=0,c=-1,u=0;for(-1===r&&(c=0,u=31&e[0],r=0,d=1);d<s;)if(a=e[d++],r)if(1!==r)if(a)if(1===a){if(c>=0){const t={data:e.subarray(c,d-r-1),type:u};n.push(t)}else{const s=this.getLastNalUnit(t.samples);if(s&&(i&&d<=4-i&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-i)),o=d-r-1,o>0)){const t=new Uint8Array(s.data.byteLength+o);t.set(s.data,0),t.set(e.subarray(0,o),s.data.byteLength),s.data=t,s.state=0}}d<s?(l=31&e[d],c=d,u=l,r=0):r=-1}else r=0;else r=3;else r=a?0:2;else r=a?0:1;if(c>=0&&r>=0){const t={data:e.subarray(c,s),type:u,state:r};n.push(t)}if(0===n.length){const s=this.getLastNalUnit(t.samples);if(s){const t=new Uint8Array(s.data.byteLength+e.byteLength);t.set(s.data,0),t.set(e,s.data.byteLength),s.data=t}}return t.naluState=r,n}parseAACPES(t,e){let s=0;const r=this.aacOverFlow;let i,n,a,o=e.data;if(r){this.aacOverFlow=null;const e=r.missing,i=r.sample.unit.byteLength;if(-1===e){const t=new Uint8Array(i+o.byteLength);t.set(r.sample.unit,0),t.set(o,i),o=t}else{const n=i-e;r.sample.unit.set(o.subarray(0,e),n),t.samples.push(r.sample),s=r.missing}}for(i=s,n=o.length;i<n-1&&!Na(o,i);i++);if(i!==s){let t;const e=i<n-1;t=e?"AAC PES did not start with ADTS header,offset:"+i:"No ADTS header found in AAC PES";const s=new Error(t);if(Fr.warn("parsing error: "+t),this.observer.emit(Ir.ERROR,Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.FRAG_PARSING_ERROR,fatal:!1,levelRetry:e,error:s,reason:t}),!e)return}if(Ba(t,this.observer,o,i,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!r)return void Fr.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Ga(t.samplerate);a=r.sample.pts+e}}let l,d=0;for(;i<n;){if(l=$a(t,o,i,a,d),i+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;i<n-1&&!Na(o,i);i++);}}parseMPEGPES(t,e){const s=e.data,r=s.length;let i=0,n=0;const a=e.pts;if(void 0!==a)for(;n<r;)if(Qa(s,n)){const e=Ya(t,s,n,a,i);if(!e)break;n+=e.length,i++}else n++;else Fr.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseID3PES(t,e){if(void 0===e.pts)return void Fr.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=Rr({},e,{type:this._avcTrack?Sn:Tn,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}}function Ja(t,e,s,r){return{key:t,frame:!1,pts:e,dts:s,units:[],debug:r,length:0}}function to(t,e){return((31&t[e+1])<<8)+t[e+2]}function eo(t,e){return(31&t[e+10])<<8|t[e+11]}function so(t,e,s,r){const i={audio:-1,avc:-1,id3:-1,segmentCodec:"aac"},n=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<n;){const n=to(t,e);switch(t[e]){case 207:if(!r){Fr.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:-1===i.audio&&(i.audio=n);break;case 21:-1===i.id3&&(i.id3=n);break;case 219:if(!r){Fr.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:-1===i.avc&&(i.avc=n);break;case 3:case 4:!0!==s.mpeg&&!0!==s.mp3?Fr.log("MPEG audio found, not supported in this browser"):-1===i.audio&&(i.audio=n,i.segmentCodec="mp3");break;case 36:Fr.warn("Unsupported HEVC stream type found")}e+=5+((15&t[e+3])<<8|t[e+4])}return i}function ro(t){let e,s,r,i,n,a=0;const o=t.data;if(!t||0===t.size)return null;for(;o[0].length<19&&o.length>1;){const t=new Uint8Array(o[0].length+o[1].length);t.set(o[0]),t.set(o[1],o[0].length),o[0]=t,o.splice(1,1)}e=o[0];if(1===(e[0]<<16)+(e[1]<<8)+e[2]){if(s=(e[4]<<8)+e[5],s&&s>t.size-6)return null;const l=e[7];192&l&&(i=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&l?(n=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2,i-n>54e5&&(Fr.warn(Math.round((i-n)/9e4)+"s delta between PTS and DTS, align them"),i=n)):n=i),r=e[8];let d=r+9;if(t.size<=d)return null;t.size-=d;const c=new Uint8Array(t.size);for(let t=0,s=o.length;t<s;t++){e=o[t];let s=e.byteLength;if(d){if(d>s){d-=s;continue}e=e.subarray(d),s-=d,d=0}c.set(e,a),a+=s}return s&&(s-=r+3),{data:c,pts:i,dts:n,len:s}}return null}function io(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const s=e.samples,r=s.length;if(!r)return void e.dropped++;{const e=s[r-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}t.debug.length&&Fr.log(t.pts+"/"+t.dts+":"+t.debug)}class AAC{static getSilentFrame(t,e){switch(t){case"mp4a.40.2":if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)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===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(1===e)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===e)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===e)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 no=Math.pow(2,32)-1;class MP4{static init(){let t;for(t in MP4.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},MP4.types)MP4.types.hasOwnProperty(t)&&(MP4.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);MP4.HDLR_TYPES={video:e,audio:s};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),i=new Uint8Array([0,0,0,0,0,0,0,0]);MP4.STTS=MP4.STSC=MP4.STCO=i,MP4.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),MP4.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),MP4.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),MP4.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);MP4.FTYP=MP4.box(MP4.types.ftyp,n,o,n,a),MP4.DINF=MP4.box(MP4.types.dinf,MP4.box(MP4.types.dref,r))}static box(t,...e){let s=8,r=e.length;const i=r;for(;r--;)s+=e[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(t,4),r=0,s=8;r<i;r++)n.set(e[r],s),s+=e[r].byteLength;return n}static hdlr(t){return MP4.box(MP4.types.hdlr,MP4.HDLR_TYPES[t])}static mdat(t){return MP4.box(MP4.types.mdat,t)}static mdhd(t,e){e*=t;const s=Math.floor(e/(no+1)),r=Math.floor(e%(no+1));return MP4.box(MP4.types.mdhd,new Uint8Array([1,0,0,0,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,s>>24,s>>16&255,s>>8&255,255&s,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(t){return MP4.box(MP4.types.mdia,MP4.mdhd(t.timescale,t.duration),MP4.hdlr(t.type),MP4.minf(t))}static mfhd(t){return MP4.box(MP4.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?MP4.box(MP4.types.minf,MP4.box(MP4.types.smhd,MP4.SMHD),MP4.DINF,MP4.stbl(t)):MP4.box(MP4.types.minf,MP4.box(MP4.types.vmhd,MP4.VMHD),MP4.DINF,MP4.stbl(t))}static moof(t,e,s){return MP4.box(MP4.types.moof,MP4.mfhd(t),MP4.traf(s,e))}static moov(t){let e=t.length;const s=[];for(;e--;)s[e]=MP4.trak(t[e]);return MP4.box.apply(null,[MP4.types.moov,MP4.mvhd(t[0].timescale,t[0].duration)].concat(s).concat(MP4.mvex(t)))}static mvex(t){let e=t.length;const s=[];for(;e--;)s[e]=MP4.trex(t[e]);return MP4.box.apply(null,[MP4.types.mvex,...s])}static mvhd(t,e){e*=t;const s=Math.floor(e/(no+1)),r=Math.floor(e%(no+1)),i=new Uint8Array([1,0,0,0,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,s>>24,s>>16&255,s>>8&255,255&s,r>>24,r>>16&255,r>>8&255,255&r,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 MP4.box(MP4.types.mvhd,i)}static sdtp(t){const e=t.samples||[],s=new Uint8Array(4+e.length);let r,i;for(r=0;r<e.length;r++)i=e[r].flags,s[r+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return MP4.box(MP4.types.sdtp,s)}static stbl(t){return MP4.box(MP4.types.stbl,MP4.stsd(t),MP4.box(MP4.types.stts,MP4.STTS),MP4.box(MP4.types.stsc,MP4.STSC),MP4.box(MP4.types.stsz,MP4.STSZ),MP4.box(MP4.types.stco,MP4.STCO))}static avc1(t){let e,s,r,i=[],n=[];for(e=0;e<t.sps.length;e++)s=t.sps[e],r=s.byteLength,i.push(r>>>8&255),i.push(255&r),i=i.concat(Array.prototype.slice.call(s));for(e=0;e<t.pps.length;e++)s=t.pps[e],r=s.byteLength,n.push(r>>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(s));const a=MP4.box(MP4.types.avcC,new Uint8Array([1,i[3],i[4],i[5],255,224|t.sps.length].concat(i).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,d=t.pixelRatio[0],c=t.pixelRatio[1];return MP4.box(MP4.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,o>>8&255,255&o,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]),a,MP4.box(MP4.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),MP4.box(MP4.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(t){const e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))}static mp4a(t){const e=t.samplerate;return MP4.box(MP4.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,255&e,0,0]),MP4.box(MP4.types.esds,MP4.esds(t)))}static mp3(t){const e=t.samplerate;return MP4.box(MP4.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,255&e,0,0]))}static stsd(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp3(t)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp4a(t)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.avc1(t))}static tkhd(t){const e=t.id,s=t.duration*t.timescale,r=t.width,i=t.height,n=Math.floor(s/(no+1)),a=Math.floor(s%(no+1));return MP4.box(MP4.types.tkhd,new Uint8Array([1,0,0,7,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,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,255&r,0,0,i>>8&255,255&i,0,0]))}static traf(t,e){const s=MP4.sdtp(t),r=t.id,i=Math.floor(e/(no+1)),n=Math.floor(e%(no+1));return MP4.box(MP4.types.traf,MP4.box(MP4.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),MP4.box(MP4.types.tfdt,new Uint8Array([1,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n])),MP4.trun(t,s.length+16+20+8+16+8+8),s)}static trak(t){return t.duration=t.duration||4294967295,MP4.box(MP4.types.trak,MP4.tkhd(t),MP4.mdia(t))}static trex(t){const e=t.id;return MP4.box(MP4.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const s=t.samples||[],r=s.length,i=12+16*r,n=new Uint8Array(i);let a,o,l,d,c,u;for(e+=8+i,n.set(["video"===t.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<r;a++)o=s[a],l=o.duration,d=o.size,c=o.flags,u=o.cts,n.set([l>>>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,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return MP4.box(MP4.types.trun,n)}static initSegment(t){MP4.types||MP4.init();const e=MP4.moov(t),s=new Uint8Array(MP4.FTYP.byteLength+e.byteLength);return s.set(MP4.FTYP),s.set(e,MP4.FTYP.byteLength),s}}MP4.types=void 0,MP4.HDLR_TYPES=void 0,MP4.STTS=void 0,MP4.STSC=void 0,MP4.STCO=void 0,MP4.STSZ=void 0,MP4.VMHD=void 0,MP4.SMHD=void 0,MP4.STSD=void 0,MP4.FTYP=void 0,MP4.DINF=void 0;function ao(t,e,s=1,r=!1){const i=t*e*s;return r?Math.round(i):i}function oo(t,e=!1){return ao(t,1e3,1/9e4,e)}let lo,co=null,uo=null;class MP4Remuxer{constructor(t,e,s,r=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=t,this.config=e,this.typeSupported=s,this.ISGenerated=!1,null===co){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);co=t?parseInt(t[1]):0}if(null===uo){const t=navigator.userAgent.match(/Safari\/(\d+)/i);uo=t?parseInt(t[1]):0}}destroy(){}resetTimeStamp(t){Fr.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){Fr.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){Fr.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1}getVideoStartPts(t){let e=!1;const s=t.reduce((t,s)=>{const r=s.pts-t;return r<-4294967296?(e=!0,ho(t,s.pts)):r>0?t:s.pts},t[0].pts);return e&&Fr.debug("PTS rollover detected"),s}remux(t,e,s,r,i,n,a,o){let l,d,c,u,h,f,g=i,p=i;const m=t.pid>-1,y=e.pid>-1,v=e.samples.length,E=t.samples.length>0,T=a&&v>0||v>1;if((!m||E)&&(!y||T)||this.ISGenerated||a){this.ISGenerated||(c=this.generateIS(t,e,i,n));const s=this.isVideoContiguous;let r,a=-1;if(T&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){Fr.warn(`[mp4-remuxer]: Dropped ${a} out of ${v} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,p+=(e.samples[0].pts-t)/e.inputTimeScale,r=p}else-1===a&&(Fr.warn(`[mp4-remuxer]: No keyframe found out of ${v} video samples`),f=!1);if(this.ISGenerated){if(E&&T){const s=this.getVideoStartPts(e.samples),r=(ho(t.samples[0].pts,s)-s)/e.inputTimeScale;g+=Math.max(0,r),p+=Math.max(0,-r)}if(E){if(t.samplerate||(Fr.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(t,e,i,n)),d=this.remuxAudio(t,g,this.isAudioContiguous,n,y||T||o===hn?p:void 0),T){const r=d?d.endPTS-d.startPTS:0;e.inputTimeScale||(Fr.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(t,e,i,n)),l=this.remuxVideo(e,p,s,r)}}else T&&(l=this.remuxVideo(e,p,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(h=fo(s,i,this._initPTS,this._initDTS)),r.samples.length&&(u=go(r,i,this._initPTS))),{audio:d,video:l,initSegment:c,independent:f,text:u,id3:h}}generateIS(t,e,s,r){const i=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS;let d,c,u,h=!l||r,f="audio/mp4";if(h&&(d=c=1/0),t.config&&i.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3")}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):MP4.initSegment([t]),metadata:{channelCount:t.channelCount}},h&&(u=t.inputTimeScale,l&&u===l.timescale?h=!1:d=c=i[0].pts-Math.round(u*s))}if(e.sps&&e.pps&&n.length&&(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:MP4.initSegment([e]),metadata:{width:e.width,height:e.height}},h))if(u=e.inputTimeScale,l&&u===l.timescale)h=!1;else{const t=this.getVideoStartPts(n),e=Math.round(u*s);c=Math.min(c,ho(n[0].dts,t)-e),d=Math.min(d,t-e)}if(Object.keys(o).length)return this.ISGenerated=!0,h?(this._initPTS={baseTime:d,timescale:u},this._initDTS={baseTime:c,timescale:u}):d=u=void 0,{tracks:o,initPTS:d,timescale:u}}remuxVideo(t,e,s,r){const i=t.inputTimeScale,n=t.samples,a=[],o=n.length,l=this._initPTS;let d,c,u=this.nextAvcDts,h=8,f=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,m=!1;if(!s||null===u){u=e*i-(n[0].pts-ho(n[0].dts,n[0].pts))}const y=l.baseTime*i/l.timescale;for(let t=0;t<o;t++){const e=n[t];e.pts=ho(e.pts-y,u),e.dts=ho(e.dts-y,u),e.dts<n[t>0?t-1:t].dts&&(m=!0)}m&&n.sort((function(t,e){const s=t.dts-e.dts,r=t.pts-e.pts;return s||r})),d=n[0].dts,c=n[n.length-1].dts;const v=c-d,E=v?Math.round(v/(o-1)):f||t.inputTimeScale/30;if(s){const t=d-u,e=t>E,s=t<-1;if((e||s)&&(e?Fr.warn(`AVC: ${oo(t,!0)} ms (${t}dts) hole between fragments detected, filling it`):Fr.warn(`AVC: ${oo(-t,!0)} ms (${t}dts) overlapping between fragments detected`),!s||u>n[0].pts)){d=u;const e=n[0].pts-t;n[0].dts=d,n[0].pts=e,Fr.log(`Video: First PTS/DTS adjusted: ${oo(e,!0)}/${oo(d,!0)}, delta: ${oo(t,!0)} ms`)}}d=Math.max(0,d);let T=0,_=0;for(let t=0;t<o;t++){const e=n[t],s=e.units,r=s.length;let i=0;for(let t=0;t<r;t++)i+=s[t].data.length;_+=i,T+=r,e.length=i,e.dts=Math.max(e.dts,d),g=Math.min(e.pts,g),p=Math.max(e.pts,p)}c=n[o-1].dts;const S=_+4*T+8;let A;try{A=new Uint8Array(S)}catch(t){return void this.observer.emit(Ir.ERROR,Ir.ERROR,{type:Dr.MUX_ERROR,details:Cr.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:S,reason:"fail allocating video mdat "+S})}const L=new DataView(A.buffer);L.setUint32(0,S),A.set(MP4.types.mdat,4);let b=!1,w=Number.POSITIVE_INFINITY,R=Number.POSITIVE_INFINITY,k=Number.NEGATIVE_INFINITY,I=Number.NEGATIVE_INFINITY;for(let t=0;t<o;t++){const e=n[t],s=e.units;let l,d=0;for(let t=0,e=s.length;t<e;t++){const e=s[t],r=e.data,i=e.data.byteLength;L.setUint32(h,i),h+=4,A.set(r,h),h+=i,d+=4+i}if(t<o-1)f=n[t+1].dts-e.dts,l=n[t+1].pts-e.pts;else{const s=this.config,a=t>0?e.dts-n[t-1].dts:E;if(l=t>0?e.pts-n[t-1].pts:E,s.stretchShortVideoTrack&&null!==this.nextAudioPts){const t=Math.floor(s.maxBufferHole*i),n=(r?g+r*i:this.nextAudioPts)-e.pts;n>t?(f=n-a,f<0?f=a:b=!0,Fr.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const c=Math.round(e.pts-e.dts);w=Math.min(w,f),k=Math.max(k,f),R=Math.min(R,l),I=Math.max(I,l),a.push(new Mp4Sample(e.key,f,d,c))}if(a.length)if(co){if(co<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(uo&&I-R<k-w&&E/k<.025&&0===a[0].cts){Fr.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=d;for(let e=0,s=a.length;e<s;e++){const r=t+a[e].duration,i=t+a[e].cts;if(e<s-1){const t=r+a[e+1].cts;a[e].duration=t-i}else a[e].duration=e?a[e-1].duration:E;a[e].cts=0,t=r}}f=b||!f?E:f,this.nextAvcDts=u=c+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const D={data1:MP4.moof(t.sequenceNumber++,d,Rr({},t,{samples:a})),data2:A,startPTS:g/i,endPTS:(p+f)/i,startDTS:d/i,endDTS:u/i,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:t.dropped};return t.samples=[],t.dropped=0,D}remuxAudio(t,e,s,r,i){const n=t.inputTimeScale,a=n/(t.samplerate?t.samplerate:n),o="aac"===t.segmentCodec?1024:1152,l=o*a,d=this._initPTS,c="mp3"===t.segmentCodec&&this.typeSupported.mpeg,u=[],h=void 0!==i;let f=t.samples,g=c?0:8,p=this.nextAudioPts||-1;const m=e*n,y=d.baseTime*n/d.timescale;if(this.isAudioContiguous=s=s||f.length&&p>0&&(r&&Math.abs(m-p)<9e3||Math.abs(ho(f[0].pts-y,m)-p)<20*l),f.forEach((function(t){t.pts=ho(t.pts-y,m)})),!s||p<0){if(f=f.filter(t=>t.pts>=0),!f.length)return;p=0===i?0:r&&!h?Math.max(0,m):f[0].pts}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let s=0,r=p;s<f.length;s++){const i=f[s],a=i.pts,o=a-r,d=Math.abs(1e3*o/n);if(o<=-e*l&&h)0===s&&(Fr.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/n)} ms.`),this.nextAudioPts=p=r=a);else if(o>=e*l&&d<1e4&&h){let e=Math.round(o/l);r=a-e*l,r<0&&(e--,r+=l),0===s&&(this.nextAudioPts=p=r),Fr.warn(`[mp4-remuxer]: Injecting ${e} audio frame @ ${(r/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<e;n++){const e=Math.max(r,0);let n=AAC.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);n||(Fr.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),n=i.unit.subarray()),f.splice(s,0,{unit:n,pts:e}),r+=l,s++}}i.pts=r,r+=l}}let v,E=null,T=null,_=0,S=f.length;for(;S--;)_+=f[S].unit.byteLength;for(let e=0,r=f.length;e<r;e++){const r=f[e],i=r.unit;let n=r.pts;if(null!==T){u[e-1].duration=Math.round((n-T)/a)}else{if(s&&"aac"===t.segmentCodec&&(n=p),E=n,!(_>0))return;_+=g;try{v=new Uint8Array(_)}catch(t){return void this.observer.emit(Ir.ERROR,Ir.ERROR,{type:Dr.MUX_ERROR,details:Cr.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:_,reason:"fail allocating audio mdat "+_})}if(!c){new DataView(v.buffer).setUint32(0,_),v.set(MP4.types.mdat,4)}}v.set(i,g);const l=i.byteLength;g+=l,u.push(new Mp4Sample(!0,o,l,0)),T=n}const A=u.length;if(!A)return;const L=u[u.length-1];this.nextAudioPts=p=T+a*L.duration;const b=c?new Uint8Array(0):MP4.moof(t.sequenceNumber++,E/a,Rr({},t,{samples:u}));t.samples=[];const w=E/n,R=p/n,k={data1:b,data2:v,startPTS:w,endPTS:R,startDTS:w,endDTS:R,type:"audio",hasAudio:!0,hasVideo:!1,nb:A};return this.isAudioContiguous=!0,k}remuxEmptyAudio(t,e,s,r){const i=t.inputTimeScale,n=i/(t.samplerate?t.samplerate:i),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,d=(null!==a?a:r.startDTS*i)+l,c=r.endDTS*i+l,u=1024*n,h=Math.ceil((c-d)/u),f=AAC.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(Fr.warn("[mp4-remuxer]: remux empty Audio"),!f)return void Fr.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const g=[];for(let t=0;t<h;t++){const e=d+t*u;g.push({unit:f,pts:e,dts:e})}return t.samples=g,this.remuxAudio(t,e,s,!1)}}function ho(t,e){let s;if(null===e)return t;for(s=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=s;return t}function fo(t,e,s,r){const i=t.samples.length;if(!i)return;const n=t.inputTimeScale;for(let a=0;a<i;a++){const i=t.samples[a];i.pts=ho(i.pts-9e4*s.baseTime/s.timescale,e*n)/n,i.dts=ho(i.dts-9e4*r.baseTime/r.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function go(t,e,s){const r=t.samples.length;if(!r)return;const i=t.inputTimeScale;for(let n=0;n<r;n++){const r=t.samples[n];r.pts=ho(r.pts-9e4*s.baseTime/s.timescale,e*i)/i}t.samples.sort((t,e)=>t.pts-e.pts);const n=t.samples;return t.samples=[],{samples:n}}class Mp4Sample{constructor(t,e,s,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=s,this.cts=r,this.flags=new Mp4SampleFlags(t)}}class Mp4SampleFlags{constructor(t){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=t?2:1,this.isNonSync=t?0:1}}function po(t,e){const s=null==t?void 0:t.codec;return s&&s.length>4?s:"hvc1"===s||"hev1"===s?"hvc1.1.c.L120.90":"av01"===s?"av01.0.04M.08":"avc1"===s||e===$r?"avc1.42e01e":"mp4a.40.5"}try{lo=self.performance.now.bind(self.performance)}catch(t){Fr.debug("Unable to use Performance API on this environment"),lo="undefined"!=typeof self&&self.Date.now}const mo=[{demux:class MP4Demuxer{constructor(t,e){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=e}resetTimeStamp(){}resetInitSegment(t,e,s,r){const i=this.videoTrack=Pa("video",1),n=this.audioTrack=Pa("audio",1),a=this.txtTrack=Pa("text",1);if(this.id3Track=Pa("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=Di(t);if(o.video){const{id:t,timescale:e,codec:s}=o.video;i.id=t,i.timescale=a.timescale=e,i.codec=s}if(o.audio){const{id:t,timescale:e,codec:s}=o.audio;n.id=t,n.timescale=e,n.codec=s}a.id=Si.text,i.sampleDuration=0,i.duration=n.duration=r}resetContiguity(){}static probe(t){return ki(t=t.length>16384?t.subarray(0,16384):t,["moof"]).length>0}demux(t,e){this.timeOffset=e;let s=t;const r=this.videoTrack,i=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Oi(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},s=ki(t,["moof"]);if(!s)return e;if(s.length<2)return e.remainder=t,e;const r=s[s.length-1];return e.valid=si(t,0,r.byteOffset-8),e.remainder=si(t,r.byteOffset-8),e}(s);this.remainderData=e.remainder,r.samples=e.valid||new Uint8Array}else r.samples=s;const n=this.extractID3Track(r,e);return i.samples=Mi(e,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,s=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(e,this.timeOffset);return s.samples=Mi(t,e),{videoTrack:e,audioTrack:Pa(),id3Track:r,textTrack:Pa()}}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const r=ki(t.samples,["emsg"]);r&&r.forEach(t=>{const r=function(t){const e=t[0];let s="",r="",i=0,n=0,a=0,o=0,l=0,d=0;if(0===e){for(;"\0"!==Ai(t.subarray(d,d+1));)s+=Ai(t.subarray(d,d+1)),d+=1;for(s+=Ai(t.subarray(d,d+1)),d+=1;"\0"!==Ai(t.subarray(d,d+1));)r+=Ai(t.subarray(d,d+1)),d+=1;r+=Ai(t.subarray(d,d+1)),d+=1,i=bi(t,12),n=bi(t,16),o=bi(t,20),l=bi(t,24),d=28}else if(1===e){d+=4,i=bi(t,d),d+=4;const e=bi(t,d);d+=4;const n=bi(t,d);for(d+=4,a=2**32*e+n,Number.isSafeInteger(a)||(a=Number.MAX_SAFE_INTEGER,Fr.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=bi(t,d),d+=4,l=bi(t,d),d+=4;"\0"!==Ai(t.subarray(d,d+1));)s+=Ai(t.subarray(d,d+1)),d+=1;for(s+=Ai(t.subarray(d,d+1)),d+=1;"\0"!==Ai(t.subarray(d,d+1));)r+=Ai(t.subarray(d,d+1)),d+=1;r+=Ai(t.subarray(d,d+1)),d+=1}return{schemeIdUri:s,value:r,timeScale:i,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(d,t.byteLength)}}(t);if(Ha.test(r.schemeIdUri)){const t=kr(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale;let i=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;i<=.001&&(i=Number.POSITIVE_INFINITY);const n=r.payload;s.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:Sn,duration:i})}})}return s}demuxSampleAes(t,e,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class PassThroughRemuxer{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(t){this.initPTS=t,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(t,e,s,r){this.audioCodec=e,this.videoCodec=s,this.generateInitSegment(function(t,e){if(!t||!e)return t;const s=e.keyId;if(s&&e.isCommonEncryption){ki(t,["moov","trak"]).forEach(t=>{const e=ki(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let r=ki(e,["enca"]);const i=r.length>0;i||(r=ki(e,["encv"])),r.forEach(t=>{ki(i?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const e=Ci(t);if(e){const t=e.subarray(8,24);t.some(t=>0!==t)||(Fr.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Ei(t)} -> ${Ei(s)}`),e.set(s,8))}})})})}return t}(t,r)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:e,videoCodec:s}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const r=this.initData=Di(t);e||(e=po(r.audio,Gr)),s||(s=po(r.video,$r));const i={};r.audio&&r.video?i.audiovideo={container:"video/mp4",codec:e+","+s,initSegment:t,id:"main"}:r.audio?i.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:r.video?i.video={container:"video/mp4",codec:s,initSegment:t,id:"main"}:Fr.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=i}remux(t,e,s,r,i,n){var a,o;let{initPTS:l,lastEndTime:d}=this;const c={audio:void 0,video:void 0,text:r,id3:s,initSegment:void 0};kr(d)||(d=this.lastEndTime=i||0);const u=e.samples;if(null==u||!u.length)return c;const h={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return Fr.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(t,e){return ki(e,["moof","traf"]).reduce((e,s)=>{const r=ki(s,["tfdt"])[0],i=r[0],n=ki(s,["tfhd"]).reduce((e,s)=>{const n=bi(s,4),a=t[n];if(a){let t=bi(r,4);if(1===i){if(t===Ti)return Fr.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;t*=Ti+1,t+=bi(r,8)}const s=t/(a.timescale||9e4);if(isFinite(s)&&(null===e||s<e))return s}return e},null);return null!==n&&isFinite(n)&&(null===e||n<e)?n:e},null)}(f,u),p=null===g?i:g;(function(t,e,s){if(null===t)return!0;const r=e-t.baseTime/t.timescale;return r<0&&Math.abs(r-s)>1}(l,p,i)||h.timescale!==l.timescale&&n)&&(h.initPTS=p-i,this.initPTS=l={baseTime:h.initPTS,timescale:1});const m=function(t,e){let s=0,r=0,i=0;const n=ki(t,["moof","traf"]);for(let t=0;t<n.length;t++){const a=n[t],o=ki(a,["tfhd"])[0],l=e[bi(o,4)];if(!l)continue;const d=l.default,c=bi(o,0)|(null==d?void 0:d.flags);let u=null==d?void 0:d.duration;8&c&&(u=bi(o,2&c?12:8));const h=l.timescale||9e4,f=ki(a,["trun"]);for(let t=0;t<f.length;t++){if(s=Pi(f[t]),!s&&u){s=u*bi(f[t],4)}l.type===$r?r+=s/h:l.type===Gr&&(i+=s/h)}}if(0===r&&0===i){let e=0;const s=ki(t,["sidx"]);for(let t=0;t<s.length;t++){const r=Ii(s[t]);null!=r&&r.references&&(e+=r.references.reduce((t,e)=>t+e.info.duration||0,0))}return e}return r||i}(u,f),y=t?p-l.baseTime/l.timescale:d,v=y+m;!function(t,e,s){ki(e,["moof","traf"]).forEach(e=>{ki(e,["tfhd"]).forEach(r=>{const i=bi(r,4),n=t[i];if(!n)return;const a=n.timescale||9e4;ki(e,["tfdt"]).forEach(t=>{const e=t[0];let r=bi(t,4);if(0===e)r-=s*a,r=Math.max(r,0),Ri(t,4,r);else{r*=Math.pow(2,32),r+=bi(t,8),r-=s*a,r=Math.max(r,0);const e=Math.floor(r/(Ti+1)),i=Math.floor(r%(Ti+1));Ri(t,4,e),Ri(t,8,i)}})})})}(f,u,l.baseTime/l.timescale),m>0?this.lastEndTime=v:(Fr.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const E=!!f.audio,T=!!f.video;let _="";E&&(_+="audio"),T&&(_+="video");const S={data1:u,startPTS:y,startDTS:y,endPTS:v,endDTS:v,type:_,hasAudio:E,hasVideo:T,nb:1,dropped:0};return c.audio="audio"===S.type?S:void 0,c.video="audio"!==S.type?S:void 0,c.initSegment=h,c.id3=fo(s,i,l,l),r.samples.length&&(c.text=go(r,i,l)),c}}},{demux:TSDemuxer,remux:MP4Remuxer},{demux:class AACDemuxer extends BaseAudioDemuxer{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,s,r){super.resetInitSegment(t,e,s,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;let e=(ni(t,0)||[]).length;for(let s=t.length;e<s;e++)if(Ua(t,e))return Fr.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return function(t,e){return e+5<t.length}(t,e)&&Ma(t,e)&&Fa(t,e)<=t.length-e}(t,e)}appendFrame(t,e,s){Ba(t,this.observer,e,s,t.manifestCodec);const r=$a(t,e,s,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}},remux:MP4Remuxer},{demux:class MP3Demuxer extends BaseAudioDemuxer{resetInitSegment(t,e,s,r){super.resetInitSegment(t,e,s,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;let e=(ni(t,0)||[]).length;for(let s=t.length;e<s;e++)if(Za(t,e))return Fr.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return Xa(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,s){if(null!==this.basePTS)return Ya(t,e,s,this.basePTS,this.frameIndex)}},remux:MP4Remuxer}];class Transmuxer{constructor(t,e,s,r,i){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=e,this.config=s,this.vendor=r,this.id=i}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,s,r){const i=s.transmuxing;i.executeStart=lo();let n=new Uint8Array(t);const{currentTransmuxState:a,transmuxConfig:o}=this;r&&(this.currentTransmuxState=r);const{contiguous:l,discontinuity:d,trackSwitch:c,accurateTimeOffset:u,timeOffset:h,initSegmentChange:f}=r||a,{audioCodec:g,videoCodec:p,defaultInitPts:m,duration:y,initSegmentData:v}=o,E=function(t,e){let s=null;t.byteLength>0&&null!=e&&null!=e.key&&null!==e.iv&&null!=e.method&&(s=e);return s}(n,e);if(E&&"AES-128"===E.method){const t=this.getDecrypter();if(!t.isSync())return this.decryptionPromise=t.webCryptoDecrypt(n,E.key.buffer,E.iv.buffer).then(t=>{const e=this.push(t,null,s);return this.decryptionPromise=null,e}),this.decryptionPromise;{let e=t.softwareDecrypt(n,E.key.buffer,E.iv.buffer);if(s.part>-1&&(e=t.flush()),!e)return i.executeEnd=lo(),yo(s);n=new Uint8Array(e)}}const T=this.needsProbing(d,c);if(T){const t=this.configureTransmuxer(n);if(t)return Fr.warn("[transmuxer] "+t.message),this.observer.emit(Ir.ERROR,Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),i.executeEnd=lo(),yo(s)}(d||c||f||T)&&this.resetInitSegment(v,g,p,y,e),(d||f||T)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const _=this.transmux(n,E,h,u,s),S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,i.executeEnd=lo(),_}flush(t){const e=t.transmuxing;e.executeStart=lo();const{decrypter:s,currentTransmuxState:r,decryptionPromise:i}=this;if(i)return i.then(()=>this.flush(t));const n=[],{timeOffset:a}=r;if(s){const e=s.flush();e&&n.push(this.push(e,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return e.executeEnd=lo(),[yo(t)];const d=o.flush(a);return vo(d)?d.then(e=>(this.flushRemux(n,e,t),n)):(this.flushRemux(n,d,t),n)}flushRemux(t,e,s){const{audioTrack:r,videoTrack:i,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;Fr.log(`[transmuxer.ts]: Flushed fragment ${s.sn}${s.part>-1?" p: "+s.part:""} of level ${s.level}`);const d=this.remuxer.remux(r,i,n,a,l,o,!0,this.id);t.push({remuxResult:d,chunkMeta:s}),s.transmuxing.executeEnd=lo()}resetInitialTimestamp(t){const{demuxer:e,remuxer:s}=this;e&&s&&(e.resetTimeStamp(t),s.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,s,r,i){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,s,r),a.resetInitSegment(t,e,s,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,s,r,i){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,s,r,i):this.transmuxUnencrypted(t,s,r,i),n}transmuxUnencrypted(t,e,s,r){const{audioTrack:i,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,n,a,o,e,s,!1,this.id),chunkMeta:r}}transmuxSampleAes(t,e,s,r,i){return this.demuxer.demuxSampleAes(t,e,s).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,s,r,!1,this.id),chunkMeta:i}))}configureTransmuxer(t){const{config:e,observer:s,typeSupported:r,vendor:i}=this;let n;for(let e=0,s=mo.length;e<s;e++)if(mo[e].demux.probe(t)){n=mo[e];break}if(!n)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=n.remux,d=n.demux;o&&o instanceof l||(this.remuxer=new l(s,e,r,i)),a&&a instanceof d||(this.demuxer=new d(s,e,r),this.probe=d.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Decrypter(this.config)),t}}const yo=t=>({remuxResult:{},chunkMeta:t});function vo(t){return"then"in t&&t.then instanceof Function}class TransmuxConfig{constructor(t,e,s,r,i){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=s,this.duration=r,this.defaultInitPts=i||null}}class TransmuxState{constructor(t,e,s,r,i,n){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=t,this.contiguous=e,this.accurateTimeOffset=s,this.trackSwitch=r,this.timeOffset=i,this.initSegmentChange=n}}var Eo={};!function(t){var e=Object.prototype.hasOwnProperty,s="~";function r(){}function i(t,e,s){this.fn=t,this.context=e,this.once=s||!1}function n(t,e,r,n,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new i(r,n||t,a),l=s?s+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0==--t._eventsCount?t._events=new r:delete t._events[e]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(s=!1)),o.prototype.eventNames=function(){var t,r,i=[];if(0===this._eventsCount)return i;for(r in t=this._events)e.call(t,r)&&i.push(s?r.slice(1):r);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(t)):i},o.prototype.listeners=function(t){var e=s?s+t:t,r=this._events[e];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,n=r.length,a=new Array(n);i<n;i++)a[i]=r[i].fn;return a},o.prototype.listenerCount=function(t){var e=s?s+t:t,r=this._events[e];return r?r.fn?1:r.length:0},o.prototype.emit=function(t,e,r,i,n,a){var o=s?s+t:t;if(!this._events[o])return!1;var l,d,c=this._events[o],u=arguments.length;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,r),!0;case 4:return c.fn.call(c.context,e,r,i),!0;case 5:return c.fn.call(c.context,e,r,i,n),!0;case 6:return c.fn.call(c.context,e,r,i,n,a),!0}for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];c.fn.apply(c.context,l)}else{var h,f=c.length;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(t,c[d].fn,void 0,!0),u){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,e);break;case 3:c[d].fn.call(c[d].context,e,r);break;case 4:c[d].fn.call(c[d].context,e,r,i);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];c[d].fn.apply(c[d].context,l)}}return!0},o.prototype.on=function(t,e,s){return n(this,t,e,s,!1)},o.prototype.once=function(t,e,s){return n(this,t,e,s,!0)},o.prototype.removeListener=function(t,e,r,i){var n=s?s+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||i&&!o.once||r&&o.context!==r||a(this,n);else{for(var l=0,d=[],c=o.length;l<c;l++)(o[l].fn!==e||i&&!o[l].once||r&&o[l].context!==r)&&d.push(o[l]);d.length?this._events[n]=1===d.length?d[0]:d:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=s?s+t:t,this._events[e]&&a(this,e)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,t.exports=o}({get exports(){return Eo},set exports(t){Eo=t}});const To=Da()||{isTypeSupported:()=>!1};class TransmuxerInterface{constructor(t,e,s,r){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const i=t.config;this.hls=t,this.id=e,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=s,this.onFlush=r;const n=(t,e)=>{(e=e||{}).frag=this.frag,e.id=this.id,t===Ir.ERROR&&(this.error=e.error),this.hls.trigger(t,e)};this.observer=new Eo,this.observer.on(Ir.FRAG_DECRYPTED,n),this.observer.on(Ir.ERROR,n);const a={mp4:To.isTypeSupported("video/mp4"),mpeg:To.isTypeSupported("audio/mpeg"),mp3:To.isTypeSupported('audio/mp4; codecs="mp3"')},o=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){if(i.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{i.workerPath?(Fr.log(`loading Web Worker ${i.workerPath} for "${e}"`),this.workerContext=function(t){const e=new self.URL(t,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}(i.workerPath)):(Fr.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){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"}),e=self.URL.createObjectURL(t);return{worker:new self.Worker(e),objectURL:e}}()),this.onwmsg=t=>this.onWorkerMessage(t);const{worker:t}=this.workerContext;t.addEventListener("message",this.onwmsg),t.onerror=t=>{const s=new Error(`${t.message} (${t.filename}:${t.lineno})`);i.enableWorker=!1,Fr.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(Ir.ERROR,{type:Dr.OTHER_ERROR,details:Cr.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:s})},t.postMessage({cmd:"init",typeSupported:a,vendor:o,id:e,config:JSON.stringify(i)})}catch(t){Fr.warn(`Error setting up "${e}" Web Worker, fallback to inline`,t),this.resetWorker(),this.error=null,this.transmuxer=new Transmuxer(this.observer,a,i,o,e)}return}}this.transmuxer=new Transmuxer(this.observer,a,i,o,e)}resetWorker(){if(this.workerContext){const{worker:t,objectURL:e}=this.workerContext;e&&self.URL.revokeObjectURL(e),t.removeEventListener("message",this.onwmsg),t.onerror=null,t.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(t,e,s,r,i,n,a,o,l,d){var c,u;l.transmuxing.start=self.performance.now();const{transmuxer:h}=this,f=n?n.start:i.start,g=i.decryptdata,p=this.frag,m=!(p&&i.cc===p.cc),y=!(p&&l.level===p.level),v=p?l.sn-p.sn:-1,E=this.part?l.part-this.part.index:-1,T=0===v&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),_=!y&&(1===v||0===v&&(1===E||T&&E<=0)),S=self.performance.now();(y||v||0===i.stats.parsing.start)&&(i.stats.parsing.start=S),!n||!E&&_||(n.stats.parsing.start=S);const A=!(p&&(null==(c=i.initSegment)?void 0:c.url)===(null==(u=p.initSegment)?void 0:u.url)),L=new TransmuxState(m,_,o,y,f,A);if(!_||m||A){Fr.log(`[transmuxer-interface, ${i.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${m}\n trackSwitch: ${y}\n contiguous: ${_}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${A}`);const t=new TransmuxConfig(s,r,e,a,d);this.configureTransmuxer(t)}if(this.frag=i,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:g,chunkMeta:l,state:L},t instanceof ArrayBuffer?[t]:[]);else if(h){const e=h.push(t,g,l,L);vo(e)?(h.async=!0,e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,l,"transmuxer-interface push error")})):(h.async=!1,this.handleTransmuxComplete(e))}}flush(t){t.transmuxing.start=self.performance.now();const{transmuxer:e}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(e){let s=e.flush(t);vo(s)||e.async?(vo(s)||(s=Promise.resolve(s)),s.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")})):this.handleFlushResult(s,t)}}transmuxerError(t,e,s){this.hls&&(this.error=t,this.hls.trigger(Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.FRAG_PARSING_ERROR,chunkMeta:e,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}onWorkerMessage(t){const e=t.data,s=this.hls;switch(e.event){case"init":{var r;const t=null==(r=this.workerContext)?void 0:r.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":Fr[e.data.logType]&&Fr[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,s.trigger(e.event,e.data)}}configureTransmuxer(t){const{transmuxer:e}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):e&&e.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class GapController{constructor(t,e,s,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=s,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(t,e){const{config:s,media:r,stalled:i}=this;if(null===r)return;const{currentTime:n,seeking:a}=r,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,n!==t){if(this.moved=!0,null!==i){if(this.stallReported){const t=self.performance.now()-i;Fr.warn(`playback not stuck anymore @${n}, after ${Math.round(t)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(l||o)return void(this.stalled=null);if(r.paused&&!a||r.ended||0===r.playbackRate||!BufferHelper.getBuffered(r).length)return;const d=BufferHelper.bufferInfo(r,n,0),c=d.len>0,u=d.nextStart||0;if(!c&&!u)return;if(a){const t=d.len>2,s=!u||e&&e.start<=n||u-n>2&&!this.fragmentTracker.getPartialFragment(n);if(t||s)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var h;const t=Math.max(u,d.start||0)-n,e=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,s=(null==e||null==(h=e.details)?void 0:h.live)?2*e.details.targetduration:2,r=this.fragmentTracker.getPartialFragment(n);if(t>0&&(t<=s||r))return void this._trySkipBufferHole(r)}const f=self.performance.now();if(null===i)return void(this.stalled=f);const g=f-i;if(!a&&g>=250&&(this._reportStall(d),!this.media))return;const p=BufferHelper.bufferInfo(r,n,s.maxBufferHole);this._tryFixBufferStall(p,g)}_tryFixBufferStall(t,e){const{config:s,fragmentTracker:r,media:i}=this;if(null===i)return;const n=i.currentTime,a=r.getPartialFragment(n);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(t.len>s.maxBufferHole||t.nextStart&&t.nextStart-n<s.maxBufferHole)&&e>1e3*s.highBufferWatchdogPeriod&&(Fr.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(t){const{hls:e,media:s,stallReported:r}=this;if(!r&&s){this.stallReported=!0;const r=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${JSON.stringify(t)})`);Fr.warn(r.message),e.trigger(Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:t.len})}}_trySkipBufferHole(t){const{config:e,hls:s,media:r}=this;if(null===r)return 0;const i=r.currentTime,n=BufferHelper.bufferInfo(r,i,0),a=i<n.start?n.start:n.nextStart;if(a){const o=n.len<=e.maxBufferHole,l=n.len>0&&n.len<1&&r.readyState<3,d=a-i;if(d>0&&(o||l)){if(d>e.maxBufferHole){const{fragmentTracker:e}=this;let s=!1;if(0===i){const t=e.getAppendedFrag(0,un);t&&a<t.end&&(s=!0)}if(!s){const s=t||e.getAppendedFrag(i,un);if(s){let t=!1,r=s.end;for(;r<a;){const s=e.getPartialFragment(r);if(!s){t=!0;break}r+=s.duration}if(t)return 0}}}const n=Math.max(a+.05,i+.1);if(Fr.warn(`skipping hole, adjusting currentTime from ${i} to ${n}`),this.moved=!0,this.stalled=null,r.currentTime=n,t&&!t.gap){const e=new Error(`fragment loaded with buffer holes, seeking from ${i} to ${n}`);s.trigger(Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:e,reason:e.message,frag:t})}return n}}return 0}_tryNudgeBuffer(){const{config:t,hls:e,media:s,nudgeRetry:r}=this;if(null===s)return;const i=s.currentTime;if(this.nudgeRetry++,r<t.nudgeMaxRetry){const n=i+(r+1)*t.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${i} to ${n}`);Fr.warn(a.message),s.currentTime=n,e.trigger(Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const s=new Error(`Playhead still not moving while enough data buffered @${i} after ${t.nudgeMaxRetry} nudges`);Fr.error(s.message),e.trigger(Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.BUFFER_STALLED_ERROR,error:s,fatal:!0})}}}class StreamController extends BaseStreamController{constructor(t,e,s){super(t,e,s,"[stream-controller]",un),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(Ir.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Ir.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ir.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Ir.LEVEL_LOADING,this.onLevelLoading,this),t.on(Ir.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Ir.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(Ir.ERROR,this.onError,this),t.on(Ir.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Ir.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(Ir.BUFFER_CREATED,this.onBufferCreated,this),t.on(Ir.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Ir.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Ir.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(Ir.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Ir.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ir.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Ir.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Ir.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(Ir.ERROR,this.onError,this),t.off(Ir.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Ir.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(Ir.BUFFER_CREATED,this.onBufferCreated,this),t.off(Ir.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Ir.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Ir.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),this.onMediaDetaching()}startLoad(t){if(this.levels){const{lastCurrentTime:e,hls:s}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=s.startLevel;-1===t&&(s.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=s.nextAutoLevel),this.level=s.nextLoadLevel=t,this.loadedmetadata=!1}e>0&&-1===t&&(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=Ea,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=va}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Ia:{var t;const{levels:e,level:s}=this,r=null==e||null==(t=e[s])?void 0:t.details;if(r&&(!r.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(r))break;this.state=Ea;break}break}case Sa:{var e;const t=self.performance.now(),s=this.retryDate;(!s||t>=s||null!=(e=this.media)&&e.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=Ea)}}this.state===Ea&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:s,media:r}=this,{config:i,nextLoadLevel:n}=t;if(null===e||!r&&(this.startFragRequested||!i.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;if(null==s||!s[n])return;const a=s[n],o=this.getMainFwdBufferInfo();if(null===o)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const t={};return this.altAudio&&(t.type="video"),this.hls.trigger(Ir.BUFFER_EOS,t),void(this.state=wa)}t.loadLevel!==n&&-1===t.manualLevel&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=t.nextLoadLevel=n;const d=a.details;if(!d||this.state===Ia||d.live&&this.levelLastLoaded!==n)return this.level=n,void(this.state=Ia);const c=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(c>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(h,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&"initSegment"!==f.sn&&this.fragmentTracker.getState(f)!==na){var g;const t=(null!=(g=this.backtrackFragment)?g:f).sn-d.startSN,e=d.fragments[t-1];e&&f.cc===e.cc&&(f=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){const t=this.audioOnly&&!this.altAudio?Gr:$r,e=(t===$r?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,un)}f=this.getNextFragmentLoopLoading(f,d,o,un,u)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(t,e,s){const r=this.fragmentTracker.getState(t);this.fragCurrent=t,r===sa?"initSegment"===t.sn?this._loadInitSegment(t,e):this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):(this.startFragRequested=!0,super.loadFragment(t,e,s)):this.clearTrackerIfNeeded(t)}getAppendedFrag(t){const e=this.fragmentTracker.getAppendedFrag(t,un);return e&&"fragment"in e?e.fragment:e}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,un)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let s;const r=this.getAppendedFrag(e.currentTime);if(r&&r.start>1&&this.flushMainBuffer(0,r.start-1),!e.paused&&t){const e=t[this.hls.nextLoadLevel],r=this.fragLastKbps;s=r&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*r)+1:0}else s=0;const i=this.getBufferedFrag(e.currentTime+s);if(i){const t=this.followingBufferedFrag(i);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,s=t.duration,r=Math.max(i.end,e+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,.5*s),.75*s));this.flushMainBuffer(r,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case Ta:case _a:case Sa:case La:case ba:this.state=Ea}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const s=e.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),s.addEventListener("playing",this.onvplaying),s.addEventListener("seeked",this.onvseeked),this.gapController=new GapController(this.config,s,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:t}=this;t&&this.onvplaying&&this.onvseeked&&(t.removeEventListener("playing",this.onvplaying),t.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const t=this.media,e=t?t.currentTime:null;kr(e)&&this.log("Media seeked to "+e.toFixed(3));const s=this.getMainFwdBufferInfo();null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${s?s.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(Ir.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.fragPlaying=null,this.backtrackFragment=null}onManifestParsed(t,e){let s,r=!1,i=!1;e.levels.forEach(t=>{s=t.audioCodec,s&&(-1!==s.indexOf("mp4a.40.2")&&(r=!0),-1!==s.indexOf("mp4a.40.5")&&(i=!0))}),this.audioCodecSwitch=r&&i&&!function(){var t;const e=Ca();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:s}=this;if(!s||this.state!==Ea)return;const r=s[e.level];(!r.details||r.details.live&&this.levelLastLoaded!==e.level||this.waitForCdnTuneIn(r.details))&&(this.state=Ia)}onLevelLoaded(t,e){var s;const{levels:r}=this,i=e.level,n=e.details,a=n.totalduration;if(!r)return void this.warn("Levels were reset while loading level "+i);this.log(`Level ${i} loaded [${n.startSN},${n.endSN}], cc [${n.startCC}, ${n.endCC}] duration:${a}`);const o=r[i],l=this.fragCurrent;!l||this.state!==_a&&this.state!==Sa||l.level===e.level&&l.urlId===o.urlId||!l.loader||this.abortCurrentFrag();let d=0;if(n.live||null!=(s=o.details)&&s.live){if(n.fragments[0]||(n.deltaUpdateFailed=!0),n.deltaUpdateFailed)return;d=this.alignPlaylists(n,o.details)}if(o.details=n,this.levelLastLoaded=i,this.hls.trigger(Ir.LEVEL_UPDATED,{details:n,level:i}),this.state===Ia){if(this.waitForCdnTuneIn(n))return;this.state=Ea}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,d),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:s,part:r,payload:i}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,d=o.PTSKnown||!o.live,c=null==(e=s.initSegment)?void 0:e.data,u=this._getAudioCodec(a),h=this.transmuxer=this.transmuxer||new TransmuxerInterface(this.hls,un,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,p=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount,i.byteLength,f,g),m=this.initPTS[s.cc];h.push(i,c,u,l,s,r,o.totalduration,d,p,m)}onAudioTrackSwitching(t,e){const s=this.altAudio;if(!!!e.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const t=this.hls;s&&(t.trigger(Ir.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),t.trigger(Ir.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const s=e.id,r=!!this.hls.audioTracks[s].url;if(r){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=r,this.tick()}onBufferCreated(t,e){const s=e.tracks;let r,i,n=!1;for(const t in s){const e=s[t];if("main"===e.id){if(i=t,r=e,"video"===t){const e=s[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&r?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:s,part:r}=e;if(s&&s.type!==un)return;if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===ba&&(this.state=Ea));const i=r?r.stats:s.stats;this.fragLastKbps=Math.round(8*i.total/(i.buffering.end-i.loading.first)),"initSegment"!==s.sn&&(this.fragPrevious=s),this.fragBufferedComplete(s,r)}onError(t,e){var s;if(e.fatal)this.state=Ra;else switch(e.details){case Cr.FRAG_GAP:case Cr.FRAG_PARSING_ERROR:case Cr.FRAG_DECRYPT_ERROR:case Cr.FRAG_LOAD_ERROR:case Cr.FRAG_LOAD_TIMEOUT:case Cr.KEY_LOAD_ERROR:case Cr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(un,e);break;case Cr.LEVEL_LOAD_ERROR:case Cr.LEVEL_LOAD_TIMEOUT:case Cr.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Ia||(null==(s=e.context)?void 0:s.type)!==ln||(this.state=Ea);break;case Cr.BUFFER_FULL_ERROR:if(!e.parent||"main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case Cr.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}checkBuffer(){const{media:t,gapController:e}=this;if(t&&e&&t.readyState){if(this.loadedmetadata||!BufferHelper.getBuffered(t).length){const t=this.state!==Ea?this.fragCurrent:null;e.poll(this.lastCurrentTime,t)}this.lastCurrentTime=t.currentTime}}onFragLoadEmergencyAborted(){this.state=Ea,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==Gr||this.audioOnly&&!this.altAudio){const t=(e===$r?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(t,e,un)}}onLevelsUpdated(t,e){this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let s=this.startPosition;if(s>=0&&e<s){if(t.seeking)return void this.log(`could not seek to ${s}, already seeking at ${e}`);const r=BufferHelper.getBuffered(t),i=(r.length?r.start(0):0)-s;i>0&&(i<this.config.maxBufferHole||i<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${i} to match buffer start`),s+=i,this.startPosition=s),this.log(`seek to target start position ${s} from current time ${e}`),t.currentTime=s}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(s=>{const{hls:r}=this;if(!s||this.fragContextChanged(t))return;e.fragmentError=0,this.state=Ea,this.startFragRequested=!1,this.bitrateTest=!1;const i=t.stats;i.parsing.start=i.parsing.end=i.buffering.start=i.buffering.end=self.performance.now(),r.trigger(Ir.FRAG_LOADED,s),t.bitrateTest=!1})}_handleTransmuxComplete(t){var e;const s="main",{hls:r}=this,{remuxResult:i,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:d}=a,{video:c,text:u,id3:h,initSegment:f}=i,{details:g}=d,p=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=La,f){f.tracks&&(this._bufferInitSegment(d,f.tracks,o,n),r.trigger(Ir.FRAG_PARSING_INIT_SEGMENT,{frag:o,id:s,tracks:f.tracks}));const t=f.initPTS,e=f.timescale;kr(t)&&(this.initPTS[o.cc]={baseTime:t,timescale:e},r.trigger(Ir.INIT_PTS_FOUND,{frag:o,id:s,initPTS:t,timescale:e}))}if(c&&!1!==i.independent){if(g){const{startPTS:t,endPTS:e,startDTS:s,endDTS:r}=c;if(l)l.elementaryStreams[c.type]={startPTS:t,endPTS:e,startDTS:s,endDTS:r};else if(c.firstKeyFrame&&c.independent&&1===n.id&&(this.couldBacktrack=!0),c.dropped&&c.independent){const s=this.getMainFwdBufferInfo();if((s?s.end:this.getLoadPosition())+this.config.maxBufferHole<(c.firstKeyFramePTS?c.firstKeyFramePTS:t)-this.config.maxBufferHole)return void this.backtrack(o);o.setElementaryStreamInfo(c.type,o.start,e,o.start,r,!0)}o.setElementaryStreamInfo(c.type,t,e,s,r),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(c,o,l,n)}}else if(!1===i.independent)return void this.backtrack(o);if(p){const{startPTS:t,endPTS:e,startDTS:s,endDTS:r}=p;l&&(l.elementaryStreams[Gr]={startPTS:t,endPTS:e,startDTS:s,endDTS:r}),o.setElementaryStreamInfo(Gr,t,e,s,r),this.bufferFragmentData(p,o,l,n)}if(g&&null!=h&&null!=(e=h.samples)&&e.length){const t={id:s,frag:o,details:g,samples:h.samples};r.trigger(Ir.FRAG_PARSING_METADATA,t)}if(g&&u){const t={id:s,frag:o,details:g,samples:u.samples};r.trigger(Ir.FRAG_PARSING_USERDATA,t)}}}_bufferInitSegment(t,e,s,r){if(this.state!==La)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;const{audio:i,video:n,audiovideo:a}=e;if(i){let e=t.audioCodec;const s=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(e&&(e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),1!==i.metadata.channelCount&&-1===s.indexOf("firefox")&&(e="mp4a.40.5")),-1!==s.indexOf("android")&&"audio/mpeg"!==i.container&&(e="mp4a.40.2",this.log("Android: force audio codec to "+e)),t.audioCodec&&t.audioCodec!==e&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${e}"`),i.levelCodec=e,i.id="main",this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${e||""}/${t.audioCodec||""}/${i.codec}]`)}n&&(n.levelCodec=t.videoCodec,n.id="main",this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${n.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.attrs.CODECS||""}/${a.codec}]`),this.hls.trigger(Ir.BUFFER_CODECS,e),Object.keys(e).forEach(t=>{const i=e[t].initSegment;null!=i&&i.byteLength&&this.hls.trigger(Ir.BUFFER_APPENDING,{type:t,data:i,frag:s,part:null,chunkMeta:r,parent:s.type})}),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,un)}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=Ea}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const s=t.currentTime;if(BufferHelper.isBuffered(t,s)?e=this.getAppendedFrag(s):BufferHelper.isBuffered(t,s+.1)&&(e=this.getAppendedFrag(s+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,s=e.level;t&&e.sn===t.sn&&t.level===s&&e.urlId===t.urlId||(this.fragPlaying=e,this.hls.trigger(Ir.FRAG_CHANGED,{frag:e}),t&&t.level===s||this.hls.trigger(Ir.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){const t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}get currentProgramDateTime(){const t=this.media;if(t){const e=t.currentTime,s=this.currentFrag;if(s&&kr(e)&&kr(s.programDateTime)){const t=s.programDateTime+1e3*(e-s.start);return new Date(t)}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class EWMA{constructor(t,e=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=s}sample(t,e){const s=Math.pow(this.alpha_,t);this.estimate_=e*(1-s)+s*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class EwmaBandWidthEstimator{constructor(t,e,s,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new EWMA(t),this.fast_=new EWMA(e),this.defaultTTFB_=r,this.ttfb_=new EWMA(t)}update(t,e){const{slow_:s,fast_:r,ttfb_:i}=this;s.halfLife!==t&&(this.slow_=new EWMA(t,s.getEstimate(),s.getTotalWeight())),r.halfLife!==e&&(this.fast_=new EWMA(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new EWMA(t,i.getEstimate(),i.getTotalWeight()))}sample(t,e){const s=(t=Math.max(t,this.minDelayMs_))/1e3,r=8*e/s;this.fast_.sample(s,r),this.slow_.sample(s,r)}sampleTTFB(t){const e=t/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(s,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}class ChunkCache{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let s;return t.length?(s=1===t.length?t[0]:function(t,e){const s=new Uint8Array(e);let r=0;for(let e=0;e<t.length;e++){const i=t[e];s.set(i,r),r+=i.length}return s}(t,e),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function _o(t,e){if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!So(t[s].attrs,e[s].attrs))return!1;return!0}function So(t,e){const s=t["STABLE-RENDITION-ID"];return s?s===e["STABLE-RENDITION-ID"]:!["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED"].some(s=>t[s]!==e[s])}class BufferableInstance{constructor(t){this.buffered=void 0;const e=(e,s,r)=>{if((s>>>=0)>r-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${r})`);return t[s][e]};this.buffered={get length(){return t.length},end:s=>e("end",s,t.length),start:s=>e("start",s,t.length)}}}function Ao(t){const e=[];for(let s=0;s<t.length;s++){const r=t[s];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||e.push(t[s])}return e}class BufferOperationQueue{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,e){const s=this.queues[e];s.push(t),1===s.length&&this.buffers[e]&&this.executeNext(e)}insertAbort(t,e){this.queues[e].unshift(t),this.executeNext(e)}appendBlocker(t){let e;const s=new Promise(t=>{e=t}),r={execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(r,t),s}executeNext(t){const{buffers:e,queues:s}=this,r=e[t],i=s[t];if(i.length){const e=i[0];try{e.execute()}catch(s){Fr.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),e.onError(s),null!=r&&r.updating||(i.shift(),this.executeNext(t))}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const Lo=Da(),bo=/([ha]vc.)(?:\.[^.,]+)+/;const wo={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},Ro=function(t){let e=t;return wo.hasOwnProperty(t)&&(e=wo[t]),String.fromCharCode(e)},ko={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Io={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Do={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Co={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Po=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class CaptionsLogger{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const s="function"==typeof e?e():e;Fr.log(`${this.time} [${t}] ${s}`)}}}const Oo=function(t){const e=[];for(let s=0;s<t.length;s++)e.push(t[s].toString(16));return e};class PenState{constructor(t,e,s,r,i){this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=t||"white",this.underline=e||!1,this.italics=s||!1,this.background=r||"black",this.flash=i||!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(t){const e=["foreground","underline","italics","background","flash"];for(let s=0;s<e.length;s++){const r=e[s];t.hasOwnProperty(r)&&(this[r]=t[r])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class StyledUnicodeChar{constructor(t,e,s,r,i,n){this.uchar=void 0,this.penState=void 0,this.uchar=t||" ",this.penState=new PenState(e,s,r,i,n)}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class Row{constructor(t){this.chars=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(let t=0;t<100;t++)this.chars.push(new StyledUnicodeChar);this.logger=t,this.pos=0,this.currPenState=new PenState}equals(t){let e=!0;for(let s=0;s<100;s++)if(!this.chars[s].equals(t.chars[s])){e=!1;break}return e}copy(t){for(let e=0;e<100;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<100;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>100&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=100)}moveCursor(t){const e=this.pos+t;if(t>1)for(let t=this.pos+1;t<e+1;t++)this.chars[t].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=Ro(t);this.pos>=100?this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e<100;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let s=0;s<100;s++){const r=this.chars[s].uchar;" "!==r&&(e=!1),t.push(r)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class CaptionScreen{constructor(t){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(let e=0;e<15;e++)this.rows.push(new Row(t));this.logger=t,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}reset(){for(let t=0;t<15;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let s=0;s<15;s++)if(!this.rows[s].equals(t.rows[s])){e=!1;break}return e}copy(t){for(let e=0;e<15;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<15;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t);this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,()=>"pacData = "+JSON.stringify(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let t=0;t<15;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const r=s.rows[t].cueStartTime,i=this.logger.time;if(r&&null!==i&&r<i)for(let r=0;r<this.nrRollUpRows;r++)this.rows[e-this.nrRollUpRows+r+1].copy(s.rows[t+r])}}this.currRow=e;const s=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,r=Math.max(e-1,0);s.setCursor(t.indent),t.color=s.chars[r].penState.foreground}const r={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+JSON.stringify(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}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 t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let s="",r=-1;for(let s=0;s<15;s++){const i=this.rows[s].getTextString();i&&(r=s+1,t?e.push("Row "+r+": '"+i+"'"):e.push(i.trim()))}return e.length>0&&(s=t?"["+e.join(" | ")+"]":e.join("\n")),s}getTextAndFormat(){return this.rows}}class Cea608Channel{constructor(t,e,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new CaptionScreen(s),this.nonDisplayedMemory=new CaptionScreen(s),this.lastOutputScreen=new CaptionScreen(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),"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=t)}insertChars(t){for(let e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>e+": "+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(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}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 t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const s=Math.floor(t/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=r[s]}this.logger.log(2,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class Cea608Parser{constructor(t,e,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const r=new CaptionsLogger;this.channels=[null,new Cea608Channel(t,e,r),new Cea608Channel(t+1,s,r)],this.cmdHistory={a:null,b:null},this.logger=r}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){let s,r,i,n=!1;this.logger.time=t;for(let t=0;t<e.length;t+=2)if(r=127&e[t],i=127&e[t+1],0!==r||0!==i){if(this.logger.log(3,"["+Oo([e[t],e[t+1]])+"] -> ("+Oo([r,i])+")"),s=this.parseCmd(r,i),s||(s=this.parseMidrow(r,i)),s||(s=this.parsePAC(r,i)),s||(s=this.parseBackgroundAttributes(r,i)),!s&&(n=this.parseChars(r,i),n)){const t=this.currentChannel;if(t&&t>0){this.channels[t].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}s||n||this.logger.log(2,"Couldn't parse cleaned data "+Oo([r,i])+" orig: "+Oo([e[t],e[t+1]]))}}parseCmd(t,e){const{cmdHistory:s}=this;if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;if(xo(t,e,s))return Mo(null,null,s),this.logger.log(3,"Repeated command ("+Oo([t,e])+") is dropped"),!0;const r=20===t||21===t||23===t?1:2,i=this.channels[r];return 20===t||21===t||28===t||29===t?32===e?i.ccRCL():33===e?i.ccBS():34===e?i.ccAOF():35===e?i.ccAON():36===e?i.ccDER():37===e?i.ccRU(2):38===e?i.ccRU(3):39===e?i.ccRU(4):40===e?i.ccFON():41===e?i.ccRDC():42===e?i.ccTR():43===e?i.ccRTD():44===e?i.ccEDM():45===e?i.ccCR():46===e?i.ccENM():47===e&&i.ccEOC():i.ccTO(e-32),Mo(t,e,s),this.currentChannel=r,!0}parseMidrow(t,e){let s=0;if((17===t||25===t)&&e>=32&&e<=47){if(s=17===t?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[s];return!!r&&(r.ccMIDROW(e),this.logger.log(3,"MIDROW ("+Oo([t,e])+")"),!0)}return!1}parsePAC(t,e){let s;const r=this.cmdHistory;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;if(xo(t,e,r))return Mo(null,null,r),!0;const i=t<=23?1:2;s=e>=64&&e<=95?1===i?ko[t]:Do[t]:1===i?Io[t]:Co[t];const n=this.channels[i];return!!n&&(n.setPAC(this.interpretPAC(s,e)),Mo(t,e,r),this.currentChannel=i,!0)}interpretPAC(t,e){let s;const r={color:null,italics:!1,indent:null,underline:!1,row:t};return s=e>95?e-96:e-64,r.underline=1==(1&s),s<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((s-16)/2),r}parseChars(t,e){let s,r=null,i=null;if(t>=25?(s=2,i=t-8):(s=1,i=t),i>=17&&i<=19){let t;t=17===i?e+80:18===i?e+112:e+144,this.logger.log(2,"Special char '"+Ro(t)+"' in channel "+s),r=[t]}else t>=32&&t<=127&&(r=0===e?[t]:[t,e]);if(r){const s=Oo(r);this.logger.log(3,"Char codes = "+s.join(",")),Mo(t,e,this.cmdHistory)}return r}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let s;const r={};16===t||24===t?(s=Math.floor((e-32)/2),r.background=Po[s],e%2==1&&(r.background=r.background+"_semi")):45===e?r.background="transparent":(r.foreground="black",47===e&&(r.underline=!0));const i=t<=23?1:2;return this.channels[i].setBkgData(r),Mo(t,e,this.cmdHistory),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}this.cmdHistory={a:null,b:null}}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const s=this.channels[e];s&&s.cueSplitAtTime(t)}}}function Mo(t,e,s){s.a=t,s.b=e}function xo(t,e,s){return s.a===t&&s.b===e}class OutputFilter{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,s){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Fo=function(){if("undefined"!=typeof self&&self.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function s(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const s=e.toLowerCase();return!!~t.indexOf(s)&&s}function r(t){return s(e,t)}function i(t,...e){let s=1;for(;s<arguments.length;s++){const e=arguments[s];for(const s in e)t[s]=e[s]}return t}function n(e,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let d="",c=!1,u=e,h=n,f=a,g=null,p="",m=!0,y="auto",v="start",E=50,T="middle",_=50,S="middle";Object.defineProperty(o,"id",i({},l,{get:function(){return d},set:function(t){d=""+t}})),Object.defineProperty(o,"pauseOnExit",i({},l,{get:function(){return c},set:function(t){c=!!t}})),Object.defineProperty(o,"startTime",i({},l,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",i({},l,{get:function(){return h},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");h=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",i({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",i({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",i({},l,{get:function(){return p},set:function(e){const r=function(e){return s(t,e)}(e);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");p=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",i({},l,{get:function(){return m},set:function(t){m=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",i({},l,{get:function(){return y},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",i({},l,{get:function(){return v},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",i({},l,{get:function(){return E},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",i({},l,{get:function(){return T},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",i({},l,{get:function(){return _},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");_=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",i({},l,{get:function(){return S},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");S=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class StringDecoder{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function No(t){function e(t,e,s,r){return 3600*(0|t)+60*(0|e)+(0|s)+parseFloat(r||0)}const s=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?e(s[2],s[3],0,s[4]):e(s[1],s[2],s[3],s[4]):null}class Settings{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,s){return s?this.has(t)?this.values[t]:e[s]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,s){for(let r=0;r<s.length;++r)if(e===s[r]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const s=parseFloat(e);if(s>=0&&s<=100)return this.set(t,s),!0}return!1}}function Uo(t,e,s,r){const i=r?t.split(r):[t];for(const t in i){if("string"!=typeof i[t])continue;const r=i[t].split(s);if(2!==r.length)continue;e(r[0],r[1])}}const Bo=new Fo(0,0,""),Go="middle"===Bo.align?"middle":"center";function $o(t,e,s){const r=t;function i(){const e=No(t);if(null===e)throw new Error("Malformed timestamp: "+r);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=i(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);t=t.slice(3),n(),e.endTime=i(),n(),function(t,e){const r=new Settings;Uo(t,(function(t,e){let i;switch(t){case"region":for(let i=s.length-1;i>=0;i--)if(s[i].id===e){r.set(t,s[i].region);break}break;case"vertical":r.alt(t,e,["rl","lr"]);break;case"line":i=e.split(","),r.integer(t,i[0]),r.percent(t,i[0])&&r.set("snapToLines",!1),r.alt(t,i[0],["auto"]),2===i.length&&r.alt("lineAlign",i[1],["start",Go,"end"]);break;case"position":i=e.split(","),r.percent(t,i[0]),2===i.length&&r.alt("positionAlign",i[1],["start",Go,"end","line-left","line-right","auto"]);break;case"size":r.percent(t,e);break;case"align":r.alt(t,e,["start",Go,"end","left","right"])}}),/:/,/\s/),e.region=r.get("region",null),e.vertical=r.get("vertical","");let i=r.get("line","auto");"auto"===i&&-1===Bo.line&&(i=-1),e.line=i,e.lineAlign=r.get("lineAlign","start"),e.snapToLines=r.get("snapToLines",!0),e.size=r.get("size",100),e.align=r.get("align",Go);let n=r.get("position","auto");"auto"===n&&50===Bo.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function Ho(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class VTTParser{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new StringDecoder,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function s(){let t=e.buffer,s=0;for(t=Ho(t);s<t.length&&"\r"!==t[s]&&"\n"!==t[s];)++s;const r=t.slice(0,s);return"\r"===t[s]&&++s,"\n"===t[s]&&++s,e.buffer=t.slice(s),r}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;t=s();const r=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==r||!r[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let r=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(r?r=!1:t=s(),e.state){case"HEADER":/:/.test(t)?Uo(t,(function(t,e){}),/:/):t||(e.state="ID");continue;case"NOTE":t||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){e.state="NOTE";break}if(!t)continue;if(e.cue=new Fo(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{$o(t,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const s=-1!==t.indexOf("--\x3e");if(!t||s&&(r=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=t}continue;case"BADCUE":t||(e.state="ID")}}}catch(t){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}}const Ko=/\r\n|\n\r|\n|\r/g,Vo=function(t,e,s=0){return t.slice(s,s+e.length)===e},qo=function(t){let e=5381,s=t.length;for(;s;)e=33*e^t.charCodeAt(--s);return(e>>>0).toString()};function jo(t,e,s){return qo(t.toString())+qo(e.toString())+qo(s)}function Wo(t,e,s,r,i,n,a){const o=new VTTParser,l=mi(new Uint8Array(t)).trim().replace(Ko,"\n").split("\n"),d=[],c=function(t,e=1){return ao(t,9e4,1/e)}(e.baseTime,e.timescale);let u,h="00:00.000",f=0,g=0,p=!0;o.oncue=function(t){const e=s[r];let n=s.ccOffset;const a=(f-c)/9e4;null!=e&&e.new&&(void 0!==g?n=s.ccOffset=e.start:function(t,e,s){let r=t[e],i=t[r.prevCC];if(!i||!i.new&&r.new)return t.ccOffset=t.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=i)&&n.new;){var n;t.ccOffset+=r.start-i.start,r.new=!1,r=i,i=t[r.prevCC]}t.presentationOffset=s}(s,r,a)),a&&(n=a-s.presentationOffset);const o=t.endTime-t.startTime,l=ho(9e4*(t.startTime+n-g),9e4*i)/9e4;t.startTime=Math.max(l,0),t.endTime=Math.max(l+o,0);const u=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(u)),t.id||(t.id=jo(t.startTime,t.endTime,u)),t.endTime>0&&d.push(t)},o.onparsingerror=function(t){u=t},o.onflush=function(){u?a(u):n(d)},l.forEach(t=>{if(p){if(Vo(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach(t=>{Vo(t,"LOCAL:")?h=t.slice(6):Vo(t,"MPEGTS:")&&(f=parseInt(t.slice(7)))});try{g=function(t){let e=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),i=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(kr(e)&&kr(s)&&kr(r)&&kr(i)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+t);return e+=1e3*s,e+=6e4*r,e+=36e5*i,e}(h)/1e3}catch(t){u=t}return}""===t&&(p=!1)}o.parse(t+"\n")}),o.flush()}const Yo=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,zo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Xo={left:"start",center:"center",right:"end",start:"start",end:"end"};function Qo(t,e,s,r){const i=ki(new Uint8Array(t),["mdat"]);if(0===i.length)return void r(new Error("Could not parse IMSC1 mdat"));const n=i.map(t=>mi(t)),a=function(t,e,s=1,r=!1){return ao(t,e,1/s,r)}(e.baseTime,1,e.timescale);try{n.forEach(t=>s(function(t,e){const s=new DOMParser,r=s.parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(i).reduce((t,e)=>(t[e]=r.getAttribute("ttp:"+e)||i[e],t),{}),a="preserve"!==r.getAttribute("xml:space"),o=Jo(Zo(r,"styling","style")),l=Jo(Zo(r,"layout","region")),d=Zo(r,"body","[begin]");return[].map.call(d,t=>{const s=function t(e,s){return[].slice.call(e.childNodes).reduce((e,r,i)=>{var n;return"br"===r.nodeName&&i?e+"\n":null!=(n=r.childNodes)&&n.length?t(r,s):s?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent},"")}(t,a);if(!s||!t.hasAttribute("begin"))return null;const r=sl(t.getAttribute("begin"),n),i=sl(t.getAttribute("dur"),n);let d=sl(t.getAttribute("end"),n);if(null===r)throw el(t);if(null===d){if(null===i)throw el(t);d=r+i}const c=new Fo(r-e,d-e,s);c.id=jo(c.startTime,c.endTime,c.text);const u=function(t,e,s){const r="http://www.w3.org/ns/ttml#styling";let i=null;const n=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;n&&s.hasOwnProperty(n)&&(i=s[n]);return["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((s,n)=>{const a=tl(e,r,n)||tl(t,r,n)||tl(i,r,n);return a&&(s[n]=a),s},{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:h}=u;if(h){const t=Xo[h];t&&(c.lineAlign=t),c.align=h}return Rr(c,u),c}).filter(t=>null!==t)}(t,a)))}catch(t){r(t)}}function Zo(t,e,s){const r=t.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(s)):[]}function Jo(t){return t.reduce((t,e)=>{const s=e.getAttribute("xml:id");return s&&(t[s]=e),t},{})}function tl(t,e,s){return t&&t.hasAttributeNS(e,s)?t.getAttributeNS(e,s):null}function el(t){return new Error("Could not parse ttml timestamp "+t)}function sl(t,e){if(!t)return null;let s=No(t);return null===s&&(Yo.test(t)?s=function(t,e){const s=Yo.exec(t),r=(0|s[4])+(0|s[5])/e.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+r/e.frameRate}(t,e):zo.test(t)&&(s=function(t,e){const s=zo.exec(t),r=Number(s[1]);switch(s[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/e.frameRate;case"t":return r/e.tickRate}return r}(t,e))),s}function rl(t,e){return!!t&&t.label===e.name&&!(t.textTrack1||t.textTrack2)}class CapLevelController{constructor(t){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=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(Ir.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(Ir.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Ir.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Ir.BUFFER_CODECS,this.onBufferCodecs,this),t.on(Ir.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(Ir.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(Ir.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Ir.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Ir.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Ir.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const s=this.hls.levels[e.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null}onManifestParsed(t,e){const s=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,s.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){const t=this.hls.levels;if(t.length){const e=this.hls;e.autoLevelCapping=this.getMaxLevel(t.length-1),e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const s=e.filter((e,s)=>this.isLevelAllowed(e)&&s<=t);return this.clientRect=null,CapLevelController.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),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 t=this.media,e={width:0,height:0};if(t){const s=t.getBoundingClientRect();e.width=s.width,e.height=s.height,e.width||e.height||(e.width=s.right-s.left||t.width||0,e.height=s.bottom-s.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return t}isLevelAllowed(t){return!this.restrictedLevels.some(e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height)}static getMaxLevelByMediaSize(t,e,s){if(null==t||!t.length)return-1;let r=t.length-1;for(let a=0;a<t.length;a+=1){const o=t[a];if((o.width>=e||o.height>=s)&&(i=o,!(n=t[a+1])||i.width!==n.width||i.height!==n.height)){r=a;break}}var i,n;return r}}class EMEController{constructor(t){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=EMEController.CDMCleanupPromise?[EMEController.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=Fr.debug.bind(Fr,"[eme]"),this.log=Fr.log.bind(Fr,"[eme]"),this.warn=Fr.warn.bind(Fr,"[eme]"),this.error=Fr.error.bind(Fr,"[eme]"),this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(Ir.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Ir.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Ir.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(Ir.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Ir.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Ir.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:s}=this.config,r=e[t];if(r)return r.licenseUrl;if(t===jr.WIDEVINE&&s)return s;throw new Error(`no license server URL configured for key-system "${t}"`)}getServerCertificateUrl(t){const{drmSystems:e}=this.config,s=e[t];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,s=(t,e,s)=>!!t&&s.indexOf(t)===e,r=e.map(t=>t.audioCodec).filter(s),i=e.map(t=>t.videoCodec).filter(s);return r.length+i.length===0&&i.push("avc1.42e01e"),new Promise((e,s)=>{const n=t=>{const a=t.shift();this.getMediaKeysPromise(a,r,i).then(t=>e({keySystem:a,mediaKeys:t})).catch(e=>{t.length?n(t):s(e instanceof EMEKeyError?e:new EMEKeyError({type:Dr.KEY_SYSTEM_ERROR,details:Cr.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))})};n(t)})}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let t="Configured requestMediaKeySystemAccess is not a function "+s;return null===ei&&"http:"===self.location.protocol&&(t="navigator.requestMediaKeySystemAccess is not available over insecure protocol "+location.protocol),Promise.reject(new Error(t))}return s(t,e)}getMediaKeysPromise(t,e,s){const r=function(t,e,s,r){let i;switch(t){case jr.FAIRPLAY:i=["cenc","sinf"];break;case jr.WIDEVINE:case jr.PLAYREADY:i=["cenc"];break;case jr.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error("Unknown key-system: "+t)}return function(t,e,s,r){return[{initDataTypes:t,persistentState:r.persistentState||"not-allowed",distinctiveIdentifier:r.distinctiveIdentifier||"not-allowed",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:e.map(t=>({contentType:`audio/mp4; codecs="${t}"`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:s.map(t=>({contentType:`video/mp4; codecs="${t}"`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}))}]}(i,e,s,r)}(t,e,s,this.config.drmSystemOptions),i=this.keySystemAccessPromises[t];let n=null==i?void 0:i.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(r)}`),n=this.requestMediaKeySystemAccess(t,r);const e=this.keySystemAccessPromises[t]={keySystemAccess:n};return n.catch(e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)}),n.then(s=>{this.log(`Access for key-system "${s.keySystem}" obtained`);const r=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),e.mediaKeys=s.createMediaKeys().then(e=>(this.log(`Media-keys created for "${t}"`),r.then(s=>s?this.setMediaKeysServerCertificate(e,t,s):e))),e.mediaKeys.catch(e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)}),e.mediaKeys})}return n.then(()=>i.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:s}){this.log(`Creating key-system session "${e}" keyId: ${Ei(t.keyId||[])}`);const r=s.createSession(),i={decryptdata:t,keySystem:e,mediaKeys:s,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const s=this.createMediaKeySessionContext(t),r=this.getKeyIdString(e),i="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(s,i,e.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return Ei(t.keyId)}updateKeySession(t,e){var s;const r=t.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${Ei((null==(s=t.decryptdata)?void 0:s.keyId)||[])}\n } (data length: ${e?e.byteLength:e})`),r.update(e)}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise((e,s)=>{const r=ti(this.config),i=t.map(Qr).filter(t=>!!t&&-1!==r.indexOf(t));return this.getKeySystemSelectionPromise(i).then(({keySystem:t})=>{const r=Jr(t);r?e(r):s(new Error(`Unable to find format for key-system "${t}"`))}).catch(s)})}loadKey(t){const e=t.keyInfo.decryptdata,s=this.getKeyIdString(e),r=`(keyId: ${s} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log("Starting session for key "+r);let i=this.keyIdToKeySessionPromise[s];return i||(i=this.keyIdToKeySessionPromise[s]=this.getKeySystemForKeyPromise(e).then(({keySystem:s,mediaKeys:i})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${r}`),this.attemptSetMediaKeys(s,i).then(()=>{this.throwIfDestroyed();const t=this.createMediaKeySessionContext({keySystem:s,mediaKeys:i,decryptdata:e});return this.generateRequestWithPreferredKeySession(t,"cenc",e.pssh,"playlist-key")}))),i.catch(t=>this.handleError(t))),i}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof EMEKeyError?this.hls.trigger(Ir.ERROR,t.data):this.hls.trigger(Ir.ERROR,{type:Dr.KEY_SYSTEM_ERROR,details:Cr.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),s=this.keyIdToKeySessionPromise[e];if(!s){const e=Qr(t.keyFormat),s=e?[e]:ti(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=ti(this.config)),0===t.length)throw new EMEKeyError({type:Dr.KEY_SYSTEM_ERROR,details:Cr.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options "+JSON.stringify({drmSystems:this.config.drmSystems}));return this.attemptKeySystemAccess(t)}_onMediaEncrypted(t){const{initDataType:e,initData:s}=t;if(this.debug(`"${t.type}" event: init data type: "${e}"`),null===s)return;let r,i;if("sinf"===e&&this.config.drmSystems[jr.FAIRPLAY]){const t=Ai(new Uint8Array(s));try{const e=Kr(JSON.parse(t).sinf),s=Ci(new Uint8Array(e));if(!s)return;r=s.subarray(8,24),i=jr.FAIRPLAY}catch(t){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{const t=function(t){if(!(t instanceof ArrayBuffer)||t.byteLength<32)return null;const e={version:0,systemId:"",kids:null,data:null},s=new DataView(t),r=s.getUint32(0);if(t.byteLength!==r&&r>44)return null;if(1886614376!==s.getUint32(4))return null;if(e.version=s.getUint32(8)>>>24,e.version>1)return null;e.systemId=Ei(new Uint8Array(t,12,16));const i=s.getUint32(28);if(0===e.version){if(r-32<i)return null;e.data=new Uint8Array(t,32,i)}else if(1===e.version){e.kids=[];for(let s=0;s<i;s++)e.kids.push(new Uint8Array(t,32+16*s,16))}return e}(s);if(null===t)return;0===t.version&&t.systemId===Zr&&t.data&&(r=t.data.subarray(8,24)),i=function(t){if(t===Zr)return jr.WIDEVINE}(t.systemId)}if(!i||!r)return;const n=Ei(r),{keyIdToKeySessionPromise:a,mediaKeySessions:o}=this;let l=a[n];for(let t=0;t<o.length;t++){const i=o[t],d=i.decryptdata;if(d.pssh||!d.keyId)continue;const c=Ei(d.keyId);if(n===c||-1!==d.uri.replace(/-/g,"").indexOf(n)){l=a[c],delete a[c],d.pssh=new Uint8Array(s),d.keyId=r,l=a[n]=l.then(()=>this.generateRequestWithPreferredKeySession(i,e,s,"encrypted-event-key-match"));break}}l||(l=a[n]=this.getKeySystemSelectionPromise([i]).then(({keySystem:t,mediaKeys:i})=>{var a;this.throwIfDestroyed();const o=new LevelKey("ISO-23001-7",n,null!=(a=Jr(t))?a:"");return o.pssh=new Uint8Array(s),o.keyId=r,this.attemptSetMediaKeys(t,i).then(()=>{this.throwIfDestroyed();const r=this.createMediaKeySessionContext({decryptdata:o,keySystem:t,mediaKeys:i});return this.generateRequestWithPreferredKeySession(r,e,s,"encrypted-event-no-match")})})),l.catch(t=>this.handleError(t))}_onWaitingForKey(t){this.log(`"${t.type}" event`)}attemptSetMediaKeys(t,e){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const r=Promise.all(s).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)});return this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${t}"`),s.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(t=>-1===s.indexOf(t))})}generateRequestWithPreferredKeySession(t,e,s,r){var i,n;const a=null==(i=this.config.drmSystems)||null==(n=i[t.keySystem])?void 0:n.generateRequest;if(a)try{const r=a.call(this.hls,e,s,t);if(!r)throw new Error("Invalid response from configured generateRequest filter");e=r.initDataType,s=t.decryptdata.pssh=r.initData?new Uint8Array(r.initData):null}catch(t){var o;if(this.warn(t.message),null!=(o=this.hls)&&o.config.debug)throw t}if(null===s)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t);const l=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${r}": ${l} (init data type: ${e} length: ${s?s.byteLength:null})`);const d=new Eo;t.mediaKeysSession.onmessage=e=>{const s=t.mediaKeysSession;if(!s)return void d.emit("error",new Error("invalid state"));const{messageType:r,message:i}=e;this.log(`"${r}" message event for session "${s.sessionId}" message size: ${i.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(t,i).catch(t=>{this.handleError(t),d.emit("error",t)}):"license-release"===r?t.keySystem===jr.FAIRPLAY&&(this.updateKeySession(t,qr("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${r}"`)},t.mediaKeysSession.onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void d.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const s=t.keyStatus;d.emit("keyStatus",s),"expired"===s&&(this.warn(`${t.keySystem} expired for key ${l}`),this.renewKeySession(t))};const c=new Promise((t,e)=>{d.on("error",e),d.on("keyStatus",s=>{s.startsWith("usable")?t():"output-restricted"===s?e(new EMEKeyError({type:Dr.KEY_SYSTEM_ERROR,details:Cr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===s?e(new EMEKeyError({type:Dr.KEY_SYSTEM_ERROR,details:Cr.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${s}"`)):"expired"===s?e(new Error("key expired while generating request")):this.warn(`unhandled key status change "${s}"`)})});return t.mediaKeysSession.generateRequest(e,s).then(()=>{var e;this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${l}`)}).catch(t=>{throw new EMEKeyError({type:Dr.KEY_SYSTEM_ERROR,details:Cr.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},"Error generating key-session request: "+t)}).then(()=>c).catch(e=>{throw d.removeAllListeners(),this.removeSession(t),e}).then(()=>(d.removeAllListeners(),t))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach((e,s)=>{this.log(`key status change "${e}" for keyStatuses keyId: ${Ei("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${Ei(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e})}fetchServerCertificate(t){const e=this.config,s=new(0,e.loader)(e),r=this.getServerCertificateUrl(t);return r?(this.log(`Fetching serverCertificate for "${t}"`),new Promise((i,n)=>{const a={responseType:"arraybuffer",url:r},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,e,s,r)=>{i(t.data)},onError:(e,s,i,o)=>{n(new EMEKeyError({type:Dr.KEY_SYSTEM_ERROR,details:Cr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:i,response:br({url:a.url,data:void 0},e)},`"${t}" certificate request failed (${r}). Status: ${e.code} (${e.text})`))},onTimeout:(e,s,i)=>{n(new EMEKeyError({type:Dr.KEY_SYSTEM_ERROR,details:Cr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:i,response:{url:a.url,data:void 0}},`"${t}" certificate request timed out (${r})`))},onAbort:(t,e,s)=>{n(new Error("aborted"))}};s.load(a,l,d)})):Promise.resolve()}setMediaKeysServerCertificate(t,e,s){return new Promise((r,i)=>{t.setServerCertificate(s).then(i=>{this.log(`setServerCertificate ${i?"success":"not supported by CDM"} (${null==s?void 0:s.byteLength}) on "${e}"`),r(t)}).catch(t=>{i(new EMEKeyError({type:Dr.KEY_SYSTEM_ERROR,details:Cr.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))})})}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then(e=>this.updateKeySession(t,new Uint8Array(e)).catch(t=>{throw new EMEKeyError({type:Dr.KEY_SYSTEM_ERROR,details:Cr.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))}setupLicenseXHR(t,e,s,r){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return i.call(this.hls,t,e,s,r)}).catch(n=>{if(!s.decryptdata)throw n;return t.open("POST",e,!0),i.call(this.hls,t,e,s,r)}).then(s=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:s||r}}):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:r}))}requestLicense(t,e){const s=this.config.keyLoadPolicy.default;return new Promise((r,i)=>{const n=this.getLicenseServerUrl(t.keySystem);this.log("Sending license request to URL: "+n);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return i(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let e=a.response;this.log("License received "+(e instanceof ArrayBuffer?e.byteLength:e));const s=this.config.licenseResponseCallback;if(s)try{e=s.call(this.hls,a,n,t)}catch(t){this.error(t)}r(e)}else{const o=s.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)i(new EMEKeyError({type:Dr.KEY_SYSTEM_ERROR,details:Cr.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const s=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${s} attempts left`),this.requestLicense(t,e).then(r,i)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=a,this.setupLicenseXHR(a,n,t,e).then(({xhr:t,licenseChallenge:e})=>{t.send(e)})})}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const s=e.media;this.media=s,s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media,e=this.mediaKeySessions;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},LevelKey.clearKeyUriToKeyIdMap();const s=e.length;EMEController.CDMCleanupPromise=Promise.all(e.map(t=>this.removeSession(t)).concat(null==t?void 0:t.setMediaKeys(null).catch(e=>{this.log(`Could not clear media keys: ${e}. media.src: ${null==t?void 0:t.src}`)}))).then(()=>{s&&(this.log("finished closing key sessions and clearing media keys"),e.length=0)}).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}. media.src: ${null==t?void 0:t.src}`)})}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t),[]);this.log("Selecting key-system from session-keys "+t.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:s}=t;if(e){this.log("Remove licenses and keys and close session "+e.sessionId),e.onmessage=null,e.onkeystatuseschange=null,s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(t);return r>-1&&this.mediaKeySessions.splice(r,1),e.remove().catch(t=>{this.log("Could not remove session: "+t)}).then(()=>e.close()).catch(t=>{this.log("Could not close session: "+t)})}}}EMEController.CDMCleanupPromise=void 0;class EMEKeyError extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}var il="m",nl="a",al="v",ol="av",ll="i",dl="tt";class CMCDController{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=t=>{try{this.apply(t,{ot:il,su:!this.initialized})}catch(t){Fr.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const e=t.frag,s=this.hls.levels[e.level],r=this.getObjectType(e),i={d:1e3*e.duration,ot:r};r!==al&&r!==nl&&r!=ol||(i.br=s.bitrate/1e3,i.tb=this.getTopBandwidth(r)/1e3,i.bl=this.getBufferLength(r)),this.apply(t,i)}catch(t){Fr.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const e=this.config=t.config,{cmcd:s}=e;null!=s&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||CMCDController.uuid(),this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.registerListeners())}registerListeners(){const t=this.hls;t.on(Ir.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Ir.MEDIA_DETACHED,this.onMediaDetached,this),t.on(Ir.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(Ir.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Ir.MEDIA_DETACHED,this.onMediaDetached,this),t.off(Ir.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null}onMediaAttached(t,e){this.media=e.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(t,e){var s,r;this.audioBuffer=null==(s=e.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(r=e.tracks.video)?void 0:r.buffer}createData(){var t;return{v:1,sf:"h",sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){Rr(e,this.createData());const s=e.ot===ll||e.ot===al||e.ot===ol;if(this.starved&&s&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering),this.useHeaders){const s=CMCDController.toHeaders(e);if(!Object.keys(s).length)return;t.headers||(t.headers={}),Rr(t.headers,s)}else{const s=CMCDController.toQuery(e);if(!s)return;t.url=CMCDController.appendQueryToUri(t.url,s)}}getObjectType(t){const{type:e}=t;return"subtitle"===e?dl:"initSegment"===t.sn?ll:"audio"===e?nl:"main"===e?this.hls.audioTracks.length?al:ol:void 0}getTopBandwidth(t){let e,s=0;const r=this.hls;if(t===nl)e=r.audioTracks;else{const t=r.maxAutoLevel,s=t>-1?t+1:r.levels.length;e=r.levels.slice(0,s)}for(const t of e)t.bitrate>s&&(s=t.bitrate);return s>0?s:NaN}getBufferLength(t){const e=this.hls.media,s=t===nl?this.audioBuffer:this.videoBuffer;if(!s||!e)return NaN;return 1e3*BufferHelper.bufferInfo(s,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,s=t||this.config.loader;return class CmcdPlaylistLoader{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,r){e(t),this.loader.load(t,s,r)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,s=t||this.config.loader;return class CmcdFragmentLoader{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,r){e(t),this.loader.load(t,s,r)}}}static uuid(){const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}static serialize(t){const e=[],s=t=>!Number.isNaN(t)&&null!=t&&""!==t&&!1!==t,r=t=>Math.round(t),i=t=>100*r(t/100),n={br:r,d:r,bl:i,dl:i,mtp:i,nor:t=>encodeURIComponent(t),rtp:i,tb:r},a=Object.keys(t||{}).sort();for(const r of a){let i=t[r];if(!s(i))continue;if("v"===r&&1===i)continue;if("pr"==r&&1===i)continue;const a=n[r];a&&(i=a(i));const o=typeof i;let l;l="ot"===r||"sf"===r||"st"===r?`${r}=${i}`:"boolean"===o?r:"number"===o?`${r}=${i}`:`${r}=${JSON.stringify(i)}`,e.push(l)}return e.join(",")}static toHeaders(t){const e=Object.keys(t),s={},r=["Object","Request","Session","Status"],i=[{},{},{},{}],n={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const s of e){i[null!=n[s]?n[s]:1][s]=t[s]}for(let t=0;t<i.length;t++){const e=CMCDController.serialize(i[t]);e&&(s["CMCD-"+r[t]]=e)}return s}static toQuery(t){return"CMCD="+encodeURIComponent(CMCDController.serialize(t))}static appendQueryToUri(t,e){if(!e)return t;const s=t.includes("?")?"&":"?";return`${t}${s}${e}`}}function cl(t,e,s,r){t&&Object.keys(e).forEach(i=>{const n=t.filter(t=>t.groupId===i).map(t=>{const n=Rr({},t);return n.details=void 0,n.attrs=new AttrList(n.attrs),n.url=n.attrs.URI=ul(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=e[i],n.attrs["PATHWAY-ID"]=r,n});t.push(...n)})}function ul(t,e,s,r){const{HOST:i,PARAMS:n,[s]:a}=r;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return i&&!o&&(l.host=i),n&&Object.keys(n).sort().forEach(t=>{t&&l.searchParams.set(t,n[t])}),l.href}const hl=/^age:\s*[\d.]+\s*$/im;class XhrLoader{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new LoadStats,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t)return;const s=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0;const i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!this.stats.aborted)return i(s,e.url)}).catch(t=>(s.open("GET",e.url,!0),i(s,e.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(s,e,t)}).catch(t=>{this.callbacks.onError({code:s.status,text:t.message},e,s,r)}):this.openAndSendXhr(s,e,t)}openAndSendXhr(t,e,s){t.readyState||t.open("GET",e.url,!0);const r=this.context.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:n}=s.loadPolicy;if(r)for(const e in r)t.setRequestHeader(e,r[e]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),s.timeout=i&&kr(i)?i:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:s}=this;if(!t||!e)return;const r=e.readyState,i=this.config;if(!s.aborted&&r>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const r=e.status,n="text"!==e.responseType;if(r>=200&&r<300&&(n&&e.response||null!==e.responseText)){s.loading.end=Math.max(self.performance.now(),s.loading.first);const i=n?e.response:e.responseText,a="arraybuffer"===e.responseType?i.byteLength:i.length;if(s.loaded=s.total=a,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(s,t,i,e),!this.callbacks)return;const l={url:e.responseURL,data:i,code:r};this.callbacks.onSuccess(l,s,t,e)}else{const n=i.loadPolicy.errorRetry;$n(n,s.retry,!1,r)?this.retry(n):(Fr.error(`${r} while loading ${t.url}`),this.callbacks.onError({code:r,text:e.statusText},t,e,s))}}}loadtimeout(){var t;const e=null==(t=this.config)?void 0:t.loadPolicy.timeoutRetry;if($n(e,this.stats.retry,!0))this.retry(e);else{Fr.warn("timeout while loading "+this.context.url);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:s}=this;this.retryDelay=Bn(t,s.retry),s.retry++,Fr.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${e.url}, retrying ${s.retry}/${t.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(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&hl.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const fl=/(\d+)-(\d+)\/(\d+)/;class FetchLoader{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||gl,this.controller=new self.AbortController,this.stats=new LoadStats}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const t=this.response;null!=t&&t.ok||(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,s){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const i=function(t,e){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Rr({},t.headers))};t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return s}(t,this.controller.signal),n=s.onProgress,a="arraybuffer"===t.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:d}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=s,this.request=this.fetchSetup(t,i),self.clearTimeout(this.requestTimeout),e.timeout=l&&kr(l)?l:d,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),s.onTimeout(r,t,this.response)},e.timeout),self.fetch(this.request).then(i=>{this.response=this.loader=i;const o=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),s.onTimeout(r,t,this.response)},d-(o-r.loading.start)),!i.ok){const{status:t,statusText:e}=i;throw new FetchError(e||"fetch, bad network response",t,i)}return r.loading.first=o,r.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=fl.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(kr(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(i.headers)||r.total,n&&kr(e.highWaterMark)?this.loadProgressively(i,r,t,e.highWaterMark,n):a?i.arrayBuffer():"json"===t.responseType?i.json():i.text()}).then(i=>{const{response:a}=this;self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const l=i[o];l&&(r.loaded=r.total=l);const d={url:a.url,data:i,code:a.status};n&&!kr(e.highWaterMark)&&n(r,t,i,a),s.onSuccess(d,r,t,a)}).catch(e=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const i=e&&e.code||0,n=e?e.message:null;s.onError({code:i,text:n},t,e?e.details:null,r)})}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,s,r=0,i){const n=new ChunkCache,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&i(e,s,n.flush(),t),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return e.loaded+=d,d<r||n.dataLength?(n.push(l),n.dataLength>=r&&i(e,s,n.flush(),t)):i(e,s,l,t),o()}).catch(()=>Promise.reject());return o()}}function gl(t,e){return new self.Request(t.url,e)}class FetchError extends Error{constructor(t,e,s){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=s}}const pl=/\s/,ml={newCue(t,e,s,r){const i=[];let n,a,o,l,d;const c=self.VTTCue||self.TextTrackCue;for(let h=0;h<r.rows.length;h++)if(n=r.rows[h],o=!0,l=0,d="",!n.isEmpty()){var u;for(let t=0;t<n.chars.length;t++)pl.test(n.chars[t].uchar)&&o?l++:(d+=n.chars[t].uchar,o=!1);n.cueStartTime=e,e===s&&(s+=1e-4),l>=16?l--:l++;const r=Ho(d.trim()),f=jo(e,s,r);null!=t&&null!=(u=t.cues)&&u.getCueById(f)||(a=new c(e,s,r),a.id=f,a.line=h+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),i.push(a))}return t&&i.length&&(i.sort((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line),i.forEach(e=>yn(t,e))),i}},yl=br(br({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:XhrLoader,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class AbrController{constructor(t){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=t;const e=t.config;this.bwEstimator=new EwmaBandWidthEstimator(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(Ir.FRAG_LOADING,this.onFragLoading,this),t.on(Ir.FRAG_LOADED,this.onFragLoaded,this),t.on(Ir.FRAG_BUFFERED,this.onFragBuffered,this),t.on(Ir.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Ir.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){const{hls:t}=this;t.off(Ir.FRAG_LOADING,this.onFragLoading,this),t.off(Ir.FRAG_LOADED,this.onFragLoaded,this),t.off(Ir.FRAG_BUFFERED,this.onFragBuffered,this),t.off(Ir.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Ir.LEVEL_LOADED,this.onLevelLoaded,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(t,e){var s;const r=e.frag;this.ignoreFragment(r)||(this.fragCurrent=r,this.partCurrent=null!=(s=e.part)?s:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(t,e){this.clearTimer()}getTimeToLoadFrag(t,e,s,r){return t+s/e+(r?this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const s=this.hls.config,{total:r,bwEstimate:i}=e.stats;kr(r)&&kr(i)&&(this.lastLevelLoadSec=8*r/i),e.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD)}_abandonRulesCheck(){const{fragCurrent:t,partCurrent:e,hls:s}=this,{autoLevelEnabled:r,media:i}=s;if(!t||!i)return;const n=performance.now(),a=e?e.stats:t.stats,o=e?e.duration:t.duration,l=n-a.loading.start;if(a.aborted||a.loaded&&a.loaded===a.total||0===t.level)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r||i.paused||!i.playbackRate||!i.readyState)return;const d=s.mainForwardBufferInfo;if(null===d)return;const c=this.bwEstimator.getEstimateTTFB(),u=Math.abs(i.playbackRate);if(l<=Math.max(c,o/(2*u)*1e3))return;const h=d.len/u;if(h>=2*o/u)return;const f=a.loading.first?a.loading.first-a.loading.start:-1,g=a.loaded&&f>-1,p=this.bwEstimator.getEstimate(),{levels:m,minAutoLevel:y}=s,v=m[t.level],E=a.total||Math.max(a.loaded,Math.round(o*v.maxBitrate/8));let T=l-f;T<1&&g&&(T=Math.min(l,8*a.loaded/p));const _=g?1e3*a.loaded/T:0,S=_?(E-a.loaded)/_:8*E/p+c/1e3;if(S<=h)return;const A=_?8*_:p;let L,b=Number.POSITIVE_INFINITY;for(L=t.level-1;L>y;L--){const t=m[L].maxBitrate;if(b=this.getTimeToLoadFrag(c/1e3,A,o*t,!m[L].details),b<h)break}b>=S||b>10*o||(s.nextLoadLevel=L,g?this.bwEstimator.sample(l-Math.min(c,f),a.loaded):this.bwEstimator.sampleTTFB(l),this.clearTimer(),Fr.warn(`[abr] Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} is loading too slowly;\n Time to underbuffer: ${h.toFixed(3)} s\n Estimated load time for current fragment: ${S.toFixed(3)} s\n Estimated load time for down switch fragment: ${b.toFixed(3)} s\n TTFB estimate: ${f}\n Current BW estimate: ${kr(p)?(p/1024).toFixed(3):"Unknown"} Kb/s\n New BW estimate: ${(this.bwEstimator.getEstimate()/1024).toFixed(3)} Kb/s\n Aborting and switching to level ${L}`),t.loader&&(this.fragCurrent=this.partCurrent=null,t.abortRequests()),s.trigger(Ir.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:a}))}onFragLoaded(t,{frag:e,part:s}){const r=s?s.stats:e.stats;if(e.type===un&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),this.lastLoadedFragLevel=e.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){const t=s?s.duration:e.duration,i=this.hls.levels[e.level],n=(i.loaded?i.loaded.bytes:0)+r.loaded,a=(i.loaded?i.loaded.duration:0)+t;i.loaded={bytes:n,duration:a},i.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:r,frag:e,part:s,id:e.type};this.onFragBuffered(Ir.FRAG_BUFFERED,t),e.bitrateTest=!1}}}onFragBuffered(t,e){const{frag:s,part:r}=e,i=null!=r&&r.stats.loaded?r.stats:s.stats;if(i.aborted)return;if(this.ignoreFragment(s))return;const n=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,i.loaded),i.bwEstimate=this.bwEstimator.getEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==un||"initSegment"===t.sn}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){const t=this._nextAutoLevel,e=this.bwEstimator;if(-1!==t&&!e.canEstimate())return t;let s=this.getNextABRAutoLevel();if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,s)&&e[t].loadError<=e[s].loadError)return t}return-1!==t&&(s=Math.min(t,s)),s}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:s}=this,{maxAutoLevel:r,config:i,minAutoLevel:n,media:a}=s,o=e?e.duration:t?t.duration:0,l=a&&0!==a.playbackRate?Math.abs(a.playbackRate):1,d=this.bwEstimator?this.bwEstimator.getEstimate():i.abrEwmaDefaultEstimate,c=s.mainForwardBufferInfo,u=(c?c.len:0)/l;let h=this.findBestLevel(d,n,r,u,i.abrBandWidthFactor,i.abrBandWidthUpFactor);if(h>=0)return h;Fr.trace(`[abr] ${u?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let f=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay,g=i.abrBandWidthFactor,p=i.abrBandWidthUpFactor;if(!u){const t=this.bitrateTestDelay;if(t){f=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-t,Fr.trace(`[abr] bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*f)} ms`),g=p=1}}return h=this.findBestLevel(d,n,r,u+f,g,p),Math.max(h,0)}findBestLevel(t,e,s,r,i,n){var a;const{fragCurrent:o,partCurrent:l,lastLoadedFragLevel:d}=this,{levels:c}=this.hls,u=c[d],h=!(null==u||null==(a=u.details)||!a.live),f=null==u?void 0:u.codecSet,g=l?l.duration:o?o.duration:0,p=this.bwEstimator.getEstimateTTFB()/1e3;let m=e,y=-1;for(let a=s;a>=e;a--){const e=c[a];if(!e||f&&e.codecSet!==f){e&&(m=Math.min(a,m),y=Math.max(a,y));continue}-1!==y&&Fr.trace(`[abr] Skipped level(s) ${m}-${y} with CODECS:"${c[y].attrs.CODECS}"; not compatible with "${u.attrs.CODECS}"`);const s=e.details,o=(l?null==s?void 0:s.partTarget:null==s?void 0:s.averagetargetduration)||g;let v;v=a<=d?i*t:n*t;const E=c[a].maxBitrate,T=this.getTimeToLoadFrag(p,v,E*o,void 0===s);if(Fr.trace(`[abr] level:${a} adjustedbw-bitrate:${Math.round(v-E)} avgDuration:${o.toFixed(1)} maxFetchDuration:${r.toFixed(1)} fetchDuration:${T.toFixed(1)}`),v>E&&(0===T||!kr(T)||h&&!this.bitrateTestDelay||T<r))return a}return-1}set nextAutoLevel(t){this._nextAutoLevel=t}},bufferController:class BufferController{constructor(t){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=()=>{const{media:t,mediaSource:e}=this;Fr.log("[buffer-controller]: Media source opened"),t&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(Ir.MEDIA_ATTACHED,{media:t})),e&&e.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{Fr.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{Fr.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:t,_objectUrl:e}=this;t&&t.src!==e&&Fr.error(`Media element src was set while attaching MediaSource (${e} > ${t.src})`)},this.hls=t,this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null}registerListeners(){const{hls:t}=this;t.on(Ir.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Ir.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Ir.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Ir.BUFFER_RESET,this.onBufferReset,this),t.on(Ir.BUFFER_APPENDING,this.onBufferAppending,this),t.on(Ir.BUFFER_CODECS,this.onBufferCodecs,this),t.on(Ir.BUFFER_EOS,this.onBufferEos,this),t.on(Ir.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Ir.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Ir.FRAG_PARSED,this.onFragParsed,this),t.on(Ir.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(Ir.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Ir.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Ir.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Ir.BUFFER_RESET,this.onBufferReset,this),t.off(Ir.BUFFER_APPENDING,this.onBufferAppending,this),t.off(Ir.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Ir.BUFFER_EOS,this.onBufferEos,this),t.off(Ir.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Ir.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Ir.FRAG_PARSED,this.onFragParsed,this),t.off(Ir.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new BufferOperationQueue(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestParsed(t,e){let s=2;(e.audio&&!e.video||!e.altAudio)&&(s=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=s,this.details=null,Fr.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")}onMediaAttaching(t,e){const s=this.media=e.media;if(s&&Lo){const t=this.mediaSource=new Lo;t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),s.src=self.URL.createObjectURL(t),this._objectUrl=s.src,s.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:e,_objectUrl:s}=this;if(e){if(Fr.log("[buffer-controller]: media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){Fr.warn(`[buffer-controller]: onMediaDetaching: ${t.message} while calling endOfStream`)}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),t&&(t.removeEventListener("emptied",this._onMediaEmptied),s&&self.URL.revokeObjectURL(s),t.src===s?(t.removeAttribute("src"),t.load()):Fr.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(Ir.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(t=>{const e=this.sourceBuffer[t];try{e&&(this.removeBufferListeners(t),this.mediaSource&&this.mediaSource.removeSourceBuffer(e),this.sourceBuffer[t]=void 0)}catch(e){Fr.warn(`[buffer-controller]: Failed to reset the ${t} buffer`,e)}}),this._initSourceBuffer()}onBufferCodecs(t,e){const s=this.getSourceBufferTypes().length;Object.keys(e).forEach(t=>{if(s){const s=this.tracks[t];if(s&&"function"==typeof s.buffer.changeType){const{id:r,codec:i,levelCodec:n,container:a,metadata:o}=e[t],l=(s.levelCodec||s.codec).replace(bo,"$1"),d=(n||i).replace(bo,"$1");if(l!==d){const e=`${a};codecs=${n||i}`;this.appendChangeType(t,e),Fr.log(`[buffer-controller]: switching codec ${l} to ${d}`),this.tracks[t]={buffer:s.buffer,codec:i,container:a,levelCodec:n,metadata:o,id:r}}}}else this.pendingTracks[t]=e[t]}),s||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())}appendChangeType(t,e){const{operationQueue:s}=this,r={execute:()=>{const r=this.sourceBuffer[t];r&&(Fr.log(`[buffer-controller]: changing ${t} sourceBuffer type to ${e}`),r.changeType(e)),s.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{Fr.warn(`[buffer-controller]: Failed to change ${t} SourceBuffer type`,e)}};s.append(r,t)}onBufferAppending(t,e){const{hls:s,operationQueue:r,tracks:i}=this,{data:n,type:a,frag:o,part:l,chunkMeta:d}=e,c=d.buffering[a],u=self.performance.now();c.start=u;const h=o.stats.buffering,f=l?l.stats.buffering:null;0===h.start&&(h.start=u),f&&0===f.start&&(f.start=u);const g=i.audio;let p=!1;"audio"===a&&"audio/mpeg"===(null==g?void 0:g.container)&&(p=!this.lastMpegAudioChunk||1===d.id||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const m=o.start,y={execute:()=>{if(c.executeStart=self.performance.now(),p){const t=this.sourceBuffer[a];if(t){const e=m-t.timestampOffset;Math.abs(e)>=.1&&(Fr.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${m} (delta: ${e}) sn: ${o.sn})`),t.timestampOffset=m)}}this.appendExecutor(n,a)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();c.executeEnd=c.end=t,0===h.first&&(h.first=t),f&&0===f.first&&(f.first=t);const{sourceBuffer:e}=this,s={};for(const t in e)s[t]=BufferHelper.getBuffered(e[t]);this.appendError=0,this.hls.trigger(Ir.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:d,parent:o.type,timeRanges:s})},onError:t=>{Fr.error(`[buffer-controller]: Error encountered while trying to append to the ${a} SourceBuffer`,t);const e={type:Dr.MEDIA_ERROR,parent:o.type,details:Cr.BUFFER_APPEND_ERROR,frag:o,part:l,chunkMeta:d,error:t,err:t,fatal:!1};t.code===DOMException.QUOTA_EXCEEDED_ERR?e.details=Cr.BUFFER_FULL_ERROR:(this.appendError++,e.details=Cr.BUFFER_APPEND_ERROR,this.appendError>s.config.appendErrorMaxRetry&&(Fr.error(`[buffer-controller]: Failed ${s.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),e.fatal=!0)),s.trigger(Ir.ERROR,e)}};r.append(y,a)}onBufferFlushing(t,e){const{operationQueue:s}=this,r=t=>({execute:this.removeExecutor.bind(this,t,e.startOffset,e.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(Ir.BUFFER_FLUSHED,{type:t})},onError:e=>{Fr.warn(`[buffer-controller]: Failed to remove from ${t} SourceBuffer`,e)}});e.type?s.append(r(e.type),e.type):this.getSourceBufferTypes().forEach(t=>{s.append(r(t),t)})}onFragParsed(t,e){const{frag:s,part:r}=e,i=[],n=r?r.elementaryStreams:s.elementaryStreams;n[Hr]?i.push("audiovideo"):(n[Gr]&&i.push("audio"),n[$r]&&i.push("video"));0===i.length&&Fr.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(()=>{const t=self.performance.now();s.stats.buffering.end=t,r&&(r.stats.buffering.end=t);const e=r?r.stats:s.stats;this.hls.trigger(Ir.FRAG_BUFFERED,{frag:s,part:r,stats:e,id:s.type})},i)}onFragChanged(t,e){this.flushBackBuffer()}onBufferEos(t,e){this.getSourceBufferTypes().reduce((t,s)=>{const r=this.sourceBuffer[s];return!r||e.type&&e.type!==s||(r.ending=!0,r.ended||(r.ended=!0,Fr.log(`[buffer-controller]: ${s} sourceBuffer now EOS`))),t&&!(r&&!r.ended)},!0)&&(Fr.log("[buffer-controller]: Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(t=>{const e=this.sourceBuffer[t];e&&(e.ending=!1)});const{mediaSource:t}=this;t&&"open"===t.readyState?(Fr.log("[buffer-controller]: Calling mediaSource.endOfStream()"),t.endOfStream()):t&&Fr.info("[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: "+t.readyState)}))}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}flushBackBuffer(){const{hls:t,details:e,media:s,sourceBuffer:r}=this;if(!s||null===e)return;const i=this.getSourceBufferTypes();if(!i.length)return;const n=e.live&&null!==t.config.liveBackBufferLength?t.config.liveBackBufferLength:t.config.backBufferLength;if(!kr(n)||n<0)return;const a=s.currentTime,o=e.levelTargetDuration,l=Math.max(n,o),d=Math.floor(a/o)*o-l;i.forEach(s=>{const i=r[s];if(i){const r=BufferHelper.getBuffered(i);if(r.length>0&&d>r.start(0)){if(t.trigger(Ir.BACK_BUFFER_REACHED,{bufferEnd:d}),e.live)t.trigger(Ir.LIVE_BACK_BUFFER_REACHED,{bufferEnd:d});else if(i.ended&&r.end(r.length-1)-a<2*o)return void Fr.info(`[buffer-controller]: Cannot flush ${s} back buffer while SourceBuffer is in ended state`);t.trigger(Ir.BUFFER_FLUSHING,{startOffset:0,endOffset:d,type:s})}}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:t,hls:e,media:s,mediaSource:r}=this,i=t.fragments[0].start+t.totalduration,n=s.duration,a=kr(r.duration)?r.duration:0;t.live&&e.config.liveDurationInfinity?(Fr.log("[buffer-controller]: Media Source duration is set to Infinity"),r.duration=1/0,this.updateSeekableRange(t)):(i>a&&i>n||!kr(n))&&(Fr.log("[buffer-controller]: Updating Media Source duration to "+i.toFixed(3)),r.duration=i)}updateSeekableRange(t){const e=this.mediaSource,s=t.fragments;if(s.length&&t.live&&null!=e&&e.setLiveSeekableRange){const r=Math.max(0,s[0].start),i=Math.max(r,r+t.totalduration);e.setLiveSeekableRange(r,i)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:e,pendingTracks:s}=this,r=Object.keys(s).length;if(r&&!t||2===r){this.createSourceBuffers(s),this.pendingTracks={};const t=this.getSourceBufferTypes();if(t.length)this.hls.trigger(Ir.BUFFER_CREATED,{tracks:this.tracks}),t.forEach(t=>{e.executeNext(t)});else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}}createSourceBuffers(t){const{sourceBuffer:e,mediaSource:s}=this;if(!s)throw Error("createSourceBuffers called when mediaSource was null");for(const r in t)if(!e[r]){const i=t[r];if(!i)throw Error(`source buffer exists for track ${r}, however track does not`);const n=i.levelCodec||i.codec,a=`${i.container};codecs=${n}`;Fr.log(`[buffer-controller]: creating sourceBuffer(${a})`);try{const t=e[r]=s.addSourceBuffer(a),o=r;this.addBufferListener(o,"updatestart",this._onSBUpdateStart),this.addBufferListener(o,"updateend",this._onSBUpdateEnd),this.addBufferListener(o,"error",this._onSBUpdateError),this.tracks[r]={buffer:t,codec:n,container:i.container,levelCodec:i.levelCodec,metadata:i.metadata,id:i.id}}catch(t){Fr.error("[buffer-controller]: error while trying to add sourceBuffer: "+t.message),this.hls.trigger(Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,mimeType:a})}}}_onSBUpdateStart(t){const{operationQueue:e}=this;e.current(t).onStart()}_onSBUpdateEnd(t){const{operationQueue:e}=this;e.current(t).onComplete(),e.shiftAndExecuteNext(t)}_onSBUpdateError(t,e){const s=new Error(t+" SourceBuffer error");Fr.error("[buffer-controller]: "+s,e),this.hls.trigger(Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.BUFFER_APPENDING_ERROR,error:s,fatal:!1});const r=this.operationQueue.current(t);r&&r.onError(e)}removeExecutor(t,e,s){const{media:r,mediaSource:i,operationQueue:n,sourceBuffer:a}=this,o=a[t];if(!r||!i||!o)return Fr.warn(`[buffer-controller]: Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void n.shiftAndExecuteNext(t);const l=kr(r.duration)?r.duration:1/0,d=kr(i.duration)?i.duration:1/0,c=Math.max(0,e),u=Math.min(s,l,d);u>c&&!o.ending?(o.ended=!1,Fr.log(`[buffer-controller]: Removing [${c},${u}] from the ${t} SourceBuffer`),o.remove(c,u)):n.shiftAndExecuteNext(t)}appendExecutor(t,e){const{operationQueue:s,sourceBuffer:r}=this,i=r[e];if(!i)return Fr.warn(`[buffer-controller]: Attempting to append to the ${e} SourceBuffer, but it does not exist`),void s.shiftAndExecuteNext(e);i.ended=!1,i.appendBuffer(t)}blockBuffers(t,e=this.getSourceBufferTypes()){if(!e.length)return Fr.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(t);const{operationQueue:s}=this,r=e.map(t=>s.appendBlocker(t));Promise.all(r).then(()=>{t(),e.forEach(t=>{const e=this.sourceBuffer[t];null!=e&&e.updating||s.shiftAndExecuteNext(t)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(t,e,s){const r=this.sourceBuffer[t];if(!r)return;const i=s.bind(this,t);this.listeners[t].push({event:e,listener:i}),r.addEventListener(e,i)}removeBufferListeners(t){const e=this.sourceBuffer[t];e&&this.listeners[t].forEach(t=>{e.removeEventListener(t.event,t.listener)})}},capLevelController:CapLevelController,errorController:class ErrorController{constructor(t){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=t,this.log=Fr.log.bind(Fr,"[info]:"),this.warn=Fr.warn.bind(Fr,"[warning]:"),this.error=Fr.error.bind(Fr,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(Ir.ERROR,this.onError,this),t.on(Ir.MANIFEST_LOADING,this.onManifestLoading,this)}unregisterListeners(){const t=this.hls;t&&(t.off(Ir.ERROR,this.onError,this),t.off(Ir.ERROR,this.onErrorOut,this),t.off(Ir.MANIFEST_LOADING,this.onManifestLoading,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(t){this.playlistError=0}stopLoad(){}getVariantLevelIndex(t){return(null==t?void 0:t.type)===un?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onError(t,e){var s;if(e.fatal)return;const r=this.hls,i=e.context;switch(e.details){case Cr.FRAG_LOAD_ERROR:case Cr.FRAG_LOAD_TIMEOUT:case Cr.KEY_LOAD_ERROR:case Cr.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case Cr.FRAG_GAP:case Cr.FRAG_PARSING_ERROR:case Cr.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Wn);case Cr.LEVEL_EMPTY_ERROR:case Cr.LEVEL_PARSING_ERROR:{var n,a;const t=e.parent===un?e.level:r.loadLevel;e.details===Cr.LEVEL_EMPTY_ERROR&&null!=(n=e.context)&&null!=(a=n.levelDetails)&&a.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case Cr.LEVEL_LOAD_ERROR:case Cr.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==i?void 0:i.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,i.level)));case Cr.AUDIO_TRACK_LOAD_ERROR:case Cr.AUDIO_TRACK_LOAD_TIMEOUT:case Cr.SUBTITLE_LOAD_ERROR:case Cr.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const t=r.levels[r.loadLevel];if(t&&(i.type===dn&&i.groupId===t.audioGroupId||i.type===cn&&i.groupId===t.textGroupId))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.loadLevel),e.errorAction.action=Wn,void(e.errorAction.flags=Xn)}return;case Cr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=r.levels[r.loadLevel],s=null==t?void 0:t.attrs["HDCP-LEVEL"];s&&(e.errorAction={action:Wn,flags:Qn,hdcpLevel:s})}return;case Cr.BUFFER_ADD_CODEC_ERROR:case Cr.REMUX_ALLOC_ERROR:return void(e.errorAction=this.getLevelSwitchAction(e,null!=(s=e.level)?s:r.loadLevel));case Cr.INTERNAL_EXCEPTION:case Cr.BUFFER_APPENDING_ERROR:case Cr.BUFFER_APPEND_ERROR:case Cr.BUFFER_FULL_ERROR:case Cr.LEVEL_SWITCH_ERROR:case Cr.BUFFER_STALLED_ERROR:case Cr.BUFFER_SEEK_OVER_HOLE:case Cr.BUFFER_NUDGE_ON_STALL:return void(e.errorAction={action:jn,flags:zn})}if(e.type===Dr.KEY_SYSTEM_ERROR){const t=this.getVariantLevelIndex(e.frag);return e.levelRetry=!1,void(e.errorAction=this.getLevelSwitchAction(e,t))}}getPlaylistRetryOrSwitchAction(t,e){var s,r;const i=Un(this.hls.config.playlistLoadPolicy,t),n=this.playlistError++,a=null==(s=t.response)?void 0:s.code;return $n(i,n,Nn(t),a)?{action:Yn,flags:zn,retryConfig:i,retryCount:n}:null!=(r=t.context)&&r.deliveryDirectives?{action:jn,flags:zn,retryConfig:i||{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},retryCount:n}:this.getLevelSwitchAction(t,e)}getFragRetryOrSwitchAction(t){const e=this.hls,s=this.getVariantLevelIndex(t.frag),r=e.levels[s],{fragLoadPolicy:i,keyLoadPolicy:n}=e.config,a=Un(t.details.startsWith("key")?n:i,t),o=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(r){var l;t.details!==Cr.FRAG_GAP&&r.fragmentError++;const e=null==(l=t.response)?void 0:l.code;if($n(a,o,Nn(t),e))return{action:Yn,flags:zn,retryConfig:a,retryCount:o}}const d=this.getLevelSwitchAction(t,s);return a&&(d.retryConfig=a,d.retryCount=o),d}getLevelSwitchAction(t,e){const s=this.hls;null==e&&(e=s.loadLevel);const r=this.hls.levels[e];if(r&&(r.loadError++,s.autoLevelEnabled)){var i,n;let e=-1;const a=s.levels,o=null==(i=t.frag)?void 0:i.type,{type:l,groupId:d}=null!=(n=t.context)?n:{};for(let i=a.length;i--;){const n=(i+s.loadLevel)%a.length;if(n!==s.loadLevel&&0===a[n].loadError){const s=a[n];if(t.details===Cr.FRAG_GAP&&t.frag){const e=a[n].details;if(e){const s=Kn(t.frag,e.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(l===dn&&d===s.audioGroupId||l===cn&&d===s.textGroupId)continue;if(o===hn&&r.audioGroupId===s.audioGroupId||o===fn&&r.textGroupId===s.textGroupId)continue}e=n;break}}if(e>-1&&s.loadLevel!==e)return t.levelRetry=!0,{action:Wn,flags:zn,nextAutoLevel:e}}return{action:Wn,flags:Xn}}onErrorOut(t,e){var s;switch(null==(s=e.errorAction)?void 0:s.action){case jn:break;case Wn:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===Cr.FRAG_GAP||(e.fatal=!0)}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,s=t.errorAction;if(!s)return;const{flags:r,hdcpLevel:i,nextAutoLevel:n}=s;switch(r){case zn:this.switchLevel(t,n);break;case Xn:s.resolved||(s.resolved=this.redundantFailover(t));break;case Qn:i&&(e.maxHdcpLevel=wn[wn.indexOf(i)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)}s.resolved||this.switchLevel(t,n)}switchLevel(t,e){void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}redundantFailover(t){const{hls:e,penalizedRenditions:s}=this,r=t.parent===un?t.level:e.loadLevel,i=e.levels[r],n=i.url.length,a=t.frag?t.frag.urlId:i.urlId;i.urlId!==a||t.frag&&!i.details||this.penalizeRendition(i,t);for(let o=1;o<n;o++){const l=(a+o)%n,d=s[l];if(!d||Zn(d,t,s[a]))return this.warn(`Switching to Redundant Stream ${l+1}/${n}: "${i.url[l]}" after ${t.details}`),this.playlistError=0,e.levels.forEach(t=>{t.urlId=l}),e.nextLoadLevel=r,!0}return!1}penalizeRendition(t,e){const{penalizedRenditions:s}=this,r=s[t.urlId]||{lastErrorPerfMs:0,errors:[],details:void 0};r.lastErrorPerfMs=performance.now(),r.errors.push(e),r.details=t.details,s[t.urlId]=r}},fpsController:class FPSController{constructor(t){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=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(Ir.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(Ir.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const s=this.hls.config;if(s.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}checkFPS(t,e,s){const r=performance.now();if(e){if(this.lastTime){const t=r-this.lastTime,i=s-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*i/t,o=this.hls;if(o.trigger(Ir.FPS_DROP,{currentDropped:i,currentDecoded:n,totalDroppedFrames:s}),a>0&&i>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;Fr.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(Ir.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=s,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:ei,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!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}}},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:ml,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 SubtitleStreamController extends BaseStreamController{constructor(t,e,s){super(t,e,s,"[subtitle-stream-controller]",fn),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){const{hls:t}=this;t.on(Ir.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Ir.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ir.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Ir.ERROR,this.onError,this),t.on(Ir.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(Ir.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(Ir.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(Ir.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(Ir.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Ir.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(Ir.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Ir.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ir.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Ir.ERROR,this.onError,this),t.off(Ir.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(Ir.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(Ir.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(Ir.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(Ir.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Ir.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(t){this.stopLoad(),this.state=Ea,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:s,success:r}=e;if(this.fragPrevious=s,this.state=Ea,!r)return;const i=this.tracksBuffered[this.currentTrackId];if(!i)return;let n;const a=s.start;for(let t=0;t<i.length;t++)if(a>=i[t].start&&a<=i[t].end){n=i[t];break}const o=s.start+s.duration;n?n.end=o:(n={start:a,end:o},i.push(n)),this.fragmentTracker.fragBuffered(s)}onBufferFlushing(t,e){const{startOffset:s,endOffset:r}=e;if(0===s&&r!==Number.POSITIVE_INFINITY){const{currentTrackId:t,levels:i}=this;if(!i.length||!i[t]||!i[t].details)return;const n=r-i[t].details.targetduration;if(n<=0)return;e.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(t=>{for(let e=0;e<t.length;)if(t[e].end<=n)t.shift();else{if(!(t[e].start<n))break;t[e].start=n,e++}}),this.fragmentTracker.removeFragmentsInRange(s,n,fn)}}onFragBuffered(t,e){var s;this.loadedmetadata||e.frag.type!==un||null!=(s=this.media)&&s.buffered.length&&(this.loadedmetadata=!0)}onError(t,e){const s=e.frag;(null==s?void 0:s.type)===fn&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==va&&(this.state=Ea))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){_o(this.levels,e)?this.levels=e.map(t=>new Level(t)):(this.tracksBuffered=[],this.levels=e.map(t=>{const e=new Level(t);return this.tracksBuffered[e.id]=[],e}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,fn),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){if(this.currentTrackId=e.id,!this.levels.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.setInterval(500)}onSubtitleTrackLoaded(t,e){var s;const{details:r,id:i}=e,{currentTrackId:n,levels:a}=this;if(!a.length)return;const o=a[n];if(i>=a.length||i!==n||!o)return;this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(r.live||null!=(s=o.details)&&s.live){const t=this.mainDetails;if(r.deltaUpdateFailed||!t)return;const e=t.fragments[0];o.details?(l=this.alignPlaylists(r,o.details),0===l&&e&&(l=e.start,Mn(r,l))):r.hasProgramDateTime&&t.hasProgramDateTime?(ma(r,t),l=r.fragments[0].start):e&&(l=e.start,Mn(r,l))}if(o.details=r,this.levelLastLoaded=i,this.startFragRequested||!this.mainDetails&&r.live||this.setStartPosition(o.details,l),this.tick(),r.live&&!this.fragCurrent&&this.media&&this.state===Ea){Kn(null,r.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(t){const{frag:e,payload:s}=t,r=e.decryptdata,i=this.hls;if(!this.fragContextChanged(e)&&s&&s.byteLength>0&&r&&r.key&&r.iv&&"AES-128"===r.method){const t=performance.now();this.decrypter.decrypt(new Uint8Array(s),r.key.buffer,r.iv.buffer).catch(t=>{throw i.trigger(Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t}).then(s=>{const r=performance.now();i.trigger(Ir.FRAG_DECRYPTED,{frag:e,payload:s,stats:{tstart:t,tdecrypt:r}})}).catch(t=>{this.warn(`${t.name}: ${t.message}`),this.state=Ea})}}doTick(){if(this.media){if(this.state===Ea){const{currentTrackId:t,levels:e}=this,s=e[t];if(!e.length||!s||!s.details)return;const r=s.details,i=r.targetduration,{config:n}=this,a=this.getLoadPosition(),o=BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],a-i,n.maxBufferHole),{end:l,len:d}=o,c=this.getFwdBufferInfo(this.media,un);if(d>this.getMaxBufferLength(null==c?void 0:c.len)+i)return;const u=r.fragments,h=u.length,f=r.edge;let g=null;const p=this.fragPrevious;if(l<f){const{maxFragLookUpTolerance:t}=n;g=Kn(p,u,Math.max(u[0].start,l),t),!g&&p&&p.start<u[0].start&&(g=u[0])}else g=u[h-1];if(!g)return;g=this.mapToInitFragWhenRequired(g),this.fragmentTracker.getState(g)===sa&&this.loadFragment(g,s,l)}}else this.state=Ea}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.max(e,t):e}loadFragment(t,e,s){this.fragCurrent=t,"initSegment"===t.sn?this._loadInitSegment(t,e):(this.startFragRequested=!0,super.loadFragment(t,e,s))}get mediaBufferTimeRanges(){return new BufferableInstance(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class SubtitleTrackController extends BasePlaylistController{constructor(t){super(t,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.trackChangeListener=()=>this.onTextTracksChanged(),this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes(this.trackId)}registerListeners(){const{hls:t}=this;t.on(Ir.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Ir.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ir.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Ir.LEVEL_LOADING,this.onLevelLoading,this),t.on(Ir.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Ir.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(Ir.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Ir.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Ir.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ir.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Ir.LEVEL_LOADING,this.onLevelLoading,this),t.off(Ir.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Ir.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(Ir.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.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(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,t)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);Ao(this.media.textTracks).forEach(t=>{vn(t)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:s,details:r}=e,{trackId:i}=this,n=this.tracksInGroup[i];if(!n)return void this.warn("Invalid subtitle track id "+s);const a=n.details;n.details=e.details,this.log(`subtitle track ${s} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(null==e||!e.textGroupIds)return;const s=e.textGroupIds[e.urlId],r=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==s){const t=this.tracks.filter(t=>!s||t.groupId===s);this.tracksInGroup=t;const e=this.findTrackId(null==r?void 0:r.name)||this.findTrackId();this.groupId=s||null;const i={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${s}" group-id`),this.hls.trigger(Ir.SUBTITLE_TRACKS_UPDATED,i),-1!==e&&this.setSubtitleTrack(e,r)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId,r)}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const r=e[s];if((!this.selectDefaultTrack||r.default)&&(!t||t===r.name))return r.id}return-1}onError(t,e){!e.fatal&&e.context&&e.context.type===cn&&e.context.id===this.trackId&&e.context.groupId===this.groupId&&this.checkRetry(e)}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1;const e=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(t,e)}loadPlaylist(t){super.loadPlaylist();const e=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(e)){const s=e.id,r=e.groupId;let i=e.url;if(t)try{i=t.addDirectives(i)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}this.log("Loading subtitle playlist for id "+s),this.hls.trigger(Ir.SUBTITLE_TRACK_LOADING,{url:i,id:s,groupId:r,deliveryDirectives:t||null})}}toggleTrackModes(t){const{media:e,trackId:s}=this;if(!e)return;const r=Ao(e.textTracks),i=r.filter(t=>t.groupId===this.groupId);if(-1===t)[].slice.call(r).forEach(t=>{t.mode="disabled"});else{const t=i[s];t&&(t.mode="disabled")}const n=i[t];n&&(n.mode=this.subtitleDisplay?"showing":"hidden")}setSubtitleTrack(t,e){var s;const r=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(this.trackId!==t&&this.toggleTrackModes(t),this.trackId===t&&(-1===t||null!=(s=r[t])&&s.details)||t<-1||t>=r.length)return;this.clearTimer();const i=r[t];if(this.log("Switching to subtitle-track "+t+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:"")),this.trackId=t,i){const{id:t,groupId:s="",name:r,type:n,url:a}=i;this.hls.trigger(Ir.SUBTITLE_TRACK_SWITCH,{id:t,groupId:s,name:r,type:n,url:a});const o=this.switchParams(i.url,null==e?void 0:e.details);this.loadPlaylist(o)}else this.hls.trigger(Ir.SUBTITLE_TRACK_SWITCH,{id:t})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1;const e=Ao(this.media.textTracks);for(let s=0;s<e.length;s++)if("hidden"===e[s].mode)t=s;else if("showing"===e[s].mode){t=s;break}this.subtitleTrack!==t&&(this.subtitleTrack=t)}},timelineController:class TimelineController{constructor(t){if(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.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=t,this.config=t.config,this.Cues=t.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}},this.config.enableCEA708Captions){const t=new OutputFilter(this,"textTrack1"),e=new OutputFilter(this,"textTrack2"),s=new OutputFilter(this,"textTrack3"),r=new OutputFilter(this,"textTrack4");this.cea608Parser1=new Cea608Parser(1,t,e),this.cea608Parser2=new Cea608Parser(3,s,r)}t.on(Ir.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Ir.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ir.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Ir.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(Ir.FRAG_LOADING,this.onFragLoading,this),t.on(Ir.FRAG_LOADED,this.onFragLoaded,this),t.on(Ir.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(Ir.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(Ir.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Ir.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(Ir.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(Ir.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Ir.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ir.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Ir.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(Ir.FRAG_LOADING,this.onFragLoading,this),t.off(Ir.FRAG_LOADED,this.onFragLoaded,this),t.off(Ir.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(Ir.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(Ir.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(Ir.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(Ir.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}addCues(t,e,s,r,i){let n=!1;for(let t=i.length;t--;){const r=i[t],c=(a=r[0],o=r[1],l=e,d=s,Math.min(o,d)-Math.max(a,l));if(c>=0&&(r[0]=Math.min(r[0],e),r[1]=Math.max(r[1],s),n=!0,c/(s-e)>.5))return}var a,o,l,d;if(n||i.push([e,s]),this.config.renderTextTracksNatively){const i=this.captionsTracks[t];this.Cues.newCue(i,e,s,r)}else{const i=this.Cues.newCue(null,e,s,r);this.hls.trigger(Ir.CUES_PARSED,{type:"captions",cues:i,track:t})}}onInitPtsFound(t,{frag:e,id:s,initPTS:r,timescale:i}){const{unparsedVttFrags:n}=this;"main"===s&&(this.initPTS[e.cc]={baseTime:r,timescale:i}),n.length&&(this.unparsedVttFrags=[],n.forEach(t=>{this.onFragLoaded(Ir.FRAG_LOADED,t)}))}getExistingTrack(t){const{media:e}=this;if(e)for(let s=0;s<e.textTracks.length;s++){const r=e.textTracks[s];if(r[t])return r}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:s,media:r}=this,{label:i,languageCode:n}=e[t],a=this.getExistingTrack(t);if(a)s[t]=a,vn(s[t]),mn(s[t],r);else{const e=this.createTextTrack("captions",i,n);e&&(e[t]=!0,s[t]=e)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const s={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=s,this.hls.trigger(Ir.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(t,e,s){const r=this.media;if(r)return r.addTextTrack(t,e,s)}onMediaAttaching(t,e){this.media=e.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:t}=this;Object.keys(t).forEach(e=>{vn(t[e]),delete t[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){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.unparsedVttFrags||[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let t=0;t<e.length;t++)vn(e[t])}onSubtitleTracksUpdated(t,e){const s=e.subtitleTracks||[],r=s.some(t=>"stpp.ttml.im1t"===t.textCodec);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(_o(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const t=this.media?this.media.textTracks:null;this.tracks.forEach((e,s)=>{let r;if(t&&s<t.length){let s=null;for(let r=0;r<t.length;r++)if(rl(t[r],e)){s=t[r];break}s&&(r=s)}if(r)vn(r);else{const t=this._captionsOrSubtitlesFromCharacteristics(e);r=this.createTextTrack(t,e.name,e.lang),r&&(r.mode="disabled")}r&&(r.groupId=e.groupId,this.textTracks.push(r))})}else if(this.tracks.length){const t=this.tracks.map(t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}));this.hls.trigger(Ir.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}_captionsOrSubtitlesFromCharacteristics(t){if(t.attrs.CHARACTERISTICS){const e=/transcribes-spoken-dialog/gi.test(t.attrs.CHARACTERISTICS),s=/describes-music-and-sound/gi.test(t.attrs.CHARACTERISTICS);if(e&&s)return"captions"}return"subtitles"}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const s="textTrack"+e[1],r=this.captionsProperties[s];r&&(r.label=t.name,t.lang&&(r.languageCode=t.lang),r.media=t)})}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){const{cea608Parser1:s,cea608Parser2:r,lastSn:i,lastPartIndex:n}=this;if(this.enabled&&s&&r&&e.frag.type===un){var a,o;const t=e.frag.sn,l=null!=(a=null==e||null==(o=e.part)?void 0:o.index)?a:-1;t===i+1||t===i&&l===n+1||(s.reset(),r.reset()),this.lastSn=t,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:s,payload:r}=e,{initPTS:i,unparsedVttFrags:n}=this;if(s.type===fn)if(r.byteLength){if(!i[s.cc])return n.push(e),void(i.length&&this.hls.trigger(Ir.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Missing initial subtitle PTS")}));const t=s.decryptdata,a="stats"in e;if(null==t||!t.encrypted||a){const t=this.tracks[s.level],e=this.vttCCs;e[s.cc]||(e[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),t&&"stpp.ttml.im1t"===t.textCodec?this._parseIMSC1(s,r):this._parseVTTs(s,r,e)}}else this.hls.trigger(Ir.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const s=this.hls;Qo(e,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),s.trigger(Ir.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},e=>{Fr.log("Failed to parse IMSC1: "+e),s.trigger(Ir.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})})}_parseVTTs(t,e,s){var r;const i=this.hls;Wo(null!=(r=t.initSegment)&&r.data?Oi(t.initSegment.data,new Uint8Array(e)):e,this.initPTS[t.cc],s,t.cc,t.start,e=>{this._appendCues(e,t.level),i.trigger(Ir.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},s=>{this._fallbackToIMSC1(t,e),Fr.log("Failed to parse VTT cue: "+s),i.trigger(Ir.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:s})})}_fallbackToIMSC1(t,e){const s=this.tracks[t.level];s.textCodec||Qo(e,this.initPTS[t.cc],()=>{s.textCodec="stpp.ttml.im1t",this._parseIMSC1(t,e)},()=>{s.textCodec="wvtt"})}_appendCues(t,e){const s=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[e];if(!s||"disabled"===s.mode)return;t.forEach(t=>yn(s,t))}else{const r=this.tracks[e];if(!r)return;const i=r.default?"default":"subtitles"+e;s.trigger(Ir.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,e){const{frag:s}=e;if(s.type===fn){if(!this.initPTS[s.cc])return void this.unparsedVttFrags.push(e);this.onFragLoaded(Ir.FRAG_LOADED,e)}}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){const{cea608Parser1:s,cea608Parser2:r}=this;if(!this.enabled||!s||!r)return;const{frag:i,samples:n}=e;if(i.type!==un||"NONE"!==this.closedCaptionsForLevel(i))for(let t=0;t<n.length;t++){const e=n[t].bytes;if(e){const i=this.extractCea608Data(e);s.addData(n[t].pts,i[0]),r.addData(n[t].pts,i[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:s,endOffsetSubtitles:r,type:i}){const{media:n}=this;if(n&&!(n.currentTime<s)){if(!i||"video"===i){const{captionsTracks:t}=this;Object.keys(t).forEach(r=>En(t[r],e,s))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==r){const{textTracks:t}=this;Object.keys(t).forEach(s=>En(t[s],e,r))}}}extractCea608Data(t){const e=[[],[]],s=31&t[0];let r=2;for(let i=0;i<s;i++){const s=t[r++],i=127&t[r++],n=127&t[r++];if(0===i&&0===n)continue;if(0!=(4&s)){const t=3&s;0!==t&&1!==t||(e[t].push(i),e[t].push(n))}}return e}},audioStreamController:class AudioStreamController extends BaseStreamController{constructor(t,e,s){super(t,e,s,"[audio-stream-controller]",hn),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:t}=this;t.on(Ir.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Ir.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ir.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Ir.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(Ir.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Ir.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(Ir.ERROR,this.onError,this),t.on(Ir.BUFFER_RESET,this.onBufferReset,this),t.on(Ir.BUFFER_CREATED,this.onBufferCreated,this),t.on(Ir.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Ir.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Ir.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(Ir.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Ir.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ir.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Ir.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(Ir.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Ir.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(Ir.ERROR,this.onError,this),t.off(Ir.BUFFER_RESET,this.onBufferReset,this),t.off(Ir.BUFFER_CREATED,this.onBufferCreated,this),t.off(Ir.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Ir.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(Ir.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(t,{frag:e,id:s,initPTS:r,timescale:i}){if("main"===s){const t=e.cc;this.initPTS[e.cc]={baseTime:r,timescale:i},this.log(`InitPTS for cc: ${t} found from main: ${r}`),this.videoTrackCC=t,this.state===ka&&this.tick()}}startLoad(t){if(!this.levels)return this.startPosition=t,void(this.state=va);const e=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),e>0&&-1===t?(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e,this.state=Ea):(this.loadedmetadata=!1,this.state=Aa),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}doTick(){switch(this.state){case Ea:this.doTickIdle();break;case Aa:{var t;const{levels:e,trackId:s}=this,r=null==e||null==(t=e[s])?void 0:t.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=ka}break}case Sa:{var e;const t=performance.now(),s=this.retryDate;(!s||t>=s||null!=(e=this.media)&&e.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=Ea);break}case ka:{const t=this.waitingData;if(t){const{frag:e,part:s,cache:r,complete:i}=t;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=_a;const t={frag:e,part:s,payload:r.flush(),networkDetails:null};this._handleFragmentLoadProgress(t),i&&super._handleFragmentLoadComplete(t)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${e.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const t=this.getLoadPosition(),s=BufferHelper.bufferInfo(this.mediaBuffer,t,this.config.maxBufferHole);Vn(s.end,this.config.maxFragLookUpTolerance,e)<0&&(this.log(`Waiting fragment cc (${e.cc}) @ ${e.start} cancelled because another fragment at ${s.end} is needed`),this.clearWaitingFragment())}}else this.state=Ea}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=Ea)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){const{hls:t,levels:e,media:s,trackId:r}=this,i=t.config;if(null==e||!e[r])return;if(!s&&(this.startFragRequested||!i.startFragPrefetch))return;const n=e[r],a=n.details;if(!a||a.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(a))return void(this.state=Aa);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,Gr,hn));const l=this.getFwdBufferInfo(o,hn);if(null===l)return;const{bufferedTrack:d,switchingTrack:c}=this;if(!c&&this._streamEnded(l,a))return t.trigger(Ir.BUFFER_EOS,{type:"audio"}),void(this.state=wa);const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,un),h=l.len,f=this.getMaxBufferLength(null==u?void 0:u.len);if(h>=f&&!c)return;const g=a.fragments[0].start;let p=l.end;if(c&&s){const t=this.getLoadPosition();d&&c.attrs!==d.attrs&&(p=t),a.PTSKnown&&t<g&&(l.end>g||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=g+.05)}let m=this.getNextFragment(p,a),y=!1;if(m&&this.isLoopLoading(m,p)&&(y=!!m.gap,m=this.getNextFragmentLoopLoading(m,a,l,un,f)),!m)return void(this.bufferFlushed=!0);const v=u&&m.start>u.end+a.targetduration;if(v||(null==u||!u.len)&&l.len){const t=this.fragmentTracker.getBufferedFrag(m.start,un);if(null===t)return;if(y||(y=!!t.gap||!!v&&0===u.len),v&&!y||y&&l.nextStart&&l.nextStart<t.end)return}this.loadFragment(m,n,p)}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.min(Math.max(e,t),this.config.maxMaxBufferLength):e}onMediaDetaching(){this.videoBuffer=null,super.onMediaDetaching()}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(t=>new Level(t))}onAudioTrackSwitching(t,e){const s=!!e.url;this.trackId=e.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),s?this.setInterval(100):this.resetTransmuxer(),s?(this.switchingTrack=e,this.state=Ea):(this.switchingTrack=null,this.bufferedTrack=e,this.state=va),this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.bufferedTrack=null,this.switchingTrack=null}onLevelLoaded(t,e){this.mainDetails=e.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(Ir.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(t,e){var s;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=e);const{levels:r}=this,{details:i,id:n}=e;if(!r)return void this.warn("Audio tracks were reset while loading level "+n);this.log(`Track ${n} loaded [${i.startSN},${i.endSN}],duration:${i.totalduration}`);const a=r[n];let o=0;if(i.live||null!=(s=a.details)&&s.live){const t=this.mainDetails;if(i.fragments[0]||(i.deltaUpdateFailed=!0),i.deltaUpdateFailed||!t)return;!a.details&&i.hasProgramDateTime&&t.hasProgramDateTime?(ma(i,t),o=i.fragments[0].start):o=this.alignPlaylists(i,a.details)}a.details=i,this.levelLastLoaded=n,this.startFragRequested||!this.mainDetails&&i.live||this.setStartPosition(a.details,o),this.state!==Aa||this.waitForCdnTuneIn(i)||(this.state=Ea),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:s,part:r,payload:i}=t,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const l=o[a];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(s.start);const c=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new TransmuxerInterface(this.hls,hn,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const h=this.initPTS[s.cc],f=null==(e=s.initSegment)?void 0:e.data;if(void 0!==h){const t=!1,e=r?r.index:-1,n=-1!==e,a=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount,i.byteLength,e,n);u.push(i,f,c,"",s,r,d.totalduration,t,a,h)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:s,part:r,cache:new ChunkCache,complete:!1};t.push(new Uint8Array(i)),this.waitingVideoCC=this.videoTrackCC,this.state=ka}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(t,e){const s=e.tracks.audio;s&&(this.mediaBuffer=s.buffer||null),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer||null)}onFragBuffered(t,e){const{frag:s,part:r}=e;var i;if(s.type===hn)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==s.sn){this.fragPrevious=s;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(Ir.AUDIO_TRACK_SWITCHED,br({},t)))}this.fragBufferedComplete(s,r)}else this.loadedmetadata||s.type!==un||null!=(i=this.videoBuffer||this.media)&&i.buffered.length&&(this.loadedmetadata=!0)}onError(t,e){var s;if(e.fatal)this.state=Ra;else switch(e.details){case Cr.FRAG_GAP:case Cr.FRAG_PARSING_ERROR:case Cr.FRAG_DECRYPT_ERROR:case Cr.FRAG_LOAD_ERROR:case Cr.FRAG_LOAD_TIMEOUT:case Cr.KEY_LOAD_ERROR:case Cr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(hn,e);break;case Cr.AUDIO_TRACK_LOAD_ERROR:case Cr.AUDIO_TRACK_LOAD_TIMEOUT:case Cr.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Aa||(null==(s=e.context)?void 0:s.type)!==dn||(this.state=Ea);break;case Cr.BUFFER_FULL_ERROR:if(!e.parent||"audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Cr.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushed(t,{type:e}){e===Gr&&(this.bufferFlushed=!0,this.state===wa&&(this.state=Ea))}_handleTransmuxComplete(t){var e;const s="audio",{hls:r}=this,{remuxResult:i,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:d}=a,{details:c}=d,{audio:u,text:h,id3:f,initSegment:g}=i;if(!this.fragContextChanged(o)&&c){if(this.state=La,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks&&(this._bufferInitSegment(g.tracks,o,n),r.trigger(Ir.FRAG_PARSING_INIT_SEGMENT,{frag:o,id:s,tracks:g.tracks})),u){const{startPTS:t,endPTS:e,startDTS:s,endDTS:r}=u;l&&(l.elementaryStreams[Gr]={startPTS:t,endPTS:e,startDTS:s,endDTS:r}),o.setElementaryStreamInfo(Gr,t,e,s,r),this.bufferFragmentData(u,o,l,n)}if(null!=f&&null!=(e=f.samples)&&e.length){const t=Rr({id:s,frag:o,details:c},f);r.trigger(Ir.FRAG_PARSING_METADATA,t)}if(h){const t=Rr({id:s,frag:o,details:c},h);r.trigger(Ir.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,e,s){if(this.state!==La)return;t.video&&delete t.video;const r=t.audio;if(!r)return;r.levelCodec=r.codec,r.id="audio",this.log(`Init audio buffer, container:${r.container}, codecs[parsed]=[${r.codec}]`),this.hls.trigger(Ir.BUFFER_CODECS,t);const i=r.initSegment;if(null!=i&&i.byteLength){const t={type:"audio",frag:e,part:null,chunkMeta:s,parent:e.type,data:i};this.hls.trigger(Ir.BUFFER_APPENDING,t)}this.tick()}loadFragment(t,e,s){const r=this.fragmentTracker.getState(t);var i;(this.fragCurrent=t,this.switchingTrack||r===sa||r===ia)?"initSegment"===t.sn?this._loadInitSegment(t,e):null!=(i=e.details)&&i.live&&!this.initPTS[t.cc]?(this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=ka):(this.startFragRequested=!0,super.loadFragment(t,e,s)):this.clearTrackerIfNeeded(t)}completeAudioSwitch(t){const{hls:e,media:s,bufferedTrack:r}=this,i=null==r?void 0:r.attrs,n=t.attrs;s&&i&&(i.CHANNELS!==n.CHANNELS||i.NAME!==n.NAME||i.LANGUAGE!==n.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(Ir.AUDIO_TRACK_SWITCHED,br({},t))}},audioTrackController:class AudioTrackController extends BasePlaylistController{constructor(t){super(t,"[audio-track-controller]"),this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ir.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Ir.LEVEL_LOADING,this.onLevelLoading,this),t.on(Ir.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Ir.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(Ir.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ir.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Ir.LEVEL_LOADING,this.onLevelLoading,this),t.off(Ir.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Ir.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(Ir.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:s,groupId:r,details:i}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==r)return void this.warn(`Track with id:${s} and group:${r} not found in active group ${n.groupId}`);const a=n.details;n.details=e.details,this.log(`audio-track ${s} "${n.name}" lang:${n.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(null==e||!e.audioGroupIds)return;const s=e.audioGroupIds[e.urlId];if(this.groupId!==s){this.groupId=s||null;const t=this.tracks.filter(t=>!s||t.groupId===s);this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=t;const e={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group:${s}`),this.hls.trigger(Ir.AUDIO_TRACKS_UPDATED,e),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(t,e){!e.fatal&&e.context&&e.context.type===dn&&e.context.id===this.trackId&&e.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(e))}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn("Invalid id passed to audio-track controller");this.clearTimer();const s=this.currentTrack;e[this.trackId];const r=e[t],{groupId:i,name:n}=r;if(this.log(`Switching to audio-track ${t} "${n}" lang:${r.lang} group:${i}`),this.trackId=t,this.currentTrack=r,this.selectDefaultTrack=!1,this.hls.trigger(Ir.AUDIO_TRACK_SWITCHING,br({},r)),r.details&&!r.details.live)return;const a=this.switchParams(r.url,null==s?void 0:s.details);this.loadPlaylist(a)}selectInitialTrack(){const t=this.tracksInGroup,e=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(-1!==e)this.setAudioTrack(e);else{const e=new Error(`No track found for running audio group-ID: ${this.groupId} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(Ir.ERROR,{type:Dr.MEDIA_ERROR,details:Cr.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const r=e[s];if(!this.selectDefaultTrack||r.default){if(!t||t.attrs["STABLE-RENDITION-ID"]===r.attrs["STABLE-RENDITION-ID"])return r.id;if(t.name===r.name&&t.lang===r.lang)return r.id}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(e)){const s=e.id,r=e.groupId;let i=e.url;if(t)try{i=t.addDirectives(i)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}this.log(`loading audio-track playlist ${s} "${e.name}" lang:${e.lang} group:${r}`),this.clearTimer(),this.hls.trigger(Ir.AUDIO_TRACK_LOADING,{url:i,id:s,groupId:r,deliveryDirectives:t||null})}}},emeController:EMEController,cmcdController:CMCDController,contentSteeringController:class ContentSteeringController{constructor(t){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.log=Fr.log.bind(Fr,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ir.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Ir.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Ir.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(Ir.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ir.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Ir.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Ir.ERROR,this.onError,this))}startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){const t=Math.max(1e3*this.timeToLoad-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,t)}else this.loadSteeringManifest(this.uri)}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),self.clearTimeout(this.reloadTimer)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter(e=>e!==t))}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(t,e){const{contentSteering:s}=e;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:s}=e;if((null==s?void 0:s.action)===Wn&&s.flags===Xn){let t=this.pathwayPriority;const e=this.pathwayId;this.penalizedPathways[e]||(this.penalizedPathways[e]=performance.now()),!t&&this.levels&&(t=this.levels.reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])),t&&t.length>1&&(this.updatePathwayPriority(t),s.resolved=this.pathwayId!==e)}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const s=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),e=this.getLevelsForPathway(s),this.pathwayId=s}return e.length!==t.length?(this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e):t}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){let e;this.pathwayPriority=t;const s=this.penalizedPathways,r=performance.now();Object.keys(s).forEach(t=>{r-s[t]>3e5&&delete s[t]});for(let r=0;r<t.length;r++){const i=t[r];if(s[i])continue;if(i===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(e=this.getLevelsForPathway(i),e.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,this.hls.trigger(Ir.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];a&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}clonePathways(t){const e=this.levels;if(!e)return;const s={},r={};t.forEach(t=>{const{ID:i,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some(t=>t.pathwayId===i))return;const o=this.getLevelsForPathway(n).map(t=>{const e=Rr({},t);e.details=void 0,e.url=ul(t.uri,t.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a);const n=new AttrList(t.attrs);n["PATHWAY-ID"]=i;const o=n.AUDIO&&`${n.AUDIO}_clone_${i}`,l=n.SUBTITLES&&`${n.SUBTITLES}_clone_${i}`;o&&(s[n.AUDIO]=o,n.AUDIO=o),l&&(r[n.SUBTITLES]=l,n.SUBTITLES=l),e.attrs=n;const d=new Level(e);return ta(d,"audio",o),ta(d,"text",l),d});e.push(...o),cl(this.audioTracks,s,a,i),cl(this.subtitleTracks,r,a,i)})}loadSteeringManifest(t){const e=this.hls.config,s=e.loader;let r;this.loader&&this.loader.destroy(),this.loader=new s(e);try{r=new self.URL(t)}catch(e){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: "+t)}if("data:"!==r.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+t)}const i={responseType:"json",url:r.href},n=e.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,s,i)=>{this.log(`Loaded steering manifest: "${r}"`);const n=t.data;if(1!==n.VERSION)return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,r).href}catch(t){return this.enabled=!1,void this.log("Failed to parse Steering Manifest RELOAD-URI: "+a)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o),l&&this.updatePathwayPriority(l)},onError:(t,e,s,r)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let i=1e3*this.timeToLoad;if(429!==t.code)this.scheduleRefresh(this.uri||e.url,i);else{const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(i=1e3*parseFloat(e))}this.log(`Steering manifest ${e.url} rate limited`)}},onTimeout:(t,e,s)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log("Requesting steering manifest: "+r),this.loader.load(i,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout(()=>{this.loadSteeringManifest(t)},e)}}});function vl(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(vl):Object.keys(t).reduce((e,s)=>(e[s]=vl(t[s]),e),{}):t}function El(t){const e=t.loader;if(e!==FetchLoader&&e!==XhrLoader)Fr.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1})()&&(t.loader=FetchLoader,t.progressive=!0,t.enableSoftwareAES=!0,Fr.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Hls{static get version(){return"1.4.0"}static isSupported(){return function(){const t=Da();if(!t)return!1;const e=Ca(),s=t&&"function"==typeof t.isTypeSupported&&t.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),r=!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove;return!!s&&!!r}()}static get Events(){return Ir}static get ErrorTypes(){return Dr}static get ErrorDetails(){return Cr}static get DefaultConfig(){return Hls.defaultConfig?Hls.defaultConfig:yl}static set DefaultConfig(t){Hls.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Eo,this._autoLevelCapping=void 0,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,function(t,e){if(self.console&&!0===t||"object"==typeof t){xr(t,"debug","log","info","warn","error");try{Mr.log(`Debug logs enabled for "${e}" in hls.js version 1.4.0`)}catch(t){Mr=Or}}else Mr=Or}(t.debug||!1,"Hls instance");const e=this.config=function(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=vl(t),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const i=("level"===t?"playlist":t)+"LoadPolicy",n=void 0===e[i],a=[];r.forEach(r=>{const o=`${t}Loading${r}`,l=e[o];if(void 0!==l&&n){a.push(o);const t=s[i].default;switch(e[i]={default:t},r){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}}),a.length&&Fr.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${i}": ${JSON.stringify(e[i])}`)}),br(br({},s),e)}(Hls.DefaultConfig,t);this.userConfig=t,this._autoLevelCapping=-1,e.progressive&&El(e);const{abrController:s,bufferController:r,capLevelController:i,errorController:n,fpsController:a}=e,o=new n(this),l=this.abrController=new s(this),d=this.bufferController=new r(this),c=this.capLevelController=new i(this),u=new a(this),h=new PlaylistLoader(this),f=new ID3TrackController(this),g=e.contentSteeringController,p=g?new g(this):null,m=this.levelController=new LevelController(this,p),y=new FragmentTracker(this),v=new KeyLoader(this.config),E=this.streamController=new StreamController(this,y,v);c.setStreamController(E),u.setStreamController(E);const T=[h,m,E];p&&T.splice(1,0,p),this.networkControllers=T;const _=[l,d,c,u,f,y];this.audioTrackController=this.createController(e.audioTrackController,T);const S=e.audioStreamController;S&&T.push(new S(this,y,v)),this.subtitleTrackController=this.createController(e.subtitleTrackController,T);const A=e.subtitleStreamController;A&&T.push(new A(this,y,v)),this.createController(e.timelineController,_),v.emeController=this.emeController=this.createController(e.emeController,_),this.cmcdController=this.createController(e.cmcdController,_),this.latencyController=this.createController(LatencyController,_),this.coreComponents=_,T.push(o);const L=o.onErrorOut;"function"==typeof L&&this.on(Ir.ERROR,L,o)}createController(t,e){if(t){const s=new t(this);return e&&e.push(s),s}return null}on(t,e,s=this){this._emitter.on(t,e,s)}once(t,e,s=this){this._emitter.once(t,e,s)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,s=this,r){this._emitter.off(t,e,s,r)}listeners(t){return this._emitter.listeners(t)}emit(t,e,s){return this._emitter.emit(t,e,s)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){Fr.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),this.trigger(Ir.ERROR,{type:Dr.OTHER_ERROR,details:Cr.INTERNAL_EXCEPTION,fatal:!1,event:t,error:e})}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){Fr.log("destroy"),this.trigger(Ir.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){Fr.log("attachMedia"),this._media=t,this.trigger(Ir.MEDIA_ATTACHING,{media:t})}detachMedia(){Fr.log("detachMedia"),this.trigger(Ir.MEDIA_DETACHING,void 0),this._media=null}loadSource(t){this.stopLoad();const e=this.media,s=this.url,r=this.url=Ar.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});Fr.log("loadSource:"+r),e&&s&&s!==r&&this.bufferController.hasSourceTypes()&&(this.detachMedia(),this.attachMedia(e)),this.trigger(Ir.MANIFEST_LOADING,{url:t})}startLoad(t=-1){Fr.log(`startLoad(${t})`),this.networkControllers.forEach(e=>{e.startLoad(t)})}stopLoad(){Fr.log("stopLoad"),this.networkControllers.forEach(t=>{t.stopLoad()})}swapAudioCodec(){Fr.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){Fr.log("recoverMediaError");const t=this._media;this.detachMedia(),t&&this.attachMedia(t)}removeLevel(t,e=0){this.levelController.removeLevel(t,e)}get levels(){const t=this.levelController.levels;return t||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){Fr.log("set currentLevel:"+t),this.loadLevel=t,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){Fr.log("set nextLevel:"+t),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){Fr.log("set loadLevel:"+t),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){Fr.log("set firstLevel:"+t),this.levelController.firstLevel=t}get startLevel(){return this.levelController.startLevel}set startLevel(t){Fr.log("set startLevel:"+t),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(Fr.log("set autoLevelCapping:"+t),this._autoLevelCapping=t)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){wn.indexOf(t)>-1&&(this._maxHdcpLevel=t)}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const s=t.length;for(let r=0;r<s;r++)if(t[r].maxBitrate>=e)return r;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:s}=this;let r;if(r=-1===e&&t&&t.length?t.length-1:e,s)for(let e=r;e--;){const r=t[e].attrs["HDCP-LEVEL"];if(r&&r<=s)return e}return r}get nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(t){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,t)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}Hls.defaultConfig=void 0;var Tl=Object.freeze({__proto__:null,ATTACHED:"hls:attached"});const _l="com.widevine.alpha";const Sl="application/vnd.apple.mpegURL",Al=[Sl,"application/x-mpegurl"],Ll=document.createElement("video").canPlayType(Sl);function bl({src:t="",type:e="",drm:s},r){const i=(null==r?void 0:r.hls)||{},n="native"in i&&i.native;return(!Ll||!n)&&(!(s&&!Object.keys(s).find(t=>{return e=t,[_l].filter((function(t){return t===e})).length;var e}))&&(!(!e||!Al.includes(e))||function(t){const{pathname:e}=gs(t);return e.endsWith(".m3u8")}(t)))}const wl=window&&window.Hls||Hls;var Rl="audio:set",kl="audio:update",Il="audio:tracks";var Dl=Object.assign(Object.assign({},{"http.404":"the video was not found","http.403":"access to this video was denied","http.410":"the video no longer exists","http.live.404":"stream is offline","http.0":"no internet connection detected"}),{keySystemNoKeys:"no keys",keySystemNoAccess:"no access to key system",keySystemNoSession:"no session for key system",keySystemLicenseRequestFailed:"license request failed",keyLoadError:"decrypt key load failed",keyLoadTimeOut:"decrypt key load timed outs"});var Cl;!function(t){t[t.FRAGMENT_ERRORS=0]="FRAGMENT_ERRORS",t[t.STALE_MANIFEST=1]="STALE_MANIFEST"}(Cl||(Cl={}));const Pl=Oe("hls:failover");class FailoverLoaderController{constructor(){this.playlistCounts={},this.fragmentFailures={},this.ttlMilliseconds=3e3}setHls(t){this.hls=t}reset(){return this.playlistCounts={},this.fragmentFailures={},this}failover(t){var e;this.reset();const s=this.hls;if(!s)return;const r=s.levels[s.currentLevel];if(!r)return;if(r.url.length<2)return;const i=s.levels[s.currentLevel].details,n=(r.urlId+1)%r.url.length;s.levels.forEach(t=>{t.urlId=n}),null===(e=s.media)||void 0===e||e.dispatchEvent(new CustomEvent("hls/failover",{detail:{reason:t,from:null==i?void 0:i.url}}))}currentLevel(){var t;return null===(t=this.hls)||void 0===t?void 0:t.levels[this.hls.currentLevel]}nextTTL(){var t;const e=Date.now()+this.ttlMilliseconds,s=this.currentLevel();if(!s)return e;const r=null===(t=s.details)||void 0===t?void 0:t.averagetargetduration;return r?Date.now()+500*r:e}ensurePlaylistUpdating(t,e){this.playlistCounts[t]||(this.playlistCounts[t]={checksum:e,count:0,ttl:this.nextTTL()});const s=this.playlistCounts[t];Date.now()<s.ttl||(s.count=s.checksum===e?s.count+1:0,s.ttl=this.nextTTL(),s.checksum=e,s.count<3||(Pl(`${t} / no change in ${s.count} tries`,this.playlistCounts),this.failover(Cl.STALE_MANIFEST)))}trackFragmentError(t){const e=this.fragmentFailures[t]||0;this.fragmentFailures[t]=e+1,this.fragmentFailures[t]>2&&this.failover(Cl.FRAGMENT_ERRORS)}createPlaylistLoader(t){const e=this;return class extends Hls.DefaultConfig.loader{load(s,r,i){const n=i.onSuccess;i.onSuccess=({data:r,url:i},...a)=>{"manifest"===(null==s?void 0:s.type)&&(t.manifest=r),e.ensurePlaylistUpdating(i,r),n({data:r,url:i},...a)},super.load(s,r,i)}}}createFragmentLoader(){const t=this;return class extends Hls.DefaultConfig.loader{load(e,s,r){const i=r.onError;r.onError=e=>{t.trackFragmentError(e.url),i(...arguments)},super.load(e,s,r)}}}}const Ol=Oe("hls");function Ml(t,e,s,i){if(!t.reaper||!s.src)return;t.hls&&t.hls.destroy();const n="live"in e==0,a={is_audio_only:!1,fragDuration:-1,media_recovers:0,audio_swaps:0};if(s.drm&&!fs()&&"localhost"!==location.hostname&&"127.0.0.1"!==location.hostname)return t.emit(r,{message:"Secure page required for DRM"});const o=new FailoverLoaderController,l=function(t){return Object.assign(Object.assign({autoStartLoad:!1,levelLoadingMaxRetry:1},t.hls),{startPosition:t.start_time||-1})}(e);l.renderTextTracksNatively=!1,l.pLoader=o.createPlaylistLoader(i),l.fLoader=o.createFragmentLoader();const d=t.hls=new wl(l);o.setHls(d),d.subtitleDisplay=!1,d.attachMedia(t),d.loadSource(s.src),t.emit("hls:attached",{hls:d}),function(t,e){t.on(Hls.Events.AUDIO_TRACKS_UPDATED,(function(t,s){e.emit(Il,s.audioTracks)})),t.on(Hls.Events.AUDIO_TRACK_SWITCHING,(function(t,s){e.emit(kl,s)})),t.on(Hls.Events.MANIFEST_PARSED,(function(t,s){s.audioTracks&&e.emit(Il,s.audioTracks)})),t.on(Hls.Events.LEVEL_SWITCHED,(function(s,r){const i=t.levels[r.level];i&&e.emit(Il,t.audioTracks.filter((function(t){return t.groupId&&~(i.audioGroupIds||[]).indexOf(t.groupId)})))}))}(d,t),function(t,e){t.on(Hls.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(s,r)=>{t.subtitleTracks.length||e.emit("tracks:text:all",r)}),t.on(Hls.Events.SUBTITLE_TRACKS_UPDATED,(t,s)=>{e.emit("tracks:text:all",{tracks:s.subtitleTracks.map(t=>Object.assign({},{subtitleTrack:t}))})}),t.on(Hls.Events.CUES_PARSED,(t,s)=>{e.emit("cues:parsed",s)})}(d,t);const c=function(t){var e;const s=null===(e=t.data)||void 0===e?void 0:e.level;"number"==typeof s&&(d.levels[s]||-1===s?d.nextLevel=s:console.error(new Error("skipping invalid quality: "+t.data)))},u=function(t){var e;const s=null===(e=t.data)||void 0===e?void 0:e.id;"number"==typeof s&&s!=d.audioTrack&&setTimeout((function(){d.audioTrack=s}),0)};t.on("quality:set",c),t.on(Rl,u),t.on("src",(function(){t.off("quality:set",c),t.off(Rl,u),t.hls&&(t.hls.destroy(),delete t.hls,i.manifest=void 0)}));let h=0;t.on(r,e=>{var s;++h,h>=5||!t.hls||(null===(s=null==t?void 0:t.error)||void 0===s?void 0:s.code)!==MediaError.MEDIA_ERR_DECODE||(e.preventDefault(),d.config.autoStartLoad=!0,d.recoverMediaError())}),t.on(_,()=>h=0),t.on("beforeplay",()=>{if(t.hls&&!t.hasState("is-casting")&&!t.hasState(tt)&&"none"===e.preload&&!e.autoplay)return t.hls.levels.length?xl(t,e.start_time||-1):void t.hls.once(wl.Events.MANIFEST_PARSED,()=>{setTimeout(()=>{xl(t,e.start_time||-1)},0)})}),t.on("tracks:video:select",(function(e){var s;const r=e.detail.track,i=null===(s=t.tracks)||void 0===s?void 0:s.find(t=>t.selected&&t!==r),n=t.hls;if(!i||!r||!n)return;i.selected=!1;const a=r.data.slice(0).map(t=>(t.details=void 0,t));n.stopLoad(),n.levelController._levels=n.streamController.levels=a,n.currentLevel=-1,n.levelController.currentLevelIndex=-1,t.emit("qualities",Fl(a)),t.hasState(st)&&!t.hasState(et)||n.startLoad()})),t.on("audioonlysource",(function(){a.is_audio_only=!0})),t.on(w,(function(){d&&d.destroy()})),t.on("remotesession:started",()=>{t.hls&&t.hls.stopLoad()}),t.on("remotesession:ended",()=>{t.hls&&xl(t)}),t.on(D,r=>{if(t.hls){if(r.preventDefault(),s.src&&d.loadSource(t.original_src),e.autoplay)return t.togglePlay(!0);t.setState(at,!1),t.emit("retry/done")}}),n&&d.on(wl.Events.LEVEL_LOADED,(function(e,s){t.setOpts({live:s.details.live})})),d.on(wl.Events.MANIFEST_PARSED,(function(r,n){const a=Fl(n.levels);t.emit("qualities",a),t.emit("parse:video:tracks",{url:s.src,manifest:i.manifest}),function(t,e,s){var r,i;if(!t.hls)return;Ol("Initializer::maybe_start_load_with_quality (start_quality, preload): (%d, %s)",e.start_quality,e.preload),void 0!==e.start_quality&&(At.HIGH&e.start_quality&&(t.hls.startLevel=s[0].level),At.LOW&e.start_quality&&(t.hls.startLevel=s[s.length-1].level),At.MEDIUM&e.start_quality&&(t.hls.startLevel=s[Math.ceil(s.length/2)-1].level));const n=(null===(r=e.hls)||void 0===r?void 0:r.maxBufferSize)||1024,a=(null===(i=e.hls)||void 0===i?void 0:i.maxBufferLength)||30;Ol("Setting maxBufferSize to %d",n),t.hls.config.maxBufferSize=n,"metadata"===e.preload&&Ol("preload === metadata, setting maxBufferLength to 1sec");t.hls.config.maxBufferLength="metadata"===e.preload?1:a,t.once(E,()=>{Ol("Playback started, set maxBufferLenght to %d",a),t.hls&&(t.hls.config.maxBufferLength=a)}),("none"!==e.preload||e.autoplay)&&xl(t,e.start_time||-1)}(t,e,a.slice(0,-1));const o=a.find(t=>!!t.videoCodec);o||t.emit("audioonlysource"),!t.opt("ratio")&&o&&0!=o.width&&0!=o.height&&t.setOpts({ratio:o.width+":"+o.height})})),d.on(wl.Events.INIT_PTS_FOUND,(function(t,e){a.fragDuration=e.frag.duration})),d.on(wl.Events.ERROR,(function(e,s){!function(t,e,s){var i,n,a,o;if(0==t.reaper)return;if(0==e.fatal)return;switch(e.type){case wl.ErrorTypes.MEDIA_ERROR:return Ol("recovering from "+e.type),s.media_recovers+5e3>Date.now()&&0==s.audio_swaps?(null===(i=t.hls)||void 0===i||i.swapAudioCodec(),Ol(`calling swapAudioCodec() : {count=${s.audio_swaps}}`),s.audio_swaps++,s.media_recovers=Date.now(),null===(n=t.hls)||void 0===n?void 0:n.recoverMediaError()):(s.media_recovers=Date.now(),s.audio_swaps=0,null===(a=t.hls)||void 0===a?void 0:a.recoverMediaError());case wl.ErrorTypes.NETWORK_ERROR:return function(t,e){var s;const i=(null===(s=e.networkDetails)||void 0===s?void 0:s.status)||e.details;let n=t.opts.live?"http.live.":"http.";n+=i.toString();const a=t.i18n("error."+n,Dl[n]||"an error occurred while loading this video");t.emit(r,{code:n,message:a,fatal:!0})}(t,e);case wl.ErrorTypes.KEY_SYSTEM_ERROR:return function(t,e){var s;t.emit(r,{fatal:!0,message:Dl[e.details]||"an error occurred while accessing this video"}),null===(s=t.hls)||void 0===s||s.destroy()}(t,e);default:null===(o=t.hls)||void 0===o||o.destroy()}}(t,s,a)})),d.on(wl.Events.LEVEL_PTS_UPDATED,(function(e,s){var r;if("video"!==s.type&&(!a.is_audio_only||"audio"!==s.type))return;const i=null===(r=null==s?void 0:s.details)||void 0===r?void 0:r.fragments;if(!i)return;const n=i[0].start||0,o=(d.liveSyncPosition||i[i.length-1].start)+i[i.length-1].duration;t.emit("dvr/window",o-n)})),d.on(wl.Events.LEVEL_SWITCHING,(e,s)=>{const r=d.levels[d.currentLevel],i=d.levels[s.level];t.emit("qualitychange",{before:r,after:i,kind:"hls"})});const f=t.opt("start_time");f&&t.once(g,(function(){t.currentTime=f}))}function xl(t,e){var s;!t.hasState(tt)&&t.setState(et,!0),null===(s=t.hls)||void 0===s||s.startLoad(e)}function Fl(t){const e=t.map((t,e)=>({level:e,text:t.name||t.width+"",width:t.width,height:t.height,videoCodec:t.videoCodec||""})).sort((t,e)=>e.width-t.width);return t.length>1&&t.every(t=>void 0!==t.bitrate)&&e.push({text:"AUTO",level:-1,width:0,height:0,videoCodec:""}),e}class HLS{init(){}onload(t,e,s,r){Ml(s,t,r,this)}wants(t,e,s){return Hls.isSupported()&&bl(e,s)}}HLS.events=Tl,HLS.version=Hls.version,HLS.failover={Reasons:Cl},ce(window,HLS);const Nl=t=>"object"==typeof t&&null!==t&&!Array.isArray(t),Ul=(...t)=>t.reduce((t,e)=>Nl(e)?(Object.keys(e).forEach(s=>{if(Nl(t[s])&&Nl(e[s]))return t[s]=Ul(t[s],e[s]);t[s]=e[s]}),t):t,{});class Pipe{constructor(t){this.data=t}static of(t){return new Pipe(t)}static maybe(t,e,...s){return null==t?t:e.apply(t,[t,...s])}tap(t,...e){return t.apply(this,[this.data,...e]),new Pipe(this.data)}fmap(t,...e){const s=t.apply(this,[this.data,...e]);return new Pipe(s)}unwrap(){return this.data}}function Bl(t){return fetch(t).then(t=>t.json())}function Gl(){let t=[].join.call(arguments,"/");return"/"!==t[0]&&(t="/"+t),$l()+"/web/public/native/config"+t}const $l=()=>"https://ljsp.lwcdn.com";function Hl(t){return~t.indexOf("/")?t:"/media/"+t}var Kl={404:"media not found",402:"invalid subscription",400:"bad request",415:"unsupported media type"};function Vl(t,e){var s,r;e="object"==typeof e?e:{};const i={title:null===(s=null==t?void 0:t.metadata)||void 0===s?void 0:s.title,description:null===(r=null==t?void 0:t.metadata)||void 0===r?void 0:r.description},n={ima:{parameters:function({media_id:t,duration:e,title:s,tags:r,category_name:i,ad_keywords:n}){return{ad_keywords:n||"",media_id:t||"",category:i||"",media_name:s||"",media_tags:r||"",media_duration:e||-1}}((null==t?void 0:t.metadata)||{})}},a=e.embed||{};return delete a.src,Ul(n,i,t,(delete(o=e).src,delete o.metadata,delete o.title,delete o.description,delete o.duration,delete o.poster,o),a);var o}const ql=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/;function jl(t){return"object"==typeof t&&"ovp/base64"==t.type}function Wl(t,e){return function(t,e){return!t.startsWith("blob:")&&(!(~t.indexOf(".")||!ql.test(t))&&(e.type="video/ovp",!0))}(t,e)||jl(e)}function Yl(t){try{return function(t){return null===t?{}:JSON.parse(t)}(decodeURIComponent(atob(t).split("").map((function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)})).join("")))}catch(t){return{err:t.message}}}function zl(t){const e=t.split(/[^0-9]/).map(t=>parseInt(t,10));return Date.UTC(e[0],e[1]-1,e[2],e[3],e[4],e[5])}function Xl(t){return t.live}var Ql=Object.freeze({__proto__:null,OVP_ERROR:"ovp:error",OVP_MEDIA_REQUEST_START:"ovp:request:start",OVP_MEDIA_REQUEST_COMPLETE:"ovp:request:media:complete",OVP_PLAYLIST_REQUEST_COMPLETE:"ovp:request:playlist:complete",LIVE_COUNTDOWN_TICK:"ovp:live:countdown:tick",LIVE_COUNTDOWN_START:"ovp:live:countdown:start",LIVE_COUNTDOWN_COMPLETE:"ovp:live:countdown:complete",OVP_MEDIA_CHANGED:"ovp:media:changed",OVP_REALTIME_MESSAGE:"ovp:message:realtime"});function Zl(t,e){const s=null==e?void 0:e.src;if(jl(e))return function(t,e){const s=Yl(e.src||"");if(function(t){return"string"==typeof t.err}(s))return console.error(s.err);Jl(t,s)}(t,e);s&&(t.setState(ft,!0),Pipe.of(s).fmap(Hl).fmap(Gl).fmap(t=>fetch(t)).fmap(e=>e.then(t=>Promise.all([t.status,t.json()])).then(([e,s])=>200==e?Jl(t,s):function(t,e){return t.setState(ft,!1),e.message?t.emit("ovp:error",e):e.status?t.emit("ovp:error",new Error(Kl[e.status])):t.emit("ovp:error",e)}(t,s))))}function Jl(t,e){return t.emit("ovp:media:changed",e),function(t){return Array.isArray(t.playlist)}(e)?function(t,e){t.emit("ovp:request:playlist:complete",function(t,e){const s=Object.assign({},t),r=(null==t?void 0:t.playlist)||{},i=Ul(e,r),n=((null==i?void 0:i.playlist)||[]).map(t=>{e.ima&&Object.assign(t,{ima:e.ima});const r=Vl(t,s);return delete r.playlist,r});return delete i.ima,Object.assign(i,{playlist:n})}(t.opts,e))}(t,e):Xl(e)?function(t,e){var s,r;const i=(null===(s=null==e?void 0:e.metadata)||void 0===s?void 0:s.live_start_time)||(null===(r=null==e?void 0:e.metadata)||void 0===r?void 0:r.starttime);i&&(e.live_start_time=Pipe.of(i).fmap(zl).unwrap());t.emit("ovp:live:countdown:start",Pipe.of(e).fmap(Vl,t.opts).unwrap())}(t,e):function(t,e){t.emit("ovp:request:media:complete",Pipe.of(e).fmap(Vl,t.opts).unwrap())}(t,e)}const td={};function ed(t,e,s){"object"!=typeof td[e]&&(td[e]=s);const r=t.opts,i=(null==r?void 0:r.metadata)||{};i.player_id=e,r.metadata=i,s.title&&delete s.title,s.description&&delete s.description;const n=Object.assign(r,s);t.setOpts(n),s.autoplay&&t.togglePlay(!0)}let sd=!1;function rd(t,e,s){id()||Pipe.of("recommendation").fmap(Gl,e,s).fmap(Bl).fmap(e=>e.then(e=>function(t,e){const s=e.playlist;if(t.opts.recommendations=s,!s.length)return;t.emit("recommendationsready",{playlist:s.map((function(t){var e,s;return{poster:t.poster,src:t.src,title:null===(e=null==t?void 0:t.metadata)||void 0===e?void 0:e.title,description:null===(s=null==t?void 0:t.metadata)||void 0===s?void 0:s.description,metadata:t.metadata||{},chapters:t.chapters,thumbnails:t.thumbnails,subtitles:t.subtitles}}))})}(t,e)).catch(nd))}function id(){return sd}function nd(t){sd=!0,console.error("Failed to load recommendations: %j",t)}function ad(t){const e=Date.now()-(t.server_time_offset||0);return Math.floor(((t.live_start_time||0)-e)/1e3)}function od(t,e){let s=0;function r(){const r=ad(e);if(r<0||isNaN(r)||0===t.reaper||void 0===e.live_start_time)return clearInterval(s),function(t,e,s){t.emit("ovp:live:countdown:complete");const r=$t(t,X);if(r&&r.remove(),t.root.classList.remove("is-livecountdown"),s)return t.setState(ft,!1);t.emit("ovp:request:media:complete",e)}(t,e,void 0===e.live_start_time);!function(t,e,s,r){s.classList.add("is-livecountdown"),e.emit("ovp:live:countdown:tick",{remaining_time:ld(r+1)}),e.hasState(st)||e.setState(st,!0)}(0,t,t.root,r)}var i;i=e,$s().then(t=>Object.assign(i,{server_time_offset:t})),r(),s=setInterval(r,250)}function ld(t){const e=function(t){"number"!=typeof t&&(t=parseInt(t,10)),t=Math.round(t);const e=Math.floor(t/86400);t-=86400*e;const s=Math.floor(t/3600);t-=3600*s;const r=Math.floor(t/60);return{days:e,hours:s,minutes:r,seconds:t-=60*r}}(t);let s="";return e.days&&(s+=e.days+":"),s+qt(e.hours)+":"+qt(e.minutes)+":"+qt(e.seconds)}class WebsocketBridge{constructor(t){this.manualDisconnect=!1,this.video=t,this.onClose=this.onClose.bind(this),this.onMessage=this.onMessage.bind(this)}static of(t){return new WebsocketBridge(t)}connect(t){this.client=new WebSocket("wss://player.ws.flowplayer.com?mediaId="+t),this.current_media_id=t,this.wireup()}onClose(){this.manualDisconnect?this.manualDisconnect=!1:this.current_media_id&&this.reconnect(this.current_media_id)}onMessage(t){JSON.parse(t.data).forEach(t=>{this.video.emit("ovp:message:realtime",t)})}reconnect(t){this.cleanup(),this.connect(t)}wireup(){this.client&&(this.client.addEventListener("message",this.onMessage),this.client.addEventListener("close",this.onClose))}cleanup(){this.client&&(this.client.removeEventListener("message",this.onMessage),this.client.removeEventListener("close",this.onClose),this.client=void 0)}disconnect(){this.client&&(this.manualDisconnect=!0,this.client.close())}}class FlowplayerLiveCountdown extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-livecountdown");const e=Kt("fp-inner");this.append(e);const s=document.createElement("p");s.innerText=t.i18n("ovp.starting_in"),e.append(s);const r=document.createElement("p");r.classList.add("fp-countdown"),e.append(r),t.on("ovp:live:countdown:tick",e=>{const s=e.detail.remaining_time;t.root.classList.add("is-livecountdown"),r.innerText=s})}}const dd=["*.lwcdn.com","*.flowplayer.com"];class OVP{constructor(t){St(t,X,FlowplayerLiveCountdown)}onload(t,e,s,r){if("string"==typeof r.src)return"string"!=typeof t.player_id||0===r.src.indexOf(t.player_id)||jl(r)||(r.src=[t.player_id,r.src].join("/")),Zl(s,r)}wants(t,e,s){return Wl(t,e)}init(t,e,s){const i=new WebsocketBridge(s);let n=Object.assign({},t);const a=function(t){return n?(delete n.src,Ul(t,n)):t};s.on("src",()=>{(s.currentSrc||s.root.classList.contains("is-livecountdown"))&&(n=!1)}),s.on("ovp:error",(function(t){s.emit(r,t.data)})),s.on("ovp:request:start",(function(){s.setState(at,!0),t.recommendations&&(t.recommendations=!1)})),s.on("ovp:media:changed",(function({data:t}){var e;const s=null===(e=null==t?void 0:t.metadata)||void 0===e?void 0:e.media_id;(null==t?void 0:t.live)&&s&&(i.disconnect(),i.connect(s))})),s.on("ovp:message:realtime",(function({data:e}){var r;const i=null==e?void 0:e.event,n=null==e?void 0:e.value,a=s.opt("metadata",{live_start_time:""});switch(i){case"METADATA":{const e=Object.assign(a,n),i=Object.assign(t,{metadata:e});i.live&&(null===(r=null==i?void 0:i.metadata)||void 0===r?void 0:r.live_start_time)&&(i.live_start_time=zl(i.metadata.live_start_time)),s.setOpts(i);break}}})),s.on("beforeplay",(function(e){const s=t;if(Xl(s)){if(cd(s))return;e.preventDefault()}})),s.on("ovp:request:media:complete",(function(t){const e=t.data;if(!e)return;if(e.src&&(e.src=Ft(e.src).map(t=>(t.src&&t.src.startsWith("//")&&(t.src="https:"+t.src),t))),0==s.reaper||"object"!=typeof e||ad(e)>0)return;const r=a(e);s.setOpts(r),s.setAttrs(r),r.src&&s.setSrc(r.src),s.setState(ft,!1)})),s.on(R,(function({data:r}){var i,n;if("string"==typeof t.src&&Wl(t.src,{}))return;if(t.src&&ud(t.src))return;if((null==r?void 0:r.domains)&&(null==r?void 0:r.domains.length)&&!((t,e)=>{const s=t.split(".").reverse();return e.concat(dd).some(t=>{const e=t.split(".").reverse(),r="*"===e[e.length-1];return r&&e.pop(),(r||e.length===s.length)&&e.every((t,e)=>s[e]===t)})})(function(){try{return window.location.hostname!==window.parent.location.hostname?gs(document.referrer).hostname:document.location.hostname}catch(t){return window.location.hostname}}(),r.domains))return Ee({root:e,video:s,data:{details:`Hostname ${window.location.hostname} is not allowed to load player ${null===(i=r.metadata)||void 0===i?void 0:i.player_id}.`,reason:"domain"}});const a=null==r?void 0:r.brand_color;return a&&s.root.style.setProperty("--fp-brand-color","#"==a[0]?a:"#"+a),"string"==typeof t.player_id&&(null===(n=null==t?void 0:t.metadata)||void 0===n?void 0:n.player_id)!==t.player_id?function(t,e){if("object"==typeof td[e])return console.debug("using Cache(%s)",e),ed(t,e,td[e]);Pipe.of(e).fmap(Gl).fmap(Bl).fmap(s=>s.then(s=>ed(t,e,s)).catch(console.error))}(s,t.player_id):void 0})),s.on("ovp:request:playlist:complete",(function(t){const e=t.data;if(!e||0==s.reaper)return;const{playlist:r}=e,i=kt(e,["playlist"]),n=a(i);Array.isArray(n.playlist)&&(n.playlist=i),s.setOpts(n),s.setAttrs(n);const o={type:"flowplayer/playlist",items:r};s.setSrc(o),s.setState(ft,!1)})),s.on("ovp:live:countdown:start",(function(r){const i=r.data;if(!i||0==s.reaper)return;const n=a(i);if(s.setOpts(n),s.setAttrs(n),ad(i)<=0)return s.emit("ovp:request:media:complete",i);$t(s,X)||(e.appendChild(_t(s,X)),od(s,t))})),s.on("timeupdate",(function(){var e,r,i;const n=t;Xl(n)?cd(n)||(s.togglePlay(!1),s.emit(S)):t.recommendations&&(null===(e=null==t?void 0:t.metadata)||void 0===e?void 0:e.media_id)&&(Array.isArray(t.recommendations)||s.currentTime/s.duration<.8||id()||(null===(r=null==t?void 0:t.metadata)||void 0===r?void 0:r.media_id)&&(null===(i=null==t?void 0:t.metadata)||void 0===i?void 0:i.player_id)&&rd(s,t.metadata.media_id,t.metadata.player_id))})),s.on(w,(function(){i.disconnect()}))}}function cd(t){var e,s;const r=null===(e=null==t?void 0:t.metadata)||void 0===e?void 0:e.live_stop_time;if(!r)return!0;return!!(null===(s=null==t?void 0:t.metadata)||void 0===s?void 0:s.allow_after_stop_time)||zl(r)>Date.now()}OVP.events=Ql;const ud=t=>{var e;if(t&&Array.isArray(t))return"object"==typeof t[0]&&"ovp/base64"===(null===(e=t[0])||void 0===e?void 0:e.type)};function hd(t){return{width:t.clientWidth,height:t.clientHeight}}function fd(t,e,s){return"number"==typeof s&&(s+="px"),t.style.setProperty(e,s),t}ce(window,OVP);const gd="ad-initialized";var pd=Object.freeze({__proto__:null,AD_INIT:gd,AD_PLAYBACK_ERROR:"ad-playback-error",AD_TEARDOWN:"ad-teardown",AD_VIDEOTAG_ATTACHED:"ad-videotag-attached",AD_BLOCKED:"ad-blocked",AD_REQUEST_ERROR:"ad-request-error",AD_REQUESTED:"ad-requested",AD_REQUEST_COMPLETED:"ad-request-completed",AD_PAUSE_CONTENT:"ad-pause-content",AD_STARTED:"ad-started",AD_COMPLETED:"ad-completed",AD_PAUSED:"ad-paused",AD_RESUMED:"ad-resumed",AD_WAITING:"ad-waiting",AD_PROGRESS:"ad-progress",AD_SKIPPED:"ad-skipped",AD_MUTED:"ad-muted",AD_VOLUME_CHANGED:"ad-volume-changed",AD_FULLSCREEN:"ad-fullscreen",AD_TIMEOUT:"ad-timeout",AD_BREAK_COMPLETED:"ad-break-completed",AD_POSTROLL_FINISHED:"ad-postroll-finished",AD_PREROLL_FINSIHED:"ad-preroll-finished",AD_MIDROLL_FINISHED:"ad-midroll-finished",VPAID_INIT:"vpaid-init",IMA_ADAPTER_INIT:"ad-ima-adapter-init",IMA_BEFORE_ADS_REQUEST:"ad-ima-before-ads-request",IMA_ADS_RENDERING_SETTINGS:"ad-ima-rendering-settings",ADAPTER_INIT_FAILED:"ad-adapter-init-failed",AD_PLAY_REQUESTED:"ad-play-requested",RELOAD_AD_REQUESTED:"reload-ad-requested",AD_ERROR:"ad-error",REQUEST_AD_PAUSE:"request/ad/pause",REQUEST_AD_PLAY:"request/ad/play",REQUEST_AD_MUTE_UNMUTE:"request/ad/muteunmute",AD_HIDE_FIRST_FRAME:"ad/hide-first-frame",AD_SHOW_FIRST_FRAME:"ad/show-first-frame",AD_RESIZE:"ad/resize",AD_SET_UI_FLAGS:"ad/set-ui-flags"});const md="undefined"!=typeof document&&"undefined"!=typeof window&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,yd="flowplayer-ad-ui",vd=Oe("ads/lifecycle"),Ed=["ad-playback-error","ad-teardown","ad-break-completed"];async function Td({config:t,root:e,content:s,ads:r,ima:i}){var n;vd("LifeCycle::initLifeCycle",t,e,s,r,i),s.autoplay=!1;const a=t.autoplay===Lt.AUDIO_REQUIRED,o=function(t,e){return{muted:!(e||!t.muted),volume:t.volume}}(s,a);s.on("volumechange",()=>{o.volume=s.volume,o.muted=s.muted});const l=_t(s,yd),d=l.adContainer;s.emit("ad/set-ui-flags",{ui_flags:null===(n=t.ads)||void 0===n?void 0:n.ui}),s.renderPlugin(l);const c={listening:!1,preload:null==i?void 0:i.preload_ads};if(vd("initial",o),r.setVideoTag(s),t.autoplay){vd("Trying to autoplay"),s.emit("ad/hide-first-frame",{root:e});await async function t(e,s){const[r,i]=[e.muted,e.volume];vd("Lifecycle::peek_content(:muted => %s, :volume => %s)",r,i);const n=()=>new Promise(t=>setTimeout(t,0,!1));s&&(e.muted=!1,e.volume=e.volume?e.volume:1);try{return await async function(t){return vd("Lifecycle::wait_for_source"),new Promise((e,s)=>{let r=0;const i=setInterval(()=>{if(++r>40)return clearInterval(i),s(new Error("No source in 2000ms, giving up"));t.currentSrc&&(e(null),clearInterval(i))},50)})}(e),e.volume&&(e.volume=.01),vd("Lifecycle::peek_content::play"),await new Promise(t=>setTimeout(()=>t(e.togglePlay(!0)))),vd("Lifecycle::peek_content::pause"),await new Promise(t=>setTimeout(()=>t(e.togglePlay(!1)))),e.volume=i,vd("Lifecycle::peek_content::true"),!0}catch(a){return e.volume=i,s?(e.muted=!1,0==e.volume&&(e.volume=1),await n()):r||!i?(vd("Lifecycle::peek_content::false"),await n()):(vd("Lifecycle::peek_content::recover"),e.muted=!0,!!await t(e)||(e.muted=r,vd("Lifecycle::peek_content::false"),await n()))}}(s,a)?(vd("Can autoplay, start ad"),s.opts.autoplay=1,_d({ads:r,content:s,state:c,adContainer:d,ima:i,config:t})):(vd("cannot autoplay(audioRequired: %s), fallback to poster state",a),t.autoplay=0,s.emit("ad/show-first-frame",{root:e}),s.setState("is-starting",!0))}t.autoplay||r.hasPreroll()&&function({content:t,ads:e,config:s,state:r,initial:i,adContainer:n,ima:a}){t.once("beforeplay",(async function(o){(t.hasState(ht)||"touchend"!=o.type)&&e.shallPlayAd(0)&&(md&&(t.muted=!1),o.preventDefault(),bd({ads:e,content:t,state:r}),vd("user_gesture(:intercept) -> shallPlayAd(0: %s)",e.shallPlayAd(0)),s.muted=i.muted,await _d({ads:e,content:t,state:r,adContainer:n,ima:a,config:s}),wd({ads:e,content:t}))}))}({content:s,ads:r,config:t,state:c,initial:o,adContainer:d,ima:i}),!t.autoplay&&r.hasPreroll()&&c.preload&&_d({ads:r,content:s,state:c,adContainer:d,ima:i,config:t}),Ld({config:t,root:e,content:s,ads:r,state:c,adContainer:d,ui:l,ima:i,initial:o});const u=async t=>{s.removeEventListener("beforeplay",u),r.resetScheduleCounter(),r.adapter&&(t.preventDefault(),await r.setCurrentTime(0),r.adapter.isAdPod()||r.trigger("ad-teardown"))};s.on("src",()=>{c.started&&(s.removeEventListener("beforeplay",u),s.addEventListener("beforeplay",u))}),s.on("beforeplay",t=>{(r.adBreak||r.adPlaying||r.adRequesting)&&(r.adBreak&&!r.adLinear||(vd("prevented content from starting because ad break is active"),t.preventDefault()))})}async function _d(t){t.state.started||(t.content.hasState(ht)?await Sd(t):t.content.once("viewenter",async()=>{await Sd(t)}))}async function Sd({ads:t,content:e,adContainer:s,ima:r,state:i,config:n}){var a;i.started=!0;const o=kt(r,["ads"]),l=hd(e.root),d=(null==n?void 0:n.muted)||e.muted,c=Object.assign(Object.assign(Object.assign({container:s,volume:d?0:e.volume,muted:d,autoplay:(null==n?void 0:n.autoplay)||!1,video_source:e.original_src,DisableCustomPlaybackForIOS10Plus:md,preload_ads:null===(a=null==n?void 0:n.ima)||void 0===a?void 0:a.preload_ads},o),l));vd("start():",c,i),await t.initialize(!1,c,i.preload)}function Ad(t,e){var s,r;return{content_width:t.clientWidth||(null===(s=t.parentNode)||void 0===s?void 0:s.clientWidth)||e.clientWidth,content_height:t.clientHeight||(null===(r=t.parentNode)||void 0===r?void 0:r.clientHeight)||e.clientHeight}}function Ld({config:t,root:e,content:s,ads:r,initial:i,adContainer:n,state:a,ui:o,ima:l}){vd("addUIListeners()"),s.once(E,async i=>{if(r){if(vd("addUIListeners() -> content started playing"),bd({ads:r,content:s,state:a}),!r.shallPlayAd(0)||!r.adapter.isLinearAd())return vd("addUIListeners() -> no more preroll ads -> resume content"),s.emit("ad/show-first-frame",{root:e}),await _d({ads:r,content:s,state:a,adContainer:n,ima:l,config:t});s.togglePlay(!1),await _d({ads:r,content:s,state:a,adContainer:n,ima:l,config:t}),r.shallPlayAd(0)&&r.adapter.isLinearAd()&&(o.classList.add("on","linear"),e.classList.add(at),wd({ads:r,content:s}))}}),s.on([I,k],(function(){if(!r)return;const{content_width:t,content_height:i}=Ad(s,e);r.resize({height:i,width:t})})),s.on("resize",t=>{if(!r||!t.detail)return;const{width:e,height:s}=t.detail.contentRect;r.resize({width:e,height:s})}),s.on(S,t=>{var e;r&&(vd("ui_listeners(:%s, event: %o)",t.type,t.detail),(null===(e=null==t?void 0:t.detail)||void 0===e?void 0:e.from)!==r&&(t.preventDefault(),Object.assign(t,{prevented_from_ads:!0}),r.finished((function(){s.emit(S,{from:r})}))))}),r.on("ad-requested",()=>{e.classList.toggle(at,!0)}),r.once("ad-started",()=>{s.on(["beforeplay","beforepause"],t=>{var e;if(!r.adBreak||!r.adapter.isLinearAd())return;t.preventDefault();const s=(null===(e=t.detail)||void 0===e?void 0:e.forced)?"beforeplay"===t.type:!r.adPlaying;s&&r.paused&&r.resume(),s||r.paused||r.pause()})}),r.on("ad-started",t=>{const n=t.detail,{linear:a,ad:l,ad_type:d}=n;let c;if(vd(`Ad[linear: ${a}, currentTime: ${s.currentTime}] starting`,l),"preroll"==d&&!a&&s.paused&&s.togglePlay(!0),a&&(c=Ad(s,e)),r.resize({width:c?c.content_width:l.width,height:c?c.content_height:l.height,linear:a,resize_non_linear:!0}),s.emit("ad/resize",{opts:{linear:a,resizeContainerAlso:!0,width:a?void 0:l.width,height:a?void 0:l.height}}),e.classList.remove(at),o.classList.add("on"),o.classList.toggle("linear",a),o.classList.toggle("non-linear",!a),!a){vd("non-linear ad / restarting content");try{s.togglePlay(!0),s.volume=i.volume,s.muted=i.muted}catch(t){vd(t)}}s.hasState(ht)||s.hasState("is-popped-out")||!a||r.pause()}),r.on("ad-pause-content",()=>{s.emit("ad/resize",{opts:{linear:!0,width:0,height:0}})}),s.on(Ed,t=>async function({root:t,content:e,ads:s,ui:r,eventName:i,err:n={reason:""}}){vd("teardown(event: %s)",i),t.classList.add("is-seamless"),r.classList.remove("is-vpaid"),t.classList.remove(at),n.reason&&vd("teardown(:err, reason: %s) %o",n.reason);r.classList.remove("on");const a=s.getLastAd();if(e.emit("ad/show-first-frame",{root:t}),!s.shouldRestartContent())return vd("Lifecycle.teardown(:skip_restart, reason: %s)","Ad prevented restarting content"),Rd(t);if(e.currentTime>0&&e.currentTime>=e.duration||"postroll"==s.ad_type||!1===(null==a?void 0:a.restart))return vd("Lifecycle.teardown(:skip_restart, reason: %s)","was a postroll ad"),Rd(t);""===e.currentSrc&&e.setSrc(e.original_src);e.paused&&s.shouldRestartContent()&&(vd("Lifecycle.teardown(:toggle_play, %s)","attempting to restart content"),await e.togglePlay(!0));if(!e.paused)return vd("Lifecycle.teardown(:ok)","restarted video content"),Rd(t)}({root:e,content:s,ads:r,ui:o,err:t.detail,eventName:t.type}));let d=!!t.autoplay;s.on("viewenter",()=>{d&&!1!==l.autopause&&r.resume()}),s.on("viewleave",Me(()=>{!1!==l.autopause&&(d=!r.paused,r.pause())}))}function bd({ads:t,content:e,state:s}){s.listening||(e.on(["timeupdate",A,E,L],s=>{t.adPlaying&&t.adapter.isLinearAd()&&!t.adapter.isSharedVideoTag()&&!e.paused&&e.pause(),wd({ads:t,content:e,seek:s.type===L})}),s.listening=!0)}function wd({ads:t,content:e,seek:s=!1}){t&&t.setCurrentTime(e.currentTime,void 0,s)}function Rd(t){t.classList.remove("is-seamless")}const kd=Oe("ads/timers");class TimerRegistry{constructor(t={},e={}){this.intervals=t,this.timers=e}}let Id=-1;function Dd(t,e,s){const r=setInterval(s,e);if(kd("TimerRegistry.createInterval() -> "+r,t.intervals),"object"==typeof r){const e=++Id;return t.intervals[e]=e,e}return t.intervals[r]=r,r}function Cd(t){if(t)return kd("TimerRegistry.empty()",Object.keys(t.timers),Object.keys(t.intervals)),Object.keys(t.intervals).forEach(e=>function(t,e){return kd("TimerRegistry.removeInterval() -> "+e,t.intervals),clearInterval(t.intervals[e]),delete t.intervals[e],t}(t,e)),Object.keys(t.timers).forEach(e=>function(t,e){return kd("TimerRegistry.removeTimeout() -> "+e,t.timers),clearTimeout(t.timers[e]),delete t.timers[e],t}(t,e)),t}function Pd(t){try{return t.getAdPodInfo().getPodIndex()}catch(t){return}}class IMA{constructor(t){this.eventHandler=t,this.log=Oe("ads/adapter/ima"),this.google=window.google,this._adHandlers=[],this._timers=new TimerRegistry,this._started=!1,this._volumeLevel=0,this._adLoaded=!1,this._paused=!1,this._all_ads_completed=!1,this._currentDuration=0,this._currentRemaining=0,this._currentDisplayTs=0,this._iosPlaysInline=!1,this.sharedVideoTag=!1,this._isInitialized=!1,this._prepared=!1,this.opts={}}async init(t){this.log("init",this.videoTag,t),this.opts=t,this._dimensions={width:t.width,height:t.height,linear:t.linear},this._prepared=!0,!this._isInitialized&&this.videoTag&&await this.initAdapter()}async initAdapter(){this.log("initAdapter",this.opts);try{await this.initialize(this.opts),this._isInitialized=!0}catch(t){this.log("initAdapter failed:",t),this._prepared=!1,this.eventHandler.trigger("ad-adapter-init-failed")}}isReady(){return!!this._isInitialized}setIOSPlaysInline(t){this.log("setIOSPlaysInline",t),this.sharedVideoTag=!t,this.initialize(Object.assign(Object.assign({},this.opts),{DisableCustomPlaybackForIOS10Plus:t}))}getIOSPlaysInline(){return this._iosPlaysInline}setVideoTag(t){this.videoTag=t}isLinearAd(){return!!this._adLinear}isSharedVideoTag(){return!!this.sharedVideoTag}getVideoTag(){return this.videoTag}getDimensions(){return this._dimensions||{}}getOpts(){return this.opts}isPaused(){return this._paused}destroy(){Cd(this._timers),this._adHandlers&&this._adHandlers.forEach(t=>t()),this._adHandlers=void 0,this._adDisplayContainer&&this._adDisplayContainer.destroy(),this._adDisplayContainer=void 0,this._adsLoader&&this._adsLoader.destroy(),this._adsLoader=void 0,this._adsManager&&this._adsManager.destroy(),this._adsManager=void 0}stop(){this._adsManager&&this._adsManager.stop()}initialize(t){const e=this.isAdPod(),r=this._adLoaded||e;if(this.cleanup(),!this.videoTag)return console.warn("videoTag not set during initialization");this.opts=t,this._volumeLevel=t.volume;const i=this.google.ima.settings;t.NumRedirects=t.NumRedirects||t.redirects;const n={VpaidMode:this.google.ima.ImaSdkSettings.VpaidMode.INSECURE,DisableCustomPlaybackForIOS10Plus:!0};if(i.setVpaidMode(t.VpaidMode||n.VpaidMode),i.setDisableCustomPlaybackForIOS10Plus(t.DisableCustomPlaybackForIOS10Plus||n.DisableCustomPlaybackForIOS10Plus),"NumRedirects"in t&&i.setNumRedirects(t.NumRedirects),"AutoPlayAdBreaks"in t&&i.setAutoPlayAdBreaks(t.AutoPlayAdBreaks),"Locale"in t&&i.setLocale(t.Locale),"Ppid"in t&&i.setPpid(t.Ppid),!document.body.contains(t.container))throw new Error("AdDisplayContainer was not found in the document.body");this._adDisplayContainer=new this.google.ima.AdDisplayContainer(t.container,s().tizen||s().webOS?void 0:this.videoTag),this._adDisplayContainer.initialize(),this._adsLoader=new this.google.ima.AdsLoader(this._adDisplayContainer),this.log("ima.initialise(:wait -> ADS_MANAGER_LOADED)",Object.assign(Object.assign({},t),{volume:this.videoTag.volume,muted:this.videoTag.muted})),this._adsLoader.addEventListener(this.google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,e=>{if(!this.videoTag)return;this.log("ima.initialise(:done -> ADS_MANAGER_LOADED)\n%o",Object.assign(Object.assign({},t),{volume:this.videoTag.volume,muted:this.videoTag.muted}));const s=new this.google.ima.AdsRenderingSettings;this.log("ima.rendering(preload: %s)",!!t.preload_ads),s.useStyledNonLinearAds=!0,s.enablePreloading=!!t.preload_ads,"number"==typeof t.media_timeout&&(s.loadVideoTimeout=t.media_timeout),s.restoreCustomPlaybackStateOnAdBreakComplete=!t.DisableCustomPlaybackForIOS10Plus,this.sharedVideoTag&&(s.playAdsAfterTime=this.videoTag.currentTime),this.eventHandler.trigger("ad-ima-rendering-settings",s);const r=this._adsManager=e.getAdsManager(this.videoTag,s);this.eventHandler.trigger("ad-ima-adapter-init",r),r.addEventListener(this.google.ima.AdEvent.Type.LOADED,()=>{this.log("debug(ima.adsManager): google.ima.AdEvent.Type.LOADED")}),r.addEventListener(this.google.ima.AdErrorEvent.Type.AD_ERROR,()=>{this.log("debug(ima.adsManager): google.ima.AdErrorEvent.Type.AD_ERROR")}),r.addEventListener(this.google.ima.AdEvent.Type.STARTED,()=>{this.log("debug(ima.adsManager): google.ima.AdEvent.Type.STARTED")}),r.addEventListener(this.google.ima.AdEvent.Type.AD_PROGRESS,t=>{var e,s;const r=null===(e=t.getAdData())||void 0===e?void 0:e.duration,i=null===(s=t.getAdData())||void 0===s?void 0:s.currentTime;isNaN(r)||isNaN(i)||(this._currentRemaining=r-i,this.eventHandler.trigger("ad-progress",{remaining:this._currentRemaining,duration:r}))}),r.addEventListener(this.google.ima.AdEvent.Type.STARTED,t=>{this._currentRemaining=-1,this.debugEvent(t);const e=t.getAd();e&&(this._currentDuration=e.getDuration(),this._currentDisplayTs=Date.now(),this.emitWithAd("ad-started",e),e.isLinear()&&IMA.pollRemaining({ima:this,adsManager:r}))}),r.addEventListener(this.google.ima.AdEvent.Type.COMPLETE,t=>{this.debugEvent(t);const e=t.getAd();e&&this.emitWithAd("ad-completed",e),Cd(this._timers)}),r.addEventListener(this.google.ima.AdEvent.Type.SKIPPED,t=>{this.debugEvent(t);const e=t.getAd();e&&this.emitWithAd("ad-skipped",e)}),r.addEventListener(this.google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,t=>{this.debugEvent(t);const e=t.getAd();e&&this.emitWithAd("ad-pause-content",e)});const i=()=>{this._started=!1,this._currentDisplayTs=0,this.eventHandler.trigger("ad-break-completed")};r.addEventListener(this.google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,t=>{this.debugEvent(t),i()}),r.addEventListener(this.google.ima.AdEvent.Type.VOLUME_CHANGED,t=>{this.log("IMA::volume(type: %s, event: %o)",t);const e=r.getVolume();this._volumeLevel=e,this.eventHandler.trigger("ad-volume-changed",e)});const n=t=>{this._paused=t,this.eventHandler.trigger(t?"ad-paused":"ad-resumed")};r.addEventListener(this.google.ima.AdEvent.Type.PAUSED,()=>n(!0)),r.addEventListener(this.google.ima.AdEvent.Type.RESUMED,()=>n(!1)),r.addEventListener(this.google.ima.AdEvent.Type.STARTED,()=>n(!1)),r.addEventListener(this.google.ima.AdEvent.Type.VOLUME_MUTED,t=>{this.log("IMA::volume(type: %s, event: %o)","mute",t),this.eventHandler.trigger("ad-muted")});const{width:a,height:o}=t;a&&o&&(r.init(a,o,this.google.ima.ViewMode.NORMAL),this.log("ima.initialise: done initializing"))}),r&&(this.log("Event(reload: %s)","reload-ad-requested"),this.eventHandler.trigger("reload-ad-requested",e)),this.eventHandler.trigger(gd,this)}destroyManager(t="unknown"){if(!this._adsManager)return this.log("ima::destroyManager(:skip, label: %s)",t);this.log("ima::destroyManager(:ok, label: %s)",t),this._adsManager.destroy()}reset(){this.destroyManager("reset"),Cd(this._timers),this.clearAdHandlers(),this._started=!1,this._adLoaded=!1}cleanup(){this.destroyManager("cleanup"),this._adsLoader&&this._adsLoader.destroy(),this._adDisplayContainer&&this._adDisplayContainer.destroy(),this._adLoaded=!1}waitForAdsManager(){return new Promise(t=>{this.log("ima.waitForAdsManager:",this._adsManager),this.once(this._adsLoader,this.google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,()=>{this.log("ima.waitForAdsManager(:ok)",this._adsManager),t(this._adsManager)})})}async initAd(t,e=5e3){this.log(`ima.initAd(adTag: ${t}, timeout: ${e})`);try{await this.requestAd(t,e),this._adLoaded=!0}catch(t){throw this.log("ima.initAd:",t),this._adLoaded=!1,t}finally{Cd(this._timers)}}async requestAd(t,e){if(this.destroyManager("requestAd"),!this.videoTag)return;const{autoplay:s=!1}=this.opts,r=Date.now(),i=this.videoTag.muted;this._volumeLevel=this.videoTag.volume;const n=i||0==this._volumeLevel;this._all_ads_completed=!1,this.log("ima.requestAd(%o)",Object.assign(Object.assign({},this.opts),{autoplay:s,muted:i,timeout:e,adTag:t,_volumeLevel:this._volumeLevel,manager:this._adsManager})),this.clearAdHandlers();const a=new this.google.ima.AdsRequest;a.adTagUrl=t;const{height:o,width:l}=this.opts;if(l&&(a.linearAdSlotWidth=l),o&&(a.linearAdSlotHeight=o),!this.opts.disable_non_linear_ads&&l&&(a.nonLinearAdSlotWidth=l),!this.opts.disable_non_linear_ads&&o&&(a.nonLinearAdSlotHeight=o-50),a.setAdWillAutoPlay(s),a.setAdWillPlayMuted(n),a.vastLoadTimeout=e,this.eventHandler.trigger("ad-ima-before-ads-request",{request:a}),!this._adsLoader)return;this._adsLoader.requestAds(a);return new Promise(async(t,s)=>{const i=e=>{clearTimeout(o),t(e)},a=t=>{clearTimeout(o),s(t)};this.once(this._adsLoader,this.google.ima.AdErrorEvent.Type.AD_ERROR,t=>{this.emitError("ad-request-error",t),a(new Error("Ad load failed"))});const o=setTimeout(()=>{const t=new Error("Ad internal timeout reached");this.eventHandler.trigger("ad-timeout",t),s(t)},1.5*(e+(this.opts.media_timeout||5e3))),l=await this.waitForAdsManager();this.volume(n?0:this._volumeLevel),this.eventHandler.trigger("ad-volume-changed",this._volumeLevel);const d=this.cuepoints();if(d&&d.length&&0!==d[0])return i({ad:!1,adsManager:l});this.once(l,this.google.ima.AdErrorEvent.Type.AD_ERROR,t=>{this.emitError("ad-playback-error",t),a(t)}),this.once(l,this.google.ima.AdEvent.Type.ALL_ADS_COMPLETED,()=>{this._all_ads_completed=!0,i(null)}),this.once(l,this.google.ima.AdEvent.Type.LOADED,t=>{this.eventHandler.trigger("ad-request-completed",{request_load_time:Date.now()-r});const e=t.getAd();e&&(this.log("ima.requestAd: AD_REQUEST_COMPLETED",e.getContentType()),"application/javascript"==e.getContentType()&&this.eventHandler.trigger("vpaid-init",e),i(null))}),this.once(l,this.google.ima.AdEvent.Type.CLICK,()=>{this.log("ima.requestAd: click event"),this.pause()})})}async playAd(){if(this.log("ima.playAd()",this),!this._adsManager||!this._adLoaded)return;const t=this.currentAd();if(t&&(!this.sharedVideoTag||t.isLinear()))try{await this.startAndWaitForAdCompletion(this._adsManager,t.isLinear())}catch(t){throw this.log("ima.playAd",t),t}finally{this._adLoaded=!1,Cd(this._timers)}}startAndWaitForAdCompletion(t,e){if(!this._started)return this.log("ima.startAndWaitForAdCompletion(manager: %o)",{volume:t.getVolume()}),new Promise((s,r)=>{let i=!1;this.once(t,this.google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,()=>{if(this.log("ima.startAndWaitForAdCompletion: CONTENT_RESUME_REQUESTED <<< happened"),this._started=!1,i)return this.log("ima.startAndWaitForAdCompletion: Content resume requested, but trying to recover from ad error");s()}),this.once(t,this.google.ima.AdErrorEvent.Type.AD_ERROR,async t=>{this.log("ima.startAndWaitForAdCompletion: beginning error recovery ->",t),i=!0;try{const{ok:e}=await IMA.pollForFatalError({err:t,ima:this});e&&(i=!1)}catch(e){this._started=!1,r(t)}});const n=this.getVideoTag();if(!n)return;const a=()=>{e&&(this._started=!0),t.start(),this.eventHandler.trigger("ad-play-requested")};if(!e||n.hasState(ht)||n.hasState("is-popped-out"))return a();n.paused||n.pause(),n.once("viewenter",()=>a())})}pause(){this.log("ima.pause()"),this._adsManager&&this._adsManager.pause()}resume(){this.log("ima.resume()"),this._adsManager&&this._adsManager.resume()}volume(t){if(this._adsManager)try{return arguments.length>0&&"number"==typeof t&&this._adsManager.setVolume(t),this._volumeLevel=this._adsManager.getVolume()}catch(t){this.log("ima.volume() failed (%o)",t)}}onResize({width:t,height:e,linear:s,silent:r,resize_non_linear:i}){this._adsManager&&(this._adLinear=void 0===s?this._adLinear:s,this.opts&&(t||e)&&(!1===s&&(t+=10,e+=10),this._dimensions={width:t,height:e,linear:s},s&&(this.opts.width=t,this.opts.height=e),(this._adLinear||i)&&(r||this.log("ima.onResize %s x %s",t,e),this._adsManager.resize(t,e,this.google.ima.ViewMode.NORMAL))))}getAdInfo(){const t=this.currentAd();if(t)return{duration:t.getDuration(),currentTime:this._currentRemaining}}currentAd(){const t=this._adsManager;if(t)return t.getCurrentAd()}isAdPod(){const t=this.cuepoints();return!!(t&&t.length>1)}cuepoints(){return this._adsManager&&this._adsManager.getCuePoints()}async contentComplete(){this.log("ima.contentComplete() -> ",this),this._adsLoader&&this._adsLoader.contentComplete();const t=this.cuepoints();t&&-1!==t.indexOf(-1)&&await new Promise(t=>{IMA.race(this.eventHandler,["ad-break-completed","ad-error"],t)})}isUiDisabled(){try{const t=this.currentAd();return t&&t.isUiDisabled()}catch(t){return null}}getAdPodInfo(){try{const t=this.currentAd();return t&&t.getAdPodInfo()}catch(t){return null}}canDismissNonLinear(){const t=this.currentAd();if(!t||t.isLinear()||!this._adsManager||!this._currentDisplayTs)return!0;const e=Date.now(),s=t.getMinSuggestedDuration();return e-this._currentDisplayTs>1e3*s}static unwrapError(t,e){if(!t)return"";if("function"==typeof t.getMessage){return t.getMessage()}return t.message?t.message:e||""}static pollForFatalError({err:t,ima:e}){let s;try{const e=t.getError(),r=e.getInnerError(),i=r?IMA.unwrapError(r,e.message):"";s={reason:i,type:e.getType(),code:e.getErrorCode()}}catch(t){}const r=e._currentRemaining;return new Promise((t,i)=>{const n=setTimeout(()=>{e.eventHandler&&e.eventHandler.trigger("ad-playback-error",s),i(new Error("Ad not progressing"))},2500);e.eventHandler.once("ad-progress",e=>{const s=e.detail.remaining;-1!==s&&s<r&&(clearTimeout(n),t({ok:1}))})})}static pollRemaining({ima:t,adsManager:e}){let s=-1;return Dd(t._timers,250,(function(){const r=e.getRemainingTime();-1!=t._currentRemaining&&t._currentRemaining<=r||(t._currentRemaining=e.getRemainingTime(),s!=t._currentRemaining&&(s=t._currentRemaining,t.eventHandler.trigger("ad-progress",{remaining:t._currentRemaining,duration:t._currentDuration})))}))}once(t,e,s){this._adHandlers.push(function(t,e,s){const r=i=>{s(i),t.removeEventListener(e,r)};return t.addEventListener(e,r),()=>t.removeEventListener(e,r)}(t,e,s))}static race(t,e,s){e.forEach(r=>{const i=(...r)=>{e.forEach(e=>t.removeListener(e,i)),s(r)};t.on(r,i)})}clearAdHandlers(){this.log("ima.clearAdHandlers"),this._adHandlers.forEach(t=>t()),this._adHandlers=[]}emitWithAd(t,e){if(this.log("ima.emitWithAd",t,e),!this._adsManager)return;const s=function(t){try{return t.getAdPodInfo().getAdPosition()}catch(t){return}}(e),r=function(t){try{return t.getAdPodInfo().getTotalAds()}catch(t){return}}(e),i={ad:{duration:e.getDuration(),width:e.getWidth(),height:e.getHeight(),position:s,totals:r},volume:this._adsManager.getVolume(),vast_ad_id:e.getAdId(),linear:e.isLinear(),mime_type:e.getContentType(),ima_event:!0};this.log(`emitWithAd::event(name: ${t}, data: %o, ad: %o)`,i,e),this.eventHandler.trigger(t,i)}emitError(t,e){const s={vast_error_type:e.getError().getType(),reason:e.getError().getMessage(),vast_error:e.getError().getErrorCode()};this.log(`ima.error(${t})`,s),this.eventHandler.trigger(t,s)}debugEvent(t){try{const e=t.getAd();if(!e)return;this.log(`ima.event.${t.type} ->`,{event:t,data:t.getAdData(),position:Pd(e),ad:e})}catch(t){}}}var Od=Ge((function(t,e){var s=function(){for(var t=new Array(256),e=0;e<256;++e)t[e]="%"+((e<16?"0":"")+e.toString(16)).toUpperCase();return t}(),r=Object.prototype.hasOwnProperty;e.arrayToObject=function(t,e){for(var s=e.plainObjects?Object.create(null):{},r=0;r<t.length;++r)void 0!==t[r]&&(s[r]=t[r]);return s},e.merge=function(t,s,i){if(!s)return t;if("object"!=typeof s){if(Array.isArray(t))t.push(s);else{if("object"!=typeof t)return[t,s];(i.plainObjects||i.allowPrototypes||!r.call(Object.prototype,s))&&(t[s]=!0)}return t}if("object"!=typeof t)return[t].concat(s);var n=t;return Array.isArray(t)&&!Array.isArray(s)&&(n=e.arrayToObject(t,i)),Object.keys(s).reduce((function(t,n){var a=s[n];return r.call(t,n)?t[n]=e.merge(t[n],a,i):t[n]=a,t}),n)},e.decode=function(t){try{return decodeURIComponent(t.replace(/\+/g," "))}catch(e){return t}},e.encode=function(t){if(0===t.length)return t;for(var e="string"==typeof t?t:String(t),r="",i=0;i<e.length;++i){var n=e.charCodeAt(i);45===n||46===n||95===n||126===n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122?r+=e.charAt(i):n<128?r+=s[n]:n<2048?r+=s[192|n>>6]+s[128|63&n]:n<55296||n>=57344?r+=s[224|n>>12]+s[128|n>>6&63]+s[128|63&n]:(i+=1,n=65536+((1023&n)<<10|1023&e.charCodeAt(i)),r+=s[240|n>>18]+s[128|n>>12&63]+s[128|n>>6&63]+s[128|63&n])}return r},e.compact=function(t,s){if("object"!=typeof t||null===t)return t;var r=s||[],i=r.indexOf(t);if(-1!==i)return r[i];if(r.push(t),Array.isArray(t)){for(var n=[],a=0;a<t.length;++a)t[a]&&"object"==typeof t[a]?n.push(e.compact(t[a],r)):void 0!==t[a]&&n.push(t[a]);return n}for(var o=Object.keys(t),l=0;l<o.length;++l){var d=o[l];t[d]=e.compact(t[d],r)}return t},e.isRegExp=function(t){return"[object RegExp]"===Object.prototype.toString.call(t)},e.isBuffer=function(t){return null!=t&&!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}})),Md={brackets:function(t){return t+"[]"},indices:function(t,e){return t+"["+e+"]"},repeat:function(t){return t}},xd={delimiter:"&",strictNullHandling:!1,skipNulls:!1,encode:!0,encoder:Od.encode},Fd=function t(e,s,r,i,n,a,o,l,d){var c=e;if("function"==typeof o)c=o(s,c);else if(c instanceof Date)c=c.toISOString();else if(null===c){if(i)return a?a(s):s;c=""}if("string"==typeof c||"number"==typeof c||"boolean"==typeof c||Od.isBuffer(c))return a?[a(s)+"="+a(c)]:[s+"="+String(c)];var u,h=[];if(void 0===c)return h;if(Array.isArray(o))u=o;else{var f=Object.keys(c);u=l?f.sort(l):f}for(var g=0;g<u.length;++g){var p=u[g];n&&null===c[p]||(h=Array.isArray(c)?h.concat(t(c[p],r(s,p),r,i,n,a,o,l,d)):h.concat(t(c[p],s+(d?"."+p:"["+p+"]"),r,i,n,a,o,l,d)))}return h},Nd=Object.prototype.hasOwnProperty,Ud={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3,strictNullHandling:!1,plainObjects:!1,allowPrototypes:!1,allowDots:!1,decoder:Od.decode},Bd=function(t,e,s){if(t){var r=s.allowDots?t.replace(/\.([^.[]+)/g,"[$1]"):t,i=/(\[[^[\]]*])/g,n=/(\[[^[\]]*])/.exec(r),a=n?r.slice(0,n.index):r,o=[];if(a){if(!s.plainObjects&&Nd.call(Object.prototype,a)&&!s.allowPrototypes)return;o.push(a)}for(var l=0;null!==(n=i.exec(r))&&l<s.depth;){if(l+=1,!s.plainObjects&&Nd.call(Object.prototype,n[1].slice(1,-1))&&!s.allowPrototypes)return;o.push(n[1])}return n&&o.push("["+r.slice(n.index)+"]"),function t(e,s,r){if(!e.length)return s;var i,n=e.shift();if("[]"===n)i=(i=[]).concat(t(e,s,r));else{i=r.plainObjects?Object.create(null):{};var a="["===n.charAt(0)&&"]"===n.charAt(n.length-1)?n.slice(1,-1):n,o=parseInt(a,10);!isNaN(o)&&n!==a&&String(o)===a&&o>=0&&r.parseArrays&&o<=r.arrayLimit?(i=[])[o]=t(e,s,r):i[a]=t(e,s,r)}return i}(o,e,s)}},Gd=function(t,e){var s,r,i=t,n=e||{},a=void 0===n.delimiter?xd.delimiter:n.delimiter,o="boolean"==typeof n.strictNullHandling?n.strictNullHandling:xd.strictNullHandling,l="boolean"==typeof n.skipNulls?n.skipNulls:xd.skipNulls,d=("boolean"==typeof n.encode?n.encode:xd.encode)?"function"==typeof n.encoder?n.encoder:xd.encoder:null,c="function"==typeof n.sort?n.sort:null,u=void 0!==n.allowDots&&n.allowDots;if(null!==n.encoder&&void 0!==n.encoder&&"function"!=typeof n.encoder)throw new TypeError("Encoder has to be a function.");"function"==typeof n.filter?i=(r=n.filter)("",i):Array.isArray(n.filter)&&(s=r=n.filter);var h,f=[];if("object"!=typeof i||null===i)return"";h=n.arrayFormat in Md?n.arrayFormat:"indices"in n?n.indices?"indices":"repeat":"indices";var g=Md[h];s||(s=Object.keys(i)),c&&s.sort(c);for(var p=0;p<s.length;++p){var m=s[p];l&&null===i[m]||(f=f.concat(Fd(i[m],m,g,o,l,d,r,c,u)))}return f.join(a)},$d=function(t,e){var s=e||{};if(null!==s.decoder&&void 0!==s.decoder&&"function"!=typeof s.decoder)throw new TypeError("Decoder has to be a function.");if(s.delimiter="string"==typeof s.delimiter||Od.isRegExp(s.delimiter)?s.delimiter:Ud.delimiter,s.depth="number"==typeof s.depth?s.depth:Ud.depth,s.arrayLimit="number"==typeof s.arrayLimit?s.arrayLimit:Ud.arrayLimit,s.parseArrays=!1!==s.parseArrays,s.decoder="function"==typeof s.decoder?s.decoder:Ud.decoder,s.allowDots="boolean"==typeof s.allowDots?s.allowDots:Ud.allowDots,s.plainObjects="boolean"==typeof s.plainObjects?s.plainObjects:Ud.plainObjects,s.allowPrototypes="boolean"==typeof s.allowPrototypes?s.allowPrototypes:Ud.allowPrototypes,s.parameterLimit="number"==typeof s.parameterLimit?s.parameterLimit:Ud.parameterLimit,s.strictNullHandling="boolean"==typeof s.strictNullHandling?s.strictNullHandling:Ud.strictNullHandling,""===t||null==t)return s.plainObjects?Object.create(null):{};for(var r="string"==typeof t?function(t,e){for(var s={},r=t.split(e.delimiter,e.parameterLimit===1/0?void 0:e.parameterLimit),i=0;i<r.length;++i){var n,a,o=r[i],l=-1===o.indexOf("]=")?o.indexOf("="):o.indexOf("]=")+1;-1===l?(n=e.decoder(o),a=e.strictNullHandling?null:""):(n=e.decoder(o.slice(0,l)),a=e.decoder(o.slice(l+1))),Nd.call(s,n)?s[n]=[].concat(s[n]).concat(a):s[n]=a}return s}(t,s):t,i=s.plainObjects?Object.create(null):{},n=Object.keys(r),a=0;a<n.length;++a){var o=n[a],l=Bd(o,r[o],s);i=Od.merge(i,l,s)}return Od.compact(i)};const Hd=Oe("fpads:macros"),Kd=/\[([\s\S]+?)\]/g;class Macros{constructor(t={},e=Kd){this.vars=t,this.pattern=e}static run(t){try{return t()}catch(t){return void console.error(t)}}static merge(...t){return t.reduce((t,e)=>Object.assign(t,e),{})}static cast(t){return void 0===t?"":"function"==typeof t?encodeURIComponent(Macros.run(t)||""):"string"==typeof t?encodeURIComponent(t):"number"==typeof t||"boolean"==typeof t?t.toString():""}static normalize(t){return t.trim()}static process_obj(t,e,s){return Object.keys(t).reduce((r,i)=>{const n=Macros.process_str(i,e,s,!0),a=t[i];return null===a?(r[n]=a,r):"object"==typeof a?(r[n]=Macros.process_obj(a,e,s),r):"string"==typeof a?(r[n]=Macros.process_str(a,e,s),r):(console.error(new Error(`${a} at ${i} not a handled Macro type`)),r)},{})}static process_str(t,e,s,r=!1){return t.replace(e.pattern,(t,e)=>{const i=Macros.normalize(e);if(!(i in s)||void 0===s[i])return t;const n=s[i],a=r?n:Macros.cast(n);return Hd("Macro.replace(raw: %s, macro: %s, value: %s)",r,e,a),a})}fork(t={},e=this.pattern){const s=Macros.merge(this.vars,t);return new Macros(s,e)}compile(t,e={}){const s=Macros.merge(this.vars,e),[r,i]=t.split("?"),n=$d(i||"",{strictNullHandling:!0,decoder:t=>t}),a=Gd(Macros.process_obj(n,this,s),{encode:!1,strictNullHandling:!0});return Macros.process_str(r,this,s,!0)+"?"+a}}function Vd(t,e={width:0,height:0}){let s,r;try{const t=document.createElement("a");t.href=s=window.location!=window.parent.location?document.referrer:document.location.href,r=t.hostname}catch(t){console.error(t)}const{width:i,height:n}=e,{video_source:a}=t||{},o=function(){const t=window;return"object"==typeof t.__flowplayerAdParameters?t.__flowplayerAdParameters:{}}();return Object.assign({random:Date.now(),page_url:s,domain:r,player_width:i,player_height:n,video_url:a,videourl:a},o)}Macros.patterns={BRACKETS:Kd,CURLY:/\{([\s\S]+?)\}/g,UNDERSCORE:/__([\s\S]+?)__/g};const qd=/^flowplayer:\/\/(.+)/;async function jd(t){if("string"==typeof t&&qd.test(t)){const e=qd.exec(t),s=e&&window[e[1]];if(s)return jd(s)}if("function"!=typeof t)return t;try{return await t()}catch(t){return""}}class Schedule{constructor(t,e={}){this._ads=t,this._opts=e,this._nextIndex=0,this._postroll=void 0,this._loadPending=!1,this._postrollActive=!1,this.reset(this._ads)}toJSON(){const t=(this._ads||[]).slice(this._nextIndex);return this._postroll&&t.push(this._postroll),t}reset(t){this.setAds(t),this._nextIndex=0,this._postrollActive=!1}resetCounter(){this._nextIndex=0,this._postrollActive=!1}setAds(t){this._ads=t||[],this.sort()}getAds(){return this._ads}getNextAd(t){return this._ads[this._nextIndex]||t}getCurrentAd(){return this._postrollActive?this._postroll:this._loadPending?0:this._ads[this._nextIndex-1]}getPostroll(){return this._postroll}isDrained(){return this._nextIndex+1>this._ads.length}setPostrollActive(){this._postrollActive=!0}updateContentDuration(t){this._opts.content_duration=t}increment(){++this._nextIndex}decrement(){this._nextIndex>0&&--this._nextIndex}getNextIndex(){return this._nextIndex}getCurrentType(){const t=this.getCurrentAd();if(t)return Schedule.kindOf(t.time)}sort(){this._postroll=this._ads.find(t=>-1===t.time),this._ads=this._ads.filter(t=>t!==this._postroll).sort((t,e)=>t.time===e.time?this._ads.indexOf(t)-this._ads.indexOf(e):t.time-e.time)}shallPlayAd(t){if(this._loadPending)return!1;const e=this.getCurrentAd()||this.getNextAd();return!!(e&&e.time<=t&&-1!==e.time)}shallPlayNext(){const t=this.getNextAd(),e=this.getCurrentAd();return!(!t||!e||t.time!==e.time)}waitForLoad(t,e,s){if(this._loadPending=!1,!e)return!1;const r=s?this._opts.preload_advance:0;return e.time>=0?this._loadPending=t<e.time-r:-1===e.time&&(this._loadPending=this._opts.content_duration>0&&-1!==t?t<this._opts.content_duration-r:-1!==t),this._loadPending}static hasPreroll(t){return!!t.find(t=>0===t.time)}static isOutstream(t){return Schedule.hasPreroll(t)&&!!t[0].outstream}static kindOf(t){switch(t){case 0:return"preroll";case-1:return"postroll";default:return"midroll"}}}const Wd=Object.prototype,Yd=Object.getPrototypeOf;const zd=Oe("fpads:ads:state");var Xd;!function(t){t[t.IDLE=0]="IDLE",t[t.INITIALIZING=1]="INITIALIZING",t[t.FETCHING_AD=2]="FETCHING_AD",t[t.AD_AVAILABLE=4]="AD_AVAILABLE",t[t.BREAK_ACTIVE=8]="BREAK_ACTIVE",t[t.PLAYING=16]="PLAYING",t[t.FATAL_ERROR=32]="FATAL_ERROR"}(Xd||(Xd={}));class AdsState{constructor(t=0){this._state=t}static of(){return new AdsState}reset(){this._state=0}toggleState(t,e){return void 0===t&&zd(new Error("AdState cannot toggleState for `undefined`")),null==typeof e?this._state^=t:e?void(this._state|=t):this._state&=~t}hasAll(t){return this._state==(this._state|t)}hasAny(t){return!!(this._state&t)}get state(){return this._state}}const Qd={ok:Oe("fpads:analytics:request-queue"),err:Oe("fpads:analytics:request-queue:err"),warn:Oe("fpads:analytics:request-queue:warn")};class RequestQueue{constructor(t=[],e=[],s={failures:0,ttl:0}){this.pending=t,this.open=e,this.stats=s}static of(){return new RequestQueue}static is_empty(t){return 0==t.pending.length}static is_high_water(t){return t.open.length==RequestQueue.MAX_OPEN_REQUESTS}static maybe_spawn_req(t){if(RequestQueue.is_empty(t))return Qd.ok("maybe_spawn_req called Queue that is EMPTY"),t;if(RequestQueue.is_high_water(t))return Qd.warn("maybe_spawn_req called on Queue that is HIGH_WATER"),t;try{const e=RequestQueue.lpop(t);e&&RequestQueue.request(t,e)}catch(t){Qd.err(t)}}static increment_failures(t){return t.stats.failures++,t.stats.failures>RequestQueue.MAX_FAILURE_COUNT&&(t.stats.ttl=Date.now()+RequestQueue.REQUEST_TTL_MS),t}static handle_error(t,e){RequestQueue.rm(t,e),RequestQueue.increment_failures(t)}static request(t,[e,s,r]){if(Qd.ok(`Request[${r.event_type}] request`,r,t.stats),Date.now()<t.stats.ttl)return Qd.warn(`Request[${r.event_type}] skipping because too many errors too quickly`,t.stats);const i=new XMLHttpRequest;t.open.push(i),i.timeout=RequestQueue.REQUEST_TIMEOUT_MS,i.ontimeout=function(){RequestQueue.handle_error(t,i),Qd.warn(`Request[${r.event_type}] timed out in ${i.timeout}ms`,t.stats)},i.onerror=function(e){RequestQueue.handle_error(t,i),e&&Qd.err(e),Qd.warn(`Request[${r.event_type}] encountered an Error`,i.responseText,t.stats)},i.onreadystatechange=function(){i.readyState==XMLHttpRequest.DONE&&RequestQueue.rm(t,i),Math.floor(i.status/100)},i.onload=function(){RequestQueue.rm(t,i),t.stats.failures&&t.stats.failures--,Qd.ok(`Request[${r.event_type}] :ok`,i.status)},i.open(s,e),i.setRequestHeader("Content-Type","text/plain;charset=UTF-8");try{i.send(JSON.stringify(r))}catch(t){Qd.err(t)}}static rpush(t,...e){return e.forEach(e=>{if(RequestQueue.is_high_water(t))return Qd.warn("Too many open requests, skipping",t.stats);t.pending.push(e),RequestQueue.maybe_spawn_req(t)}),t}static lpop(t){return t.pending.shift()}static rm(t,e){const s=t.open.lastIndexOf(e);return~s&&t.open.splice(s,1),t}}RequestQueue.MAX_OPEN_REQUESTS=3,RequestQueue.REQUEST_TIMEOUT_MS=4e3,RequestQueue.REQUEST_TTL_MS=5e3,RequestQueue.MAX_FAILURE_COUNT=3;const Zd={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},Jd={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},tc={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},ec={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},sc={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class Utils{static getFirstMatch(t,e){const s=e.match(t);return s&&s.length>0&&s[1]||""}static getSecondMatch(t,e){const s=e.match(t);return s&&s.length>1&&s[2]||""}static matchAndReturnConst(t,e,s){if(t.test(e))return s}static getWindowsVersionName(t){switch(t){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(t){const e=t.split(".").splice(0,2).map(t=>parseInt(t,10)||0);if(e.push(0),10===e[0])switch(e[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(t){const e=t.split(".").splice(0,2).map(t=>parseInt(t,10)||0);if(e.push(0),!(1===e[0]&&e[1]<5))return 1===e[0]&&e[1]<6?"Cupcake":1===e[0]&&e[1]>=6?"Donut":2===e[0]&&e[1]<2?"Eclair":2===e[0]&&2===e[1]?"Froyo":2===e[0]&&e[1]>2?"Gingerbread":3===e[0]?"Honeycomb":4===e[0]&&e[1]<1?"Ice Cream Sandwich":4===e[0]&&e[1]<4?"Jelly Bean":4===e[0]&&e[1]>=4?"KitKat":5===e[0]?"Lollipop":6===e[0]?"Marshmallow":7===e[0]?"Nougat":8===e[0]?"Oreo":9===e[0]?"Pie":void 0}static getVersionPrecision(t){return t.split(".").length}static compareVersions(t,e,s=!1){const r=Utils.getVersionPrecision(t),i=Utils.getVersionPrecision(e);let n=Math.max(r,i),a=0;const o=Utils.map([t,e],t=>{const e=n-Utils.getVersionPrecision(t),s=t+new Array(e+1).join(".0");return Utils.map(s.split("."),t=>new Array(20-t.length).join("0")+t).reverse()});for(s&&(a=n-Math.min(r,i)),n-=1;n>=a;){if(o[0][n]>o[1][n])return 1;if(o[0][n]===o[1][n]){if(n===a)return 0;n-=1}else if(o[0][n]<o[1][n])return-1}}static map(t,e){const s=[];let r;if(Array.prototype.map)return Array.prototype.map.call(t,e);for(r=0;r<t.length;r+=1)s.push(e(t[r]));return s}static find(t,e){let s,r;if(Array.prototype.find)return Array.prototype.find.call(t,e);for(s=0,r=t.length;s<r;s+=1){const r=t[s];if(e(r,s))return r}}static assign(t,...e){const s=t;let r,i;if(Object.assign)return Object.assign(t,...e);for(r=0,i=e.length;r<i;r+=1){const t=e[r];if("object"==typeof t&&null!==t){Object.keys(t).forEach(e=>{s[e]=t[e]})}}return t}static getBrowserAlias(t){return Zd[t]}static getBrowserTypeByAlias(t){return Jd[t]||""}}const rc=/version\/(\d+(\.?_?\d+)+)/i,ic=[{test:[/googlebot/i],describe(t){const e={name:"Googlebot"},s=Utils.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,t)||Utils.getFirstMatch(rc,t);return s&&(e.version=s),e}},{test:[/opera/i],describe(t){const e={name:"Opera"},s=Utils.getFirstMatch(rc,t)||Utils.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/opr\/|opios/i],describe(t){const e={name:"Opera"},s=Utils.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,t)||Utils.getFirstMatch(rc,t);return s&&(e.version=s),e}},{test:[/SamsungBrowser/i],describe(t){const e={name:"Samsung Internet for Android"},s=Utils.getFirstMatch(rc,t)||Utils.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/Whale/i],describe(t){const e={name:"NAVER Whale Browser"},s=Utils.getFirstMatch(rc,t)||Utils.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/MZBrowser/i],describe(t){const e={name:"MZ Browser"},s=Utils.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,t)||Utils.getFirstMatch(rc,t);return s&&(e.version=s),e}},{test:[/focus/i],describe(t){const e={name:"Focus"},s=Utils.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,t)||Utils.getFirstMatch(rc,t);return s&&(e.version=s),e}},{test:[/swing/i],describe(t){const e={name:"Swing"},s=Utils.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,t)||Utils.getFirstMatch(rc,t);return s&&(e.version=s),e}},{test:[/coast/i],describe(t){const e={name:"Opera Coast"},s=Utils.getFirstMatch(rc,t)||Utils.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(t){const e={name:"Opera Touch"},s=Utils.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,t)||Utils.getFirstMatch(rc,t);return s&&(e.version=s),e}},{test:[/yabrowser/i],describe(t){const e={name:"Yandex Browser"},s=Utils.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,t)||Utils.getFirstMatch(rc,t);return s&&(e.version=s),e}},{test:[/ucbrowser/i],describe(t){const e={name:"UC Browser"},s=Utils.getFirstMatch(rc,t)||Utils.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/Maxthon|mxios/i],describe(t){const e={name:"Maxthon"},s=Utils.getFirstMatch(rc,t)||Utils.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/epiphany/i],describe(t){const e={name:"Epiphany"},s=Utils.getFirstMatch(rc,t)||Utils.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/puffin/i],describe(t){const e={name:"Puffin"},s=Utils.getFirstMatch(rc,t)||Utils.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/sleipnir/i],describe(t){const e={name:"Sleipnir"},s=Utils.getFirstMatch(rc,t)||Utils.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/k-meleon/i],describe(t){const e={name:"K-Meleon"},s=Utils.getFirstMatch(rc,t)||Utils.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/micromessenger/i],describe(t){const e={name:"WeChat"},s=Utils.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,t)||Utils.getFirstMatch(rc,t);return s&&(e.version=s),e}},{test:[/qqbrowser/i],describe(t){const e={name:/qqbrowserlite/i.test(t)?"QQ Browser Lite":"QQ Browser"},s=Utils.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,t)||Utils.getFirstMatch(rc,t);return s&&(e.version=s),e}},{test:[/msie|trident/i],describe(t){const e={name:"Internet Explorer"},s=Utils.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/\sedg\//i],describe(t){const e={name:"Microsoft Edge"},s=Utils.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/edg([ea]|ios)/i],describe(t){const e={name:"Microsoft Edge"},s=Utils.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/vivaldi/i],describe(t){const e={name:"Vivaldi"},s=Utils.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/seamonkey/i],describe(t){const e={name:"SeaMonkey"},s=Utils.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/sailfish/i],describe(t){const e={name:"Sailfish"},s=Utils.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,t);return s&&(e.version=s),e}},{test:[/silk/i],describe(t){const e={name:"Amazon Silk"},s=Utils.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/phantom/i],describe(t){const e={name:"PhantomJS"},s=Utils.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/slimerjs/i],describe(t){const e={name:"SlimerJS"},s=Utils.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e={name:"BlackBerry"},s=Utils.getFirstMatch(rc,t)||Utils.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/(web|hpw)[o0]s/i],describe(t){const e={name:"WebOS Browser"},s=Utils.getFirstMatch(rc,t)||Utils.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/bada/i],describe(t){const e={name:"Bada"},s=Utils.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/tizen/i],describe(t){const e={name:"Tizen"},s=Utils.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,t)||Utils.getFirstMatch(rc,t);return s&&(e.version=s),e}},{test:[/qupzilla/i],describe(t){const e={name:"QupZilla"},s=Utils.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,t)||Utils.getFirstMatch(rc,t);return s&&(e.version=s),e}},{test:[/firefox|iceweasel|fxios/i],describe(t){const e={name:"Firefox"},s=Utils.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/electron/i],describe(t){const e={name:"Electron"},s=Utils.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/MiuiBrowser/i],describe(t){const e={name:"Miui"},s=Utils.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/chromium/i],describe(t){const e={name:"Chromium"},s=Utils.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,t)||Utils.getFirstMatch(rc,t);return s&&(e.version=s),e}},{test:[/chrome|crios|crmo/i],describe(t){const e={name:"Chrome"},s=Utils.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/GSA/i],describe(t){const e={name:"Google Search"},s=Utils.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test(t){const e=!t.test(/like android/i),s=t.test(/android/i);return e&&s},describe(t){const e={name:"Android Browser"},s=Utils.getFirstMatch(rc,t);return s&&(e.version=s),e}},{test:[/playstation 4/i],describe(t){const e={name:"PlayStation 4"},s=Utils.getFirstMatch(rc,t);return s&&(e.version=s),e}},{test:[/safari|applewebkit/i],describe(t){const e={name:"Safari"},s=Utils.getFirstMatch(rc,t);return s&&(e.version=s),e}},{test:[/.*/i],describe(t){const e=-1!==t.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:Utils.getFirstMatch(e,t),version:Utils.getSecondMatch(e,t)}}}];var nc=[{test:[/Roku\/DVP/],describe(t){const e=Utils.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,t);return{name:ec.Roku,version:e}}},{test:[/windows phone/i],describe(t){const e=Utils.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,t);return{name:ec.WindowsPhone,version:e}}},{test:[/windows /i],describe(t){const e=Utils.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,t),s=Utils.getWindowsVersionName(e);return{name:ec.Windows,version:e,versionName:s}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(t){const e={name:ec.iOS},s=Utils.getSecondMatch(/(Version\/)(\d[\d.]+)/,t);return s&&(e.version=s),e}},{test:[/macintosh/i],describe(t){const e=Utils.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,t).replace(/[_\s]/g,"."),s=Utils.getMacOSVersionName(e),r={name:ec.MacOS,version:e};return s&&(r.versionName=s),r}},{test:[/(ipod|iphone|ipad)/i],describe(t){const e=Utils.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,t).replace(/[_\s]/g,".");return{name:ec.iOS,version:e}}},{test(t){const e=!t.test(/like android/i),s=t.test(/android/i);return e&&s},describe(t){const e=Utils.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,t),s=Utils.getAndroidVersionName(e),r={name:ec.Android,version:e};return s&&(r.versionName=s),r}},{test:[/(web|hpw)[o0]s/i],describe(t){const e=Utils.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,t),s={name:ec.WebOS};return e&&e.length&&(s.version=e),s}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e=Utils.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,t)||Utils.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,t)||Utils.getFirstMatch(/\bbb(\d+)/i,t);return{name:ec.BlackBerry,version:e}}},{test:[/bada/i],describe(t){const e=Utils.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,t);return{name:ec.Bada,version:e}}},{test:[/tizen/i],describe(t){const e=Utils.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,t);return{name:ec.Tizen,version:e}}},{test:[/linux/i],describe:()=>({name:ec.Linux})},{test:[/CrOS/],describe:()=>({name:ec.ChromeOS})},{test:[/PlayStation 4/],describe(t){const e=Utils.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,t);return{name:ec.PlayStation4,version:e}}}],ac=[{test:[/googlebot/i],describe:()=>({type:"bot",vendor:"Google"})},{test:[/huawei/i],describe(t){const e=Utils.getFirstMatch(/(can-l01)/i,t)&&"Nova",s={type:tc.mobile,vendor:"Huawei"};return e&&(s.model=e),s}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:()=>({type:tc.tablet,vendor:"Nexus"})},{test:[/ipad/i],describe:()=>({type:tc.tablet,vendor:"Apple",model:"iPad"})},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:()=>({type:tc.tablet,vendor:"Apple",model:"iPad"})},{test:[/kftt build/i],describe:()=>({type:tc.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"})},{test:[/silk/i],describe:()=>({type:tc.tablet,vendor:"Amazon"})},{test:[/tablet(?! pc)/i],describe:()=>({type:tc.tablet})},{test(t){const e=t.test(/ipod|iphone/i),s=t.test(/like (ipod|iphone)/i);return e&&!s},describe(t){const e=Utils.getFirstMatch(/(ipod|iphone)/i,t);return{type:tc.mobile,vendor:"Apple",model:e}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:()=>({type:tc.mobile,vendor:"Nexus"})},{test:[/[^-]mobi/i],describe:()=>({type:tc.mobile})},{test:t=>"blackberry"===t.getBrowserName(!0),describe:()=>({type:tc.mobile,vendor:"BlackBerry"})},{test:t=>"bada"===t.getBrowserName(!0),describe:()=>({type:tc.mobile})},{test:t=>"windows phone"===t.getBrowserName(),describe:()=>({type:tc.mobile,vendor:"Microsoft"})},{test(t){const e=Number(String(t.getOSVersion()).split(".")[0]);return"android"===t.getOSName(!0)&&e>=3},describe:()=>({type:tc.tablet})},{test:t=>"android"===t.getOSName(!0),describe:()=>({type:tc.mobile})},{test:t=>"macos"===t.getOSName(!0),describe:()=>({type:tc.desktop,vendor:"Apple"})},{test:t=>"windows"===t.getOSName(!0),describe:()=>({type:tc.desktop})},{test:t=>"linux"===t.getOSName(!0),describe:()=>({type:tc.desktop})},{test:t=>"playstation 4"===t.getOSName(!0),describe:()=>({type:tc.tv})},{test:t=>"roku"===t.getOSName(!0),describe:()=>({type:tc.tv})}],oc=[{test:t=>"microsoft edge"===t.getBrowserName(!0),describe(t){if(/\sedg\//i.test(t))return{name:sc.Blink};const e=Utils.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,t);return{name:sc.EdgeHTML,version:e}}},{test:[/trident/i],describe(t){const e={name:sc.Trident},s=Utils.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:t=>t.test(/presto/i),describe(t){const e={name:sc.Presto},s=Utils.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test(t){const e=t.test(/gecko/i),s=t.test(/like gecko/i);return e&&!s},describe(t){const e={name:sc.Gecko},s=Utils.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:sc.Blink})},{test:[/(apple)?webkit/i],describe(t){const e={name:sc.WebKit},s=Utils.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}}];class Parser{constructor(t,e=!1){if(null==t||""===t)throw new Error("UserAgent parameter can't be empty");this._ua=t,this.parsedResult={},!0!==e&&this.parse()}getUA(){return this._ua}test(t){return t.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const t=Utils.find(ic,t=>{if("function"==typeof t.test)return t.test(this);if(t.test instanceof Array)return t.test.some(t=>this.test(t));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.browser=t.describe(this.getUA())),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(t){return t?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const t=Utils.find(nc,t=>{if("function"==typeof t.test)return t.test(this);if(t.test instanceof Array)return t.test.some(t=>this.test(t));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os}getOSName(t){const{name:e}=this.getOS();return t?String(e).toLowerCase()||"":e||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(t=!1){const{type:e}=this.getPlatform();return t?String(e).toLowerCase()||"":e||""}parsePlatform(){this.parsedResult.platform={};const t=Utils.find(ac,t=>{if("function"==typeof t.test)return t.test(this);if(t.test instanceof Array)return t.test.some(t=>this.test(t));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(t){return t?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const t=Utils.find(oc,t=>{if("function"==typeof t.test)return t.test(this);if(t.test instanceof Array)return t.test.some(t=>this.test(t));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return Utils.assign({},this.parsedResult)}satisfies(t){const e={};let s=0;const r={};let i=0;if(Object.keys(t).forEach(n=>{const a=t[n];"string"==typeof a?(r[n]=a,i+=1):"object"==typeof a&&(e[n]=a,s+=1)}),s>0){const t=Object.keys(e),s=Utils.find(t,t=>this.isOS(t));if(s){const t=this.satisfies(e[s]);if(void 0!==t)return t}const r=Utils.find(t,t=>this.isPlatform(t));if(r){const t=this.satisfies(e[r]);if(void 0!==t)return t}}if(i>0){const t=Object.keys(r),e=Utils.find(t,t=>this.isBrowser(t,!0));if(void 0!==e)return this.compareVersion(r[e])}}isBrowser(t,e=!1){const s=this.getBrowserName().toLowerCase();let r=t.toLowerCase();const i=Utils.getBrowserTypeByAlias(r);return e&&i&&(r=i.toLowerCase()),r===s}compareVersion(t){let e=[0],s=t,r=!1;const i=this.getBrowserVersion();if("string"==typeof i)return">"===t[0]||"<"===t[0]?(s=t.substr(1),"="===t[1]?(r=!0,s=t.substr(2)):e=[],">"===t[0]?e.push(1):e.push(-1)):"="===t[0]?s=t.substr(1):"~"===t[0]&&(r=!0,s=t.substr(1)),e.indexOf(Utils.compareVersions(i,s,r))>-1}isOS(t){return this.getOSName(!0)===String(t).toLowerCase()}isPlatform(t){return this.getPlatformType(!0)===String(t).toLowerCase()}isEngine(t){return this.getEngineName(!0)===String(t).toLowerCase()}is(t,e=!1){return this.isBrowser(t,e)||this.isOS(t)||this.isPlatform(t)}some(t=[]){return t.some(t=>this.is(t))}}
|
|
281
2
|
/*!
|
|
282
3
|
* Bowser - a browser detector
|
|
283
4
|
* https://github.com/lancedikson/bowser
|
|
284
5
|
* MIT License | (c) Dustin Diaz 2012-2015
|
|
285
6
|
* MIT License | (c) Denis Demchenko 2015-2019
|
|
286
|
-
*/const ps=class Bowser{static getParser(t,e=!1){if("string"!=typeof t)throw new Error("UserAgent should be a string");return new Parser(t,e)}static parse(t){return new Parser(t).getResult()}static get BROWSER_MAP(){return ss}static get ENGINE_MAP(){return ls}static get OS_MAP(){return os}static get PLATFORMS_MAP(){return as}}.parse(window.navigator.userAgent),{platform:gs,os:vs,browser:ms}=ps,ys=t=>t&&t.toLowerCase();var Es={rnd:Math.random().toString(36).substr(2,32),os:ys(vs.name+(vs.versionName?" "+vs.versionName:"")),device:ys(gs.type),browser:ys(ms.name),browser_version:(ms&&ms.version?ms.version:"unknown").split(".").shift(),plugin_version:"3.7.2-rc.0"};const Ts="https://fp-eu-w1-aai.flowplayer.com/in",_s="POST",Ss=["ad-requested","ad-request-error","ad-request-completed","ad-completed","ad-started","ad-error","ad-skipped"],bs=["event_type","ad_tag_id","media_id","player_id","site_id","sitegroup_id","rnd","os","device","browser","browser_version","plugin_version","player_version"],As=["vast_error","reason","request_load_time","ad_type","vast_ad_id"],Ls=Pe("ads/analytics"),ws=RequestQueue.of(),Ds=(...t)=>Object.assign({},...t);class Analytics{constructor(t,e={}){this.emitter=t,this.metadata=Ds(Es,e.metadata||{}),this.emitter=t,this.events=e.events||[],this.required_keys=e.required_keys||[],this.optional_keys=e.optional_keys||[],this.valid_keys=this.required_keys.slice(0).concat(this.optional_keys),Ls(this),this.wireup()}static of(t,e){return new Analytics(t,e)}static ensure_required_keys(t,e){return t.required_keys.filter(t=>!(t in e))}static pluck_valid_keys(t,e){return((t,...e)=>Object.keys(t).filter(t=>~e.indexOf(t)).reduce((e,r)=>Object.assign(e,{[r]:t[r]}),{}))(e,...t.valid_keys)}static mergeMetadata(t,e={}){return t.metadata=Analytics.pluck_valid_keys(t,Ds(t.metadata,e,{player_version:"3.7.2-rc.0"})),t}wireup(){this.events.forEach(t=>{this.emitter.on(t,e=>{const r=e.detail,i=Ds(this.metadata,{event_type:t},r),n=Analytics.pluck_valid_keys(this,i),s=Analytics.ensure_required_keys(this,n);if(Ls(`Event[${t}]`,{payload:n,observation:r}),s.length)return Ls(`Analytics.validate_metadata() failed for\n Event[${t}]\n missing keys: ${s}`,n);RequestQueue.rpush(ws,[Ts,_s,n])})})}destroy(){this.emitter=this.metadata=this.events=this.required_keys=this.optional_keys=this.valid_keys=void 0}}const Rs=Pe("ads/controller"),Is={show_all_ads_on_seek:!1,timeout:5e3,preload_advance:10};class AdsController extends class EventBus{constructor(t=document.createElement("div"),e=[]){this._bus=t,this._listeners=e}removeAllListeners(){this._listeners.length=0,this._bus=document.createElement("div")}emit(t,e){const r=new CustomEvent(t,{detail:e||{}});this._bus.dispatchEvent(r)}on(t,e){this._listeners.push([t,e]),this._bus.addEventListener(t,e,{passive:!0})}once(t,e){this._bus.addEventListener(t,e,{once:!0})}removeListener(t,e){this._bus.removeEventListener(t,e)}}{constructor(t={}){var e;super(),this.adapter=function(t,e){return t.adapter?new t.adapter(e):new IMA(e)}(t,this),this.opts=Object.assign(Object.assign({},Is),t),this.analytics=(e=this,Analytics.of(e,{required_keys:bs,optional_keys:As,events:Ss})),this._state=AdsState.of(),this._schedule=void 0,this._lastAd=void 0,this._macros=new Macros(t.parameters||{}),this.wireup(),this.content_processing_src=!1}reset(){return this.removeAllListeners(),this.wireup(),this.analytics&&this.analytics.wireup(),this._state.reset(),this.adapter.reset(),this}destroy(){this.removeAllListeners(),this.analytics&&this.analytics.destroy(),this.adapter&&this.adapter.destroy();this.analytics=void 0,this.opts=void 0,this.adapter=void 0,this._state=void 0,this._schedule=void 0,this._lastAd=void 0,this._macros=void 0}stop(){this.adapter&&this.adapter.stop()}onContentNewSrc(){this._state.reset(),this.adapter.destroyManager(),this.adapter.contentComplete()}wireup(){const t=()=>{var t;const e=new CustomEvent("ad/playing");null===(t=this.videoTag)||void 0===t||t.dispatchEvent(e),this._state.toggleState(rs.PLAYING,!0)};this.on("ad-play-requested",t),this.on("ad-started",t),this.on("ad-resumed",t);const e=()=>{var t;if(!this.adPlaying)return;const e=new CustomEvent("ad/paused");null===(t=this.videoTag)||void 0===t||t.dispatchEvent(e),this._state.toggleState(rs.PLAYING,!1)};this.on("ad-break-completed",e),this.on("ad-teardown",e),this.on("ad-playback-error",e),this.on("ad-request-error",e),this.on("ad-paused",e),this.on("ad-skipped",e),this.on("ad-completed",e),this.on("ad-break-completed",()=>{requestAnimationFrame(()=>{var t;const e=new CustomEvent("ad/complete");null===(t=this.videoTag)||void 0===t||t.dispatchEvent(e),this._state.toggleState(rs.BREAK_ACTIVE,!1)})}),this.on("ad-adapter-init-failed",()=>{console.error("Adapter init failed"),e(),this._state.toggleState(rs.FATAL_ERROR,!0)}),this.on("reload-ad-requested",async t=>{if(Rs("Ads.on(RELOAD_AD_REQUESTED)",t),this._schedule){if(e(),t)return this._schedule.reset(this._schedule.getAds());this._state.hasAny(rs.AD_AVAILABLE)&&(this._schedule.decrement(),this._state.toggleState(rs.AD_AVAILABLE,!1))}})}async initialize(t,e={},r){return Rs("Ads.initialize():",t,e,r),this._state.toggleState(rs.INITIALIZING,!0),Object.assign(this.opts,e),Array.isArray(t)&&this.setSchedule(t),await this.adapter.init(this.opts),this._macros=this._macros.fork(Object.assign({},e.parameters||{},{autoplay:e.autoplay,muted:e.muted})),this.adapter.isReady()&&await this.adapterInitialized(r),this}get videoTag(){return this.adapter.getVideoTag()}get adInfo(){return this.adapter.getAdInfo()}async setVideoTag(t){Rs("Ads.setVideoTag():",t),await this.adapter.setVideoTag(t),this.trigger("ad-videotag-attached",t),this.adapter.isReady()&&await this.adapterInitialized(),t.on("request/ad/pause",()=>this.adapter.pause()),t.on("request/ad/play",()=>this.adapter.resume()),t.on("request/ad/muteunmute",()=>t.toggleMute()),t.on("volumechange",()=>{this.adapter.volume(t.muted?0:0==t.volume?.1:t.volume)}),t.on("src",()=>t.hasState("ad-playing")||t.hasState("ad-paused")?(this.stop(),this.adapter.isLinearAd()?(this.setIsContentProcessingNewSrc(!0),void this.once("ad-break-completed",()=>{setTimeout(()=>{this.setIsContentProcessingNewSrc(!1),this.onContentNewSrc()},0)})):this.onContentNewSrc()):this.onContentNewSrc())}waitForVideoTag(){return new Promise(t=>{const e=this.adapter.getVideoTag();if(e)return t(e);this.on("ad-videotag-attached",e=>{this.once(Tn,()=>t(e))})})}async adapterInitialized(t){Rs("Ads.adapterInitialized()"),this._state.toggleState(rs.INITIALIZING,!1),this._state.toggleState(rs.BREAK_ACTIVE,!!this.hasPreroll()),await this.setCurrentTime(0,t),this.checkIfBreakComplete(),this.adapter.isAdPod()||t&&!this.opts.autoplay||this.trigger("ad-teardown")}async fetchNextAd(t,e=0){var r,i;if(!this._schedule)return;if(!this.adapter.isReady())return;if(e>50)throw this._state.toggleState(rs.FATAL_ERROR,!0),this._state.toggleState(rs.FETCHING_AD,!1),new Error("Ads.fetchNextAd() :max_recursion_depth");const n=(null===(r=this._schedule)||void 0===r?void 0:r.getNextAd())||(null===(i=this._schedule)||void 0===i?void 0:i.getPostroll());if(!n||this.adapter.canDismissNonLinear()||-1===t)if(this._schedule.waitForLoad(t,n,this.opts.preload_ads))this._state.toggleState(rs.FETCHING_AD,!1);else if(n===this._schedule.getPostroll()&&this._schedule.setPostrollActive(),this._schedule.isDrained()||this._schedule.increment(),n){Rs("Ads.fetchNextAd",n),this._state.toggleState(rs.FETCHING_AD,!0);try{return await this.requestAd(n),this._state.toggleState(rs.AD_AVAILABLE,!0),void this._state.toggleState(rs.FETCHING_AD,!1)}catch(r){if(Rs("Ads.fetchNextAd(err: %o, ad: %o)",r,n),this.setLastAd(n),n!==this._schedule.getPostroll())return await this.fetchNextAd(t,++e)}}else this._state.toggleState(rs.FETCHING_AD,!1)}skipAdsOnSeek(t){if(!this._schedule)return;let e=this._schedule.getNextAd();for(;e&&e.time<t;)this._schedule.increment(),e=this._schedule.getNextAd()}async setCurrentTime(t,e=!1,r=!1){if(!this._schedule)return;if(!this.adapter.isReady())return;if(this._state.hasAny(rs.FETCHING_AD))return;if(this._state.hasAny(rs.PLAYING)&&this.adapter.isLinearAd())return;const i=0===t&&0===this._schedule.getNextIndex();try{if(r&&!this.opts.show_all_ads_on_seek&&this.skipAdsOnSeek(t),this._state.hasAny(rs.AD_AVAILABLE)||await this.fetchNextAd(t),!this._state.hasAny(rs.AD_AVAILABLE)||!this.shallPlayAd(t)||e)return;await this.playAd(),await this.setCurrentTime(t),this.checkIfBreakComplete()}catch(t){Rs("setCurrentTime: Error(from: setCurrentTime, message: %s)",t.message)}finally{i&&this.trigger("ad-preroll-finished")}}async playAd(){var t;if(!this._state.hasAny(rs.AD_AVAILABLE))return;this._state.toggleState(rs.AD_AVAILABLE,!1),this._state.toggleState(rs.BREAK_ACTIVE,!0);const e=null===(t=this._schedule)||void 0===t?void 0:t.getCurrentAd();try{await this.adapter.playAd()}catch(t){console.error("Ads.playAd: error",t)}finally{e&&this.setLastAd(e)}}checkIfBreakComplete(){if(!this._state.hasAny(rs.BREAK_ACTIVE))return Rs("Ads.checkIfBreakComplete(:bail, ad: %o)",this.getLastAd());Rs("Ads.checkIfBreakComplete(:run, ad: %o)",this.getLastAd()),this._state.toggleState(rs.BREAK_ACTIVE,!1),this.adapter.isAdPod()||this.trigger("ad-break-completed")}resetScheduleCounter(){this._schedule&&this._schedule.resetCounter()}setSchedule(t,e){if(e&&!isNaN(e)&&this._schedule&&this._schedule.updateContentDuration(e),this._schedule&&this._schedule.getNextIndex()>0)return this._schedule.setAds(t);this._schedule=new Schedule(t,{preload_advance:this.opts.preload_advance,content_duration:e?0:e})}toJSON(){return this._schedule?this._schedule.toJSON():[]}trigger(t,e={}){var r;if(!this.adapter.getVideoTag())return;if(!this._state)return;if("ad-break-completed"===t&&this._state.hasAny(rs.BREAK_ACTIVE)&&!this.adapter.isAdPod())return Rs("skipping AD_BREAK_COMPLETE reason: %s pod=%s",this._state.toString(),this.adapter.isAdPod());if(null===(i=e)||"object"!=typeof i||ts(i)!==Jn)return this.dispatch(t,e);var i;const n=Object.assign({},this.adapter.getOpts()||{},(null===(r=this._schedule)||void 0===r?void 0:r.getCurrentAd())||{},{ad_type:this.ad_type},e);return this.dispatch(t,n)}dispatch(t,e){const r=this.adapter.getVideoTag();if(r){Rs(":dispatch",t,e);try{const i={event:"ads/"+t,detail:{outstream:e.outstream,ad_type:e.ad_type,ad_break_time:e.time,ad_remaining_seconds:e.remaining,ad_muted:e.muted,ad_duration_seconds:e.duration,ad_error_reason:e.reason,ad_vast_error:e.vast_error,ad_vast_error_type:e.vast_error_type,ad_request_load_type:e.request_load_time}};r.dispatchEvent(new CustomEvent(Pr,{detail:i}))}catch(t){Rs(":error",t)}te(r,t,e),this.emit(t,e)}}get ad_type(){return this._schedule&&this._schedule.getCurrentType()}shouldRestartContent(){if(this.getIsContentProcessingNewSrc())return!1;if(this.adapter.isAdPod())return!0;const t=this.getLastAd();return!t||!t.outstream&&!1!==t.restart}async finished(t){if(this._schedule&&(Rs("Ads.finished"),!(this.adapter.isSharedVideoTag()&&this._state.hasAny(rs.PLAYING)&&this.adapter.isLinearAd()))){Rs("Ads.finished: trying to play postroll");try{if(!this._schedule.getPostroll())return Rs("Ads.finished: no postroll found"),await this.adapter.contentComplete();this._state.hasAny(rs.AD_AVAILABLE)||await this.fetchNextAd(-1),await this.playAd(),this.adapter.contentComplete()}catch(t){Rs("Ads.finished: postroll failed:",t)}finally{this.trigger("ad-postroll-finished"),this.checkIfBreakComplete(),"function"==typeof t&&t()}}}hasPreroll(){return this._schedule&&Schedule.hasPreroll(this._schedule.getAds())}shallPlayAd(t){var e;return(!this.adapter||!this.adapter.isAdPod())&&(!(!this._state||this._state.hasAny(rs.FATAL_ERROR))&&!!(null===(e=this._schedule)||void 0===e?void 0:e.shallPlayAd(t)))}setLastAd(t){return this._lastAd=t,this}setIsContentProcessingNewSrc(t){this.content_processing_src=t}getLastAd(){return this._lastAd}getIsContentProcessingNewSrc(){return this.content_processing_src}mergeMacros(t={}){return this._macros=this._macros.fork(Object.assign({},t)),this}get paused(){return this.adapter&&this.adapter.isPaused()}pause(){this.adapter&&this.adapter.pause()}resume(){this.adapter&&this.adapter.resume()}resize(t){this.adapter&&this.adapter.onResize(t)}async requestAd(t,e=0,r=this.opts.timeout){if(!this._state)return;Rs("Ads.requestAd(ad: %o)",{ad:t,timeout:r,idx:e});const i=await async function t(e){if("function"==typeof e)return[await Zn(e)];if("string"==typeof e)return[await Zn(e)];if(Array.isArray(e)){const t=e;return await Promise.all(t.map(Zn))}if("object"==typeof e&&e&&e.adTag)return await t(e.adTag);throw new Error(`\n unhandled ads type ${typeof e}:\n ${JSON.stringify(e)}\n can be:\n | Array<string>\n | string\n | function\n | {adTag: Array<string>|string|function}\n `)}(t);if(void 0===i[e])return Promise.reject(new Error("Ad failed, no fallbacks left"));if(!i[e])return await this.requestAd(i,e+1,r);this.trigger("ad-requested",t);const n=this._macros.compile(i[e],Qn(this.opts,this.adapter.getDimensions()));try{return void await this.adapter.initAd(n,r)}catch(t){return Rs(`Ads.requestAd(:fallback, idx: ${e}, length: ${i.length}, adTag: ${i[e]})\nError `,{adTag:i,err:t}),this.requestAd(i,e+1,r)}}resetSchedule(t){this._schedule&&this._schedule.reset(t)}get adPlaying(){return this._state&&this._state.hasAny(rs.PLAYING)}get adBreak(){return this._state&&this._state.hasAny(rs.BREAK_ACTIVE)}get adRequesting(){return this._state.hasAny(rs.FETCHING_AD)}get adLinear(){return this.adBreak&&this.adapter.isLinearAd()}}var ks=new Blob([new Uint8Array([255,227,24,196,0,0,0,3,72,1,64,0,0,4,132,16,31,227,192,225,76,255,67,12,255,221,27,255,228,97,73,63,255,195,131,69,192,232,223,255,255,207,102,239,255,255,255,101,158,206,70,20,59,255,254,95,70,149,66,4,16,128,0,2,2,32,240,138,255,36,106,183,255,227,24,196,59,11,34,62,80,49,135,40,0,253,29,191,209,200,141,71,7,255,252,152,74,15,130,33,185,6,63,255,252,195,70,203,86,53,15,255,255,247,103,76,121,64,32,47,255,34,227,194,209,138,76,65,77,69,51,46,57,55,170,170,170,170,170,170,170,170,170,170,255,227,24,196,73,13,153,210,100,81,135,56,0,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170])],{type:"audio/mpeg"}),Os=new Blob([new Uint8Array([0,0,0,28,102,116,121,112,105,115,111,109,0,0,2,0,105,115,111,109,105,115,111,50,109,112,52,49,0,0,0,8,102,114,101,101,0,0,2,239,109,100,97,116,33,16,5,32,164,27,255,192,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,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,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,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,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,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,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,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,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,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,55,167,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,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,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,0,0,0,0,0,0,0,0,0,0,0,112,33,16,5,32,164,27,255,192,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,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,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,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,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,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,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,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,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,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,55,167,128,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,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,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,0,0,0,0,0,0,0,0,0,0,0,112,0,0,2,194,109,111,111,118,0,0,0,108,109,118,104,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,232,0,0,0,47,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,0,0,0,3,0,0,1,236,116,114,97,107,0,0,0,92,116,107,104,100,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,47,0,0,0,0,0,0,0,0,0,0,0,1,1,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,36,101,100,116,115,0,0,0,28,101,108,115,116,0,0,0,0,0,0,0,1,0,0,0,47,0,0,0,0,0,1,0,0,0,0,1,100,109,100,105,97,0,0,0,32,109,100,104,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,172,68,0,0,8,0,85,196,0,0,0,0,0,45,104,100,108,114,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,0,0,1,15,109,105,110,102,0,0,0,16,115,109,104,100,0,0,0,0,0,0,0,0,0,0,0,36,100,105,110,102,0,0,0,28,100,114,101,102,0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1,0,0,0,211,115,116,98,108,0,0,0,103,115,116,115,100,0,0,0,0,0,0,0,1,0,0,0,87,109,112,52,97,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,2,0,16,0,0,0,0,172,68,0,0,0,0,0,51,101,115,100,115,0,0,0,0,3,128,128,128,34,0,2,0,4,128,128,128,20,64,21,0,0,0,0,1,244,0,0,1,243,249,5,128,128,128,2,18,16,6,128,128,128,1,2,0,0,0,24,115,116,116,115,0,0,0,0,0,0,0,1,0,0,0,2,0,0,4,0,0,0,0,28,115,116,115,99,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,2,0,0,0,1,0,0,0,28,115,116,115,122,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,115,0,0,1,116,0,0,0,20,115,116,99,111,0,0,0,0,0,0,0,1,0,0,0,44,0,0,0,98,117,100,116,97,0,0,0,90,109,101,116,97,0,0,0,0,0,0,0,33,104,100,108,114,0,0,0,0,0,0,0,0,109,100,105,114,97,112,112,108,0,0,0,0,0,0,0,0,0,0,0,0,45,105,108,115,116,0,0,0,37,169,116,111,111,0,0,0,29,100,97,116,97,0,0,0,1,0,0,0,0,76,97,118,102,53,54,46,52,48,46,49,48,49])],{type:"video/mp4"});function Cs(t){return Object.assign({muted:!1,timeout:250,inline:!1},t)}function Ps(t,e){var r=t.muted,i=t.timeout,n=t.inline,s=e(),a=s.element,o=s.source,l=void 0,d=void 0,u=void 0;return a.muted=r,!0===r&&a.setAttribute("muted","muted"),!0===n&&a.setAttribute("playsinline","playsinline"),a.src=o,new Promise((function(t){l=a.play(),d=setTimeout((function(){u(!1,new Error("Timeout "+i+" ms has been reached"))}),i),u=function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;a.remove(),a.srcObject=null,clearTimeout(d),t({result:e,error:r})},void 0!==l?l.then((function(){return u(!0)})).catch((function(t){return u(!1,t)})):u(!0)}))}var xs={audio:function(t){return Ps(t=Cs(t),(function(){return{element:document.createElement("audio"),source:URL.createObjectURL(ks)}}))},video:function(t){return Ps(t=Cs(t),(function(){return{element:document.createElement("video"),source:URL.createObjectURL(Os)}}))}};let Ms=void 0;async function Ns(t=!0){return Ms||(Ms=await xs.video({timeout:500,muted:t}),Ms)}const Fs=new Blob([new Uint8Array([0,0,0,28,102,116,121,112,105,115,111,109,0,0,2,0,105,115,111,109,105,115,111,50,109,112,52,49,0,0,0,8,102,114,101,101,0,0,2,239,109,100,97,116,33,16,5,32,164,27,255,192,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,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,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,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,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,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,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,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,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,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,55,167,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,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,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,0,0,0,0,0,0,0,0,0,0,0,112,33,16,5,32,164,27,255,192,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,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,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,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,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,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,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,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,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,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,55,167,128,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,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,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,0,0,0,0,0,0,0,0,0,0,0,112,0,0,2,194,109,111,111,118,0,0,0,108,109,118,104,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,232,0,0,0,47,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,0,0,0,3,0,0,1,236,116,114,97,107,0,0,0,92,116,107,104,100,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,47,0,0,0,0,0,0,0,0,0,0,0,1,1,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,36,101,100,116,115,0,0,0,28,101,108,115,116,0,0,0,0,0,0,0,1,0,0,0,47,0,0,0,0,0,1,0,0,0,0,1,100,109,100,105,97,0,0,0,32,109,100,104,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,172,68,0,0,8,0,85,196,0,0,0,0,0,45,104,100,108,114,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,0,0,1,15,109,105,110,102,0,0,0,16,115,109,104,100,0,0,0,0,0,0,0,0,0,0,0,36,100,105,110,102,0,0,0,28,100,114,101,102,0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1,0,0,0,211,115,116,98,108,0,0,0,103,115,116,115,100,0,0,0,0,0,0,0,1,0,0,0,87,109,112,52,97,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,2,0,16,0,0,0,0,172,68,0,0,0,0,0,51,101,115,100,115,0,0,0,0,3,128,128,128,34,0,2,0,4,128,128,128,20,64,21,0,0,0,0,1,244,0,0,1,243,249,5,128,128,128,2,18,16,6,128,128,128,1,2,0,0,0,24,115,116,116,115,0,0,0,0,0,0,0,1,0,0,0,2,0,0,4,0,0,0,0,28,115,116,115,99,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,2,0,0,0,1,0,0,0,28,115,116,115,122,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,115,0,0,1,116,0,0,0,20,115,116,99,111,0,0,0,0,0,0,0,1,0,0,0,44,0,0,0,98,117,100,116,97,0,0,0,90,109,101,116,97,0,0,0,0,0,0,0,33,104,100,108,114,0,0,0,0,0,0,0,0,109,100,105,114,97,112,112,108,0,0,0,0,0,0,0,0,0,0,0,0,45,105,108,115,116,0,0,0,37,169,116,111,111,0,0,0,29,100,97,116,97,0,0,0,1,0,0,0,0,76,97,118,102,53,54,46,52,48,46,49,48,49])],{type:"video/mp4"});var Us=Object.freeze({__proto__:null,STICKY_CONTROLS:1,NO_FULLSCREEN:2,NO_AD_INDICATOR:4,AD_ATTRIBUTION:8,AD_CHOICES:16,REMAINING_TIME:32,VOLUME_BAR:64});const Bs=["progress","duration","remaining"],Gs=Pe("ads/ui");class AdUI extends HTMLElement{constructor(t,e=document.createElement("div")){super(),this.player=t,this.adContainer=e,this.render(),t.addEventListener("ad/playing",t=>this.updateState(t.type)),t.addEventListener("ad/paused",t=>this.updateState(t.type)),t.addEventListener("ad/complete",t=>this.updateState(t.type)),t.on("ad-progress",t=>{const{remaining:e}=t.detail;this.setAttribute("remaining",e+"")}),t.on("ad/hide-first-frame",t=>{const{root:e}=t.detail;Gs("hideFirstFrame"),e.classList.toggle("ad-hide-first-frame",!0)}),t.on("ad/show-first-frame",t=>{const{root:e}=t.detail;Gs("showFirstFrame"),e.classList.toggle("ad-hide-first-frame",!1)}),t.on("ad/resize",t=>{const{opts:e}=t.detail,r=this.style;e.linear?e.width&&(r.width=e.width+"px"):e.width?this.adContainer.style.width=e.width+"px":r.removeProperty("width"),e.height?r.height=e.height+"px":r.removeProperty("height")}),t.on("ad/set-ui-flags",t=>{let{ui_flags:e}=t.detail;if(e=e||0,this.classList.toggle("is-ad-controls-sticky",(1&e)>0),this.classList.toggle("no-fullscreen",(2&e)>0),this.classList.toggle("no-indicator",(4&e)>0),(8&e)>0){const t=document.createElement("div");t.classList.add("ad-attribution"),t.textContent=this.player.i18n("ads.advertisement","Advertisement"),this.adContainer.append(t)}if(this.classList.toggle("no-volume-bar",0==(64&e)),(32&e)>0&&this.controls&&(this.remaining=document.createElement("div"),this.remaining.classList.add("fp-ad-remaining","fp-color-text"),this.controls.prepend(this.remaining)),(16&e)>0&&this.controls){this.classList.toggle("is-ad-choices",!0);const t=document.createElement("div");t.classList.add("fp-ad-choices"),t.textContent=this.player.i18n("ads.adchoices","AdChoices"),t.addEventListener("click",t=>{t.preventDefault(),this.player.togglePlay(!1),window.open("https://adssettings.google.com","_blank")}),this.controls.append(t)}})}static get observedAttributes(){return Bs}updateState(t){["ad/paused","ad/playing"].forEach(e=>{const r=e.replace("/","-"),i=t===e;this.player.setState(r,i),this.classList.toggle(r,i)})}attributeChangedCallback(t,e,r){switch(t){case"duration":return this.onDurationChange(parseFloat(r));case"progress":return this.onProgress(parseFloat(e),parseFloat(r));case"remaining":return this.onRemaining(r)}}onDurationChange(t){}onProgress(t,e){}onRemaining(t){this.remaining&&(this.remaining.textContent=Wt(parseFloat(t)))}render(){this.adContainer.classList.add("fp-ad-container"),this.append(this.adContainer),this.controls=_t(this.player,"flowplayer-ad-controls");const t=_t(this.player,"flowplayer-ad-countdown");this.append(this.controls,t)}}const Hs=Pe("fpads:native:outstream"),js={OUTSTREAM:"is-outstream",HIDDEN:"is-outstream-hidden",SHOWING:"is-outstream-visible",DONE:"is-outstream-done"};var Vs,Ks;!function(t){t.OUTSTREAM_VISIBLE="ads-outstream-visible",t.OUTSTREAM_VIEWPORT_UPDATE="ads-outstream-viewport-update",t.OUTSTREAM_TEARDOWN="ads-outstream-teardown",t.OUTSTREAM_ENDSCREEN_READY="ads-outstream-endscreen-ready"}(Vs||(Vs={})),function(t){t[t.None=0]="None",t[t.Booting=1]="Booting",t[t.Ready=2]="Ready",t[t.Disposed=3]="Disposed"}(Ks||(Ks={}));class Outstream{constructor({ads:t,root:e,content:r,ima:i}){this.state=Ks.None,Hs("creating Outstream instance"),this.content=r,this.ads=t,this.root=e,this.ima=i,this.aspectRatio=r.videoHeight/r.videoWidth,this.dimensions=function(t){if(t.clientWidth>0||t.clientHeight)return yn(t);const e={height:t.style.height};En(t,"opacity",0),En(t,"display","absolute"),En(t,"display","inline-block"),En(t,"height","auto");const r=yn(t);return En(t,"height",e.height),En(t,"opacity",1),r}(this.root),this.adUi=new AdUI(r),this.adContainer=this.adUi.adContainer,this.initialVolumeState={},e.classList.add(js.OUTSTREAM),e.append(this.adUi),this.hide(),this.ads.on("ad-pause-content",t=>{var e;if(this.state==Ks.Disposed)return;const r=!!(null===(e=t.detail)||void 0===e?void 0:e.linear);this.ads.resize(Object.assign(Object.assign({},this.dimensions),{linear:r}))}),r.on("resize",t=>{if(this.state==Ks.Disposed)return;const e=t.detail;e&&(this.dimensions={width:e.contentRect.width,height:e.contentRect.height},this.ads.resize(this.dimensions))}),r.on("intersectionchange",t=>{if(this.state==Ks.Disposed)return;const e=t.detail;if(e)switch(this.state){case Ks.Booting:return Hs(":boot skipping intersectionchange");case Ks.None:return this.state=Ks.Booting,this.begin_life_cycle();case Ks.Ready:if(e.ratio>=.5&&this.ads.adPlaying)return;e.ratio>=.5&&this.ads.resume(),e.ratio<.5&&this.ads.pause()}}),this.setup(),setTimeout(()=>(this.state=Ks.Booting,this.begin_life_cycle()),0)}hide(){return this}restore_aspect_ratio(){return Hs(`Outstream.restore_aspect_ratio(${this.aspectRatio})`),this.content.setOpts({ratio:this.aspectRatio}),this}show(){this.root.classList.remove(Outstream.CLASS.HIDDEN),this.root.classList.add(Outstream.CLASS.SHOWING),this.adUi.classList.add("linear","on")}async begin_life_cycle(){this.state=Ks.Ready;const{error:t,result:e}=await Ns(!1),{result:r}=await Ns(!0);this.attach_ad_listeners(),this.initialVolumeState={can_autoplay:!(!e&&!r),muted:!e},Hs("Outstream.show() :autoplay >> sound="+e),t&&this.content&&!e&&(this.content.muted=!0,this.content.volume=0),await this.ads.setVideoTag(this.content),await Dn({ads:this.ads,content:this.content,adContainer:this.adContainer,ima:this.ima,state:{listening:!1},config:this.content.opts}),Cn({content:this.content,ads:this.ads}),this.state=Ks.Ready}attach_ad_listeners(){const t=this.ads;t.once("ad-pause-content",()=>{this.show(),this.ads.adPlaying&&this.ads.pause()}),this.ima.always_show_controls||t.on("vpaid-init",()=>this.adUi.classList.add("is-vpaid"));const e=()=>{Ln.forEach(t=>this.ads.removeListener(t,e));const t=new CustomEvent(Vs.OUTSTREAM_TEARDOWN);Hs("Outstream(:teardown)",t),this.content.dispatchEvent(t)};Ln.forEach(t=>this.ads.once(t,e)),this.content.once(Vs.OUTSTREAM_TEARDOWN,t=>{setTimeout(()=>{if(t.defaultPrevented)return this.handle_endscreen();this.dispose()},0)})}handle_endscreen(){this.reset_ui(),this.ads.reset(),kn({config:this.content.opts,ui:this.adUi,ads:this.ads,adContainer:this.adContainer,ima:this.ima,content:this.content,root:this.content.root,state:{started:!0,listening:!1},initial:{muted:!0,volume:1}})}empty_src(){this.content.setSrc({type:"video/mp4",src:URL.createObjectURL(Fs)})}setup(){this.root.classList.add(Outstream.CLASS.OUTSTREAM),this.root.classList.add(Outstream.CLASS.HIDDEN),this.empty_src()}reset_ui(){const t=this.root;t.classList.remove(Outstream.CLASS.SHOWING),t.classList.remove(Outstream.CLASS.OUTSTREAM),this.adUi.classList.remove("on")}dispose(){if(this.state==Ks.Disposed)return;const t=this.root,e=this.content;this.reset_ui(),t.classList.add(Outstream.CLASS.OUTSTREAM),t.classList.add(Outstream.CLASS.DONE);this.video=this.container=this.ads=0,this.state=Ks.Disposed,e.destroy(),t.innerHTML=""}}function qs(t){return t&&"number"==typeof t.time}function Ws(t){return t&&"number"==typeof t.percentage&&"number"!=typeof t.time}Outstream.CLASS=js;const zs=Pe("ads/ima/sdk");var Ys;async function Xs(t){var e;if(null===(e=null===window||void 0===window?void 0:window.google)||void 0===e?void 0:e.ima)return void zs(":noop");const r=t._storage.getItem("ima/debug")?"https://imasdk.googleapis.com/js/sdkloader/ima3_debug.js":"https://imasdk.googleapis.com/js/sdkloader/ima3.js";try{return await async function(t){return new Promise((e,r)=>{let i=document.querySelector(`script[src='${t}']`);if(i)return Qs(i,e,r);i=document.createElement("script"),i.setAttribute("state",Ys.LOADING),Qs(i,e,r),i.src=t,document.head.appendChild(i)})}(r),void zs(":loaded")}catch(t){zs(":error "+t.message,t)}}function Qs(t,e,r){const i=t.getAttribute("state");if(i&&[Ys.ERROR,Ys.LOADED].includes(i))return e(void 0);t.addEventListener("load",()=>{t.setAttribute("state",Ys.LOADED),e(void 0)},{once:!0}),["error","abort"].forEach(e=>{t.addEventListener(e,()=>{t.setAttribute("state",Ys.ERROR),r("script failed to load")},{once:!0})})}!function(t){t.LOADING="loading",t.LOADED="loaded",t.ERROR="error"}(Ys||(Ys={}));const $s=Pe("ads/index");async function Zs(t,e,r){let i=t.autoplay;if(t.autoplay&&($s("handling initial autoplay, original_autoplay: ",i),r.autoplay=!1,t.autoplay=0,r.once(m,()=>{setTimeout(()=>{var e;if(!(null===(e=t.ima)||void 0===e?void 0:e.ads)){if(t.autoplay=i,!r.hasState(ht))return r.once("viewenter",()=>r.togglePlay(!0));r.togglePlay(!0)}},0)})),await Xs(r),!("google"in window))return console.warn("google.ima unavailable");const n=r.ads=new AdsController,s=n.analytics;let a=!1;n.resize(yn(e)),Sn&&(r.on([h,f,"webkitendfullscreen"],t=>{var e;const i=t.type===h;null===(e=null==r?void 0:r.ads)||void 0===e||e.adapter.setIOSPlaysInline(!i)}),n.on("ad-postroll-finished",()=>{n.adapter.isSharedVideoTag()&&n.once("ad-break-completed",()=>{r.src=r.original_src,r.once(_,()=>{r.togglePlay(!1)}),r.webkitExitFullscreen()})})),r.on(w,(function(){n&&n.destroy()}));const o=async t=>{const o=t.ima;if(void 0===i&&t.autoplay&&(i=t.autoplay),!o)return;if(!Array.isArray(o.ads))return $s("handling non-array ima.ads"),void(void 0!==i?t.autoplay=i:delete t.autoplay);const l=t.duration||r.duration;if(o.ads=function(t,e){return Array.isArray(t)?t.filter(t=>qs(t)||Ws(t)).reduce((t,r)=>{if(qs(r))return t.push(r),t;if(r.lazy)return t.push(r),t;if(Ws(r)){const i=Object.assign({},r),n=r.percentage?r.percentage*e:0;return isNaN(n)||(i.time=n<0||n===e?-1:n),t.push(i),t}return t},[]):(console.warn("AdSchedule was not an Array"),[])}(o.ads,l),n.setSchedule(o.ads,l),t.metadata&&Analytics.mergeMetadata(s,t.metadata),t.metadata&&n.mergeMacros(t.metadata),t.metadata&&o.parameters&&(o.parameters=Object.assign(Object.assign({},o.parameters),t.metadata)),Analytics.mergeMetadata(s,{muted:t.muted||!1,autoplay:t.autoplay||!1}),!a){if(a=!0,t.lang&&!o.Locale&&(o.Locale=t.lang),Schedule.isOutstream(o.ads))return $s("is outstream, returning"),new Outstream({root:e,content:r,ads:n,ima:o});wn({config:Object.assign(Object.assign({},t),{autoplay:i}),root:e,content:r,ads:n,ima:o})}};t.ima&&o(t),r.on(D,({detail:t})=>o(t))}class AdControls extends HTMLElement{constructor(t){super(),this.player=t,this.render()}render(){this.classList.add("fp-ad-controls");const t=_t(this.player,"flowplayer-ad-indicator"),e=document.createElement("div");e.classList.add("ad-playback-controls");const r=_t(this.player,K),i=_t(this.player,q);r.addEventListener("click",()=>{this.player.emit("request/ad/play"),setTimeout((function(){i.focus&&i.focus()}),100)}),i.addEventListener("click",()=>{this.player.emit("request/ad/pause"),setTimeout((function(){r.focus&&r.focus()}),100)}),e.append(r,i);const n=_t(this.player,X);n.addEventListener("click",()=>this.player.emit("request/ad/muteunmute"));const s=_t(this.player,U),a=_t(this.player,G);this.append(t,e,n,s,a)}}class AdCountdown extends HTMLElement{constructor(t){super(),this.player=t,t.on("ad-progress",t=>{const{duration:e,remaining:r}=t.detail;this.setAttribute("duration",e+""),this.setAttribute("remaining",r+"")}),t.on("ad-started",t=>{t.detail.linear&&(this.style.setProperty("--ad-percent-previous","0"),this.style.setProperty("--ad-percent-complete","0"))}),this.addEventListener("animationend",()=>{const t=this.style.getPropertyValue("--ad-percent-complete")||"0";this.style.setProperty("--ad-percent-previous",t)})}static get observedAttributes(){return["remaining"]}attributeChangedCallback(t,e,r){switch(t){case"remaining":return this.onRemaining(r)}}onRemaining(t){const e=parseFloat(this.getAttribute("duration")||"0");t||(t=e+"");const r=parseFloat(t),i=this.style.getPropertyValue("--ad-percent-complete")||"0";this.style.setProperty("--ad-percent-previous",i),this.classList.remove("go");const n=((e-r)/e*100).toFixed(3);requestAnimationFrame(()=>{this.style.setProperty("--ad-percent-complete",n),this.classList.add("go")})}}class AdIndicator extends HTMLElement{constructor(t){super(),this.player=t,this.render(),t.on("ad-started",t=>{const{position:e,totals:r}=t.detail.ad;this.setAttribute("position",e+""),this.setAttribute("totals",r+"")})}static get observedAttributes(){return["position","totals"]}attributeChangedCallback(t,e){switch(t){case"position":case"totals":return this.updateText()}}updateText(){if(!this.element)return;const t=parseFloat(this.getAttribute("position")||"0"),e=parseFloat(this.getAttribute("totals")||"0");this.element.textContent=`${this.player.i18n("ads.indicator","ADS")} ${t} / ${e}`}render(){this.element=document.createElement("div"),this.element.classList.add("ad-indicator","fp-color-text"),this.element.textContent=this.player.i18n("ads.indicator","ADS"),this.append(this.element)}}var Js=Object.freeze({__proto__:null,SINGlE_INLINE_LINEAR:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_ad_samples&sz=640x480&cust_params=sample_ct%3Dlinear&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=",SINGLE_SKIPPABLE_INLINE:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_preroll_skippable&sz=640x480&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=",SINGLE_REDIRECT_LINEAR:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_ad_samples&sz=640x480&cust_params=sample_ct%3Dredirectlinear&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=",SINGLE_REDIRECT_ERROR:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_ad_samples&sz=640x480&cust_params=sample_ct%3Dredirecterror&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=",SINGLE_REDIRECT_BROKEN:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_ad_samples&sz=640x480&cust_params=sample_ct%3Dredirecterror&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&nofb=1&correlator=",SINGLE_VPAID_20_LINEAR:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_ad_samples&sz=640x480&cust_params=sample_ct%3Dlinearvpaid2js&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=",SINGLE_VPAID_20_NON_LINEAR:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_ad_samples&sz=640x480&cust_params=sample_ct%3Dnonlinearvpaid2js&ciu_szs=728x90%2C300x250&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=",SINGLE_NON_LINEAR_INLINE:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/nonlinear_ad_samples&sz=480x70&cust_params=sample_ct%3Dnonlinear&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=",VMAP_SESSION_AD_RULE_PREROLL:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sar%3Da0f2&ciu_szs=300x250&ad_rule=1&gdfp_req=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&correlator=",VMAP_PREROLL:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sample_ar%3Dpreonly&ciu_szs=300x250%2C728x90&gdfp_req=1&ad_rule=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&correlator=",VMAP_PREROLL_BUMPER:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sample_ar%3Dpreonlybumper&ciu_szs=300x250&gdfp_req=1&ad_rule=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&correlator=",VMAP_POSTROLL:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sample_ar%3Dpostonly&ciu_szs=300x250&gdfp_req=1&ad_rule=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&correlator=",VMAP_POSTROLL_BUMPER:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sample_ar%3Dpostonlybumper&ciu_szs=300x250&gdfp_req=1&ad_rule=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&correlator="});const{samsung_tv:ta}=r();class Ads{constructor(t){this.umd=t,St(t,bn,AdUI),St(t,"flowplayer-ad-controls",AdControls),St(t,"flowplayer-ad-countdown",AdCountdown),St(t,"flowplayer-ad-indicator",AdIndicator)}init(t,e,r){if(ye.from_token(t.token||"").is_granted(ye.permissions.ADS)&&!ta)return Zs(t,e,r)}}return Ads.events=_n,Ads.ui=Us,Ads.tags=Js,ue(window,Ads),bi.extensions.push(HLS,OVP,Ads),Object.assign(bi,{hls:HLS,ads:Ads,ovp:OVP}),bi}));
|
|
7
|
+
*/const lc=class Bowser{static getParser(t,e=!1){if("string"!=typeof t)throw new Error("UserAgent should be a string");return new Parser(t,e)}static parse(t){return new Parser(t).getResult()}static get BROWSER_MAP(){return Jd}static get ENGINE_MAP(){return sc}static get OS_MAP(){return ec}static get PLATFORMS_MAP(){return tc}}.parse(window.navigator.userAgent),{platform:dc,os:cc,browser:uc}=lc,hc=t=>t&&t.toLowerCase();var fc={rnd:Math.random().toString(36).substr(2,32),os:hc(cc.name+(cc.versionName?" "+cc.versionName:"")),device:hc(dc.type),browser:hc(uc.name),browser_version:(uc&&uc.version?uc.version:"unknown").split(".").shift(),plugin_version:"3.8.0"};const gc="https://fp-eu-w1-aai.flowplayer.com/in",pc="POST",mc=["ad-requested","ad-request-error","ad-request-completed","ad-completed","ad-started","ad-error","ad-skipped"],yc=["event_type","ad_tag_id","media_id","player_id","site_id","sitegroup_id","rnd","os","device","browser","browser_version","plugin_version","player_version"],vc=["vast_error","reason","request_load_time","ad_type","vast_ad_id"],Ec=Oe("ads/analytics"),Tc=RequestQueue.of(),_c=(...t)=>Object.assign({},...t);class Analytics{constructor(t,e={}){this.emitter=t,this.metadata=_c(fc,e.metadata||{}),this.emitter=t,this.events=e.events||[],this.required_keys=e.required_keys||[],this.optional_keys=e.optional_keys||[],this.valid_keys=this.required_keys.slice(0).concat(this.optional_keys),Ec(this),this.wireup()}static of(t,e){return new Analytics(t,e)}static ensure_required_keys(t,e){return t.required_keys.filter(t=>!(t in e))}static pluck_valid_keys(t,e){return((t,...e)=>Object.keys(t).filter(t=>~e.indexOf(t)).reduce((e,s)=>Object.assign(e,{[s]:t[s]}),{}))(e,...t.valid_keys)}static mergeMetadata(t,e={}){return t.metadata=Analytics.pluck_valid_keys(t,_c(t.metadata,e,{player_version:"3.8.0"})),t}wireup(){this.events.forEach(t=>{this.emitter.on(t,e=>{const s=e.detail,r=_c(this.metadata,{event_type:t},s),i=Analytics.pluck_valid_keys(this,r),n=Analytics.ensure_required_keys(this,i);if(Ec(`Event[${t}]`,{payload:i,observation:s}),n.length)return Ec(`Analytics.validate_metadata() failed for\n Event[${t}]\n missing keys: ${n}`,i);RequestQueue.rpush(Tc,[gc,pc,i])})})}destroy(){this.emitter=this.metadata=this.events=this.required_keys=this.optional_keys=this.valid_keys=void 0}}const Sc=Oe("ads/controller"),Ac={show_all_ads_on_seek:!1,timeout:5e3,preload_advance:10};class AdsController extends class EventBus{constructor(t=document.createElement("div"),e=[]){this._bus=t,this._listeners=e}removeAllListeners(){this._listeners.length=0,this._bus=document.createElement("div")}emit(t,e){const s=new CustomEvent(t,{detail:e||{}});this._bus.dispatchEvent(s)}on(t,e){this._listeners.push([t,e]),this._bus.addEventListener(t,e,{passive:!0})}once(t,e){this._bus.addEventListener(t,e,{once:!0})}removeListener(t,e){this._bus.removeEventListener(t,e)}}{constructor(t={}){var e;super(),this.adapter=function(t,e){return t.adapter?new t.adapter(e):new IMA(e)}(t,this),this.opts=Object.assign(Object.assign({},Ac),t),this.analytics=(e=this,Analytics.of(e,{required_keys:yc,optional_keys:vc,events:mc})),this._state=AdsState.of(),this._schedule=void 0,this._lastAd=void 0,this._macros=new Macros(t.parameters||{}),this.wireup(),this.content_processing_src=!1}reset(){return this.removeAllListeners(),this.wireup(),this.analytics&&this.analytics.wireup(),this._state.reset(),this.adapter.reset(),this}destroy(){this.removeAllListeners(),this.analytics&&this.analytics.destroy(),this.adapter&&this.adapter.destroy();this.analytics=void 0,this.opts=void 0,this.adapter=void 0,this._state=void 0,this._schedule=void 0,this._lastAd=void 0,this._macros=void 0}stop(){this.adapter&&this.adapter.stop()}onContentNewSrc(){this._state.reset(),this.adapter.destroyManager(),this.adapter.contentComplete()}wireup(){const t=()=>{var t;const e=new CustomEvent("ad/playing");null===(t=this.videoTag)||void 0===t||t.dispatchEvent(e),this._state.toggleState(Xd.PLAYING,!0)};this.on("ad-play-requested",t),this.on("ad-started",t),this.on("ad-resumed",t);const e=()=>{var t;if(!this.adPlaying)return;const e=new CustomEvent("ad/paused");null===(t=this.videoTag)||void 0===t||t.dispatchEvent(e),this._state.toggleState(Xd.PLAYING,!1)};this.on("ad-break-completed",e),this.on("ad-teardown",e),this.on("ad-playback-error",e),this.on("ad-request-error",e),this.on("ad-paused",e),this.on("ad-skipped",e),this.on("ad-completed",e),this.on("ad-break-completed",()=>{requestAnimationFrame(()=>{var t;const e=new CustomEvent("ad/complete");null===(t=this.videoTag)||void 0===t||t.dispatchEvent(e),this._state.toggleState(Xd.BREAK_ACTIVE,!1)})}),this.on("ad-adapter-init-failed",()=>{console.error("Adapter init failed"),e(),this._state.toggleState(Xd.FATAL_ERROR,!0)}),this.on("reload-ad-requested",async t=>{if(Sc("Ads.on(RELOAD_AD_REQUESTED)",t),this._schedule){if(e(),t)return this._schedule.reset(this._schedule.getAds());this._state.hasAny(Xd.AD_AVAILABLE)&&(this._schedule.decrement(),this._state.toggleState(Xd.AD_AVAILABLE,!1))}})}async initialize(t,e={},s){return Sc("Ads.initialize():",t,e,s),this._state.toggleState(Xd.INITIALIZING,!0),Object.assign(this.opts,e),Array.isArray(t)&&this.setSchedule(t),await this.adapter.init(this.opts),this._macros=this._macros.fork(Object.assign({},e.parameters||{},{autoplay:e.autoplay,muted:e.muted})),this.adapter.isReady()&&await this.adapterInitialized(s),this}get videoTag(){return this.adapter.getVideoTag()}get adInfo(){return this.adapter.getAdInfo()}async setVideoTag(t){Sc("Ads.setVideoTag():",t),await this.adapter.setVideoTag(t),this.trigger("ad-videotag-attached",t),this.adapter.isReady()&&await this.adapterInitialized(),t.on("request/ad/pause",()=>this.adapter.pause()),t.on("request/ad/play",()=>this.adapter.resume()),t.on("request/ad/muteunmute",()=>t.toggleMute()),t.on("volumechange",()=>{this.adapter.volume(t.muted?0:0==t.volume?.1:t.volume)}),t.on("src",()=>t.hasState("ad-playing")||t.hasState("ad-paused")?(this.stop(),this.adapter.isLinearAd()?(this.setIsContentProcessingNewSrc(!0),void this.once("ad-break-completed",()=>{setTimeout(()=>{this.setIsContentProcessingNewSrc(!1),this.onContentNewSrc()},0)})):this.onContentNewSrc()):this.onContentNewSrc())}waitForVideoTag(){return new Promise(t=>{const e=this.adapter.getVideoTag();if(e)return t(e);this.on("ad-videotag-attached",e=>{this.once(gd,()=>t(e))})})}async adapterInitialized(t){Sc("Ads.adapterInitialized()"),this._state.toggleState(Xd.INITIALIZING,!1),this._state.toggleState(Xd.BREAK_ACTIVE,!!this.hasPreroll()),await this.setCurrentTime(0,t),this.checkIfBreakComplete(),this.adapter.isAdPod()||t&&!this.opts.autoplay||this.trigger("ad-teardown")}async fetchNextAd(t,e=0){var s,r;if(!this._schedule)return;if(!this.adapter.isReady())return;if(e>50)throw this._state.toggleState(Xd.FATAL_ERROR,!0),this._state.toggleState(Xd.FETCHING_AD,!1),new Error("Ads.fetchNextAd() :max_recursion_depth");const i=(null===(s=this._schedule)||void 0===s?void 0:s.getNextAd())||(null===(r=this._schedule)||void 0===r?void 0:r.getPostroll());if(!i||this.adapter.canDismissNonLinear()||-1===t)if(this._schedule.waitForLoad(t,i,this.opts.preload_ads))this._state.toggleState(Xd.FETCHING_AD,!1);else if(i===this._schedule.getPostroll()&&this._schedule.setPostrollActive(),this._schedule.isDrained()||this._schedule.increment(),i){Sc("Ads.fetchNextAd",i),this._state.toggleState(Xd.FETCHING_AD,!0);try{return await this.requestAd(i),this._state.toggleState(Xd.AD_AVAILABLE,!0),void this._state.toggleState(Xd.FETCHING_AD,!1)}catch(s){if(Sc("Ads.fetchNextAd(err: %o, ad: %o)",s,i),this.setLastAd(i),i!==this._schedule.getPostroll())return await this.fetchNextAd(t,++e)}}else this._state.toggleState(Xd.FETCHING_AD,!1)}skipAdsOnSeek(t){if(!this._schedule)return;let e=this._schedule.getNextAd();for(;e&&e.time<t;)this._schedule.increment(),e=this._schedule.getNextAd()}async setCurrentTime(t,e=!1,s=!1){if(!this._schedule)return;if(!this.adapter.isReady())return;if(this._state.hasAny(Xd.FETCHING_AD))return;if(this._state.hasAny(Xd.PLAYING)&&this.adapter.isLinearAd())return;const r=0===t&&0===this._schedule.getNextIndex();try{if(s&&!this.opts.show_all_ads_on_seek&&this.skipAdsOnSeek(t),this._state.hasAny(Xd.AD_AVAILABLE)||await this.fetchNextAd(t),!this._state.hasAny(Xd.AD_AVAILABLE)||!this.shallPlayAd(t)||e)return;await this.playAd(),await this.setCurrentTime(t),this.checkIfBreakComplete()}catch(t){Sc("setCurrentTime: Error(from: setCurrentTime, message: %s)",t.message)}finally{r&&this.trigger("ad-preroll-finished")}}async playAd(){var t;if(!this._state.hasAny(Xd.AD_AVAILABLE))return;this._state.toggleState(Xd.AD_AVAILABLE,!1),this._state.toggleState(Xd.BREAK_ACTIVE,!0);const e=null===(t=this._schedule)||void 0===t?void 0:t.getCurrentAd();try{await this.adapter.playAd()}catch(t){console.error("Ads.playAd: error",t)}finally{e&&this.setLastAd(e)}}checkIfBreakComplete(){if(!this._state.hasAny(Xd.BREAK_ACTIVE))return Sc("Ads.checkIfBreakComplete(:bail, ad: %o)",this.getLastAd());Sc("Ads.checkIfBreakComplete(:run, ad: %o)",this.getLastAd()),this._state.toggleState(Xd.BREAK_ACTIVE,!1),this.adapter.isAdPod()||this.trigger("ad-break-completed")}resetScheduleCounter(){this._schedule&&this._schedule.resetCounter()}setSchedule(t,e){if(e&&!isNaN(e)&&this._schedule&&this._schedule.updateContentDuration(e),this._schedule&&this._schedule.getNextIndex()>0)return this._schedule.setAds(t);this._schedule=new Schedule(t,{preload_advance:this.opts.preload_advance,content_duration:e?0:e})}toJSON(){return this._schedule?this._schedule.toJSON():[]}trigger(t,e={}){var s;if(!this.adapter.getVideoTag())return;if(!this._state)return;if("ad-break-completed"===t&&this._state.hasAny(Xd.BREAK_ACTIVE)&&!this.adapter.isAdPod())return Sc("skipping AD_BREAK_COMPLETE reason: %s pod=%s",this._state.toString(),this.adapter.isAdPod());if(null===(r=e)||"object"!=typeof r||Yd(r)!==Wd)return this.dispatch(t,e);var r;const i=Object.assign({},this.adapter.getOpts()||{},(null===(s=this._schedule)||void 0===s?void 0:s.getCurrentAd())||{},{ad_type:this.ad_type},e);return this.dispatch(t,i)}dispatch(t,e){const s=this.adapter.getVideoTag();if(s){Sc(":dispatch",t,e);try{const r={event:"ads/"+t,detail:{outstream:e.outstream,ad_type:e.ad_type,ad_break_time:e.time,ad_remaining_seconds:e.remaining,ad_muted:e.muted,ad_duration_seconds:e.duration,ad_error_reason:e.reason,ad_vast_error:e.vast_error,ad_vast_error_type:e.vast_error_type,ad_request_load_type:e.request_load_time}};s.dispatchEvent(new CustomEvent(Ps,{detail:r}))}catch(t){Sc(":error",t)}te(s,t,e),this.emit(t,e)}}get ad_type(){return this._schedule&&this._schedule.getCurrentType()}shouldRestartContent(){if(this.getIsContentProcessingNewSrc())return!1;if(this.adapter.isAdPod())return!0;const t=this.getLastAd();return!t||!t.outstream&&!1!==t.restart}async finished(t){if(this._schedule&&(Sc("Ads.finished"),!(this.adapter.isSharedVideoTag()&&this._state.hasAny(Xd.PLAYING)&&this.adapter.isLinearAd()))){Sc("Ads.finished: trying to play postroll");try{if(!this._schedule.getPostroll())return Sc("Ads.finished: no postroll found"),await this.adapter.contentComplete();this._state.hasAny(Xd.AD_AVAILABLE)||await this.fetchNextAd(-1),await this.playAd(),this.adapter.contentComplete()}catch(t){Sc("Ads.finished: postroll failed:",t)}finally{this.trigger("ad-postroll-finished"),this.checkIfBreakComplete(),"function"==typeof t&&t()}}}hasPreroll(){return this._schedule&&Schedule.hasPreroll(this._schedule.getAds())}shallPlayAd(t){var e;return(!this.adapter||!this.adapter.isAdPod())&&(!(!this._state||this._state.hasAny(Xd.FATAL_ERROR))&&!!(null===(e=this._schedule)||void 0===e?void 0:e.shallPlayAd(t)))}setLastAd(t){return this._lastAd=t,this}setIsContentProcessingNewSrc(t){this.content_processing_src=t}getLastAd(){return this._lastAd}getIsContentProcessingNewSrc(){return this.content_processing_src}mergeMacros(t={}){return this._macros=this._macros.fork(Object.assign({},t)),this}get paused(){return this.adapter&&this.adapter.isPaused()}pause(){this.adapter&&this.adapter.pause()}resume(){this.adapter&&this.adapter.resume()}resize(t){this.adapter&&this.adapter.onResize(t)}async requestAd(t,e=0,s=this.opts.timeout){if(!this._state)return;Sc("Ads.requestAd(ad: %o)",{ad:t,timeout:s,idx:e});const r=await async function t(e){if("function"==typeof e)return[await jd(e)];if("string"==typeof e)return[await jd(e)];if(Array.isArray(e)){const t=e;return await Promise.all(t.map(jd))}if("object"==typeof e&&e&&e.adTag)return await t(e.adTag);throw new Error(`\n unhandled ads type ${typeof e}:\n ${JSON.stringify(e)}\n can be:\n | Array<string>\n | string\n | function\n | {adTag: Array<string>|string|function}\n `)}(t);if(void 0===r[e])return Promise.reject(new Error("Ad failed, no fallbacks left"));if(!r[e])return await this.requestAd(r,e+1,s);this.trigger("ad-requested",t);const i=this._macros.compile(r[e],Vd(this.opts,this.adapter.getDimensions()));try{return void await this.adapter.initAd(i,s)}catch(t){return Sc(`Ads.requestAd(:fallback, idx: ${e}, length: ${r.length}, adTag: ${r[e]})\nError `,{adTag:r,err:t}),this.requestAd(r,e+1,s)}}resetSchedule(t){this._schedule&&this._schedule.reset(t)}get adPlaying(){return this._state&&this._state.hasAny(Xd.PLAYING)}get adBreak(){return this._state&&this._state.hasAny(Xd.BREAK_ACTIVE)}get adRequesting(){return this._state.hasAny(Xd.FETCHING_AD)}get adLinear(){return this.adBreak&&this.adapter.isLinearAd()}}var Lc=new Blob([new Uint8Array([255,227,24,196,0,0,0,3,72,1,64,0,0,4,132,16,31,227,192,225,76,255,67,12,255,221,27,255,228,97,73,63,255,195,131,69,192,232,223,255,255,207,102,239,255,255,255,101,158,206,70,20,59,255,254,95,70,149,66,4,16,128,0,2,2,32,240,138,255,36,106,183,255,227,24,196,59,11,34,62,80,49,135,40,0,253,29,191,209,200,141,71,7,255,252,152,74,15,130,33,185,6,63,255,252,195,70,203,86,53,15,255,255,247,103,76,121,64,32,47,255,34,227,194,209,138,76,65,77,69,51,46,57,55,170,170,170,170,170,170,170,170,170,170,255,227,24,196,73,13,153,210,100,81,135,56,0,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170])],{type:"audio/mpeg"}),bc=new Blob([new Uint8Array([0,0,0,28,102,116,121,112,105,115,111,109,0,0,2,0,105,115,111,109,105,115,111,50,109,112,52,49,0,0,0,8,102,114,101,101,0,0,2,239,109,100,97,116,33,16,5,32,164,27,255,192,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,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,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,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,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,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,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,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,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,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,55,167,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,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,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,0,0,0,0,0,0,0,0,0,0,0,112,33,16,5,32,164,27,255,192,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,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,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,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,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,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,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,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,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,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,55,167,128,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,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,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,0,0,0,0,0,0,0,0,0,0,0,112,0,0,2,194,109,111,111,118,0,0,0,108,109,118,104,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,232,0,0,0,47,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,0,0,0,3,0,0,1,236,116,114,97,107,0,0,0,92,116,107,104,100,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,47,0,0,0,0,0,0,0,0,0,0,0,1,1,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,36,101,100,116,115,0,0,0,28,101,108,115,116,0,0,0,0,0,0,0,1,0,0,0,47,0,0,0,0,0,1,0,0,0,0,1,100,109,100,105,97,0,0,0,32,109,100,104,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,172,68,0,0,8,0,85,196,0,0,0,0,0,45,104,100,108,114,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,0,0,1,15,109,105,110,102,0,0,0,16,115,109,104,100,0,0,0,0,0,0,0,0,0,0,0,36,100,105,110,102,0,0,0,28,100,114,101,102,0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1,0,0,0,211,115,116,98,108,0,0,0,103,115,116,115,100,0,0,0,0,0,0,0,1,0,0,0,87,109,112,52,97,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,2,0,16,0,0,0,0,172,68,0,0,0,0,0,51,101,115,100,115,0,0,0,0,3,128,128,128,34,0,2,0,4,128,128,128,20,64,21,0,0,0,0,1,244,0,0,1,243,249,5,128,128,128,2,18,16,6,128,128,128,1,2,0,0,0,24,115,116,116,115,0,0,0,0,0,0,0,1,0,0,0,2,0,0,4,0,0,0,0,28,115,116,115,99,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,2,0,0,0,1,0,0,0,28,115,116,115,122,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,115,0,0,1,116,0,0,0,20,115,116,99,111,0,0,0,0,0,0,0,1,0,0,0,44,0,0,0,98,117,100,116,97,0,0,0,90,109,101,116,97,0,0,0,0,0,0,0,33,104,100,108,114,0,0,0,0,0,0,0,0,109,100,105,114,97,112,112,108,0,0,0,0,0,0,0,0,0,0,0,0,45,105,108,115,116,0,0,0,37,169,116,111,111,0,0,0,29,100,97,116,97,0,0,0,1,0,0,0,0,76,97,118,102,53,54,46,52,48,46,49,48,49])],{type:"video/mp4"});function wc(t){return Object.assign({muted:!1,timeout:250,inline:!1},t)}function Rc(t,e){var s=t.muted,r=t.timeout,i=t.inline,n=e(),a=n.element,o=n.source,l=void 0,d=void 0,c=void 0;return a.muted=s,!0===s&&a.setAttribute("muted","muted"),!0===i&&a.setAttribute("playsinline","playsinline"),a.src=o,new Promise((function(t){l=a.play(),d=setTimeout((function(){c(!1,new Error("Timeout "+r+" ms has been reached"))}),r),c=function(e){var s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;a.remove(),a.srcObject=null,clearTimeout(d),t({result:e,error:s})},void 0!==l?l.then((function(){return c(!0)})).catch((function(t){return c(!1,t)})):c(!0)}))}var kc={audio:function(t){return Rc(t=wc(t),(function(){return{element:document.createElement("audio"),source:URL.createObjectURL(Lc)}}))},video:function(t){return Rc(t=wc(t),(function(){return{element:document.createElement("video"),source:URL.createObjectURL(bc)}}))}};let Ic=void 0;async function Dc(t=!0){return Ic||(Ic=await kc.video({timeout:500,muted:t}),Ic)}const Cc=new Blob([new Uint8Array([0,0,0,28,102,116,121,112,105,115,111,109,0,0,2,0,105,115,111,109,105,115,111,50,109,112,52,49,0,0,0,8,102,114,101,101,0,0,2,239,109,100,97,116,33,16,5,32,164,27,255,192,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,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,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,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,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,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,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,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,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,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,55,167,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,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,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,0,0,0,0,0,0,0,0,0,0,0,112,33,16,5,32,164,27,255,192,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,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,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,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,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,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,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,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,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,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,55,167,128,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,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,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,0,0,0,0,0,0,0,0,0,0,0,112,0,0,2,194,109,111,111,118,0,0,0,108,109,118,104,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,232,0,0,0,47,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,0,0,0,3,0,0,1,236,116,114,97,107,0,0,0,92,116,107,104,100,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,47,0,0,0,0,0,0,0,0,0,0,0,1,1,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,36,101,100,116,115,0,0,0,28,101,108,115,116,0,0,0,0,0,0,0,1,0,0,0,47,0,0,0,0,0,1,0,0,0,0,1,100,109,100,105,97,0,0,0,32,109,100,104,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,172,68,0,0,8,0,85,196,0,0,0,0,0,45,104,100,108,114,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,0,0,1,15,109,105,110,102,0,0,0,16,115,109,104,100,0,0,0,0,0,0,0,0,0,0,0,36,100,105,110,102,0,0,0,28,100,114,101,102,0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1,0,0,0,211,115,116,98,108,0,0,0,103,115,116,115,100,0,0,0,0,0,0,0,1,0,0,0,87,109,112,52,97,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,2,0,16,0,0,0,0,172,68,0,0,0,0,0,51,101,115,100,115,0,0,0,0,3,128,128,128,34,0,2,0,4,128,128,128,20,64,21,0,0,0,0,1,244,0,0,1,243,249,5,128,128,128,2,18,16,6,128,128,128,1,2,0,0,0,24,115,116,116,115,0,0,0,0,0,0,0,1,0,0,0,2,0,0,4,0,0,0,0,28,115,116,115,99,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,2,0,0,0,1,0,0,0,28,115,116,115,122,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,115,0,0,1,116,0,0,0,20,115,116,99,111,0,0,0,0,0,0,0,1,0,0,0,44,0,0,0,98,117,100,116,97,0,0,0,90,109,101,116,97,0,0,0,0,0,0,0,33,104,100,108,114,0,0,0,0,0,0,0,0,109,100,105,114,97,112,112,108,0,0,0,0,0,0,0,0,0,0,0,0,45,105,108,115,116,0,0,0,37,169,116,111,111,0,0,0,29,100,97,116,97,0,0,0,1,0,0,0,0,76,97,118,102,53,54,46,52,48,46,49,48,49])],{type:"video/mp4"});var Pc=Object.freeze({__proto__:null,STICKY_CONTROLS:1,NO_FULLSCREEN:2,NO_AD_INDICATOR:4,AD_ATTRIBUTION:8,AD_CHOICES:16,REMAINING_TIME:32,VOLUME_BAR:64});const Oc=["progress","duration","remaining"],Mc=Oe("ads/ui");class AdUI extends HTMLElement{constructor(t,e=document.createElement("div")){super(),this.player=t,this.adContainer=e,this.render(),t.addEventListener("ad/playing",t=>this.updateState(t.type)),t.addEventListener("ad/paused",t=>this.updateState(t.type)),t.addEventListener("ad/complete",t=>this.updateState(t.type)),t.on("ad-progress",t=>{const{remaining:e}=t.detail;this.setAttribute("remaining",e+"")}),t.on("ad/hide-first-frame",t=>{const{root:e}=t.detail;Mc("hideFirstFrame"),e.classList.toggle("ad-hide-first-frame",!0)}),t.on("ad/show-first-frame",t=>{const{root:e}=t.detail;Mc("showFirstFrame"),e.classList.toggle("ad-hide-first-frame",!1)}),t.on("ad/resize",t=>{const{opts:e}=t.detail,s=this.style;e.linear?e.width&&(s.width=e.width+"px"):e.width?this.adContainer.style.width=e.width+"px":s.removeProperty("width"),e.height?s.height=e.height+"px":s.removeProperty("height")}),t.on("ad/set-ui-flags",t=>{let{ui_flags:e}=t.detail;if(e=e||0,this.classList.toggle("is-ad-controls-sticky",(1&e)>0),this.classList.toggle("no-fullscreen",(2&e)>0),this.classList.toggle("no-indicator",(4&e)>0),(8&e)>0){const t=document.createElement("div");t.classList.add("ad-attribution"),t.textContent=this.player.i18n("ads.advertisement","Advertisement"),this.adContainer.append(t)}if(this.classList.toggle("no-volume-bar",0==(64&e)),(32&e)>0&&this.controls&&(this.remaining=document.createElement("div"),this.remaining.classList.add("fp-ad-remaining","fp-color-text"),this.controls.prepend(this.remaining)),(16&e)>0&&this.controls){this.classList.toggle("is-ad-choices",!0);const t=document.createElement("div");t.classList.add("fp-ad-choices"),t.textContent=this.player.i18n("ads.adchoices","AdChoices"),t.addEventListener("click",t=>{t.preventDefault(),this.player.togglePlay(!1),window.open("https://adssettings.google.com","_blank")}),this.controls.append(t)}})}static get observedAttributes(){return Oc}updateState(t){["ad/paused","ad/playing"].forEach(e=>{const s=e.replace("/","-"),r=t===e;this.player.setState(s,r),this.classList.toggle(s,r)})}attributeChangedCallback(t,e,s){switch(t){case"duration":return this.onDurationChange(parseFloat(s));case"progress":return this.onProgress(parseFloat(e),parseFloat(s));case"remaining":return this.onRemaining(s)}}onDurationChange(t){}onProgress(t,e){}onRemaining(t){this.remaining&&(this.remaining.textContent=jt(parseFloat(t)))}render(){this.adContainer.classList.add("fp-ad-container"),this.append(this.adContainer),this.controls=_t(this.player,"flowplayer-ad-controls");const t=_t(this.player,"flowplayer-ad-countdown");this.append(this.controls,t)}}const xc=Oe("fpads:native:outstream"),Fc={OUTSTREAM:"is-outstream",HIDDEN:"is-outstream-hidden",SHOWING:"is-outstream-visible",DONE:"is-outstream-done"};var Nc,Uc;!function(t){t.OUTSTREAM_VISIBLE="ads-outstream-visible",t.OUTSTREAM_VIEWPORT_UPDATE="ads-outstream-viewport-update",t.OUTSTREAM_TEARDOWN="ads-outstream-teardown",t.OUTSTREAM_ENDSCREEN_READY="ads-outstream-endscreen-ready"}(Nc||(Nc={})),function(t){t[t.None=0]="None",t[t.Booting=1]="Booting",t[t.Ready=2]="Ready",t[t.Disposed=3]="Disposed"}(Uc||(Uc={}));class Outstream{constructor({ads:t,root:e,content:s,ima:r}){this.state=Uc.None,xc("creating Outstream instance"),this.content=s,this.ads=t,this.root=e,this.ima=r,this.aspectRatio=s.videoHeight/s.videoWidth,this.dimensions=function(t){if(t.clientWidth>0||t.clientHeight)return hd(t);const e={height:t.style.height};fd(t,"opacity",0),fd(t,"display","absolute"),fd(t,"display","inline-block"),fd(t,"height","auto");const s=hd(t);return fd(t,"height",e.height),fd(t,"opacity",1),s}(this.root),this.adUi=new AdUI(s),this.adContainer=this.adUi.adContainer,this.initialVolumeState={},e.classList.add(Fc.OUTSTREAM),e.append(this.adUi),this.hide(),this.ads.on("ad-pause-content",t=>{var e;if(this.state==Uc.Disposed)return;const s=!!(null===(e=t.detail)||void 0===e?void 0:e.linear);this.ads.resize(Object.assign(Object.assign({},this.dimensions),{linear:s}))}),s.on("resize",t=>{if(this.state==Uc.Disposed)return;const e=t.detail;e&&(this.dimensions={width:e.contentRect.width,height:e.contentRect.height},this.ads.resize(this.dimensions))}),s.on("intersectionchange",t=>{if(this.state==Uc.Disposed)return;const e=t.detail;if(e)switch(this.state){case Uc.Booting:return xc(":boot skipping intersectionchange");case Uc.None:return this.state=Uc.Booting,this.begin_life_cycle();case Uc.Ready:if(e.ratio>=.5&&this.ads.adPlaying)return;e.ratio>=.5&&this.ads.resume(),e.ratio<.5&&this.ads.pause()}}),this.setup(),setTimeout(()=>(this.state=Uc.Booting,this.begin_life_cycle()),0)}hide(){return this}restore_aspect_ratio(){return xc(`Outstream.restore_aspect_ratio(${this.aspectRatio})`),this.content.setOpts({ratio:this.aspectRatio}),this}show(){this.root.classList.remove(Outstream.CLASS.HIDDEN),this.root.classList.add(Outstream.CLASS.SHOWING),this.adUi.classList.add("linear","on")}async begin_life_cycle(){this.state=Uc.Ready;const{error:t,result:e}=await Dc(!1),{result:s}=await Dc(!0);this.attach_ad_listeners(),this.initialVolumeState={can_autoplay:!(!e&&!s),muted:!e},xc("Outstream.show() :autoplay >> sound="+e),t&&this.content&&!e&&(this.content.muted=!0,this.content.volume=0),await this.ads.setVideoTag(this.content),await _d({ads:this.ads,content:this.content,adContainer:this.adContainer,ima:this.ima,state:{listening:!1},config:this.content.opts}),wd({content:this.content,ads:this.ads}),this.state=Uc.Ready}attach_ad_listeners(){const t=this.ads;t.once("ad-pause-content",()=>{this.show(),this.ads.adPlaying&&this.ads.pause()}),this.ima.always_show_controls||t.on("vpaid-init",()=>this.adUi.classList.add("is-vpaid"));const e=()=>{Ed.forEach(t=>this.ads.removeListener(t,e));const t=new CustomEvent(Nc.OUTSTREAM_TEARDOWN);xc("Outstream(:teardown)",t),this.content.dispatchEvent(t)};Ed.forEach(t=>this.ads.once(t,e)),this.content.once(Nc.OUTSTREAM_TEARDOWN,t=>{setTimeout(()=>{if(t.defaultPrevented)return this.handle_endscreen();this.dispose()},0)})}handle_endscreen(){this.reset_ui(),this.ads.reset(),Ld({config:this.content.opts,ui:this.adUi,ads:this.ads,adContainer:this.adContainer,ima:this.ima,content:this.content,root:this.content.root,state:{started:!0,listening:!1},initial:{muted:!0,volume:1}})}empty_src(){this.content.setSrc({type:"video/mp4",src:URL.createObjectURL(Cc)})}setup(){this.root.classList.add(Outstream.CLASS.OUTSTREAM),this.root.classList.add(Outstream.CLASS.HIDDEN),this.empty_src()}reset_ui(){const t=this.root;t.classList.remove(Outstream.CLASS.SHOWING),t.classList.remove(Outstream.CLASS.OUTSTREAM),this.adUi.classList.remove("on")}dispose(){if(this.state==Uc.Disposed)return;const t=this.root,e=this.content;this.reset_ui(),t.classList.add(Outstream.CLASS.OUTSTREAM),t.classList.add(Outstream.CLASS.DONE);this.video=this.container=this.ads=0,this.state=Uc.Disposed,e.destroy(),t.innerHTML=""}}function Bc(t){return t&&"number"==typeof t.time}function Gc(t){return t&&"number"==typeof t.percentage&&"number"!=typeof t.time}Outstream.CLASS=Fc;const $c=Oe("ads/ima/sdk");var Hc;async function Kc(t){var e;if(null===(e=null===window||void 0===window?void 0:window.google)||void 0===e?void 0:e.ima)return void $c(":noop");const s=t._storage.getItem("ima/debug")?"https://imasdk.googleapis.com/js/sdkloader/ima3_debug.js":"https://imasdk.googleapis.com/js/sdkloader/ima3.js";try{return await async function(t){return new Promise((e,s)=>{let r=document.querySelector(`script[src='${t}']`);if(r)return Vc(r,e,s);r=document.createElement("script"),r.setAttribute("state",Hc.LOADING),Vc(r,e,s),r.src=t,document.head.appendChild(r)})}(s),void $c(":loaded")}catch(t){$c(":error "+t.message,t)}}function Vc(t,e,s){const r=t.getAttribute("state");if(r&&[Hc.ERROR,Hc.LOADED].includes(r))return e(void 0);t.addEventListener("load",()=>{t.setAttribute("state",Hc.LOADED),e(void 0)},{once:!0}),["error","abort"].forEach(e=>{t.addEventListener(e,()=>{t.setAttribute("state",Hc.ERROR),s("script failed to load")},{once:!0})})}!function(t){t.LOADING="loading",t.LOADED="loaded",t.ERROR="error"}(Hc||(Hc={}));const qc=Oe("ads/index");async function jc(t,e,s){let r=t.autoplay;if(t.autoplay&&(qc("handling initial autoplay, original_autoplay: ",r),s.autoplay=!1,t.autoplay=0,s.once(y,()=>{setTimeout(()=>{var e;if(!(null===(e=t.ima)||void 0===e?void 0:e.ads)){if(t.autoplay=r,!s.hasState(ht))return s.once("viewenter",()=>s.togglePlay(!0));s.togglePlay(!0)}},0)})),await Kc(s),!("google"in window))return console.warn("google.ima unavailable");const i=s.ads=new AdsController,n=i.analytics;let a=!1;i.resize(hd(e)),md&&(s.on([h,f,"webkitendfullscreen"],t=>{var e;const r=t.type===h;null===(e=null==s?void 0:s.ads)||void 0===e||e.adapter.setIOSPlaysInline(!r)}),i.on("ad-postroll-finished",()=>{i.adapter.isSharedVideoTag()&&i.once("ad-break-completed",()=>{s.src=s.original_src,s.once(_,()=>{s.togglePlay(!1)}),s.webkitExitFullscreen()})})),s.on(w,(function(){i&&i.destroy()}));const o=async t=>{const o=t.ima;if(void 0===r&&t.autoplay&&(r=t.autoplay),!o)return;if(!Array.isArray(o.ads))return qc("handling non-array ima.ads"),void(void 0!==r?t.autoplay=r:delete t.autoplay);const l=t.duration||s.duration;if(o.ads=function(t,e){return Array.isArray(t)?t.filter(t=>Bc(t)||Gc(t)).reduce((t,s)=>{if(Bc(s))return t.push(s),t;if(s.lazy)return t.push(s),t;if(Gc(s)){const r=Object.assign({},s),i=s.percentage?s.percentage*e:0;return isNaN(i)||(r.time=i<0||i===e?-1:i),t.push(r),t}return t},[]):(console.warn("AdSchedule was not an Array"),[])}(o.ads,l),i.setSchedule(o.ads,l),t.metadata&&Analytics.mergeMetadata(n,t.metadata),t.metadata&&i.mergeMacros(t.metadata),t.metadata&&o.parameters&&(o.parameters=Object.assign(Object.assign({},o.parameters),t.metadata)),Analytics.mergeMetadata(n,{muted:t.muted||!1,autoplay:t.autoplay||!1}),!a){if(a=!0,t.lang&&!o.Locale&&(o.Locale=t.lang),Schedule.isOutstream(o.ads))return qc("is outstream, returning"),new Outstream({root:e,content:s,ads:i,ima:o});Td({config:Object.assign(Object.assign({},t),{autoplay:r}),root:e,content:s,ads:i,ima:o})}};t.ima&&o(t),s.on(R,({detail:t})=>o(t))}class AdControls extends HTMLElement{constructor(t){super(),this.player=t,this.render()}render(){this.classList.add("fp-ad-controls");const t=_t(this.player,"flowplayer-ad-indicator"),e=document.createElement("div");e.classList.add("ad-playback-controls");const s=_t(this.player,V),r=_t(this.player,q);s.addEventListener("click",()=>{this.player.emit("request/ad/play"),setTimeout((function(){r.focus&&r.focus()}),100)}),r.addEventListener("click",()=>{this.player.emit("request/ad/pause"),setTimeout((function(){s.focus&&s.focus()}),100)}),e.append(s,r);const i=_t(this.player,z);i.addEventListener("click",()=>this.player.emit("request/ad/muteunmute"));const n=_t(this.player,U),a=_t(this.player,G);this.append(t,e,i,n,a)}}class AdCountdown extends HTMLElement{constructor(t){super(),this.player=t,t.on("ad-progress",t=>{const{duration:e,remaining:s}=t.detail;this.setAttribute("duration",e+""),this.setAttribute("remaining",s+"")}),t.on("ad-started",t=>{t.detail.linear&&(this.style.setProperty("--ad-percent-previous","0"),this.style.setProperty("--ad-percent-complete","0"))}),this.addEventListener("animationend",()=>{const t=this.style.getPropertyValue("--ad-percent-complete")||"0";this.style.setProperty("--ad-percent-previous",t)})}static get observedAttributes(){return["remaining"]}attributeChangedCallback(t,e,s){switch(t){case"remaining":return this.onRemaining(s)}}onRemaining(t){const e=parseFloat(this.getAttribute("duration")||"0");t||(t=e+"");const s=parseFloat(t),r=this.style.getPropertyValue("--ad-percent-complete")||"0";this.style.setProperty("--ad-percent-previous",r),this.classList.remove("go");const i=((e-s)/e*100).toFixed(3);requestAnimationFrame(()=>{this.style.setProperty("--ad-percent-complete",i),this.classList.add("go")})}}class AdIndicator extends HTMLElement{constructor(t){super(),this.player=t,this.render(),t.on("ad-started",t=>{const{position:e,totals:s}=t.detail.ad;this.setAttribute("position",e+""),this.setAttribute("totals",s+"")})}static get observedAttributes(){return["position","totals"]}attributeChangedCallback(t,e){switch(t){case"position":case"totals":return this.updateText()}}updateText(){if(!this.element)return;const t=parseFloat(this.getAttribute("position")||"0"),e=parseFloat(this.getAttribute("totals")||"0");this.element.textContent=`${this.player.i18n("ads.indicator","ADS")} ${t} / ${e}`}render(){this.element=document.createElement("div"),this.element.classList.add("ad-indicator","fp-color-text"),this.element.textContent=this.player.i18n("ads.indicator","ADS"),this.append(this.element)}}var Wc=Object.freeze({__proto__:null,SINGlE_INLINE_LINEAR:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_ad_samples&sz=640x480&cust_params=sample_ct%3Dlinear&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=",SINGLE_SKIPPABLE_INLINE:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_preroll_skippable&sz=640x480&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=",SINGLE_REDIRECT_LINEAR:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_ad_samples&sz=640x480&cust_params=sample_ct%3Dredirectlinear&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=",SINGLE_REDIRECT_ERROR:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_ad_samples&sz=640x480&cust_params=sample_ct%3Dredirecterror&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=",SINGLE_REDIRECT_BROKEN:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_ad_samples&sz=640x480&cust_params=sample_ct%3Dredirecterror&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&nofb=1&correlator=",SINGLE_VPAID_20_LINEAR:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_ad_samples&sz=640x480&cust_params=sample_ct%3Dlinearvpaid2js&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=",SINGLE_VPAID_20_NON_LINEAR:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_ad_samples&sz=640x480&cust_params=sample_ct%3Dnonlinearvpaid2js&ciu_szs=728x90%2C300x250&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=",SINGLE_NON_LINEAR_INLINE:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/nonlinear_ad_samples&sz=480x70&cust_params=sample_ct%3Dnonlinear&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=",VMAP_SESSION_AD_RULE_PREROLL:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sar%3Da0f2&ciu_szs=300x250&ad_rule=1&gdfp_req=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&correlator=",VMAP_PREROLL:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sample_ar%3Dpreonly&ciu_szs=300x250%2C728x90&gdfp_req=1&ad_rule=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&correlator=",VMAP_PREROLL_BUMPER:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sample_ar%3Dpreonlybumper&ciu_szs=300x250&gdfp_req=1&ad_rule=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&correlator=",VMAP_POSTROLL:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sample_ar%3Dpostonly&ciu_szs=300x250&gdfp_req=1&ad_rule=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&correlator=",VMAP_POSTROLL_BUMPER:"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sample_ar%3Dpostonlybumper&ciu_szs=300x250&gdfp_req=1&ad_rule=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&correlator="});const{samsung_tv:Yc}=s();class Ads{constructor(t){this.umd=t,St(t,yd,AdUI),St(t,"flowplayer-ad-controls",AdControls),St(t,"flowplayer-ad-countdown",AdCountdown),St(t,"flowplayer-ad-indicator",AdIndicator)}init(t,e,s){if(ve.from_token(t.token||"").is_granted(ve.permissions.ADS)&&!Yc)return jc(t,e,s)}}return Ads.events=pd,Ads.ui=Pc,Ads.tags=Wc,ce(window,Ads),Sr.extensions.push(HLS,OVP,Ads),Object.assign(Sr,{hls:HLS,ads:Ads,ovp:OVP}),Sr}));
|