@flowplayer/player 3.43.0-rc.1 → 3.43.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/embed.js CHANGED
@@ -1,7 +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 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),i=/Android/.test(e)&&!/Firefox/.test(e),r=/^((?!chrome|android).)*safari/i.test(e),n=/chrome|crios/i.test(e)&&!/opr|opera|chromium|edg|ucbrowser|googlebot/i.test(e),a=/firefox|fxios/i.test(e)&&!/seamonkey/i.test(e),o=/edg/i.test(e),l=/opr|opera/i.test(e),d=/SamsungBrowser/.test(e),c=d&&/SMART-TV/.test(e);return{controls:!s,video:function(e){return t&&document.createElement("video").canPlayType(e)},lang:t&&window.navigator.language,android:i,iphone:s,safari:r,edge:o,opera:l,chrome:n,firefox:a,ios:t&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,samsung:d,samsung_tv:d&&c,touch:"ontouchstart"in window,tizen:"tizen"in window,webOS:"webos"in window,anyTv:"tizen"in window||"webos"in window}}const i="mount",r="retry",n="error",a="click",o="dblclick",l="mouseleave",d="mouseup",c="mousedown",h="mousemove",u="touchstart",f="touchmove",g="touchend",p="touchcancel",m="resize",v="fullscreenenter",y="fullscreenexit",E="loadedmetadata",T="loadeddata",S="progress",A="timeupdate",_="loadstart",b="volumechange",L="pause",R="playing",I="play",k="waiting",w="canplay",P="ended",D="seeked",C="seeking",O="durationchange",M="viewenter",x="viewleave",F="src",N="reap",U="qualities",B="qualitychange",$="quality:set",G="tracks:video:select",H="landscape",K="portrait",V="dvr",j="live",q="recover",W="seek:queued",Y="seek:cancel",z="remotesession:started",Q="remotesession:ended",X="intersectionchange",Z="renderplugin",J="audioonlysource",tt="error:fatal",et="config",st="state",it="beforeplay",rt="beforepause",nt="content:loadstart",at="flowplayer:error";var ot=Object.freeze({__proto__:null,MOUNT:i,RETRY:r,ERROR:n,CONTEXT_MENU:"contextmenu",CLICK:a,DBL_CLICK:o,KEYUP:"keyup",KEYDOWN:"keydown",LOAD:"load",MOUSE_ENTER:"mouseenter",MOUSE_LEAVE:l,MOUSE_UP:d,MOUSE_DOWN:c,MOUSE_MOVE:h,TOUCH_START:u,TOUCH_MOVE:f,TOUCH_END:g,TOUCH_CANCEL:p,RESIZE:m,SCROLL:"scroll",FULLSCREEN_ENTER:v,FULLSCREEN_EXIT:y,FULLSCREEN_CHANGE:"fullscreenchange",METADATA:E,DATA:T,PROGRESS:S,TIME_UPDATE:A,LOAD_START:_,VOLUME_CHANGE:b,PAUSE:L,PLAYING:R,PLAY:I,WAITING:k,CAN_PLAY:w,ENDED:P,SEEKED:D,SEEKING:C,DURATION_CHANGE:O,VIEW_ENTER:M,VIEW_LEAVE:x,SOURCE:F,REAP:N,QUALITIES:U,QUALITY_CHANGE:B,VIDEO_TRACKS:"videoTracks",SET_QUALITY:$,VIDEO_TRACK_SELECT:G,RECOMMENDATIONS_READY:"recommendationsready",LANDSCAPE:H,PORTRAIT:K,DVR:V,LIVE:j,RECOVER:q,SEEK_QUEUED:W,SEEK_CANCEL:Y,PLUGIN_REGISTERED:"plugin:registered",REMOTE_SESSION_STARTED:z,REMOTE_SESSION_ENDED:Q,INTERSECTIONCHANGE:X,WEBKIT_NEEDKEY:"webkitneedkey",RENDER_PLUGIN:Z,AUDIO_ONLY_SOURCE:J,NON_RECOVERABLE_ERROR:tt,CONFIG:et,STATE:st,BEFORE_PLAY:it,BEFORE_PAUSE:rt,CONTENT_REAL_LOAD_START:nt,CUEPOINTS:"cuepoints",CUEPOINT_START:"cuepointstart",CUEPOINT_END:"cuepointend",STANDARD_ERROR:at});const lt="flowplayer-ui",dt="flowplayer-logo",ct="flowplayer-control",ht="flowplayer-control-buttons",ut="flowplayer-live-status",ft="flowplayer-elapsed-time",gt="flowplayer-timeline-bar",pt="flowplayer-control-duration",mt="flowplayer-volume-control",vt="flowplayer-volume-bar",yt="flowplayer-header",Et="flowplayer-header-left-zone",Tt="flowplayer-header-right-zone",St="flowplayer-header-duration",At="flowplayer-middle",_t="flowplayer-middle-zone",bt="flowplayer-wait",Lt="flowplayer-middle-buttons",Rt="flowplayer-middle-left-zone",It="flowplayer-middle-right-zone",kt="flowplayer-small-play-icon",wt="flowplayer-small-pause-icon",Pt="flowplayer-play-icon",Dt="flowplayer-pause-icon",Ct="flowplayer-fullscreen-enter-icon",Ot="flowplayer-fullscreen-exit-icon",Mt="flowplayer-fast-forward-icon",xt="flowplayer-rewind-icon",Ft="flowplayer-volume-icon",Nt="flowplayer-live-countdown",Ut="flowplayer-error";var Bt=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",SETTINGS_MOUNT_ZONE:"flowplayer-settings-mount-zone",QSEL_MOUNT_ZONE:"flowplayer-qsel-mount-zone",ASEL_MOUNT_ZONE:"flowplayer-asel-mount-zone",VTSEL_MOUNT_ZONE:"flowplayer-vtsel-mount-zone",SPEED_MOUNT_ZONE:"flowplayer-speed-mount-zone",UI:lt,LOGO:dt,CONTROL:ct,CONTROL_BUTTONS:ht,LIVE_STATUS:ut,ELAPSED:ft,TIMELINE:gt,CHAPTERS_TIMELINE:"flowplayer-chapters-timeline-bar",CONTROL_DURATION:pt,VOLUME_CONTROL:mt,VOLUME_BAR:vt,HEADER:yt,HEADER_LEFT_ZONE:Et,HEADER_RIGHT_ZONE:Tt,HEADER_DURATION:St,MIDDLE:At,MIDDLE_ZONE:_t,WAIT:bt,MIDDLE_BUTTONS:Lt,MIDDLE_LEFT_ZONE:Rt,MIDDLE_RIGHT_ZONE:It,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:kt,SMALL_PAUSE_ICON:wt,PLAY_ICON:Pt,PAUSE_ICON:Dt,FULLSCREEN_ENTER_ICON:Ct,FULLSCREEN_EXIT_ICON:Ot,SKIP_NEXT_ICON:"flowplayer-skip-next-icon",SKIP_PREVIOUS_ICON:"flowplayer-skip-previous-icon",FAST_FORWARD_ICON:Mt,REWIND_ICON:xt,SHARE_ICON:"flowplayer-share-icon",SUBTITLES_MENU_ICON:"flowplayer-subs-menu-icon",SETTINGS_MENU_ICON:"flowplayer-settings-icon",MENU_BACK_ICON:"flowplayer-menu-back",VOLUME_ICON:Ft,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:Nt,PLAYLIST_CONTROLS:"flowplayer-playlist-controls",THUMBNAILS_CAROUSEL:"flowplayer-thumbnails-carousel",ERROR_COMPONENT:Ut,TV_MENU:"flowplayer-tv-menu",CUE_COMPONENT:"flowplayer-cue",SSAI_UI:"flowplayer-ssai-ui",SSAI_CONTROLS:"flowplayer-ssai-controls",SSAI_TIMELINE:"flowplayer-ssai-timeline",SSAI_INDICATOR:"flowplayer-ssai-indicator"});const $t="is-playing",Gt="is-fullscreen",Ht="is-paused",Kt="is-muted",Vt="is-loaded",jt="is-loading",qt="is-starting",Wt="is-seeking",Yt="is-disabled",zt="is-small",Qt="is-tiny",Xt="is-ended",Zt="is-live",Jt="is-error",te="is-waiting",ee="is-autoplay",se="is-toggling",ie="is-live-seeked",re="no-timeline",ne="has-poster",ae="will-play",oe="will-pause",le="has-menu-opened",de="is-touched",ce="is-hovered",he="is-touch-device",ue="will-seek",fe="is-seekable",ge="is-in-viewport",pe="no-controls",me="is-destroyed",ve="is-source-processing";var ye=Object.freeze({__proto__:null,PLAYING:$t,FULLSCREEN:Gt,PAUSED:Ht,MUTED:Kt,LOADED:Vt,LOADING:jt,STARTING:qt,SEEKING:Wt,DISABLED:Yt,SMALL:zt,TINY:Qt,TV:"is-tv",ENDED:Xt,LIVE:Zt,ERRORED:Jt,WAITING:te,AUTOPLAY:ee,SEAMLESS:"is-seamless",TOGGLING:se,LIVE_SEEKED:ie,NO_DVR:re,HAS_POSTER:ne,WILL_PLAY:ae,WILL_PAUSE:oe,MENU_OPENED:le,TOUCHED:de,HOVERED:ce,TOUCH_DEVICE:he,WILL_SEEK:ue,SEEKABLE:fe,IN_VIEWPORT:ge,NO_CONTROLS:pe,DESTROYED:me,IS_SOURCE_PROCESSING:ve});function Ee(t){this.message=t}Ee.prototype=new Error,Ee.prototype.name="InvalidCharacterError";var Te="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new Ee("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,i,r=0,n=0,a="";i=e.charAt(n++);~i&&(s=r%4?64*s+i:i,r++%4)?a+=String.fromCharCode(255&s>>(-2*r&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return a};var Se=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(Te(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 Te(e)}};function Ae(t){this.message=t}Ae.prototype=new Error,Ae.prototype.name="InvalidTokenError";var _e=function(t,e){if("string"!=typeof t)throw new Ae("Invalid token specified");var s=!0===(e=e||{}).header?0:1;try{return JSON.parse(Se(t.split(".")[s]))}catch(t){throw new Ae("Invalid token specified: "+t.message)}};_e.InvalidTokenError=Ae;const be=new Map,Le=(t,e)=>new(((t,e)=>{const s=t.get(e);if(!s)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 r=window.customElements.get(s);return"function"!=typeof r?i:r})(t._customElements,e))(t),Re=(t,e,s)=>{window.customElements.get(e)||window.customElements.define(e,s),t.customElements.get(e)||t.customElements.set(e,e)},Ie=(t,e)=>{const s=t.customElements.get(e),i=s&&s===e,r=Object.values(t.defaultElements).includes(e);return Boolean(r||i)};var ke,we;function Pe(t){return!0===t?we.ON:!1===t?we.OFF:t}!function(t){t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=4]="HIGH"}(ke||(ke={})),function(t){t[t.OFF=0]="OFF",t[t.ON=1]="ON",t[t.AUDIO_REQUIRED=2]="AUDIO_REQUIRED"}(we||(we={}));const De={Unknown:"00-00",MediaUnknown:"01-00",MediaUnavailable:"01-01",MediaUnsupportedVideoFormat:"01-02",MediaUnsupportedAudioFormat:"01-03",MediaBitrateExceeded:"01-04",MediaBufferOverread:"01-05",MediaIntegerOverflow:"01-06",MediaQuotaExceeded:"01-07",MediaInvalidCompositionDuration:"01-08",MediaInvalidCompositionSourceDuration:"01-09",MediaInvalidCompositionSourceStartTime:"01-10",MediaMalformedDepth:"01-11",PlaybackUnknown:"02-00",PlaybackVideoBufferUnderRun:"02-01",PlaybackAudioBufferUnderRun:"02-02",PlaybackVideoBufferingTimeout:"02-03",PlaybackAudioBufferingTimeout:"02-04",PlaybackManifestParseError:"02-05",PlaybackVideoDecodeError:"02-06",PlaybackAudioDecodeError:"02-07",PlaybackDroppedFramesExceeded:"02-08",PlaybackPlayheadExceedsDuration:"02-09",PlaybackUnsupportedDevice:"02-10",PlaybackManifestLoadError:"02-11",PlaybackManifestLoadTimeout:"02-12",PlaybackManifestParsingError:"02-13",PlaybackManifestIncompatibleCodecs:"02-14",PlaybackLevelEmptyError:"02-15",PlaybackLevelLoadError:"02-16",PlaybackLevelLoadTimeout:"02-17",PlaybackLevelSwitchError:"02-18",PlaybackAudioTrackLoadError:"02-19",PlaybackAudioTrackLoadTimeout:"02-20",PlaybackFragLoadError:"02-21",PlaybackFragLoadTimeout:"02-22",PlaybackFragDecryptError:"02-23",PlaybackFragParsingError:"02-24",PlaybackFragGap:"02-25",PlaybackRemuxAllocError:"02-26",PlaybackBufferAddCodecError:"02-27",PlaybackBufferIncompatibleCodecs:"02-28",PlaybackBufferAppendError:"02-29",PlaybackBufferStalledError:"02-30",PlaybackBufferFullError:"02-31",PlaybackBufferSeekOverHole:"02-32",PlaybackBufferNudgeOnStall:"02-33",PlaybackInternalException:"02-34",PlaybackInternalAborted:"02-35",PlaybackManifestLoaderFailure:"02-36",PlaybackSegmentBaseLoaderError:"02-37",PlaybackTimeSyncFailed:"02-38",PlaybackFragmentLoaderFailure:"02-39",PlaybackAppendError:"02-40",PlaybackRemoveError:"02-41",PlaybackDataUpdateFailed:"02-42",PlaybackManifestNoStreams:"02-43",PlaybackUnknownManifestType:"02-44",PlaybackDashInsufficientSegmentInfo:"02-45",PlaybackDashNoRepresentations:"02-46",PlaybackDashNoAdaptationSets:"02-47",PlaybackDashNoInitSegment:"02-48",PlaybackDashUnsupportedContainerFormat:"02-49",PlaybackDashKeySystemMismatch:"02-50",PlaybackMultipleKeyIDs:"02-51",PlaybackDashConflictingKeyIDs:"02-52",PlaybackRestrictedStreams:"02-53",PlaybackHlsMasterAndMediaTags:"02-54",PlaybackRepresentationIdConflict:"02-55",PlaybackHlsUnsupportedKeyFormats:"02-56",PlaybackManifestNoVariants:"02-57",PlaybackHlsUndeclaredVariables:"02-58",PlaybackAes128InvalidKeyLength:"02-59",PlaybackDashConflictingAes128Keys:"02-60",PlaybackDashUnsupportedAes128Encryption:"02-61",PlaybackManifestPatchMismatch:"02-62",PlaybackEmptyMediaPlaylist:"02-63",PlaybackNonContiguousCompositionTrack:"02-64",PlaybackDecoderNotFound:"02-65",PlaybackDecoderTemporarilyUnavailable:"02-66",PlaybackIncompatibleAsset:"02-67",PlaybackNoCompatibleExternalDisplay:"02-69",PlaybackOutOfMemory:"02-70",PlaybackToneMappingFailed:"02-71",PlaybackVideoCompositorFailed:"02-72",NetworkUnknown:"03-00",NetworkNoInternet:"03-01",NetworkRequestTimeout:"03-02",NetworkUnableToResolveHost:"03-03",NetworkResourceNotFound:"03-04",NetworkExpiredUrl:"03-05",NetworkUrlResolutionFailed:"03-06",NetworkDownloadErrorIdManifest:"03-07",NetworkDownloadErrorIdSidx:"03-08",NetworkDownloadErrorIdContent:"03-09",NetworkDownloadErrorIdInitialization:"03-10",NetworkDownloadErrorIdXlink:"03-11",NetworkHttpRequestFailed:"03-12",NetworkMaxRetriesExceeded:"03-13",NetworkSegmentMissing:"03-14",NetworkHttp400BadRequest:"03-400",NetworkHttp401Unauthorized:"03-401",NetworkHttp402PaymentRequired:"03-402",NetworkHttp403Forbidden:"03-403",NetworkHttp404NotFound:"03-404",NetworkHttp405MethodNotAllowed:"03-405",NetworkHttp406NotAcceptable:"03-406",NetworkHttp407ProxyAuthenticationRequired:"03-407",NetworkHttp408RequestTimeout:"03-408",NetworkHttp409Conflict:"03-409",NetworkHttp410Gone:"03-410",NetworkHttp411LengthRequired:"03-411",NetworkHttp412PreconditionFailed:"03-412",NetworkHttp413PayloadTooLarge:"03-413",NetworkHttp414URITooLong:"03-414",NetworkHttp415UnsupportedMediaType:"03-415",NetworkHttp416RangeNotSatisfiable:"03-416",NetworkHttp417ExpectationFailed:"03-417",NetworkHttp418ImATeapot:"03-418",NetworkHttp421MisdirectedRequest:"03-421",NetworkHttp422UnprocessableEntity:"03-422",NetworkHttp423Locked:"03-423",NetworkHttp424FailedDependency:"03-424",NetworkHttp425TooEarly:"03-425",NetworkHttp426UpgradeRequired:"03-426",NetworkHttp428PreconditionRequired:"03-428",NetworkHttp429TooManyRequests:"03-429",NetworkHttp431RequestHeaderFieldsTooLarge:"03-431",NetworkHttp451UnavailableForLegalReasons:"03-451",NetworkHttp500InternalServerError:"03-500",NetworkHttp501NotImplemented:"03-501",NetworkHttp502BadGateway:"03-502",NetworkHttp503ServiceUnavailable:"03-503",NetworkHttp504GatewayTimeout:"03-504",NetworkHttp505HTTPVersionNotSupported:"03-505",NetworkHttp506VariantAlsoNegotiates:"03-506",NetworkHttp507InsufficientStorage:"03-507",NetworkHttp508LoopDetected:"03-508",NetworkHttp510NotExtended:"03-510",NetworkHttp511NetworkAuthenticationRequired:"03-511",ContentProtectionUnknown:"04-00",ContentProtectionConcurrentStreamLimitExceeded:"04-01",ContentProtectionEntitlementRefused:"04-02",ContentProtectionLicenseExpired:"04-03",ContentProtectionBadLicenseRequest:"04-04",ContentProtectionLicenseServerTimeout:"04-05",ContentProtectionInsufficientHDCPSupport:"04-06",ContentProtectionGeoRestricted:"04-07",ContentProtectionParentalControlRestricted:"04-08",ContentProtectionCDNUnauthorized:"04-09",ContentProtectionInvalidAccessToken:"04-10",ContentProtectionKeySystemNoKeys:"04-11",ContentProtectionKeySystemNoAccess:"04-12",ContentProtectionKeySystemNoSession:"04-13",ContentProtectionKeySystemNoConfiguredLicense:"04-14",ContentProtectionKeySystemCertificateRequestFailed:"04-15",ContentProtectionKeySystemCertificateUpdateFailed:"04-16",ContentProtectionKeySystemSessionUpdateFailed:"04-17",ContentProtectionKeySystemStatusOutputRestricted:"04-18",ContentProtectionKeySystemStatusInternalError:"04-19",ContentProtectionKeyLoadError:"04-20",ContentProtectionKeyLoadTimeout:"04-21",ContentProtectionCapabilityMediaKeysError:"04-22",ContentProtectionManifestKeySystemUnknown:"04-23",ContentProtectionKeySystemUnavailable:"04-24",ContentProtectionCDMCreationFailed:"04-25",ContentProtectionCDMAttachFailed:"04-26",ContentProtectionCDMServerCertificateRejected:"04-27",ContentProtectionCDMSessionCreationFailed:"04-28",ContentProtectionCDMLicenseRequestFailed:"04-29",ContentProtectionCDMLicenseResponseRejected:"04-30",ContentProtectionManifestMissingDRMInfo:"04-31",ContentProtectionLicenseServerMissing:"04-32",ContentProtectionOfflineSessionRemoved:"04-33",ContentProtectionInitDataTransformationError:"04-34",ContentProtectionServerCertificateRequestFailed:"04-35",ContentProtectionInsufficientHDCPVersion:"04-36",ContentProtectionHDCPVersionCheckFailed:"04-37",AdsUnknown:"08-00",AdsVastParseError:"08-100",AdsInvalidVastSchema:"08-101",AdsVastVersionNotSupported:"08-102",AdsUnexpectedAdType:"08-200",AdsCreativeLinearityMismatch:"08-201",AdsCreativeDurationMismatch:"08-202",AdsCreativeSizeMismatch:"08-203",AdsWrapperVastError:"08-300",AdsVastResponseRedirectTimeout:"08-301",AdsWrapperLimitReached:"08-302",AdsVastResponseEmpty:"08-303",AdsLinearAdDisplayError:"08-400",AdsMediaFileNotFound:"08-401",AdsMediaFileUnavailable:"08-402",AdsUnsupportedMimeType:"08-403",AdsUnableToDisplayMediaFile:"08-405",AdsMezzanineFileMissing:"08-406",AdsMezzanineFileDownloaded:"08-407",AdsRejectedAd:"08-408",AdsInteractiveCreativeError:"08-409",AdsVerificationNodeExecutionError:"08-410",AdsNonLinearAdDisplayError:"08-500",AdsNonLinearAdSizeMismatch:"08-501",AdsNonLinearAdFetchError:"08-502",AdsNonLinearUnsupportedType:"08-503",AdsCompanionAdDisplayError:"08-600",AdsCompanionAdSizeMismatch:"08-601",AdsRequiredCompanionAdError:"08-602",AdsCompanionAdFetchError:"08-603",AdsUndefinedVastError:"08-900",AdsUnknownVpaidError:"08-901",AdsVastDocumentEmpty:"08-999"},Ce=Object.fromEntries(Object.entries(De).map(([t,e])=>[e,t]));function Oe(t,e,s){const i="boolean"==typeof s;if("boolean"!=typeof s&&(s=!!t.hasState(oe)||t.paused),function(t,e,s){const i=t.poll(e?it:rt,{forced:s});return i&&i.defaultPrevented}(t,s,i))return Promise.resolve();if(!s)return t.hasState(ae)?(t.setState(oe,!0),t.setState(ae,!1),Promise.resolve()):Promise.resolve(t.pause());if(0==t.reaper)return Promise.resolve();const r=t.reaper.get("__pending_play");return t.paused||r?r?(r.src!==xe(t.original_src)&&Me(t),r):(function(t){return(0==t.networkState||0==t.readyState)&&t.currentSrc==xe(t.original_src)}(t)&&Me(t),function(t){const e=t.hasState(ee),s=e&&(t=>t.autoplay&&we.AUDIO_REQUIRED&Pe(t.autoplay))(t.opts);s&&(t.muted&&t.toggleMute(!1),0==t.volume&&(t.volume=1));e&&t.setState(ee,!1);return t.play().then(()=>{t.hasState(oe)&&t.togglePlay(!1)}).catch(i=>{if(console.warn(e?s?"[flowplayer/play] autoplay audio required\n%s":"[flowplayer/play] attempting muted autoplay\n%s":"",i.message,"\ninstance:",t),e&&!s)return t.muted=!0,t.play()})}(t)):(t.setState(oe,!1),!t.hasState($t)&&t.setState(ae,!0),Promise.resolve())}function Me(t){t.opts.is_native&&(t.hasState(Vt)||(t.hasState(jt)||t.emit(nt),t.setState(jt,!0),t.load()))}function xe(t){const e=document.createElement("a");return e.href=t,e.href}function Fe(t,e){var s={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(s[i]=t[i]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(t);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r])&&(s[i[r]]=t[i[r]])}return s}function Ne(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 Ue(t){switch(t){case"video/mpd":return"application/dash+xml";case"video/m3u8":return"application/x-mpegurl";default:return t}}const Be=t=>{var{src:e}=t,s=Fe(t,["src"]);return[Object.assign({src:e,type:e?Ue("video/"+Ne(e)):""},s)]};function $e(t){return Be({src:t})}function Ge(t){var{src:e,type:s}=t,i=Fe(t,["src","type"]);return e&&s?[Object.assign({src:e,type:s},i)]:s&&!e?[Object.assign({type:s},i)]:Be(Object.assign({src:e},i))}const He="health:record",Ke="rebuffer",Ve="rebuffer:ended",je="display",qe="insights:ttff",We="insights:time_to_first_frag_loaded",Ye="insights:watched_interval",ze="flowplayer:feature",Qe="health:ready";var Xe=Object.freeze({__proto__:null,RECORD:He,REBUFFER:Ke,REBUFFER_ENDED:Ve,DISPLAY:je,TIME_TO_FIRST_FRAME:qe,TIME_TO_FIRST_FRAGMENT_LOADED:We,WATCHED_INTERVAL:Ye,FEATURE_USAGE:ze,HEALTH_SERVICE_READY:Qe});const Ze={All:1,High:.1,Medium:.01,Low:.001,None:0};function Je(t,{feature_name:e,behavior:s,sample_rate:i}){e&&(i||(i=Ze.All),t.emit(ze,{feature_name:e,behavior:s,sample_rate:i}))}const ts=new Map;var es;function ss(t,e,s,i={safari:!1}){const r=is(s);return function(t){[Wt,oe,ae,$t,Ht,jt,Vt,ie].forEach(e=>t.setState(e,!1)),t.setState(qt,!0)}(t),Array(...Array(r.length)).map((t,e)=>e).some(s=>{const n=r[s];if(es.Ok==function(t,e,s){t.emit(F,s),e.playback_token&&"string"==typeof s.src&&s.src.startsWith("https://")&&(s.src=function(t,e){const s=new URL(t);return s.pathname=`/pt:${e}${s.pathname}`,s.toString()}(s.src,e.playback_token),Je(t,{feature_name:"signed-urls",behavior:"used",sample_rate:.1}));"string"==typeof s.src&&(t.original_src=s.src);const i=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:!i}),i?(i.onload(e,t.root,t,s),es.Ok):es.Err}(t,e,n)||es.Ok==function(t,e,s,i={safari:!1}){var r;/^audio\//.test(s.type||"")&&t.emit(J);e.start_time&&(s.src=s.src+"#t="+e.start_time);if(""==t.canPlayType(s.type||""))return es.Err;if(s.drm&&(!s.drm["com.apple.fps.1_0"]||!i.safari))return es.Err;"string"==typeof s.src&&(t.preload=null!==(r=e.preload)&&void 0!==r?r:"auto",t.src=s.src);return es.Ok}(t,e,n,i))return!0;s==r.length-1&&"string"==typeof n.src&&(t.src=n.src)}),t}function is(t){return"string"==typeof t?$e(t):Array.isArray(t)||"object"!=typeof t?t.reduce(function(t,e){return"string"==typeof e&&(e=$e(e)),"object"!=typeof e||Array.isArray(e)||(e=Ge(e)),t.concat(e)},[]):Ge(t)}!function(t){t[t.Err=0]="Err",t[t.Ok=1]="Ok"}(es||(es={}));const rs=[N,C,F,Y];var ns;function as(t,e,s){return isNaN(t.duration)||isNaN(t.currentTime)?{}:(e.offset+=s,0==e.offset?os(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,os(t,e))},1e3),function(t,e){t.setState(ue,!0),t.setState(ns.BACKWARD,e.offset<0),t.setState(ns.FORWARD,e.offset>0)}(t,e),t.emit(W,e),e))}function os(t,e){e.timer&&clearTimeout(e.timer),e.timer=e.offset=0,function(t){t.setState(ns.FORWARD,!1),t.setState(ns.BACKWARD,!1),t.setState(ue,!1)}(t)}function ls(t,e,s){const i=function(t){return Array.isArray(t)?t.slice(0):t.split(".")}(e);for(;i.length;){if(null==t)return s;const e=i.shift();if("string"!=typeof e)return s;t=t[e]}return null==t?s:t}function ds(t){const e="number"==typeof t?t:parseInt(t,10);return(e>9?"":"0")+e}function cs(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 i=Math.floor(t/60);return t-=60*i,s>=1?(i-=60*s,e+s+":"+ds(i)+":"+ds(t)):e+ds(i)+":"+ds(t)}!function(t){t.FORWARD="forward",t.BACKWARD="backward"}(ns||(ns={}));const hs=navigator.languages||[navigator.language];function us(t,e,s,i){if((i=i||0)>=t.length)return s;return ls(t[i],e,us(t,e,s,i+1))}function fs(t,e,s){const i=new Map,r=e.lang;return r&&t[r]&&i.set(r,t[r]),function(){try{return hs.reduce((t,e)=>~e.indexOf("-")?t.concat(e,e.split("-")[0]):t.concat(e),[])}catch(t){return[]}}().forEach(function(e){t[e]&&!i.has(e)&&i.set(e,t[e])}),t[s]&&!i.has(s)&&i.set(s,t[s]),Array.from(i.values())}const gs=[1e7]+""+-1e3+-4e3+-8e3+-1e11,ps=()=>"undefined"==typeof crypto?"":gs.replace(/[018]/g,t=>(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)),ms="flowplayer/uuid";let vs="";!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 ys=["touchstart","touchmove"];function Es(t,e){const s=new CustomEvent(t,{detail:e,cancelable:!0});return e&&Object.defineProperty(s,"data",{get:()=>e}),s}function Ts(t,e,s){const i=Es(e,s);return t.dispatchEvent(i),t}function Ss(t,e,s){const i=Es(e,s);return t.dispatchEvent(i),i}function As(t,e,s,i){Array.isArray(e)?e.forEach(e=>_s(t,e,s,i)):_s(t,e,s,i)}function _s(t,e,s,i){if(r=e,!~ys.indexOf(r))return t.addEventListener(e,s,i),t;var r;const n=Object.assign(i||{},{passive:!0});return t.addEventListener(e,s,n),t}function bs(t,e,s,i){return As(t,e,s,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 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 Ls={preload:"auto",rtl:!1,controls:!0},Rs=["muted","preload"];function Is(t,i,r){let n;r.live_state={dvr_window:void 0,get dvr(){return n},set dvr(e){n=e;const s=!(!t.live||e);r.hasState(re)!=s&&r.setState(re,s)}},r._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),r.toJSON=function(){return{duration:r.duration,volume:r.volume,currentTime:r.currentTime,states:r.root.className}},r.setSrc=function(e){return ss(r,t,e,s())},r.playerState=r.playerState||{},r.setState=function(t,e){if(r.playerState[t]===!!e)return r;const s=Object.assign({},r.playerState,{[t]:e});return r.playerState=s,Ts(r,st,r.playerState),r},r.createComponents=function(...t){return Array.from({length:t.length}).map((e,s)=>Le(this,t[s]))},r.hasState=function(t){return!!r.playerState[t]},r.transitionState=function(t,e,s){!r.hasState(t)&&r.hasState(e)||(s=0),s&&r.setState(se,!0),r.setState(e,!1),r.setState(t,!0),s&&setTimeout(function(){r.setState(se,!1)},s)},r.emit=(t,e)=>(Ts(r,t,e),r),r.on=(t,e)=>(As(r,t,e),r),r.once=(t,e)=>(bs(r,t,e),r),r.off=(t,e)=>{var s,i;return s=t,i=e,r.removeEventListener(s,i),r},r.poll=(t,e)=>Ss(r,t,e),r.togglePlay=function(t){return r.hasState(Jt)?Promise.reject():Oe(r,0,t)},r.toggleMute=function(t){t=null==t?!r.muted:!!t,r.muted=t,r.muted||r.volume||(r.volume=1),Ts(r,b)},r.toggleDisable=function(t){t=null==t?!r.disabled:!!t,r.setState(Yt,t),r.disabled=t},r.destroy=function(){r.pause();const t=e.indexOf(r);~t&&e.splice(t,1),setTimeout(function(){r.setSrc([]),r.reaper&&r.reaper.clear(),Ts(r,N),r.setState(me,!0)},0)},r.setAttrs=function(t){return Rs.forEach(e=>{if(!(e in t))return;const s=t[e];s?r.setAttribute(e,s.toString()):r.removeAttribute(e)}),r},r.opt=function(e,s){return s=void 0===s?ls(Ls,e):s,ls(t,e,s)},r.i18n=function(t,e){if(!r.reaper)return"";const s=r.reaper.get("translations");return s?us(s,t,e||""):e||""},r.setOpts=function(e){Object.assign(t,e),t.live&&!r.hasState(Zt)&&(r.setState(re,!0),Ts(r,j)),"disabled"in e&&void 0!==e.disabled&&r.toggleDisable(e.disabled),"muted"in e&&void 0!==e.muted&&r.toggleMute(e.muted),"dvr"in t&&(r.live_state.dvr=r.opt("dvr")),r.setState(Zt,!!t.live),r.setState(ne,"string"==typeof t.poster&&t.poster.length>0),r.setState(fe,!!t.seekable),r.setState(pe,0==t.controls),i.style.backgroundImage=r.hasState(ne)?"url('"+t.poster+"')":"",Ts(r,et,t)},r.renderPlugin=function(t){Ss(r,Z,t).defaultPrevented||r.root.appendChild(t)};const a={offset:0,timer:0};var o,l;l=a,(o=r).on(rs,function(){os(o,l)}),r.enqueueSeek=function(t){if(0!=r.opts.seekable&&!(1==r.opts.disabled&&t>0))return as(r,a,t)},r.deviceId=function(){return function(t){if(vs)return vs;try{const e=t.getItem(ms);if(e)return e;const s=ps();return t.setItem(ms,s),s}catch(t){return vs=ps()}}(r._storage)}}var ks="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function ws(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 Ps(){return"undefined"!=typeof window?window:void 0!==ks?ks:{}}const Ds=["localhost","127.0.0.1","0.0.0.0","s.codepen.io","cdpn.io","try.flowplayer.com"];function Cs(t,e){return!!~Ds.indexOf(t)||t.indexOf(e)===t.length-e.length}Cs.check_whitelist=function(t){return!!~Ds.indexOf(t)};const Os="production";function Ms(t,e){const s={valid_jwt:!1,raw:"",data:{acl:0},exp:0};let i={c:"{}",exp:0};e=e||{};try{i=_e(t),s.valid_jwt=!0}catch(t){}return s.raw=t,s.data=JSON.parse(i.c),s.exp=i.exp,e.require_valid_token&&Ms.validate(s),s}var xs;function Fs(t){return{grant:t,is_granted:e=>(t&e)===e}}Ms.validate=function(t){if("string"==typeof t&&(t=Ms(t)),!t||!t.raw){if(Cs.check_whitelist(window.location.hostname)||"dev"===Os.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=Cs.bind(null,e);if("dev"!==Os.toString()&&t.data.domain&&t.data.domain.length&&!t.data.domain.some(s))throw new Error("Domain not allowed");if("dev"!==Os.toString()&&1e3*t.exp-Date.now()<0)throw new Error("Expired token");return!0},Ms.id=function(t){if(t)return"string"==typeof t&&(t=Ms(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"}(xs||(xs={})),Fs.of=Fs,Fs.from_token=function(t){const e=Ms(t,{require_valid_token:!0});return Fs.of(e.data.acl)},Fs.permissions=xs;const Ns=["Expired token","No token provided in configuration","Invalid token provided","Domain not allowed"];function Us({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 i=!!(r=s.details)&&Ns.some(t=>r.includes(t));var r;const n=document.createElement("h2");n.textContent=i?"No Valid Token":"Playback Error";const a=document.createElement("p");a.textContent="Are you the site owner?";const o=document.createElement("a");o.classList.add("troubleshoot"),o.target="_blank",i?(o.href="https://form.typeform.com/to/YKJpmJSy",o.textContent="Get Trial Token (Beta)"):(o.href="https://docs.flowplayer.com/troubleshooting/player#"+s.reason,o.textContent="Troubleshoot?");const l=document.createElement("img");l.src="https://flowplayer.com/user/pages/images/logo-white.png",l.alt="Flowplayer Logo",t.append(n,a,o,l)}function Bs(t){return e=>{setTimeout(function(){if(!e.defaultPrevented&&!e.prevented)return t(e)},0)}}const $s="is-casting";function Gs(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 Hs(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 Ks(t,e){t.style.width="0",e.style.display="none"}function Vs(t,e,s){isNaN(t)||isNaN(e.duration)||(Gs(s,t),s.textContent=cs(t/100*e.duration))}function js(t,e){const s=t.seekable;if("object"!=typeof t.opts||0==s.length)return{head:0,tail:0};const i=Ys(t),r=e||t.live_state.dvr_window;return{head:i,tail:"number"!=typeof r||i-r<0?s.start(0):i-r}}function qs(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:js(t).head}function Ys(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 zs(t){const e=t.currentTime,s=js(t);return{progress:Math.min(100,Math.max(0,(e-s.tail)/(s.head-s.tail)*100)),is_live:e-s.head>=-10}}function Qs(t,e,s){if(!e.seekable||0==e.seekable.length)return;Gs(s,t);const i=js(e),r=(100-Math.max(0,Math.min(t,100)))/100*(i.head-i.tail);s.innerText="-"+cs(r)}function Xs(t){t.currentTime=js(t).tail}function Zs(t){try{t.dvr_offset=0,t.currentTime=Ys(t)}catch(t){console.warn("failed to seek to now: %j",t)}}function Js(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=js(t);return s.tail+e*(s.head-s.tail)}(e,t)}function ti(t,e){t.style.width="0",e.style.display="none"}function ei(t,e){const s=e.clientWidth;e.classList.toggle(zt,s<600),e.classList.toggle(Qt,s<400)}function si(t,e){if(!t.hasState(Zt)||![void 0,0,-1].includes(e)||!t.seekable.length||t.hasState("has-casted"))return t.setState(qt,!1);t.once(D,()=>t.setState(qt,!1)),0===e?Xs(t):Zs(t)}const ii=[0].concat(Array.from({length:100}).map((t,e)=>(e+1)/100));function ri(){return e.find(t=>t.hasState($s))}const ni=.5625;function ai(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}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(R,this.render),null===(e=this.player)||void 0===e||e.once(P,this.wireUp)}cleanUp(){var t,e,s,i;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(R,this.render),null===(i=this.player)||void 0===i||i.off(P,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 i=(null===(s=this.root)||void 0===s?void 0:s.querySelector(".fp-ui"))||this.root;if(!i)return;const r=this._logo=document.createElement("a");r.href="https://developer.wowza.com/docs/wowza-flowplayer",r.target="_blank",r.className="fp-explorer-logo",i.appendChild(r)}}ExplorerPlan.pluginName="explorer-plan";const oi="flowplayer/"+R;function li(t,e){const s=[];t.addEventListener("contextmenu",i=>{const r=i.timeStamp;for(s.push(r);s.length>3;)s.shift();s.length>=3&&s.every(t=>t-r<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 i=document.createElement("div");i.classList.add("debug-info");const r=di("flowplayer.version","3.43.0-rc.1");i.append(r);const n=null===(s=null==e?void 0:e.hls)||void 0===s?void 0:s.constructor;if(n&&n.version){const t=di("hls.version",n.version);i.append(t)}t.appendChild(i)}(t,e))})}const di=(t,e)=>{const s=document.createElement("div");s.classList.add("row",t);const i=document.createElement("span");i.classList.add("attr"),i.textContent=t;const r=document.createElement("span");return r.textContent=e,r.classList.add("value"),s.append(i,r),s};function ci(t,e){const s=function(){try{return localStorage.getItem("flowplayer/debug")}catch(t){return""}}(),i=(i,...r)=>{try{const n=(null==e?void 0:e.debug)||s;n&&t.match(n)&&console.log(`flowplayer/${t} -- ${i}`,...r)}catch(t){console.warn(t)}};return i.log=i,i}const hi="on",ui="without_recovery",fi="off";class FlowplayerError extends Error{static getErrorKey(t){return t in Ce?Ce[t]:Ce["00-00"]}constructor(t,e,s={}){super(t),this.message=t,this.flowplayerErrorCode=e,this.config=s,this.id=ps(),this.isFatal=!!s.isFatal,this.errorKey=FlowplayerError.getErrorKey(this.flowplayerErrorCode)||"unknown"}toJSON(){return{message:this.message,flowplayer_error_code:this.flowplayerErrorCode,id:this.id,root_error_id:this.config.rootErrorId,resource:this.config.resource,is_fatal:this.isFatal,is_retry:!!this.config.isRetry}}}const gi=ci("core/retry");function pi(t,e){const s={pending:void 0,count:0};t.on(at,i=>{var n,a,o,l,d;const c=null===(n=i.detail)||void 0===n?void 0:n.error;c.config.isRetry=!!s.count,void 0===s.pending&&(null===(o=null===(a=c.config)||void 0===a?void 0:a.retryOpts)||void 0===o?void 0:o.retry)!==fi&&(e.retry||(null===(d=null===(l=c.config)||void 0===l?void 0:l.retryOpts)||void 0===d?void 0:d.retry))&&(++s.count,s.pending=function(t,e,s){var i,n;return setTimeout(()=>{var i;t.hasState(me)||(e.pending=void 0,(null===(i=s.config.retryOpts)||void 0===i?void 0:i.retry)!==ui&&t.emit(q),t.emit(r,{error:s}),gi("%s try",e.count))},null!==(n=null===(i=s.config.retryOpts)||void 0===i?void 0:i.retryTimeout)&&void 0!==n?n:3e3*e.count)}(t,s,c))}),t.on(R,()=>{s.count=0}),t.on([F,q],t=>{t.type===F&&(s.count=0),clearTimeout(s.pending),s.pending=void 0}),t.on(r,Bs(()=>{t.load()}))}const mi=[nt,n,F];function vi(t){const e=document.createElement("a");return e.href=t,e}function yi(t){try{return!!new URL(t)}catch(t){return!1}}function Ei(){try{return window.location.hostname!==window.parent.location.hostname?vi(document.referrer).hostname:document.location.hostname}catch(t){return window.location.hostname}}const Ti=navigator;function Si(t){var e,s;const i=null===(e=t.hls)||void 0===e?void 0:e.bandwidthEstimate;return i?1e-6*i:(null===(s=Ti.connection)||void 0===s?void 0:s.downlink)||-1}function Ai(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 _i=t=>{switch(t){case!0:return we.ON;case!1:return we.OFF;default:return t}};function bi(){try{const t=window.location!==window.parent.location?document.referrer:document.location.href;return"string"==typeof t&&t.slice(0,200)}catch(t){return!1}}const Li=[],Ri="https://ihi.flowplayer.com/v1/health/events";function Ii(t){if(t.suspended)return;const e=Li.slice(0);Li.length=0,0!=e.length&&(t.logger.log(`:dispatch events={${e.length}}`),Ai(function(){try{return"undefined"==typeof window?Ri:window.__FLOWPLAYER_INSIGHTS_URL?window.__FLOWPLAYER_INSIGHTS_URL:Ri}catch(t){return Ri}}(),e))}async function ki(t,e,s){const i=await Pi();Li.push(Object.assign(e,i)),t.logger.log(":enqueue",e.event,e),Li.length<10&&!s||Ii(t)}const wi=()=>{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}},Pi=async()=>({client_time:Date.now()}),Di=(t,e)=>Object.assign(t,{detail:e}),Ci=(t,{event:e,media_session_id:s,session_id:i,play_range_id:r})=>({event:e,media_session_id:s,session_id:i,play_range_id:r,device_id:t.deviceId(),version:"3.43.0-rc.1",commit:"4146cbb86e09f6dc9d30a6b1e2f7edaebd896e6d",ima_sdk_version:wi(),preload:t.opt("preload"),autoplay:_i(t.opt("autoplay")),live:t.opt("live"),dvr:!!t.live_state.dvr,source:t.original_src,downlink_mbs:Si(t),page_url:bi(),player_id:t.opt("metadata.player_id"),media_id:t.opt("metadata.media_id")||t.opt("metadata.stream_target_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")}),Oi=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"]});const Mi=(t,e)=>{let s=null;return(...i)=>{null!==s&&(clearTimeout(s),s=null),s=setTimeout(()=>e(...i),t)}};const xi="ad-initialized",Fi="ad-playback-error",Ni="ad-teardown",Ui="ad-videotag-attached",Bi="ad-request-error",$i="ad-requested",Gi="ad-request-completed",Hi="ad-pause-content",Ki="ad-started",Vi="ad-completed",ji="ad-paused",qi="ad-resumed",Wi="ad-progress",Yi="ad-skipped",zi="ad-muted",Qi="ad-volume-changed",Xi="ad-timeout",Zi="ad-break-completed",Ji="ad-postroll-finished",tr="ad-preroll-finished",er="vpaid-init",sr="ad-ima-adapter-init",ir="ad-ima-before-ads-request",rr="ad-ima-rendering-settings",nr="ad-adapter-init-failed",ar="ad-play-requested",or="reload-ad-requested",lr="ad-error",dr="request/ad/pause",cr="request/ad/play",hr="request/ad/muteunmute",ur="ad/show-first-frame",fr="ad/resize",gr="ad/set-ui-flags",pr="ad/pbjs";var mr,vr=Object.freeze({__proto__:null,AD_INIT:xi,AD_PLAYBACK_ERROR:Fi,AD_TEARDOWN:Ni,AD_VIDEOTAG_ATTACHED:Ui,AD_BLOCKED:"ad-blocked",AD_REQUEST_ERROR:Bi,AD_REQUESTED:$i,AD_REQUEST_COMPLETED:Gi,AD_PAUSE_CONTENT:Hi,AD_STARTED:Ki,AD_COMPLETED:Vi,AD_PAUSED:ji,AD_RESUMED:qi,AD_WAITING:"ad-waiting",AD_PROGRESS:Wi,AD_SKIPPED:Yi,AD_MUTED:zi,AD_VOLUME_CHANGED:Qi,AD_FULLSCREEN:"ad-fullscreen",AD_TIMEOUT:Xi,AD_BREAK_COMPLETED:Zi,AD_POSTROLL_FINISHED:Ji,AD_PREROLL_FINSIHED:tr,AD_MIDROLL_FINISHED:"ad-midroll-finished",VPAID_INIT:er,IMA_ADAPTER_INIT:sr,IMA_BEFORE_ADS_REQUEST:ir,IMA_ADS_RENDERING_SETTINGS:rr,ADAPTER_INIT_FAILED:nr,AD_PLAY_REQUESTED:ar,RELOAD_AD_REQUESTED:or,AD_ERROR:lr,REQUEST_AD_PAUSE:dr,REQUEST_AD_PLAY:cr,REQUEST_AD_MUTE_UNMUTE:hr,AD_SHOW_FIRST_FRAME:ur,AD_RESIZE:fr,AD_SET_UI_FLAGS:gr,PBJS_AVAILABLE:pr});!function(t){t[t.Starting=0]="Starting",t[t.ConfigFinalized=1]="ConfigFinalized",t[t.TimerStartedWithAutoplay=2]="TimerStartedWithAutoplay",t[t.TimerStartedWithUserGesture=3]="TimerStartedWithUserGesture",t[t.MetricReported=4]="MetricReported"}(mr||(mr={}));const yr=[a,g];class TimeToFirstFrame{constructor(t=mr.Starting,e=!1){this.state=t,this.loadedAd=e}reset(){this.state=mr.Starting,this.loadedAd=!1,this.start=void 0,this.end=void 0,this.adDetails=void 0}adInfo(){const{ad_tag_id:t,vast_ad_id:e}=this.adDetails||{};return{ad_tag_id:t,vast_ad_id:e}}toJSON(){return Object.assign({ad_was_requested:this.loadedAd,ms_to_first_frame:Math.round(this.end&&this.start?this.end-this.start:-1)},this.adInfo())}startTimer(t){this.state==mr.ConfigFinalized&&(this.state=t,this.start=performance.now())}hasStarted(){return[mr.TimerStartedWithAutoplay,mr.TimerStartedWithUserGesture].includes(this.state)}stopTimer(t){this.hasStarted()&&(this.end||(this.end=performance.now()),this.state=mr.MetricReported,t())}}function Er(t){return Math.round(1e3*t)/1e3}class EWMA$1{constructor(t){this.tickInterval=t,this.ewma=0,this.startTime=Date.now()}decay(){const t=Date.now()-this.startTime;return Math.pow(2,-t/(4*this.tickInterval))}update(t){const e=this.decay();return this.ewma=e*this.ewma+(1-e)*t,this.ewma}toJSON(){return this.ewma}}const Tr={skipUnreliableSegments:!0};class WatchedState{constructor(t){this.player=t,this.marchingInterval=void 0,this.lastWatchedPoint=void 0,this.watchedSum=0,this.lastReportedSum=0,this.ewmaTickWatched=new EWMA$1(WatchedState.AccuracyMilliseconds)}reset(){this.onNotWatching(),this.watchedSum=0,this.lastReportedSum=0,this.lastWatchedPoint=void 0}onNotWatching(){this.marchingInterval&&(this.updateWatched(),this.marchingInterval=clearInterval(this.marchingInterval))}onWatching(){this.marchingInterval||(this.lastWatchedPoint=this.createWatchedPoint(),this.marchingInterval=setInterval(()=>{this.updateWatched()},WatchedState.AccuracyMilliseconds))}createWatchedPoint(){return{currentTime:this.player.currentTime,paused:this.player.paused}}updateWatched(){const t=this.createWatchedPoint();this.lastWatchedPoint&&this.calculateTimeWatched(this.lastWatchedPoint,t),this.lastWatchedPoint=t}calculateTimeWatched(t,e){var s,i;const r=e.currentTime-t.currentTime,n=this.ewmaTickWatched.update(r);if(!(r<0)&&!(!1!==(null===(i=null===(s=this.player.opts)||void 0===s?void 0:s.health)||void 0===i?void 0:i.skipUnreliableSegments)&&1e3*r>1.3*WatchedState.AccuracyMilliseconds)&&(this.watchedSum+=r,this.watchedSum!=this.lastReportedSum&&(this.watchedSum>this.lastReportedSum+WatchedState.ReportingIntervalSeconds||this.player.ended))){const t=Er(n),e={total_watched_seconds:Er(this.watchedSum),tick_watched_seconds:t,batch_watched_seconds:Er(this.watchedSum-this.lastReportedSum)};this.lastReportedSum=this.watchedSum,this.player.emit(Ye,e)}}}WatchedState.ReportingIntervalSeconds=5,WatchedState.AccuracyMilliseconds=160;const Sr=ps();class Health{constructor(t,e){let s;this.session_id=Sr,this.suspended=!1,this.logger=ci("health",e.opts),this.media_session_id=ps(),this.play_range_id=ps(),this.analyticsLoop=setInterval(()=>Ii(this),2e3),e.on(N,()=>clearInterval(this.analyticsLoop)),e.on(R,()=>{s!==this.media_session_id&&(s=this.media_session_id,this.first_playing_event_timestamp=Date.now()),this.play_range_id=ps()});let i=Date.now()-1e3;e.on(A,t=>{if(s!==this.media_session_id)return;const r=Date.now();if(r<i)return;i=Date.now()+5e3;const n=Ci(e,this.eventInfo(t.type)),a=Di(n,{duration:(o=e.duration,Number.isFinite(o)?o:o===1/0?-1:void 0)});var o;this.first_playing_event_timestamp&&(Object.assign(a,{ms_since_first_playing:r-this.first_playing_event_timestamp}),this.first_playing_event_timestamp=void 0),ki(this,a)});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(()=>Ii(this),2e3)}init(t,e,s){if(bi().toString().startsWith("data:"))return this.suspend();!function(t){let e=null;const s=()=>{e=null};t.on(k,function(e){t.seeking||t.networkState===t.NETWORK_LOADING&&(t.readyState<HTMLMediaElement.HAVE_CURRENT_DATA||t.emit(Ke))}),t.on(Ke,t=>{e=t}),t.on(w,i=>{if(e){const r=i.timeStamp-e.timeStamp;if(s(),r<31)return;if(r>3e5)return;t.emit(Ve,{rebuffer_duration:r/1e3})}}),mi.forEach(e=>t.on(e,s))}(s),function(t){let e;[w,nt].forEach(s=>{t.on(s,s=>{const i=Date.now();switch(s.type){case nt:return e=i;case w:if(e)return t.emit(We,{ms_since_loading_started:i-e}),e=null}})})}(s),function(t){if(void 0===window.performance)return;const e=new TimeToFirstFrame;t.on(F,()=>{if(!t.opt("metadata.media_id"))return e.reset();e.reset(),e.state=mr.ConfigFinalized}),t.on(nt,()=>{(t.root.classList.contains("ad-hide-first-frame")||t.opt("autoplay"))&&e.startTimer(mr.TimerStartedWithAutoplay)}),yr.forEach(s=>{t.on(s,()=>{t.opt("autoplay")||e.startTimer(mr.TimerStartedWithUserGesture)})}),t.on($i,()=>{e.loadedAd=!0}),t.on(A,()=>{if(!(t.readyState<HTMLMediaElement.HAVE_CURRENT_DATA)){if(t.root.classList.contains("ad-hide-first-frame"))return!e.end&&(e.end=performance.now());switch(e.state){case mr.TimerStartedWithAutoplay:case mr.TimerStartedWithUserGesture:return e.stopTimer(()=>t.emit(qe,e.toJSON()))}}}),t.on(Ki,s=>{switch(e.end=void 0,e.adDetails=s.detail,e.state){case mr.TimerStartedWithAutoplay:case mr.TimerStartedWithUserGesture:return e.stopTimer(()=>t.emit(qe,e.toJSON()))}})}(s),function(t){const e=new WatchedState(t);t.on(nt,()=>e.reset()),t.on(R,()=>e.onWatching()),t.on(Ve,()=>!t.paused&&e.onWatching()),t.on(Ke,()=>e.onNotWatching()),t.on(L,()=>e.onNotWatching()),t.on(C,()=>{t.currentTime>1&&e.updateWatched(),e.onNotWatching()}),t.on(D,()=>{t.paused||e.onWatching()}),t.on(P,()=>e.updateWatched()),t.on("visibilitychange",()=>e.updateWatched())}(s),s.on(je,t=>{ki(this,Ci(s,this.eventInfo(t.type)),!0)}),s.on(He,({detail:t})=>{const e=Ci(s,this.eventInfo(t.event));Object.assign(e,t.detail||{}),ki(this,e)}),s.on(ze,t=>{if(e=t.detail.sample_rate,!Object.values(Ze).includes(e))return console.debug(`sample_rate=${t.detail.sample_rate} is invalid`);var e,i;if(!(0!==(i=t.detail).sample_rate&&Math.random()<=i.sample_rate))return;const r=Ci(s,this.eventInfo(t.type));ki(this,Di(r,t.detail))}),s.on(F,()=>{s.opt("metadata.media_id")&&s.emit(Qe)}),[_,E,T,S,k,Ke].forEach(t=>{s.on(t,t=>{ki(this,Ci(s,this.eventInfo(t.type)))})}),[Ve,qe,We,Ye].forEach(t=>{s.on(t,t=>{const e=Ci(s,this.eventInfo(t.type));ki(this,Object.assign(e,t.detail))})}),[R,L,C,D,P,v,y,w,nt].forEach(t=>{s.on(t,t=>{ki(this,Ci(s,this.eventInfo(t.type)))})}),s.on(b,Mi(800,t=>{const e=Ci(s,this.eventInfo(t.type));ki(this,Di(e,{volume:parseFloat(s.volume.toFixed(2)),muted:s.muted}))})),s.on(m,Mi(800,t=>{const i=Ci(s,this.eventInfo(t.type));ki(this,Di(i,{height:e.clientHeight,width:e.clientWidth}))})),s.on("hls/failover",t=>{const e=Ci(s,this.eventInfo(t.type)),i=t.detail,{reason:r,from:n}=i;ki(this,Di(e,{reason:r,from:n}))}),s.on(B,({type:t,detail:e})=>{if("hls"===e.plugin)return function(t,e,s,i){const r=Ci(e,t.eventInfo(s)),n=Object.assign({before:Oi(i.before),after:Oi(i.after),automatic:i.automatic,downscale:i.downscale},i.before?{}:{start_quality:e.opts.start_quality});ki(t,Object.assign(Object.assign({},r),{state:n}))}(this,s,t,e)}),s.on(at,t=>{const e=Ci(s,this.eventInfo(t.type)),i=t.detail.error;if(!i)return ki(this,e,!0);return ki(this,Di(e,i.toJSON()),!0)}),s.on(F,t=>{var e;const i=null===(e=t.detail)||void 0===e?void 0:e.src;if("string"!=typeof i)return;if(!yi(s.original_src))return;if(!yi(i))return;if(i==s.original_src)return;this.media_session_id=ps();ki(this,Ci(s,this.eventInfo(t.type))),Ii(this),s.setOpts({health:Object.assign(Object.assign({},s.opts.health),Tr)})}),s.on("visibilitychange",t=>{ki(this,Ci(s,this.eventInfo(t.type))),Ii(this)})}}function Ar(t,e){return function(t){return t.extensions.reduce((t,e)=>t.find(t=>t.pluginName===e.pluginName)?(console.warn("flowplayer: duplicate plugin %s detected, plugin names should be unique",e.name),t):(t.push(e),t),[])}(t).map(s=>new s(t,e))}function _r(t,e={}){var s,i,r,n,a,o;switch(t.code){case MediaError.MEDIA_ERR_ABORTED:return new FlowplayerError(null!==(s=t.message)&&void 0!==s?s:"The playback was aborted, typically by the user.",De.PlaybackInternalAborted,Object.assign({isFatal:!1,retryOpts:{retry:fi}},e));case MediaError.MEDIA_ERR_NETWORK:return new FlowplayerError(null!==(i=t.message)&&void 0!==i?i:"A network error prevented media from being downloaded.",De.NetworkHttpRequestFailed,Object.assign({isFatal:!0},e));case MediaError.MEDIA_ERR_DECODE:return new FlowplayerError(null!==(r=t.message)&&void 0!==r?r:"An error occurred while decoding the media.",De.PlaybackVideoDecodeError,Object.assign({isFatal:!0},e));case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:return new FlowplayerError(null!==(n=t.message)&&void 0!==n?n:"The media could not be loaded because the format is not supported.",De.MediaUnsupportedVideoFormat,Object.assign({isFatal:!0},e));case 5:return new FlowplayerError(null!==(a=t.message)&&void 0!==a?a:"Encrypted content could not be played due to missing keys or unsupported protection scheme.",De.ContentProtectionKeySystemNoKeys,Object.assign({isFatal:!0},e));default:return new FlowplayerError(null!==(o=t.message)&&void 0!==o?o:"An unknown playback error occurred.",De.PlaybackUnknown,Object.assign({isFatal:!0},e))}}Health.pluginName="health",Health.events=Xe,Health._UNLOAD_SUBSCRIBED=!1;const br=function(){const t=Ps(),e=t.flowplayer?t.flowplayer:{extensions:[]};return Array.isArray(e.extensions)||(e.extensions=[]),e}();function Lr(s,r){if("function"==typeof s)return t.push(...[...arguments].filter(t=>"function"==typeof t)),Lr;"string"==typeof r&&(r={src:r}),r||(r={}),r.token||"string"!=typeof window.__FLOWPLAYER_TOKEN||(r.token=window.__FLOWPLAYER_TOKEN);const a="string"==typeof s?document.querySelector(s):s;if(!a)return console.error(new Error("Flowplayer: '"+s.toString()+"' not found"));const o=a.querySelector("video.fp-engine");if(o)return o;const l=function(t){try{return Ms.validate(t),{success:!0,message:""}}catch(t){return{success:!1,message:t.message}}}(r.token);if(!l.success)return Us({root:a,data:{reason:"token",details:l.message}});const d=new Map,c=function(t,e){const s=e.querySelector("video"),i=s||(t._video_element_callback?t._video_element_callback(t):document.createElement("video"));return i.classList.add("fp-engine"),i.playsInline=!0,s||e.append(i),i}(r,a);var h;c.reaper=d,c._customElements=be,Object.defineProperty(c,"token",{value:"string"==typeof r.token?Ms.id(r.token):"",writable:!1}),c.addEventListener(N,()=>{d.clear(),c.reaper=0,delete c.root}),c.root=a,r.token&&Fs.from_token(r.token).is_granted(Fs.permissions.DEVELOPER_PLAN)&&Lr.extensions.push(ExplorerPlan),!~e.indexOf(c)&&e.push(c),Is(r,a,c),c.setAttrs(r),c.plugins=Ar(Lr,c),function(t,e,s){let i=!0;e.classList.add("flowplayer"),ei(0,e),bs(s,_,()=>{void 0!==t.start_quality&&Je(s,{feature_name:"start-quality",behavior:String(t.start_quality),sample_rate:Ze.High})}),As(s,_,()=>{if(!s.hasState(jt)&&!s.hasState(Vt)&&t.is_native&&"none"!==t.preload)return"metadata"===t.preload?(s.setState(jt,!0),s.emit(nt)):void Me(s)}),As(s,E,()=>{t.is_native&&"metadata"===t.preload&&s.paused&&s.emit(w)}),As(s,[_,m],function(){ei(0,e)}),As(s,st,function(){Object.entries(s.playerState).forEach(function([t,s]){e.classList.toggle(t,s)})}),As(s,A,function(){s.setState(te,!s.hasState($s)&&!s.hasState(qt)&&s.readyState<3)}),As(s,P,function(e){const i=s.original_src;Bs(()=>{if(i===s.original_src){if(s.setState(Xt,!0),bs(s,A,function(){s.setState(Xt,!1),i===s.original_src&&s.setState(qt,!t.loop&&!!t.rewind&&s.paused)}),t.loop)return s.togglePlay(!0);t.rewind&&(s.currentTime=0)}})(e)}),As(s,[C,D],function(t){s.setState(Wt,t.type==C)}),As(s,Q,function(t){setTimeout(()=>{t.defaultPrevented||(s.currentTime=t.detail.currentTime)},0)}),As(s,P,function(){s.setState($t,!1),i=!0}),As(s,S,()=>{if(!s.opts.live||!s.opts.is_native)return;const t=s.seekable;0!=t.length&&s.emit("dvr/window",t.end(t.length-1)-t.start(0))}),As(s,T,function(){s.setState(Vt,!0),s.setState(jt,!1)}),As(s,I,()=>{s.setState(ae,!0)}),As(s,[k,w,_],function(e){if(!s.hasState(Wt)&&(e.type!=w||t.autoplay||s.setState(te,!1),e.type!=_||"none"!=s.opt("preload")||t.autoplay)){if(e.type==_&&t.autoplay)return bs(s,R,function(){s.setState(te,!1)});e.type!=k||s.hasState(Vt)||s.setState(jt,!0),s.setState(Xt,!1),s.setState(te,e.type==k)}}),As(s,[R,L],function(e){setTimeout(()=>{const t=new CustomEvent("flowplayer/"+e.type,{detail:s});document.dispatchEvent(t)},0);const r=e.type==R,n=s.currentTime==s.duration,a=r&&i&&t.autoplay||s.hasState(te);if(r&&(s.started=!0,i=!1),s.setState(te,!1).setState(ae,!1),!r&&s.setState(oe,!1),n)return;const o=r?$t:Ht,l=r?Ht:$t;s.transitionState(o,l,a?0:300),!s.hasState(qt)||s.root.classList.contains("ad-hide-first-frame")||s.root.classList.contains("preroll-ios")||si(s,t.start_time)})}(r,a,c),function(t,e,s){if(!window.IntersectionObserver)return;const i={should_resume:!!t.autoplay,locked:!1};As(s,I,function(){i.locked||(i.should_resume=!0)});const r=()=>{if(!t.autoplay)return;if(s.hasState(ge)&&i.should_resume)return s.togglePlay(!0);const e=s.currentSrc;t.autopause||s.hasState(ge)||!i.should_resume||bs(s,M,()=>{t.autoplay&&i.should_resume&&e===s.currentSrc&&s.togglePlay(!0)})},n=()=>{if(!t.autoplay)return;if(!t.is_native)return;if("auto"===t.preload)return;if(s.hasState(ge))return Me(s);const e=s.currentSrc;bs(s,M,()=>{e!==s.currentSrc||s.readyState>1||!s.paused||Me(s)})};As(s,F,function(){i.should_resume=!!t.autoplay,s.off(_,n),s.once(_,n),s.off(w,r),s.once(w,r)}),As(s,L,function(){i.locked||(i.should_resume=!1)});const a=new IntersectionObserver(t=>{t.forEach(t=>{setTimeout(()=>{const e=t.intersectionRatio,i=s.hasState(ge);if(s.setState(ge,e>=.2),s.emit(X,{ratio:e}),i===s.hasState(ge))return;const r=s.hasState(ge)?M:x;s.emit(r)},0)})},{threshold:ii});a.observe(e),s.on(N,()=>a.disconnect()),As(s,M,function(){!i.should_resume||!t.autopause||ri()||s.opts.autoplay&&!s.readyState||s.togglePlay(!0)}),As(s,x,function(){if(!t.autopause||ri())return;const e=!s.paused;i.locked=!0,s.pause(),setTimeout(function(){i.should_resume=e,i.locked=!1},0)})}(r,a,c),function(t,e){if(!window.ResizeObserver)return;const s=new ResizeObserver(t=>{const s=t[t.length-1];e.emit(m,s)});s.observe(t),e.on(N,()=>s.disconnect())}(a,c),function(t,e,s){const i=!!t.ratio,r=document.createElement("div");r.classList.add("fp-ratio"),e.append(r);let n=ai(t.ratio||ni);r.style.paddingTop=100*n+"%";const a=[T,E];s.on(a,function(){if(i)return;const t=s.videoHeight&&s.videoWidth&&s.videoHeight/s.videoWidth;t&&s.setOpts({ratio:t})}),s.on(et,function(){const e=s.videoHeight&&s.videoWidth&&s.videoHeight/s.videoWidth,i=ai((null==t?void 0:t.ratio)||e||ni);n!==i&&(n=i,r.style.paddingTop=100*i+"%")})}(r,a,c),function(t){const e=e=>{e.detail!==t&&!1===t.opt("multiplay")&&t.togglePlay(!1)};t.on(N,()=>document.removeEventListener(oi,e)),document.addEventListener(oi,e)}(c),li(a,c),pi(c,r),(h=c).on(n,Bs(t=>{const e=t instanceof MediaError?t:h.error;e&&h.emit(at,{error:_r(e,{resource:h.original_src})})})),c.plugins.forEach(t=>{try{t.init(r,a,c)}catch(e){console.log("Error(plugin/%s)",t.constructor.name,e)}}),c.setOpts(r),c.opts=r,r.src&&c.setSrc(r.src);const u=c.readyState;return u>0&&c.currentSrc&&c.emit(E),u>2&&c.currentSrc&&c.emit(w),c.emit(i),c.on(tt,function(t){Us({root:a,video:c,data:t.data||{}})}),setTimeout(Ts,0,document,"flowplayer:player:created",c),c}Object.assign(Lr,br),function(i){Array.isArray(i.extensions)&&i.extensions.forEach(e=>t.push(e)),i.customElements=be,i.defaultElements=Bt,i.version="3.43.0-rc.1",i.commit="4146cbb86e09f6dc9d30a6b1e2f7edaebd896e6d",i.instances=e,i.extensions=t,i.support=s,i.events=ot,i.states=ye,i.errors=De,i.jwt=_e,i.autoplay=we,i.quality=ke}(Lr),"object"==typeof document&&setTimeout(Ts,0,document,"flowplayer:umd",Lr),Lr.extensions.unshift.apply(Lr.extensions,[Health]),"undefined"!=typeof window&&"function"==typeof window.matchMedia&&[H,K].forEach(function(t){window.matchMedia("(orientation: "+t+")").addListener(function(s){e.length&&e.forEach(function(e){s.matches&&e.emit(t)})})});function Rr(t,e,s){"undefined"!=typeof window&&"ontouchstart"in window&&s.setState(he,!0),s.setState("is-accessibility",!1)}const Ir=[_,q];function kr(t,e){const s=Le(e,Ut);t.append(s),e.on(at,i=>{if(!document.body.contains(t))return;const r=i.detail.error;!1!==r.config.showErrorUI&&(r.isFatal||r.config.showErrorUI)&&(e.setState(Jt,!0),console.warn(r),Ts(s,at,{error:r}),Ts(s,n,{error:r}))}),Ir.forEach(t=>e.on(t,()=>{!function(t){if(!t.hasState(Jt))return;t.setState(te,!0),t.setState(Jt,!1)}(e)}))}const wr=16384;var Pr=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:wr,LOGO_ON_BOTTOM:32768});function Dr(t,e){const s=t._customElements.get(e);return s&&t.root.querySelector(s)||void 0}function Cr(...t){const e=document.createElement("div");return 0==t.length||e.classList.add(...t),e}function Or(t,e,s){let i=()=>document.fullscreenElement,r="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),r="webkit"+r,i=()=>e.webkitCurrentFullScreenElement}const n=()=>s.getFullsceenTarget?s.getFullsceenTarget():e;s.toggleFullScreen=function(t,e){if(s.ios_fullscreen_disabled)return;if("boolean"!=typeof t&&(t=!s.hasState(Gt)),Mr(s)&&(t?function(t,e){t.getAttribute("playsinline")&&t.removeAttribute("playsinline");t.getAttribute("webkit-playsinline")&&t.removeAttribute("webkit-playsinline");e||t.webkitEnterFullScreen()}(s,e):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(de)||t.setState(de,!0)}(s,e)),!document.fullscreenEnabled)return;const r=n();if(t)return r.requestFullscreen();i()===r&&document.exitFullscreen()},Mr(s)&&(s.ios_fullscreen_disabled=!0,s.once(it,function(){s.ios_fullscreen_disabled=!1}),s.on(["webkitendfullscreen","webkitbeginfullscreen"],t=>{const e="webkitbeginfullscreen"===t.type;s.setState(Gt,e).emit(e?v:y).toggleFullScreen(e,!0)})),setTimeout(()=>{const t=n();t.addEventListener(r,function(){const e=i(),r=e===t||e==s;s.emit(r?v:y),s.setState(Gt,r)})},0),!1!==t.doubleclick&&e.addEventListener(o,function(t){var e;t.target&&(null===(e=t.target)||void 0===e?void 0:e.classList.contains("fp-ui"))&&s.toggleFullScreen()})}function Mr(t){return!document.fullscreenEnabled&&"function"==typeof t.webkitEnterFullScreen&&"function"==typeof t.webkitExitFullScreen}const xr="use-play-",Fr="mute";function Nr(t,e,s){if(!s.reaper)return;const i=document.createDocumentFragment(),r=Le(s,lt),n=Le(s,dt);e.append(n),i.append(r),s.reaper.set("ui",r),~e.className.indexOf(xr)||e.classList.add(xr+1),function(t,e,s){const i=Cr("fp-footer");e.append(i),s.on(et,function(t){var e,s;const r=null===(e=t.data)||void 0===e?void 0:e.description,n=null===(s=t.data)||void 0===s?void 0:s.title;if(i.innerHTML="","string"==typeof n){const t=Cr("fp-title");t.innerText=n,i.append(t)}if("string"==typeof r){const t=r.split(" "),e=Cr("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,s),kr(r,s),e.appendChild(i);let a=null;[h,f,l].forEach(t=>{e.addEventListener(t,function(t){if(!s.hasState(he)||t.type===f){if(clearTimeout(a),t.type===l)return s.setState(ce,!1);s.setState(ce,!0),a=setTimeout(function(){s.setState("is-hovered",!1)},2e3)}})}),Or(t,e,s),s.on(b,function(){const t=0==s.volume||s.muted;s.muted=t,s.setState(Kt,t),s._storage.setItem(Fr,t.toString())}),"true"==s._storage.getItem(Fr)&&(s.muted=!0,s.setState(Kt,s.muted));const o=s._storage.getItem("volume");o&&!isNaN(Number(o))&&(s.volume=Number(o)),s.emit(b),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 i=js(t,s);return i.head-i.tail>=e}(s,t.seconds_to_dvr||60,e.detail),s.live_state.dvr_window=e.detail)}),s.on(j,()=>{const t=setInterval(()=>{if(!s.opts.live||0==s.reaper)return clearInterval(t);if(0==s.seekable.length||s.hasState(Jt))return;const e=zs(s);s.hasState(ie)==e.is_live&&s.setState(ie,!e.is_live),s.live_state.dvr&&s.emit(V,e.progress)},200)}),s.on(E,function(){s.setOpts({live:qs(s)})}),s.on(O,function(t){const e=qs(s),i=e?Ws(s):t.data||s.duration;isNaN(i)||s.setOpts({live:e,duration:i})}),s.on(["playlist/advance",F],e=>{if(s.setState(ee,!!t.autoplay),s.root.classList.contains("is-livecountdown"))return Ur(s,t);(s.currentSrc||s.srcObject)&&(e.type===F&&["is-playlist",ve].some(t=>s.root.classList.contains(t))||Ur(s,t))}),s.on(et,function(s){var i,r;t.seekable=void 0===(null===(i=null==s?void 0:s.data)||void 0===i?void 0:i.seekable)||s.data.seekable;const n=null===(r=s.data)||void 0===r?void 0:r.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",(wr&n)>0)})}function Ur(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,"metadata"in e&&delete e.metadata}function Br(t,e,s){if(Fs.from_token(t.token||"").is_granted(Fs.permissions.NO_METERING))return;Ms.id(t.token||"")&&s.once(R,async()=>await $r(s,t.token||""))}async function $r(t,e){const s=Ms.id(e||"");t.once(F,()=>{t.once(R,()=>$r(t,e))});if(401==(await fetch("https://pmi.flowplayer.com/in",{method:"POST",body:JSON.stringify({token_id:s,factor:1,rnd:Math.random().toString(36).substring(2)})})).status)return t.emit(tt,{reason:"token",details:"The token online validation failed"})}class I18n{init(t,e,s){var i;s.reaper&&s.reaper.set("translations",fs(I18n,t,"en")),(i=s).once(Qe,()=>{const t=I18n.languagesLoaded().filter(t=>"en"!==t);t.length>0&&t.forEach(t=>{Je(i,{feature_name:"translations",behavior:`loaded-lang-${t}`,sample_rate:Ze.Low})})}),i.on(Qe,()=>{i.opts.lang&&Je(i,{feature_name:"translations",behavior:`used-lang-${i.opts.lang}`,sample_rate:Ze.Medium})})}static languagesLoaded(){return Object.keys(I18n).filter(t=>!I18n._nonLanguageFields.includes(t)).concat(I18n.en?["en"]:[])}}I18n.pluginName="i18n",I18n.en={ads:{ad:"Ad",ads:"Ads",advertisement:"Advertisement",indicator:"Ads",adchoices:"AdChoices"},audio:{button_txt:"Audio",menu_title:"Audio"},cc:{button:"CC",menu_title:"Subtitles",options:"Options",tracks:"Tracks",reset:"Reset",colors:{Black:"Black",Blue:"Blue",Cyan:"Cyan",Green:"Green",Magenta:"Magenta",Red:"Red",White:"White",Yellow:"Yellow"},edgeStyle:{None:"None","Drop shadow":"Drop shadow",Raised:"Raised",Depressed:"Depressed",Outline:"Outline"},fontFamily:{"Monospaced Serif":"Monospaced Serif","Proportional Serif":"Proportional Serif","Monospaced Sans-Serif":"Monospaced Sans-Serif","Proportional Sans-Serif":"Proportional Sans-Serif",Casual:"Casual",Cursive:"Cursive"},properties:{fontFamily:"Font family",fontSize:"Font size",fontColor:"Font color",fontOpacity:"Font opacity",backgroundColor:"Background color",backgroundOpacity:"Background opacity",characterEdgeStyle:"Character edge style"}},chromecast:{start:"start casting",stop:"stop casting"},core:{exit_fullscreen:"Exit fullscreen",fullscreen:"Fullscreen",mute:"Mute",muted:"Muted",pause:"Pause",play:"Play",seconds:"Seconds",timeline_aria_label:"Seek slider",unmute:"Unmute",volume:"Volume",options:"Options",close:"Close","skip-next":"Next","skip-prev":"Previous"},ovp:{starting_in:"Countdown"},playlist:{cancel:"Cancel",up_next:"Up next",autoplay:"Autoplay",now_playing:"Now playing",turn_off_autoplay:"Turn off autoplay",playlist:"Playlist"},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"},vtsel:{button_txt:"Video",menu_title:"Video Track"},spins:{more:"More",less:"Less"}},I18n._nonLanguageFields=[],I18n._nonLanguageFields=Object.keys(I18n);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(et,t=>{var s;const i=e.logo,r=(null===(s=null==t?void 0:t.data)||void 0===s?void 0:s.logo)||"";i!=r&&(e.logo=r,this.set_logo(r,t.detail.logo_alt_text,t.detail.logo_href))})}set_logo(t,e,s){this.innerHTML="";const i=document.createElement("img");if(!t)return;if(i.src=t,i.alt=e||"Logo",!s)return this.append(i);const r=document.createElement("a");r.href=s,r.append(i),this.append(r)}}class FlowplayerHeaderDuration extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-duration"),t.on(et,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)?cs(s):""})}}const Gr={name:"fp-fullscreen",translation_key:"core.fullscreen"},Hr={name:"fp-fullscreen-exit",translation_key:"core.exit_fullscreen"},Kr={name:"fp-play",translation_key:"core.play"},Vr={name:"fp-pause",translation_key:"core.pause"},jr={translation_key:"core.mute",name:"fp-volume-mute-unmute"},qr={translation_key:"core.play",name:"fp-small-play"},Wr={translation_key:"core.pause",name:"fp-small-pause"},Yr={name:"fp-fast-forward"},zr={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")}}function Qr(){}const Xr="fp-menu-container",Zr="details[open]."+Xr;document.addEventListener(a,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(Zr);s&&(s.open=!1,null===(e=s.querySelector("summary"))||void 0===e||e.removeAttribute("aria-expanded"),t.root.classList.toggle(le,!1))}),this.active_menu=void 0)});const Jr={passive:!0};var tn;function en(t,e){let s=0,i=-1,r=-1;const n=Math.random().toString(36).replace(/[^a-z]+/g,"").substr(0,5),a=t.classList;t.id=n,a.remove(tn.GRABBING),a.remove(tn.TOUCHING);const o=e.onseek||Qr,l=e.onstart||Qr,m=e.onend||Qr,v=e.onmouse||Qr,y=e.ontouch||Qr,E=e.ontouchend||Qr;function T(e){!function(){const e=t.getBoundingClientRect();s=e.left,i=e.width}();let r=(function(t){return"function"==typeof window.TouchEvent&&t instanceof TouchEvent}(e)?e.changedTouches[0].pageX:e.pageX)-s;return r>i&&(r=i),r<0&&(r=0),r/i*100}function S(e){const s=T(e);s!=r&&(o(t,s),r=s)}return t.addEventListener(u,function(e){sn(t,e)&&(a.add(tn.TOUCHING),rn(t.parentElement)&&(a.add(tn.GRABBING),y(t,T(e)),l(t,T(e)),S(e)))},Jr),t.addEventListener(f,function(e){S(e),v(t,T(e))},Jr),t.addEventListener(g,function(e){setTimeout(function(){a.remove(tn.TOUCHING)},500),sn(t,e)&&(a.remove(tn.GRABBING),E(t,T(e)),m(t,T(e)),i=0)},Jr),t.addEventListener(p,function(){a.remove(tn.GRABBING,tn.TOUCHING),i=0},Jr),t.addEventListener(c,function(e){a.contains(tn.TOUCHING)||(document.addEventListener(h,S),a.add(tn.GRABBING),l(t,T(e)),e.preventDefault(),S(e))}),t.addEventListener(h,function(e){a.contains(tn.TOUCHING)||v(t,T(e))}),document.addEventListener(d,function(e){a.contains(tn.TOUCHING)||(document.removeEventListener(h,S),a.contains(tn.GRABBING)&&(a.remove(tn.GRABBING),m(t,T(e)),i=0))}),t}function sn(t,e){const s=e.target;return!!s&&(s&&!s.closest(t.id)||!rn(t.parentElement)||!t.classList.contains(tn.TOUCHING))}function rn(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"}(tn||(tn={}));const nn="fp-tick";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,i=Array.from({length:s}).map(()=>{const t=document.createElement("i");return t.className=nn,t});this.append(...i),en(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)},onend:()=>{Je(t,{feature_name:"volume-slider",sample_rate:Ze.High,behavior:String(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")),this.adjustVolumeSlider(t.volume),t.on(b,()=>{const e=0==t.volume||t.muted;e&&this.adjustVolumeSlider(0);const s=t.opt("ui");this.classList.contains(tn.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("."+nn)),s=Math.round(t*e.length);e.forEach((t,e)=>{t.classList.toggle("fp-color",e<s)})}}class FlowplayerTimelineBar extends FlowplayerComponent{constructor(t){let e;super(t),this.bufferEle=Cr("fp-buffer"),this.progress=Cr("fp-progress","fp-color"),this.tooltipEle=Cr("fp-timestamp"),this.proposedSeekBar=Cr("fp-hover"),this.dragger=Cr("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("core.timeline_aria_label","Seek slider")),this.setAttribute("aria-valuenow","0"),this.progress.append(this.dragger),this.append(this.bufferEle,this.progress,this.proposedSeekBar,this.tooltipEle);const s=requestAnimationFrame;let i;const r=()=>{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(tn.GRABBING)||i||(i=setTimeout(r,200)))},n=()=>!!this.player.opt("seekable",!0)&&!isNaN(this.player.duration);en(this,{onseek:(s,i)=>{if(n())switch(!!e.live){case!0:Qs(i,t,this.tooltipEle);break;case!1:!function(t,e,s){const i=e.duration*(t/100);if(e.disabled&&i>e.currentTime)return!1;s.style.width=t+"%",e.currentTime=i}(i,t,this.progress),Vs(i,t,this.tooltipEle)}},onstart:()=>{n()&&(t.emit("timeline/gesture/start"),!t.hasState($s)&&t.setState(Wt,!0),e.live||function(t){t.style.display="block"}(this.tooltipEle))},onend:function(i,n){s(r),0!=e.seekable&&e.live&&Js(n,t)},ontouchend:()=>{e.live?ti(this.proposedSeekBar,this.tooltipEle):Ks(this.proposedSeekBar,this.tooltipEle),setTimeout(()=>t.emit("timeline/gesture/end"),0)},onmouse:(s,i)=>{if(n()&&(t.emit("timeline/gesture/move",{percent:i}),!this.classList.contains(tn.GRABBING)))switch(!!e.live){case!0:!function(t,e){e.style.width=t+"%"}(i,this.proposedSeekBar),Qs(i,t,this.tooltipEle);break;case!1:!function(t,e){e.style.width=t+"%"}(i,this.proposedSeekBar),Vs(i,t,this.tooltipEle)}}}),t.on(et,function(t){t.data&&(e=t.data)}),t.on(R,()=>s(r)),t.on(S,()=>{0==t.reaper||e.live||Hs(t,this.bufferEle)}),t.on(V,t=>{this.progress.style.width=t.detail+"%"}),t.on(A,()=>{0!=t.reaper&&(s(r),this.setAttribute("aria-valuenow",t.currentTime+""),this.setAttribute("aria-valuetext",Math.round(t.currentTime)+" "+t.i18n("core.seconds","Seconds")),e.live||Hs(t,this.bufferEle))}),t.on(E,()=>{0!=t.reaper&&(e.live||Hs(t,this.bufferEle))}),t.on(O,e=>{if(0==t.reaper)return;const s=qs(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?ti(this.proposedSeekBar,this.tooltipEle):Ks(this.proposedSeekBar,this.tooltipEle)})}}class FlowplayerLiveStatus extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-live-status");const e=Cr("fp-live-text"),s=Cr("fp-live-indicator","fp-color");e.textContent="live",this.setAttribute("tabindex","0"),this.setAttribute("role","button"),this.append(s,e),this.addEventListener(a,function(){Zs(t)})}}class FlowplayerDuration extends FlowplayerComponent{constructor(t){let e;super(t),this.classList.add("fp-duration"),this.setAttribute("aria-hidden","true"),t.on(et,s=>{if(0==t.reaper||!s.data)return;e=s.data;const i=qs(t)?NaN:s.data.duration||0;if(isNaN(i)||i>=Number.MAX_SAFE_INTEGER)return this.style.display="none";this.style.display="inline-block",this.innerText=cs(i)}),t.on(E,()=>{0==t.reaper||e.live||function(t,e){t.duration&&(e.innerText=cs(t.duration))}(t,this)})}}class FlowplayerElapsedTime extends FlowplayerComponent{constructor(t){let e;super(t),this.classList.add("fp-elapsed"),this.innerText=cs(0),this.setAttribute("aria-hidden","true"),t.on(et,t=>{t.data&&(e=t.data)}),t.on(A,()=>{0!=t.reaper&&(e.live?function(t,e){e.innerText=cs(t.currentTime)}(t,this):function(t,e){e.innerText=cs(t.currentTime)}(t,this))})}}class FlowplayerControlButtons extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-btns","fp-small-switch");const e=Le(t,wt),s=Le(t,kt);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,i=document.createElement("span"),r=Le(t,this.classList.contains("fp-left-zone")?xt:Mt);r.removeAttribute("tabindex"),i.classList.add("fp-zone-seconds"),this.append(i,r);t.on(D,()=>{i.innerText=""}),t.on(W,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(Y,()=>{this.reset_zone()}),this.reset_zone(),this.addEventListener(g,function(e){isNaN(t.duration)||isNaN(t.currentTime)||wr&t.opt("ui")||t.hasState(re)||!t.hasState(ue)&&!t.hasState(de)||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 FlowplayerErrorView extends FlowplayerComponent{constructor(t){super(t),this.className="fp-error",this.message=document.createElement("p"),this.message.className="error-message",this.errorId=document.createElement("p"),this.errorId.className="error-id",this.errorKey=document.createElement("p"),this.errorKey.className="error-key",this.append(this.errorKey,this.message,this.errorId),this.addEventListener(at,e=>{var s;const i=!!(null===(s=t.opts)||void 0===s?void 0:s.metadata),r=t.opts.live,n=e.detail.error.flowplayerErrorCode==De.PlaybackManifestLoadError;if((i||r)&&n)return void(this.message.textContent="stream offline");const a=e.detail.error;this.message.textContent=a.message,this.errorKey.textContent=a.errorKey,console.warn("flowplayer encountered an %s error while loading %s id:%s",a.errorKey,a.config.resource,a.id)})}}class FlowplayerHeaderLeftRight extends FlowplayerComponent{constructor(t,e,...s){super(t),this.className=e;const i=t.createComponents(...s);this.append(...i),"fp-left"!==e&&i.forEach(e=>{e.addEventListener(a,()=>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(bt,Lt);this.append(...e)}}class FlowplayerMiddleButtons extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-switch"),[Pt,Dt].forEach(e=>{const s=Le(t,e);s.removeAttribute("tabindex"),this.append(s)})}}class FlowplayerVolumeControl extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-volume-control");const e=Le(t,Ft);this.append(e),!s().ios&&this.append(Le(t,vt)),e instanceof FlowplayerIcon&&e.addEventListener(a,function(){t.toggleMute()})}}class FlowplayerHeader extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-header"),this.append(...t.createComponents(Et,Tt)),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(ht,ut,ft,gt,pt,mt))}}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(Rt,_t,It)),this.setAttribute("tabindex","0"),t.reaper&&t.reaper.set("middle",this),this.handleClick(t),this.handleTouch(t),t.once(it,()=>{this.removeAttribute("tabindex"),this.removeAttribute("role"),this.removeAttribute("aria-label")})}handleClick(t){[a,o].forEach(e=>this.addEventListener(e,function(s){if(!(s.defaultPrevented||t.root.classList.contains("is-endscreen")||e===o&&t.root.classList.contains("no-fullscreen")))return s.preventDefault(),t.emit(s.type),!1})),t.on(a,function(e){setTimeout(function(){e.defaultPrevented||t.togglePlay()},0)}),t.on(o,function(e){setTimeout(function(){e.defaultPrevented||t.toggleFullScreen()},0)})}handleTouch(t){let e=!1;this.addEventListener(g,function(e){e.cancelable&&!t.hasState("is-endscreen")&&(e.preventDefault(),t.emit(e.type,{source:e}))}),t.on(g,function(s){setTimeout(function(){if(s.defaultPrevented)return;if(t.ended)return t.togglePlay(!0);const i=t.hasState(qt);e&&clearTimeout(e),(i||t.hasState(de))&&(t.hasState(de)&&(t.setState(de,!1),t.setState(ce,!1)),t.togglePlay(),i)||(t.setState(de,!0),t.paused||(e=setTimeout(function(){e=!1,t.setState(de,!1),t.setState(ce,!1)},2e3)))},0)})}}class FlowplayerUi extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-ui"),this.append(...t.createComponents(yt,At,ct))}}const an=t=>{let e=!1;t.on(Qe,()=>{e||(t=>{const e=t.customElements.entries();for(var[s,i]of e)if(!Ie(t,i))return!0;return!1})(Lr)&&(Je(t,{feature_name:"custom-components",behavior:"used",sample_rate:Ze.High}),e=!0)})},on="flowplayer-ad-ui",ln="flowplayer-ad-controls",dn="flowplayer-ad-countdown",cn="flowplayer-ad-indicator",hn=t=>{const e=t.closest(`.${Xr}`);return e?((t,e)=>{var s,i;const r=`${((null===(s=e.parentElement)||void 0===s?void 0:s.localName)||"")+">"+t.localName}>${e.open?"open":"closed"}`;return t instanceof HTMLSpanElement?r+">"+(t.textContent||""):t instanceof HTMLLIElement?r+">"+((null===(i=t.querySelector("span"))||void 0===i?void 0:i.textContent)||""):r})(t,e):t.closest(gt)?gt:t.closest(vt)?vt:t.closest(bt)?bt:t.closest(on)?on+">"+t.localName:t.localName},un=new Set(["click","drag","quick-clicks"]),fn=t=>t.hasState(he)?t.hasState(de):t.hasState(ce),gn=(t,e,s,i)=>{const r=t=>"string"==typeof t?t:hn(t);return((t,e,s={})=>{const i=e.join(","),r=Object.entries(s).map(([t,e])=>`${t}=${e}`).join(",");return r?`${t}:${i}:${r}`:`${t}:${i}`})(t,s?[r(e),r(s)]:[r(e)],i||{})},pn=(t,e,s,i,r)=>{if(!function(t,e){var s;const i=null===(s=t.health)||void 0===s?void 0:s.session_id;if(!i)return Math.random()<=e;if(!ts.has(i)){const t=Math.random()<=e;return ts.set(i,t),t}return!!ts.get(i)}(t,Ze.Low))return;const n=un.has(e)?Object.assign({is_hovered:fn(t)?1:0},r):r;Je(t,{feature_name:"ui",behavior:gn(e,s,i,n),sample_rate:Ze.All})};class ClickTracker{constructor(t){this.handleTouchStart=t=>{const e=t.target,s=t.touches[0];e&&s&&this.touches.set(e,{startX:s.clientX,startY:s.clientY})},this.handleTouchEnd=t=>{const e=t.target;if(!this.shouldTrackElement(e))return;const s=this.touches.get(e),i=t.changedTouches[0];if(i){const t=Object.assign(Object.assign({},s),{endX:i.clientX,endY:i.clientY});if(((t,e)=>{if(void 0===t.startX||void 0===t.startY||void 0===t.endX||void 0===t.endY)return!1;const s=Math.abs(t.endX-t.startX),i=Math.abs(t.endY-t.startY);return s>e||i>e})(t,10)){const s=document.elementFromPoint(i.clientX,i.clientY);s&&this.shouldTrackElement(s)&&(this.touches.set(e,Object.assign(Object.assign({},t),{endTimestamp:Date.now()})),pn(this.video,"drag",e,s)),this.touches.delete(e)}else this.touches.set(e,Object.assign(Object.assign({},t),{endTimestamp:Date.now()})),pn(this.video,"click",e),this.handleQuickClickDetection(e,i.clientX,i.clientY)}else this.touches.set(e,Object.assign(Object.assign({},s),{endTimestamp:Date.now()})),pn(this.video,"click",e)},this.handleClick=t=>{const e=t.target;if(!this.shouldTrackElement(e))return;const s=this.touches.get(e);if((null==s?void 0:s.endTimestamp)&&Date.now()-s.endTimestamp<100)return;const i=t.clientX,r=t.clientY;pn(this.video,"click",e),this.handleQuickClickDetection(e,i,r)};const e=t.root;if(!e)throw new Error("Player root element is required for click tracking");this.root=e,this.video=t,this.touches=new WeakMap,this.lastClick={element:null,timestamp:null,x:null,y:null}}track(){this.root.addEventListener("touchstart",this.handleTouchStart,{capture:!0,passive:!0}),this.root.addEventListener("touchend",this.handleTouchEnd,{capture:!0,passive:!0}),this.root.addEventListener("click",this.handleClick,{capture:!0})}handleQuickClickDetection(t,e,s){const i=Date.now();if(this.lastClick.element&&this.lastClick.timestamp&&null!==this.lastClick.x&&null!==this.lastClick.y){const r=i-this.lastClick.timestamp;if(r<1200){const i=((t,e,s,i)=>{const r=s-t,n=i-e;return Math.sqrt(r*r+n*n)})(this.lastClick.x,this.lastClick.y,e,s);if(i<=50){const e=100*Math.ceil(r/100),s=10*Math.ceil(i/10);return pn(this.video,"quick-clicks",this.lastClick.element,t,{"time-diff":e,distance:s}),void this.clearClick()}}}this.lastClick.element=t,this.lastClick.timestamp=i,this.lastClick.x=e,this.lastClick.y=s}shouldTrackElement(t){return!(!t||!this.root.contains(t))&&t!==this.video}clearClick(){this.lastClick.element=null,this.lastClick.timestamp=null,this.lastClick.x=null,this.lastClick.y=null}}const mn=t=>50*Math.round(t/50),vn=t=>{if(!t.root)return;const e=e=>{var s;const i=null===(s=t.root)||void 0===s?void 0:s.getBoundingClientRect(),r=mn((null==i?void 0:i.width)||0),n=mn((null==i?void 0:i.height)||0),a=(()=>{var t,e;return(null===(e=null===(t=window.screen)||void 0===t?void 0:t.orientation)||void 0===e?void 0:e.type)?window.screen.orientation.type.includes("portrait")?"portrait":"landscape":"unknown"})(),o=(t=>{if(Mr(t)){const e=t.webkitDisplayingFullscreen;return"boolean"==typeof e&&e}return!!document.fullscreenElement})(t)?"true":"false";pn(t,"player-dimensions",`${r},${n}`,void 0,{delay:e}),pn(t,"orientation",a,void 0,{delay:e}),pn(t,"fullscreen-status",o,void 0,{delay:e})};t.once(R,()=>{e(0);const s=setTimeout(()=>{t.paused||e(5e3)},5e3);t.once(N,()=>clearTimeout(s))})},yn=(...t)=>t.reduce((t,e)=>Object.assign(Object.assign({},t),e),{}),En=(t,e)=>{const s=t.lastIndexOf(e);return~s&&t.splice(s,1),t};class RequestQueue$1{static of(){return new RequestQueue$1}static is_empty(t){return 0==t.pending.length}static is_high_water(t){return t.open.length==RequestQueue$1.MAX_OPEN_REQUESTS}static maybe_spawn_req(t){if(RequestQueue$1.is_empty(t))return t;if(RequestQueue$1.is_high_water(t))return t;try{const e=RequestQueue$1.lpop(t);e&&RequestQueue$1.request(t,e)}catch(t){}}static increment_failures(t){return t.stats.failures++,t.stats.failures>RequestQueue$1.MAX_FAILURE_COUNT&&(t.stats.ttl=Date.now()+RequestQueue$1.REQUEST_TTL_MS),t}static handle_error(t,e){RequestQueue$1.rm(t,e),RequestQueue$1.increment_failures(t)}static request(t,[e,s,i]){if(Date.now()<t.stats.ttl)return;const r=new XMLHttpRequest;t.open.push(r),r.timeout=RequestQueue$1.REQUEST_TIMEOUT_MS,r.ontimeout=function(){RequestQueue$1.handle_error(t,r)},r.onerror=function(e){RequestQueue$1.handle_error(t,r)},r.onreadystatechange=function(){r.readyState==XMLHttpRequest.DONE&&RequestQueue$1.rm(t,r),Math.floor(r.status/100)},r.onload=function(){RequestQueue$1.rm(t,r),t.stats.failures&&t.stats.failures--},r.open(s,e),r.setRequestHeader("Content-Type","text/plain;charset=UTF-8");try{r.send(JSON.stringify(i))}catch(t){}}static rpush(t,...e){return e.forEach(e=>{t.pending.length>=RequestQueue$1.MAX_PENDING||(t.pending.push(e),RequestQueue$1.maybe_spawn_req(t))}),t}static lpop(t){return t.pending.shift()}static rm(t,e){return En(t.open,e),t}constructor(){this.pending=[],this.open=[],this.stats={failures:0,ttl:0}}}RequestQueue$1.MAX_OPEN_REQUESTS=3,RequestQueue$1.MAX_PENDING=5,RequestQueue$1.REQUEST_TIMEOUT_MS=4e3,RequestQueue$1.REQUEST_TTL_MS=5e3,RequestQueue$1.MAX_FAILURE_COUNT=3;var Tn=RequestQueue$1.of();const Sn=/:([a-zA-Z_]+)/g;class Log$1{static prepare(t,e){const s=document.createEvent("Event");return s.initEvent(t,!1,!0),s.ns=t,s.data=e,s}static of(t){return new Log$1(t)}constructor(t){this.emitter=t}info(t){this.emitter.dispatchEvent(Log$1.prepare(Log$1.NAMESPACE.INFO,t))}error(t){this.emitter.dispatchEvent(Log$1.prepare(Log$1.NAMESPACE.ERROR,t))}warn(t){this.emitter.dispatchEvent(Log$1.prepare(Log$1.NAMESPACE.WARN,t))}}var An;Log$1.NAMESPACE={INFO:"tracker:info",ERROR:"tracker:err",WARN:"tracker:warn"},function(t){t.POST="POST",t.PUT="PUT",t.GET="GET"}(An||(An={}));class Tracker{static of(t,e){return new Tracker(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)=>yn(e,{[s]:t[s]}),{}))(e,...t.valid_keys)}static merge_metadata(t,e={}){return t.metadata=Tracker.pluck_valid_keys(t,yn(t.metadata,e)),t}static assert_emitter_api(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")}static create_listener(t,e,s){var i;t.listeners.push([e,s]),null===(i=t.emitter)||void 0===i||i.addEventListener(e,s)}constructor(t,e={}){const s=this;if(this.emitter=t,this.url=e.url,this.log=Log$1.of(this.emitter),this.verb=e.verb,this.metadata=yn({},e.metadata||{}),this.rq=e.rq||Tn,this.events=e.events||[],this.required_keys=e.required_keys||[],this.optional_keys=e.optional_keys||[],this.listeners=[],this.valid_keys=this.required_keys.slice(0).concat(this.optional_keys),Tracker.assert_emitter_api(this.emitter),void 0===Tracker.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`);Tracker.TRACKERS.push(this),s.events.forEach(t=>{Tracker.create_listener(this,t,(e={})=>{var i;if(null===(i=this.emitter)||void 0===i?void 0:i.hasState("consent-no-tracking"))return;const r=yn(s.metadata,{event_type:t},e.data||e),n=function(t,e){return t.replace(Sn,t=>{const s=t.slice(1,t.length);return s in e?e[s].toString():t})}(s.url,r),a=Tracker.pluck_valid_keys(s,r),o=Tracker.ensure_required_keys(s,a);if(o.length)return s.log.error(`Tracker.validate_metadata() failed for\n Event[${t}]\n missing keys: ${o}\n payload:\n ${JSON.stringify(a,null,2)}`);this.rq&&RequestQueue$1.rpush(this.rq,[n,this.verb,a])})})}destroy(){this.listeners.forEach(([t,e])=>{var s;return null===(s=this.emitter)||void 0===s?void 0:s.removeEventListener(t,e)}),delete this.rq,delete this.emitter,En(Tracker.TRACKERS,this)}put(t={}){return Tracker.merge_metadata(this,t),this}}Tracker.TRACKERS=[],Tracker.QUEUE=Tn,Tracker.verb=An;var _n="ping",bn="display",Ln="view";const Rn=["sitegroup_id","session_id","media_id","site_id","player_id","video_type"],In=["created","position"],kn=["player_version","created","source","category","category_id","autoplay","muted","customer_user_id"];const wn=100,Pn=1e3;function Dn(t,e){return t.duration/1===t.duration&&Object.assign(e,function(t){const e=t/wn;return{segment_duration:e,breakpoints:Array(...Array(wn)).map(function(t,s){return Math.floor(s*e*Pn)/Pn})}}(t.duration))}function Cn(t,e,s,i){if(!e.segment_duration&&!Dn(t,e))return;const r=function(t,e,s,i){const r=e.last_idx,n=s?100:On(t,e,i);return e.last_idx=n,n<=r?[]:e.breakpoints.slice(r,n).map(function(t){return e.breakpoints.indexOf(t)})}(t,e,s,i);0!=r.length&&t.emit(_n,{position:r})}function On(t,e,s){const i=void 0!==s?s:t.currentTime;return Math.min(100,Math.max(0,Math.floor(i/e.segment_duration-.8)+1))}var Mn;const xn="vod",Fn="live",Nn=[bn,_n,Ln];function Un(t,e,s,i){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(_n,{position:60*e.ticks}))}(t,e);case"vod":return Cn(t,e,"boolean"==typeof s&&s,i)}}function Bn(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))))}const $n=(Mn=class Analytics{init(t,e,s){if(!Fs.from_token(t.token||"").is_granted(Fs.permissions.ANALYTICS))return;if(s.analytics)return;const i=s.analytics={ticker:void 0,last_media_id:"",ended:!1,played:!1},r={locked:void 0,ttl:6e3,task:()=>{s.hasState(Wt)||Un(s,i.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.43.0-rc.1"},a=Tracker.of(s,{verb:Tracker.verb.POST,url:"https://ptm.flowplayer.com/:video_type/:sitegroup_id/:event_type",events:Nn,required_keys:Rn,optional_keys:kn.concat(In).slice(0),metadata:n});s.on(N,function(){a&&a.destroy()});let o=0,l=0;s.on(et,function(e){if(!a)return;const r=ls(e,"data.metadata",{});if(!r.media_id&&r.stream_target_id&&(r.media_id=r.stream_target_id),!r.media_id)return i.last_media_id="";if(i.last_media_id===r.media_id)return;i.played=!1,i.last_media_id=r.media_id;const n=ls(t,"analytics",{});a.put(r),a.put(n);const l=ls(t,"metadata.live_start_time",t.live)?Fn:xn;a.put({video_type:l,source:t.source||bi()||""}),i.ticker=ls(t,"metadata.live_start_time",t.live)?{ticks:0,last_tracked_ts:Date.now(),kind:"live"}:{last_idx:0,segment_duration:0,breakpoints:[],kind:"vod"},o=0,i.ended=!1,s.emit(bn)}),s.on(R,function(){if(!a)return;if(l||i.played||!i.last_media_id)return;a.put({muted:s.muted});const t=Bn(s);if(t)return l=Promise.resolve(t).then(function(){i.played=!0,s.emit(Ln),l=0}).catch(function(){l=0});i.played=!0,s.emit(Ln)}),s.on(A,function(){var e;a&&(o=s.currentTime,l||Bn(s)||i.ended||!i.last_media_id||s.hasState(Wt)||(!t.live&&s.currentTime+.25>=s.duration&&Un(s,i.ticker,!0),(e=r).locked||(e.locked=setTimeout(function(){return e.task(),function(t){return t.locked=void 0,t}(e)},e.ttl))))}),s.on(D,function(){var t;a&&i.last_media_id&&(i.ended&&(i.ended=!1,o=0,"vod"===(null===(t=i.ticker)||void 0===t?void 0:t.kind)&&(i.ticker.last_idx=0)),i.ticker&&"vod"==i.ticker.kind&&function(t,e){Dn(t,e),e.last_idx=On(t,e)}(s,i.ticker))}),s.on("timeline/gesture/start",function(){Un(s,i.ticker,!1,o)}),s.on(P,function(){a&&i.last_media_id&&function(t,e){e.ended||(e.ended=!0,Un(t,e.ticker))}(s,i)})}},Mn.pluginName="analytics",Mn),Gn=ws(Ps(),$n),Hn=t=>0==t.volume||t.muted?"true":"false";class Default{constructor(t){Re(t,lt,FlowplayerUi),Re(t,Ut,FlowplayerErrorView),Re(t,ct,FlowplayerControls),Re(t,ut,FlowplayerLiveStatus),Re(t,pt,FlowplayerDuration),Re(t,gt,FlowplayerTimelineBar),Re(t,ft,FlowplayerElapsedTime),Re(t,vt,FlowplayerVolumeBar),Re(t,mt,FlowplayerVolumeControl),Re(t,ht,FlowplayerControlButtons),Re(t,yt,FlowplayerHeader),Re(t,dt,FlowplayerLogo),Re(t,St,FlowplayerHeaderDuration),Re(t,Et,class extends FlowplayerHeaderLeftRight{constructor(t){super(t,"fp-left",St)}}),Re(t,Tt,class extends FlowplayerHeaderLeftRight{constructor(t){super(t,"fp-right fp-togglable",Ct,Ot)}}),Re(t,At,FlowplayerMiddle),Re(t,_t,FlowplayerMiddleZone),Re(t,bt,FlowplayerMiddleWait),Re(t,Lt,FlowplayerMiddleButtons),Re(t,It,class extends FlowplayerLeftRightZone{constructor(t){super(t,"fp-right-zone")}}),Re(t,Rt,class extends FlowplayerLeftRightZone{constructor(t){super(t,"fp-left-zone")}}),Re(t,kt,class extends FlowplayerIcon{constructor(t){super(t,qr),this.setAttribute("role","button")}}),Re(t,wt,class extends FlowplayerIcon{constructor(t){super(t,Wr),this.setAttribute("role","button")}}),Re(t,Pt,class extends FlowplayerIcon{constructor(t){super(t,Kr),this.setAttribute("role","button")}}),Re(t,Dt,class extends FlowplayerIcon{constructor(t){super(t,Vr),this.setAttribute("role","button")}}),Re(t,Ct,class extends FullscreenIcon{constructor(t){super(t,Gr)}}),Re(t,Ot,class extends FullscreenIcon{constructor(t){super(t,Hr)}}),Re(t,Mt,class extends FlowplayerIcon{constructor(t){super(t,Yr)}}),Re(t,xt,class extends FlowplayerIcon{constructor(t){super(t,zr)}}),Re(t,Ft,class extends FlowplayerIcon{constructor(t){super(t,jr),this.classList.add("fp-volumebtn"),this.setAttribute("role","switch"),this.setAttribute("aria-checked",Hn(t)),t.on(b,()=>{this.setAttribute("aria-label",t.i18n("core.muted","Muted")),this.setAttribute("aria-checked",Hn(t))})}})}init(t,e,s){Br(t,0,s),Nr(t,e,s),Rr(0,0,s),an(s),(t=>{if(!t.root)return;new ClickTracker(t).track(),vn(t)})(s)}}Default.pluginName="default",Lr.extensions.unshift.apply(Lr.extensions,[I18n,Gn,Default]);var Kn=Object.assign(Lr,{ui:Pr,i18n:I18n});const Vn=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},jn=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=qn},qn=Number.MAX_SAFE_INTEGER||9007199254740991;let Wn=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}({}),Yn=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.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",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.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",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_APPEND_NO_PROGRESS="bufferAppendNoProgress",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",t.UNKNOWN="unknown",t}({}),zn=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",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.BUFFERED_TO_END="hlsBufferedToEnd",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.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",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_TRACK_UPDATED="hlsSubtitleTrackUpdated",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.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",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.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});function Qn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Xn,Zn={exports:{}};var Jn=(Xn||(Xn=1,function(t){var e,s,i,r,n;e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,n={buildAbsoluteURL:function(t,e,i){if(i=i||{},t=t.trim(),!(e=e.trim())){if(!i.alwaysNormalize)return t;var r=n.parseURL(t);if(!r)throw new Error("Error trying to parse base URL.");return r.path=n.normalizePath(r.path),n.buildURLFromParts(r)}var a=n.parseURL(e);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return i.alwaysNormalize?(a.path=n.normalizePath(a.path),n.buildURLFromParts(a)):e;var o=n.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=s.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 c=o.path,h=c.substring(0,c.lastIndexOf("/")+1)+a.path;d.path=n.normalizePath(h)}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?n.normalizePath(a.path):a.path),n.buildURLFromParts(d)},parseURL:function(t){var s=e.exec(t);return s?{scheme:s[1]||"",netLoc:s[2]||"",path:s[3]||"",params:s[4]||"",query:s[5]||"",fragment:s[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(i,"");t.length!==(t=t.replace(r,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=n}(Zn)),Zn.exports);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 ta="manifest",ea="level",sa="audioTrack",ia="subtitleTrack",ra="media-fragment",na="key",aa="steering-manifest",oa="server-certificate",la="interstitial-asset-list",da="main",ca="audio",ha="subtitle",ua="audio",fa="video",ga="audiovideo";class BaseSegment{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,e){const s=ya(t,e);s&&(s.enumerable=!0,Object.defineProperty(t,e,s))}(this,"stats")}setByteRange(t,e){const s=t.split("@",2);let i;i=1===s.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[ua]:null,[fa]:null,[ga]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new LoadStats),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.relurl&&(this._url=Jn.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[ua]=null,t[fa]=null,t[ga]=null,this.url=null}}function pa(t){return"initSegment"!==t.sn}function ma(t,e){return t.sn===(null==e?void 0:e.sn)&&t.level===e.level}function va(t,e){return t.sn===(null==e?void 0:e.sn)&&t.level===e.level&&t.cc===e.cc}class Fragment extends BaseSegment{constructor(t,e){super(e),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const t=this.byteRange[0],e=this.byteRange[1];if(Vn(t)&&Vn(e))return e-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(null==(t=this._decryptdata)||!t.keyId){const t=Object.keys(e);if(1===t.length){const s=this._decryptdata=e[t[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const t=Vn(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){var e;const t=Object.keys(this.levelkeys),s=t.length;if(s>1||1===s&&null!=(e=this.levelkeys[t[0]])&&e.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){Vn(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return pa(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var s;const i=e[t];!i||null!=(s=this._decryptdata)&&s.keyId||(this._decryptdata=i.getDecryptData(this.sn,e))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,s,i,r,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,i),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:s,startDTS:i,endDTS:r,partial:n}}}class Part extends BaseSegment{constructor(t,e,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,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=i;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo||this.fragment.type===ha&&this.stats.loading.end>0)}}function ya(t,e){const s=Object.getPrototypeOf(t);if(s){const t=Object.getOwnPropertyDescriptor(s,e);return t||ya(s,e)}}function Ea(t,e,s){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var s=t[Symbol.toPrimitive];if(void 0!==s){var i=s.call(t,e);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function Ta(){return Ta=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var s=arguments[e];for(var i in s)({}).hasOwnProperty.call(s,i)&&(t[i]=s[i])}return t},Ta.apply(null,arguments)}function Sa(t,e){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),s.push.apply(s,i)}return s}function Aa(t){for(var e=1;e<arguments.length;e++){var s=null!=arguments[e]?arguments[e]:{};e%2?Sa(Object(s),!0).forEach(function(e){Ea(t,e,s[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):Sa(Object(s)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(s,e))})}return t}function _a(t,e){if(null==t)return{};var s,i,r=function(t,e){if(null==t)return{};var s={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(-1!==e.indexOf(i))continue;s[i]=t[i]}return s}(t,e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);for(i=0;i<n.length;i++)s=n[i],-1===e.indexOf(s)&&{}.propertyIsEnumerable.call(t,s)&&(r[s]=t[s])}return r}function ba(t){switch(t.details){case Yn.FRAG_LOAD_TIMEOUT:case Yn.KEY_LOAD_TIMEOUT:case Yn.LEVEL_LOAD_TIMEOUT:case Yn.MANIFEST_LOAD_TIMEOUT:case Yn.AUDIO_TRACK_LOAD_TIMEOUT:case Yn.SUBTITLE_TRACK_LOAD_TIMEOUT:case Yn.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function La(t){return t.details.startsWith("key")}function Ra(t){return La(t)&&!!t.frag&&!t.frag.decryptdata}function Ia(t,e){const s=ba(e);return t.default[(s?"timeout":"error")+"Retry"]}function ka(t,e){const s="linear"===t.backoff?1:Math.pow(2,e);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function wa(t){return Aa(Aa({},t),{errorRetry:null,timeoutRetry:null})}function Pa(t,e,s,i){if(!t)return!1;const r=null==i?void 0:i.code,n=e<t.maxNumRetry&&(function(t){return Da(t)||!!t&&(t<400||t>499)}(r)||!!s);return t.shouldRetry?t.shouldRetry(t,e,s,i,n):n}function Da(t){return 0===t&&!1===navigator.onLine}function Ca(t,e){return e>0&&t.loadError>0&&0!==t.loadErrorTime&&self.performance.now()-t.loadErrorTime>e}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,i=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_=i,this.ttfb_=new EWMA(t)}update(t,e){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==t&&(this.slow_=new EWMA(t,s.getEstimate(),s.getTotalWeight())),i.halfLife!==e&&(this.fast_=new EWMA(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new EWMA(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){if(e<=0)return;const s=Math.min(this.minDelayMs_,e/1e5),i=8*e,r=Math.max(t,s)/1e3,n=i/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}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_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}class Logger{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${t}]:`;this.trace=Oa,this.debug=e.debug.bind(null,s),this.log=e.log.bind(null,s),this.warn=e.warn.bind(null,s),this.info=e.info.bind(null,s),this.error=e.error.bind(null,s)}}const Oa=function(){},Ma={trace:Oa,debug:Oa,log:Oa,warn:Oa,info:Oa,error:Oa};function xa(){return Ta({},Ma)}function Fa(t,e,s){return e[t]?e[t].bind(e):function(t,e){const s=self.console[t];return s?s.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):Oa}(t,s)}const Na=xa();const Ua=Na;function Ba(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function $a(t,e){const s=Object.keys(t),i=Object.keys(e),r=s.length,n=i.length;return!r||!n||r===n&&!s.some(t=>-1===i.indexOf(t))}function Ga(t){return t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer}const Ha="utf-16be",Ka="utf-16le",Va="utf-8";function ja(t,e){if(t<0)return-ja(-t,e);const s=Math.pow(10,e);if(Math.abs(t*s%1-.5)<Number.EPSILON){const e=Math.floor(t*s);return(e%2==0?e:e+1)/s}return Math.round(t*s)/s}function qa(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const s=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?s:3&s|8).toString(16)})}}}function Wa(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}function Ya(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}function za(t,e){return Wa(t,e)&&Ya(t,e+6)+10<=t.length-e}function Qa(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}function Xa(t,e){const s=e;let i=0;for(;Wa(t,e);){i+=10;i+=Ya(t,e+6),Qa(t,e+10)&&(i+=10),e+=i}if(i>0)return t.subarray(s,s+i)}function Za(t,e=0,s=1/0){return function(t,e,s,i){const r=(n=t,Ga(n)?n:n.buffer);var n;let a=1;"BYTES_PER_ELEMENT"in i&&(a=i.BYTES_PER_ELEMENT);const o=(h=t,h&&Ga(h.buffer)&&void 0!==h.byteLength&&void 0!==h.byteOffset?t.byteOffset:0),l=(o+t.byteLength)/a,d=(o+e)/a,c=Math.floor(Math.max(0,Math.min(d,l)));var h;return new i(r,c,Math.floor(Math.min(c+Math.max(s,0),l))-c)}(t,e,s,Uint8Array)}function Ja(t,e=!1){const s=e?t.indexOf(0):t.length,i=function(t,e={}){let s;s=Ga(t)?new DataView(t):new DataView(t.buffer,t.byteOffset,t.byteLength);let i=0,{encoding:r}=e;if(!r){const t=s.getUint8(0),e=s.getUint8(1);239==t&&187==e&&191==s.getUint8(2)?(r=Va,i=3):254==t&&255==e?(r=Ha,i=2):255==t&&254==e?(r=Ka,i=2):r=Va}if("undefined"!=typeof TextDecoder)return new TextDecoder(r).decode(s);const{byteLength:n}=s,a=r!==Ha;let o,l="";for(;i<n;){switch(r){case Va:if(o=s.getUint8(i),o<128)i++;else if(o>=194&&o<=223)if(i+1<n){const t=s.getUint8(i+1);t>=128&&t<=191?(o=(31&o)<<6|63&t,i+=2):i++}else i++;else if(o>=224&&o<=239)if(i+2<=n-1){const t=s.getUint8(i+1),e=s.getUint8(i+2);t>=128&&t<=191&&e>=128&&e<=191?(o=(15&o)<<12|(63&t)<<6|63&e,i+=3):i++}else i++;else if(o>=240&&o<=244)if(i+3<=n-1){const t=s.getUint8(i+1),e=s.getUint8(i+2),r=s.getUint8(i+3);t>=128&&t<=191&&e>=128&&e<=191&&r>=128&&r<=191?(o=(7&o)<<18|(63&t)<<12|(63&e)<<6|63&r,i+=4):i++}else i++;else i++;break;case Ha:case"utf-16":case Ka:o=s.getUint16(i,a),i+=2}l+=String.fromCodePoint(o)}return l}(new DataView(t.buffer,t.byteOffset,s),{encoding:Va});return e?i:i.replace(/\0/g,"")}function to(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const s=t.data.subarray(1).indexOf(0);if(-1===s)return;const i=Ja(Za(t.data,1,s)),r=t.data[2+s],n=t.data.subarray(3+s).indexOf(0);if(-1===n)return;const a=Ja(Za(t.data,3+s,n));let o;var l;return"--\x3e"===i?o=Ja(Za(t.data,4+s+n)):o=Ga(l=t.data.subarray(4+s+n))?l:0==l.byteOffset&&l.byteLength==l.buffer.byteLength?l.buffer:new Uint8Array(l).buffer,e.mimeType=i,e.pictureType=r,e.description=a,e.data=o,e}function eo(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=Ja(t.data,!0),s=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:s.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const s=Ja(t.data.subarray(e),!0);e+=s.length+1;const i=Ja(t.data.subarray(e));return{key:t.type,info:s,data:i}}const e=Ja(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?to(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const{data:s}=t,i=Ja(s.subarray(e),!0);e+=i.length+1;const r=Ja(s.subarray(e));return{key:t.type,info:i,data:r}}const e=Ja(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function so(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),s=Ya(t,4);return{type:e,size:s,data:t.subarray(10,10+s)}}function io(t){let e=0;const s=[];for(;Wa(t,e);){const i=Ya(t,e+6);t[e+5]>>6&1&&(e+=10),e+=10;const r=e+i;for(;e+10<r;){const i=so(t.subarray(e)),r=eo(i);r&&s.push(r),e+=i.size+10}Qa(t,e)&&(e+=10)}return s}function ro(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function no(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),s=1&e[3];let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,s&&(i+=47721858.84),Math.round(i)}}function ao(t){const e=io(t);for(const t of e)if(ro(t))return no(t)}function oo(t){let e="";for(let s=0;s<t.length;s++){let i=t[s].toString(16);i.length<2&&(i="0"+i),e+=i}return e}function lo(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function co(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function ho(t){return String.fromCharCode.apply(null,t)}const uo=Math.pow(2,32)-1,fo={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},go={video:1,audio:2,id3:3,text:4};function po(t,e){const s=t[e]<<8|t[e+1];return s<0?65536+s:s}function mo(t,e){const s=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3];return s<0?4294967296+s:s}function vo(t,e){let s=mo(t,e);return s*=Math.pow(2,32),s+=mo(t,e+4),s}function yo(t,e){let s="";for(let i=e;i<t.length;i++)if(s+=String.fromCharCode(t[i]),0===t[i])return s;return null}function Eo(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function To(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 So(t,e,s){const i=e.byteOffset-t.byteOffset-8,r=8+s,n=e.byteLength+8-r;n<8||(To(t,i,r),To(t,i+r,n),To(t,i+r+4,fo.free))}function Ao(t,e){return[t.byteOffset-e-8,t.byteOffset-e+t.byteLength]}function _o(t,e){e.sort((t,e)=>t[0]-e[0]);const s=e.reduce((t,[e,s])=>t+s-e,0),i=new Uint8Array(t.byteLength-s);let r=0,n=0;for(let s=0;s<e.length;s++){const[a,o]=e[s];i.set(t.subarray(r,a),n),n+=a-r,r=o}i.set(t.subarray(r),n);return{result:i,dropped:s,droppedBefore:t=>e.reduce((e,[s,i])=>i<=t?e+i-s:e,0)}}function bo(t,e){const s=[];return e.length?(Lo(t,e,0,0,t.byteLength,s),s):s}function Lo(t,e,s,i,r,n){const a=e[s];if(4!==(null==a?void 0:a.length))return;const o=a.charCodeAt(0),l=a.charCodeAt(1),d=a.charCodeAt(2),c=a.charCodeAt(3),h=e.length-1;for(let a=i;a<r;){const i=a+8<=r,u=a+4<=r?16777216*t[a]+(t[a+1]<<16|t[a+2]<<8|t[a+3]):mo(t,a),f=u>1?a+u:r;if(i&&t[a+4]===o&&t[a+5]===l&&t[a+6]===d&&t[a+7]===c){const i=Math.min(f,r);s===h?n.push(t.subarray(a+8,i)):Lo(t,e,s+1,a+8,i,n)}a=f}}function Ro(t){const e=[],s=t[0];let i=8;const r=mo(t,i);i+=4;let n=0,a=0;0===s?(n=mo(t,i),a=mo(t,i+4),i+=8):(n=vo(t,i),a=vo(t,i+8),i+=16),i+=2;let o=t.length+a;const l=po(t,i);i+=2;for(let s=0;s<l;s++){let s=i;const n=mo(t,s);s+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return Ua.warn("SIDX has hierarchical references (not supported)"),null;const l=mo(t,s);s+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,s+=4,i=s}return{earliestPresentationTime:n,timescale:r,version:s,referencesCount:l,references:e}}function Io(t){const e=[],s=bo(t,["moov","trak"]);for(let t=0;t<s.length;t++){const i=s[t],r=bo(i,["tkhd"])[0];if(r){let t=r[0];const s=mo(r,0===t?12:20),n=bo(i,["mdia","mdhd"])[0];if(n){t=n[0];const r=mo(n,0===t?12:20),a=bo(i,["mdia","hdlr"])[0];if(a){const t=ho(a.subarray(8,12)),n={soun:ua,vide:fa}[t],o=ko(bo(i,["mdia","minf","stbl","stsd"])[0]);n?(e[s]={timescale:r,type:n,stsd:o},e[n]=Aa({timescale:r,id:s},o)):e[s]={timescale:r,type:t,stsd:o}}}}}return bo(t,["moov","mvex","trex"]).forEach(t=>{const s=mo(t,4),i=e[s];i&&(i.default={duration:mo(t,12),sampleSize:mo(t,16),flags:mo(t,20)})}),e}function ko(t){const e=t.subarray(8),s=e.subarray(86),i=ho(e.subarray(4,8));let r,n=i;const a="enca"===i||"encv"===i;if(a){const t=bo(e,[i])[0];bo(t.subarray("enca"===i?28:78),["sinf"]).forEach(t=>{const e=bo(t,["schm"])[0];if(e){const s=ho(e.subarray(4,8));if("cbcs"===s||"cenc"===s){const e=bo(t,["frma"])[0];e&&(n=ho(e))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=bo(s,["avcC"])[0];t&&t.length>3&&(n+="."+Do(t[1])+Do(t[2])+Do(t[3]),r=wo("avc1"===o?"dva1":"dvav",s));break}case"mp4a":{const t=bo(e,[i])[0],s=bo(t.subarray(28),["esds"])[0];if(s&&s.length>7){let t=4;if(3!==s[t++])break;t=Po(s,t),t+=2;const e=s[t++];if(128&e&&(t+=2),64&e&&(t+=s[t++]),4!==s[t++])break;t=Po(s,t);const i=s[t++];if(64!==i)break;if(n+="."+Do(i),t+=12,5!==s[t++])break;t=Po(s,t);const r=s[t++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&s[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=bo(s,["hvcC"])[0];if(t&&t.length>12){const e=t[1],s=["","A","B","C"][e>>6],i=31&e,r=mo(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);n+="."+s+i,n+="."+function(t){let e=0;for(let s=0;s<32;s++)e|=(t>>s&1)<<31-s;return e>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let d="";for(let t=l.length;t--;){const e=l[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}n+=d}r=wo("hev1"==o?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=wo(n,s)||n;break;case"vp09":{const t=bo(s,["vpcC"])[0];if(t&&t.length>6){const e=t[4],s=t[5],i=t[6]>>4&15;n+="."+Co(e)+"."+Co(s)+"."+Co(i)}break}case"av01":{const t=bo(s,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,i=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,d=2===e&&o?l?12:10:o?10:8,c=(16&t[2])>>4,h=(8&t[2])>>3,u=(4&t[2])>>2,f=3&t[2],g=1,p=1,m=1,v=0;n+="."+e+"."+Co(i)+a+"."+Co(d)+"."+c+"."+h+u+f+"."+Co(g)+"."+Co(p)+"."+Co(m)+"."+v,r=wo("dav1",s)}break}}return{codec:n,encrypted:a,supplemental:r}}function wo(t,e){const s=bo(e,["dvvC"]),i=s.length?s[0]:bo(e,["dvcC"])[0];if(i){const e=i[2]>>1&127,s=i[2]<<5&32|i[3]>>3&31;return t+"."+Co(e)+"."+Co(s)}}function Po(t,e){const s=e+5;for(;128&t[e++]&&e<s;);return e}function Do(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function Co(t){return(t<10?"0":"")+t}function Oo(t,e){bo(t,["moov","trak"]).forEach(t=>{const s=bo(t,["mdia","minf","stbl","stsd"])[0];if(!s)return;const i=s.subarray(8);let r=bo(i,["enca"]);const n=r.length>0;n||(r=bo(i,["encv"])),r.forEach(t=>{bo(n?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const s=Mo(t);s&&e(s,n)})})})}function Mo(t){const e=bo(t,["schm"])[0];if(e){const s=ho(e.subarray(4,8));if("cbcs"===s||"cenc"===s){const e=bo(t,["schi","tenc"])[0];if(e)return e}}}let xo;function Fo(t){if("undefined"==typeof TextDecoder)return Ja(t);return(xo||(xo=new TextDecoder("utf-8"))).decode(t).replace(/\0/g,"")}function No(t,e,s,i,r){const n={};let a=!1;const o=function(t){const e=t.byteLength,s=[];for(let i=0;i<e;){const r=i+8<=e,n=i+4<=e?16777216*t[i]+(t[i+1]<<16|t[i+2]<<8|t[i+3]):mo(t,i),a=n>1?i+n:e;if(r&&109===t[i+4]&&111===t[i+5]&&111===t[i+6]&&102===t[i+7]){const r=Math.min(a,e);for(let e=i+8;e<r;){const n=e+8<=r,a=e+4<=r?16777216*t[e]+(t[e+1]<<16|t[e+2]<<8|t[e+3]):mo(t,e),o=a>1?e+a:r;if(n&&116===t[e+4]&&114===t[e+5]&&97===t[e+6]&&102===t[e+7]){const n=Math.min(o,r);let a,l;const d=[];for(let s=e+8;s<n;){const e=s+8<=n,i=s+4<=n?16777216*t[s]+(t[s+1]<<16|t[s+2]<<8|t[s+3]):mo(t,s),r=i>1?s+i:n;if(e&&116===t[s+4]){const e=Math.min(r,n);102===t[s+5]&&104===t[s+6]&&100===t[s+7]?l||(l=t.subarray(s+8,e)):102===t[s+5]&&100===t[s+6]&&116===t[s+7]?a||(a=t.subarray(s+8,e)):114===t[s+5]&&117===t[s+6]&&110===t[s+7]&&d.push(t.subarray(s+8,e))}s=r}s.push({moofOffset:t.byteOffset+i,tfdt:a,tfhd:l,truns:d})}e=o}}i=a}return s}(t),l=t.byteLength;for(let h=0;h<o.length;h++){const{moofOffset:u,tfdt:f,tfhd:g,truns:p}=o[h],m=mo(g,4),v=e[m];if(!v)continue;const y=n[m]||(n[m]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:v.timescale,type:v.type});let E;if(f){const t=f[0];E=mo(f,4),1===t&&(E===uo?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(E*=uo+1,E+=mo(f,8))),Vn(E)&&(!Vn(y.start)||E<y.start)&&(y.start=E),r&&Vn(E)&&(r.timeOffset=E/r.timescale)}const T=(null==r?void 0:r.trackId)===m&&v.type===fa,S=v.default,A=16777215&mo(g,0);let _,b=(null==S?void 0:S.duration)||0,L=(null==S?void 0:S.sampleSize)||0,R=8;1&A&&(R+=8),2&A&&(R+=4),8&A&&(b=mo(g,R),_=g.byteOffset-t.byteOffset+R,R+=4),16&A&&(L=mo(g,R));let I=0;const k=!!(1&A),w=!k&&!!(131072&A);k?(I=mo(g,8),I*=Math.pow(2,32),I+=mo(g,12)):w&&(I=u);let P=E||0,D=0,C=b;for(let e=0;e<p.length;e++){const s=p[e],n=mo(s,4),a=y.sampleCount;y.sampleCount+=n;const o=1&s[3];let h=0;const u=4&s[3],f=1&s[2],g=2&s[2],m=4&s[2],v=8&s[2];let E=8;if(o&&(h=Eo(s,E),E+=4),u){1&s[E+1]||void 0!==y.keyFrameIndex||(y.keyFrameIndex=a),E+=4}let S,A,R,k=I+h;if(!i&&0===s[1]&&6===s[2]&&1===s[3]){var d,c;const e=P,i=k,a=E;let o=-1,h=0,u=0,f=null!=(d=null==r?void 0:r.timeOffset)?d:0;const g=b/(null!=(c=null==r?void 0:r.timescale)?c:1),p=!0===(null==r?void 0:r.isHEVCFlavor),m=p?2:1;for(let e=0;e<n;e++){const i=0===s[E]?s[E+1]<<16|s[E+2]<<8|s[E+3]:mo(s,E),n=-1===o&&void 0===y.keyFrameIndex&&!(1&s[E+5]);E+=8;const a=k+i;if(T){if(i>0){let e=k;do{const s=0===t[e]?t[e+1]<<16|t[e+2]<<8|t[e+3]:mo(t,e);e+=4;const i=t[e],n=p?i>>1&63:31&i;(p?39===n||40===n:6===n)&&Go(t.subarray(e,e+s),m,f,r.samples),e+=s}while(e<a)}f+=g}k=a,n&&(o=e,h=k)}if(k<=l)u=n;else{let t=i,e=a;for(let i=0;i<n;i++){if(t+=0===s[e]?s[e+1]<<16|s[e+2]<<8|s[e+3]:mo(s,e),t>l)break;u=i+1,e+=8}}if(T&&(r.timeOffset=f),-1!==o&&h<=l&&void 0===y.keyFrameIndex&&(y.keyFrameIndex=o,y.keyFrameStart=e+o*b),u){(!Vn(y.ptsMin)||e<y.ptsMin)&&(y.ptsMin=e);const t=e+u*b;(!Vn(y.ptsMax)||t>y.ptsMax)&&(y.ptsMax=t)}const v=b*n;P=e+v,D+=v;continue}i&&(S=[],A={sampleOffset:k,samples:S,defaultSampleDurationOffset:_},k<=l&&y.trun.push(A));for(let e=0;e<n;e++){let n,a,o;f?(i&&(n=s.byteOffset-t.byteOffset+E),C=mo(s,E),E+=4):C=b,g?(R=mo(s,E),E+=4):R=L,m&&(o=1&s[E+1]?1:0,i&&(a={isNonSync:o,dependsOn:1==(3&s[E])?1:2}),E+=4);let d=0;if(v){d=0===s[0]?mo(s,E):Eo(s,E),E+=4}if(T){let e=k,s=0;for(;s<R;){const i=mo(t,e);e+=4,$o(r.isHEVCFlavor,t[e])&&Go(t.subarray(e,e+i),r.isHEVCFlavor?2:1,r.timeOffset+d/r.timescale,r.samples),e+=i,s+=i+4}r.timeOffset+=C/r.timescale}if(k+=R,k<=l){A&&void 0!==n&&(A.lastSampleDurationOffset=n),0===o&&void 0===y.keyFrameIndex&&(y.keyFrameIndex=e,y.keyFrameStart=P);const t=P+d;(!Vn(y.ptsMin)||t<y.ptsMin)&&(y.ptsMin=t),(!Vn(y.ptsMax)||t+C>y.ptsMax)&&(y.ptsMax=t+C),S&&(S[e]={cts:d,duration:C,flags:a,size:R})}P+=C,D+=C}!D&&b&&(D+=b*n)}y.duration+=D,y.duration&&(a=!0)}if(!a){let e=1/0,s=0;const i=bo(t,["sidx"]);for(let t=0;t<i.length;t++){const r=Ro(i[t]);if(null!=r&&r.references){e=Math.min(e,r.earliestPresentationTime/r.timescale);const t=r.references.reduce((t,e)=>t+e.info.duration||0,0);s=Math.max(s,t+r.earliestPresentationTime/r.timescale)}}s&&Vn(s)&&Object.keys(n).forEach(t=>{n[t].duration||(n[t].duration=s*n[t].timescale-n[t].start)})}return n}function Uo(t,e){const s=new Uint8Array(t.length+e.length);return s.set(t),s.set(e,t.length),s}function Bo(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function $o(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function Go(t,e,s,i){const r=Ho(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const t=r.length-n;let e=n;if(o<t)n+=o;else if(o>t){Ua.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=po(r,e);if(e+=2,49===t){const t=mo(r,e);if(e+=4,1195456820===t){const t=r[e++];if(3===t){const n=r[e++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let t=1;t<l;t++)d[t]=r[e++]}i.push({type:t,payloadType:a,pts:s,bytes:d})}}}}}else if(5===a&&o>16){const t=[];for(let s=0;s<16;s++){const i=r[e++].toString(16);t.push(1==i.length?"0"+i:i),3!==s&&5!==s&&7!==s&&9!==s||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=r[e++];i.push({payloadType:a,pts:s,uuid:t.join(""),userData:Fo(l),userDataBytes:l})}}}function Ho(t){const e=t.byteLength;let s,i=t.indexOf(3,3);for(;-1!==i;)0===t[i-1]&&0===t[i-2]&&(s||(s=[])).push(i),i=t.indexOf(3,i+1);if(!s)return t;const r=e-s.length,n=new Uint8Array(r);let a=0,o=0;for(let e=0;e<r;o++,e++)o===s[a]&&(o++,a++),n[e]=t[o];return n}function Ko(t,e,s){if(16!==t.byteLength)throw new RangeError("Invalid system id");let i,r,n;i=0,r=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),function(t,...e){const s=e.length;let i=8,r=s;for(;r--;)i+=e[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(t,4),r=0,i=8;r<s;r++)n.set(e[r],i),i+=e[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),t,n,r,a,s)}function Vo(t){const e=[];if(t instanceof ArrayBuffer){const s=t.byteLength;let i=0;for(;i+32<s;){const s=jo(new DataView(t,i));e.push(s),i+=s.size}}return e}function jo(t){const e=t.getUint32(0),s=t.byteOffset,i=t.byteLength;if(i<e)return{offset:s,size:i};if(1886614376!==t.getUint32(4))return{offset:s,size:e};const r=t.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:s,size:e};const n=t.buffer,a=oo(new Uint8Array(n,s+12,16));let o=null,l=null,d=0;if(0===r)d=28;else{const r=t.getUint32(28);if(!r||i<32+16*r)return{offset:s,size:e};o=[];for(let t=0;t<r;t++)o.push(new Uint8Array(n,s+32+16*t,16));d=32+16*r}if(!d)return{offset:s,size:e};const c=t.getUint32(d);return e-32<c?{offset:s,size:e}:(l=new Uint8Array(n,s+d+4,c),0===r&&(o=function(t){const e=[];for(let s=0;s<t.length;){const i=t[s++],r=7&i;if(0===r){for(;128&t[s++];);continue}if(2!==r){s+=1===r?8:4;continue}let n=0;for(let e=0,i=128;128&i;e+=7)n|=(127&(i=t[s++]))<<e;if(i>>3==2)if(32===n){const i=new Uint8Array(16);for(let e=0;e<16;e++)i[e]=parseInt(String.fromCharCode(t[s+2*e],t[s+2*e+1]),16);e.push(i)}else 16===n&&e.push(t.subarray(s,s+16));s+=n}return e}(l)),{version:r,systemId:a,kids:o,data:l,offset:s,size:e})}const qo=Xo("userAgent"),Wo=Xo("vendor");let Yo,zo,Qo;function Xo(t){try{return navigator[t]||""}catch(t){}return""}function Zo(){if(void 0===Yo){const t=qo.match(/Chrome\/(\d+)/i);Yo=t?parseInt(t[1]):0}return Yo}function Jo(){return/\(Windows.+Firefox\//i.test(qo)}const tl={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function el(t,e){const s=tl[e];return!!s&&!!s[t.slice(0,4)]}function sl(t,e,s=!0){return!t.split(",").some(t=>!il(t,e,s))}function il(t,e,s=!0){var i;const r=Ba(s);return null!=(i=null==r?void 0:r.isTypeSupported(rl(t,e)))&&i}function rl(t,e){return`${e}/mp4;codecs=${t}`}function nl(t){if(t){const e=t.substring(0,4);return tl.video[e]}return 2}function al(t){const e=Jo();return t.split(",").reduce((t,s)=>{const i=e&&Bo(s)?9:tl.video[s];return i?(2*i+t)/(t?3:2):(tl.audio[s]+t)/(t?2:1)},0)}const ol={};const ll=/flac|opus|mp4a\.40\.34/i;function dl(t,e=!0){return t.replace(ll,t=>function(t,e=!0){if(ol[t])return ol[t];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let r=0;r<s.length;r++){var i;if(il(s[r],"audio",e))return ol[t]=s[r],s[r];if("mp3"===s[r]&&null!=(i=Ba(e))&&i.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e))}function cl(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(hl(t,"audio")||hl(t,"video")))return t;if(e){const s=e.split(",");if(s.length>1){if(t)for(let e=s.length;e--;)if(s[e].substring(0,4)===t.substring(0,4))return s[e];return s[0]}}return e||t}function hl(t,e){return el(t,e)&&il(t,e)}function ul(t){if(t.startsWith("av01.")){const e=t.split("."),s=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=s[t-4];return e.join(".")}return t}function fl(t){const e=Ba(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function gl(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const pl={supported:!1,smooth:!1,powerEfficient:!1},ml={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function vl(t,e){return{supported:!1,configurations:e,decodingInfoResults:[pl],error:t}}function yl(t,e,s,i,r,n){const a=t.videoCodec,o=t.audioCodec?t.audioGroups:null,l=null==n?void 0:n.audioCodec,d=null==n?void 0:n.channels,c=d?parseInt(d):l?1/0:2;let h=null;if(null!=o&&o.length)try{h=1===o.length&&o[0]?e.groups[o[0]].channels:o.reduce((t,s)=>{if(s){const i=e.groups[s];if(!i)throw new Error(`Audio track group ${s} not found`);Object.keys(i.channels).forEach(e=>{t[e]=(t[e]||0)+i.channels[e]})}return t},{2:0})}catch(t){return!0}return void 0!==a&&(a.split(",").some(t=>Bo(t))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(i,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(r,8e6))||!!h&&Vn(c)&&Object.keys(h).some(t=>parseInt(t)>c)}function El(t,e,s,i={}){const r=t.videoCodec;if(!r&&!t.audioCodec||!s)return Promise.resolve(ml);const n=[],a=function(t){var e;const s=null==(e=t.videoCodec)?void 0:e.split(","),i=Sl(t),r=t.width||640,n=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return s?s.map(t=>{const e={contentType:rl(ul(t),"video"),width:r,height:n,bitrate:i,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e}):[]}(t),o=a.length,l=function(t,e,s){var i;const r=null==(i=t.audioCodec)?void 0:i.split(","),n=Sl(t);if(r&&t.audioGroups)return t.audioGroups.reduce((t,i)=>{var a;const o=i?null==(a=e.groups[i])?void 0:a.tracks:null;return o?o.reduce((t,e)=>{if(e.groupId===i){const i=parseFloat(e.channels||"");r.forEach(e=>{const r={contentType:rl(e,"audio"),bitrate:s?Tl(e,n):n};i&&(r.channels=""+i),t.push(r)})}return t},t):t},[]);return[]}(t,e,o>0),d=l.length;for(let t=o||1*d||1;t--;){const e={type:"media-source"};if(o&&(e.video=a[t%o]),d){e.audio=l[t%d];const s=e.audio.bitrate;e.video&&s&&(e.video.bitrate-=s)}n.push(e)}if(r){const t=navigator.userAgent;if(r.split(",").some(t=>Bo(t))&&Jo())return Promise.resolve(vl(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),n))}return Promise.all(n.map(t=>{const e=function(t){let e="";const{audio:s,video:i}=t;if(i){e+=`${gl(i.contentType)}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(s){e+=`${i?"_":""}${gl(s.contentType)}_c${s.channels}`}return e}(t);return i[e]||(i[e]=s.decodingInfo(t))})).then(t=>({supported:!t.some(t=>!t.supported),configurations:n,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:n,decodingInfoResults:[],error:t}))}function Tl(t,e){if(e<=1)return 1;let s=128e3;return"ec-3"===t?s=768e3:"ac-3"===t&&(s=64e4),Math.min(e/2,s)}function Sl(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}function Al(t,e,s){const i=encodeURIComponent(e),r=`${i}=${encodeURIComponent(s)}`;let n=!1;const a=[];t.search.substring(1).split("&").forEach(t=>{t===i||t.startsWith(i+"=")?n||(a.push(r),n=!0):t&&a.push(t)}),n||a.push(r),t.search=a.join("&")}const _l=["NONE","TYPE-0","TYPE-1",null];const bl=["SDR","PQ","HLG"];var Ll="",Rl="YES",Il="v2";function kl(t){const{canSkipUntil:e,canSkipDateRanges:s,age:i}=t;return e&&i<e/2?s?Il:Rl:Ll}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&&Al(e,"_HLS_msn",this.msn.toString()),void 0!==this.part&&Al(e,"_HLS_part",this.part.toString()),this.skip&&Al(e,"_HLS_skip",this.skip),e.href}}class Level{constructor(t){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[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.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,"imageCodec"in t&&(this.imageCodec=t.imageCodec),this.codecSet=[t.videoCodec,t.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const s=null==(e=t.supplemental)?void 0:e.videoCodec;s&&s!==t.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}"iframes"in t&&t.iframes?this.iframes=!0:(this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return wl(this._audioGroups,t)}hasSubtitleGroup(t){return wl(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function wl(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function Pl(t,e){let s=!1,i=[];if(t&&(s="SDR"!==t,i=[t]),e){i=e.allowedVideoRanges||bl.slice(0);const t="SDR"!==i.join("")&&!e.videoCodec;s=void 0!==e.preferHDR?e.preferHDR:t&&function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),s||(i=["SDR"])}return{preferHDR:s,allowedVideoRanges:i}}const Dl=(t,e)=>JSON.stringify(t,(t=>{const e=new WeakSet;return(s,i)=>{if(t&&(i=t(s,i)),"object"==typeof i&&null!==i){if(e.has(i))return;e.add(i)}return i}})(e));function Cl(t,e){Ua.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function Ol(t){return t.reduce((t,e)=>{let s=t.groups[e.groupId];s||(s=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(e);const i=e.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||e.default,s.hasAutoSelect=s.hasAutoSelect||e.autoselect,s.hasDefault&&(t.hasDefaultAudio=!0),s.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Ml(t){if(!t)return t;const{lang:e,assocLang:s,characteristics:i,channels:r,audioCodec:n}=t;return{lang:e,assocLang:s,characteristics:i,channels:r,audioCodec:n}}function xl(t,e,s){if("attrs"in t){const s=e.indexOf(t);if(-1!==s)return s}for(let i=0;i<e.length;i++){if(Fl(t,e[i],s))return i}return-1}function Fl(t,e,s){const{groupId:i,name:r,lang:n,assocLang:a,default:o}=t,l=t.forced;return(void 0===i||e.groupId===i)&&(void 0===r||e.name===r)&&(void 0===n||function(t,e="--"){if(t.length===e.length)return t===e;return t.startsWith(e)||e.startsWith(t)}(n,e.lang))&&(void 0===n||e.assocLang===a)&&(void 0===o||e.default===o)&&(void 0===l||e.forced===l)&&(!("characteristics"in t)||function(t,e=""){const s=t.split(","),i=e.split(",");return s.length===i.length&&!s.some(t=>-1===i.indexOf(t))}(t.characteristics||"",e.characteristics))&&(void 0===s||s(t,e))}function Nl(t,e){const{audioCodec:s,channels:i}=t;return!(void 0!==s&&(e.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==i&&i!==(e.channels||"2"))}function Ul(t,e,s){for(let i=e;i>-1;i--)if(s(t[i]))return i;for(let i=e+1;i<t.length;i++)if(s(t[i]))return i;return-1}function Bl(t,e){var s;return!!t&&t!==(null==(s=e.loadLevelObj)?void 0:s.uri)}function $l(t,e){return!e||-1!==e.indexOf(t)}function Gl(t,e){if(e||t){const s=Ta({},e);return t&&(t.videoCodec&&(s.videoCodec=t.videoCodec),t.videoRange&&(s.allowedVideoRanges=[t.videoRange])),s}}const Hl=function(t,e){let s=0,i=t.length-1,r=null,n=null;for(;s<=i;){r=(s+i)/2|0,n=t[r];const a=e(n);if(a>0)s=r+1;else{if(!(a<0))return n;i=r-1}}return null};function Kl(t,e,s=0,i=0,r=.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;const i=t.endDTS-s;i>0&&i<15e-7&&(s+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===s&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===Vl(s,i,n)||function(t,e,s){if(0===(null==e?void 0:e.start)&&e.level<t.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t),s);return t.start<=i}return!1}(n,t,Math.min(r,i))))return n;const a=Hl(e,Vl.bind(null,s,i));return!a||a===t&&n?n:a}function Vl(t=0,e=0,s){if(s.start<=t&&s.start+s.duration>t)return 0;const i=Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-i<=t?1:s.start-i>t&&s.start?-1:0}function jl(t,e,s){const i=1e3*Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-i>t}function ql(t,e,s){if(t&&t.startCC<=e&&t.endCC>=e){let i=t.fragments;const{fragmentHint:r}=t;let n;return r&&(i=i.concat(r)),Hl(i,t=>t.cc<e?1:t.cc>e?-1:(n=t,t.end<=s?1:t.start>s?-1:0)),n||null}return null}function Wl(t,e){return e===t.endSN&&t.fragmentHint?t.fragmentHint:t.fragments[1+e-t.startSN]||null}var Yl=0,zl=2,Ql=3,Xl=5,Zl=0,Jl=1,td=2,ed=4,sd=8,id=16;function rd(t){const e=t.details;return e===Yn.BUFFER_ADD_CODEC_ERROR||e===Yn.MEDIA_SOURCE_REQUIRES_RESET||e===Yn.BUFFER_APPEND_ERROR&&!nd(t)}function nd(t){return t.details===Yn.BUFFER_APPEND_ERROR&&("QuotaExceededError"===t.error.name||"InvalidStateError"===t.error.name)}function ad(t){const e={action:Yl,flags:Zl};return t&&(e.resolved=!0),e}var od="NOT_LOADED",ld="APPENDING",dd="PARTIAL",cd="OK";class FragmentTracker{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t&&(t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.BUFFER_APPENDED,this.onBufferAppended,this),t.on(zn.FRAG_BUFFERED,this.onFragBuffered,this),t.on(zn.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.BUFFER_APPENDED,this.onBufferAppended,this),t.off(zn.FRAG_BUFFERED,this.onFragBuffered,this),t.off(zn.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const s=this.activePartLists[e];if(s)for(let e=s.length;e--;){const i=s[e];if(!i)break;if(i.start<=t&&t<=i.end&&i.loaded)return i}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const a=i[r[n]];if((null==a?void 0:a.body.type)===e&&(!s||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,s,i,r,n){this.timeRanges&&(this.timeRanges[t]=e);const a=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(r=>{const o=this.fragments[r];if(!o||!this.hls)return;const l=o.body;if(a>=l.sn)return;if(!o.buffered&&(!o.loaded||n))return void(l.type===s&&this.removeFragment(l));const d=o.range[t];if(d)if(0!==d.time.length){if(d.time.some(t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return s&&this.removeFragment(l),s}),i&&i!==l&&Zo()){const t=i.endPTS,e=l.startPTS;if(t&&e&&o.range.video){const s=e-t;s<0&&s>-.1&&(this.removeFragment(l),this.hls.trigger(zn.BUFFER_FLUSHING,{startOffset:t+.004,endOffset:1/0,type:"video"}))}}}else this.removeFragment(l)})}detectPartialFragments(t){const e=this.timeRanges,{frag:s,part:i,id:r}=t;if(!e||!pa(s))return;const n=ud(s),a=this.fragments[n];if(!a||a.buffered&&s.gap)return;const o=!s.relurl;Object.keys(e).forEach(t=>{const n=s.elementaryStreams[t];if(!n)return;const l=e[t],d=o||!0===n.partial;a.range[t]=this.getBufferedTimes(s,i,d,l),this.detectEvictedFragments(t,l,r,s,i)}),a.loaded=null;const l=Object.keys(a.range);if(l.length){if(this.bufferedEnd(a,s),hd(a)||this.removeParts(s.sn-1,s.type),!i){const t=Math.min(.004,s.duration);l.some(e=>{var i;const r=null==(i=a.range[e])?void 0:i.time,n=0===r.length||1===r.length&&r[0].endPTS-r[0].startPTS<t;return n&&this.addAsGap(s),n})}}else this.removeFragment(s)}addAsGap(t){t.gap=!0,this.removeFragment(t),this.fragBuffered(t,!0)}bufferedEnd(t,e){t.buffered=!0;(t.body.endList=e.endList||t.body.endList)&&!e.gap&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const s=this.activePartLists[e];s&&(this.activePartLists[e]=fd(s,e=>e.fragment.sn>=t))}fragBuffered(t,e){const s=ud(t);let i=this.fragments[s];return!i&&e&&(i=this.fragments[s]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,t)),i}getBufferedTimes(t,e,s,i){const r={time:[],partial:s},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<i.length;t++){const e=i.start(t)-this.bufferPadding,s=i.end(t)+this.bufferPadding;if(l>=e&&o<=s){r.time.push({startPTS:Math.max(n,i.start(t)),endPTS:Math.min(a,i.end(t))});break}if(n<s&&a>e){const e=Math.max(n,i.start(t)),s=Math.min(a,i.end(t));s>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:s}))}else if(a<=e)break}return r}getPartialFragment(t){let e,s,i,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&hd(d)&&(s=d.body.start-a,i=d.body.end+a,t>=s&&t<=i&&(e=Math.min(t-s,i-t),n<=e&&(r=d.body,n=e)))}),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||hd(e))}getState(t){const e=ud(t),s=this.fragments[e];return s?s.buffered?hd(s)?dd:cd:ld:od}isTimeBuffered(t,e,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,t>=i&&e<=r)return!0;if(e<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if(!pa(e.frag)||e.frag.bitrateTest)return;const s=e.frag,i=e.part?null:e,r=ud(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:s,part:i,timeRanges:r}=e;if(!pa(s))return;const n=s.type;if(i){let t=this.activePartLists[n];t||(this.activePartLists[n]=t=[]),t.push(i)}this.timeRanges=r}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=ud(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,s=Object.keys(e);if(!t)return s.length>0;for(let i=s.length;i--;){const r=e[s[i]];if((null==r?void 0:r.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}getBackBufferEvictionEnd(t,e,s){const{fragments:i}=this;let r=0,n=0;const a=Object.keys(i);for(let o=0;o<a.length;o++){const l=i[a[o]];if(!l||!l.buffered||l.body.type!==e)continue;const d=l.body;if(d.gap)return 0;const c=d.hasStats&&d.stats.loaded||d.byteLength||d.bitrate&&8*d.bitrate*d.duration;if(d.end<=t&&c&&(r+=c,n=Math.max(n,d.end),r>=s))return n}return n>0?n:0}removeFragmentsInRange(t,e,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||i&&!o.gap||o.start<e&&o.end>t&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(t){const e=ud(t);t.clearElementaryStreamInfo();const s=this.activePartLists[t.type];if(s){const e=t.sn;this.activePartLists[t.type]=fd(s,t=>t.fragment.sn!==e)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach(t=>t.clearElementaryStreamInfo())}}function hd(t){var e,s,i,r;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(s=t.range.audio)&&s.partial||null!=(i=t.range.audiovideo)&&i.partial||null!=(r=t.range.subs)&&r.partial)}function ud(t){return`${t.type}_${t.level}_${t.sn}`}function fd(t,e){return t.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var gd=0,pd=1;class AESCrypto{constructor(t,e,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=s}decrypt(t,e){switch(this.aesMode){case gd:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case pd:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}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,i=s[0],r=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],d=o[1],c=o[2],h=o[3],u=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)u[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=u[f],p=u[o],m=u[p];let v=257*u[s]^16843008*s;i[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*m^65537*p^257*o^16843008*f,l[s]=v<<24|v>>>8,d[s]=v<<16|v>>>16,c[s]=v<<8|v>>>24,h[s]=v,f?(f=o^u[u[u[m^o]]],g^=u[u[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let s=!0,i=0;for(;i<e.length&&s;)s=e[i]===this.key[i],i++;if(s)return;this.key=e;const r=this.keySize=e.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),c=this.sBox,h=this.rcon,u=this.invSubMix,f=u[0],g=u[1],p=u[2],m=u[3];let v,y;for(a=0;a<n;a++)a<r?v=l[a]=e[a]:(y=v,a%r===0?(y=y<<8|y>>>24,y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y],y^=h[a/r|0]<<24):r>6&&a%r===4&&(y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?y:f[c[y>>>24]]^g[c[y>>>16&255]]^p[c[y>>>8&255]]^m[c[255&y]],d[o]=d[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],c=a[3],h=this.uint8ArrayToUint32Array_(s);let u=h[0],f=h[1],g=h[2],p=h[3];const m=new Int32Array(t),v=new Int32Array(m.length);let y,E,T,S,A,_,b,L,R,I,k,w,P,D;const C=this.networkToHostOrderSwap;for(;e<m.length;){for(R=C(m[e]),I=C(m[e+1]),k=C(m[e+2]),w=C(m[e+3]),A=R^r[0],_=w^r[1],b=k^r[2],L=I^r[3],P=4,D=1;D<i;D++)y=o[A>>>24]^l[_>>16&255]^d[b>>8&255]^c[255&L]^r[P],E=o[_>>>24]^l[b>>16&255]^d[L>>8&255]^c[255&A]^r[P+1],T=o[b>>>24]^l[L>>16&255]^d[A>>8&255]^c[255&_]^r[P+2],S=o[L>>>24]^l[A>>16&255]^d[_>>8&255]^c[255&b]^r[P+3],A=y,_=E,b=T,L=S,P+=4;y=n[A>>>24]<<24^n[_>>16&255]<<16^n[b>>8&255]<<8^n[255&L]^r[P],E=n[_>>>24]<<24^n[b>>16&255]<<16^n[L>>8&255]<<8^n[255&A]^r[P+1],T=n[b>>>24]<<24^n[L>>16&255]<<16^n[A>>8&255]<<8^n[255&_]^r[P+2],S=n[L>>>24]<<24^n[A>>16&255]<<16^n[_>>8&255]<<8^n[255&b]^r[P+3],v[e]=C(y^u),v[e+1]=C(S^f),v[e+2]=C(T^g),v[e+3]=C(E^p),u=R,f=I,g=k,p=w,e+=4}return v.buffer}}class FastAESKey{constructor(t,e,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=s}expandKey(){const t=function(t){switch(t){case gd:return"AES-CBC";case pd:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}class Decrypter{constructor(t,e){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,!0!==e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const s=new Uint8Array(t);this.reset();const i=this.decryptRange;return i?0===i.start&&i.end>=s.length?s:s.slice(i.start,i.end):function(t){const e=t.byteLength,s=e&&new DataView(t.buffer).getUint8(e-1);return s?t.slice(0,e-s):t}(s)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,s,i,r){return this.decryptRange=r,this.useSoftware||r?new Promise((r,n)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,s,i);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,s,i)}softwareDecrypt(t,e,s,i){const{currentIV:r,currentResult:n,remainderData:a}=this;if(i!==gd||16!==e.byteLength)return Ua.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=Uo(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new AESDecryptor),l.expandKey(e);const d=n;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(t,e,s,i){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,s,i));this.key=e,this.fastAesKey=new FastAESKey(this.subtle,e,i)}return this.fastAesKey.expandKey().then(e=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new AESCrypto(this.subtle,new Uint8Array(s),i).decrypt(t.buffer,e)}).catch(r=>(Ua.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,s,i)))}onWebCryptoError(t,e,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,s,i);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const s=t.length-t.length%16;return s!==t.length&&(e=t.slice(0,s),this.remainderData=t.slice(s)),e}logOnce(t){this.logEnabled&&(Ua.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const md=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,s,i){const r=t.url;if(!r)return Promise.reject(new LoadError({type:Wn.NETWORK_ERROR,details:Yn.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();const n=this.config,a=n.fLoader,o=n.loader;return new Promise((l,d)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some(t=>"GAP"===t[0]))return void d(Ed(t));t.gap=!1}const c=this.loader=a?new a(n):new o(n),h=vd(t,null,e);t.loader=c;const u=wa(n.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:md};c.stats.retry=t.stats.retry,t.stats=c.stats;const g={onSuccess:(e,s,i,r)=>{this.resetLoader(t,c);let n=e.data;i.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),l({frag:t,part:null,payload:n,networkDetails:r})},onError:(e,s,i,n)=>{this.resetLoader(t,c),d(new LoadError({type:Wn.NETWORK_ERROR,details:Yn.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:Aa({url:r,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:i,stats:n}))},onAbort:(e,s,i)=>{this.resetLoader(t,c),d(new LoadError({type:Wn.NETWORK_ERROR,details:Yn.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:i,stats:e}))},onTimeout:(e,s,i)=>{this.resetLoader(t,c),d(new LoadError({type:Wn.NETWORK_ERROR,details:Yn.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:i,stats:e}))}};if(s){const e=this.gateProgress(s,i);g.onProgress=(s,i,r,n)=>e({frag:t,part:null,payload:r,networkDetails:n})}c.load(h,f,g)})}gateProgress(t,e){let s=t;if(e){const i=[];let r=!1;e.then(()=>{r=!0,i.forEach(e=>t(e)),i.length=0}).catch(()=>{}),s=e=>{r?t(e):i.push(e)}}return s}loadPart(t,e,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(Ed(t,e));const l=this.loader=r?new r(i):new n(i),d=vd(t,e);t.loader=l;const c=wa(i.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:md};e.stats=l.stats,l.load(d,h,{onSuccess:(i,r,n,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const d={frag:t,part:e,payload:i.data,networkDetails:o};s(d),a(d)},onError:(s,i,r,n)=>{this.resetLoader(t,l),o(new LoadError({type:Wn.NETWORK_ERROR,details:Yn.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:Aa({url:d.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:r,stats:n}))},onAbort:(s,i,r)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new LoadError({type:Wn.NETWORK_ERROR,details:Yn.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:r,stats:s}))},onTimeout:(s,i,r)=>{this.resetLoader(t,l),o(new LoadError({type:Wn.NETWORK_ERROR,details:Yn.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:r,stats:s}))}})})}updateStatsFromPart(t,e){const s=t.stats,i=e.stats,r=i.total;if(s.loaded+=i.loaded,r){const i=Math.round(t.duration/e.duration),n=Math.min(Math.round(s.loaded/r),i),a=(i-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=i.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,t.url=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function vd(t,e=null,s){const i={type:ra,frag:t,part:e,responseType:"arraybuffer",url:(e||t).url,headers:{},rangeStart:0,rangeEnd:0},r=yd(t,e,s);return r.resetIV&&(i.resetIV=!0),r.byteRange&&(i.rangeStart=r.byteRange.start,i.rangeEnd=r.byteRange.end),i}function yd(t,e=null,s){const i={},r=e||t,n=r.byteRangeStartOffset,a=r.byteRangeEndOffset;var o,l;if(Vn(n)&&Vn(a))if("initSegment"!==t.sn&&!s||"AES-128"!==(l=null==(o=t.decryptdata)?void 0:o.method)&&"AES-256"!==l)i.byteRange={start:n,end:a};else{let t=16*Math.floor(n/16);const e=16*Math.ceil(a/16);i.decryptRange={start:n-t,end:a-t},t>=16&&(i.resetIV=!0,t-=16),i.byteRange={start:t,end:e}}return i}function Ed(t,e){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),i={type:Wn.MEDIA_ERROR,details:Yn.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return e&&(i.part=e),(e||t).stats.aborted=!0,new LoadError(i)}class LoadError extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class TaskLoop extends Logger{constructor(t,e){super(t,e),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):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class ChunkMetadata{constructor(t,e,s,i=0,r=-1,n=!1,a,o,l){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.iframe=void 0,this.duration=void 0,this.decryptRange=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=i,this.part=r,this.partial=n,this.duration=a||0,this.decryptRange=l,this.iframe=o||!1}}const Td={length:0,start:()=>0,end:()=>0};class BufferHelper{static isBuffered(t,e){if(t){const s=BufferHelper.getBuffered(t);for(let t=s.length;t--;)if(e>=s.start(t)&&e<=s.end(t))return!0}return!1}static bufferedRanges(t){if(t){const e=BufferHelper.getBuffered(t);return BufferHelper.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let s=0;s<t.length;s++)e.push({start:t.start(s),end:t.end(s)});return e}static bufferInfo(t,e,s){if(t){const i=BufferHelper.bufferedRanges(t);if(i.length)return BufferHelper.bufferedInfo(i,e,s)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,s){e=Math.max(0,e),t.length>1&&t.sort((t,e)=>t.start-e.start||e.end-t.end);let i=-1,r=[];if(s)for(let n=0;n<t.length;n++){e>=t[n].start&&e<=t[n].end&&(i=n);const a=r.length;if(a){const e=r[a-1].end;t[n].start-e<s?t[n].end>e&&(r[a-1].end=t[n].end):r.push(t[n])}else r.push(t[n])}else r=t;let n,a=0,o=e,l=e;for(let t=0;t<r.length;t++){const d=r[t].start,c=r[t].end;if(-1===i&&e>=d&&e<=c&&(i=t),e+s>=d&&e<c)o=d,l=c,a=l-e;else if(e+s<d){n=d;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:t,bufferedIndex:i}}static getBuffered(t){try{return t.buffered||Td}catch(t){return Ua.log("failed to get media.buffered",t),Td}}}const Sd=/\{\$([a-zA-Z0-9-_]+)\}/g;function Ad(t){return Sd.lastIndex=0,Sd.test(t)}function _d(t,e){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return e.replace(Sd,e=>{const i=e.substring(2,e.length-1),r=null==s?void 0:s[i];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),e):r})}return e}function bd(t,e,s){let i,r,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){i=e.QUERYPARAM;try{const t=new self.URL(s).searchParams;if(!t.has(i))throw new Error(`"${i}" does not match any query parameter in URI: "${s}"`);r=t.get(i)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else i=e.NAME,r=e.VALUE;i in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=r||""}function Ld(t,e,s){const i=e.IMPORT;if(s&&i in s){let e=t.variableList;e||(t.variableList=e={}),e[i]=s[i]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const Rd=/^(\d+)x(\d+)$/,Id=/(.+?)=(".*?"|.*?)(?:,|$)/g;class AttrList{constructor(t,e){"string"==typeof t&&(t=AttrList.parseAttrList(t,e)),Ta(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>"X-"===t.substring(0,2))}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]}enumeratedStringList(t,e){const s=this[t];return(s?s.split(/[ ,]+/):[]).reduce((t,e)=>(t[e.toLowerCase()]=!0,t),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=Rd.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let s;const i={};for(Id.lastIndex=0;null!==(s=Id.exec(t));){const r=s[1].trim();let n=s[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(a||o))n=_d(e,n);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Ua.warn(`${t}: attribute ${r} is missing quotes`)}i[r]=n}return i}}function kd(t){return"ID"!==t&&"CLASS"!==t&&"CUE"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function wd(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class DateRange{constructor(t,e,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==e?void 0:e.tagAnchor)||null,this.tagOrder=null!=(i=null==e?void 0:e.tagOrder)?i:s,e){const s=e.attr;for(const e in s)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==s[e]){Ua.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=Ta(new AttrList({}),s,t)}if(this.attr=t,e?(this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in t){const s=(null==e?void 0:e.endDate)||new Date(t["END-DATE"]);Vn(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(Ua.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(Vn(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 isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&Vn(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:Vn(this.startDate.getTime())?!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr?this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Interstitial Date range missing X-ASSET-(LIST|URI)":"Date range invalid start date":"Missing ID"}}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.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=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.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&s>0,this.updated||this.advanced?this.misses=0:this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(e=>{let s=e.decryptdata;return s||(e.setKeyFormat(t.keyFormat),s=e.decryptdata),!!s&&t.matches(s)})}get hasProgramDateTime(){return!!this.fragments.length&&Vn(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(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(-1!==e){for(let s=t.length;s--;)if(t[s].index>e)return t[s].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function Pd(t,e){return t.length===e.length&&!t.some((t,s)=>t!==e[s])}function Dd(t,e){return!t&&!e||!(!t||!e)&&Pd(t,e)}function Cd(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function Od(t){switch(t){case"AES-128":case"AES-256":return gd;case"AES-256-CTR":return pd;default:throw new Error(`invalid full segment method ${t}`)}}function Md(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}function xd(t){const e=function(t,e,s){const i=t[e];t[e]=t[s],t[s]=i};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function Fd(t){const e=t.split(":");let s=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),i=t[t.length-1].split(",");if(2===i.length){const e="base64"===i[0],r=i[1];e?(t.splice(-1,1),s=co(r)):s=function(t){const e=Md(t).subarray(0,16),s=new Uint8Array(16);return s.set(e,16-e.length),s}(r)}}return s}const Nd="undefined"!=typeof self?self:void 0;var Ud={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Bd="org.w3.clearkey",$d="com.apple.streamingkeydelivery",Gd="com.microsoft.playready",Hd="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Kd(t){switch(t){case $d:return Ud.FAIRPLAY;case Gd:return Ud.PLAYREADY;case Hd:return Ud.WIDEVINE;case Bd:return Ud.CLEARKEY}}var Vd="edef8ba979d64acea3c827dcd51d21ed";function jd(t){switch(t){case Ud.FAIRPLAY:return $d;case Ud.PLAYREADY:return Gd;case Ud.WIDEVINE:return Hd;case Ud.CLEARKEY:return Bd}}function qd(t){const{drmSystems:e,widevineLicenseUrl:s}=t,i=e?[Ud.FAIRPLAY,Ud.WIDEVINE,Ud.PLAYREADY,Ud.CLEARKEY].filter(t=>!!e[t]):[];return!i[Ud.WIDEVINE]&&s&&i.push(Ud.WIDEVINE),i}const Wd=null!=Nd&&null!=(Yd=Nd.navigator)&&Yd.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var Yd;function zd(t){const e=ho(new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2)),s=e.substring(e.indexOf("<"),e.length),i=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(i){const t=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(t){const e=co(t).subarray(0,16);return xd(e),e}}return null}let Qd={};class LevelKey{static clearKeyUriToKeyIdMap(){Qd={}}static setKeyIdForUri(t,e){Qd[t]=e}static addKeyIdForUri(t){const e=Object.keys(Qd).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,e),Qd[t]=s,s}constructor(t,e,s,i=[1],r=null,n){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.scheme=void 0,this.method=t,this.uri=e,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!Cd(t),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(lo(n)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&Pd(t.keyFormatVersions,this.keyFormatVersions)&&Dd(t.iv,this.iv)&&Dd(t.keyId,this.keyId)}isSupported(){if(this.method){if(Cd(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case $d:case Hd:case Gd:case Bd:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t,e){var s;if(!this.encrypted||!this.uri)return null;if(Cd(this.method)){let e=this.iv;e||("number"!=typeof t&&(Ua.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),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)}if(this.keyId){const t=Qd[this.uri];if(t&&!Pd(this.keyId,t)&&LevelKey.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=Fd(this.uri);if(i)switch(this.keyFormat){case Hd:if(this.pssh=i,!this.keyId){const t=Vo(i.buffer).filter(t=>t.systemId===Vd);if(t.length){var r;const e=t[0];this.keyId=null!=(r=e.kids)&&r.length?e.kids[0]:null}}this.keyId||(this.keyId=Xd(e));break;case Gd:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Ko(t,0,i),this.keyId=zd(i);break}default:{let t=i.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(16!==(null==(s=this.keyId)?void 0:s.byteLength)){let t;t=function(t){const e=null==t?void 0:t[Hd];if(e)return e.keyId;return null}(e),t||(t=Xd(e),t||(t=Qd[this.uri])),t&&(this.keyId=t,LevelKey.setKeyIdForUri(this.uri,t))}return this}}function Xd(t){const e=null==t?void 0:t[Gd];if(e){const t=Fd(e.uri);if(t)return zd(t)}return null}const Zd=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,Jd=/#EXT-X-MEDIA:(.*)/g,tc=/^#EXT(?:INF|-X-TARGETDURATION):/m,ec=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),sc=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class M3U8Parser{static findGroup(t,e){for(let s=0;s<t.length;s++){const i=t[s];if(i.id===e)return i}}static resolve(t,e){return Jn.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return tc.test(t)}static parseMasterPlaylist(t,e){const s={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Ad(t)},i=[];if(Zd.lastIndex=0,!t.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let r;for(;null!=(r=Zd.exec(t));)if(r[1]){const t=ic(new AttrList(r[1],s),r[2],e,s,i);t&&s.levels.push(t)}else if(r[3]){const t=r[3],n=r[4];switch(t){case"I-FRAME-STREAM-INF":{const t=new AttrList(n,s),r=ic(t,t.URI,e,s,i,!0);r&&s.iframeVariants.push(r)}break;case"SESSION-DATA":{const t=new AttrList(n,s),e=t["DATA-ID"];e&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[e]=t);break}case"SESSION-KEY":{const t=ac(n,e,s);t.encrypted&&t.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(t)):Ua.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${n}"`);break}case"DEFINE":bd(s,new AttrList(n,s),e);break;case"CONTENT-STEERING":{const t=new AttrList(n,s);s.contentSteering={uri:M3U8Parser.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=oc(n)}}const n=i.length>0&&i.length<s.levels.length;return s.levels=n?i:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,e,s){let i;const r={},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(Jd.lastIndex=0;null!==(i=Jd.exec(t));){const t=new AttrList(i[1],s),n=t.TYPE;if(n){const s=a[n],i=r[n]||[];r[n]=i;const l=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],c=t.CHANNELS,h=t.CHARACTERISTICS,u=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?M3U8Parser.resolve(t.URI,e):""};if(d&&(f.assocLang=d),c&&(f.channels=c),h&&(f.characteristics=h),u&&(f.instreamId=u),null!=s&&s.length){const t=M3U8Parser.findGroup(s,f.groupId)||s[0];dc(f,t,"audioCodec"),dc(f,t,"textCodec")}i.push(f)}}return r}static parseLevelPlaylist(t,e,s,i,r,n){var a;const o={url:e},l=new LevelDetails(e),d=l.fragments,c=[];let h,u,f,g,p=null,m=0,v=0,y=0,E=0,T=0,S=null,A=new Fragment(i,o),_=-1,b=!1,L=null;if(ec.lastIndex=0,l.m3u8=t,l.hasVariableRefs=Ad(t),"#EXTM3U"!==(null==(a=ec.exec(t))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(h=ec.exec(t));){b&&(b=!1,A=new Fragment(i,o),A.playlistOffset=y,A.setStart(y),A.sn=m,A.cc=E,T&&(A.bitrate=T),A.level=s,p&&(A.initSegment=p,p.rawProgramDateTime&&(A.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),L&&(A.setByteRange(L),L=null)));const t=h[1];if(t){A.duration=parseFloat(t);const e=(" "+h[2]).slice(1);A.title=e||null,A.tagList.push(e?["INF",t,e]:["INF",t])}else if(h[3]){if(Vn(A.duration)){var R;A.playlistOffset=y,A.setStart(y),f&&uc(A,f,l),A.sn=m,A.level=s,A.cc=E;const t=(" "+h[3]).slice(1);A.relurl=_d(l,t),cc(A,S,c),S=A,y+=A.duration,m++,v=0;const e=A.byteRange;if(2===e.length&&(A.bitrate=8*(e[1]-e[0])/A.duration|0),l.iframesOnly&&e[0]&&(null==(R=p)?void 0:R.cc)!==E){const t=new Fragment(i,o);t.relurl=A.relurl,t.setByteRange(`${Math.min(e[0],1316)}@0`),t.level=s,t.sn="initSegment",f&&(t.levelkeys=f,f.identity&&(t._decryptdata=f.identity.getDecryptData(0))),p=t,A.initSegment=p}d.push(A),b=!0}}else{if(h=h[0].match(sc),!h){Ua.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u<h.length&&void 0===h[u];u++);const t=(" "+h[u]).slice(1),r=(" "+h[u+1]).slice(1),a=h[u+2]?(" "+h[u+2]).slice(1):null;switch(t){case"BYTERANGE":S?A.setByteRange(r,S):A.setByteRange(r);break;case"PROGRAM-DATE-TIME":A.rawProgramDateTime=r,A.tagList.push(["PROGRAM-DATE-TIME",r]),-1===_&&(_=d.length);break;case"PLAYLIST-TYPE":l.type&&fc(l,t,h),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?fc(l,t,h):null!==S&&gc(l,t,h),l.startSN=parseInt(r),m=l.startSN+l.skippedSegments;break;case"SKIP":{l.skippedSegments&&fc(l,t,h);const e=new AttrList(r,l),s=e.decimalInteger("SKIPPED-SEGMENTS");if(Vn(s)){l.skippedSegments+=s;for(let t=s;t--;)d.push(null);m+=s}const i=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(i.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&fc(l,t,h),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&fc(l,t,h),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":l.iframesOnly=!0;break;case"ENDLIST":l.live||fc(l,t,h),l.live=!1;break;case"#":(r||a)&&A.tagList.push(a?[r,a]:[r]);break;case"DISCONTINUITY":E++,A.tagList.push(["DIS"]);break;case"GAP":A.gap=!0,A.tagList.push([t]);break;case"BITRATE":A.tagList.push([t,r]),T=1e3*parseInt(r),Vn(T)?A.bitrate=T:T=0;break;case"DATERANGE":{const t=new AttrList(r,l),e=new DateRange(t,l.dateRanges[t.ID],l.dateRangeTagCount);l.dateRangeTagCount++,e.isValid||l.skippedSegments?l.dateRanges[e.id]=e:Ua.log(`Ignoring invalid DATERANGE tag: ${e.invalidReason}: ${r}`),A.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const t=new AttrList(r,l);"IMPORT"in t?Ld(l,t,n):bd(l,t,e)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC&&fc(l,t,h),l.startCC=E=parseInt(r),d.forEach(t=>t&&(t.cc=E));break;case"KEY":{const t=ac(r,e,l);if(t.isSupported()){if("NONE"===t.method){f=void 0;break}f||(f={});const e=f[t.keyFormat];null!=e&&e.matches(t)||(e&&(f=Ta({},f)),f[t.keyFormat]=t)}else Ua.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":l.startTimeOffset=oc(r);break;case"MAP":{const t=new AttrList(r,l);if(A.duration){const e=new Fragment(i,o);hc(e,t,s,f),p=e,A.initSegment=p,p.rawProgramDateTime&&!A.rawProgramDateTime&&(A.rawProgramDateTime=p.rawProgramDateTime)}else{const e=A.byteRangeEndOffset;if(e){const t=A.byteRangeStartOffset;L=`${e-t}@${t}`}else L=null;hc(A,t,s,f),p=A,b=!0}p.cc=E;break}case"SERVER-CONTROL":g&&fc(l,t,h),g=new AttrList(r),l.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),l.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&fc(l,t,h);const e=new AttrList(r);l.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=l.partList;t||(t=l.partList=[]);const e=v>0?t[t.length-1]:void 0,s=v++,i=new AttrList(r,l),n=new Part(i,A,o,s,e);t.push(n),A.duration+=n.duration;break}case"PRELOAD-HINT":{const t=new AttrList(r,l);l.preloadHint=t;break}case"RENDITION-REPORT":{const t=new AttrList(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(t);break}default:Ua.warn(`line parsed but not handled: ${h}`)}}}S&&!S.relurl?(d.pop(),y-=S.duration,l.partList&&(l.fragmentHint=S)):l.partList&&(cc(A,S,c),A.cc=E,l.fragmentHint=A,f&&uc(A,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const I=d.length,k=d[0],w=d[I-1];if(y+=l.skippedSegments*l.targetduration,y>0&&I&&w){l.averagetargetduration=y/I;const t=w.sn;l.endSN="initSegment"!==t?t:0,l.live||(w.endList=!0),_>0&&(!function(t,e,s){if(s||(s=t[e]),!s)return;for(let i=e;i--;){const e=t[i];if(!e)return;e.programDateTime=s.programDateTime-1e3*e.duration,s=e}}(d,_,_>I-1?A:null),k&&c.unshift(k))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,c.length&&l.dateRangeTagCount&&k&&rc(c,l),l.endCC=E,l}}function ic(t,e,s,i,r,n){var a;if(void 0===e)return null;const o=_d(i,e),l={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:M3U8Parser.resolve(o,s)},d=t.decimalResolution("RESOLUTION");d&&(l.width=d.width,l.height=d.height),lc(t.CODECS,l);const c=t["SUPPLEMENTAL-CODECS"];return c&&(l.supplemental={},lc(c,l.supplemental)),null!=(a=l.unknownCodecs)&&a.length||r.push(l),n&&(l.iframes=!0),l}function rc(t,e){let s=t.length;if(!s){if(!e.hasProgramDateTime)return;{const i=e.fragments[e.fragments.length-1];t.push(i),s++}}const i=t[s-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=i.ref;for(let i=s;i--;){var a;if((null==(a=t[i])?void 0:a.sn)<e.startSN)break;const s=nc(e,d,t,i,r);if(s){l.tagAnchor=s.ref;break}}}}function nc(t,e,s,i,r){const n=s[i];if(n){const o=n.programDateTime;if(e>=o||0===i){var a;if(e<=o+1e3*(((null==(a=s[i+1])?void 0:a.start)||r)-n.start)){const r=n.sn-t.startSN,a=t.fragments;if(r>=0&&r<a.length){if(a.length>s.length){const n=s[i+1]||a[a.length-1];for(let s=Math.min(n.sn-t.startSN,a.length-1);s>r;s--){const t=a[s].programDateTime;if(e>=t&&e<t+1e3*a[s].duration)return a[s]}}return a[r]}}}}return null}function ac(t,e,s){var i,r;const n=new AttrList(t,s),a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,c=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&Ua.error(`Invalid IV: ${n.IV}`);const h=o?M3U8Parser.resolve(o,e):"",u=(d||"1").split("/").map(Number).filter(Number.isFinite);return new LevelKey(a,h,c,u,l,n.KEYID)}function oc(t){const e=new AttrList(t).decimalFloatingPoint("TIME-OFFSET");return Vn(e)?e:null}function lc(t,e){let s=(t||"").split(/[ ,]+/).filter(t=>t);["video","audio","text","image"].forEach(t=>{const i=s.filter(e=>el(e,t));i.length&&(e[`${t}Codec`]=i.map(t=>t.split("/")[0]).join(","),s=s.filter(t=>-1===i.indexOf(t)))}),e.unknownCodecs=s}function dc(t,e,s){const i=e[s];i&&(t[s]=i)}function cc(t,e,s){t.rawProgramDateTime?s.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function hc(t,e,s,i){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=s,t.sn="initSegment",i&&(t.levelkeys=i),t.initSegment=null}function uc(t,e,s){t.levelkeys=e;const{encryptedFragments:i}=s;i.length&&i[i.length-1].levelkeys===e||!Object.keys(e).some(t=>e[t].isCommonEncryption)||i.push(t)}function fc(t,e,s){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${s[0]})`)}function gc(t,e,s){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${s[0]})`)}function pc(t,e){const s=e.startPTS;if(Vn(s)){let i,r=0;e.sn>t.sn?(r=s-t.start,i=t):(r=t.start-s,i=e),i.duration!==r&&i.setDuration(r)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration)}else e.setStart(Math.max(t.start-e.duration,0))}function mc(t,e,s,i,r,n,a,o){i-s<=0&&(o.warn("Fragment should have a positive duration",e),i=s+e.duration,n=r+e.duration);let l=s,d=i;const c=e.startPTS,h=e.endPTS;if(Vn(c)){const a=Math.abs(c-s);t&&a>t.totalduration?o.warn(`media timestamps and playlist times differ by ${a}s for level ${e.level} ${t.url}`):Vn(e.deltaPTS)?e.deltaPTS=Math.max(a,e.deltaPTS):e.deltaPTS=a,l=Math.max(s,c),s=Math.min(s,c),r=void 0!==e.startDTS?Math.min(r,e.startDTS):r,d=Math.min(i,h),i=Math.max(i,h),n=void 0!==e.endDTS?Math.max(n,e.endDTS):n}const u=s-e.start;0!==e.start&&e.setStart(s),e.setDuration(i-e.start),e.startPTS=s,e.maxStartPTS=l,e.startDTS=r,e.endPTS=i,e.minEndPTS=d,e.endDTS=n;const f=e.sn;if(!t||f<t.startSN||f>t.endSN)return 0;let g;const p=f-t.startSN,m=t.fragments;for(m[p]=e,g=p;g>0;g--)pc(m[g],m[g-1]);for(g=p;g<m.length-1;g++)pc(m[g],m[g+1]);return t.fragmentHint&&pc(m[m.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,u}function vc(t,e,s){if(t===e)return;let i=null;const r=t.fragments;for(let t=r.length-1;t>=0;t--){const e=r[t].initSegment;if(e){i=e;break}}let n;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,s){var i;const r=e.skippedSegments,n=Math.max(t.startSN,e.startSN)-e.startSN,a=(t.fragmentHint?1:0)+(r?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,o=e.startSN-t.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,d=null!=(i=t.fragmentHint)&&i.duration?t.fragments.concat(t.fragmentHint):t.fragments;for(let i=n;i<=a;i++){const n=d[o+i];let a=l[i];if(r&&!a&&n&&(a=e.fragments[i]=n),n&&a){s(n,a,i,l);const r=n.relurl,o=a.relurl;if(r&&Lc(r,o))return void(e.playlistParsingError=yc(`media sequence mismatch ${a.sn}:`,t,e,n,a));if(n.cc!==a.cc)return void(e.playlistParsingError=yc(`discontinuity sequence mismatch (${n.cc}!=${a.cc})`,t,e,n,a))}}}(t,e,(t,s,r,a)=>{if((!e.startCC||e.skippedSegments)&&s.cc!==t.cc){const i=t.cc-s.cc;for(let t=r;t<a.length;t++)a[t].cc+=i;e.endCC=a[a.length-1].cc}Vn(t.startPTS)&&Vn(t.endPTS)&&(s.setStart(s.startPTS=t.startPTS),s.startDTS=t.startDTS,s.maxStartPTS=t.maxStartPTS,s.endPTS=t.endPTS,s.endDTS=t.endDTS,s.minEndPTS=t.minEndPTS,s.setDuration(t.endPTS-t.startPTS),s.duration&&(n=s),e.PTSKnown=e.alignedSliding=!0),t.hasStreams&&(s.elementaryStreams=t.elementaryStreams),s.loader=t.loader,t.hasStats&&(s.stats=t.stats),t.initSegment&&(s.initSegment=t.initSegment,i=t.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(i&&o.forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=i)?void 0:e.relurl)||(t.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(t=>!t),e.deltaUpdateFailed){s.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=function(t,e,s){const{dateRanges:i,recentlyRemovedDateranges:r}=e,n=Ta({},t);r&&r.forEach(t=>{delete n[t]});const a=Object.keys(n).length;if(!a)return i;return Object.keys(i).forEach(t=>{const e=n[t],r=new DateRange(i[t].attr,e);r.isValid?(n[t]=r,e||(r.tagOrder+=a)):s.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Dl(i[t].attr)}"`)}),n}(t.dateRanges,e,s));const i=t.fragments.filter(t=>t.rawProgramDateTime);if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let t=1;t<o.length;t++)null===o[t].programDateTime&&cc(o[t],o[t-1],i);rc(i,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const s=Sc(t,e.startSN-1);e.startCC=null!=(l=null==s?void 0:s.cc)?l:a[0].cc}if(function(t,e,s){if(t&&e){let i=0;for(let r=0,n=t.length;r<n;r++){const n=t[r],a=e[r+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):i--}}}(t.partList,e.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats,e.gap=t.gap||e.gap}),n){e.iframesOnly&&n.type;mc(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,0,s)}else Ec(t,e);a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const d=e.advancedDateTime;if(e.advanced&&d){const t=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=t),e.driftEndTime=d,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;-1===e.requestScheduled&&(e.requestScheduled=t.requestScheduled)}function yc(t,e,s,i,r){return new Error(`${t} ${r.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${s.startSN}\n${s.m3u8}`)}function Ec(t,e,s=!0,i){const r=e.startSN+e.skippedSegments-t.startSN,n=t.fragments,a=r>=0;let o=0;if(a&&r<n.length)o=n[r].start,null==i||i.log(`Aligning playlists based on SN ${e.startSN} (diff: ${o})`);else if(a&&e.startSN===t.endSN+1)o=t.fragmentEnd,null==i||i.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${o})`);else if(a&&s)o=t.fragmentStart+r*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return o;o=t.fragmentStart,null==i||i.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${o})`)}return function(t,e){if(e){const s=t.fragments;for(let i=t.skippedSegments;i<s.length;i++)s[i].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}(e,o),o}function Tc(t,e=1/0){let s=1e3*t.targetduration;if(t.updated){const i=t.fragments,r=4;if(i.length&&s*r>e){const t=1e3*i[i.length-1].duration;t<s&&(s=t)}}else s/=2;return Math.round(s)}function Sc(t,e,s){var i;if(!t)return null;let r=t.fragments[e-t.startSN];return r||(r=t.fragmentHint,(null==(i=r)?void 0:i.sn)===e?r:s&&e<t.startSN&&s.sn===e?s:null)}function Ac(t,e,s){return t?_c(t.partList,e,s):null}function _c(t,e,s){if(t)for(let i=t.length;i--;){const r=t[i];if(r.index===s&&r.fragment.sn===e)return r}return null}function bc(t){t.forEach((t,e)=>{var s;null==(s=t.details)||s.fragments.forEach(t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)})})}function Lc(t,e){return!(t===e||!e)&&Rc(t)!==Rc(e)}function Rc(t){return t.replace(/\?[^?]*$/,"")}function Ic(t,e){for(let i=0,r=t.length;i<r;i++){var s;if((null==(s=t[i])?void 0:s.cc)===e)return t[i]}return null}function kc(t,e){const s=t.start+e;t.setStart(s)}function wc(t,e){const s=e.fragments;for(let e=0,i=s.length;e<i;e++)kc(s[e],t);e.fragmentHint&&kc(e.fragmentHint,t),e.alignedSliding=!0}function Pc(t,e,s){t&&(!function(t,e,s){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const i=Math.min(e.endCC,t.endCC),r=Ic(e.fragments,i),n=Ic(t.fragments,i);if(!r||!n)return;const a=r.start-n.start;s.log(`Aligning playlists using dicontinuity sequence ${i} (diff: ${a})`),wc(a,t)}(e,t,s),e.alignedSliding||function(t,e,s){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const i=t.fragments,r=e.fragments;if(!i.length||!r.length)return;let n,a;const o=Math.min(e.endCC,t.endCC);e.startCC<o&&t.startCC<o&&(n=Ic(r,o),a=Ic(i,o));n&&a||(n=r[Math.floor(r.length/2)]||r.filter(t=>!!t)[0],a=Ic(i,n.cc)||i[Math.floor(i.length/2)]);const l=n.programDateTime,d=a.programDateTime;if(!l||!d)return;const c=(d-l)/1e3;if(Math.abs(c)>Math.max(60,t.totalduration))return void s.log(`Cannot align playlists using PDT without overlap (${Math.abs(c)} > ${t.totalduration})`);const h=c-(a.start-n.start);s.log(`Aligning playlists using PDT (diff: ${h})`),wc(h,t)}(e,t,s),e.alignedSliding||e.skippedSegments||Ec(t,e,!1,s))}function Dc(t,e,s){Cc(t,e,s),t.addEventListener(e,s)}function Cc(t,e,s){t.removeEventListener(e,s)}function Oc(t){let e="";const s=t.length;for(let i=0;i<s;i++)e+=`[${t.start(i).toFixed(3)}-${t.end(i).toFixed(3)}]`;return e}const Mc="STOPPED",xc="IDLE",Fc="KEY_LOADING",Nc="FRAG_LOADING",Uc="FRAG_LOADING_WAITING_RETRY",Bc="WAITING_TRACK",$c="PARSING",Gc="PARSED",Hc="ENDED",Kc="ERROR",Vc="WAITING_INIT_PTS",jc="WAITING_LEVEL";class BaseStreamController extends TaskLoop{constructor(t,e,s,i,r){super(i,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Mc,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=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:t,fragCurrent:e,media:s,mediaBuffer:i,state:r}=this,n=s?s.currentTime:0,a=BufferHelper.bufferInfo(i||s,n,t.maxBufferHole),o=a.len;if(this.log(`Media seeking to ${n}, state: ${r}, ${o?"in":"out of"} buffer`),this.state===Hc)this.resetLoadingState();else if(e){const s=t.maxFragLookUpTolerance,i=e.start-s,r=e.start+e.duration+s;if(!o||r<a.start||i>a.end){const t=n<i,s=n>r;(t||s)&&(!e.loader||!s&&this.isFragmentNearlyDownloaded(e)?this.fragPrevious=null:(this.log(`Cancelling fragment load for seek (sn: ${e.sn}) - ${t?"backward":"forward"} seek`),e.abortRequests(),this.resetLoadingState()))}}if(s){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const t=Math.max(a.end,n),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${n} with buffer @${t}`),this.loadingParts=e)}}const l=!BufferHelper.isBuffered(s,n);this.hls.hasEnoughToStart&&!l||(this.log(`Setting ${l?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,l&&(this.startPosition=n)),o<1&&this.state===xc&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=t,this.fragmentLoader=new FragmentLoader(t.config),this.initFragmentLoader=new FragmentLoader(t.config),this.keyLoader=s,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Decrypter(t.config)}registerListeners(){const{hls:t}=this;t.on(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(zn.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(zn.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===Mc)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);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=Mc}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;if(-1===e&&t){const e=this.getLevelDetails();if(null!=e&&e.live){return(this.hls.liveSyncPosition||e.fragmentStart)+this.timelineOffset}return t}return e}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(t){}get couldBacktrack(){return!1}set couldBacktrack(t){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const s=t.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=t.buffered;this.config.maxBufferHole&&r&&r.length>1&&(t=BufferHelper.bufferedInfo(r,t.start,0));const n=t.nextStart;if(n&&n>i&&n<e.edge)return!1;if(this.media.currentTime<t.start)return!1;const a=e.partList;if(null!=a&&a.length){const t=a[a.length-1];return BufferHelper.isBuffered(this.media,t.start+t.duration/2)}const o=e.fragments[e.fragments.length-1];return this.fragmentTracker.isEndListAppended(o.type)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;var e;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}onMediaAttached(t,e){const s=this.media=this.mediaBuffer=e.media;Dc(s,"seeking",this.onMediaSeeking),Dc(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===Mc&&this.startLoad(i.startPosition)}onMediaDetaching(t,e){this.fragPlaying=null;const s=!!e.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Cc(i,"seeking",this.onMediaSeeking),Cc(i,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,s)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}onError(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Mc,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,s){this.startFragRequested=!0,this._loadFragForPlayback(t,e,s)}_loadFragForPlayback(t,e,s){this._doFragLoad(t,e,s,t=>{const e=t.frag;if(this.fragContextChanged(e))return this.warn(`${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)} was dropped during download.`),void this.fragmentTracker.removeFragment(e);const s=++e.stats.chunkCount;this.log(`load progress ${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)} chunk: ${s}`),this._handleFragmentLoadProgress(t)}).then(t=>{if(!t)return;const e=this.state,s=t.frag;this.fragContextChanged(s)?(e===Nc||!this.fragCurrent&&e===$c)&&(this.fragmentTracker.removeFragment(s),this.state=xc):("payload"in t&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level} (bytes ${s.stats.loaded})`),this.hls.trigger(zn.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))}).catch(e=>{this.state!==Mc&&this.state!==Kc&&(this.log(`Frag error ${t.type} sn:${t.sn} cc:${t.cc}: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:s}=this;if(s.getState(t)===ld){const e=t.type,i=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(r,t.duration))&&s.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?s.removeAllFragments():s.hasParts(t.type)&&(s.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),s.getState(t)===dd&&s.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=this.fragmentTracker,s=t.fragments[t.fragments.length-1];if(s.endList&&!e.isEndListAppended(this.playlistType)){const t=e.getPartialFragment(s.end);t&&(e.removeFragment(t),e.fragBuffered(s,!0))}e.detectPartialFragments({frag:s,part:null,stats:s.stats,id:s.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e,s=null){if(!(t-e))return;const i={startOffset:t,endOffset:e,type:s};this.hls.trigger(zn.BUFFER_FLUSHING,i)}_loadInitSegment(t){const{hls:e}=this;return this.initFragmentLoader.abort(),e.trigger(zn.FRAG_LOADING,{frag:t,targetBufferTime:0}),this.initFragmentLoader.load(t).then(t=>{var e;const s=t.frag;if(!this.levels||!va(s,null==(e=this.fragCurrent)?void 0:e.initSegment))throw new LoadError({type:Wn.NETWORK_ERROR,details:Yn.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:s,networkDetails:null});return t}).then(t=>{const{frag:s,payload:i}=t,r=s.decryptdata;if(i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&Cd(r.method)){const n=self.performance.now(),{decryptRange:a}=yd(s,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,Od(r.method),a).catch(t=>{throw e.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:s}),this.fragmentLoader.abort(),t}).then(i=>{const r=self.performance.now();return e.trigger(zn.FRAG_DECRYPTED,{frag:s,part:null,payload:i,stats:{tstart:n,tdecrypt:r}}),t.payload=i,this.completeInitSegmentLoad(t)})}return this.completeInitSegmentLoad(t)})}completeInitSegmentLoad(t){const e=t.frag.stats;t.frag.data=new Uint8Array(t.payload),e.parsing.start=e.buffering.start=self.performance.now(),e.parsing.end=e.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(t){const{initSegment:e}=t;if(!this.bitrateTest&&pa(t)&&e&&!e.data){var s;return(!e.encrypted||null!=(s=e.decryptdata)&&s.key?this._loadInitSegment(e):this.keyLoader.load(e).then(()=>this._loadInitSegment(e))).catch(e=>{if(this.state===Mc||this.state===Kc)throw e;throw"data"in e&&(e.data.frag=t,this.fragmentLoader.abort(),this.handleFragLoadError(e)),this.resetFragmentLoading(t),e})}}unhandledEncryptionError(t,e){var s,i;const r=t.tracks;if(r&&!e.encrypted&&(null!=(s=r.audio)&&s.encrypted||null!=(i=r.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const t=this.media,s=new Error(`Encrypted track with no key in ${this.fragInfo(e)} (media ${t?"attached mediaKeys: "+t.mediaKeys:"detached"})`);return this.warn(s.message),!t||t.mediaKeys?!1:(this.hls.trigger(zn.ERROR,{type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!va(t,e)}fragBufferedComplete(t,e){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${s?Oc(BufferHelper.getBuffered(s)):"(detached)"})`),pa(t)){var i;if(t.type!==ha){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return void(this.state=xc)}const s=null==(i=this.levels)?void 0:i[t.level];null!=s&&s.fragmentError&&(e||this.fragmentTracker.getState(t)!==dd)&&(this.log(`Resetting level fragment error count of ${s.fragmentError} on frag buffered`),s.fragmentError=0,t.stats.retry=0)}this.state=xc}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const s=t.frag,{part:i,partsLoaded:r}=t,n=!r||0===r.length||r.some(t=>!t),{decryptRange:a}=yd(s,i),o=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n,s.duration,this.iframesOnly,a);this.log(`load complete ${s.type} sn: ${s.sn}${i?" part: "+i.index:""} of ${this.fragInfo(s,!1,i)}`),e.flush(o)}_handleFragmentLoadProgress(t){}loadKeyFor(t,e,s){var i;let r=null;return!t.encrypted||null!=(i=t.decryptdata)&&i.key?t.encrypted||(r=this.keyLoader.loadClear(t,e.encryptedFragments,this.startFragRequested),r&&this.log(`[eme] blocking frag sn: ${t.sn} load until media-keys acquired`)):(this.log(`Loading key for ${t.sn} of [${e.startSN}-${e.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=Fc,r=this.keyLoader.load(t,s).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(zn.KEY_LOADED,t),this.state===Fc&&(this.state=xc),t}),this.hls.trigger(zn.KEY_LOADING,{frag:t})),r}_doFragLoad(t,e,s=null,i){this.fragCurrent=t;const r=e.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" detail"}s`);const n=this.fragPrevious;if(!ma(t,n)){const s=this.shouldLoadParts(e.details,t.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?"ON":"OFF"} loading sn ${null==n?void 0:n.sn}->${t.sn}`),this.loadingParts=s)}if(s=Math.max(t.start,s||0),this.loadingParts){const a=r.partList;if(a&&i){s>r.fragmentEnd&&r.fragmentHint&&(t=r.fragmentHint);const o=this.getNextPart(a,t,s);if(o>-1){const l=a[o];if(!ma(t=this.fragCurrent=l.fragment,n)&&!this.shouldLoadParts(e.details,t.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(t,!1,l)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(l,e.details))return Promise.resolve(null);const d=this.loadKeyFor(t,r);if(this.fragContextChanged(t))return Promise.resolve(null);let c;this.log(`Loading ${t.type} sn: ${t.sn} part: ${l.index} (${o}/${a.length-1}) of ${this.fragInfo(t,!1,l)} cc: ${t.cc} [${r.startSN}-${r.endSN}], target: ${s}${l.byteRange.length?` range:${l.byteRange.join("-")}`:""}`),this.nextLoadPosition=l.start+l.duration,this.state=Nc;const h=this.loadInitSegmentIfNeeded(t);if(d||h){const s=!!d;c=Promise.all([d,h]).then(([r])=>!s||r&&!this.fragContextChanged(r.frag)?this.doFragPartsLoad(t,l,e,i):null).catch(t=>this.handleFragLoadError(t))}else c=this.doFragPartsLoad(t,l,e,i).catch(t=>this.handleFragLoadError(t));return this.hls.trigger(zn.FRAG_LOADING,{frag:t,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):c}if(!t.url||this.loadedEndOfParts(a,s))return Promise.resolve(null)}}var a;if(this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s} Check buffer at sn: ${t.sn} loaded parts: ${null==(a=r.partList)?void 0:a.filter(t=>t.loaded).map(t=>`[${t.start}-${t.end}]`)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(t,e.details))return Promise.resolve(null);const o=this.loadInitSegmentIfNeeded(t),l=this.loadKeyFor(t,r,o);var d;if(this.fragContextChanged(t))return this.log(`Context changed in KEY_LOADING sn: ${t.sn} ${t.relurl} > ${null==(d=this.fragCurrent)?void 0:d.relurl}`),null==o||o.catch(()=>null),null==l||l.catch(()=>null),Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)} cc: ${t.cc} ${"["+r.startSN+"-"+r.endSN+"]"}, target: ${s}${t.byteRange.length?` range:${t.byteRange.join("-")}`:""}`),Vn(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Nc;const c=this.config.progressive&&t.type!==ha;let h;return h=c&&l?l.then(e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,this.iframesOnly,i,o)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,this.iframesOnly,c?i:void 0,c?o:void 0),l,o]).then(([t])=>(!c&&i&&i(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(zn.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([h,o]).then(([t])=>t)}doFragPartsLoad(t,e,s,i){return new Promise((r,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,d=e=>{this.fragmentLoader.loadPart(t,e,i).then(i=>{o[e.index]=i;const n=i.part;this.hls.trigger(zn.FRAG_LOADED,i);const a=Ac(s.details,t.sn,e.index+1)||_c(l,t.sn,e.index+1);if(!a)return r({frag:t,part:n,partsLoaded:o});d(a)}).catch(n)};d(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;e.frag&&e.details===Yn.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):e.frag&&e.type===Wn.KEY_SYSTEM_ERROR&&!e.fatal&&(e.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e.frag)),this.hls.trigger(zn.ERROR,e)}else this.hls.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==$c)return void(this.fragCurrent||this.state===Mc||this.state===Kc||(this.state=xc));const{frag:s,part:i,level:r}=e,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&s.sn>a.endSN||this.shouldLoadParts(a,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end}`),this.loadingParts=o),this.updateLevelTiming(s,i,r,t)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList&&!this.iframesOnly){var s;const i=t.partList[0];if(e>=i.end+((null==(s=t.fragmentHint)?void 0:s.duration)||0)){if(this.playhead>i.start-i.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:s}=this,{level:i,sn:r,part:n}=t;if(null==e||!e[i])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=e[i],o=a.details,l=n>-1?Ac(o,r,n):null,d=l?l.fragment:Sc(o,r,s);return d?(s&&s!==d&&(d.stats=s.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(t,e,s,i,r){if(this.state!==$c)return;pa(e)&&!this.fragContextChanged(e)&&(this.fragPrevious=e);const{data1:n,data2:a}=t;let o=n;if(a&&(o=Uo(n,a)),!o.length)return;const l=this.initPTS[e.cc],d=l?-l.baseTime/l.timescale:void 0,c={type:t.type,frag:e,part:s,chunkMeta:i,offset:d,parent:e.type,data:o};if(this.hls.trigger(zn.BUFFER_APPENDING,c),t.dropped&&t.independent&&!s){if(r)return;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,i=BufferHelper.bufferInfo(e,s,0),r=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(t.start-n,i.end-n),s+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var s;const i=this.playhead,r=this.lastCurrentTime>i||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,i,e,r)}getFwdBufferInfoAtPos(t,e,s,i){const r=BufferHelper.bufferInfo(t,e,i);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,s);if(n&&(r.nextStart<=n.end||n.gap)){const s=Math.max(Math.min(r.nextStart,n.end)-e,i);return BufferHelper.bufferInfo(t,e,s)}}return r}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)}exceedsMaxBuffer(t,e,s){const i=t.nextStart;if(i&&s.start>i){const i=t.buffered;if(i){let r=t.len;const n=t.bufferedIndex;for(let t=i.length-1;t>n;t--)i[t].start<s.start&&(r+=i[t].end-i[t].start);return r>=e}}return!1}reduceMaxBufferLength(t,e){const s=this.config,i=Math.max(Math.min(t-e,s.maxBufferLength),e/2),r=Math.max(t-3*e,s.maxMaxBufferLength/2,i);return r>=i&&(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(t){const e=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,this.playlistType):null;return e&&"fragment"in e?e.fragment:e}getNextFragment(t,e){const s=e.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=e.fragmentStart,a=r.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const s=r.initialLiveManifestSize;if(i<s)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${s})`),null;if(this.startFragRequested||!a||this.loadingParts||(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n){var l;o=this.getInitialLiveFragment(e);const s=this.config.startPosition,i=this.hls.startPosition,r=this.hls.liveSyncPosition,a=(null==(l=o)?void 0:l.start)||0;let d,c;if(-1!==i&&i>=n?(d=i,c=i===s?"config":"next load start"):r?(d=r,c="live edge"):(d=t,c="buffer pos"),d<a&&(d=a,c="live frag start"),d<n&&(d=n,c="playlist start"),this.startPosition!=d||this.nextLoadPosition!=d){const l=e.live&&!this.filterReplacedPrimary(o,e)?-1:d;this.log(`Setting startPosition to ${l} next load ${d} ${-1===i?"":`(from ${s}) `}based on ${c}. live edge: ${r} live frag start: ${a} playlist start: ${n} buffer pos: ${t}`),this.startPosition=l,this.nextLoadPosition=d}}}else t<=n&&(o=s[0]);if(!o){const s=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,s,e)}let d=this.filterReplacedPrimary(o,e);return!d&&o&&(d=Wl(e,o.sn),d&&(this.nextLoadPosition=d.start)),d}isLoopLoading(t,e){if(this.nextLoadPosition<=e)return!1;const s=this.fragmentTracker.getState(t);if(s===cd)return!0;if(s===dd){if(t.gap)return!0;if(t.stats.retry>1)return!0}return!1}getNextFragmentLoopLoading(t,e,s,i,r){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&s.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(null!==t&&s.len+t.len>=r){const t=n.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(Wc(this.config)){var t;if(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,e){if(!t)return t;if(Wc(this.config)&&("type"in t?t:t.fragment).type!==ha){const s=this.hls.interstitialsManager,i=null==s?void 0:s.bufferingItem;if(i){const s=i.event;if(s){if(!s.appendInPlace&&(Math.abs(t.start-i.start)>1||0===i.start))return null}else{if(t.end<=i.start&&!1===(null==e?void 0:e.live))return null;if(t.start>=i.end&&i.nextEvent&&(i.nextEvent.appendInPlace&&!i.nextEvent.hasPlayed||t.start-i.end>1))return null}}if(qc(t,null==s?void 0:s.playerQueue,this.playhead))return null}return t}getNextPart(t,e,s){let i=-1,r=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,i>-1&&s<o.start)break;const l=o.loaded||o.gap;l?i=-1:(r||(o.independent||n)&&o.fragment===e)&&(i=a),r=l&&!o.gap}const a=t[i];return a&&a.fragment!==e&&this.log(`Need buffer at ${s} but next unloaded part starts at ${a.start} (sn: ${e.sn} -> ${a.fragment.sn})`),i}loadedEndOfParts(t,e){let s;for(let i=t.length;i--;){if(s=t[i],!s.loaded)return!1;if(e>s.start)return!0}return!1}getInitialLiveFragment(t){const e=t.fragments,s=this.fragPrevious;let i=null;if(s){if(t.hasProgramDateTime&&(i=function(t,e,s){if(null===e||!Array.isArray(t)||!t.length||!Vn(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;for(let i=0;i<t.length;++i){const r=t[i];if(jl(e,s,r))return r}return null}(e,s.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!i){const r=s.sn+1;if(r>=t.startSN&&r<=t.endSN){const n=e[r-t.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=ql(t,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(i=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i}getFragmentAtPosition(t,e,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=i,d=s.partList,c=!!(this.loadingParts&&null!=d&&d.length&&o);let h;if(c&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),r&&this.fragmentTracker.getState(r)===od&&(r=null),t<e){var u;h=Kl(r,n,t,t<this.lastCurrentTime||t>e-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l)}else h=n[n.length-1];if(h){const t=h.sn-s.startSN,e=this.fragmentTracker.getState(h);if((e===cd||e===dd&&h.gap)&&(r=h),ma(h,r)&&(!c||d[0].fragment.sn>h.sn||!s.live)){const e=n[t+1];h=h.sn<a&&this.fragmentTracker.getState(e)!==cd?e:null}}return h}alignPlaylists(t,e,s){const i=t.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=t.fragmentStart,n=!e,a=t.alignedSliding&&Vn(r);if(n||!a&&!r){Pc(s,t,this);const r=t.fragmentStart;return this.log(`Live playlist sliding: ${r} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${i}`),r}return r}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;s<e&&(s=-1);const i=this.timelineOffset;if(-1===s){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:t.startTimeOffset;if(null!==n&&Vn(n))s=e+n,n<0&&(s+=t.edge),s=Math.min(Math.max(e,s),e+t.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s;else if(t.live){const t=this.hls.liveSyncPosition;s=t||e,this.log(`Setting startPosition to -1 to start at ${t?"live edge":"playlist start"} ${s}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=s=0;this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var t;const{media:e}=this;let s=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e&&!this.iframesOnly?s=e.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}get playhead(){var t;if(null!=(t=this.hls)&&t.hasEnoughToStart){var e;const t=null==(e=this.media)?void 0:e.currentTime;return Vn(t)?t:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var t;if(this.playlistType!==da)return!1;const e=this.getLevelDetails();return e?e.iframesOnly:null==(t=this.levelLastLoaded)?void 0:t.iframes}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&pa(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===Uc)||(this.state=xc)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const{frag:s,part:i}=e;if(!s||!this.levels||s.type!==t)return;var r;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.relurl} > ${null==(r=this.fragCurrent)?void 0:r.relurl}`);const n=e.details===Yn.FRAG_GAP;n&&this.fragmentTracker.addAsGap(s);const a=e.errorAction;if(!a)return void(this.state=Kc);const{action:o,flags:l,retryCount:d=0,retryConfig:c}=a,h=!!c,u=h&&o===Xl,f=h&&!a.resolved&&l&Jl,g=this.hls.latestLevelDetails,p=null==g?void 0:g.live;if(!u&&f&&pa(s)&&p&&s.sn<g.endSN&&!Ra(e))this.resetFragmentErrors(t),i?i.gap=!0:this.treatAsGap(s),a.resolved=!0;else if((u||f)&&d<c.maxNumRetry){var m;const i=Da(null==(m=e.response)?void 0:m.code),r=ka(c,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=Uc,a.resolved=!0,i)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(e.reason="offline");this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${d+1}/${c.maxNumRetry} in ${r}ms`)}else if(c){if(this.resetFragmentErrors(t),!(d<c.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${d})`);n||o===Ql||(a.resolved=!0)}else this.state=o===zl?jc:Kc;this.tickImmediate()}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,s=e===1/0;(!e||t>=e||s&&!Da(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=xc)}reduceLengthAndFlushBuffer(t){if(this.state===$c||this.state===Gc){const e=t.frag,s=t.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(null==e?void 0:e.duration)||10);const n=!r;return n?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${s} buffer`):i.nextStart&&e&&i.nextStart>e.start&&this.flushMainBuffer(i.nextStart,Number.POSITIVE_INFINITY,s===ca?s:void 0),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===ca&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Mc&&(this.state=xc)}afterBufferFlushed(t,e){if(!t)return;const s=BufferHelper.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,s,this.playlistType),this.state===Hc&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Mc&&(this.state=xc)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.getLevelDetails();null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${-1===t.level?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,s,i){const r=s.details;if(!r)return void this.warn("level.details undefined");this.log(`update level timing ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`);const n=Object.keys(t.elementaryStreams).reduce((e,n)=>{const a=t.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${n} duration reliably (${o})`),e||!1;const l=i.partial?0:mc(r,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this.iframesOnly,this);return this.hls.trigger(zn.LEVEL_PTS_UPDATED,{details:r,level:s,drift:l,type:n,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e},!1);if(!n){var a,o,l,d;const i=null===(null==(a=this.transmuxer)?void 0:a.error),r=null!=(null==(o=this.transmuxer)?void 0:o.error),n=(null!=(l=null==(d=this.levels)?void 0:d.length)?l:0)>1;if((0===s.fragmentError||i&&(s.fragmentError<2||t.endList)||r&&n)&&this.treatAsGap(t,s),i){const i=new Error(`Found no media in ${this.playlistLabel()} ${t.level} ${e?`part: ${e.index} of `:""}sn: ${t.sn} at playlist time: ${t.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(i.message),this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.FRAG_PARSING_ERROR,fatal:!1,error:i,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Gc,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`),this.hls.trigger(zn.FRAG_PARSED,{frag:t,part:e,chunkMeta:i})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(t,e=!0,s){var i,r;return`${this.playlistLabel()} ${t.level} (${s?"part":"frag"}:[${null!=(i=e&&!s?t.startPTS:(s||t).start)?i:NaN}-${null!=(r=e&&!s?t.endPTS:(s||t).end)?r:NaN}]${s&&"main"===t.type?"INDEPENDENT="+(s.independent?"YES":"NO"):""})`}treatAsGap(t,e){e&&e.fragmentError++,this.fragmentTracker.addAsGap(t)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}isFragmentNearlyDownloaded(t){var e;const s=null==(e=t.loader)?void 0:e.stats;if(!s)return!1;const i=s.loading.first>0,r=(s.total-s.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return i&&r<=.15}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}calculateOptimalSwitchPoint(t,e){let s=0;const{hls:i,media:r,config:n,levels:a,playlistType:o}=this,l=this.getLevelDetails();if(r&&!r.paused&&a){var d;const e=o===ca?Tl(t.audioCodec,128e3):t.maxBitrate,r=1+i.ttfbEstimate/1e3,a=i.bandwidthEstimate*n.abrBandWidthUpFactor;s=r+e*(l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||(null==(d=this.fragCurrent)?void 0:d.duration)||6)/a,t.details||(s+=r)}const c=this.playhead;return{fetchdelay:s,okToFlushForwardBuffer:!(null!=l&&l.live)||e.end-c>1.5*s}}scheduleTrackSwitch(t,e,s){const{media:i,playlistType:r}=this;if(!i||!t)return;const n=s?this.getBufferedFrag(this.playhead+e):null;if(n){const t=this.followingBufferedFrag(n);if(t){var a;this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,s=t.duration,i=Math.max(n.end,e+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));if(((null==(a=this.getLevelDetails())?void 0:a.fragmentStart)||0)>i)return;const o=r===da?null:"audio";this.flushMainBuffer(i,Number.POSITIVE_INFINITY,o),this.cleanupBackBuffer()}}}cleanupBackBuffer(){const{media:t,playlistType:e}=this;if(!t)return;const s=this.getAppendedFrag(this.playhead);if(s&&s.start>1){const t=e===ca;this.flushMainBuffer(0,s.start-(t?0:1),t?"audio":null)}}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,this.playlistType)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case Fc:case Nc:case Uc:case $c:case Gc:this.state=xc}this.nextLoadPosition=this.playhead}checkFragPlaying(){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=void 0,!ma(e,this.fragPlaying)))return this.fragPlaying=e,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){const{levels:t,media:e,hls:s,config:i,playlistType:r}=this;if(null!=e&&e.readyState&&t&&s&&i){const e=this.getBufferOutput(),i=this.getFwdBufferInfo(e,r);if(!i)return;const n=t[r===ca?s.nextAudioTrack:s.nextLoadLevel],{fetchdelay:a,okToFlushForwardBuffer:o}=this.calculateOptimalSwitchPoint(n,i);this.scheduleTrackSwitch(i,a,o)}this.tickImmediate()}}function qc(t,e,s){if(e)for(let i=e.length;i--;){const r=e[i].interstitial,n=r.startTime,a=Math.min(n+r.duration,r.resumeTime);if(r.appendInPlace){if(t.start>=n&&t.end<=a)return!0;if(s>t.start&&t.end>n&&t.start<a)return!0}}return!1}function Wc(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}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 i=0;for(let e=0;e<t.length;e++){const r=t[e];s.set(r,i),i+=r.length}return s}(t,e),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Yc,zc={exports:{}};var Qc=(Yc||(Yc=1,function(t){var e=Object.prototype.hasOwnProperty,s="~";function i(){}function r(t,e,s){this.fn=t,this.context=e,this.once=s||!1}function n(t,e,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new r(i,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 i:delete t._events[e]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function(){var t,i,r=[];if(0===this._eventsCount)return r;for(i in t=this._events)e.call(t,i)&&r.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=s?s+t:t,i=this._events[e];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,a=new Array(n);r<n;r++)a[r]=i[r].fn;return a},o.prototype.listenerCount=function(t){var e=s?s+t:t,i=this._events[e];return i?i.fn?1:i.length:0},o.prototype.emit=function(t,e,i,r,n,a){var o=s?s+t:t;if(!this._events[o])return!1;var l,d,c=this._events[o],h=arguments.length;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),h){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,i),!0;case 4:return c.fn.call(c.context,e,i,r),!0;case 5:return c.fn.call(c.context,e,i,r,n),!0;case 6:return c.fn.call(c.context,e,i,r,n,a),!0}for(d=1,l=new Array(h-1);d<h;d++)l[d-1]=arguments[d];c.fn.apply(c.context,l)}else{var u,f=c.length;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(t,c[d].fn,void 0,!0),h){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,i);break;case 4:c[d].fn.call(c[d].context,e,i,r);break;default:if(!l)for(u=1,l=new Array(h-1);u<h;u++)l[u-1]=arguments[u];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,i,r){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||r&&!o.once||i&&o.context!==i||a(this,n);else{for(var l=0,d=[],c=o.length;l<c;l++)(o[l].fn!==e||r&&!o[l].once||i&&o[l].context!==i)&&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 i,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}(zc)),zc.exports),Xc=Qn(Qc);const Zc="1.7.2",Jc={};function th(t,e){return 255===t[e]&&240==(246&t[e+1])}function eh(t,e){return 1&t[e+1]?7:9}function sh(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function ih(t,e){return e+1<t.length&&th(t,e)}function rh(t,e){if(ih(t,e)){const s=eh(t,e);if(e+s>=t.length)return!1;const i=sh(t,e);if(i<=s)return!1;const r=e+i;return r===t.length||ih(t,r)}return!1}function nh(t,e,s,i,r){if(!t.samplerate){const n=function(t,e,s,i){const r=e[s+2],n=r>>2&15;if(n>12){const e=new Error(`invalid ADTS sampling index:${n}`);return void t.emit(zn.ERROR,zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const a=1+(r>>6&3),o=e[s+3]>>6&3|(1&r)<<2,l=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let d,c=n;5!==a&&29!==a||(c-=3);const h=(14&c)>>1,u=(1&c)<<7|o<<3;let f=0;if(1===a&&n>=6){f=5;const t=n-3;d=[f<<3|h,u|(14&t)>>1,(1&t)<<7|8,0]}else d=[a<<3|h,u];const g="mp4a.40."+(f||a);return Ua.log(`manifest codec:${i}, parsed codec:${g}, channels:${o}, rate:${l} (ADTS object type:${a} sampling index:${n} esds config:[${d.join(",")}])`),{config:d,samplerate:l,channelCount:o,codec:g,parsedCodec:g,manifestCodec:i}}(e,s,i,r);if(!n)return;Ta(t,n)}}function ah(t){return 9216e4/t}function oh(t,e,s,i,r){const n=i+r*ah(t.samplerate),a=function(t,e){const s=eh(t,e);if(e+s<=t.length){const i=sh(t,e)-s;if(i>0)return{headerLength:s,frameLength:i}}}(e,s);let o;if(a){const{frameLength:i,headerLength:r}=a,l=r+i,d=Math.max(0,s+l-e.length);d?(o=new Uint8Array(l-r),o.set(e.subarray(s+r,e.length),0)):o=e.subarray(s+r,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}}let lh=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function dh(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,i){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=Uo(this.cachedData,t),this.cachedData=null);let s,i=Xa(t,0),r=i?i.length:0;const n=this._audioTrack,a=this._id3Track,o=i?ao(i):void 0,l=t.length;for((null===this.basePTS||0===this.frameIndex&&Vn(o))&&(this.basePTS=ch(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:lh.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(t,r)){const e=this.appendFrame(n,t,r);e?(this.frameIndex++,this.lastPTS=e.sample.pts,r+=e.length,s=r):r=l}else za(t,r)?(i=Xa(t,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:lh.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,s=r):r++;if(r===l&&s!==l){const e=t.slice(s);this.cachedData?this.cachedData=Uo(this.cachedData,e):this.cachedData=e}}return{audioTrack:n,videoTrack:dh(),id3Track:a,textTrack:dh()}}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:dh(),id3Track:this._id3Track,textTrack:dh()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const ch=(t,e,s)=>{if(Vn(t))return 90*t;return 9e4*e+(s?9e4*s.baseTime/s.timescale:0)},hh=[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],uh=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],fh=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],gh=[0,1,1,4];function ph(t,e,s,i,r){if(s+24>e.length)return;const n=mh(e,s);if(n&&s+n.frameLength<=e.length){const a=i+r*(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 mh(t,e){const s=t[e+1]>>3&3,i=t[e+1]>>1&3,r=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==s&&0!==r&&15!==r&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*hh[14*(3===s?3-i:3===i?3:4)+r-1],d=uh[3*(3===s?0:2===s?1:2)+n],c=3===o?1:2,h=fh[s][i],u=gh[i],f=8*h*u,g=Math.floor(h*l/d+a)*u,p=Zo();return!!p&&p<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:d,channelCount:c,frameLength:g,samplesPerFrame:f}}}function vh(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function yh(t,e){return e+1<t.length&&vh(t,e)}function Eh(t,e){if(e+1<t.length&&vh(t,e)){const s=4,i=mh(t,e);let r=s;null!=i&&i.frameLength&&(r=i.frameLength);const n=e+r;return n===t.length||yh(t,n)}return!1}class SampleAesDecrypter{constructor(t,e,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Decrypter(e,!0)}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,gd,{start:0,end:t.byteLength})}decryptAacSample(t,e,s){const i=t[e].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(r=>{const n=new Uint8Array(r);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,s)}).catch(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 i=0;for(let e=32;e<t.length-16;e+=160,i+=16)s.set(t.subarray(e,e+16),i);return s}getAvcDecryptedUnit(t,e){const s=new Uint8Array(e);let i=0;for(let e=32;e<t.length-16;e+=160,i+=16)t.set(s.subarray(i,i+16),e);return t}decryptAvcSample(t,e,s,i,r){const n=Ho(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,s+1,i)}).catch(i)}decryptAvcSamples(t,e,s,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,s=0){if(e>=t.length)return void i();const r=t[e].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,s,i,n),this.decrypter.isSync())))return}}}}const Th=(t,e)=>{let s=0,i=5;e+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=t[e];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,s=s?s<<o|r[0]:r[0],e+=1,i-=o}return s};class AC3Demuxer extends BaseAudioDemuxer{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,s){const i=Sh(t,e,s,this.basePTS,this.frameIndex);if(-1!==i){return{sample:t.samples[t.samples.length-1],length:i,missing:0}}}static probe(t){if(!t)return!1;const e=Xa(t,0);if(!e)return!1;const s=e.length;if(11===t[s]&&119===t[s+1]&&void 0!==ao(e)){if(Th(t,s)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}}function Sh(t,e,s,i,r){if(s+8>e.length)return-1;if(11!==e[s]||119!==e[s+1])return-1;const n=e[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[s+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(s+l>e.length)return-1;const d=e[s+6]>>5;let c=0;2===d?c+=2:(1&d&&1!==d&&(c+=2),4&d&&(c+=2));const h=(e[s+6]<<8|e[s+7])>>12-c&1,u=[2,1,2,3,3,4,4,5][d]+h,f=e[s+5]>>3,g=7&e[s+5],p=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|d<<3|h<<2|o>>4,o<<4&224]),m=i+r*(1536/a*9e4),v=e.subarray(s,s+l);return t.config=p,t.channelCount=u,t.samplerate=a,t.samples.push({unit:v,pts:m}),l}const Ah=/\/emsg[-/]ID3/i;function _h(t,e){return Vn(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class BaseVideoParser{constructor(){this.VideoSample=null}createVideoSample(t,e,s){return{key:t,frame:!1,pts:e,dts:s,units:[],length:0}}getLastNalUnit(t){var e;let s,i=this.VideoSample;if(i&&0!==i.units.length||(i=t[t.length-1]),null!=(e=i)&&e.units){const t=i.units;s=t[t.length-1]}return s}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const s=e.samples,i=s.length;if(!i)return void e.dropped++;{const e=s[i-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,s){const i=e.byteLength;if(0===i)return[];const r=t.naluState||0,n=-1===r?0:r,a=[];let o=0,l=0,d=-1,c=0;for(-1===r&&(d=0,c=this.getNALuType(e,0),l=1);l<i;){const s=e.indexOf(1,l);if(-1===s)break;l=s+1;let r=s;for(;r>0&&0===e[r-1];)r--;if(!(s-r+(0===r?n:0)<2)){if(d>=0)a.push({data:e.subarray(d,r),type:c});else{const s=this.getLastNalUnit(t.samples);s&&(r>0?s.data=Uo(s.data,e.subarray(0,r)):n>0&&(s.data=s.data.subarray(0,s.data.byteLength-n)),s.state=0)}if(!(l<i)){o=-1,d=-1;break}d=l,c=this.getNALuType(e,l)}}if(-1!==o){let t=i;for(;t>0&&0===e[t-1];)t--;o=i-t+(0===t?n:0)}if(d>=0)a.push({data:e.subarray(d),type:c,state:o});else if(0===a.length&&-1!==o){const s=this.getLastNalUnit(t.samples);s&&(s.data=Uo(s.data,e),s.state=o)}return t.naluState=o,a}}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,i=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");i.set(t.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}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&&Ua.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(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)}}class AvcVideoParser extends BaseVideoParser{parsePES(t,e,s,i,r){const n=r.iframe,a=this.parseNALu(t,s.data,i);let o,l=this.VideoSample,d=!1;s.data=null,l&&a.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.forEach(i=>{var r,a;switch(i.type){case 1:{if(n)break;let e=!1;o=!0;const r=i.data;if(d&&r.length>4){const t=this.readSliceType(r);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var c;if(e)null!=(c=l)&&c.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null);l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.frame=!0,l.key=e;break}case 5:o=!0,null!=(r=l)&&r.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.key=!0,l.frame=!0;break;case 6:if(n)break;o=!0,Go(i.data,1,s.pts,e.samples);break;case 7:{var h,u;o=!0,d=!0;const e=i.data,s=this.readSPS(e);if(!t.sps||t.width!==s.width||t.height!==s.height||(null==(h=t.pixelRatio)?void 0:h[0])!==s.pixelRatio[0]||(null==(u=t.pixelRatio)?void 0:u[1])!==s.pixelRatio[1]){t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[e];const i=e.subarray(1,4);let r="avc1.";for(let t=0;t<3;t++){let e=i[t].toString(16);e.length<2&&(e="0"+e),r+=e}t.codec=r}break}case 8:o=!0,t.pps=[i.data];break;case 9:o=!0,t.audFound=!0,null!=(a=l)&&a.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1}if(l&&o){l.units.push(i)}}),i&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new ExpGolomb(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let s,i=8,r=8;for(let n=0;n<t;n++)0!==r&&(s=e.readEG(),r=(i+s+256)%256),i=0===r?i:r}readSPS(t){const e=new ExpGolomb(t);let s,i,r,n=0,a=0,o=0,l=0;const d=e.readUByte.bind(e),c=e.readBits.bind(e),h=e.readUEG.bind(e),u=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),p=e.skipUEG.bind(e),m=this.skipScalingList.bind(this);d();const v=d();if(c(5),f(3),d(),p(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const t=h();if(3===t&&f(1),p(),p(),f(1),u())for(i=3!==t?8:12,r=0;r<i;r++)u()&&m(r<6?16:64,e)}p();const y=h();if(0===y)h();else if(1===y)for(f(1),g(),g(),s=h(),r=0;r<s;r++)g();p(),f(1);const E=h(),T=h(),S=c(1);0===S&&f(1),f(1),u()&&(n=h(),a=h(),o=h(),l=h());let A=[1,1];if(u()&&u()){switch(d()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:A=[d()<<8|d(),d()<<8|d()]}}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:A}}}class HevcVideoParser extends BaseVideoParser{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,s,i){const r=this.parseNALu(t,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null;const l=t=>(a=this.VideoSample=this.createVideoSample(t,s.pts,s.dts),a);r.forEach((i,r)=>{var d,c;if(this.startsNewAccessUnit(a,t,i,r)){this.pushAccessUnit(a,t);const e=i.type>=16&&i.type<=23;a=l(e),o=!1}switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=l(!1)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:var h;if(n=!0,o)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 39:n=!0,Go(i.data,2,s.pts,e.samples);break;case 32:n=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=Ta(t.params,this.readVPS(i.data)),this.initVPS=i.data),t.vps=[i.data];break;case 33:if(n=!0,o=!0,void 0===t.vps||t.vps[0]===this.initVPS||void 0===t.sps||this.matchSPS(t.sps[0],i.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const e=this.readSPS(i.data);t.width=e.width,t.height=e.height,t.pixelRatio=e.pixelRatio,t.codec=e.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={});for(const s in e.params)t.params[s]=e.params[s]}this.pushParameterSet(t.sps,i.data,t.vps),a||(a=l(!1));break;case 34:if(n=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const e=this.readPPS(i.data);for(const s in e)t.params[s]=e[s]}this.pushParameterSet(t.pps,i.data,t.vps)}break;case 35:n=!0,t.audFound=!0,null!=(c=a)&&c.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=l(!1));break;default:n=!1}if(a&&n){a.units.push(i)}}),i&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}pushParameterSet(t,e,s){(s&&s[0]===this.initVPS||!s&&!t.length)&&t.push(e)}startsNewAccessUnit(t,e,s,i){if(!t)return!1;if(!e.audFound&&0===i)return!0;if(!t.frame)return!1;const{type:r,data:n}=s;return!!(r>=32&&r<=35||39===r||r>=41&&r<=44||r>=48&&r<=55)||r<=31&&n.length>2&&!!(128&n[2])}getNALuType(t,e){return(126&t[e])>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let s=0;for(let i=0;i<t.byteLength;i++)i>=2&&3===t[i]&&0===t[i-1]&&0===t[i-2]||(e[s]=t[i],s++);return new Uint8Array(e.buffer,0,s)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new ExpGolomb(t);e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6);return{numTemporalLayers:e.readBits(3)+1,temporalIdNested:e.readBoolean()}}readSPS(t){const e=new ExpGolomb(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const s=e.readBits(3);e.readBoolean();const i=e.readBits(2),r=e.readBoolean(),n=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),d=e.readUByte(),c=e.readUByte(),h=e.readUByte(),u=e.readUByte(),f=e.readUByte(),g=e.readUByte(),p=e.readUByte(),m=e.readUByte(),v=[],y=[];for(let t=0;t<s;t++)v.push(e.readBoolean()),y.push(e.readBoolean());if(s>0)for(let t=s;t<8;t++)e.readBits(2);for(let t=0;t<s;t++)v[t]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),y[t]&&e.readUByte();e.readUEG();const E=e.readUEG();3==E&&e.skipBits(1);const T=e.readUEG(),S=e.readUEG(),A=e.readBoolean();let _=0,b=0,L=0,R=0;A&&(_+=e.readUEG(),b+=e.readUEG(),L+=e.readUEG(),R+=e.readUEG());const I=e.readUEG(),k=e.readUEG(),w=e.readUEG();for(let t=e.readBoolean()?0:s;t<=s;t++)e.skipUEG(),e.skipUEG(),e.skipUEG();e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.readBoolean()){if(e.readBoolean())for(let t=0;t<4;t++)for(let s=0;s<(3===t?2:6);s++){if(e.readBoolean()){const s=Math.min(64,1<<4+(t<<1));t>1&&e.readEG();for(let t=0;t<s;t++)e.readEG()}else e.readUEG()}}e.readBoolean(),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const P=e.readUEG();let D=0;for(let t=0;t<P;t++){let s=!1;if(0!==t&&(s=e.readBoolean()),s){t===P&&e.readUEG(),e.readBoolean(),e.readUEG();let s=0;for(let t=0;t<=D;t++){const t=e.readBoolean();let i=!1;t||(i=e.readBoolean()),(t||i)&&s++}D=s}else{const t=e.readUEG(),s=e.readUEG();D=t+s;for(let s=0;s<t;s++)e.readUEG(),e.readBoolean();for(let t=0;t<s;t++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const t=e.readUEG();for(let s=0;s<t;s++){for(let t=0;t<w+4;t++)e.readBits(1);e.readBits(1)}}let C=0,O=1,M=1,x=!0,F=1,N=0;e.readBoolean(),e.readBoolean();let U=!1;if(e.readBoolean()){if(e.readBoolean()){const t=e.readUByte();t>0&&t<16?(O=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(O=e.readBits(16),M=e.readBits(16))}e.readBoolean()&&e.readBoolean();if(e.readBoolean()){e.readBits(3),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.readUByte(),e.readUByte())}e.readBoolean()&&(e.readUEG(),e.readUEG()),e.readBoolean(),e.readBoolean(),e.readBoolean(),U=e.readBoolean(),U&&(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG());if(e.readBoolean()){F=e.readBits(32),N=e.readBits(32);e.readBoolean()&&e.readUEG();if(e.readBoolean()){const t=e.readBoolean(),i=e.readBoolean();let r=!1;(t||i)&&(r=e.readBoolean(),r&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),r&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=s;n++){x=e.readBoolean();let s=!1;x||e.readBoolean()?e.readEG():s=e.readBoolean();const n=s?1:e.readUEG()+1;if(t)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(i)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),C=e.readUEG())}let B=T,$=S;if(A){let t=1,e=1;1===E?t=e=2:2==E&&(t=2),B=T-t*b-t*_,$=S-e*R-e*L}const G=i?["A","B","C"][i]:"",H=a<<24|o<<16|l<<8|d;let K=0;for(let t=0;t<32;t++)K=(K|(H>>t&1)<<31-t)>>>0;let V=K.toString(16);1===n&&"2"===V&&(V="6");return{codecString:`hvc1.${G}${n}.${V}.${r?"H":"L"}${m}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[a,o,l,d],general_constraint_indicator_flags:[c,h,u,f,g,p],general_level_idc:m,bit_depth:I+8,bit_depth_luma_minus8:I,bit_depth_chroma_minus8:k,min_spatial_segmentation_idc:C,chroma_format_idc:E,frame_rate:{fixed:x,fps:N/F}},width:B,height:$,pixelRatio:[O,M]}}readPPS(t){const e=new ExpGolomb(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.skipUEG(),e.skipUEG(),e.skipBits(2),e.skipBits(3),e.skipBits(2),e.skipUEG(),e.skipUEG(),e.skipEG(),e.skipBits(2);e.readBoolean()&&e.skipUEG(),e.skipEG(),e.skipEG(),e.skipBits(4);const s=e.readBoolean(),i=e.readBoolean();let r=1;return i&&s?r=0:i?r=3:s&&(r=2),{parallelismType:r}}matchSPS(t,e){return ho(t).substring(3)===ho(e).substring(3)}}const bh=188;class TSDemuxer{constructor(t,e,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=t,this.config=e,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(t,e){const s=TSDemuxer.syncOffset(t);return s>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),-1!==s}static syncOffset(t){const e=t.length;let s=Math.min(940,e-bh)+1,i=0;for(;i<s;){let r=!1,n=-1,a=0;for(let o=i;o<e;o+=bh){if(71!==t[o]||e-o!==bh&&71!==t[o+bh]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(s=Math.min(n+18612,t.length-bh)+1)),r||(r=0===Lh(t,o)),r&&a>1&&(0===n&&a>2||o+bh>s))return n}i++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:go[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,s,i,r,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=TSDemuxer.createTrack("video"),this._videoTrack.duration=i,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new PacketsIntegrityChecker(this.logger):null,this._audioTrack=TSDemuxer.createTrack("audio",i),this._id3Track=TSDemuxer.createTrack("id3"),this._txtTrack=TSDemuxer.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=s,t&&this.demux(t,0,n,"SAMPLE-AES"===(null==r?void 0:r.method))}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:s}=this;t&&(t.pesData=null),e&&(e.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,s,i=!1,r=!1){let n;i||(this.sampleAes=null);const a=this._videoTrack,o=this.videoIntegrityChecker,l=this._audioTrack,d=this._id3Track,c=this._txtTrack,h=s.iframe;let u=a.pid,f=a.pesData,g=l.pid,p=d.pid,m=this._klvPid,v=l.pesData,y=d.pesData,E=null,T=null,S=this.pmtParsed,A=this._pmtId,_=t.length;if(this.remainderData&&(_=(t=Uo(this.remainderData,t)).length,this.remainderData=null),_<bh&&!r)return this.remainderData=t,{audioTrack:l,videoTrack:a,id3Track:d,textTrack:c};const b=Math.max(0,TSDemuxer.syncOffset(t));_-=(_-b)%bh,_<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,_,t.buffer.byteLength-_));let L=0;for(let e=b;e<_;e+=bh)if(71===t[e]){const r=!!(64&t[e+1]),_=Lh(t,e);let L;if((48&t[e+3])>>4>1){if(L=e+5+t[e+4],L===e+bh)continue}else L=e+4;switch(_){case u:r&&(!f||null!=o&&o.isCorrupted||!(n=Ph(f,this.logger))||(this.readyVideoParser(a.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(a,c,n,!1,s)),f={data:[],size:0},null==o||o.reset(u)),null==o||o.handlePacket(t.subarray(e)),f&&(f.data.push(t.subarray(L,e+bh)),f.size+=e+bh-L);break;case g:if(h)break;if(r){if(v&&(n=Ph(v,this.logger)))switch(l.segmentCodec){case"aac":this.parseAACPES(l,n,s);break;case"mp3":this.parseMPEGPES(l,n);break;case"ac3":this.parseAC3PES(l,n)}v={data:[],size:0}}v&&(v.data.push(t.subarray(L,e+bh)),v.size+=e+bh-L);break;case p:if(h)break;r&&(y&&(n=Ph(y,this.logger))&&this.parseID3PES(d,n),y={data:[],size:0}),y&&(y.data.push(t.subarray(L,e+bh)),y.size+=e+bh-L);break;case m:if(h)break;r&&(E&&(n=Ph(E,this.logger))&&this.parseKlvPES(d,n),E={data:[],size:0}),E&&(E.data.push(t.subarray(L,e+bh)),E.size+=e+bh-L);break;case 0:r&&(L+=t[L]+1),A=this._pmtId=Rh(t,L);break;case A:{r&&(L+=t[L]+1);const n=Ih(t,L,this.typeSupported,i,this.observer,this.logger,this.config,s);u=n.videoPid,u>0&&(a.pid=u,a.segmentCodec=n.segmentVideoCodec),g=n.audioPid,g>0&&(l.pid=g,l.segmentCodec=n.segmentAudioCodec),p=n.id3Pid,p>0&&(d.pid=p),m=n.klvPid,m>0&&(this._klvPid=m),null===T||S||(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${T}'. Backtracking to sync byte @${b} to parse all TS packets.`),T=null,e=b-188),S=this.pmtParsed=!0;break}case 17:case 8191:break;default:T=_}}else L++;L>0&&kh(this.observer,new Error(`Found ${L} TS packet/s that do not start with 0x47`),s,void 0,this.logger),a.pesData=f,l.pesData=v,d.pesData=y;const R={audioTrack:l,videoTrack:a,id3Track:d,textTrack:c};return r&&this.extractRemainingSamples(R,s),R}flush(t,e){const{remainderData:s}=this;let i;return this.remainderData=null,i=s?this.demux(s,0,e,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(i,e),this.sampleAes?this.decrypt(i,this.sampleAes):i}extractRemainingSamples(t,e){const{audioTrack:s,videoTrack:i,id3Track:r,textTrack:n}=t,a=i.pesData,o=s.pesData,l=r.pesData,d=this.videoIntegrityChecker;let c;if(!a||null!=d&&d.isCorrupted||!(c=Ph(a,this.logger))?i.pesData=a:(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,n,c,!0,e),i.pesData=null)),o&&(c=Ph(o,this.logger))){switch(s.segmentCodec){case"aac":this.parseAACPES(s,c,e);break;case"mp3":this.parseMPEGPES(s,c);break;case"ac3":this.parseAC3PES(s,c)}s.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),s.pesData=o;l&&(c=Ph(l,this.logger))?(this.parseID3PES(r,c),r.pesData=null):r.pesData=l}demuxSampleAes(t,e,s,i){const r=this.demux(t,s,i,!0,!this.config.progressive),n=this.sampleAes=new SampleAesDecrypter(this.observer,this.config,e);return this.decrypt(r,n)}readyVideoParser(t){null===this.videoParser&&("avc"===t?this.videoParser=new AvcVideoParser:"hevc"===t&&(this.videoParser=new HevcVideoParser))}decrypt(t,e){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=t;i.samples&&"aac"===i.segmentCodec?e.decryptAacSamples(i.samples,0,()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,()=>{s(t)}):s(t)}):r.samples&&e.decryptAvcSamples(r.samples,0,0,()=>{s(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(t,e,s){let i=0;const r=this.aacOverFlow;let n,a,o,l=e.data;if(r){this.aacOverFlow=null;const e=r.missing,s=r.sample.unit.byteLength;if(-1===e)l=Uo(r.sample.unit,l);else{const n=s-e;r.sample.unit.set(l.subarray(0,e),n),t.samples.push(r.sample),i=r.missing}}for(n=i,a=l.length;n<a-1&&!ih(l,n);n++);if(n!==i){let t;const e=n<a-1;if(t=e?`AAC PES did not start with ADTS header,offset:${n}`:"No ADTS header found in AAC PES",kh(this.observer,new Error(t),s,e,this.logger),!e)return}if(nh(t,this.observer,l,n,this.audioCodec),void 0!==e.pts)o=e.pts;else{if(!r)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=ah(t.samplerate);o=r.sample.pts+e}}let d,c=0;for(;n<a;){if(d=oh(t,l,n,o,c),n+=d.length,d.missing){this.aacOverFlow=d;break}for(c++;n<a-1&&!ih(l,n);n++);}}parseMPEGPES(t,e){const s=e.data,i=s.length;let r=0,n=0;const a=e.pts;if(void 0!==a)for(;n<i;)if(yh(s,n)){const e=ph(t,s,n,a,r);if(!e)break;n+=e.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const s=e.data,i=e.pts;if(void 0===i)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=s.length;let n,a=0,o=0;for(;o<r&&(n=Sh(t,s,o,i,a++))>0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=Ta({},e,{type:this._videoTrack?lh.emsg:lh.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}parseKlvPES(t,e){var s;const i=null!=(s=e.pts)?s:e.dts;if(void 0===i)return void this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");const r=e.data;if(r.length<16)return void this.logger.warn("[tsdemuxer]: KLV PES payload too short");let n=0;for(;n<r.length;){var a;if(n+16>r.length)break;const s=n;if(n+=16,n>=r.length)break;const o=r[n];n+=1;let l=0;if(128&o){const t=127&o;if(0===t||t>4||n+t>r.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let e=0;e<t;e++)l=l<<8|r[n+e];n+=t}else l=o;if(n+l>r.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const d=n+l,c=r.subarray(s,d),h={data:c,len:c.byteLength,pts:i,dts:null!=(a=e.dts)?a:i,type:lh.misbklv,duration:Number.POSITIVE_INFINITY};t.samples.push(h),n=d}}}function Lh(t,e){return((31&t[e+1])<<8)+t[e+2]}function Rh(t,e){return(31&t[e+10])<<8|t[e+11]}function Ih(t,e,s,i,r,n,a,o){const l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},d=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<d;){const d=Lh(t,e),c=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!i){wh("ADTS AAC",n);break}case 15:-1===l.audioPid&&(l.audioPid=d);break;case 21:-1===l.id3Pid&&(l.id3Pid=d);break;case 219:if(!i){wh("H.264",n);break}case 27:-1===l.videoPid&&(l.videoPid=d);break;case 3:case 4:s.mpeg||s.mp3?-1===l.audioPid&&(l.audioPid=d,l.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){wh("AC-3",n);break}case 129:s.ac3?-1===l.audioPid&&(l.audioPid=d,l.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(c>0){let i=e+5,r=c;for(;r>2;){switch(t[i]){case 106:-1===l.audioPid&&(!0!==s.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=d,l.segmentAudioCodec="ac3"));break;case 5:-1===l.klvPid&&a.enableEmsgKLVMetadata&&(l.klvPid=d,n.log(`KLV metadata PID found: ${d}`))}const e=t[i+1]+2;i+=e,r-=e}}break;case 194:case 135:return kh(r,new Error("Unsupported EC-3 in M2TS found"),o,void 0,n),l;case 36:-1===l.videoPid&&(l.videoPid=d,l.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}e+=c+5}return l}function kh(t,e,s,i,r){r.warn(`parsing error: ${e.message}`),t.emit(zn.ERROR,zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,chunkMeta:s,error:e,reason:e.message})}function wh(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Ph(t,e){let s,i,r,n,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Uo(l[0],l[1]),l.splice(1,1);s=l[0];if(1===(s[0]<<16)+(s[1]<<8)+s[2]){if(i=(s[4]<<8)+s[5],i&&i>t.size-6)return null;const d=s[7];192&d&&(n=536870912*(14&s[9])+4194304*(255&s[10])+16384*(254&s[11])+128*(255&s[12])+(254&s[13])/2,64&d?(a=536870912*(14&s[14])+4194304*(255&s[15])+16384*(254&s[16])+128*(255&s[17])+(254&s[18])/2,n-a>54e5&&(e.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=s[8];let c=r+9;if(t.size<=c)return null;t.size-=c;const h=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){s=l[t];let e=s.byteLength;if(c){if(c>e){c-=e;continue}s=s.subarray(c),e-=c,c=0}h.set(s,o),o+=e}return i&&(i-=r+3),{data:h,pts:n,dts:a,len:i}}return null}class PacketsIntegrityChecker{constructor(t){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=t}get isCorrupted(){return"ok"!==this.integrityState}reset(t){this.pid=t,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(t){if(t.byteLength<4)return;const e=Lh(t,0);if(e!==this.pid)return void this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${e}`);const s=(48&t[3])>>4;if(0===s)return;const i=15&t[3],r=this.lastContinuityCounter;this.lastContinuityCounter=i;const n=!!(1&s);if(!!(2&s)&&0!=t[4]&&!!(128&t[5]))return;if(r<0)return;const a=n?r+1&15:r;return i!==a?(this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${e}', CC=${i}, Expected-CC=${a} Last-CC=${r}`),void(this.integrityState="cc-failed")):128&t[1]?(this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${e}'`),void(this.integrityState="tei-bit")):void 0}}class AAC{static getSilentFrame(t,e){if("mp4a.40.2"===t){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])}else{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])}}}var Dh;const Ch={video: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]),audio: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])},Oh=new Uint8Array([0,0,0,0,0,0,0,0]),Mh=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),xh=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Fh=new Uint8Array([0,0,0,0,0,0,0,0]),Nh=new Uint8Array([0,0,0,0,0,0,0,1]),Uh=new Uint8Array([105,115,111,109]),Bh=new Uint8Array([97,118,99,49]),$h=new Uint8Array([0,0,0,1]);class MP4{static box(t,...e){let s=8,i=e.length;const r=i;for(;i--;)s+=e[i].byteLength;const n=new Uint8Array(s);for(To(n,0,s),To(n,4,t),i=0,s=8;i<r;i++)n.set(e[i],s),s+=e[i].byteLength;return n}static hdlr(t){return MP4.box(fo.hdlr,Ch[t])}static mdat(t){return MP4.box(fo.mdat,t)}static mdhd(t,e){e*=t;const s=Math.floor(e/(uo+1)),i=Math.floor(e%(uo+1));return MP4.box(fo.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,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}static mdia(t){return MP4.box(fo.mdia,MP4.mdhd(t.timescale||0,t.duration||0),MP4.hdlr(t.type),MP4.minf(t))}static mfhd(t){return MP4.box(fo.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(fo.minf,MP4.box(fo.smhd,Fh),MP4.DINF,MP4.stbl(t)):MP4.box(fo.minf,MP4.box(fo.vmhd,xh),MP4.DINF,MP4.stbl(t))}static moof(t,e,s){return MP4.box(fo.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,[fo.moov,MP4.mvhd(t[0].timescale||0,t[0].duration||0)].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,[fo.mvex,...s])}static mvhd(t,e){e*=t;const s=Math.floor(e/(uo+1)),i=Math.floor(e%(uo+1)),r=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,i>>24,i>>16&255,i>>8&255,255&i,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(fo.mvhd,r)}static sdtp(t){const e=t.samples||[],s=new Uint8Array(4+e.length);let i,r;for(i=0;i<e.length;i++)r=e[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return MP4.box(fo.sdtp,s)}static stbl(t){return MP4.box(fo.stbl,MP4.stsd(t),MP4.box(fo.stts,Oh),MP4.box(fo.stsc,Oh),MP4.box(fo.stsz,Mh),MP4.box(fo.stco,Oh))}static avc1(t){let e,s,i,r=[],n=[];for(e=0;e<t.sps.length;e++)s=t.sps[e],i=s.byteLength,r.push(i>>>8&255),r.push(255&i),r=r.concat(Array.prototype.slice.call(s));for(e=0;e<t.pps.length;e++)s=t.pps[e],i=s.byteLength,n.push(i>>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(s));const a=MP4.box(fo.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,d=t.pixelRatio[0],c=t.pixelRatio[1];return MP4.box(fo.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(fo.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),MP4.box(fo.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,s=e.length;return new Uint8Array([0,0,0,0,3,23+s,0,1,0,4,15+s,64,21,0,0,0,0,0,0,0,0,0,0,0,5,s,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return MP4.box(fo.mp4a,MP4.audioStsd(t),MP4.box(fo.esds,MP4.esds(t)))}static mp3(t){return MP4.box(fo[".mp3"],MP4.audioStsd(t))}static ac3(t){return MP4.box(fo["ac-3"],MP4.audioStsd(t),MP4.box(fo.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return MP4.box(fo.stsd,Nh,MP4.mp4a(t));if("ac3"===e&&t.config)return MP4.box(fo.stsd,Nh,MP4.ac3(t));if("mp3"===e&&"mp3"===t.codec)return MP4.box(fo.stsd,Nh,MP4.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return MP4.box(fo.stsd,Nh,MP4.avc1(t));if("hevc"===e&&t.vps)return MP4.box(fo.stsd,Nh,MP4.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,s=(t.duration||0)*(t.timescale||0),i=t.width||0,r=t.height||0,n=Math.floor(s/(uo+1)),a=Math.floor(s%(uo+1));return MP4.box(fo.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,i>>8&255,255&i,0,0,r>>8&255,255&r,0,0]))}static traf(t,e){const s=MP4.sdtp(t),i=t.id,r=Math.floor(e/(uo+1)),n=Math.floor(e%(uo+1));return MP4.box(fo.traf,MP4.box(fo.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),MP4.box(fo.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,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(fo.trak,MP4.tkhd(t),MP4.mdia(t))}static trex(t){const e=t.id;return MP4.box(fo.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||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let a,o,l,d,c,h;for(e+=8+r,n.set(["video"===t.type?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<i;a++)o=s[a],l=o.duration,d=o.size,c=o.flags,h=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,h>>>24&255,h>>>16&255,h>>>8&255,255&h],12+16*a);return MP4.box(fo.trun,n)}static initSegment(t){const e=MP4.moov(t);return Uo(MP4.FTYP,e)}static hvc1(t){const e=t.params,s=[t.vps,t.sps,t.pps],i=new Uint8Array([1,e.general_profile_space<<6|(e.general_tier_flag?32:0)|e.general_profile_idc,e.general_profile_compatibility_flags[0],e.general_profile_compatibility_flags[1],e.general_profile_compatibility_flags[2],e.general_profile_compatibility_flags[3],e.general_constraint_indicator_flags[0],e.general_constraint_indicator_flags[1],e.general_constraint_indicator_flags[2],e.general_constraint_indicator_flags[3],e.general_constraint_indicator_flags[4],e.general_constraint_indicator_flags[5],e.general_level_idc,240|e.min_spatial_segmentation_idc>>8,255&e.min_spatial_segmentation_idc,252|e.parallelismType,252|e.chroma_format_idc,248|e.bit_depth_luma_minus8,248|e.bit_depth_chroma_minus8,0,parseInt(e.frame_rate.fps),3|e.temporal_id_nested<<2|e.num_temporal_layers<<3|(e.frame_rate.fixed?64:0),s.length]);let r=i.length;for(let t=0;t<s.length;t+=1){r+=3;for(let e=0;e<s[t].length;e+=1)r+=2+s[t][e].length}const n=new Uint8Array(r);n.set(i,0),r=i.length;const a=s.length-1;for(let t=0;t<s.length;t+=1){n.set(new Uint8Array([32+t|(t===a?128:0),0,s[t].length]),r),r+=3;for(let e=0;e<s[t].length;e+=1)n.set(new Uint8Array([s[t][e].length>>8,255&s[t][e].length]),r),r+=2,n.set(s[t][e],r),r+=s[t][e].length}const o=MP4.box(fo.hvcC,n),l=t.width,d=t.height,c=t.pixelRatio[0],h=t.pixelRatio[1];return MP4.box(fo.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,d>>8&255,255&d,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,MP4.box(fo.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),MP4.box(fo.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,h>>24,h>>16&255,h>>8&255,255&h])))}}Dh=MP4,MP4.FTYP=Dh.box(fo.ftyp,Uh,$h,Uh,Bh),MP4.DINF=Dh.box(fo.dinf,Dh.box(fo.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));function Gh(t,e,s=1,i=!1){const r=t*e*s;return i?Math.round(r):r}function Hh(t,e=!1){return Gh(t,1e3,1/9e4,e)}function Kh(t){const{baseTime:e,timescale:s,trackId:i}=t;return`${e/s} (${e}/${s}) trackId: ${i}`}const Vh=8589934592;function jh(t,e,s,i){return{duration:e,size:s,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1,paddingValue:0}}}class MP4Remuxer extends Logger{constructor(t,e,s,i){super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=s,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;e&&t&&t.trackId===e.trackId&&t.baseTime===e.baseTime&&t.timescale===e.timescale||this.log(`Reset initPTS: ${e?Kh(e):e} > ${t?Kh(t):t}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const s=t[0].pts,i=t.reduce((t,i)=>{let r=i.pts,n=r-t;return n<-4294967296&&(e=!0,r=qh(r,s),n=r-t),n>0?t:r},s);return e&&this.debug("PTS rollover detected"),i}remux(t,e,s,i,r,n,a,o,l){let d,c,h,u,f,g,p=r,m=r;const v=!l.iframe&&t.pid>-1,y=e.pid>-1,E=e.samples.length,T=t.samples.length>0,S=a&&E>0||E>1;if((!v||T)&&(!y||S)||this.ISGenerated||a){if(this.ISGenerated){var A,_,b,L;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(A=e.pixelRatio)?void 0:A[0])!==(null==(_=t.pixelRatio)?void 0:_[0])||(null==(b=e.pixelRatio)?void 0:b[1])!==(null==(L=t.pixelRatio)?void 0:L[1]))||!t&&S||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,e,r,n));const s=this.isVideoContiguous;let i,a=-1;if(S&&(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(g=!0,a>0){this.warn(`Dropped ${a} out of ${E} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,m+=(e.samples[0].pts-t)/e.inputTimeScale,i=m}else-1===a&&(this.warn(`No keyframe found out of ${E} video samples`),g=!1);if(this.ISGenerated){if(T&&S&&r){const s=this.getVideoStartPts(e.samples),i=(qh(t.samples[0].pts,s)-s)/e.inputTimeScale;p+=Math.max(0,i),m+=Math.max(0,-i)}if(T){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(t,e,r,n)),c=this.remuxAudio(t,p,this.isAudioContiguous,n,y||S||o===ca?m:void 0,l),S){const i=c?c.endPTS-c.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(t,e,r,n)),d=this.remuxVideo(e,m,s,i,l)}}else S&&(d=this.remuxVideo(e,m,s,0,l));d&&(d.firstKeyFrame=a,d.independent=-1!==a,d.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=Wh(s,r,this._initPTS,this._initDTS)),i.samples.length&&(u=Yh(i,r,this._initPTS))),{audio:c,video:d,initSegment:h,independent:g,text:u,id3:f}}computeInitPts(t,e,s,i){const r=Math.round(s*e);let n=qh(t,r);if(n<r)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/e} ${i}`);n<r;)n+=Vh;return n-r}generateIS(t,e,s,i){const r=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS,d=!l||i;let c,h,u,f="audio/mp4",g=-1;if(d&&(c=h=1/0),t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}if(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}},d){g=t.id,u=t.inputTimeScale;const e=this.computeInitPts(r[0].pts,u,s,"audio");(!l||u!==l.timescale||0===s&&e<l.baseTime)&&(c=h=e)}}if(e.sps&&e.pps&&n.length){if(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}},d){g=e.id,u=e.inputTimeScale;const t=this.getVideoStartPts(n),i=qh(n[0].dts,t),r=this.computeInitPts(i,u,s,"video"),a=this.computeInitPts(t,u,s,"video");(!l||u!==l.timescale||Vn(c)||0===s&&a<l.baseTime)&&(h=Math.min(h,r),c=Math.min(c,r))}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,d&&Vn(c)?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${c/u} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${c/u} (${c}/${u}) trackId: ${g}`),this._initPTS={baseTime:c,timescale:u,trackId:g},this._initDTS={baseTime:h,timescale:u,trackId:g}):c=u=void 0,{tracks:o,initPTS:c,timescale:u,trackId:g}}remuxVideo(t,e,s,i,r){const n=t.inputTimeScale,a=t.samples,o=[],l=a.length,d=this._initPTS,c=d.baseTime*n/d.timescale;let h,u,f=this.nextVideoTs,g=8,p=this.videoSampleDuration,m=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,y=!1;if(!s||null===f){const t=c+e*n,i=a[0].pts-qh(a[0].dts,a[0].pts);Zo()&&null!==f&&Math.abs(t-i-(f+c))<15e3?s=!0:f=t-i-c}const E=f+c;for(let t=0;t<l;t++){const e=a[t];e.pts=qh(e.pts,E),e.dts=qh(e.dts,E),e.dts<a[t>0?t-1:t].dts&&(y=!0)}y&&a.sort(function(t,e){const s=t.dts-e.dts,i=t.pts-e.pts;return s||i}),h=a[0].dts,u=a[a.length-1].dts;const T=u-h,S=T?Math.round(T/(l-1)):p||t.inputTimeScale/30;if(s){const s=h-E,i=s>S,r=s<-1;if((i||r)&&(i?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Hh(s,!0)} ms (${s}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Hh(-s,!0)} ms (${s}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||E>=a[0].pts||Zo())){h=E;const t=a[0].pts-s;if(i)a[0].dts=h,a[0].pts=t;else{let e=!0;for(let i=0;i<a.length&&!(a[i].dts>t&&e);i++){const t=a[i].pts;if(a[i].dts-=s,a[i].pts-=s,i<a.length-1){const s=a[i+1].pts;e=s<=a[i].pts==s<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${Hh(t,!0)}/${Hh(h,!0)}, delta: ${Hh(s,!0)} ms`)}}h=Math.max(0,h);let A=0,_=0,b=h;for(let t=0;t<l;t++){const e=a[t],s=e.units,i=s.length;let r=0;for(let t=0;t<i;t++)r+=s[t].data.length;_+=r,A+=i,e.length=r,e.dts<b?(e.dts=b,b+=S/4|0||1):b=e.dts,m=Math.min(e.pts,m),v=Math.max(e.pts,v)}u=a[l-1].dts;const L=_+4*A+8;let R;try{R=new Uint8Array(L)}catch(t){return void this.observer.emit(zn.ERROR,zn.ERROR,{type:Wn.MUX_ERROR,details:Yn.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:r,error:t,bytes:L,reason:`fail allocating video mdat ${L}`})}To(R,0,L),To(R,4,fo.mdat);let I=!1,k=Number.POSITIVE_INFINITY,w=Number.POSITIVE_INFINITY,P=Number.NEGATIVE_INFINITY,D=Number.NEGATIVE_INFINITY;for(let t=0;t<l;t++){const e=a[t],d=e.units;let h,u=0;for(let t=0,e=d.length;t<e;t++){const e=d[t],s=e.data,i=e.data.byteLength;To(R,g,i),g+=4,R.set(s,g),g+=i,u+=4+i}if(t<l-1)p=a[t+1].dts-e.dts,h=a[t+1].pts-e.pts;else{const s=this.config,r=t>0?e.dts-a[t-1].dts:S;if(h=t>0?e.pts-a[t-1].pts:S,s.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(s.maxBufferHole*n),a=(i?m+i*n:this.nextAudioTs+c)-e.pts;a>t?(p=a-r,p<0?p=r:I=!0,this.log(`It is approximately ${a/90} ms to the next segment; using duration ${p/90} ms for the last video frame.`)):p=r}else p=r}let f=Math.round(e.pts-e.dts);if(k=Math.min(k,p),P=Math.max(P,p),w=Math.min(w,h),D=Math.max(D,h),!s&&0===t&&f>p){const t=Math.round(f/S)*S;t-f===1&&(this.log(`pad first CTS ${f} -> ${t} of sn: ${r.sn}`),f=t)}o.push(jh(e.key,p,u,f))}if(o.length){const t=Zo();if(t){if(t<70){const t=o[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(function(){if(void 0===Qo){const t=qo.match(/Safari\/(\d+)/i);Qo=t?parseInt(t[1]):0}return Qo}()&&D-w<P-k&&S/P<.025&&0===o[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=h;for(let e=0,s=o.length;e<s;e++){const i=t+o[e].duration,r=t+o[e].cts;if(e<s-1){const t=i+o[e+1].cts;o[e].duration=t-r}else o[e].duration=e?o[e-1].duration:S;o[e].cts=0,t=i}}}p=I||!p?S:p;const C=u+p;this.nextVideoTs=f=C-c,this.videoSampleDuration=p,this.isVideoContiguous=!0,r.iframe&&(1===o.length?(o[0].duration=p=r.duration*n,this.nextVideoTs=f=h+p-c):this.warn(`Not adjusting IFrame duration (sample count ${o.length})`));const O={data1:MP4.moof(r.sn,h,Ta(t,{samples:o})),data2:R,startPTS:(m-c)/n,endPTS:(v+p-c)/n,startDTS:(h-c)/n,endDTS:f/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:t.dropped};return t.samples=[],t.dropped=0,O}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,s,i,r,n){const a=t.inputTimeScale,o=a/(t.samplerate?t.samplerate:a),l=this.getSamplesPerFrame(t),d=l*o,c=this._initPTS,h="mp3"===t.segmentCodec&&this.typeSupported.mpeg,u=[],f=void 0!==r;let g=t.samples,p=h?0:8,m=this.nextAudioTs||-1;const v=c.baseTime*a/c.timescale,y=v+e*a;if(this.isAudioContiguous=s=s||g.length&&m>0&&(i&&Math.abs(y-(m+v))<9e3||Math.abs(qh(g[0].pts,y)-(m+v))<20*d),g.forEach(function(t){t.pts=qh(t.pts,y)}),!s||m<0){const t=g.length;if(g=g.filter(t=>t.pts>=0),t!==g.length&&this.warn(`Removed ${g.length-t} of ${t} samples (initPTS ${v} / ${a})`),!g.length)return;m=0===r?0:i&&!f?Math.max(0,y-v):g[0].pts-v}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let s=0,i=m+v;s<g.length;s++){const r=g[s],n=r.pts,o=n-i,l=Math.abs(1e3*o/a);if(o<=-e*d&&f)0===s&&(this.warn(`Audio frame @ ${(n/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/a)} ms.`),this.nextAudioTs=m=n-v,i=n);else if(o>=e*d&&l<1e4&&f){let e=Math.round(o/d);for(i=n-e*d;i<0&&e&&d;)e--,i+=d;0===s&&(this.nextAudioTs=m=i-v),this.warn(`Injecting ${e} audio frames @ ${((i-v)/a).toFixed(3)}s due to ${Math.round(1e3*o/a)} ms gap.`);for(let n=0;n<e;n++){let e=AAC.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);e||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),e=r.unit.subarray()),g.splice(s,0,{unit:e,pts:i}),i+=d,s++}}r.pts=i,i+=d}}let E,T=null,S=null,A=0,_=g.length;for(;_--;)A+=g[_].unit.byteLength;for(let e=0,i=g.length;e<i;e++){const i=g[e],r=i.unit;let a=i.pts;if(null!==S){u[e-1].duration=Math.round((a-S)/o)}else{if(s&&"aac"===t.segmentCodec&&(a=m+v),T=a,!(A>0))return;A+=p;try{E=new Uint8Array(A)}catch(t){return void this.observer.emit(zn.ERROR,zn.ERROR,{type:Wn.MUX_ERROR,details:Yn.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:n,error:t,bytes:A,reason:`fail allocating audio mdat ${A}`})}h||(To(E,0,A),To(E,4,fo.mdat))}E&&E.set(r,p);const d=r.byteLength;p+=d,u.push(jh(!0,l,d,0)),S=a}const b=u.length;if(!b)return;const L=u[u.length-1];m=S-v,this.nextAudioTs=m+o*L.duration;const R=h?new Uint8Array(0):MP4.moof(t.sequenceNumber++,T/o,Ta({},t,{samples:u}));t.samples=[];const I=(T-v)/a,k=this.nextAudioTs/a,w={data1:R,data2:E,startPTS:I,endPTS:k,startDTS:I,endDTS:k,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,w}}function qh(t,e){let s;if(null===e)return t;for(s=e<t?-8589934592:Vh;Math.abs(t-e)>4294967296;)t+=s;return t}function Wh(t,e,s,i){const r=t.samples.length;if(!r)return;const n=t.inputTimeScale;for(let a=0;a<r;a++){const r=t.samples[a];r.pts=qh(r.pts-s.baseTime*n/s.timescale,e*n)/n,r.dts=qh(r.dts-i.baseTime*n/i.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function Yh(t,e,s){const i=t.samples.length;if(!i)return;const r=t.inputTimeScale;for(let n=0;n<i;n++){const i=t.samples[n];i.pts=qh(i.pts-s.baseTime*r/s.timescale,e*r)/r}t.samples.sort((t,e)=>t.pts-e.pts);const n=t.samples;return t.samples=[],{samples:n}}function zh(t,e,s=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(s?t.duration:0))/t.timescale:e}function Qh(t,e,s){const i=t.codec;if(i&&i.length>4)return i;if(e===ua){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return dl(i,!1)}return s.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"}return"mjpg"===i?i:(s.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}let Xh;try{Xh=self.performance.now.bind(self.performance)}catch(t){Xh=Date.now}const Zh=[{demux:class MP4Demuxer{constructor(t,e,s,i=Ua){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.initData=void 0,this.logger=void 0,this.config=e,this.logger=i}resetTimeStamp(){}resetInitSegment(t,e,s,i){const r=this.videoTrack=dh("video",1),n=this.audioTrack=dh("audio",1),a=this.txtTrack=dh("text",1);if(this.id3Track=dh("id3",1),this.initData=void 0,this.timeOffset=0,null==t||!t.byteLength)return;const o=this.initData=Io(t);if(o.video){const{id:t,timescale:e,codec:s,supplemental:i}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=s,r.supplemental=i}if(o.audio){const{id:t,timescale:e,codec:s}=o.audio;n.id=t,n.timescale=e,n.codec=s}a.id=go.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(t){return function(t,e){const s=t.byteLength;for(let i=0;i<s;){const r=mo(t,i);if(r>8&&mo(t,i+4)===fo[e])return!0;i=r>1?i+r:s}return!1}(t,"moof")}demux(t,e,s){this.timeOffset=e;let i=t;const r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Uo(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},s=bo(t,["moof"]);if(s.length<2)return e.remainder=t,e;const i=s[s.length-1];return e.valid=t.slice(0,i.byteOffset-8),e.remainder=t.slice(i.byteOffset-8),e}(i);this.remainderData=e.remainder,r.samples=e.valid||new Uint8Array}else r.samples=i;const a=this.extractID3Track(r,e),o=this.parseFragment(r,n,e,s);return{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack,initData:this.initData,sampleData:o}}flush(t,e){const s=this.timeOffset,i=this.videoTrack,r=this.txtTrack;i.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(i,this.timeOffset),a=this.parseFragment(i,r,s,e);return{videoTrack:i,audioTrack:dh(),id3Track:n,textTrack:dh(),initData:this.initData,sampleData:a}}parseFragment(t,e,s,i){const r=this.initData;if(r&&i){const{samples:n,sampleData:a}=function(t,e,s,i,r=!1){const n=[];return{samples:n,sampleData:{includeSampleDetails:r,tracks:No(e.samples,s,i,r,{isHEVCFlavor:Bo(e.codec),samples:n,timeOffset:t,timescale:e.timescale,trackId:e.id})}}}(s,t,r,this.logger,i.iframe);return e.samples=n,a}e.samples=function(t,e){const s=[],i=e.samples,r=e.timescale,n=e.id;let a=!1;return bo(i,["moof"]).map(o=>{const l=o.byteOffset-8;bo(o,["traf"]).map(o=>{const d=bo(o,["tfdt"]).map(t=>{const e=t[0];let s=mo(t,4);return 1===e&&(s*=Math.pow(2,32),s+=mo(t,8)),s/r})[0];return void 0!==d&&(t=d),bo(o,["tfhd"]).map(d=>{const c=mo(d,4),h=16777215&mo(d,0),u=!!(1&h);let f=0;const g=!!(2&h),p=!!(8&h);let m=0;const v=!!(16&h);let y=0;const E=!!(32&h),T=!u&&!!(131072&h);let S=8;c===n&&(u?(f=mo(d,S),S+=4,f*=Math.pow(2,32),f+=mo(d,S),S+=4):T&&(f=l),g&&(S+=4),p&&(m=mo(d,S),S+=4),v&&(y=mo(d,S),S+=4),E&&(S+=4),"video"===e.type&&(a=Bo(e.codec)),bo(o,["trun"]).map(n=>{const o=n[0],l=16777215&mo(n,0),d=!!(1&l);let c=0;const h=!!(4&l),u=!!(256&l);let g=0;const p=!!(512&l);let v=0;const E=!!(1024&l),T=!!(2048&l);let S=0;const A=mo(n,4);let _=8;d&&(c=mo(n,_),_+=4),h&&(_+=4);let b=f+c;for(let l=0;l<A;l++){if(u?(g=mo(n,_),_+=4):g=m,p?(v=mo(n,_),_+=4):v=y,E&&(_+=4),T&&(S=0===o?mo(n,_):Eo(n,_),_+=4),e.type===fa){let e=0;for(;e<v;){const n=mo(i,b);b+=4,$o(a,i[b])&&Go(i.subarray(b,b+n),a?2:1,t+S/r,s),b+=n,e+=n+4}}t+=g/r}}))})})}),s}(s,t)}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const i=bo(t.samples,["emsg"]);i&&i.forEach(t=>{const i=function(t){const e=t[0];let s,i="",r="",n=0,a=0,o=0,l=0,d=4;if(0===e){const e=yo(t,d),s=null!==e?yo(t,d+e.length):null;null!==e&&null!==s?(i=e,r=s,d+=e.length+s.length,n=mo(t,d),d+=4,a=mo(t,d),d+=4,o=mo(t,d),d+=4,l=mo(t,d),d+=4):(Ua.warn(`Unterminated ${null===e?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),d=t.length)}else if(1===e){n=mo(t,d),d+=4;const e=mo(t,d);d+=4;const a=mo(t,d);d+=4,s=2**32*e+a,jn(s)||(s=Number.MAX_SAFE_INTEGER,Ua.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=mo(t,d),d+=4,l=mo(t,d),d+=4;const c=yo(t,d),h=null!==c?yo(t,d+c.length):null;null!==c&&(i=c,d+=c.length),null!==h?(r=h,d+=h.length):(Ua.warn(`Unterminated ${null===c?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${null===c?"strings and payload":"value and payload"}`),d=t.length)}return{schemeIdUri:i,value:r,timeScale:n,presentationTime:s,presentationTimeDelta:a,eventDuration:o,id:l,payload:t.subarray(d,t.byteLength)}}(t);if(Ah.test(i.schemeIdUri)){const t=_h(i,e);let r=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=i.payload;s.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:lh.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata){const t=this.config.emsgKLVSchemaUri||lh.misbklv;if(i.schemeIdUri.startsWith(t)){const t=_h(i,e);s.samples.push({data:i.payload,len:i.payload.byteLength,dts:t,pts:t,type:lh.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return s}demuxSampleAes(t,e,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}},remux:class PassThroughRemuxer extends Logger{constructor(t,e,s,i){super("passthrough-remuxer",i),this.observer=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=t}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(t){this.lastEndTime=null;const e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,s,i){this.audioCodec=e,this.videoCodec=s,this.decryptdata=i,this.pendingInitSegment=t,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(t,e,s){this.videoOnlyRemux=!1;let{audioCodec:i,videoCodec:r}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:n,video:a}=this.initData=s||Io(t);if(e)!function(t,e){if(!t||!e)return;const s=e.keyId;16===(null==s?void 0:s.byteLength)&&e.isCommonEncryption&&Oo(t,(t,e)=>{const i=t.subarray(8,24);i.some(t=>0!==t)||(Ua.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${oo(i)} -> ${oo(s)}`),t.set(s,8))})}(t,e);else{const t=n||a;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}n&&(i=Qh(n,ua,this)),a&&(r=Qh(a,fa,this));const o={};n&&a?o.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:n?o.audio={container:"audio/mp4",codec:i,encrypted:n.encrypted,initSegment:t,id:"audio"}:a?o.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(t,e,s,i,r,n,a,o,l,d,c){var h,u;let{initPTS:f,lastEndTime:g}=this;const p={audio:void 0,video:void 0,text:void 0,id3:s,initSegment:void 0};Vn(g)||(g=this.lastEndTime=r||0);const m=e.samples;if(!m.length)return p;const v=this.pendingInitSegment;v&&(this.pendingInitSegment=void 0,this.generateInitSegment(v,this.decryptdata,d));const y={initPTS:void 0,timescale:void 0,trackId:void 0};let E=this.initData;if(null!=(h=E)&&h.length||(this.generateInitSegment(m),E=this.initData),null==(u=E)||!u.length)return this.warn("Failed to generate initSegment."),p;if(l.iframe&&E.audio&&E.video){var T;const t=null==(T=this.initTracks)||null==(T=T.audiovideo)?void 0:T.initSegment,e=t?function(t){const e=bo(t,["moov"]);if(1!==e.length||bo(t,["moof"]).length)return null;const s=t.byteOffset,i=[],r=[];let n=!1;const a=bo(e[0],["trak"]);for(let t=0;t<a.length;t++){const e=a[t],o=bo(e,["mdia","hdlr"])[0];if("vide"===(o?ho(o.subarray(8,12)):"")){n=!0;continue}const l=bo(e,["tkhd"])[0];if(!l)return null;const d=l[0];r.push(mo(l,0===d?12:20)),i.push(Ao(e,s))}if(!n||!i.length)return null;const o=bo(e[0],["mvex"])[0];let l=0;if(o){const t=bo(o,["trex"]);for(let e=0;e<t.length;e++){const n=t[e];-1!==r.indexOf(mo(n,4))&&(i.push(Ao(n,s)),l+=n.byteLength+8)}}const{result:d,dropped:c,droppedBefore:h}=_o(t,i);if(To(d,e[0].byteOffset-s-8,e[0].byteLength+8-c),o&&l){const t=o.byteOffset-s-8;To(d,t-h(t),o.byteLength+8-l)}return d}(t):null;var S;if(e)this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(e,this.decryptdata),null!=(S=this.initData)&&S.length&&(E=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}this.emitInitSegment&&(y.tracks=this.initTracks,p.initSegment=y,this.emitInitSegment=!1);const A=l.iframe,_=!c||A&&!c.includeSampleDetails?function(t,e,s,i,r=!0){return No(t,e,i,r)}(m,E,0,this,A):c.tracks,b=E.audio?_[E.audio.id]:null,L=E.video?_[E.video.id]:null,R=!!E.audio,I=!!E.video;let k="";R&&(k+="audio"),I&&(k+="video");const w=zh(L,1/0),P=zh(b,1/0),D=zh(L,0,!0),C=zh(b,0,!0);let O=r,M=0;L&&b&&E.audio&&(P>D||w>C)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${w}-${D} a: ${P}-${C}}`,L,b);const x=!!b&&(!L||!f&&P<w||!!f&&f.trackId===E.audio.id),F=x?b:L;if(!F)return this.log(`No media samples found in ${o} ${l.level} ${-1===l.part?"":`part: ${l.part} of`} sn: ${l.sn} at playlist time: ${r}`),p;let N,U=m;if(L&&L.sampleCount>=1&&E.video&&l.iframe){const{trun:t,start:e}=L,s=1===t.length,i=t.length?s?t[0].samples:t[0].samples.concat(...t.slice(1).map(t=>t.samples)):[];if(i.length){const r=t[0];let n=r;for(let e=t.length;e--;)if(t[e].samples.length){n=t[e];break}const a=n.lastSampleDurationOffset,{defaultSampleDurationOffset:o}=r,d=Math.abs(l.duration-(D-w))>.05,c=i.length<L.sampleCount;if(d||c||this.videoOnlyRemux||!s){const t=c?n.sampleOffset+n.samples.reduce((t,e)=>t+e.size,0):void 0,s=d?l.duration:D-w,r=function(t,e,s,i){if(void 0!==s){const i=t[t.length-1];let r=e;for(let e=0;e<t.length-1;e++)r-=t[e].duration;return r<=0&&(r=i.duration),i.duration=r,{durationOffset:s,value:r}}if(void 0===i)return;const r=Math.round(e/t.length);for(let e=0;e<t.length;e++)t[e].duration=r;return{durationOffset:i,value:r}}(i,s*E.video.timescale,a,o),h=function(t,e,s,i,r){if(s<1)return null;const n=bo(t,["moof"]);if(1!==n.length)return null;const a=n[0],o=t.byteOffset,l=[],d=[],c=bo(a,["traf"]);let h=!0;for(let t=0;t<c.length;t++){const s=c[t],i=bo(s,["tfhd"])[0];if(!i)return null;mo(i,4)===e?(l.push(s),131072&mo(i,0)||(h=!1)):d.push(Ao(s,o))}if(!l.length)return null;if(d.length&&!h)return null;if(void 0!==i){let e=s;for(let s=0;s<l.length;s++){const i=l[s];let r=0;const n=bo(i,["trun"]);for(let s=0;s<n.length;s++){const i=n[s],a=Math.min(e,mo(i,4));if(a){To(t,i.byteOffset-o+4,a);const e=16777215&mo(i,0);So(t,i,8+(1&e?4:0)+(4&e?4:0)+a*((256&e?4:0)+(512&e?4:0)+(1024&e?4:0)+(2048&e?4:0)))}else To(t,i.byteOffset-o-4,fo.free);e-=a,r+=a}const a=bo(i,["senc"])[0];a&&To(t,a.byteOffset-o+4,r);const d=bo(i,["saiz"])[0];if(d){let e=4;1&(d[1]<<16|d[2]<<8|d[3])&&(e+=8);const s=d[e];e+=1,To(t,d.byteOffset-o+e,r),So(t,d,e+4+(0===s?r:0))}}const r=bo(t,["mdat"]);if(1===r.length){const e=r[0].byteOffset-o-8;To(t,e,i-e)}}let u=t,f=0,g=()=>0;if(d.length){({result:u,dropped:f,droppedBefore:g}=_o(t,d)),To(u,a.byteOffset-o-8,a.byteLength+8-f);for(let t=0;t<l.length;t++){const e=l[t],s=g(e.byteOffset-o),i=bo(e,["trun"]);for(let t=0;t<i.length;t++){const e=i[t];1&mo(e,0)&&To(u,e.byteOffset-o-s+8,mo(e,8)-f)}if(s){const t=bo(e,["saio"]);for(let e=0;e<t.length;e++){const i=t[e],r=0===i[0]?4:8;let n=1&mo(i,0)?12:4,a=mo(i,n);for(n+=4;a--;n+=r){const t=n+r-4;To(u,i.byteOffset-o-s+t,mo(i,t)-s)}}}}}if(r){const{durationOffset:t,value:e}=r;To(u,t-g(t),e)}return void 0!==i?u.subarray(0,i-f):u}(m,E.video.id,i.length,t,r);h?(U=h,N=function(t,e){let s=t,i=t;for(let t=0;t<e.length;t++){const{cts:r,duration:n}=e[t];i=Math.max(i,s+(r||0)+n),s+=n}return i}(e,i)):this.warn(`IFrame remux skipped (sn ${l.sn}); using native sample duration`),M=h&&r?s:D-w}else M=D-w}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${t.length})`),M=D-w}else M=x?C-P:D-w;if(this.videoOnlyRemux&&U===m)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${l.sn})`),p;const B=F.timescale,$=F.start-r*B,G=x?E.audio.id:E.video.id;if(O=F.start/B,(n||!f)&&(function(t,e,s,i){if(null===t)return!0;const r=Math.max(i,1),n=e-t.baseTime/t.timescale;return Math.abs(n-s)>=r}(f,O,r,M)||B!==f.timescale)){let t=!1;const e=x?"audio":"video";if(f){const s=0!==r?O/r:1+O/1;t=O>=0&&Math.abs(1-s)<.001,this.log(`${e} timestamps in track ${G} at playlist time: ${n?"":"~"}${r} maps to ${O} with initPTS: ${f.baseTime/f.timescale} (${$/B-f.baseTime/f.timescale}s diff) (${k}) drift estimate: ${s} ${t?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}t||(this.log(`Found initPTS in ${e} track ${G} at playlist time: ${r} offset: ${O-r} (${$}/${B})`),f=null,y.initPTS=$,y.timescale=B,y.trackId=G)}f?(y.initPTS=f.baseTime,y.timescale=f.timescale,y.trackId=f.trackId):(y.timescale&&void 0!==y.trackId&&void 0!==y.initPTS||(this.warn("Could not set initPTS"),y.initPTS=O,y.timescale=1,y.trackId=-1),this.initPTS=f={baseTime:y.initPTS,timescale:y.timescale,trackId:y.trackId});const H=O-f.baseTime/f.timescale,K=H+M,V=I&&void 0!==(null==F?void 0:F.ptsMin)?F.ptsMin/F.timescale-f.baseTime/f.timescale:H,j=void 0!==N&&L?N/L.timescale-f.baseTime/f.timescale:I&&null!=F&&F.ptsMax?F.ptsMax/F.timescale-f.baseTime/f.timescale:K;M>0?this.lastEndTime=K:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const q={data1:U,data2:undefined,startPTS:V,startDTS:H,endPTS:j,endDTS:K,type:k,hasAudio:R,hasVideo:I,nb:1,dropped:0,encrypted:!!E.audio&&E.audio.encrypted||!!E.video&&E.video.encrypted};p.audio=R&&!I?q:void 0,p.video=I?q:void 0;const W=this.isVideoContiguous,Y=null==L?void 0:L.sampleCount;if(Y){const t=L.keyFrameIndex,e=-1!==t;q.nb=Y,q.dropped=0===t||W?0:e?t:Y,q.independent=e,q.firstKeyFrame=t,e&&L.keyFrameStart&&(q.firstKeyFramePTS=(L.keyFrameStart-f.baseTime)/f.timescale),W||(p.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),q.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${Y} dropped: ${q.dropped} start: ${q.firstKeyFramePTS||"NA"}`)}return p.initSegment=y,p.id3=Wh(s,r,f,f),i.samples.length&&(p.text=Yh(i,r,f)),p}}},{demux:TSDemuxer,remux:MP4Remuxer},{demux:class AACDemuxer extends BaseAudioDemuxer{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=t,this.config=e}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const s=Xa(t,0);let i=(null==s?void 0:s.length)||0;if(Eh(t,i))return!1;for(let s=t.length;i<s;i++)if(rh(t,i))return e.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)&&th(t,e)&&sh(t,e)<=t.length-e}(t,e)}appendFrame(t,e,s){nh(t,this.observer,e,s,t.manifestCodec);const i=oh(t,e,s,this.basePTS,this.frameIndex);if(0===(null==i?void 0:i.missing))return i}demuxSampleAes(t,e,s){const i=this.demux(t,s),r=this.sampleAes=new SampleAesDecrypter(this.observer,this.config,e);return new Promise(t=>{r.decryptAacSamples(i.audioTrack.samples,0,()=>{t(i)})})}},remux:MP4Remuxer},{demux:class MP3Demuxer extends BaseAudioDemuxer{resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=Xa(t,0);let s=(null==e?void 0:e.length)||0;if(e&&11===t[s]&&119===t[s+1]&&void 0!==ao(e)&&Th(t,s)<=16)return!1;for(let e=t.length;s<e;s++)if(Eh(t,s))return Ua.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return vh(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,s){if(null!==this.basePTS)return ph(t,e,s,this.basePTS,this.frameIndex)}},remux:MP4Remuxer}];Zh.splice(2,0,{demux:AC3Demuxer,remux:MP4Remuxer});class Transmuxer{constructor(t,e,s,i,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=e,this.config=s,this.id=r,this.logger=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,s,i){if(!this.observer)return Jh(s);const r=s.transmuxing;r.executeStart=Xh();const n=new Uint8Array(t),{currentTransmuxState:a,transmuxConfig:o}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:d,trackSwitch:c,accurateTimeOffset:h,timeOffset:u,initSegmentChange:f}=i||a,{audioCodec:g,videoCodec:p,defaultInitPts:m,duration:v,initSegmentData:y}=o,E=function(t,e){let s=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(s=e);return s}(n,e);if(E&&Cd(E.method)){const t=this.getDecrypter(),e=Od(E.method);return this.asyncResult=!0,this.decryptionPromise=t.decrypt(n,E.key.buffer,E.iv.buffer,e,s.decryptRange).then(t=>{const e=this.push(t,null,s);return this.decryptionPromise=null,e}),this.decryptionPromise}const T=this.needsProbing(d,c);if(T){const t=s.iframe&&y&&TSDemuxer.probe(y,this.logger)?y:n,e=this.configureTransmuxer(t);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(zn.ERROR,zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),r.executeEnd=Xh(),Jh(s)}(d||c||f||T)&&this.resetInitSegment(y,g,p,v,e,s),(d||f||T)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const S=this.transmux(n,E,u,h,s);this.asyncResult=tu(S);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=Xh(),S}flush(t){const e=t.transmuxing;e.executeStart=Xh();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(t));const n=[],{timeOffset:a}=i;if(s){const e=s.flush();e&&n.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Xh();const s=[Jh(t)];return this.asyncResult?Promise.resolve(s):s}const d=o.flush(a,t);return tu(d)?(this.asyncResult=!0,d.then(e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,d,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,s){if(!this.remuxer)return;const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id} playlist ${s.level}`);const d=this.remuxer.remux(i,r,n,a,l,o,!0,this.id,s,e.initData,e.sampleData);t.push({remuxResult:d,chunkMeta:s}),s.transmuxing.executeEnd=Xh()}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,i,r,n){const{demuxer:a,remuxer:o}=this;a&&o&&(a.resetInitSegment(t,e,s,i,r,n),o.resetInitSegment(t,e,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(t,e,s,i,r){let n;return n="SAMPLE-AES"===(null==e?void 0:e.method)?this.transmuxSampleAes(t,e,s,i,r):this.transmuxUnencrypted(t,s,i,r),n}transmuxUnencrypted(t,e,s,i){const{demuxer:r,remuxer:n}=this;if(!r||!n)return Jh(i);const a=r.demux(t,e,i,!1,!this.config.progressive),{audioTrack:o,videoTrack:l,id3Track:d,textTrack:c}=a;return{remuxResult:n.remux(o,l,d,c,e,s,!1,this.id,i,a.initData,a.sampleData),chunkMeta:i}}transmuxSampleAes(t,e,s,i,r){return this.demuxer?this.demuxer.demuxSampleAes(t,e,s,r).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,s,i,!1,this.id,r,t.initData,t.sampleData),chunkMeta:r})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(t){const{config:e,observer:s,typeSupported:i}=this;if(!s)return;let r;try{for(let e=0,s=Zh.length;e<s;e++){var n;if(null!=(n=Zh[e].demux)&&n.probe(t,this.logger)){r=Zh[e];break}}}catch(t){return t}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.demux,d=r.remux;a&&a instanceof l||(this.logger.log(`Using ${l.name}`),this.demuxer=new l(s,e,i,this.logger),this.probe=l.probe),o&&o instanceof d||(this.logger.log(`Using ${d.name}`),this.remuxer=new d(s,e,i,this.logger))}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 Jh=t=>({remuxResult:{},chunkMeta:t});function tu(t){return"then"in t&&t.then instanceof Function}class TransmuxConfig{constructor(t,e,s,i,r){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=i,this.defaultInitPts=r||null}}class TransmuxState{constructor(t,e,s,i,r,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=i,this.timeOffset=r,this.initSegmentChange=n}}let eu=0;class TransmuxerInterface{constructor(t,e,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=eu++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=t=>{const e=t.data,s=this.hls;if(s&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var i;const t=null==(i=this.workerContext)?void 0:i.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":s.logger[e.data.logType]&&s.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,s.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;const e=new Error(`${t.message} (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const r=t.config;this.hls=t,this.id=e,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===zn.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new Xc,this.observer.on(zn.FRAG_DECRYPTED,n),this.observer.on(zn.ERROR,n);const a=fl(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const s=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(s.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=function(t){const e=Jc[t];if(e)return e.clientCount++,e;const s=new self.URL(t,self.location.href).href,i={worker:new self.Worker(s),scriptURL:s,clientCount:1};return Jc[t]=i,i}(r.workerPath)):(s.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=Jc[Zc];if(t)return t.clientCount++,t;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),s=self.URL.createObjectURL(e),i={worker:new self.Worker(s),objectURL:s,clientCount:1};return Jc[Zc]=i,i}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:e,config:Dl(r)})}catch(i){s.warn(`Error setting up "${e}" Web Worker, fallback to inline`,i),this.terminateWorker(),this.error=null,this.transmuxer=new Transmuxer(this.observer,a,r,"",e,t.logger)}return}}this.transmuxer=new Transmuxer(this.observer,a,r,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=eu++;const e=this.hls.config,s=fl(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:s,id:this.id,config:Dl(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const e=Jc[t||Zc];if(e&&1===e.clientCount--){const{worker:s,objectURL:i}=e;delete Jc[t||Zc],i&&self.URL.revokeObjectURL(i),s.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,s,i,r,n,a,o,l,d){var c,h;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:r.start,p=r.decryptdata,m=this.frag,v=!m||r.cc!==m.cc,y=!m||l.level!==m.level,E=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),A=!y&&(1===E||0===E&&(1===T||S&&T<=0)),_=self.performance.now();(y||E||0===r.stats.parsing.start)&&(r.stats.parsing.start=_),!n||!T&&A||(n.stats.parsing.start=_);const b=!(m&&(null==(c=r.initSegment)?void 0:c.url)===(null==(h=m.initSegment)?void 0:h.url)),L=new TransmuxState(v,A,o,y,g,b);if(!A||v||b){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id} playlist: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${A}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${b}`);const t=new TransmuxConfig(s,i,e,a,d);this.configureTransmuxer(t)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:t,decryptdata:p,chunkMeta:l,state:L},t instanceof ArrayBuffer?[t]:[]);else if(f){const e=f.push(t,p,l,L);tu(e)?e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(s){const e=s.flush(t);tu(e)?e.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}):this.handleFlushResult(e,t)}}transmuxerError(t,e,s){this.hls&&(this.error=t,this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):s&&s.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class BasePlaylistController extends Logger{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}destroy(){this.clearTimer(),this.hls=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,s){const i=null==e?void 0:e.renditionReports;if(i){let r=-1;for(let s=0;s<i.length;s++){const n=i[s];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){this.warn(`Could not construct new URL for Rendition Report: ${t}`),a=n.URI||""}if(a===t){r=s;break}a===t.substring(0,a.length)&&(r=s)}if(-1!==r){const t=i[r],n=parseInt(t["LAST-MSN"])||e.lastPartSn;let a=parseInt(t["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);a>=0&&t>e.partTarget&&(a+=1)}const o=s&&kl(s);return new HlsUrlParameters(n,a>=0?a:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}return t}playlistLoaded(t,e,s){const{details:i,stats:r}=e,n=i.fragments,a=self.performance.now(),o=r.loading.first?Math.max(0,Math.floor(a-r.loading.first)):0;i.advancedDateTime=Date.now()-o;const l=this.hls.config.timelineOffset;if(l!==i.appliedTimelineOffset){const t=Math.max(l||0,0);i.appliedTimelineOffset=t,n.forEach(e=>{null==e||e.setStart(e.playlistOffset+t)})}if(i.live||null!=s&&s.live){var d;const l="levelInfo"in e?e.levelInfo:e.track;i.reloaded(s);const c=null==(d=n[n.length-1])?void 0:d.type;if(i.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){const t=new Error(`${c} playlist ${l.id} hit max allowed unchanged reloads.`);this.warn(t);const{networkDetails:s,context:n}=e;return void this.hls.trigger(zn.ERROR,{type:Wn.NETWORK_ERROR,details:Yn.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:i.url,error:t,reason:t.message,level:e.level,parent:c,context:n,networkDetails:s,stats:r})}if(s){vc(s,i,this);const t=i.playlistParsingError;if(t){this.warn(t);const s=this.hls;if(!s.config.ignorePlaylistParsingErrors){const{networkDetails:n}=e;return void s.trigger(zn.ERROR,{type:Wn.NETWORK_ERROR,details:Yn.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:t,reason:t.message,level:e.level,parent:c,networkDetails:n,stats:r})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=r.loading.start);const h=this.hls.mainForwardBufferInfo,u=h?h.end-h.len:0,f=Tc(i,1e3*(i.edge-u));i.requestScheduled+f<a?i.requestScheduled=a:i.requestScheduled<=a&&(i.requestScheduled+=f);const g=e.deliveryDirectives;if(this.log(`live playlist ${t} ${i.advanced?`REFRESHED ${i.lastPartSn} - ${i.lastPartIndex}`:i.updated?"UPDATED":`MISSED (received ${i.lastPartSn} - ${i.lastPartIndex}${g?` | requested ${g.msn} - ${g.part}`:""})`}`),!this.canLoad||!i.live)return;let p,m,v;if(i.canBlockReload&&i.advanced){const t=this.hls.config.lowLatencyMode,r=i.lastPartSn,n=i.endSN,o=i.lastPartIndex,d=r===n;-1!==o?d?(m=n+1,v=t?0:o):(m=r,v=t?o+1:i.maxPartIndex):m=n+1;const c=i.age,h=c+i.ageHeader;let u=Math.min(h-i.partTarget,1.5*i.targetduration);if(u>0){if(h>3*i.targetduration)this.log(`Playlist last advanced ${c.toFixed(2)}s ago. Omitting segment and part directives.`),m=void 0,v=void 0;else if(null!=s&&s.tuneInGoal&&h-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${u} with playlist age: ${i.age}`),u=0;else{const t=Math.floor(u/i.targetduration);if(m+=t,void 0!==v){v+=Math.round(u%i.targetduration/i.partTarget)}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${c.toFixed(2)}s goal: ${u} skip sn ${t} to part ${v}`)}i.tuneInGoal=u}if(p=this.getDeliveryDirectives(i,e.deliveryDirectives,m,v),t||!d)return i.requestScheduled=a,void this.loadingPlaylist(l,p)}else(i.canBlockReload||i.canSkipUntil)&&(p=this.getDeliveryDirectives(i,e.deliveryDirectives,m,v));p&&void 0!==m&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(f-2*o,f/2)),this.scheduleLoading(l,p,i)}else this.clearTimer()}scheduleLoading(t,e,s){const i=s||t.details;if(!i)return void this.loadingPlaylist(t,e);const r=self.performance.now(),n=i.requestScheduled;if(r>=n)return void this.loadingPlaylist(t,e);const a=n-r;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),a)}getDeliveryDirectives(t,e,s,i){let r=kl(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(s=e.msn,i=e.part,r=Ll),new HlsUrlParameters(s,i,r)}checkRetry(t){const e=t.details,s=ba(t),i=t.errorAction,{action:r,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(r===Xl||!i.resolved&&r===zl);if(o){var l;if(n>=a.maxNumRetry)return!1;if(s&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{var d;const s=Da(null==(d=t.response)?void 0:d.code);if(this.clearTimer(),s)this.log("Waiting for connection (offline)"),t.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const t=ka(a,n);this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),t)}}t.levelRetry=!0,i.resolved=!0}return o}checkOfflineStatus(){this.clearTimer(),Da(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}function su(t,e){if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!iu(t[s].attrs,e[s].attrs))return!1;return!0}function iu(t,e,s){const i=t["STABLE-RENDITION-ID"];return i&&!s?i===e["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>t[s]!==e[s])}class BufferOperationQueue{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,s){if(null===this.queues||null===this.tracks)return;const i=this.queues[e];i.push(t),1!==i.length||s||this.executeNext(e)}appendBlocker(t){return new Promise(e=>{const s={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,t)})}prependBlocker(t){return new Promise(e=>{if(this.queues){const s={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(s)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const s=null==(e=t[0])?void 0:e.label;"async-blocker"===s||"async-blocker-prepend"===s?(t[0].execute(),t.splice(0,1)):"block-audio"===s&&t.splice(0,1)})}insertNext(t,e){null!==this.queues&&this.queues[e].splice(1,0,...t)}unblockAudio(){var t;null!==this.queues&&"block-audio"===(null==(t=this.current("audio"))?void 0:t.label)&&this.shiftAndExecuteNext("audio")}audioBlocking(){return null!==this.queues&&this.queues.audio.some(t=>"block-audio"===t.label)}executeNext(t){if(null===this.queues||null===this.tracks)return;const e=this.queues[t];if(e.length){const i=e[0];try{i.execute()}catch(e){var s;if(i.onError(e),null===this.queues||null===this.tracks)return;const r=null==(s=this.tracks[t])?void 0:s.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return null===t||null===e?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var e,s;return null!=(e=this.queues)&&e[t]||null!=(s=this.tracks)&&s[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const s=null==(e=this.tracks)?void 0:e[t],i=null==s?void 0:s.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map(t=>t.label).join(", "))||""}}const ru=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,nu="HlsJsTrackRemovedError";class HlsJsTrackRemovedError extends Error{constructor(t){super(t),this.name=nu}}function au(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}function ou(t){return"audio"===t?1:0}function lu(t,e){return`${t?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function du(t){return`${t.type}_${t.sn}_${t.level}`}function cu(t,e){const{start:s,end:i}=e;let r=0;for(let e=0;e<t.length;e++){const n=t[e];if(n.start>=i)break;const a=Math.max(s,n.start),o=Math.min(i,n.end);o>a&&(r+=o-a)}return r}function hu(t,e){return e.duration-t<=.05}class CapLevelController{constructor(t){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){const{hls:t}=this;t&&(t.on(zn.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.on(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(zn.BUFFER_CODECS,this.onBufferCodecs,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){const{hls:t}=this;t&&(t.off(zn.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.off(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(zn.BUFFER_CODECS,this.onBufferCodecs,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(t,e){if(!this.hls)return;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){const s=e.media;this.clientRect=null,this.hls&&(s instanceof HTMLVideoElement?(this.media=s,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(t,e){this.restrictedLevels=[],e.video&&this.startCapping(),this.onLevelsUpdated()}onLevelsUpdated(){if(this.hls)if((this.timer||this.observer)&&(Vn(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(void 0===this.observer&&void 0===this.timer){const t=this.hls.levels;t.length>1&&t.some(t=>!!t.videoCodec)&&this.startCapping()}}onBufferCodecs(t,e){e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls)return void(this.clientRect=null);const t=this.hls.levels;if(t.length>1){const e=this.hls,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=s,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}else 1===t.length&&this.stopCapping()}}getMaxLevel(t){if(!this.hls)return-1;const e=this.hls.levels;if(!e.length)return-1;const s=e.filter((e,s)=>this.isLevelAllowed(e)&&s<=t);return this.observer||(this.clientRect=null),CapLevelController.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}observe(){const t=self.ResizeObserver;t&&(this.observer=new t(t=>{var e;const s=null==(e=t[0])?void 0:e.contentRect;s&&(this.clientRect=s,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var t;this.timer||this.observer||null==(t=this.hls)||!t.config.capLevelToPlayerSize||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=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)return t;const{ignoreDevicePixelRatio:e,maxDevicePixelRatio:s}=this.hls.config;if(!e)try{t=self.devicePixelRatio}catch(t){}return Math.min(t,s)}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;const i=(t,e)=>!e||(t.width!==e.width||t.height!==e.height);let r=t.length-1;const n=Math.max(e,s);for(let e=0;e<t.length;e+=1){const s=t[e];if((s.width>=n||s.height>=n)&&i(s,t[e+1])){r=e;break}}return r}}var uu=class SfItem{constructor(t,e){Array.isArray(t)&&(t=t.map(t=>t instanceof SfItem?t:new SfItem(t))),this.value=t,this.params=e}};function fu(t,e,s,i){return new Error(`failed to ${t} "${r=e,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${s}`,{cause:i});var r}const gu="Bare Item";const pu=/[\x00-\x1f\x7f]+/;var mu=class{constructor(t){this.description=t}};function vu(t,e,s){return fu("serialize",t,e,s)}function yu(t){if(!1===ArrayBuffer.isView(t))throw vu(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function Eu(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw vu(t,"Integer");return t.toString()}function Tu(t){const e=ja(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw vu(t,"Decimal");const s=e.toString();return s.includes(".")?s:`${s}.0`}function Su(t){const e=(s=t).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw vu(e,"Token");return e}function Au(t){switch(typeof t){case"number":if(!Vn(t))throw vu(t,gu);return Number.isInteger(t)?Eu(t):Tu(t);case"string":return function(t){if(pu.test(t))throw vu(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return Su(t);case"boolean":return function(t){if("boolean"!=typeof t)throw vu(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${Eu(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return yu(t);if(t instanceof mu)return Su(t);default:throw vu(t,gu)}}function _u(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw vu(t,"Key");return t}function bu(t){return null==t?"":Object.entries(t).map(([t,e])=>!0===e?`;${_u(t)}`:`;${_u(t)}=${Au(e)}`).join("")}function Lu(t){return t instanceof uu?`${Au(t.value)}${bu(t.params)}`:Au(t)}function Ru(t,e={whitespace:!0}){if("object"!=typeof t||null==t)throw vu(t,"Dict");const s=t instanceof Map?t.entries():Object.entries(t),i=null!=e&&e.whitespace?" ":"";return Array.from(s).map(([t,e])=>{e instanceof uu==!1&&(e=new uu(e));let s=_u(t);var i;return!0===e.value?s+=bu(e.params):(s+="=",Array.isArray(e.value)?s+=`(${(i=e).value.map(Lu).join(" ")})${bu(i.params)}`:s+=Lu(e)),s}).join(`,${i}`)}function Iu(t,e){return Ru(t,e)}const ku=["url"],wu=["version","eventTargets","sid","transmissionMode"],Pu=["customData","headers"],Du=t=>t instanceof uu?new uu(Math.round(t.value),t.params):Math.round(t),Cu=t=>Array.isArray(t)?t.map(Du):Du(t),Ou=(t,e)=>Array.isArray(t)?t.map(t=>Ou(t,e)):t instanceof uu&&"string"==typeof t.value?new uu(Ou(t.value,e),t.params):(e.baseUrl&&(t=function(t,e){let s;try{s=new URL(t)}catch(e){return t}const i=new URL(e);if(s.origin!==i.origin)return t;const r=s.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1),a=Math.min(r.length,n.length);for(let t=0;t<a&&r[t]===n[t];t++)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+s.search+s.hash}(t,function(t){const e="string"==typeof t?new URL(t):t;return e.origin+e.pathname.substring(0,e.pathname.lastIndexOf("/")+1)}(e.baseUrl))),1===e.version?encodeURIComponent(t):t),Mu=t=>t instanceof uu?new uu(100*Math.round(t.value/100),t.params):100*Math.round(t/100),xu=t=>Array.isArray(t)?t.map(Mu):Mu(t),Fu={br:Cu,d:Cu,bl:xu,dl:xu,mtp:xu,nor:(t,e)=>{let s=t;return e.version>=2&&(t instanceof uu&&"string"==typeof t.value?s=new uu([t]):"string"==typeof t&&(s=[t])),Ou(s,e)},rtp:xu,tb:Cu},Nu=2,Uu="rr",Bu="bc",$u="e",Gu=Uu,Hu="ce",Ku=new Map([["ps","sta"],["pr","pr"],["c","cid"],["b","bg"],["bc","br"]]),Vu="event",ju="request",qu=["cen","e","h","ts"],Wu=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],Yu=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function zu(t){return Yu.test(t)}const Qu=new Set(Wu);function Xu(t){return Qu.has(t)||zu(t)}const Zu=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Ju=new Set(Zu);function tf(t){return Ju.has(t)}const ef=new Set(qu);const sf=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),rf=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],nf=new Set(rf);function af(t){return nf.has(t)||zu(t)}const of=new Set(["ot","sf","st","e","sta"]);function lf(t){return of.has(t)}function df(t){return"number"==typeof t?Vn(t):null!=t&&""!==t&&!1!==t}const cf={[Vu]:function(t){return Xu(t)||tf(t)||ef.has(t)},[ju]:Xu};function hf(t,e){if(Array.isArray(t)){let s;return e&&(s=t.find(t=>{var s;return(null==(s=t.params)?void 0:s.ot)===e})),s||(s=t[0]),hf(s)}return t instanceof uu?t.value:t}function uf(t,e={}){const s={};if(null==t||"object"!=typeof t)return s;const i=e.version||t.v||Nu,r=e.reportingMode||ju,n=1===i?function(t){const e={};for(const[i,r]of Object.entries(t))if(null!=r)if("nor"===i){const t=(Array.isArray(r)?r:[r])[0];var s;t instanceof uu?(e.nor=t.value,null!=(s=t.params)&&s.r&&(e.nrr=t.params.r)):e.nor=t}else sf.has(i)?e[i]=hf(r,t.ot):e[i]=r;else e[i]=r;return e}(t):t,a=1===i?af:cf[r];let o=Object.keys(n).filter(a);n.e&&n.e!==Uu&&(o=o.filter(t=>!tf(t)));const l=e.filter;"function"==typeof l&&(o=o.filter(l));const d=r===Vu;if(d){const t=n.e;o.includes("e")||null==t||o.push("e"),o.includes("ts")||o.push("ts"),o.includes("cen")||null==n.cen||"ce"!==t||o.push("cen");const e=t?Ku.get(t):void 0;e&&null!=n[e]&&!o.includes(e)&&o.push(e)}if(0===o.length)return s;i>1&&!o.includes("v")&&o.push("v");const c={version:i,reportingMode:r,baseUrl:e.baseUrl};o.sort();for(const t of o){var h,u;let r=n[t];const a=null!=(h=null==(u=e.formatters)?void 0:u[t])?h:Fu[t];if("function"==typeof a&&(r=a(r,c)),"v"===t){if(1===i)continue;r=i}if("pr"===t&&1===r&&(!d||"pr"!==n.e))continue;d&&"ts"===t&&!Vn(r)&&(r=Date.now());const o=d&&!1===r&&"bg"===t&&"b"===n.e;(df(r)||o)&&(lf(t)&&"string"==typeof r&&(r=new mu(r)),s[t]=r)}return s}const ff="CMCD-Object",gf="CMCD-Request",pf="CMCD-Session",mf="CMCD-Status",vf=gf,yf={ab:ff,br:ff,d:ff,lab:ff,lb:ff,ot:ff,tab:ff,tb:ff,tpb:ff,bl:gf,cs:gf,dfa:gf,dl:gf,ltc:gf,mtp:gf,nor:gf,nrr:gf,pb:gf,sn:gf,sta:gf,su:gf,tbl:gf,cid:pf,msd:pf,sf:pf,sid:pf,st:pf,v:pf,bg:mf,bs:mf,bsa:mf,bsd:mf,bsda:mf,cdn:mf,ec:mf,nr:mf,pr:mf,pt:mf,rtp:mf};function Ef(t,e){const s={};if(!t)return s;const i=Object.keys(t),r=e?(n=e,Object.keys(n).reduce((t,e)=>{var s;return null==(s=n[e])||s.forEach(s=>t[s]=e),t},{})):{};var n;for(const e of i){var a;const i=yf[e]||r[e]||vf;(null!=(a=s[i])?a:s[i]={})[e]=t[e]}return s}const Tf="CMCD";function Sf(t){return Iu(t,{whitespace:!1})}const Af=[...rf,...Wu,...Zu,...qu].filter((t,e,s)=>s.indexOf(t)===e),_f="m",bf="a",Lf="v",Rf="av",If="i",kf="tt",wf="s",Pf="p",Df="k",Cf="r",Of="a",Mf="e",xf="f",Ff="d",Nf="query",Uf="headers";function Bf(t,e,s){var i;const r=new Set(null!=(i=e.enabledKeys)?i:[]);return{version:e.version||Nu,reportingMode:t,filter:t=>r.has(t),baseUrl:s}}const $f=Object.is,Gf=t=>t,Hf=Array.from(Ku,([t,e])=>"br"===e?{event:t,field:e,equal:(t,e)=>void 0===t||void 0===e?t===e:function(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++){const i=t[s],r=e[s];if(i===r)continue;if("number"==typeof i||"number"==typeof r)return!1;if(i.value!==r.value)return!1;const n=i.params,a=r.params,o=n&&Object.keys(n)[0],l=a&&Object.keys(a)[0];if(o!==l)return!1;if(void 0!==o&&void 0!==l&&n&&a&&n[o]!==a[l])return!1}return!0}(t,e),snapshot:t=>t.slice()}:{event:t,field:e,equal:$f,snapshot:Gf}),Kf=new Map(Hf.map(t=>[t.event,t]));function Vf(t){const{url:e}=t,s=_a(t,ku);return fetch(e,s)}var jf=class{constructor(t,e=Vf){var s;this.timeOrigin=performance.timeOrigin||(null==(s=performance.timing)?void 0:s.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=function(t){const{version:e=Nu,eventTargets:s=[],sid:i=qa(),transmissionMode:r=Nf}=t;return Aa(Aa({},_a(t,wu)),{},{version:e,transmissionMode:r,sid:i,eventTargets:s.reduce((t,e)=>{var s,i,r;return null!=e&&e.url&&null!=(s=e.events)&&s.length&&t.push({version:e.version||Nu,enabledKeys:(null==(i=e.enabledKeys)?void 0:i.slice())||[],url:e.url,events:e.events.slice(),interval:null!=(r=e.interval)?r:30,batchSize:e.batchSize||1}),t},[])})}(t),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=e;for(const t of this.config.eventTargets)this.eventTargets.set(t,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((t,e)=>{if(this.disarmInterval(t),0===e.interval||!e.events.includes("t"))return;const s=()=>{this.recordTargetEvent(t,e,"t"),this.processEventTargets()};t.intervalId=setInterval(s,1e3*e.interval),s()})}stop(t=!1){t&&this.flush(),this.eventTargets.forEach(t=>{this.disarmInterval(t)})}flush(){this.processEventTargets(!0)}update(t){t.sid&&t.sid!==this.data.sid&&this.resetSession(),t.msd&&!isNaN(t.msd)&&(this.msd=t.msd),this.data=Aa(Aa(Aa({},this.data),t),{},{msd:void 0});for(const e of Hf)e.field in t&&!e.equal(this.data[e.field],this.lastEmitted[e.field])&&this.recordEvent(e.event)}recordEvent(t,e={}){const s=Kf.get(t);if(s){const t=s.field,i=e[t];void 0!==i&&Ta(this.data,{[t]:i});const r=this.data[t];if(void 0===r)return;if(s.equal(r,this.lastEmitted[t]))return;Ta(this.lastEmitted,{[t]:s.snapshot(r)})}this.eventTargets.forEach((s,i)=>{this.recordTargetEvent(s,i,t,e)}),this.processEventTargets()}recordTargetEvent(t,e,s,i={}){var r;if(!e.events.includes(s))return;const n=Aa(Aa(Aa({},this.data),i),{},{e:s,ts:null!=(r=i.ts)?r:Date.now(),sn:t.sn++});isNaN(this.msd)||t.msdSent||(n.msd=this.msd,t.msdSent=!0),t.queue.push(n)}recordResponseReceived(t,e={}){var s,i,r;const{request:n}=t,a=null!=(s=e.url)?s:null==n?void 0:n.url;if(!a)return;const o=new URL(a);o.searchParams.delete(Tf);const l={url:o.toString(),rc:t.status},d=t.resourceTiming;d&&(null!=d.startTime&&(l.ts=Math.round(this.timeOrigin+d.startTime),null!=d.responseStart&&(l.ttfb=Math.round(d.responseStart-d.startTime))),null!=d.duration&&(l.ttlb=Math.round(d.duration)));const c=null!=(i=null==(r=n.customData)?void 0:r.cmcd)?i:{};this.recordEvent(Uu,Aa(Aa(Aa({},c),l),e))}applyRequestReport(t){var e;return null!=(e=this.createRequestReport(t))?e:t}isRequestReportingEnabled(){var t;return!(null==(t=this.config.enabledKeys)||!t.length)}createRequestReport(t,e){var s;const{customData:i={},headers:r={}}=t,n=Aa(Aa({},_a(t,Pu)),{},{headers:Aa({},r),customData:Aa(Aa({},i),{},{cmcd:{}})});if(null==(s=this.config.enabledKeys)||!s.length||!n.url)return n;const a=new URL(n.url),o=Aa(Aa(Aa({},this.data),e),{},{sn:this.requestTarget.sn++}),l=Bf(ju,this.config,n.url);isNaN(this.msd)||this.requestTarget.msdSent||(o.msd=this.msd,this.requestTarget.msdSent=!0);const d=n.customData.cmcd=uf(o,l);switch(this.config.transmissionMode){case Nf:const t=Sf(d);t&&(a.searchParams.set(Tf,t),n.url=a.toString());break;case Uf:Ta(n.headers,function(t,e){const s={},i=Ef(t,e);for(const[t,e]of Object.entries(i)){const i=Iu(e,{whitespace:!1});i&&(s[t]=i)}return s}(d,l.customHeaderMap))}return n}processEventTargets(t=!1){let e=!1;this.eventTargets.forEach((s,i)=>{const{queue:r}=s;if(!r.length)return;if(r.length<i.batchSize&&!t)return;const n=t?r.length:i.batchSize,a=r.splice(0,n);this.sendEventReport(i,a).catch(()=>{s.queue.unshift(...a)}),e||(e=r.length>0)}),e&&this.processEventTargets()}async sendEventReport(t,e){const s=Bf(Vu,t),{status:i}=await this.requester({url:t.url,method:"POST",headers:{"Content-Type":"application/cmcd"},body:e.map(t=>function(t,e={}){return t?Sf(uf(t,e)):""}(t,s)).join("\n")+"\n"});if(410===i)this.disposeEventTarget(t);else if(429===i||i>499&&i<600)throw new Error(`Event report failed with status ${i}`)}disarmInterval(t){clearInterval(t.intervalId),t.intervalId=void 0}disposeEventTarget(t){const e=this.eventTargets.get(t);e&&(this.disarmInterval(e),this.eventTargets.delete(t))}resetSession(){this.eventTargets.forEach(t=>t.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}};const qf="h",Wf="v",Yf="l",zf="ll";const Qf=["includeKeys"];function Xf(t){return Object.keys(t).every(zu)}function Zf(t,e,s,i){t&&Object.keys(e).forEach(r=>{const n=t.filter(t=>t.groupId===r).map(t=>{const n=Ta({},t);return n.details=void 0,n.attrs=new AttrList(n.attrs),n.url=n.attrs.URI=Jf(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=e[r],n.attrs["PATHWAY-ID"]=i,n});t.push(...n)})}function Jf(t,e,s,i){if(e){const{[s]:t}=i;if(t){const s=t[e];if(s)return s}}const{HOST:r,PARAMS:n}=i,a=new self.URL(t);return r&&(a.hostname=r),n&&Object.keys(n).sort().forEach(t=>{t&&Al(a,t,n[t])}),a.href}class LicenseAndKeysRequestEmitter{constructor(){this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new Xc,this.error=void 0,this.ok=void 0}get errored(){return this.error}set errored(t){this.error=t,this.emitter.eventNames().length&&this.emitter.emit("error",t)}get hasListeners(){return this.emitter.eventNames().length>0}get resolved(){return this.ok}resolve(){this.ok=!0,this.emitter.emit("resolved")}get useable(){return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise((t,e)=>{this.emitter.on("error",e),this.emitter.on("resolved",t)})}reset(){this.emitter.removeAllListeners();const t=this.licenseXhr;t&&(t.readyState!==XMLHttpRequest.DONE&&t.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=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}}class EMEController extends Logger{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysQueue=EMEController.CDMCleanupPromise?[EMEController.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:e,initData:s}=t,i=`"${t.type}" event: init data type: "${e}"`;if(this.log(i),null!==s){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=qd(this.config));const e=t.map(jd).filter(t=>!!t);this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then(r=>{let n;const a=Kd(r),o=this.activeLevelKeys();if(a===Ud.FAIRPLAY&&"sinf"===e)try{const t=ho(new Uint8Array(s)),e=Mo(co(JSON.parse(t).sinf));if(!e)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");n=new Uint8Array(e.subarray(8,24))}catch(t){return void this.warn(`${i} Failed to parse sinf: ${t}`)}else if(a===Ud.PLAYREADY)n=zd(new Uint8Array(s));else if(a===Ud.WIDEVINE){const t=Vo(s).filter(t=>t.systemId===Vd);if(t.length){var l;const e=t[0];n=null!=(l=e.kids)&&l.length?e.kids[0]:null}}let d;if(n){const t=oo(n);for(let i=0;i<o.length;i++){const r=o[i];if(r.keyId&&(Pd(n,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(t))){r.pssh||(r.scheme=e,r.pssh=new Uint8Array(s),r.keyId=n,LevelKey.setKeyIdForUri(r.uri,n)),d=this.getSessionForKey(r,"encrypted-event-key-match");break}}}if(!d){var c,h;if(o.length)return(c=o[0]).scheme||(c.scheme=e),(h=o[0]).pssh||(h.pssh=new Uint8Array(s)),this.getSessionForKey(o[0],"encrypted-event-no-match");if(n)throw new Error(`Key ID ${oo(n)} not encountered in playlist`);this.log(`Ignoring "${t.type}" event - could not determine keyId`)}return d}).catch(t=>this.handleError(t))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){const{hls:t}=this;t&&(t.on(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(zn.MEDIA_DETACHED,this.onMediaDetached,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(zn.DESTROYING,this.onDestroying,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(zn.MEDIA_DETACHED,this.onMediaDetached,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(zn.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(t){if(!this.hls)return Promise.reject(new Error("destroyed"));const e=this.hls.levels,s=(t,e,s)=>!!t&&s.indexOf(t)===e,i=e.map(t=>t.audioCodec).filter(s),r=e.map(t=>t.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((e,s)=>{const n=t=>{const a=t.shift();this.getMediaKeysPromise(a,i,r).then(t=>e({keySystem:a,mediaKeys:t})).catch(e=>{t.length?n(t):s(e instanceof EMEKeyError?e:new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:Yn.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===Wd&&"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){var i;const r=function(t,e,s,i){let r;switch(t){case Ud.FAIRPLAY:r=["cenc","sinf"];break;case Ud.WIDEVINE:case Ud.PLAYREADY:r=["cenc"];break;case Ud.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,s,i){return[{initDataTypes:t,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(t=>({contentType:`audio/mp4; codecs=${t}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:s.map(t=>({contentType:`video/mp4; codecs=${t}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}(r,e,s,i)}(t,e,s,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[t],a=null==(i=n)?void 0:i.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${Dl(r)}`),a=this.requestMediaKeySystemAccess(t,r);const e=n=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch(e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)}),a.then(s=>{this.throwIfDestroyed(),this.log(`Access for key-system "${s.keySystem}" obtained`);const i=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const r=e.mediaKeys=s.createMediaKeys().then(s=>(this.log(`Media-keys created for "${t}"`),e.hasMediaKeys=!0,i.then(e=>e?this.setMediaKeysServerCertificate(s,t,e):s)));return r.catch(e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)}),r})}return a.then(()=>n.mediaKeys)}getMediaKeySessionContext(t,e,s,i){const{mediaKeySessions:r}=this,n=` key-session "${t}" keyId: ${oo(s.keyId||[])} keyUri: ${s.uri} for "${i}"`;for(let t=0;t<r.length;t++){const e=r[t];if(!e.initialized&&e.createdFor.levelKey.uri===s.uri)return this.log(`Reusing${n}`),e}this.log(`Creating${n}`);const a=e.createSession(),o={keySystem:t,mediaKeys:e,mediaKeysSession:a,keyRequests:{},keyStatuses:{},createdFor:{levelKey:s,reason:i},initialized:!1};return r.push(o),o}resetMediaKeys(){var t;const e=null==(t=this.mediaKeySessions[0])?void 0:t.keySystem,s=this.keySystemAccessPromises[e];s&&(this.log("reset mediaKeys"),this.mediaKeys=null,s.hasMediaKeys=!1,delete s.mediaKeys,delete this.keySystemAccessPromises[e])}updateKeySession(t,e,s){const i=t.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${oo(e.keyId||[])}\n } (data length: ${s.byteLength})`),i.update(s)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>jd(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:t,mediaKeys:e})=>this.attemptSetMediaKeys(t,e))}selectKeySystem(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:t})=>{const e=jd(t);if(!e)throw new Error(`Unable to find format for key-system "${t}"`);return 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){const e=qd(this.config),s=t.map(Kd).filter(t=>!!t&&-1!==e.indexOf(t));return this.selectKeySystem(s)}loadClear(t,e,s){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(e.length)for(let i=0,r=e.length;i<r;i++){const n=e[i];if(t.cc<=n.cc&&(!pa(t)||!pa(n)||t.sn<n.sn)||!s&&i==r-1)return this.selectKeySystemFormat(n).then(t=>{if(!this.hls)return;n.setKeyFormat(t);const e=Kd(t);return e?this.getKeySystemAccess([e]):void 0})}if(this.config.requireKeySystemAccessOnStart){const t=qd(this.config);if(t.length)return this.getKeySystemAccess(t)}}return null}getKeyStatus(t){const{mediaKeySessions:e}=this;for(let s=0;s<e.length;s++){const i=tg(t,e[s]);if(i)return i}}loadKey(t){const e=t.decryptdata,s=this.getKeyStatus(e);if("internal-error"===s){const i=eg(s,e);return i.data.frag=t,this.error(`${i.message} (${oo(e.keyId||[])})`),Promise.reject(i)}const i=t.type,r=this.activeKeys,n=r[i];n&&!e.matches(n.decryptdata)&&(r.previous||(r.previous=[]),r.previous.push(n),delete r[i]),r[i]||(r[i]=t);for(let t=this.mediaKeySessions.length;t--;){const s=this.mediaKeySessions[t];if(e.keyId&&"expired"===s.keyStatuses[oo(e.keyId)])return this.renewKeySession(e,s)}return this.updateUsablePromise(e,"playlist-key",t)}renewKeySession(t,e){return this.resetMediaKeys(),this.removeSession(e).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(t,"expired")))}updateUsablePromise(t,e,s){const i=this.getSessionForKey(t,e);return i.catch(t=>this.handleError(t,s)),i.then(e=>t)}getSessionForKey(t,e){const s=this.findContextForKey(t);if(void 0!==s)return Promise.resolve(s);const i=t.uri,r=this.sessionSetupByUri[i];let n;n=void 0===r?this.resolveSessionForKey(t,e):r.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(t,e))),this.sessionSetupByUri[i]=n;const a=()=>{this.sessionSetupByUri[i]===n&&delete this.sessionSetupByUri[i]};return n.then(a,a),n}findContextForKey(t){const{mediaKeySessions:e}=this;for(let s=e.length;s--;){const i=e[s];if(tg(t,i))return i}}resolveSessionForKey(t,e){return this.getKeySystemForKeyPromise(t).then(({keySystem:s,mediaKeys:i})=>{this.throwIfDestroyed();for(let s=this.mediaKeySessions.length;s--;){const i=this.mediaKeySessions[s];if(tg(t,i))return i;const r=this.getUsableKeyPromise(i,t,e);if(r)return r}return this.attemptSetMediaKeys(s,i).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(s,i,t,e))).then(s=>{this.throwIfDestroyed();const i=t.scheme||"cenc",r=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(s,t,i,r,e)})})}getUsableKeyPromise(t,e,s){const i=t.keyRequests[e.uri];if(i)return this.log(`Waiting for usable key (${s} keyId: ${function(t){if(t.keyFormat===$d)return t.uri;if(null===t.keyId)throw new Error("keyId is null");return oo(t.keyId)}(e)} format: "${e.keyFormat}" URI: ${e.uri})`),i.useable.then(()=>t)}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,e){if(this.hls)if(t instanceof EMEKeyError){e&&(t.data.frag=e);const s=t.data.decryptdata;this.error(`${t.message}${s?` (${oo(s.keyId||[])})`:""}`),this.hls.trigger(zn.ERROR,t.data)}else this.error(t.message),this.hls.trigger(zn.ERROR,{type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const e=Kd(t.keyFormat),s=e?[e]:qd(this.config);return this.attemptKeySystemAccess(s)}getKeySystemSelectionPromise(t){if(t.length||(t=qd(this.config)),0===t.length)throw new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Dl({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}activeLevelKeys(){const t=this.activeKeys,e=(t.previous||[]).map(t=>t.decryptdata);return t.audio&&e.unshift(t.audio.decryptdata),t.main&&e.unshift(t.main.decryptdata),e}attemptSetMediaKeys(t,e){if(this.mediaResolved=void 0,this.mediaKeys===e)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(e):new Promise((t,s)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return s(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=e,this.media.setMediaKeys(e).then(t).catch(s)}}));return this.mediaKeys=e,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${t}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(t=>-1===s.indexOf(t))})}filterInitData(t,e,s,i,r){var n;const a=null==(n=this.config.drmSystems)||null==(n=n[t.keySystem])?void 0:n.generateRequest;if(a)try{const n=a.call(this.hls,s,i,Ta({},t,{decryptdata:e,reason:r}),r);if(!n)throw new Error("Invalid response from configured generateRequest filter");e.scheme=n.initDataType?n.initDataType:"cenc";const o=n.initData?n.initData:null;return e.pssh=o?new Uint8Array(o):null,n}catch(t){var o;if(this.warn(t.message),null!=(o=this.hls)&&o.config.debug)throw t}return{initDataType:s,initData:i}}generateRequestWithPreferredKeySession(t,e,s,i,r){const n=this.getUsableKeyPromise(t,e,r);if(n)return n;const a=this.filterInitData(t,e,s,i,r);if(a&&(i=a.initData?a.initData:null,s=a.initDataType),null===i)return r.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${r}"`)):(this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t));const o=e.uri,l=new LicenseAndKeysRequestEmitter;t.keyRequests[o]=l;const d=s=>{const i=t.mediaKeysSession;if(!i){const t=new Error("invalid state");return void(l.errored=t)}const{messageType:r,message:n}=s;l.status=r,this.log(`"${r}" message event for session "${i.sessionId}" message size: ${n.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(t,e,n).catch(e=>{l.errored=e,l.hasListeners||this.handleError(e),this.removeSession(t)}):"license-release"===r?t.keySystem===Ud.FAIRPLAY&&this.updateKeySession(t,e,Md("acknowledged")).then(()=>this.removeSession(t)).catch(t=>this.handleError(t)):this.warn(`unhandled media key message type "${r}"`)};l.onmessage=d,Dc(t.mediaKeysSession,"message",d);return this.generateRequest(t,e,s,i,r,!1)}generateRequest(t,e,s,i,r,n){if(n){const n=this.filterInitData(t,e,s,i,r);n&&(i=n.initData?n.initData:i,s=n.initDataType)}const a=e.uri,o=t.keyRequests[a],l=oo(e.keyId||[]),d=t=>{let s;t.startsWith("usable")?o.resolve():"internal-error"===t||"output-restricted"===t||"output-downscaled"===t?s=eg(t,e):"expired"===t?s=new Error(`key expired (keyId: ${l})`):"released"===t?s=new Error("key released"):"status-pending"===t||this.warn(`unhandled key status change "${t}" (keyId: ${l})`),s&&(o.errored=s,o.hasListeners||this.handleError(s))},c=s=>{if(!t.mediaKeysSession){const t=new Error("invalid state");return void(o.errored=t)}const i=t.keyStatuses=this.getKeyStatuses(t);if(!Object.keys(i).some(t=>"status-pending"!==i[t]))return;const r=this.activeLevelKeys();for(let s=0;s<r.length;s++){const a=oo(r[s].keyId||[]);if("expired"===i[a]){var n;this.log(`Expired key ${Dl(i)} in key-session "${null==(n=t.mediaKeysSession)?void 0:n.sessionId}"`),this.renewKeySession(e,t).catch(t=>this.handleError(t));break}}let a=i[l];if(a)d(a);else{var c;const s=1e3;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(c=t.keyStatusTimeouts)[l]||(c[l]=self.setTimeout(()=>{var i;if(!t.mediaKeysSession)return;const r=this.getKeyStatus(e);var n;if(r&&"status-pending"!==r)return this.log(`No status for keyId ${l} in key-session "${null==(n=t.mediaKeysSession)?void 0:n.sessionId}". Using session key-status ${r} from other session.`),d(r);this.log(`key status for ${l} in key-session "${null==(i=t.mediaKeysSession)?void 0:i.sessionId}" timed out after ${s}ms`),a="internal-error",d(a)},s)),this.log(`No status for keyId ${l} (${Dl(i)}).`)}};o.onkeystatuseschange=c,Dc(t.mediaKeysSession,"keystatuseschange",c);const h=o.useable;return this.log(`Generating key-session request for "${r}" keyId: ${l} URI: ${a} (init data type: ${s} length: ${i.byteLength})`),o.status="started",t.initialized=!0,t.mediaKeysSession.generateRequest(s,i).then(()=>{var e;o.status="generated",this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${l} URI: ${a}`)}).catch(t=>{throw this.log(`mediaKeysSession.generateRequest failed: ${t}`),new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>h).catch(e=>{var s;this.log(`mediaKeysSession.generateRequest failed: ${e}`);const i=null==(s=e.data)?void 0:s.details;return i!==Yn.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED&&i!==Yn.KEY_SYSTEM_STATUS_INTERNAL_ERROR||!Object.keys(t.keyStatuses).some(e=>"usable"===t.keyStatuses[e])?this.removeSession(t).then(()=>{throw e}):(this.handleError(e),t)}).then(()=>t)}getKeyStatuses(t){const e={},s=t.mediaKeysSession.sessionId;return t.mediaKeysSession.keyStatuses.forEach((i,r)=>{if("string"==typeof r&&"object"==typeof i){const t=r;r=i,i=t}const n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(t.keySystem===Ud.PLAYREADY&&16===n.length){const t=oo(n);e[t]=i,xd(n)}const a=oo(n);this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${s}"`),e[a]=i}),e}fetchServerCertificate(t){const e=this.config,s=new(0,e.loader)(e),i=function(t,e){const{drmSystems:s}=e,i=null==s?void 0:s[t];if(i)return i.serverCertificateUrl}(t,e);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise((r,n)=>{const a={type:oa,responseType:"arraybuffer",url:i},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,e,s,i)=>{r(t.data)},onError:(e,s,r,o)=>{n(new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:Aa({url:a.url,data:void 0},e)},`"${t}" certificate request failed (${i}). Status: ${e.code} (${e.text})`))},onTimeout:(e,s,r)=>{n(new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(t,e,s)=>{n(new Error("aborted"))}};s.load(a,l,d)})):(this.log(`No Server Certificate in config.drmSystems["${t}"]`),Promise.resolve())}setMediaKeysServerCertificate(t,e,s){return new Promise((i,r)=>{t.setServerCertificate(s).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${s.byteLength}) on "${e}"`),i(t)}).catch(t=>{r(new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))})})}renewLicense(t,e,s){return this.requestLicense(t,e,new Uint8Array(s)).then(s=>this.updateKeySession(t,e,new Uint8Array(s)).catch(t=>{throw new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(t,e){const s=ho(new Uint16Array(e.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const i=(new DOMParser).parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let s=0,i=r.length;s<i;s++){var n,a;e=r[s];const i=null==(n=e.querySelector("name"))?void 0:n.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;i&&o&&t.setRequestHeader(i,o)}}const o=i.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Md(atob(l))}setupLicenseXHR(t,e,s,i,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>(this.throwIfDestroyed(),n.call(this.hls,t,e,Aa(Aa({},s),{},{decryptdata:i}),r))).catch(a=>{if(!s.mediaKeysSession)throw a;return t.open("POST",e,!0),n.call(this.hls,t,e,Aa(Aa({},s),{},{decryptdata:i}),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,s){return new Promise((i,r)=>{const n=function(t,e){const{drmSystems:s,widevineLicenseUrl:i}=e,r=null==s?void 0:s[t];if(r)return r.licenseUrl;if(t===Ud.WIDEVINE&&i)return i}(t.keySystem,this.config);if(!n)return r(new Error(`no license server URL configured for key-system "${t.keySystem}"`));const a=t.keyRequests[e.uri];if(!a)return r(new Error("License emitter removed"));this.log(`Sending license request to URL: ${n}`);const o=this.config.keyLoadPolicy.default,l=new XMLHttpRequest;l.responseType="arraybuffer",l.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return r(new Error("invalid state"));if(4===l.readyState)if(200===l.status){a.requestErrors=[];let s=l.response;this.log(`License received ${s instanceof ArrayBuffer?s.byteLength:s}`);const r=this.config.licenseResponseCallback;if(r)try{s=r.call(this.hls,l,n,Aa(Aa({},t),{},{decryptdata:e}))}catch(t){this.error(t)}i(s)}else{const d=o.errorRetry,c=d?d.maxNumRetry:0;if(a.requestErrors.push({status:l.status,message:l.statusText}),a.requestErrors.length>c||l.status>=400&&l.status<500)r(new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e,fatal:!0,networkDetails:l,response:{url:n,data:void 0,code:l.status,text:l.statusText}},`License Request XHR failed (${n}). Status: ${l.status} (${l.statusText})`));else{const n=c-a.requestErrors.length;this.warn(`Retrying license request, ${n} attempts left`),this.requestLicense(t,e,s).then(i,r)}}},a.licenseXhr&&a.licenseXhr.readyState!==XMLHttpRequest.DONE&&a.licenseXhr.abort(),a.licenseXhr=l,this.setupLicenseXHR(l,n,t,e,s).then(({xhr:e,licenseChallenge:s})=>{t.keySystem==Ud.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(e,s)),e.send(s)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const s=e.media;this.media=s,Dc(s,"encrypted",this.onMediaEncrypted),Dc(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const t=this.media;t&&(Cc(t,"encrypted",this.onMediaEncrypted),Cc(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};const e=this.mediaResolved;if(e&&e(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,LevelKey.clearKeyUriToKeyIdMap();const r=i.length;EMEController.CDMCleanupPromise=Promise.all(i.map(t=>this.removeSession(t)).concat((null==s||null==(t=s.setMediaKeys(null))?void 0:t.catch(t=>{this.log(`Could not clear media keys: ${t}`),this.hls&&this.hls.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})}))||Promise.resolve())).catch(t=>{this.log(`Could not close sessions and clear media keys: ${t}`),this.hls&&this.hls.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear(),this.keyFormatPromise=null}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),this.keyFormatPromise.catch(()=>{})}}removeSession(t){const{mediaKeysSession:e}=t;if(e){this.log(`Remove licenses and keys and close session "${e.sessionId}"`),Object.keys(t.keyRequests).forEach(s=>{const i=t.keyRequests[s];i.onmessage&&e.removeEventListener("message",i.onmessage),i.onkeystatuseschange&&e.removeEventListener("keystatuseschange",i.onkeystatuseschange),i.reset(),t.keyRequests[s]=void 0}),t.mediaKeysSession=void 0;const s=this.mediaKeySessions.indexOf(t);s>-1&&this.mediaKeySessions.splice(s,1);const{keyStatusTimeouts:i}=t;i&&Object.keys(i).forEach(t=>self.clearTimeout(i[t]));const{drmSystemOptions:r}=this.config,n=function(t){var e;return!(!t||"persistent-license"!==t.sessionType&&(null==(e=t.sessionTypes)||!e.some(t=>"persistent-license"===t)))}(r)?new Promise((t,s)=>{self.setTimeout(()=>s(new Error("MediaKeySession.remove() timeout")),8e3),e.remove().then(t).catch(s)}):Promise.resolve();return n.catch(t=>{this.log(`Could not remove session: ${t}`),this.hls&&this.hls.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})}).then(()=>e.close()).then(()=>e.closed).catch(t=>{this.log(`Could not close session: ${t}`),this.hls&&this.hls.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})})}return Promise.resolve()}}function tg(t,e){const s=t.keyId,i=e.mediaKeysSession;if(s&&i){const t=e.mediaKeysSession.keyStatuses;if(t.size)return t.has(s)?t.get(s):e.keyStatuses[oo(s)]}}function eg(t,e){const s="output-restricted"===t,i=s?Yn.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Yn.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},s?"HDCP level output restricted":`key status changed to "${t}"`)}EMEController.CDMCleanupPromise=void 0;var sg=function(){if(null!=Nd&&Nd.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 i(t){return s(e,t)}function r(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,h=e,u=n,f=a,g=null,p="",m=!0,v="auto",y="start",E=50,T="middle",S=50,A="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return d},set:function(t){d=""+t}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return c},set:function(t){c=!!t}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return h},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");h=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return p},set:function(e){const i=function(e){return s(t,e)}(e);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");p=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return m},set:function(t){m=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},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",r({},l,{get:function(){return T},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return A},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");A=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 ig(t){function e(t,e,s,i){return 3600*(0|t)+60*(0|e)+(0|s)+parseFloat(i||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 i=0;i<s.length;++i)if(e===s[i]){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 rg(t,e,s,i){const r=i?t.split(i):[t];for(const t in r){if("string"!=typeof r[t])continue;const i=r[t].split(s);if(2!==i.length)continue;e(i[0],i[1])}}const ng=new sg(0,0,""),ag="middle"===ng.align?"middle":"center";function og(t,e,s){const i=t;function r(){const e=ig(t);if(null===e)throw new Error("Malformed timestamp: "+i);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=r(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);t=t.slice(3),n(),e.endTime=r(),n(),function(t,e){const i=new Settings;rg(t,function(t,e){let r;switch(t){case"region":for(let r=s.length-1;r>=0;r--)if(s[r].id===e){i.set(t,s[r].region);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),i.integer(t,r[0]),i.percent(t,r[0])&&i.set("snapToLines",!1),i.alt(t,r[0],["auto"]),2===r.length&&i.alt("lineAlign",r[1],["start",ag,"end"]);break;case"position":r=e.split(","),i.percent(t,r[0]),2===r.length&&i.alt("positionAlign",r[1],["start",ag,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",ag,"end","left","right"])}},/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");let r=i.get("line","auto");"auto"===r&&-1===ng.line&&(r=-1),e.line=r,e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100),e.align=i.get("align",ag);let n=i.get("position","auto");"auto"===n&&50===ng.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function lg(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=lg(t);s<t.length&&"\r"!==t[s]&&"\n"!==t[s];)++s;const i=t.slice(0,s);return"\r"===t[s]&&++s,"\n"===t[s]&&++s,e.buffer=t.slice(s),i}function i(t){rg(t,function(t,e){},/:/)}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 i=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==i||!i[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)?i(t):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 sg(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{og(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}}function dg(t){let e=5381,s=t.length;for(;s;)e=33*e^t.charCodeAt(--s);return(e>>>0).toString()}const cg=/\r\n|\n\r|\n|\r/g,hg="Missing initPTS for VTT ";function ug(t,e,s){return dg(t.toString())+dg(e.toString())+dg(s)}function fg(t,e,s,i,r,n,a){const o=new VTTParser,l=Ja(new Uint8Array(t)).trim().replace(cg,"\n").split("\n"),d=[],c=e?function(t,e=1){return Gh(t,9e4,1/e)}(e.baseTime,e.timescale):0;let h,u="00:00.000",f=0,g=0,p=!1,m=!0;o.oncue=function(t){const n=s[i];let a=s.ccOffset;const o=(f-c)/9e4;if(p){if(null!=n&&n.new&&(a=s.ccOffset=n.start),o){if(!e)return void(h=new Error(hg+"MPEGTS"));a=o-s.presentationOffset}}else{if(!e)return void(h=new Error(hg+"without X-TIMESTAMP-MAP"));a=-e.baseTime/e.timescale}const l=t.endTime-t.startTime,u=qh(9e4*(t.startTime+a-g),9e4*r)/9e4;t.startTime=Math.max(u,0),t.endTime=Math.max(u+l,0);const m=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(m)),t.id?i&&(t.id=`hlsjscc${i}_${t.id}`):t.id=ug(t.startTime,t.endTime,m),t.endTime>0&&d.push(t)},o.onparsingerror=function(t){h=t},o.onflush=function(){h?a(h):n(d)},l.forEach(t=>{if(m){if(t.startsWith("X-TIMESTAMP-MAP=")){m=!1,p=!0,t.slice(16).split(",").forEach(t=>{t.startsWith("LOCAL:")?u=t.slice(6):t.startsWith("MPEGTS:")&&(f=parseInt(t.slice(7)))});try{g=function(t){let e=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),i=parseInt(t.slice(-9,-7)),r=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(Vn(e)&&Vn(s)&&Vn(i)&&Vn(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*s,e+=6e4*i,e+=36e5*r,e}(u)/1e3}catch(t){h=t}return}""===t&&(m=!1)}o.parse(t+"\n")}),o.flush()}const gg="stpp.ttml.im1t",pg=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,mg=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,vg={left:"start",center:"center",right:"end",start:"start",end:"end"};function yg(t,e,s,i){const r=bo(new Uint8Array(t),["mdat"]);if(0===r.length)return void i(new Error("Could not parse IMSC1 mdat"));const n=r.map(t=>Ja(t)),a=function(t,e,s=1,i=!1){return Gh(t,e,1/s,i)}(e.baseTime,1,e.timescale);try{n.forEach(t=>s(function(t,e){const s=new DOMParser,i=s.parseFromString(t,"text/xml"),r=i.getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:1},a=Object.keys(n).reduce((t,e)=>(t[e]=r.getAttribute(`ttp:${e}`)||n[e],t),{});!r.getAttribute("ttp:tickRate")&&r.getAttribute("ttp:frameRate")&&(a.tickRate=Number(a.frameRate)*Number(a.subFrameRate));const o="preserve"!==r.getAttribute("xml:space"),l=Tg(Eg(r,"styling","style")),d=Tg(Eg(r,"layout","region")),c=Eg(r,"body","[begin]");return[].map.call(c,t=>{const s=Sg(t,o);if(!s||!t.hasAttribute("begin"))return null;const i=bg(t.getAttribute("begin"),a),r=bg(t.getAttribute("dur"),a);let n=bg(t.getAttribute("end"),a);if(null===i)throw _g(t);if(null===n){if(null===r)throw _g(t);n=i+r}const c=new sg(i-e,n-e,s);c.id=ug(c.startTime,c.endTime,c.text);const h=function(t,e,s){const i="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&s.hasOwnProperty(a)&&(r=s[a]);return n.reduce((s,n)=>{const a=Ag(e,i,n)||Ag(t,i,n)||Ag(r,i,n);return a&&(s[n]=a),s},{})}(d[t.getAttribute("region")],l[t.getAttribute("style")],l),{textAlign:u}=h;if(u){const t=vg[u];t&&(c.lineAlign=t),c.align=u}return Ta(c,h),c}).filter(t=>null!==t)}(t,a)))}catch(t){i(t)}}function Eg(t,e,s){const i=t.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(s)):[]}function Tg(t){return t.reduce((t,e)=>{const s=e.getAttribute("xml:id");return s&&(t[s]=e),t},{})}function Sg(t,e){return[].slice.call(t.childNodes).reduce((t,s,i)=>{var r;return"br"===s.nodeName&&i?t+"\n":null!=(r=s.childNodes)&&r.length?Sg(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function Ag(t,e,s){return t&&t.hasAttributeNS(e,s)?t.getAttributeNS(e,s):null}function _g(t){return new Error(`Could not parse ttml timestamp ${t}`)}function bg(t,e){if(!t)return null;let s=ig(t);return null===s&&(pg.test(t)?s=function(t,e){const s=pg.exec(t),i=(0|s[4])+(0|s[5])/e.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+i/e.frameRate}(t,e):mg.test(t)&&(s=function(t,e){const s=mg.exec(t),i=Number(s[1]);switch(s[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return i/1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}(t,e))),s}function Lg(t,e,s,i="",r="disabled"){const n=t.ownerDocument.createElement("track");return n.kind=e,n.label=s,i&&(n.srclang=i),n.src="data:,WEBVTT",n.track.mode=r,t.appendChild(n),n}function Rg(t){return t.forced&&(Wo.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(qo))?"forced":t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Ig(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){Ua.debug(`[texttrack-utils]: ${s}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,t.addCue(s)}catch(t){Ua.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===s&&(t.mode=s)}function kg(t,e,s,i){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,s){const i=[],r=function(t,e){if(e<=t[0].startTime)return 0;const s=t.length-1;if(e>t[s].endTime)return-1;let i,r=0,n=s;for(;r<=n;)if(i=Math.floor((n+r)/2),e<t[i].startTime)n=i-1;else{if(!(e>t[i].startTime&&r<s))return i;r=i+1}return t[r].startTime-e<e-t[n].startTime?r:n}(t,e);if(r>-1)for(let n=r,a=t.length;n<a;n++){const r=t[n];if(r.startTime>=e&&r.endTime<=s)i.push(r);else if(r.startTime>s)return i}return i}(t.cues,e,s);for(let e=0;e<r.length;e++)i&&!i(r[e])||t.removeCue(r[e])}"disabled"===r&&(t.mode=r)}function wg(t,e){const s=Pg(t.main);if(s&&s.start<=e)return s;const i=Pg(t.audio);return i&&i.start<=e?i:null}function Pg(t){if(!t)return null;switch(t.state){case xc:case Mc:case Hc:case Kc:return null}return t.frag}function Dg(t,e){return e.getAppendedFrag(t,da)||e.getPartialFragment(t)}function Cg(t,e,s,i){const r=i.latestLevelDetails,n=Dg(e,s);if(Wc(i.config)&&!t.nextStart&&r&&n&&i.interstitialsManager){const s="type"in n?n:n.fragment,a=Wl(r,s.sn);(null==a?void 0:a.level)===s.level&&qc(a,i.interstitialsManager.playerQueue,e)&&(t.nextStart=a.start)}}function Og(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Mg(t,e,s,i,r){let n=new t(e,s,"");try{n.value=i,r&&(n.type=r)}catch(a){n=new t(e,s,Dl(r?Aa({type:r},i):i))}return n}const xg=(()=>{const t=Og();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Fg(){return self.SourceBuffer||self.WebKitSourceBuffer}function Ng(){if(!Ba())return!1;const t=Fg();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}var Ug=0,Bg=1,$g=2;class StreamController extends BaseStreamController{constructor(t,e,s){super(t,e,s,"stream-controller",da),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=Ug,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const t=this.media,e=t?t.currentTime:null;if(null===e||!Vn(e))return;if(this.log(`Media seeked to ${e}`),!this.getBufferedFrag(e))return;const s=this.getFwdBufferInfoAtPos(t,e,da,0);s&&0!==s.len?this.tick():this.log(`Main buffer empty at ${e} on "seeked" event: ${s?s.len:s}`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.on(zn.LEVEL_LOADING,this.onLevelLoading,this),t.on(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.on(zn.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(zn.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(zn.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(zn.BUFFER_CREATED,this.onBufferCreated,this),t.on(zn.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(zn.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.off(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.off(zn.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(zn.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(zn.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(zn.BUFFER_CREATED,this.onBufferCreated,this),t.off(zn.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(zn.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=i.startLevel;-1===t&&(i.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=i.firstAutoLevel),i.nextLoadLevel=t,this.level=i.loadLevel,this._hasEnoughToStart=!!e}s>0&&-1===t&&!e&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s}`),t=s),this.state=xc,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,e||this.fragmentTracker.hasFragments(this.playlistType)||(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=Mc}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case jc:{const{levels:t,level:e}=this,s=null==t?void 0:t[e],i=null==s?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=xc;break}if(this.hls.nextLoadLevel!==this.level){this.state=xc;break}break}case Uc:this.checkRetryDate()}this.state===xc&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:s,media:i}=this;if(null===e||!i&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==s||!s[r])return;const n=s[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={type:this.targetBufferType()};return this.hls.trigger(zn.BUFFER_EOS,t),void(this.state=Hc)}if(!this.buffering)return;t.loadLevel!==r&&-1===t.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const l=n.details;if(!l||this.state===jc||this.waitForLive(n))return this.level=r,this.state=jc,void(this.startFragRequested=!1);const d=a.len,c=this.getMaxBufferLength(n.maxBitrate);if(d>=c)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=void 0);const h=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(h,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&pa(u)&&this.fragmentTracker.getState(u)!==cd){var f;const t=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,e=l.fragments[t-1];e&&u.cc===e.cc&&(u=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=void 0);if(u&&this.isLoopLoading(u,h)){if(!u.gap){const t=this.audioOnly&&!this.altAudio?ua:fa,e=(t===fa?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t)}u=this.getNextFragmentLoopLoading(u,l,a,da,c)}u&&(this.exceedsMaxBuffer(a,c,u)||this.loadFragment(u,n,h))}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);i===od||i===dd?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)):super.loadFragment(t,e,s):this.clearTrackerIfNeeded(t)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==Ug){var t;((null==(t=this.getLevelDetails())?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===$g?this.mediaBuffer:this.media}checkFragmentChanged(){const t=this.fragPlaying;if(!this.checkFragPlaying())return!1;const e=this.fragPlaying;if(e){const s=e.level;this.hls.trigger(zn.FRAG_CHANGED,{frag:e,previousFrag:t}),(null==t?void 0:t.level)!==s&&this.hls.trigger(zn.LEVEL_SWITCHED,{level:s})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(t){this._backtrackFragment=t}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(t){this._couldBacktrack=t}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.targetBufferType())}targetBufferType(){return this.altAudio!==$g||this.audioOnly?null:"video"}onMediaAttached(t,e){super.onMediaAttached(t,e);const s=e.media;Dc(s,"playing",this.onMediaPlaying),Dc(s,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:s}=this;s&&(Cc(s,"playing",this.onMediaPlaying),Cc(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(t,e);!!e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(zn.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=Ug,this.audioOnly=!1}onManifestParsed(t,e){let s=!1,i=!1;for(let t=0;t<e.levels.length;t++){const r=e.levels[t].audioCodec;r&&(s=s||-1!==r.indexOf("mp4a.40.2"),i=i||-1!==r.indexOf("mp4a.40.5"))}this.audioCodecSwitch=s&&i&&!function(){var t;const e=Fg();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!==xc)return;const i=e.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=jc)}onLevelLoaded(t,e){var s;const{levels:i,startFragRequested:r}=this,n=e.level,a=e.details,o=a.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=e.levelInfo,d=this.fragCurrent;!d||this.state!==Nc&&this.state!==Uc||d.level!==e.level&&d.loader&&this.abortCurrentFrag();let c=0;if(a.live||null!=(s=l.details)&&s.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,null==(h=this.levelLastLoaded)?void 0:h.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,c),this.hls.trigger(zn.LEVEL_UPDATED,{details:a,level:n}),this.state===jc){if(this.waitForCdnTuneIn(a))return;this.state=xc}r&&a.live&&this.synchronizeToLiveEdge(a),this.initPTS.some((t,e)=>{if(e>=a.startCC)return!0;delete this.initPTS[e]}),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.playhead,n=t.fragmentStart,a=t.edge,o=r>=n-e.maxFragLookUpTolerance&&r<=a;if(null!==i&&s.duration>i&&(r<i||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!o&&s.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i}`),"buffered"===this.config.liveSyncMode){var l;const t=BufferHelper.bufferInfo(s,i,0);if(null==(l=t.buffered)||!l.length)return void(s.currentTime=i);if(t.start<=r)return void(s.currentTime=i);const{nextStart:e}=BufferHelper.bufferedInfo(t.buffered,r,0);e&&(s.currentTime=e)}else s.currentTime=i}}_handleFragmentLoadProgress(t){var e;const s=t.frag,{part:i,payload:r}=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];if(!a)return void this.warn(`Level ${s.level} not found on progress`);const 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,h=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new TransmuxerInterface(this.hls,da,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,{decryptRange:p,byteRange:m}=yd(s,i,this.iframesOnly),v=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount,m?m.end-m.start:r.byteLength,f,g,s.duration,this.iframesOnly,p),y=this.initPTS[s.cc];u.push(r,c,h,l,s,i,o.totalduration,d,v,y)}onAudioTrackSwitching(t,e){const s=this.hls,i=this.altAudio!==Ug;if(Bl(e.url,s))this.altAudio=Bg;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const 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();if(i)return this.altAudio=Ug,this.fragmentTracker.removeAllFragments(),s.once(zn.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(zn.AUDIO_TRACK_SWITCHED,e)}),void s.trigger(zn.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});s.trigger(zn.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const s=Bl(e.url,this.hls);if(s){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=s?$g:Ug,this.tick()}onBufferCreated(t,e){const s=e.tracks;let i,r,n=!1;for(const t in s){const e=s[t];if("main"===e.id){if(r=t,i=e,"video"===t){const e=s[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:s,part:i}=e,r=s.type===da;if(r){if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Gc&&(this.state=xc));let t=!1;if(pa(s)&&(t=!!s.gap&&!s.tagList.some(t=>"GAP"===t[0])),this.fragBufferedComplete(s,i),t){var n;s.stats.retry++;const t=null==(n=this.levels)?void 0:n[s.level];t&&t.fragmentError++}}const a=this.media;a&&(!this._hasEnoughToStart&&BufferHelper.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var s;if(e.fatal)this.state=Kc;else switch(e.details){case Yn.FRAG_GAP:case Yn.FRAG_PARSING_ERROR:case Yn.FRAG_DECRYPT_ERROR:case Yn.FRAG_LOAD_ERROR:case Yn.FRAG_LOAD_TIMEOUT:case Yn.KEY_LOAD_ERROR:case Yn.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(da,e);break;case Yn.LEVEL_LOAD_ERROR:case Yn.LEVEL_LOAD_TIMEOUT:case Yn.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==jc||(null==(s=e.context)?void 0:s.type)!==ea||(this.state=xc);break;case Yn.BUFFER_APPEND_NO_PROGRESS:if("main"!==e.parent)return;e.frag&&(e.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${e.frag.sn} of level ${e.frag.level} as a gap after ${e.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(e.frag));break;case Yn.BUFFER_ADD_CODEC_ERROR:case Yn.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case Yn.BUFFER_FULL_ERROR:if("main"!==e.parent)return;if(this.reduceLengthAndFlushBuffer(e)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case Yn.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=xc,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==ua||!this.altAudio){const t=(e===fa?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),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 i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=BufferHelper.getBuffered(t),a=n.length?n.start(0):0,o=a-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),s+=o,this.startPosition=s),e<s&&(this.log(`seek to target start position ${s} from current time ${e} buffer start ${a}`),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(t=>{const{hls:s}=this,i=null==t?void 0:t.frag;if(!i||this.fragContextChanged(i))return;e.fragmentError=0,this.state=xc,this.startFragRequested=!1,this.bitrateTest=!1;const r=i.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger(zn.FRAG_LOADED,t),i.bitrateTest=!1}).catch(e=>{this.state!==Mc&&this.state!==Kc&&(this.warn(e),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const e=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=t,n=this.getCurrentContext(r);if(!n)return void this.resetWhenMissingContext(r);const{frag:a,part:o,level:l}=n,{video:d,text:c,id3:h,initSegment:u}=i,{details:f}=l,g=this.altAudio?void 0:i.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=$c,u){const t=u.tracks;if(t){const i=a.initSegment||a;if(this.unhandledEncryptionError(u,a))return;this._bufferInitSegment(l,t,i,r),s.trigger(zn.FRAG_PARSING_INIT_SEGMENT,{frag:i,id:e,tracks:t})}const i=u.initPTS,n=u.timescale,o=this.initPTS[a.cc];if(Vn(i)&&(!o||o.baseTime!==i||o.timescale!==n)){const t=u.trackId;this.initPTS[a.cc]={baseTime:i,timescale:n,trackId:t};const r=this.initPTS.slice(0);s.trigger(zn.INIT_PTS_FOUND,{timestampOffsets:r,frag:a,id:e,initPTS:i,timescale:n,trackId:t})}}if(d&&f){g&&"audiovideo"===d.type&&this.logMuxedErr(a);const t=f.fragments[a.sn-1-f.startSN],e=a.sn===f.startSN,s=!t||a.cc>t.cc;if(!1!==i.independent){const{startPTS:t,endPTS:i,startDTS:n,endDTS:l}=d;if(o)o.elementaryStreams[d.type]={startPTS:t,endPTS:i,startDTS:n,endDTS:l};else if(d.firstKeyFrame&&d.independent&&1===r.id&&!s&&(this.couldBacktrack=!0),d.dropped&&d.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=d.firstKeyFramePTS?d.firstKeyFramePTS:t;if(!e&&n<o-this.config.maxBufferHole&&!s)return void this.backtrack(a);s&&(a.gap=!0),a.setElementaryStreamInfo(d.type,a.start,i,a.start,l,!0)}else e&&t-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(d.type,t,i,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(d,a,o,r,e||s)}else{if(!e&&!s)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=g;o&&(o.elementaryStreams[ua]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),a.setElementaryStreamInfo(ua,t,e,s,i),this.bufferFragmentData(g,a,o,r)}if(f&&null!=h&&h.samples.length){const t={id:e,frag:a,details:f,samples:h.samples};s.trigger(zn.FRAG_PARSING_METADATA,t)}if(f&&c){const t={id:e,frag:a,details:f,samples:c.samples};s.trigger(zn.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${pa(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,s,i){if(this.state!==$c)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:a}=e;if(r){const s=t.audioCodec;let i=cl(r.codec,s);if("mp4a"===i&&(i="mp4a.40.5"),this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=r.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&!function(){if(void 0===zo){const t=qo.match(/Firefox\/(\d+)/i);zo=t?parseInt(t[1]):0}return zo}()&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&/Android/.test(qo)&&"audio/mpeg"!==r.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),s&&s!==i&&this.log(`Swapping manifest audio codec "${s}" for "${i}"`),r.levelCodec=i,r.id=da,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${i||""}/${s||""}/${r.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=da;const s=n.codec;if(4===(null==s?void 0:s.length))switch(s){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${s}]${n.codec!==s?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete e.audiovideo}a&&(this.iframesOnly&&this.logMuxedErr(s),this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),delete e.video,delete e.audio);const o=Object.keys(e);if(o.length){if(this.hls.trigger(zn.BUFFER_CODECS,e),!this.hls)return;o.forEach(t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger(zn.BUFFER_APPENDING,{type:t,data:r,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.getBufferOutput();return this.getFwdBufferInfo(t,da)}get maxBufferLength(){const{levels:t,level:e}=this,s=null==t?void 0:t[e];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}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=xc}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return Vn(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(Vn(e)){const t=this.getLevelDetails(),s=this.currentFrag||(t?Kl(null,t.fragments,e):null);if(s){const t=s.programDateTime;if(null!==t){const i=t+1e3*(e-s.start);return new Date(i)}}}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 IFrameStreamController extends StreamController{constructor(...t){super(...t),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{const t=this.media;null!=t&&t.seeking&&(t.currentTime=t.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(t){this.initPTS=t.slice()}loadMediaAt(t,e){if(!this.hls)return;const{seekOnAppend:s}=e,i=t+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=i,this.startPosition=t,this.state){case Mc:case Hc:case Kc:this.state=xc}this.state===xc?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[i,e]):this.nextOp=[i,e],this.hls.off(zn.BUFFERED_TO_END,this.onBufferedToEnd);const r=this.media;if(s&&r){this.seekTo(i)&&(this.currentOp=[i,e],this.nextOp=void 0,this.flushPipeline(i,!0))}}seekTo(t){const e=this.media;if(e){var s;const i=null==(s=this.getLevelDetails())?void 0:s.edge,r=void 0!==i?i:e.duration;t>=r&&(t=r-.01);if(BufferHelper.bufferInfo(e,t,0).len>0&&this.getBufferedAt(t))return e.currentTime=t,!0}return!1}getBufferedAt(t){return this.fragmentTracker.getBufferedFrag(t,da)}cacheSet(t,e){if(!this.hls)return;t.data=e;const s=this.cached;s.push(t),this.cachedSize+=e.buffer.byteLength;const i=this.hls.config.iframeCacheLimit;for(;this.cachedSize>i&&s.length>1;){const t=s.shift();if(!t.data){this.cached=s.filter(t=>!!t.data),this.cachedSize=s.reduce((t,{data:e})=>e?e.buffer.byteLength:0,0);break}this.cachedSize-=t.data.byteLength,t.data=void 0}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(t){const e=t.frag,{part:s,payload:i}=t;this.cacheFragmentData&&!s&&null!=i&&i.byteLength&&!e.data&&pa(e)&&this.cacheSet(e,new Uint8Array(i.slice(0))),super._handleFragmentLoadProgress(t)}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);i!==od&&i!==dd||!this.canReplayCached(t)?super.loadFragment(t,e,s):this.replayCachedFragment(t)}canReplayCached(t){var e;if(!this.cacheFragmentData||null==(e=t.data)||!e.byteLength)return!1;const s=t.decryptdata;return"identity"!==(null==s?void 0:s.keyFormat)||!!s.key}replayCachedFragment(t){const e=t.data.slice().buffer;this.log(`Buffering cached ${t.type} sn: ${t.sn} of level ${t.level} (${e.byteLength} bytes)`),this.fragCurrent=t,this.startFragRequested=!0;const s=t.stats=new LoadStats;s.loading.start=s.loading.first=s.loading.end=self.performance.now(),s.loaded=s.total=e.byteLength,s.chunkCount=1,this.state=Nc;const i={frag:t,part:null,payload:e,networkDetails:null};this._handleFragmentLoadProgress(i),this.hls.trigger(zn.FRAG_LOADED,i),this._handleFragmentLoadComplete(i)}fragBufferedComplete(t,e){super.fragBufferedComplete(t,e);const{currentOp:s,nextOp:i}=this;this.currentOp=this.nextOp=void 0,this.state=Mc,null!=s&&s[1].seekOnAppend&&(this.flushPipeline(s[0],!i),this.seekTo(s[0])||this.log(`Could not seek to ${s[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?Oc(BufferHelper.getBuffered(this.media)):"none"}`)),i&&this.loadMediaAt.apply(this,i)}flushPipeline(t,e){if(e){const e=this.media;if(e){const s=BufferHelper.bufferInfo(e,t,0),i=s.len?s.nextStart:0;i&&(this.fragmentTracker.removeFragmentsInRange(i,1/0,da),this.flushMainBuffer(i,1/0))}this.hls.once(zn.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(zn.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){const t=this.hls;t.nextLoadLevel=-1===t.startLevel?0:t.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(t,e,s){const i=this.initDetails;return this.initDetails=null,super.alignPlaylists(t,e,s||i||void 0)}getMainFwdBufferInfo(){const t=this.playhead,e=this.getBufferedAt(t);if(e){const s=e.duration;return{len:s,start:t,end:t+s,bufferedIndex:-1}}return{len:0,start:t,end:t,bufferedIndex:-1}}_streamEnded(){const t=this.playhead,e=this.fragmentTracker.getBufferedFrag(t,da);return!(null==e||!e.endList)}}class ImageIFrameStreamController extends IFrameStreamController{constructor(...t){super(...t),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(t){var e;const s=null==(e=this._img)?void 0:e.src;s&&self.URL.revokeObjectURL(s),this._img=t}loadMediaAt(t){if(!this.hls)return;const e=t+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=e,this.startPosition=t,this.state){case Mc:case Hc:case Kc:this.state=xc}if(this.state===xc){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===xc){const e=this.getBufferedAt(t);e&&(this.fragCurrent=e,this.updateImage(e,null))}}else{const s=this.fragCurrent;(!s||t>=s.start&&t<s.end)&&(this.queued=[e])}}updateImage(t,e,s){const i=t.data;i||this.fragmentTracker.removeFragment(t);const r=this._img;if(r&&i){const n=self.performance.now();(e?e.stats:t.stats).buffering.start=t.stats.buffering.start=n,r.onload=()=>{if(!this.hls)return;const i=this.hls.levels[t.level];null!=i&&i.fragmentError&&(i.fragmentError=0,t.stats.retry=0);const r=self.performance.now(),n=e?e.stats:t.stats;n.buffering.end=t.stats.buffering.end=r,this.hls.trigger(zn.FRAG_BUFFERED,{frag:t,part:e,stats:n,id:t.type,chunkMeta:s})},r.onerror=()=>{this.handleError("Image decode error",t,e,s)};const a=r.src;a&&self.URL.revokeObjectURL(a);const o=new Blob([i],{type:"image/jpeg"});r.src=self.URL.createObjectURL(o)}else this.state=Mc,this.processQueued()}processQueued(){const t=this.queued;this.queued=void 0,t&&this.loadMediaAt.apply(this,t)}handleError(t,e,s,i){if(!this.hls)return;const r=new Error(t);this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.FRAG_PARSING_ERROR,chunkMeta:i,frag:e,part:s,fatal:!1,error:r,err:r})}_bufferInitSegment(){}bufferFragmentData(t,e,s,i){super.bufferFragmentData(t,e,s,i,!0);const r=bo(new Uint8Array(t.data1),["mdat"]);if(0===r.length)return void this.handleError("Could not find I-Frame mdat",e,s,i);const n=e;this.cacheSet(n,r[0]),this.updateImage(n,s,i)}fragBufferedComplete(t,e){this.fragmentTracker.fragBuffered(t,!0),super.fragBufferedComplete(t,e),this.processQueued()}checkFragPlaying(){var t;const e=null==(t=this.fragPrevious)?void 0:t.start;if(void 0!==e){const t=this.getAppendedFrag(e);if(t&&!ma(t,this.fragPlaying))return this.fragPlaying=t,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}const Gg="Image I-Frame player does not accept HTMLMediaElements",Hg={seekOnAppend:!0};let Kg,Vg;const jg=.025;let qg=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function Wg(t,e,s){return`${t.identifier}-${s+1}-${dg(e)}`}class InterstitialEvent{constructor(t,e){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=e,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,null==(t=this.assetListLoader)||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var e;if(t>0&&t>=this.assetList.length)return!0;const s=this.playoutLimit;if(t<=0||isNaN(s))return!1;if(0===s)return!0;return((null==(e=this.assetList[t])?void 0:e.startOffset)||0)>s}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const e=this.dateRange.tagAnchor;if(e)return zg(e,t)?Yg(t,e):t}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const e=this.dateRange.startTime;return e-Yg(e,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,e=Vn(t)?t:this.duration;return this.cumulativeDuration+e}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const e=this.resumeAnchor;if(e)return zg(e,t)?Yg(t,e):t}return t}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<jg))}set appendInPlace(t){this.appendInPlaceStarted?this.resetOnResume=!t:this.appendInPlaceDisabled=!t}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let e;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e}set duration(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?qg.Range:qg.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(t=this).identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`;var t}}function Yg(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<jg)?e.start:e.start+e.duration}function zg(t,e){return e>t.start-jg&&e<t.start+t.duration+jg}function Qg(t,e,s){const i=new self.URL(t,s);return"data:"!==i.protocol&&Al(i,"_HLS_primary_id",e),i}function Xg(t,e){for(;null!=(s=t.assetList[++e])&&s.error;)var s;return e}function Zg(t){const e=t.timelineStart,s=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+s).toFixed(2)}]`}class HlsAssetPlayer{constructor(t,e,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(zn.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new t(e);this.interstitial=s,this.assetItem=i;const n=()=>{this.hasDetails=!0};r.once(zn.LEVEL_LOADED,n),r.once(zn.AUDIO_TRACK_LOADED,n),r.once(zn.SUBTITLE_TRACK_LOADED,n),r.on(zn.MEDIA_ATTACHING,(t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e;this.interstitial.playoutLimit&&(e.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(zn.BUFFER_APPENDED,()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,r.trigger(zn.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let e=this.assetItem.uri;try{e=Qg(e,t.config.primarySessionId||"").href}catch(t){}t.loadSource(e)}}bufferedInPlaceToEnd(t,e){var s;if(!this.appendInPlace)return!1;if(null!=(s=this.hls)&&s.bufferedToEnd)return!0;if(!t)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset+(e||0),n=BufferHelper.bufferInfo(t,r,.02);return this.getAssetTime(n.end)>=i-.02}reachedPlayout(t){const e=this.interstitial.playoutLimit;return this.startOffset+t>=e}get destroyed(){var t;return!(null!=(t=this.hls)&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return(null==(t=this.hls)?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const e=BufferHelper.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const e=this.interstitial.playoutLimit;if(e){const s=e-this.startOffset;if(s>0&&s<t)return s}return t}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const e=this.timelineOffset;if(t!==e){const s=t-e;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const e=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,t-e),s)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var t;this.mediaAttached&&(null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var e;this.loadSource(),null==(e=this.hls)||e.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,null==(t=this.hls)||t.detachMedia()}resumeBuffering(){var t;null==(t=this.hls)||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.hls)||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),(null==(t=this.hls)?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const e=t=>delete t.details;t.levels.forEach(e),t.allAudioTracks.forEach(e),t.allSubtitleTracks.forEach(e),this.hasDetails=!1}}on(t,e,s){var i;null==(i=this.hls)||i.on(t,e)}once(t,e,s){var i;null==(i=this.hls)||i.once(t,e)}off(t,e,s){var i;null==(i=this.hls)||i.off(t,e)}toString(){var t;return`HlsAssetPlayer: ${Zg(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Jg=.033;class InterstitialsSchedule extends Logger{constructor(t,e){super("interstitials-sched",e),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,e){return this.events?this.events.reduce((s,i)=>t<=i.startOffset&&e>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,e){if(t.event)return this.findEventIndex(t.event.identifier);let s=-1;t.nextEvent?s=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(s=this.findEventIndex(t.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(void 0===e&&(e=t.start),s=this.findItemIndexAtTime(e));s>=0&&null!=(r=i[s])&&r.event;){var r;s--}return s}findItemIndexAtTime(t,e){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];e&&"primary"!==e&&(r=r[e]);const n=r.start,a=s[i].event,o=null!=a&&a.cue.pre?a.duration:r.end;if(t===n||t>n&&t<o)return i}return-1}findJumpRestrictedIndex(t,e){const s=this.items;if(s)for(let i=t;i<=e&&s[i];i++){const t=s[i].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return i}return-1}findEventIndex(t){const e=this.items;if(e)for(let i=e.length;i--;){var s;if((null==(s=e[i].event)?void 0:s.identifier)===t)return i}return-1}findAssetIndex(t,e){const s=t.assetList,i=s.length;if(i>1)for(let t=0;t<i;t++){const r=s[t];if(!r.error){const s=r.timelineStart;if(e===s||e>s&&(e<s+(r.duration||0)||t===i-1))return t}}return 0}get assetIdAtEnd(){var t;const e=null==(t=this.items)||null==(t=t[this.length-1])?void 0:t.event;if(e){const t=e.assetList,s=t[t.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(t,e,s=0){const i=t.main.details,{dateRanges:r}=i,n=this.events,a=this.parseDateRanges(r,{url:i.url},e),o=Object.keys(r),l=n?n.filter(t=>-1===o.indexOf(t.identifier)):[];a.length&&a.sort((t,e)=>{const s=t.cue.pre,i=t.cue.post,r=e.cue.pre,n=e.cue.post;if(s&&!r)return-1;if(r&&!s)return 1;if(i&&!n)return 1;if(n&&!i)return-1;if(!(s||r||i||n)){const s=t.startTime,i=e.startTime;if(s!==i)return s-i}return t.dateRange.tagOrder-e.dateRange.tagOrder}),this.events=a,l.forEach(t=>{this.removeEvent(t)}),this.updateSchedule(t,l,s)}updateSchedule(t,e=[],s=0,i=!1){const r=this.events||[];if(r.length||e.length||this.length<2){const n=this.items,a=this.parseSchedule(r,t,s);(i||e.length||(null==n?void 0:n.length)!==a.length||a.some((t,e)=>Math.abs(t.playout.start-n[e].playout.start)>.005||Math.abs(t.playout.end-n[e].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(e,n))}}parseDateRanges(t,e,s){const i=[],r=Object.keys(t);for(let n=0;n<r.length;n++){const a=r[n],o=t[a];if(o.isInterstitial){let t=this.eventMap[a];t?t.setDateRange(o):(t=new InterstitialEvent(o,e),this.eventMap[a]=t,!1===s&&(t.appendInPlace=s)),i.push(t)}}return i}parseSchedule(t,e,s=0){const i=[],r=e.main.details,n=r.live?1/0:r.edge;let a=0;if((t=t.filter(t=>!(t.error||t.cue.once&&t.hasPlayed))).length){this.resolveOffsets(t,e);let l=0,d=0;if(t.forEach((e,o)=>{const c=e.cue.pre,h=e.cue.post,u=t[o-1]||null,f=e.appendInPlace,g=h?n:e.startOffset,p=e.duration,m=e.timelineOccupancy===qg.Range?p:0,v=c&&r.live?s+(e.resumeOffset||0):0,y=v||e.resumptionOffset,E=(null==u?void 0:u.startTime)===g,T=g+e.cumulativeDuration;let S=f?T+p:g+y;if(c||!h&&g<=0){const t=d;d+=m,e.timelineStart=T;const s=a;a+=p,i.push({event:e,start:T,end:S,playout:{start:s,end:a},integrated:{start:t,end:d}})}else{if(!(g<=n))return;{if(!E){const s=g-l;if(s>Jg){const r=l,n=d;d+=s;const c=a;a+=s;const h={previousEvent:t[o-1]||null,nextEvent:e,start:r,end:r+s,playout:{start:c,end:a},integrated:{start:n,end:d}};i.push(h)}else s>0&&u&&(u.cumulativeDuration+=s,i[i.length-1].end=g)}h&&(S=T),e.timelineStart=T;const s=d;d+=m;const r=a;a+=p,i.push({event:e,start:T,end:S,playout:{start:r,end:a},integrated:{start:s,end:d}})}}const A=v||e.resumeTime;l=h||A>n?n:!c&&S&&e.appendInPlaceStarted&&A-S>Jg?S:A}),l<n){var o;const t=l,e=d,s=n-l;d+=s;const r=a;a+=s,i.push({previousEvent:(null==(o=i[i.length-1])?void 0:o.event)||null,nextEvent:null,start:l,end:t+s,playout:{start:r,end:a},integrated:{start:e,end:d}})}this.setDurations(n,a,d)}else{const t=0;i.push({previousEvent:null,nextEvent:null,start:t,end:n,playout:{start:t,end:n},integrated:{start:t,end:n}}),this.setDurations(n,n,n)}return i}setDurations(t,e,s){this.durations={primary:t,playout:e,integrated:s}}resolveOffsets(t,e){const s=e.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;t.forEach((a,o)=>{const l=a.cue.pre,d=a.cue.post,c=l?0:d?i:a.startTime;this.updateAssetDurations(a);if(n===c?a.cumulativeDuration=r:(r=0,n=c),!d&&a.snapOptions.in&&(a.resumeAnchor=Kl(null,s.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,e)||(a.appendInPlace=!1)}if(!a.appendInPlace&&o+1<t.length){t[o+1].startTime-t[o].resumeTime<Jg&&(t[o+1].appendInPlace=!1,t[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`))}const h=Vn(a.resumeOffset)?a.resumeOffset:a.duration;r+=h})}primaryCanResumeInPlaceAt(t,e){const s=t.resumeTime,i=t.startTime+t.resumptionOffset;if(Math.abs(s-i)>jg)return this.log(`"${t.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1;return!Object.keys(e).some(i=>{const r=e[i].details,n=r.edge;if(s>=n)return this.log(`"${t.identifier}" resumption ${s} past ${i} playlist end ${n}`),!1;const a=Kl(null,r.fragments,s);if(!a)return this.log(`"${t.identifier}" resumption ${s} does not align with any fragments in ${i} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===i?.175:0;return!(Math.abs(a.start-s)<jg+o||Math.abs(a.end-s)<jg+o)&&(this.log(`"${t.identifier}" resumption ${s} not aligned with ${i} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})}updateAssetDurations(t){if(!t.assetListLoaded)return;const e=t.timelineStart;let s=0,i=!1,r=!1;for(let n=0;n<t.assetList.length;n++){const a=t.assetList[n],o=e+s;a.startOffset=s,a.timelineStart=o,i||(i=null===a.duration),r||(r=!!a.error);s+=a.error?0:a.duration||0}t.duration=i&&!r?Math.max(s,t.duration):s}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function tp(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class AssetListLoader{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const s=t.assetListUrl;let i;try{i=Qg(s,this.hls.sessionId,t.baseUrl)}catch(e){const i=this.assignAssetListError(t,Yn.ASSET_LIST_LOAD_ERROR,e,s);return void this.hls.trigger(zn.ERROR,i)}e&&"data:"!==i.protocol&&Al(i,"_HLS_start_offset",""+e);const r=this.hls.config,n=new(0,r.loader)(r),a={type:la,responseType:"json",url:i.href},o=r.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,s,i,r)=>{const n=e.data,a=null==n?void 0:n.ASSETS;if(!Array.isArray(a)){const e=this.assignAssetListError(t,Yn.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),i.url,s,r);return void this.hls.trigger(zn.ERROR,e)}t.assetListResponse=n,this.hls.trigger(zn.ASSET_LIST_LOADED,{event:t,assetListResponse:n,networkDetails:r})},onError:(e,s,i,r)=>{const n=this.assignAssetListError(t,Yn.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${s.url})`),s.url,r,i);this.hls.trigger(zn.ERROR,n)},onTimeout:(e,s,i)=>{const r=this.assignAssetListError(t,Yn.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${s.url})`),s.url,e,i);this.hls.trigger(zn.ERROR,r)}};return n.load(a,l,d),this.hls.trigger(zn.ASSET_LIST_LOADING,{event:t}),n}assignAssetListError(t,e,s,i,r,n){return t.error=s,{type:Wn.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:i,error:s,networkDetails:n,stats:r}}}function ep(t){var e;null==t||null==(e=t.play())||e.catch(()=>{})}function sp(t,e){return`[${t}] Advancing timeline position to ${e}`}class BufferableInstance{constructor(t){this.buffered=void 0;const e=(e,s,i)=>{if((s>>>=0)>i-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${i})`);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)}}}const ip={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},rp=t=>String.fromCharCode(ip[t]||t),np=15,ap=42,op={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},lp={17:2,18:4,21:6,22:8,23:10,19:13,20:15},dp={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},cp={25:2,26:4,29:6,30:8,31:10,27:13,28:15},hp=["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;Ua.log(`${this.time} [${t}] ${s}`)}}}const up=function(t){const e=[];for(let s=0;s<t.length;s++)e.push(t[s].toString(16));return e},fp=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1});class PenState{constructor(){this.styles=fp}get foreground(){return this.styles.foreground}set foreground(t){const e=this.styles;this.styles={foreground:t,underline:e.underline,italics:e.italics,background:e.background,flash:e.flash}}get underline(){return this.styles.underline}set underline(t){const e=this.styles;this.styles={foreground:e.foreground,underline:t,italics:e.italics,background:e.background,flash:e.flash}}get italics(){return this.styles.italics}set italics(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:t,background:e.background,flash:e.flash}}get background(){return this.styles.background}set background(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:e.italics,background:t,flash:e.flash}}get flash(){return this.styles.flash}set flash(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:e.italics,background:e.background,flash:t}}reset(){this.styles=fp}setStyles(t){const e=this.styles,s=Object.prototype.hasOwnProperty;this.styles={foreground:s.call(t,"foreground")?t.foreground:e.foreground,underline:s.call(t,"underline")?t.underline:e.underline,italics:s.call(t,"italics")?t.italics:e.italics,background:s.call(t,"background")?t.background:e.background,flash:s.call(t,"flash")?t.flash:e.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class StyledUnicodeChar{constructor(){this.uchar=" ",this.penState=new PenState}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.styles=e.styles}setPenState(t){this.penState.styles=t.styles}copy(t){this.uchar=t.uchar,this.penState.styles=t.penState.styles}}class Row{constructor(t){this.chars=[],this.pos=0,this.currPenState=new PenState,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<ap;t++)this.chars.push(new StyledUnicodeChar);this.logger=t}equals(t){const e=this.chars,s=t.chars;for(let t=0;t<ap;t++){const i=e[t],r=s[t];if(i.uchar!==r.uchar)return!1;const n=i.penState.styles,a=r.penState.styles;if(n!==a&&(n.foreground!==a.foreground||n.underline!==a.underline||n.italics!==a.italics||n.background!==a.background||n.flash!==a.flash))return!1}return!0}copy(t){for(let e=0;e<ap;e++)this.chars[e].copy(t.chars[e])}isEmpty(){const t=this.chars;for(let e=0;e<ap;e++){const s=t[e];if(" "!==s.uchar)return!1;const i=s.penState.styles;if(i!==fp&&("white"!==i.foreground||i.underline||i.italics||"black"!==i.background||i.flash))return!1}return!0}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>=ap&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=41)}moveCursor(t){const e=Math.min(this.pos+t,ap);if(t>1)for(let t=this.pos+1;t<e;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=rp(t);this.pos>=ap?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<ap;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<ap;s++){const i=this.chars[s].uchar;" "!==i&&(e=!1),t.push(i)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class CaptionScreen{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<np;e++)this.rows.push(new Row(t));this.logger=t}reset(){for(let t=0;t<np;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let s=0;s<np;s++)if(!this.rows[s].equals(t.rows[s])){e=!1;break}return e}copy(t){for(let e=0;e<np;e++){const s=this.rows[e].chars,i=t.rows[e].chars;for(let t=0;t<ap;t++){const e=s[t],r=i[t];e.uchar=r.uchar,e.penState.styles=r.penState.styles}}}isEmpty(){let t=!0;for(let e=0;e<np;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 = "+Dl(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<np;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const i=s.rows[t].cueStartTime,r=this.logger.time;if(null!==i&&null!==r&&i<r)for(let i=0;i<this.nrRollUpRows;i++)this.rows[e-this.nrRollUpRows+i+1].copy(s.rows[t+i])}}this.currRow=e;const s=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,i=Math.max(e-1,0);s.setCursor(t.indent),t.color=s.chars[i].penState.foreground}const i={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+Dl(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="",i=-1;for(let s=0;s<np;s++){const r=this.rows[s].getTextString();r&&(i=s+1,t?e.push("Row "+i+": '"+r+"'"):e.push(r.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,i=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=i[s]}this.logger.log(2,"MIDROW: "+Dl(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=[null,null,null],this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new CaptionsLogger,this.field=t,this.outputFilters=[null,e,s]}getHandler(t){return this.outputFilters[t]}setHandler(t,e){var s;this.outputFilters[t]=e,null==(s=this.channels[t])||s.setHandler(e)}getChannel(t){let e=this.channels[t];return e||(e=this.channels[t]=new Cea608Channel(this.field+t-1,this.outputFilters[t],this.logger)),e}addData(t,e){this.logger.time=t;for(let t=0;t<e.length;t+=2){const s=127&e[t],i=127&e[t+1];let r=!1,n=null;if(0===s&&0===i)continue;this.logger.log(3,()=>"["+up([e[t],e[t+1]])+"] -> ("+up([s,i])+")");const a=this.cmdHistory;if(s>=16&&s<=31){if(pp(s,i,a)){gp(null,null,a),this.logger.log(3,()=>"Repeated command ("+up([s,i])+") is dropped");continue}gp(s,i,this.cmdHistory),r=this.parseCmd(s,i),r||(r=this.parseMidrow(s,i)),r||(r=this.parsePAC(s,i)),r||(r=this.parseBackgroundAttributes(s,i))}else gp(null,null,a);if(!r&&(n=this.parseChars(s,i),n)){const t=this.currentChannel;if(t&&t>0){this.getChannel(t).insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+up([s,i])+" orig: "+up([e[t],e[t+1]]))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;const s=20===t||21===t||23===t?1:2,i=this.getChannel(s);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),this.currentChannel=s,!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 i=this.channels[s];return!!i&&(i.ccMIDROW(e),this.logger.log(3,()=>"MIDROW ("+up([t,e])+")"),!0)}return!1}parsePAC(t,e){let s;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const i=t<=23?1:2;s=e>=64&&e<=95?1===i?op[t]:dp[t]:1===i?lp[t]:cp[t];return this.getChannel(i).setPAC(this.interpretPAC(s,e)),this.currentChannel=i,!0}interpretPAC(t,e){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:t};return s=e>95?e-96:e-64,i.underline=!(1&~s),s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((s-16)/2),i}parseChars(t,e){let s,i=null,r=null;if(t>=25?(s=2,r=t-8):(s=1,r=t),r>=17&&r<=19){let t;t=17===r?e+80:18===r?e+112:e+144,this.logger.log(2,()=>"Special char '"+rp(t)+"' in channel "+s),i=[t]}else t>=32&&t<=127&&(i=0===e?[t]:[t,e]);return i&&this.logger.log(3,()=>"Char codes = "+up(i).join(",")),i}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 i={};16===t||24===t?(s=Math.floor((e-32)/2),i.background=hp[s],e%2==1&&(i.background=i.background+"_semi")):45===e?i.background="transparent":(i.foreground="black",47===e&&(i.underline=!0));const r=t<=23?1:2;return this.getChannel(r).setBkgData(i),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}gp(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const s=this.channels[e];s&&s.cueSplitAtTime(t)}}}function gp(t,e,s){s.a=t,s.b=e}function pp(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}}function mp(t,e,s,i){return Math.min(e,i)-Math.max(t,s)}const vp=/\s/,yp={newCue(t,e,s,i){const r=[];let n,a,o,l,d;const c=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=!0,l=0,d="",!n.isEmpty()){var h;for(let t=0;t<n.chars.length;t++)vp.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 i=lg(d.trim()),f=ug(e,s,i);null!=t&&null!=(h=t.cues)&&h.getCueById(f)||(a=new c(e,s,i),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return t&&r.length&&(r.sort((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line),r.forEach(e=>Ig(t,e))),r}};class BaseLoader{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new LoadStats}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(t,e,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=s,this.loadInternal()}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(Pa(t,this.stats.retry,!0))this.retry(t);else{var e;Ua.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(t){const{context:e,stats:s}=this;this.retryDelay=ka(t,s.retry),s.retry++,Ua.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${s.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}}const Ep=/(\d+)-(\d+)\/(\d+)/;class FetchLoader extends BaseLoader{constructor(t){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=t.fetchSetup||Tp}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){const{config:t,context:e,stats:s}=this;if(!t||!e)return;s.loading.first=0,s.loaded=0,s.aborted=!1,this.controller=new self.AbortController;const i=function(t,e){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Ta({},t.headers))};t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return s}(e,this.controller.signal),r="arraybuffer"===e.responseType,n=r?"byteLength":"length",{maxTimeToFirstByteMs:a,maxLoadTimeMs:o}=t.loadPolicy;this.request=this.fetchSetup(e,i),self.clearTimeout(this.requestTimeout),t.timeout=a&&Vn(a)?a:o,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},t.timeout);(tu(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(i=>{var n;this.response=i;const a=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=o,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},o-(a-s.loading.start)),!i.ok){const{status:t,statusText:e}=i;throw new FetchError(e||"fetch, bad network response",t,i)}s.loading.first=a,s.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=Ep.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(Vn(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(i.headers)||s.total;const l=null==(n=this.callbacks)?void 0:n.onProgress;return l&&Vn(t.highWaterMark)?this.loadProgressively(i,s,e,t.highWaterMark,l):r?i.arrayBuffer():"json"===e.responseType?i.json():i.text()}).then(i=>{var r,a;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const l=i[n];l&&(s.loaded=s.total=l);const d={url:o.url,data:i,code:o.status},c=null==(r=this.callbacks)?void 0:r.onProgress;c&&!Vn(t.highWaterMark)&&c(s,e,i,o),null==(a=this.callbacks)||a.onSuccess(d,s,e,o)}).catch(i=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const r=i&&i.code||0,n=i?i.message:null,a=t.loadPolicy.errorRetry;var o;Pa(a,s.retry,!1,{url:e.url,data:void 0,code:r})?this.retry(a):(Ua.error(`${r} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:r,text:n},e,i?i.details:null,s))})}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,i=0,r){const n=new ChunkCache,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&r(e,s,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return e.loaded+=d,d<i||n.dataLength?(n.push(l),n.dataLength>=i&&r(e,s,n.flush().buffer,t)):r(e,s,l.buffer,t),o()}).catch(()=>Promise.reject());return o()}}function Tp(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 Sp=/^age:\s*[\d.]+\s*$/im;class XhrLoader extends BaseLoader{constructor(t){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=t.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=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()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===s&&!this.stats.aborted)return r.call(this,s,e.url,e)}).catch(t=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",e.url,!0),r.call(this,s,e.url,e)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,e,t)}).catch(t=>{var r;null==(r=this.callbacks)||r.onError({code:s.status,text:t.message},e,s,i)}):this.openAndSendXhr(s,e,t)}openAndSendXhr(t,e,s){t.readyState||t.open("GET",e.url,!0);const i=e.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const e in i)t.setRequestHeader(e,i[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=r&&Vn(r)?r: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 i=e.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const i=e.status,l="text"===e.responseType?e.responseText:null;if(i>=200&&i<300){const r=null!=l?l:e.response;if(null!=r){var n,a;s.loading.end=Math.max(self.performance.now(),s.loading.first);const o="arraybuffer"===e.responseType?r.byteLength:r.length;s.loaded=s.total=o,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(s,t,r,e);const d={url:e.responseURL,data:r,code:i};return t.rangeEnd&&o!==t.rangeEnd-t.rangeStart&&Ua.warn(`Payload length ${o} does not match requested Range: bytes=${t.rangeStart}-${t.rangeEnd-1}`),void(null==(a=this.callbacks)||a.onSuccess(d,s,t,e))}}const d=r.loadPolicy.errorRetry;var o;if(Pa(d,s.retry,!1,{url:t.url,data:void 0,code:i}))this.retry(d);else Ua.error(`${i} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:i,text:e.statusText},t,e,s)}}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&Sp.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 Ap=Aa(Aa({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh: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,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:XhrLoader,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Wd,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:StreamController,abrController:class AbrController extends Logger{constructor(t){super("abr",t.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var e;const{fragCurrent:s,partCurrent:i,hls:r}=this;if(!r)return;const{autoLevelEnabled:n,media:a}=r;if(!s||!a)return;const o=performance.now(),l=i?i.stats:s.stats,d=i?i.duration:s.duration,c=o-l.loading.start,h=r.minAutoLevel,u=s.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||u<=h)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==u,p=!!t||g;if(!p&&(a.paused||!a.playbackRate||!a.readyState))return;const m=r.mainForwardBufferInfo;if(!p&&null===m)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(c<=Math.max(v,d/(2*y)*1e3))return;const E=m?m.len/y:0,T=l.loading.first?l.loading.first-l.loading.start:-1,S=l.loaded&&T>-1,A=this.getBwEstimate(),_=r.levels,b=_[u],L=Math.max(l.loaded,Math.round(d*(s.bitrate||b.averageBitrate)/8));let R=S?c-T:c;R<1&&S&&(R=Math.min(c,8*l.loaded/A));const I=S?1e3*l.loaded/R:0,k=v/1e3,w=I?(L-l.loaded)/I:8*L/A+k;if(w<=E)return;const P=I?8*I:A,D=!0===(null==(e=(null==t?void 0:t.details)||r.latestLevelDetails)?void 0:e.live),C=r.config.abrBandWidthUpFactor;let O,M=Number.POSITIVE_INFINITY;for(O=u-1;O>h;O--){const t=_[O].maxBitrate,e=!_[O].details||D;if(M=this.getTimeToLoadFrag(k,P,d*t,e),M<Math.min(E,d+k))break}if(M>=w)return;if(M>10*d)return;S?this.bwEstimator.sample(c-Math.min(v,T),l.loaded):this.bwEstimator.sampleTTFB(c);const x=_[O].maxBitrate;this.getBwEstimate()*C>x&&(this.firstAutoFloor=Math.min(O,r.firstLevel),this.resetEstimator(x));const F=this.findBestLevel(x,h,O,0,E,1,1);F>-1&&(O=F),this.warn(`Fragment ${s.sn}${i?" part "+i.index:""} of level ${u} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${E.toFixed(3)} s\n Estimated load time for current fragment: ${w.toFixed(3)} s\n Estimated load time for down switch fragment: ${M.toFixed(3)} s\n TTFB estimate: ${0|T} ms\n Current BW estimate: ${Vn(A)?0|A:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${O} @ ${0|x} bps`),r.nextLoadLevel=r.nextAutoLevel=O,this.clearTimer();const N=()=>{this.clearTimer();const t=this.hls;if(this.fragCurrent===s&&t.loadLevel===O&&O>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${O>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,O>h){let s=this.findBestLevel(t.levels[h].bitrate,h,O,0,e,1,1);-1===s&&(s=h),t.nextLoadLevel=t.nextAutoLevel=s,this.firstAutoFloor=Math.min(s,t.firstLevel),this.resetEstimator(t.levels[s].bitrate)}}};g||w>2*M?N():this.timer=self.setInterval(N,1e3*M),r.trigger(zn.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:i,stats:l})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){this.hls&&(t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){const t=this.hls.config;return new EwmaBandWidthEstimator(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const t=this.hls;t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.FRAG_LOADING,this.onFragLoading,this),t.on(zn.FRAG_LOADED,this.onFragLoaded,this),t.on(zn.FRAG_BUFFERED,this.onFragBuffered,this),t.on(zn.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.on(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(zn.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(zn.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.FRAG_LOADING,this.onFragLoading,this),t.off(zn.FRAG_LOADED,this.onFragLoaded,this),t.off(zn.FRAG_BUFFERED,this.onFragBuffered,this),t.off(zn.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.off(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(zn.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(zn.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const s=e.frag;if(!this.ignoreFragment(s)){var i;if(!s.bitrateTest)this.fragCurrent=s,this.partCurrent=null!=(i=e.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case Yn.BUFFER_ADD_CODEC_ERROR:case Yn.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Yn.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:s,partCurrent:i}=this;if(t&&va(t,s)){const e=performance.now(),s=i?i.stats:t.stats,r=e-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(t,n),s.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,s,i){return t+s/e+(i?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const s=this.hls.config,{loading:i}=e.stats,r=i.end-i.first;Vn(r)&&(this.lastLevelLoadSec=r/1e3),e.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,e){var s;const{frag:i,part:r}=e,n=r?r.stats:i.stats;if(i.type===da&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,null!=(s=this.hls)&&s.config.abrMaxWithRealBitrate){const t=r?r.duration:i.duration,e=this.hls.levels[i.level],s=(e.loaded?e.loaded.bytes:0)+n.loaded,a=(e.loaded?e.loaded.duration:0)+t;e.loaded={bytes:s,duration:a},e.realBitrate=Math.round(8*s/a)}if(i.bitrateTest){const t={stats:n,frag:i,part:r,id:i.type};this.onFragBuffered(zn.FRAG_BUFFERED,t),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}}onFragBuffered(t,e){const{frag:s,part:i}=e,r=null!=i&&i.stats.loaded?i.stats:s.stats;if(r.aborted)return;if(this.ignoreFragment(s))return;const n=((s.bitrate||0)>=1e5?r.parsing.end:r.loading.end)-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(t){return t.type!==da||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{hls:t}=this;if(!t)return 0;const{maxAutoLevel:e,minAutoLevel:s}=t,i=this.getBwEstimate(),r=this.getStarvationDelay(),n=t.config.maxStarvationDelay,a=this.findBestLevel(i,s,e,r/2,n,1,1);if(a>-1)return a;const o=t.firstLevel,l=-1===this.firstAutoFloor?1/0:this.firstAutoFloor,d=Math.min(Math.max(o,s),e,l);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${d}`),d}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const i=e&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,i)&&e[t].loadError<=e[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:s}=this;if(!s)return-1;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=r.abrBandWidthFactor,c=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,i,l,0,d,c);if(t>=0)return this.rebufferNotice=-1,t}let h=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){h=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),d=c=1}}const u=this.findBestLevel(o,n,i,l,h,d,c);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=s.levels[n],g=s.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:s.loadLevel}getStarvationDelay(){const t=this.hls,e=null==t?void 0:t.media;if(!e)return 1/0;const s=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,i=t.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(t,e,s,i,r,n,a){const{hls:o,lastLoadedFragLevel:l,fragCurrent:d,partCurrent:c}=this;if(!o)return-1;const h=i+r,u=-1===l?o.firstLevel:l,{levels:f,allAudioTracks:g,loadLevel:p,latestLevelDetails:m,config:v}=o;if(1===f.length)return 0;const y=f[u],E=!(null==m||!m.live),T=-1===p||-1===l;let S,A="SDR",_=(null==y?void 0:y.frameRate)||0;const{audioPreference:b,videoPreference:L}=v,R=this.audioTracksByGroup||(this.audioTracksByGroup=Ol(g));let I=-1;if(T){if(-1!==this.firstSelection)return this.firstSelection;const i=this.codecTiers||(this.codecTiers=function(t,e,s,i){return t.slice(s,i+1).reduce((t,s,i)=>{if(!s.codecSet)return t;const r=s.audioGroups;let n=t[s.codecSet];n||(t[s.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,s.bitrate);const a=Math.min(s.height,s.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,s.frameRate),n.minIndex=Math.min(n.minIndex,i),n.maxScore=Math.max(n.maxScore,s.score),n.fragmentError+=s.fragmentError,n.videoRanges[s.videoRange]=(n.videoRanges[s.videoRange]||0)+1,r&&r.forEach(t=>{if(!t)return;const s=e.groups[t];s&&(n.hasDefaultAudio=n.hasDefaultAudio||e.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(s.channels).forEach(t=>{n.channels[t]=(n.channels[t]||0)+s.channels[t]}))}),t},{})}(f,R,e,s)),r=function(t,e,s,i,r){const n=Object.keys(t),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==r?void 0:r.videoCodec,d=a&&2===parseInt(a);let c=!1,h=!1,u=1/0,f=1/0,g=1/0,p=1/0,m=0,v=[];const{preferHDR:y,allowedVideoRanges:E}=Pl(e,r);for(let e=n.length;e--;){const s=t[n[e]];c||(c=s.channels[2]>0),u=Math.min(u,s.minHeight),f=Math.min(f,s.minFramerate),g=Math.min(g,s.minBitrate),E.filter(t=>s.videoRanges[t]>0).length>0&&(h=!0)}u=Vn(u)?u:0,f=Vn(f)?f:0;const T=Math.max(1080,u),S=Math.max(30,f);g=Vn(g)?g:s,s=Math.max(g,s),h||(e=void 0);const A=n.length>1;return{codecSet:n.reduce((e,i)=>{const r=t[i];if(i===e)return e;if(v=h?E.filter(t=>r.videoRanges[t]>0):[],A){if(r.minBitrate>s)return Cl(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),e;if(!r.hasDefaultAudio)return Cl(i,"no renditions with default or auto-select sound found"),e;if(o&&i.indexOf(o.substring(0,4))%5!=0)return Cl(i,`audio codec preference "${o}" not found`),e;if(a&&!d){if(!r.channels[a])return Cl(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!o||d)&&c&&0===r.channels[2])return Cl(i,"no renditions with stereo sound found"),e;if(r.minHeight>T)return Cl(i,`min resolution of ${r.minHeight} > maximum of ${T}`),e;if(r.minFramerate>S)return Cl(i,`min framerate of ${r.minFramerate} > maximum of ${S}`),e;if(!v.some(t=>r.videoRanges[t]>0))return Cl(i,`no variants with VIDEO-RANGE of ${Dl(v)} found`),e;if(l&&i.indexOf(l.substring(0,4))%5!=0)return Cl(i,`video codec preference "${l}" not found`),e;if(r.maxScore<m)return Cl(i,`max score of ${r.maxScore} < selected max of ${m}`),e}return e&&(al(i)>=al(e)||r.fragmentError>t[e].fragmentError)?e:(p=r.minIndex,m=r.maxScore,i)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:p}}(i,A,t,b,L),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:d,preferHDR:c}=r;I=d,S=n,A=c?a[a.length-1]:a[0],_=o,t=Math.max(t,l),this.log(`picked start tier ${Dl(r)}`)}else S=null==y?void 0:y.codecSet,A=null==y?void 0:y.videoRange;const k=c?c.duration:d?d.duration:0,w=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let o=s;o>=e;o--){var D;const e=f[o],d=o>u;if(!e)continue;if(v.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&yl(e,R,A,_,t,b)?(e.supportedPromise=El(e,R,s,this.supportedCache),e.supportedPromise.then(t=>{if(!this.hls)return;e.supportedResult=t;const s=this.hls.levels,i=s.indexOf(e);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${i} ${Dl(t)}`):t.supported?t.decodingInfoResults.some(t=>!1===t.smooth||!1===t.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${i} not smooth or powerEfficient: ${Dl(t)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${i} ${Dl(t)}`),i>-1&&s.length>1&&(this.log(`Removing unsupported level ${i}`),this.hls.removeLevel(i),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(t=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${t}`)})):e.supportedResult=ml}if((S&&e.codecSet!==S||A&&e.videoRange!==A||d&&_>e.frameRate||!d&&_>0&&_<e.frameRate||null!=(D=e.supportedResult)&&null!=(D=D.decodingInfoResults)&&D.some(t=>!1===t.smooth))&&(!T||o!==I)){P.push(o);continue}const g=e.details,m=(c?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||k||1;let y;y=d?a*t:n*t;const L=k&&i>=2*k&&0===r?e.averageBitrate:e.maxBitrate,C=this.getTimeToLoadFrag(w,y,L*m,!g||g.live);if(y>=L&&(o===l||0===e.loadError&&0===e.fragmentError||Ca(e,v.errorPenaltyExpireMs))&&(C<=w||!Vn(C)||E&&!this.bitrateTestDelay||C<h)){const t=this.forcedAutoLevel;return o===p||-1!==t&&t===p||(P.length&&this.trace(`Skipped level(s) ${P.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[P[0]].codecs}" ${f[P[0]].videoRange}; not compatible with "${S}" ${A}`),this.info(`switch candidate:${u}->${o} adjustedbw(${Math.round(y)})-bitrate=${Math.round(y-L)} ttfb:${w.toFixed(1)} avgDuration:${m.toFixed(1)} maxFetchDuration:${h.toFixed(1)} fetchDuration:${C.toFixed(1)} firstSelection:${T} codecSet:${e.codecSet} videoRange:${e.videoRange} hls.loadLevel:${p}`)),T&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){if(!this.hls)return-1;const{maxAutoLevel:e,minAutoLevel:s}=this.hls;return Math.min(Math.max(t,s),e)}},bufferController:class BufferController extends Logger{constructor(t,e){var s;super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=t=>{var e;this.hls&&"open"===(null==(e=this.mediaSource)?void 0:e.readyState)&&this.media&&!this.media.seeking&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:e,mediaSource:s}=this;t&&this.log("Media source opened"),e&&s&&(Cc(s,"sourceopen",this._onMediaSourceOpen),Cc(e,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(zn.MEDIA_ATTACHED,{media:e,mediaSource:s}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){const t=this.media.error,{appendError:e,appendErrors:s}=this;let i=!1;if(!e&&t){i=Math.max(++s.audio,++s.video,++s.audiovideo)>=this.hls.config.appendErrorMaxRetry}const r=new Error(`MediaSource closed while media attached${lu(i,t)}`);this.warn(r),this.hls.trigger(zn.ERROR,Ta({fatal:i},e,{type:Wn.MEDIA_ERROR,details:Yn.MEDIA_SOURCE_REQUIRES_RESET,error:r}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&this.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this._onMediaError=()=>{const{media:t}=this;var e,s;t&&this.log(`Media error (code: ${null==(e=t.error)?void 0:e.code}): ${null==(s=t.error)?void 0:s.message}`)},this.hls=t,this.fragmentTracker=e,this.appendSource=(s=Ba(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null,this._onMediaEmptied=this._onMediaError=null}registerListeners(){const{hls:t}=this;t.on(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.on(zn.BUFFER_RESET,this.onBufferReset,this),t.on(zn.BUFFER_APPENDING,this.onBufferAppending,this),t.on(zn.BUFFER_CODECS,this.onBufferCodecs,this),t.on(zn.BUFFER_EOS,this.onBufferEos,this),t.on(zn.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(zn.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(zn.FRAG_PARSED,this.onFragParsed,this),t.on(zn.FRAG_CHANGED,this.onFragChanged,this),t.on(zn.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.off(zn.BUFFER_RESET,this.onBufferReset,this),t.off(zn.BUFFER_APPENDING,this.onBufferAppending,this),t.off(zn.BUFFER_CODECS,this.onBufferCodecs,this),t.off(zn.BUFFER_EOS,this.onBufferEos,this),t.off(zn.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(zn.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(zn.FRAG_PARSED,this.onFragParsed,this),t.off(zn.FRAG_CHANGED,this.onFragChanged,this),t.off(zn.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const s={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const e=this.isQueued();(t||e)&&this.warn(`Transfering MediaSource with${e?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return i&&!this.sourceBufferCount&&i.mediaSource===e?Ta(s,i.tracks):this.sourceBuffers.forEach(t=>{const[e]=t;e&&(s[e]=Ta({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null}),{media:t,mediaSource:e,tracks:s}}initTracks(){this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(t,e){var s;let i=2;(e.audio&&!e.video||!e.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),null!=(s=this.transferData)&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(t,e){const s=this.media=e.media;this.transferData=this.overrides=void 0;const i=Ba(this.appendSource);if(i){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const r=this.mediaSource=e.mediaSource||new i;if(this.assignMediaSource(r),t)this._objectUrl=s.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{s.removeAttribute("src");const e=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||e&&r instanceof e,au(s),function(t,e){const s=self.document.createElement("source");s.type="video/mp4",s.src=e,t.appendChild(s)}(s,t),s.load()}catch(e){s.src=t}else s.src=t}Dc(s,"emptied",this._onMediaEmptied),Dc(s,"error",this._onMediaError),this.appendSource&&Dc(s,"seeking",this._onStartStreaming)}}assignMediaSource(t){var e,s;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(s=t.constructor)?void 0:s.name}`),Dc(t,"sourceopen",this._onMediaSourceOpen),Dc(t,"sourceended",this._onMediaSourceEnded),Dc(t,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Dc(t,"startstreaming",this._onStartStreaming),Dc(t,"endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const s=this.tracks,i=e.tracks,r=i?Object.keys(i):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${Dl(s,(t,e)=>"initSegment"===t?void 0:e)};\ntransfer tracks: ${Dl(i,(t,e)=>"initSegment"===t?void 0:e)}}`),!$a(i,s)){e.mediaSource=null,e.tracks=void 0;const r=t.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching(zn.MEDIA_DETACHING,{}),this.onMediaAttaching(zn.MEDIA_ATTACHING,e),void(t.currentTime=a))}this.transferData=void 0,r.forEach(t=>{const e=t,s=i[e];if(s){const t=s.buffer;if(t){const i=this.fragmentTracker,r=s.id;if(i.hasFragments(r)||i.hasParts(r)){const s=BufferHelper.getBuffered(t);i.detectEvictedFragments(e,s,r,null,null,!0)}const n=ou(e),a=[e,t];this.sourceBuffers[n]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,s)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const s=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(s?"transferring":"detaching")),s)this.sourceBuffers.forEach(([t])=>{t&&this.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===r.readyState;try{const e=r.sourceBuffers;for(let s=e.length;s--;)t&&e[s].abort(),r.removeSourceBuffer(e[s]);t&&r.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}Cc(r,"sourceopen",this._onMediaSourceOpen),Cc(r,"sourceended",this._onMediaSourceEnded),Cc(r,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Cc(r,"startstreaming",this._onStartStreaming),Cc(r,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(Cc(i,"emptied",this._onMediaEmptied),Cc(i,"error",this._onMediaError),Cc(i,"seeking",this._onStartStreaming),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&au(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const s=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),s)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(e){this.warn(`onBufferReset ${t}`,e)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[ou(t)]=[null,null];const e=this.tracks[t];e&&(this.clearBufferAppendTimeoutId(e),e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new BufferOperationQueue(this.tracks)}onBufferCodecs(t,e){var s;const i=this.tracks,r=Object.keys(e);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in e&&(i.audio||i.video)||i.audiovideo&&("audio"in e||"video"in e),a=!n&&this.sourceBufferCount&&this.media&&r.some(t=>!i[t]);n||a?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`):(r.forEach(t=>{var s,r;const n=e[t],{id:a,codec:o,levelCodec:l,container:d,metadata:c,supplemental:h}=n;let u=i[t];const f=null==(s=this.transferData)||null==(s=s.tracks)?void 0:s[t],g=null!=f&&f.buffer?f:u,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;u||(u=i[t]={buffer:void 0,listeners:[],codec:o,supplemental:h,container:d,levelCodec:l,metadata:c,id:a});const v=cl(p,m),y=null==v?void 0:v.replace(ru,"$1");let E=cl(o,l);const T=null==(r=E)?void 0:r.replace(ru,"$1");E&&v&&y!==T&&("audio"===t.slice(0,5)&&(E=dl(E,this.appendSource)),this.log(`switching codec ${p} to ${E}`),E!==(u.pendingCodec||u.codec)&&(u.pendingCodec=E),u.container=d,this.appendChangeType(t,d,E))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&"main"===(null==(s=e.audio)?void 0:s.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,e)=>{const s=this.tracks[e];return t[e]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},t},{})}appendChangeType(t,e,s){const i=`${e};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const r=this.tracks[t];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${t} sourceBuffer type to ${i}`),n.changeType(i),r.codec=s,r.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(r,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const s=t.start,i=s+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(s,da))?void 0:e.gap))return;const r={label:"block-audio",execute:()=>{var t,e;(this.lastVideoAppendEnd>i||BufferHelper.isBuffered(null==(t=this.tracks.video)?void 0:t.buffer,i)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,da))?void 0:e.gap))&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.append(r,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(t,e){const{tracks:s}=this,{data:i,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:d}=e,c=l.buffering[r],h=pa(a)&&!o&&!a.gap&&!l.partial&&!l.iframe;let u=null,f=!1;const{sn:g,cc:p}=a,m=self.performance.now();c.start=m;const v=a.stats.buffering,y=o?o.stats.buffering:null;0===v.start&&(v.start=m),0===(null==y?void 0:y.start)&&(y.start=m);const E=s.audio;let T=!1;"audio"===r&&"audio/mpeg"===(null==E?void 0:E.container)&&(T=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const S=s.video,A=null==S?void 0:S.buffer;if(A&&"initSegment"!==g&&void 0!==d){const t=null==E?void 0:E.buffer,e=o||a;if("audio"===r&&"main"!==n&&!S.ending&&!S.ended&&t&&BufferHelper.getBuffered(t).length){const t=e.start+.05*e.duration,s=BufferHelper.getBuffered(A),i=this.currentOp("video");s.length||i?!BufferHelper.isBuffered(A,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}else if("video"===r){const t=e.end,s=this.lastVideoAppendEnd-t;this.lastVideoAppendEnd=t,s<0||s>e.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}const _=(o||a).start,b={label:`append-${r}`,execute:()=>{var t;c.executeStart=self.performance.now();const e=null==(t=this.tracks[r])?void 0:t.buffer;e&&(h&&(u=BufferHelper.timeRangesToArray(BufferHelper.getBuffered(e)),f=hu(cu(u,a),a)),T?this.updateTimestampOffset(e,_,.1,r,g,p):void 0!==d&&Vn(d)&&this.updateTimestampOffset(e,d,1e-6,r,g,p)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[r]);const t=self.performance.now();c.executeEnd=c.end=t,0===v.first&&(v.first=t),0===(null==y?void 0:y.first)&&(y.first=t);const e={};if(this.sourceBuffers.forEach(([t,s])=>{t&&(e[t]=BufferHelper.getBuffered(s))}),h){const t=this.getFragmentAppendProgress(a),s=e[r];if(s&&u){const e=cu(BufferHelper.timeRangesToArray(s),a);t.progressed||(t.progressed=e-cu(u,a)>.001);const i=f&&hu(e,a);t.fullyBuffered[r]=(void 0===t.fullyBuffered[r]||t.fullyBuffered[r])&&i}}this.hls.trigger(zn.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:n,timeRanges:e})},onError:t=>{var e;this.clearBufferAppendTimeoutId(this.tracks[r]);const s=t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t;if(s&&!this._quotaEvictionPending[r]){const t=this.getBackBufferEvictionTarget(r,i.byteLength,a.type);if(t>0){this._quotaEvictionPending[r]=!0,this.log(`QuotaExceededError on "${r}" append sn: ${g} - evicting back buffer to ${t.toFixed(3)}s and retrying`);const e=this.getFlushOp(r,0,t),s=this.getClearEvictionPendingOp(r);return void this.insertNext([e,b,s],r)}this.warn(`QuotaExceededError on "${r}" sn: ${g} - no back buffer available to evict`)}h&&(this.getFragmentAppendProgress(a).errored=!0);const d={type:Wn.MEDIA_ERROR,parent:n,details:Yn.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:t,err:t,fatal:!1},c=null==(e=this.media)?void 0:e.error;if(t.name!==nu||0!==this.sourceBufferCount||this.media&&0!==this.pendingTrackCount){var u;s&&(d.details=Yn.BUFFER_FULL_ERROR);const e=++this.appendErrors[r],i=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${e}/${i+1} times to append segment in "${r}" sourceBuffer with error: ${t.message}`),e>=i&&(d.fatal=!s);const n=null==(u=this.mediaSource)?void 0:u.readyState;("ended"===n||"closed"===n||c)&&(this.warn(`MediaSource readyState "${n}" during SourceBuffer${lu(d.fatal,c)}`),d.details=Yn.MEDIA_SOURCE_REQUIRES_RESET)}else d.errorAction=ad(!0);this.appendError=d,this.hls.trigger(zn.ERROR,d),s&&this.hls&&this.trimBuffers(a.start,1)}};this.log(`queuing "${r}" append sn: ${g}${o?" p: "+o.index:""} of ${n} playlist ${a.level} cc: ${p} offset: ${d} bytes: ${i.byteLength}`),this.append(b,r,this.isPending(this.tracks[r]))}getClearEvictionPendingOp(t){return{label:"clear",execute:()=>{this._quotaEvictionPending[t]=!1,this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(t,e,s){return this.log(`queuing "${t}" remove ${e}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,s)},onStart:()=>{},onComplete:()=>{var i;const r=null==(i=this.tracks[t])?void 0:i.buffer;this.log(`Remove request ${e}-${s} from ${t} Source Buffer complete > buffer: ${r?Oc(BufferHelper.getBuffered(r)):"(detached)"}`),this.hls.trigger(zn.BUFFER_FLUSHED,{type:t,start:e,end:s})},onError:i=>{this.warn(`Failed to remove ${e}-${s} from "${t}" SourceBuffer`,i),this.hls.trigger(zn.BUFFER_FLUSHED,{type:t,start:0,end:0,error:i})}}}onBufferFlushing(t,e){const{type:s,startOffset:i,endOffset:r}=e;s&&"audio"!==s||this.unblockAudio(),s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([t])=>{t&&this.append(this.getFlushOp(t,i,r),t)})}onFragParsed(t,e){const{frag:s,part:i,chunkMeta:r}=e,n=[],a=i?i.elementaryStreams:s.elementaryStreams;a[ga]?n.push("audiovideo"):(a[ua]&&n.push("audio"),a[fa]&&n.push("video"));0===n.length&&this.log(`Fragments must have at least one ElementaryStreamType set. ${s.type} ${s.level} ${i?`part: ${i.index} of `:""}sn: ${s.sn}`),this.blockBuffers(()=>{const t=self.performance.now();s.stats.buffering.end=t,i&&(i.stats.buffering.end=t);const e=i?i.stats:s.stats;this.checkAppendProgress(s,i,r,n),this.hls&&(this.hls.trigger(zn.FRAG_BUFFERED,{frag:s,part:i,stats:e,id:s.type,chunkMeta:r}),!i&&s.gap&&e.retry&&this.log(`Nothing buffered for ${s.type} level: ${s.level} sn: ${s.sn} retries ${e.retry}`))},n).catch(t=>{this.warn(`Fragment buffered callback ${t.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){var s,i;const r=null==(s=this.hls)?void 0:s.config;if(!r)return;const{backBufferLength:n,frontBufferFlushThreshold:a}=r;this.trimBuffers(a,n,e.frag,e.previousFrag);const o=e.frag.elementaryStreams,{appendErrors:l}=this,d=null==(i=this.appendError)?void 0:i.sourceBufferName;Object.keys(o).forEach(t=>{o[t]&&(l[t]=0,t===d&&(this.appendError=void 0),"audio"===t||"video"===t?(l.audiovideo=0,"audiovideo"===d&&(this.appendError=void 0)):(l.audio=0,l.video=0,"audiovideo"!==d&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const e=this.tracks[t];if(e)return!e.ended||e.ending}return!1})}onBufferEos(t,e){var s;this.sourceBuffers.forEach(([t])=>{if(t){const s=this.tracks[t];e.type&&e.type!==t||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${t} buffer reached EOS`)))}});const i=!1!==(null==(s=this.overrides)?void 0:s.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)})?(this.unblockAudio(),i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:t}=this;"open"===(null==t?void 0:t.readyState)?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(zn.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})):(this.tracksEnded(),this.hls.trigger(zn.BUFFERED_TO_END,void 0))):"video"===e.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(null!==t){const e=this.tracks[t];e&&(e.ending=!1)}})}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,e){if(e.details===Yn.BUFFER_APPEND_ERROR&&e.frag){var s;const t=null==(s=e.errorAction)?void 0:s.nextAutoLevel;Vn(t)&&t!==e.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(t,e,s){const{media:i}=this;return i?this.fragmentTracker.getBackBufferEvictionEnd(i.currentTime,s,e):0}getFragmentAppendProgress(t){var e;const s=du(t);let i=this.fragmentAppendProgress[s];return(null==(e=i)?void 0:e.stats)!==t.stats&&(i={stats:t.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[s]=i),i}checkAppendProgress(t,e,s,i){if(e||!pa(t)||t.gap||s.iframe||s.partial)return;const r=du(t),n=this.fragmentAppendProgress[r];delete this.fragmentAppendProgress[r];const a=t.stats.buffering;if(a.start&&!a.first)return;const o=(null==n?void 0:n.stats)===t.stats?n:void 0;if(null!=o&&o.errored)return;const l=i.length>0&&i.every(t=>!0===(null==o?void 0:o.fullyBuffered[t]));if(null!=o&&o.progressed||l)return void delete this.appendsWithoutProgress[r];if(!o&&0===i.length)return;const d=(this.appendsWithoutProgress[r]||0)+1,c=this.hls;d>=c.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[r]:this.appendsWithoutProgress[r]=d,this.warn(`Fragment ${t.sn} of ${t.type} playlist ${t.level} appended ${d} time${d>1?"s":""} without buffered range growth`),c.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:t,chunkMeta:s,parent:t.type,appendsWithoutProgress:d,error:new Error(`Fragment append did not increase buffered coverage (${d})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(t,e,s,i){const{hls:r,details:n,media:a}=this;if(!a||null===n)return;if(!this.sourceBufferCount)return;const o=r.config,l=a.currentTime,d=n.levelTargetDuration;e=n.live&&null!==o.liveBackBufferLength?o.liveBackBufferLength:e;let c=-1/0;if(Vn(e)&&e>=0){const t=Math.max(e,d);c=Math.floor(l/d)*d-t}if(s){const t=this.getLoopBackBufferFlushEnd(s,null!=i?i:null);t>0&&(c=Math.max(c,t))}if(c>0&&this.flushBackBuffer(l,d,c),Vn(t)&&t>0){const e=Math.max(o.maxBufferLength,t),s=Math.max(e,d),i=Math.floor(l/d)*d+s;this.flushFrontBuffer(l,d,i)}}getLoopBackBufferFlushEnd(t,e){var s;const{media:i}=this;if(!1===(null==(s=this.hls)?void 0:s.config.loopBackBufferFlush)||null==i||!i.loop||!e||t.level<=e.level)return 0;const{video:r,audiovideo:n}=t.elementaryStreams;if(null!=r&&r.partial||null!=n&&n.partial)return 0;const a=this.getEarliestElementaryStreamStart(t)-.25;return a<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${t.level}, range [0-${a.toFixed(3)}]`),a)}getEarliestElementaryStreamStart(t){const{audio:e,video:s,audiovideo:i}=t.elementaryStreams;let r=t.start;return i?r=Math.min(r,i.startDTS):(e&&(r=Math.min(r,e.startDTS)),s&&(r=Math.min(r,s.startDTS))),r}flushBackBuffer(t,e,s){this.sourceBuffers.forEach(([t,e])=>{if(e){const a=BufferHelper.getBuffered(e);if(a.length>0&&s>a.start(0)){var i,r,n;this.hls.trigger(zn.BACK_BUFFER_REACHED,{bufferEnd:s});const e=this.tracks[t];if(null!=(i=this.details)&&i.live)this.hls.trigger(zn.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(null!=e&&e.ended&&(null==(r=this.media)||!r.loop||!1===(null==(n=this.hls)?void 0:n.config.loopBackBufferFlush)))return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(zn.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:t})}}})}flushFrontBuffer(t,e,s){this.sourceBuffers.forEach(([e,i])=>{if(i){const r=BufferHelper.getBuffered(i),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(s>a||t>=a&&t<=o)return;this.hls.trigger(zn.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:e})}})}getDurationAndRange(){var t;const{details:e,mediaSource:s}=this;if(!e||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const i=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&s.setLiveSeekableRange){const t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,i)}}return{duration:1/0}}const r=null==(t=this.overrides)?void 0:t.duration;if(r)return Vn(r)?{duration:r}:null;const n=this.media.duration;return i>(Vn(s.duration)?s.duration:0)&&i>n||!Vn(n)?{duration:i}:null}updateMediaSource({duration:t,start:e,end:s}){const i=this.mediaSource;i&&this.media&&"open"===i.readyState&&(i.duration!==t&&(Vn(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),i.duration=t),void 0!==e&&void 0!==s&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${e}-${s}.`),i.setLiveSeekableRange(e,s)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${Dl(s)}`),this.tracksReady){var i;const t=null==(i=this.transferData)?void 0:i.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,s])=>{if(e){const i=this.tracks[e];t[e]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(zn.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in t){const n=r,a=t[n];if(this.isPending(a)){const t=this.getTrackCodec(a,n),r=`${a.container};codecs=${t}`;a.codec=t,this.log(`creating sourceBuffer(${r})${this.currentOp(n)?" Queued":""} ${Dl(a)}`);try{const t=s.addSourceBuffer(r),i=ou(n),o=[n,t];e[i]=o,a.buffer=t}catch(t){var i;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(n),null==(i=this.operationQueue)||i.removeBlockers(),delete this.tracks[n],void this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:n,mimeType:r,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}clearBufferAppendTimeoutId(t){t&&(self.clearTimeout(t.bufferAppendTimeoutId),t.bufferAppendTimeoutId=void 0)}getTrackCodec(t,e){const s=t.supplemental;let i=t.codec;s&&("video"===e||"audiovideo"===e)&&sl(s,"video")&&(i=function(t,e){const s=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)el(e[t],"video")||s.push(e[t])}return e&&s.push(e),s.join(",")}(i,s));const r=cl(i,t.levelCodec);return r?"audio"===e.slice(0,5)?dl(r,this.appendSource):r:""}trackSourceBuffer(t,e){const s=e.buffer;if(!s)return;const i=this.getTrackCodec(e,t);this.tracks[t]={buffer:s,codec:i,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(t,e)=>{const s=e.removedRanges;null!=s&&s.length&&(this.log(`${t} buffer removed ${Oc(s)}`),this.hls.trigger(zn.BUFFER_FLUSHED,{type:t,start:s.start(0),end:s.end(s.length-1)}))})}get mediaSrc(){var t,e;const s=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==s?void 0:s.src}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e,s;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const i=this.currentOp(t);if(!i)return;i.onComplete();if(null==(s=this.tracks[t])||null==(s=s.buffer)?void 0:s.updating)return this.log(`${t} SourceBuffer updating on "updateend"`),void this.blockUntilOpen(()=>{this.shiftAndExecuteNext(t)});this.shiftAndExecuteNext(t)}onSBUpdateError(t,e){var s;const i=null==(s=this.mediaSource)?void 0:s.readyState,r=new Error(`${t} SourceBuffer error. MediaSource readyState: ${i}`);this.error(`${r.message}`,e),this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:r,fatal:!1});const n=this.currentOp(t);n&&n.onError(r)}updateTimestampOffset(t,e,s,i,r,n){const a=e-t.timestampOffset;Math.abs(a)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${e} (sn: ${r} cc: ${n})`),t.timestampOffset=e)}removeExecutor(t,e,s){const{media:i,mediaSource:r}=this,n=this.tracks[t],a=null==n?void 0:n.buffer;if(!i||!r||!a)throw new Error(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`);const o=Vn(i.duration)?i.duration:1/0,l=Vn(r.duration)?r.duration:1/0,d=Math.max(0,e);var c;if(d>=l)return null==(c=this.currentOp(t))||c.onComplete(),void this.shiftAndExecuteNext(t);const h=Math.min(s,o,l);if(!(h>d)||n.ending&&!n.ended)throw new Error(`Cannot remove ${h<=d?`invalid range (${d} >= ${h}) `:""}from the ${t} SourceBuffer${n.ending?" while track ending":""}`);n.ended=!1,this.log(`Removing [${d},${h}] from the ${t} SourceBuffer`),a.remove(d,h)}appendExecutor(t,e){const s=this.tracks[e],i=null==s?void 0:s.buffer;if(!i)throw new HlsJsTrackRemovedError(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);if(s.ending=!1,s.ended=!1,this.hls.config.appendTimeout!==1/0){const t=this.calculateAppendTimeoutTime(i);s.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(e,i,t),t)}i.appendBuffer(t)}appendTimeoutHandler(t,e,s){this.log(`Received timeout after ${s}ms for append on ${t} source buffer. Aborting and triggering error.`);try{e.abort()}catch(e){this.log(`Failed to abort append on ${t} source buffer after timeout.`)}const i=this.currentOp(t);i&&i.onError(new Error(`${t}-append-timeout`))}calculateAppendTimeoutTime(t){let e=10;this.details&&(e=this.details.levelTargetDuration);let s=2*e*1e3;if(null===this.media)return s;const i=BufferHelper.bufferInfo(t,this.media.currentTime,0);return i.len?(s=Math.max(1e3*i.len,s),Math.max(this.hls.config.appendTimeout,s)):s}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}isAudioBlocked(){var t;return"block-audio"===(null==(t=this.currentOp("audio"))?void 0:t.label)}isAudioBlocking(){return!!this.operationQueue&&this.operationQueue.audioBlocking()}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:s}=this,i=2===e.length&&this.isAudioBlocking()?[this.appendBlocker("video")]:e.map(t=>this.appendBlocker(t));return Promise.all(i).then(e=>{s===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(t=>{var e;const s=null==(e=this.tracks[t])?void 0:e.buffer;!s||s.updating||"audio"===t&&this.isAudioBlocked()||this.shiftAndExecuteNext(t)})}append(t,e,s){this.operationQueue&&this.operationQueue.append(t,e,s)}insertNext(t,e){this.operationQueue&&this.operationQueue.insertNext(t,e)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[e])=>t+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,e,s){const i=this.tracks[t];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,t);i.listeners.push({event:e,listener:n}),Dc(r,e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const s=e.buffer;s&&(e.listeners.forEach(t=>{Cc(s,t.event,t.listener)}),e.listeners.length=0)}},capLevelController:CapLevelController,errorController:class ErrorController extends Logger{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(zn.ERROR,this.onError,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(zn.ERROR,this.onError,this),t.off(zn.ERROR,this.onErrorOut,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===da?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,s=e.currentLevel;return null!=(t=e.loadLevelObj)&&t.details||-1===s?e.loadLevel:s}variantHasKey(t,e){if(t){var s;if(null!=(s=t.details)&&s.hasKey(e))return!0;const i=t.audioGroups;if(i){return this.hls.allAudioTracks.filter(t=>i.indexOf(t.groupId)>=0).some(t=>{var s;return null==(s=t.details)?void 0:s.hasKey(e)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var s;if(e.fatal)return;const i=this.hls,r=e.context;switch(e.details){case Yn.FRAG_LOAD_ERROR:case Yn.FRAG_LOAD_TIMEOUT:case Yn.KEY_LOAD_ERROR:case Yn.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case Yn.FRAG_PARSING_ERROR:if(null!=(s=e.frag)&&s.gap)return void(e.errorAction=ad());case Yn.FRAG_GAP:case Yn.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=zl);case Yn.PLAYLIST_UNCHANGED_ERROR:case Yn.LEVEL_EMPTY_ERROR:case Yn.LEVEL_PARSING_ERROR:{var n;const t=e.parent===da?e.level:i.loadLevel;e.details===Yn.LEVEL_EMPTY_ERROR&&null!=(n=e.context)&&null!=(n=n.levelDetails)&&n.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case Yn.LEVEL_LOAD_ERROR:case Yn.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.level)));case Yn.AUDIO_TRACK_LOAD_ERROR:case Yn.AUDIO_TRACK_LOAD_TIMEOUT:case Yn.SUBTITLE_LOAD_ERROR:case Yn.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const t=i.loadLevelObj;if(t&&(r.type===sa&&t.hasAudioGroup(r.groupId)||r.type===ia&&t.hasSubtitleGroup(r.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,i.loadLevel),e.errorAction.action=zl,void(e.errorAction.flags=Jl)}return;case Yn.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:zl,flags:td});case Yn.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Yn.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Yn.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:zl,flags:ed});case Yn.BUFFER_ADD_CODEC_ERROR:case Yn.REMUX_ALLOC_ERROR:case Yn.BUFFER_APPEND_ERROR:return void(e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)));case Yn.MEDIA_SOURCE_REQUIRES_RESET:return e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)),void(e.errorAction.flags|=id|sd);case Yn.INTERNAL_EXCEPTION:case Yn.BUFFER_APPENDING_ERROR:case Yn.BUFFER_APPEND_NO_PROGRESS:case Yn.BUFFER_FULL_ERROR:case Yn.LEVEL_SWITCH_ERROR:case Yn.BUFFER_STALLED_ERROR:case Yn.BUFFER_SEEK_OVER_HOLE:case Yn.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=ad())}e.type===Wn.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=ad())}getPlaylistRetryOrSwitchAction(t,e){const s=Ia(this.hls.config.playlistLoadPolicy,t),i=this.playlistError++;if(Pa(s,i,ba(t),t.response))return{action:Xl,flags:Zl,retryConfig:s,retryCount:i};const r=this.getLevelSwitchAction(t,e);return s&&(r.retryConfig=s,r.retryCount=i),r}getFragRetryOrSwitchAction(t){const e=this.hls,s=this.getVariantLevelIndex(t.frag),i=e.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=e.config,a=Ia(La(t)?n:r,t),o=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(i&&(t.details!==Yn.FRAG_GAP&&i.fragmentError++,!Ra(t))){if(Pa(a,o,ba(t),t.response))return{action:Xl,flags:Zl,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(t,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const s=this.hls;null==e&&(e=s.loadLevel);const i=this.hls.levels[e];if(i){var r,n;const e=t.details;i.loadError++,i.loadErrorTime=self.performance.now(),e===Yn.BUFFER_APPEND_ERROR&&i.fragmentError++;let l=-1;const{levels:d,loadLevel:c,minAutoLevel:h,maxAutoLevel:u}=s;s.autoLevelEnabled||s.config.preserveManualLevelOnError||(s.loadLevel=-1);const f=null==(r=t.frag)?void 0:r.type,g=(f===ca&&e===Yn.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&rd(t))&&d.some(({audioCodec:t})=>i.audioCodec!==t),p="video"===t.sourceBufferName&&rd(t)&&d.some(({codecSet:t,audioCodec:e})=>i.codecSet!==t&&i.audioCodec===e),{type:m,groupId:v}=null!=(n=t.context)?n:{};for(let r=d.length;r--;){const n=(r+c)%d.length;if(n!==c&&n>=h&&n<=u&&(0===d[n].loadError||Ca(d[n],s.config.errorPenaltyExpireMs))){var a,o;const s=d[n];if(e===Yn.FRAG_GAP&&f===da&&t.frag){const e=d[n].details;if(e){const s=Kl(t.frag,e.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(m===sa&&s.hasAudioGroup(v)||m===ia&&s.hasSubtitleGroup(v))continue;if(f===ca&&null!=(a=i.audioGroups)&&a.some(t=>s.hasAudioGroup(t))||f===ha&&null!=(o=i.subtitleGroups)&&o.some(t=>s.hasSubtitleGroup(t))||g&&i.audioCodec===s.audioCodec||p&&i.codecSet===s.codecSet||!g&&i.audioCodec!==s.audioCodec)continue}l=n;break}}if(l>-1&&s.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:zl,flags:Zl,nextAutoLevel:l}}return{action:zl,flags:Jl}}onErrorOut(t,e){var s,i;switch(null==(s=e.errorAction)?void 0:s.action){case Yl:break;case zl:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===Yn.FRAG_GAP||e.details===Yn.PLAYLIST_UNCHANGED_ERROR||nd(e)||(e.fatal=!0)}((null==(i=e.errorAction)?void 0:i.flags)||0)&id&&this.hls.recoverMediaError(),e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,s=t.errorAction;if(!s)return;let i=s.nextAutoLevel;if(s.flags===Zl)this.switchLevel(t,i);else if(s.flags&sd){const t=this.hls.levels;for(let e=t.length;e--;)"SDR"!==t[e].videoRange?(t[e].fragmentError++,t[e].loadError++):void 0===i&&(i=e)}else if(s.flags&td){const i=this.getVariantLevelIndex(t.frag),r=e.levels[i],n=null==r?void 0:r.attrs["HDCP-LEVEL"];s.hdcpLevel=n;const a="NONE"===n;n&&!a?(e.maxHdcpLevel=_l[_l.indexOf(n)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)):(a&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),s.flags|=ed)}if(s.flags&ed){const e=t.decryptdata;if(e){const i=this.hls.levels,a=i.length;for(let s=a;s--;){var r,n;if(this.variantHasKey(i[s],e))this.log(`Banned key found in level ${s} (${i[s].bitrate}bps) or audio group "${null==(r=i[s].audioGroups)?void 0:r.join(",")}" (${null==(n=t.frag)?void 0:n.type} fragment) ${oo(e.keyId||[])}`),i[s].fragmentError++,i[s].loadError++,this.log(`Removing level ${s} with key error (${t.error})`),this.hls.removeLevel(s)}const o=t.frag;if(this.hls.levels.length<a)s.resolved=!0;else if(o&&o.type!==da){const t=o.decryptdata;t&&!e.matches(t)&&(s.resolved=!0)}}}s.resolved||this.switchLevel(t,i)}switchLevel(t,e){if(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,t.details===Yn.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=gl(t.mimeType),s=this.hls.levels;for(let i=s.length;i--;)s[i][`${t.sourceBufferName}Codec`]===e&&(this.log(`Removing level ${i} for ${t.details} ("${e}" not supported)`),this.hls.removeLevel(i))}}},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(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(zn.MEDIA_DETACHING,this.onMediaDetaching,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)}}onMediaDetaching(){this.media=null}checkFPS(t,e,s){const i=performance.now();if(e){if(this.lastTime){const t=i-this.lastTime,r=s-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*r/t,o=this.hls;if(o.trigger(zn.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:s}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(zn.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=i,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)}},id3TrackController:class ID3TrackController{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(zn.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(zn.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(zn.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(zn.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(zn.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(zn.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(zn.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){this.media=e.media}onMediaAttached(){var t;const e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null;!!e.transferMedia||(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){return Lg(t,"metadata","id3","","hidden")}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Og();if(n)for(let t=0;t<r.length;t++){const e=r[t].type;if(e===lh.emsg&&!s||!i)continue;const a=io(r[t].data),o=r[t].pts;let l=o+r[t].duration;l>xg&&(l=xg);l-o<=0&&(l=o+.25);for(let t=0;t<a.length;t++){const s=a[t];if(!ro(s)){this.updateId3CueEnds(o,e);const t=Mg(n,o,l,s,e);t&&this.id3Track.track.addCue(t)}}}}updateId3CueEnds(t,e){var s;const i=null==(s=this.id3Track)?void 0:s.track.cues;if(i)for(let s=i.length;s--;){const r=i[s];r.type===e&&r.startTime<t&&r.endTime===xg&&(r.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let t;t="audio"===i?t=>t.type===lh.audioId3&&o:"video"===i?t=>t.type===lh.emsg&&a:t=>t.type===lh.audioId3&&o||t.type===lh.emsg&&a,kg(r.track,e,s,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=Og();if(s&&i&&!n){const{fragmentStart:e,fragmentEnd:i}=t;let r=this.assetCue;r?(r.startTime=e,r.endTime=i):a&&(r=this.assetCue=Mg(a,e,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=t,d=Object.keys(l);let c=this.dateRangeCuesAppended;var h;if(o&&e)if(null!=(h=o.track.cues)&&h.length){const t=Object.keys(c).filter(t=>-1===d.indexOf(t));for(let e=t.length;e--;){var u;const s=t[e],i=null==(u=c[s])?void 0:u.cues;delete c[s],i&&Object.keys(i).forEach(t=>{const e=i[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{o.track.removeCue(e)}catch(t){}}})}}else c=this.dateRangeCuesAppended={};const f=t.fragments[t.fragments.length-1];if(0!==d.length&&Vn(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<d.length;t++){const e=d[t],s=l[e],i=s.startTime,r=c[e],o=(null==r?void 0:r.cues)||{};let h=(null==r?void 0:r.durationKnown)||!1,u=xg;const{duration:f,endDate:g}=s;if(g&&null!==f)u=i+f,h=!0;else if(s.endOnNext&&!h){const t=d.reduce((t,e)=>{if(e!==s.id){const i=l[e];if(i.class===s.class&&i.startDate>s.startDate&&(!t||s.startDate<t.startDate))return i}return t},null);t&&(u=t.startTime,h=!0)}const p=Object.keys(s.attr);for(let t=0;t<p.length;t++){const l=p[t];if(!kd(l))continue;const d=o[l];if(d)!h||null!=r&&r.durationKnown?Math.abs(d.startTime-i)>.01&&(d.startTime=i,d.endTime=u):d.endTime=u;else if(a){let t=s.attr[l];wd(l)&&(t=lo(t));const r=Mg(a,i,u,{key:l,data:t},lh.dateRange);r&&(r.id=e,this.id3Track.track.addCue(r),o[l]=r,n&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||r.addEventListener("enter",this.onEventCueEnter)))}}c[e]={cues:o,dateRange:s,durationKnown:h}}}}},gapController:class GapController extends TaskLoop{constructor(t,e){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(zn.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(zn.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(zn.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;const s=this.media=e.media;Dc(s,"playing",this.onMediaPlaying),Dc(s,"waiting",this.onMediaWaiting),Dc(s,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:s}=this;s&&(Cc(s,"playing",this.onMediaPlaying),Cc(s,"waiting",this.onMediaWaiting),Cc(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var t;const e=(null==(t=this.hls)?void 0:t.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,e):e}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const e=this.getCurrentTime();this.media.currentTime<e||(this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e)}poll(t,e){var s,i;const r=null==(s=this.hls)?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,d=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,t!==e)return e&&(this.ended=0),this.moved=!0,a||(this.skipRetry=this.nudgeRetry=0,r.nudgeOnVideoHole&&!d&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(l||o)return void(o&&this.stallResolved(t));if(d)return this.skipRetry=this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(zn.MEDIA_ENDED,{stalled:!1})));if(!BufferHelper.getBuffered(n).length)return void(this.skipRetry=this.nudgeRetry=0);const c=BufferHelper.bufferInfo(n,t,0),h=this.fragmentTracker;h&&this.hls&&Cg(c,t,h,this.hls);const u=c.nextStart||0;if(a&&h&&this.hls){const e=wg(this.hls.inFlightFragments,t),s=c.len>2,i=!u||e||u-t>2&&!h.getPartialFragment(t);if(s||i)return;this.moved=!1}const f=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&h){if(!(c.len>0)&&!u)return;const e=Math.max(u,c.start||0)-t,s=!(null==f||!f.live)?2*f.targetduration:2,i=Dg(t,h);if(e>0&&(e<=s||i))return void(n.paused||this._trySkipBufferHole(i))}const g=r.detectStallWithCurrentTimeMs,p=self.performance.now(),m=this.waiting;let v=this.stalled;if(null===v){if(!(m>0&&p-m<g))return void(this.stalled=p);v=this.stalled=m}const y=p-v;if(!a&&(y>=g||m&&this.moved)&&this.hls){var E;if("ended"===(null==(E=this.mediaSource)?void 0:E.readyState)&&(null==f||!f.live)&&Math.abs(t-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(zn.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return;if(n.currentTime!==t){const e=t;return t=n.currentTime,this.moved=!0,void this.log(`currentTime changed ${e} > ${t}`)}}const T=BufferHelper.bufferInfo(n,t,r.maxBufferHole);this._tryFixBufferStall(T,y,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(zn.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(s=this.buffered.audio)&&s.length&&i&&i.length>1&&t>i.end(0)){const s=BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio),t,0);if(s.len>1&&e>=s.start){const s=BufferHelper.timeRangesToArray(i),r=BufferHelper.bufferedInfo(s,e,0).bufferedIndex;if(r>-1&&r<s.length-1){const e=BufferHelper.bufferedInfo(s,t,0).bufferedIndex,i=s[r].end,n=s[r+1].start;if((-1===e||e>r)&&n-i<1&&t-i<2){const s=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${i} -> ${n} buffered index: ${e}`);this.warn(s.message),this.media.currentTime+=1e-6;let r=Dg(t,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);const a=BufferHelper.bufferInfo(this.media,t,0);this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(t,e,s){var i,r;const{fragmentTracker:n,media:a}=this,o=null==(i=this.hls)?void 0:i.config;if(!a||!n||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,d=Dg(s,n);if(d||null!=l&&l.live&&s<l.fragmentStart){if(this._trySkipBufferHole(d)||!this.media)return}const c=t.buffered,h=this.adjacentTraversal(t,s);(c&&c.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-s<o.maxBufferHole||h))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const s=this.fragmentTracker,i=t.nextStart;if(s&&i){const t=s.getFragAtPos(e,da),r=s.getFragAtPos(i,da);if(t&&r)return r.sn-t.sn<2}return!1}_reportStall(t){const{hls:e,media:s,stallReported:i,stalled:r}=this;if(!i&&null!==r&&s&&e){this.stallReported=!0;const i=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${Dl(t)})`);this.warn(i.message),e.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:t.len,bufferInfo:t,stalled:{start:r}})}}_trySkipBufferHole(t){const{fragmentTracker:e,media:s,hls:i}=this,r=null==i?void 0:i.config;if(!s||!e||!r)return 0;const n=s.currentTime,a=BufferHelper.bufferInfo(s,n,0);Cg(a,n,e,i);const o=n<a.start?a.start:a.nextStart;if(o){const d=a.len<=r.maxBufferHole,c=a.len>0&&a.len<1&&s.readyState<3,h=o-n;if(h>0&&(d||c)){if(h>r.maxBufferHole){let s=!1;if(0===n){const t=e.getAppendedFrag(0,da);t&&o<t.end&&(s=!0)}if(!s&&t){var l;if(null==(l=i.loadLevelObj)||!l.details)return 0;if(wg(i.inFlightFragments,o))return 0;let s=!1,r=t.end;for(;r<o;){const t=Dg(r,e),i=t?t.duration:0;if(!(i>0)){s=!0;break}r+=i}if(s)return 0}}const{nudgeMaxRetry:d,skipBufferHolePadding:c}=r,u=++this.skipRetry>d,f=Math.max(o,n)+c;if(u||(this.warn(`skipping hole, adjusting currentTime from ${n} to ${f}`),this.moved=!0,s.currentTime=f),null==t||!t.gap||u){const e=new Error(u?`Playhead still not moving after seeking over buffer hole from ${n} to ${f} after ${r.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${n} to ${f}`),s={type:Wn.MEDIA_ERROR,details:Yn.BUFFER_SEEK_OVER_HOLE,fatal:u,error:e,reason:e.message,buffer:a.len,bufferInfo:a};t&&("fragment"in t?s.part=t:s.frag=t),i.trigger(zn.ERROR,s)}return f}}return 0}_tryNudgeBuffer(t){const{hls:e,media:s,nudgeRetry:i}=this,r=null==e?void 0:e.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const a=n+(i+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),s.currentTime=a,e.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:t.len,bufferInfo:t})}else{const s=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(s.message),e.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.BUFFER_STALLED_ERROR,error:s,fatal:!0,buffer:t.len,bufferInfo:t})}}},latencyController:class LatencyController{constructor(t){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var t;const{media:e}=this,s=this.levelDetails;if(!e||!s||!this.hls)return;this.currentTime=e.currentTime;const i=this.hls.config,r=this.computeLatency();if(null===r)return;this._latency=r;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=i;if(!n||1===a||!s.live)return;const o=this.targetLatency;if(null===o)return;const l=r-o,d=l<Math.min(this.maxLatency,o+s.targetduration),c=Wc(i)&&!(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)||!t.event);if(d&&l>.05&&this.forwardBufferLength>1&&!c){const t=Math.min(2,Math.max(1,a)),s=Math.round(2/(1+Math.exp(-.75*l-this.edgeStalled))*20)/20,i=Math.min(t,Math.max(1,s));this.changeMediaPlaybackRate(e,i)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=t,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var t;const e=null==(t=this.hls)?void 0:t.config;if(!e)return 0;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const s=this.levelDetails;return s?e.liveMaxLatencyDurationCount*s.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||!this.hls)return null;const e=this.hls.config,{holdBack:s,partHoldBack:i,targetduration:r}=t,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=e,l=this.hls.userConfig;let d=o&&i||s;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===d)&&(d=void 0!==n?n:a*r);const c=r;return d+Math.min(this.stallCount*e.liveSyncOnStallIncrease,c)}set targetLatency(t){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=t,this._targetLatencyUpdated=!0)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e||!this.hls)return null;const s=this.levelDetails;if(null===s)return null;const i=s.edge,r=t-e-this.edgeStalled,n=i-s.totalduration,a=i-(this.hls.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(null===t||!this.hls)return 0;const e=3*(this.hls.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t}=this,e=this.levelDetails;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.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(zn.ERROR,this.onError,this),t.on(zn.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(zn.ERROR,this.onError,this),t.off(zn.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(t,e){var s;const i=this.hls,r=this.media||e.event.appendInPlace&&(null==i||null==(s=i.interstitialsManager)?void 0:s.playerQueue.reduce((t,e)=>t||e.media,null));i&&r&&r.playbackRate>1&&r.playbackRate<=i.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(r,1)}onError(t,e){var s;e.details===Yn.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(s=this.levelDetails)&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var s,i;t.playbackRate!==e&&(null==(s=this.hls)||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(i=this.targetLatency)?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}},{cueHandler:yp,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",ha),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.on(zn.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(zn.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(zn.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(zn.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(zn.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.off(zn.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(zn.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(zn.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(zn.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(zn.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,e){this.stopLoad(),this.state=xc,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,e){this.tracksBuffered=[],super.onMediaDetaching(t,e)}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:s,part:i,success:r}=e;if(!r)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a;const o=(i||s).start;for(let t=0;t<n.length;t++)if(o>=n[t].start&&o<=n[t].end){a=n[t];break}const l=o+(i||s).duration;if(a?a.end=l:(a={start:o,end:l},n.push(a)),!i||l>=s.end){const t=this.fragmentTracker.fragBuffered(s);i&&t&&(t.range.subs={time:[{startPTS:s.start,endPTS:l}],partial:!0}),pa(s)&&!this.fragContextChanged(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i),this.media&&this.tickImmediate()}}onBufferFlushing(t,e){const{startOffset:s,endOffset:i}=e;if(0===s&&i!==Number.POSITIVE_INFINITY){const t=i-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach(e=>{if(e)for(let s=0;s<e.length;)if(e[s].end<=t)e.shift();else{if(!(e[s].start<t))break;e[s].start=t,s++}}),this.fragmentTracker.removeFragmentsInRange(s,t,ha)}}onError(t,e){const s=e.frag;(null==s?void 0:s.type)===ha&&(e.details===Yn.FRAG_GAP&&this.fragmentTracker.addAsGap(s),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Mc&&(this.state=xc))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&su(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,ha),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var s;if(this.currentTrackId=e.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const i=this.levels[this.currentTrackId];null!=i&&i.details?(this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==Mc&&this.setInterval(500)):this.mediaBuffer=null}onSubtitleTrackLoaded(t,e){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:a}=e;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;const l=this.mainDetails;let d=0;if(n.live||null!=(s=o.details)&&s.live){if(n.deltaUpdateFailed)return;if(!l)return void(this.startFragRequested=!1);var c;if(o.details)d=this.alignPlaylists(n,o.details,null==(c=this.levelLastLoaded)?void 0:c.details);n.alignedSliding||(Pc(l,n,this),d=n.fragmentStart)}o.details=n,this.levelLastLoaded=o,l&&!this.startFragRequested&&this.setStartPosition(l,d),a===i&&(this.hls.trigger(zn.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:e.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(t){const{frag:e,part:s,payload:i}=t;s&&null!=i&&i.byteLength&&this.shouldDecrypt(e)&&this.decryptPayload(i,e,s)}_handleFragmentLoadComplete(t){const{frag:e,payload:s}=t;!this.fragContextChanged(e)&&null!=s&&s.byteLength&&this.shouldDecrypt(e)&&this.decryptPayload(s,e,null)}shouldDecrypt(t){const e=t.decryptdata;return!!(null!=e&&e.key&&e.iv&&Cd(e.method))}decryptPayload(t,e,s){const i=e.decryptdata,r=performance.now();this.decrypter.decrypt(new Uint8Array(t),i.key.buffer,i.iv.buffer,Od(i.method)).then(t=>{this.fragContextChanged(e)||this.hls.trigger(zn.FRAG_DECRYPTED,{frag:e,part:s,payload:t,stats:{tstart:r,tdecrypt:performance.now()}})}).catch(t=>{this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e,part:s}),s||(this.warn(`${t.name}: ${t.message}`),this.state=xc)})}doTick(){if(this.state===xc&&this.levels){var t;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;const{currentTrackId:s,levels:i}=this,r=i[s],n=null==r?void 0:r.details;if(!n||this.waitForLive(r)||this.waitForCdnTuneIn(n))return void(this.startFragRequested=!1);const{config:a}=this,o=this.playhead,l=BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],o,a.maxBufferHole),{end:d,len:c}=l;if(c>Math.max(this.hls.maxBufferLength+n.levelTargetDuration,(null==(t=this.hls.mainForwardBufferInfo)?void 0:t.len)||0)||c&&!this.buffering)return;let h=this.getNextFragment(d,n);if(!h)return;if(pa(h)){var e;const t=h.sn-n.startSN,s=n.fragments[t-1];h.cc!==(null==s?void 0:s.cc)||null!=(e=n.partList)&&e.length||this.fragmentTracker.getState(s)!==od||(h=s)}this.loadFragment(h,r,d)}}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);i!==od&&i!==dd||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.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1,e=!1;if(this.currentTrack){var s;const i=null==(s=this.currentTrack.trackNode)?void 0:s.track.mode;"showing"===i?(t=this.trackId,e=!0):"hidden"===i&&(t=this.trackId)}if(!e)for(let e=0;e<this.tracksInGroup.length;e++){var i;const s=null==(i=this.tracksInGroup[e].trackNode)?void 0:i.track.mode;if("showing"===s){t=e;break}t<0&&"hidden"===s&&(t=e)}var r;t>-1&&(this._subtitleDisplay="showing"===(null==(r=this.tracksInGroup[t].trackNode)?void 0:r.track.mode));this.setSubtitleTrack(t,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.on(zn.LEVEL_LOADING,this.onLevelLoading,this),t.on(zn.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(zn.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(zn.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.off(zn.LEVEL_LOADING,this.onLevelLoading,this),t.off(zn.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(zn.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(zn.ERROR,this.onError,this)}createTracksInGroup(){var t;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(t=>{t.trackNode||(t.trackNode=Lg(this.media,Rg(t),t.name,t.lang))});const e=null==(t=this.currentTrack)||null==(t=t.trackNode)?void 0:t.track;"disabled"===(null==e?void 0:e.mode)&&(e.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(t,e){const s=e.media;this.media=s;let i=this.trackId;this.queuedDefaultTrack>-1&&(i=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(i),this.createTracksInGroup(),this.useTextTrackPolling=!(s.textTracks&&"onchange"in s.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):s.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,e){const s=this.media;if(!s)return;const i=!!e.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,i||this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(t=>{const e=t.trackNode;e&&(e.track.mode="hidden",e.remove(),t.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} 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(!e)return;const s=e.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some(t=>-1===(null==i?void 0:i.indexOf(t)))){this.groupIds=s;const t=[];if(this.tracks.forEach(e=>{(e.textCodec===gg?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!s||s.indexOf(e.groupId)>-1?(e.id=t.length,t.push(e)):e.trackNode&&(e.trackNode.remove(),e.trackNode=void 0))}),t.length===this.tracksInGroup.length){let e=!1;for(let s=0;s<t.length;s++)if(t[s]!==this.tracksInGroup[s]){e=!0;break}if(!e)return}t.length&&this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=t,this.trackId=-1,this.currentTrack=null;const e=this.hls.config.subtitlePreference;if(!r&&e){this.selectDefaultTrack=!1;const s=xl(e,t);if(s>-1)r=t[s];else{const t=xl(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(zn.SUBTITLE_TRACKS_UPDATED,n),this.setSubtitleTrack(i),this.createTracksInGroup()}}findTrackId(t){const e=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<e.length;i++){const r=e[i];if((!s||r.default)&&(s||t)&&(!t||Fl(r,t)))return i}if(t){for(let s=0;s<e.length;s++){const i=e[s];if(iu(t.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const i=e[s];if(iu(t.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}onError(t,e){!e.fatal&&e.context&&e.context.type===ia&&e.context.id===this.trackId&&$l(e.context.groupId,this.groupIds)&&this.checkRetry(e)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t,!0)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){if(-1===t.id)return this.setSubtitleTrack(-1,!0),null;const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const s=this.currentTrack;if(s&&Fl(t,s))return s;const i=xl(t,this.tracksInGroup);if(i>-1){const t=this.tracksInGroup[i];return this.setSubtitleTrack(i,!0),t}if(s)return null;{const s=xl(t,e);if(s>-1)return e[s]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=t.id,i=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${s} "${t.name}" lang:${t.lang} group:${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(zn.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null,track:t})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;const t=this.currentTrack;this.tracksInGroup.forEach(e=>{if(e.trackNode){const s=e===t?this._subtitleDisplay?"showing":"hidden":"disabled",i=e.trackNode.track;i.mode!==s&&(i.mode=s)}})}setSubtitleTrack(t,e=!1){const s=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=t),t<-1||t>=s.length||!Vn(t))return void this.warn(`Invalid subtitle track id: ${t}`);const i=this.currentTrack,r=s[t]||null;if(this.trackId=t,this.currentTrack=r,e&&this.toggleTrackModes(),!r)return void(i&&this.hls.trigger(zn.SUBTITLE_TRACK_SWITCH,{id:t}));const n=!!r.details&&!r.details.live;if(r===i&&n)return;this.log(`Switching to subtitle-track ${t}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:a,groupId:o="",name:l,type:d,url:c}=r;this.hls.trigger(zn.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:d,url:c});const h=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(h)}},timelineController:class TimelineController{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.cueCache={},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}},t.on(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(zn.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(zn.FRAG_LOADING,this.onFragLoading,this),t.on(zn.FRAG_LOADED,this.onFragLoaded,this),t.on(zn.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(zn.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(zn.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(zn.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(zn.BUFFER_APPENDED,this.onBufferAppended,this),t.on(zn.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(zn.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(zn.FRAG_LOADING,this.onFragLoading,this),t.off(zn.FRAG_LOADED,this.onFragLoaded,this),t.off(zn.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(zn.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(zn.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(zn.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(zn.BUFFER_APPENDED,this.onBufferAppended,this),t.off(zn.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new OutputFilter(this,"textTrack1"),e=new OutputFilter(this,"textTrack2"),s=new OutputFilter(this,"textTrack3"),i=new OutputFilter(this,"textTrack4");this.cea608Parser1=new Cea608Parser(1,t,e),this.cea608Parser2=new Cea608Parser(3,s,i)}addCues(t,e,s,i,r){let n=!1;for(let t=r.length;t--;){const i=r[t],a=mp(i[0],i[1],e,s);if(a>=0&&(i[0]=Math.min(i[0],e),i[1]=Math.max(i[1],s),n=!0,a/(s-e)>.5))return}if(n||r.push([e,s]),this.config.renderTextTracksNatively){const r=this.cueCache[t];if(r){const t=this.Cues.newCue(null,e,s,i);t.length&&r.push.apply(r,t)}else{const r=this.captionsTracks[t].track;this.Cues.newCue(r,e,s,i)}}else{var a;const r=this.Cues.newCue(null,e,s,i),n=null==(a=this.captionsProperties[t])?void 0:a.media;this.hls.trigger(zn.CUES_PARSED,{type:"captions",cues:r,track:t,closedCaptions:n})}}onInitPtsFound(t,{id:e,timestampOffsets:s}){const{unparsedVttFrags:i}=this;e===da&&(this.initPTS=s),i.length&&(this.unparsedVttFrags=[],i.forEach(t=>{this.initPTS[t.frag.cc]?this.onFragLoaded(zn.FRAG_LOADED,t):this.hls.trigger(zn.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:s,cueCache:i,media:r}=this,{label:n,languageCode:a}=e[t];r&&(i[t]=[],s[t]=Lg(r,"captions",n,a,"hidden"))}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(zn.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}onMediaAttaching(t,e){this.media=e.media}onMediaDetaching(t,e){const s=!!e.transferMedia;if(this.media=null,!s){if(this.config.renderTextTracksNatively){const{captionsTracks:t,cueCache:e}=this;for(const s in t)t[s].remove(),delete e[s]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(t,e){const s=e.subtitleTracks||[];if(s.length&&!this.config.renderTextTracksNatively&&!su(this.tracks,s)){const t=s.map(t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}));this.hls.trigger(zn.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}this.tracks=s}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]}`,i=this.captionsProperties[s];i&&(i.label=t.name,t.lang&&(i.languageCode=t.lang),i.media=t)})}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===da){var s,i;const{cea608Parser1:t,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(s=null==(i=e.part)?void 0:i.index)?s:-1;t&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:s,payload:i}=e;var r;if(s.level<this.tracks.length&&s.type===ha)if(i.byteLength||null!=(r=s.initSegment)&&null!=(r=r.data)&&r.byteLength){const t=s.decryptdata,i="stats"in e;if(null==t||!t.encrypted||i){const t=this.tracks[s.level],i=this.vttCCs;i[s.cc]||(i[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),(null==t?void 0:t.textCodec)===gg?this._parseIMSC1(e):this._parseVTTs(e)}}else{const t="part"in e?e.part:null;this.hls.trigger(zn.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:t,error:new Error("Empty subtitle payload")})}}_parseIMSC1(t){const{frag:e,payload:s}=t,i="part"in t?t.part:null,r=this.hls;yg(s,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),r.trigger(zn.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e,part:i})},t=>{r.logger.log(`Cannot parse IMSC1 (sn: ${e.sn} @${e.start}): ${t}`),r.trigger(zn.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,part:i,error:t})})}_parseVTTs(t){var e;const{frag:s,payload:i}=t,r="part"in t?t.part:null,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[s.cc]&&-1===o)return void a.push(t);const l=this.hls,d=null==(e=s.initSegment)?void 0:e.data;fg(d?Uo(d,new Uint8Array(i)).buffer:i,this.initPTS[s.cc],this.vttCCs,s.cc,(r&&!d?r:s).start,t=>{this._appendCues(t,s.level),l.trigger(zn.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s,part:r})},e=>{const i=e.message.startsWith("Missing initPTS");l.logger.log(`${i?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${s.sn} @${s.start}): ${e}`),i?a.push(t):(this.config.enableIMSC1&&this._fallbackToIMSC1(t),l.trigger(zn.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:r,error:e}))})}_fallbackToIMSC1(t){const{frag:e,payload:s}=t,i=this.tracks[e.level];i.textCodec||yg(s,this.initPTS[e.cc],()=>{i.textCodec=gg,this._parseIMSC1(t)},()=>{i.textCodec="wvtt"})}_appendCues(t,e){const s=this.hls;if(this.config.renderTextTracksNatively){var i;const s=null==(i=this.tracks[e].trackNode)?void 0:i.track;if(!s||"disabled"===s.mode)return;t.forEach(t=>Ig(s,t))}else{const i=this.tracks[e];if(!i)return;const r=i.default?"default":"subtitles"+e;s.trigger(zn.CUES_PARSED,{type:"subtitles",cues:t,track:r,subtitleTrack:i})}}onFragDecrypted(t,e){const{frag:s}=e;s.type===ha&&this.onFragLoaded(zn.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=e;if(s.type!==da||"NONE"!==this.closedCaptionsForLevel(s))for(let t=0;t<i.length;t++){const e=i[t].bytes;if(e){this.cea608Parser1||this.initCea608Parsers();const s=this.extractCea608Data(e);this.cea608Parser1.addData(i[t].pts,s[0]),this.cea608Parser2.addData(i[t].pts,s[1])}}}onBufferAppended(t,e){if(this.config.renderTextTracksNatively){var s;const{type:t,timeRanges:i}=e;if("video"===t&&null!=(s=i[t])&&s.length){const{captionsTracks:t,cueCache:e}=this;Object.keys(e).forEach(s=>{var i;const r=null==(i=t[s])?void 0:i.track;if(r){const t=e[s];for(let e=0;e<t.length;e++)Ig(r,t[e])}delete e[s]})}}}onBufferFlushing(t,e){const{startOffset:s,endOffset:i,endOffsetSubtitles:r,type:n}=e,{media:a}=this;if(a&&!(a.currentTime<i)){if(!n||"video"===n){const{captionsTracks:t,cueCache:e}=this;Object.keys(t).forEach(e=>kg(t[e].track,s,i)),Object.keys(e).forEach(t=>{const r=e[t];for(let t=r.length;t--;){const e=r[t];e.startTime>=s&&e.endTime<=i&&r.splice(t,1)}})}this.config.renderTextTracksNatively&&0===s&&void 0!==r&&this.tracks.forEach(t=>{var e;const i=null==(e=t.trackNode)?void 0:e.track;i&&kg(i,s,r)})}}extractCea608Data(t){const e=[[],[]],s=31&t[0];let i=2;for(let r=0;r<s;r++){const s=t[i++],r=127&t[i++],n=127&t[i++];if(0===r&&0===n)continue;if(!!(4&s)){const t=3&s;0!==t&&1!==t||(e[t].push(r),e[t].push(n))}}return e}},audioStreamController:class AudioStreamController extends BaseStreamController{constructor(t,e,s){super(t,e,s,"audio-stream-controller",ca),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.on(zn.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(zn.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(zn.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(zn.BUFFER_RESET,this.onBufferReset,this),t.on(zn.BUFFER_CREATED,this.onBufferCreated,this),t.on(zn.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(zn.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(zn.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(zn.FRAG_LOADING,this.onFragLoading,this),t.on(zn.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.off(zn.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(zn.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(zn.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(zn.BUFFER_RESET,this.onBufferReset,this),t.off(zn.BUFFER_CREATED,this.onBufferCreated,this),t.off(zn.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(zn.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(zn.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(zn.FRAG_LOADING,this.onFragLoading,this),t.off(zn.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,e){const{frag:s,id:i,initPTS:r,timescale:n,trackId:a,timestampOffsets:o}=e;if(i===da){const t=s.cc,e=this.fragCurrent;if(this.initPTS=o,this.log(`InitPTS for cc: ${t} found from main: ${r/n} (${r}/${n}) trackId: ${a}`),this.mainAnchor=s,this.state===Vc){const e=this.waitingData;(!e&&!this.loadingParts||e&&e.frag.cc!==t)&&this.syncWithAnchor(s,null==e?void 0:e.frag)}else!this.hls.hasEnoughToStart&&e&&e.cc!==t?(e.abortRequests(),this.syncWithAnchor(s,e)):this.state===xc&&this.tick()}}getLoadPosition(){var t;return!this.startFragRequested&&this.nextLoadPosition>=0&&!1!==(null==(t=this.switchingTrack)?void 0:t.flushImmediate)?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,e){var s;const i=(null==(s=this.mainFragLoading)?void 0:s.frag)||null;if(e&&(null==i?void 0:i.cc)===e.cc)return;const r=(i||t).cc,n=ql(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===xc&&this.doTickIdle())}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=Mc);const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),s>0&&-1===t&&!e&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),t=s),this.state=xc,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,e||this.fragmentTracker.hasFragments(this.playlistType)||(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case xc:this.doTickIdle();break;case Bc:{const{levels:t,trackId:e}=this,s=null==t?void 0:t[e],i=null==s?void 0:s.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=Vc}break}case Uc:this.checkRetryDate();break;case Vc:{const t=this.waitingData;if(t){const{frag:e,part:s,cache:i,complete:r}=t,n=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=Nc;const t={frag:e,part:s,payload:i.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else n&&n.cc!==t.frag.cc&&this.syncWithAnchor(n,t.frag)}else this.state=xc}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime,this.checkFragmentChanged())}doTickIdle(){var t;const{hls:e,levels:s,media:i,trackId:r}=this,n=e.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==s||!s[r])return;const a=s[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=Bc,void(this.startFragRequested=!1);const l=this.getBufferOutput();this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,ua));const d=this.getFwdBufferInfo();if(null===d)return;if(!this.switchingTrack&&this._streamEnded(d,o))return e.trigger(zn.BUFFER_EOS,{type:"audio"}),void(this.state=Hc);const c=d.len,h=e.maxBufferLength,u=o.fragments,f=u[0].start,g=this.getLoadPosition(),p=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?g:d.end;if(this.switchingTrack&&i){const t=g;o.PTSKnown&&t<f&&t>=this.timelineOffset&&(d.end>f||d.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${t} -> ${f} + 0.05`),i.currentTime=f+.05)}if(c>=h&&!this.switchingTrack&&p<u[u.length-1].start)return;let m=this.getNextFragment(p,o);if(m&&this.isLoopLoading(m,p)&&(m=this.getNextFragmentLoopLoading(m,o,d,da,h)),!m)return void(this.bufferFlushed=!0);if(this.exceedsMaxBuffer(d,h,m))return;let v=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&pa(m)&&!m.endList&&(!o.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===cd&&(this.mainFragLoading=v=null),v&&pa(v))){if(m.start>v.end){const t=this.fragmentTracker.getFragAtPos(p,da);t&&t.end>v.end&&(v=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(m.start>v.end)return}this.loadFragment(m,a,p)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}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:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=e,e.flushImmediate||(this.nextTrackId=e.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(e),this.state!==Mc&&(this.setInterval(100),this.state=xc,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,e){this.mainDetails=e.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(zn.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(t,e){var s;const{levels:i}=this,{details:r,id:n,groupId:a,track:o}=e;if(!i)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=e,void(this.state!==Mc&&(this.state=Bc));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const d=i[n];let c=0;if(r.live||null!=(s=d.details)&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var h;if(d.details)c=this.alignPlaylists(r,d.details,null==(h=this.levelLastLoaded)?void 0:h.details);r.alignedSliding||(Pc(l,r,this),c=r.fragmentStart)}d.details=r,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(zn.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:e.groupId}),this.state!==Bc||this.waitForCdnTuneIn(r)||(this.state=xc),this.tick()}_handleFragmentLoadProgress(t){var e;const s=t.frag,{part:i,payload:r}=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 h=this.transmuxer;h||(h=this.transmuxer=new TransmuxerInterface(this.hls,ca,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(e=s.initSegment)?void 0:e.data;if(void 0!==u){const t=!1,e=i?i.index:-1,n=-1!==e,a=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount,r.byteLength,e,n,s.duration);h.push(r,f,c,"",s,i,d.totalduration,t,a,u)}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:i,cache:new ChunkCache,complete:!1};t.push(new Uint8Array(r)),this.state!==Mc&&(this.state=Vc)}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;const s=e.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===da&&pa(e.frag)&&(this.mainFragLoading=e,this.state===xc&&this.tick())}onFragBuffered(t,e){const{frag:s,part:i}=e;if(s.type===ca)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(pa(s)){const t=this.switchingTrack;t&&(this.bufferedTrack=t)}this.fragBufferedComplete(s,i),this.media&&this.tick()}else this.audioOnly||s.type!==da||s.elementaryStreams.video||s.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}getFwdBufferInfo(){const t=this.getBufferOutput();return super.getFwdBufferInfo(t,ca)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){const t=this.fragPlaying;if(!this.checkFragPlaying())return!1;const e=this.fragPlaying,s=null==t?void 0:t.level;return e&&e.level===s||(t&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(t,e){var s;if(e.fatal)this.state=Kc;else switch(e.details){case Yn.FRAG_GAP:case Yn.FRAG_PARSING_ERROR:case Yn.FRAG_DECRYPT_ERROR:case Yn.FRAG_LOAD_ERROR:case Yn.FRAG_LOAD_TIMEOUT:case Yn.KEY_LOAD_ERROR:case Yn.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ca,e);break;case Yn.AUDIO_TRACK_LOAD_ERROR:case Yn.AUDIO_TRACK_LOAD_TIMEOUT:case Yn.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Bc||(null==(s=e.context)?void 0:s.type)!==sa||(this.state=xc);break;case Yn.BUFFER_APPEND_NO_PROGRESS:if("audio"!==e.parent)return;e.frag&&(e.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${e.frag.sn} of track ${e.frag.level} as a gap after ${e.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(e.frag));break;case Yn.BUFFER_ADD_CODEC_ERROR:case Yn.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case Yn.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Yn.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==fa&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==fa){this.flushing=!1,this.bufferFlushed=!0,this.state===Hc&&(this.state=xc);const t=this.getBufferOutput();t&&(this.afterBufferFlushed(t,e),this.tick())}}_handleTransmuxComplete(t){var e;const s="audio",{hls:i}=this,{remuxResult:r,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:h,text:u,id3:f,initSegment:g}=r;if(this.fragContextChanged(o)||!c)return this.fragmentTracker.removeFragment(o),void(null!=g&&g.tracks&&this.resetTransmuxer());if(this.state=$c,h&&this.switchingTrack&&!this.switchingTrack.flushImmediate){const{config:t}=this,e=t.nextAudioTrackBufferFlushForwardOffset,s=Math.max(this.getLoadPosition()+e,o.start);super.flushMainBuffer(s,Number.POSITIVE_INFINITY,ca)}if(null!=g&&g.tracks){const t=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(d,g.tracks,t,n),i.trigger(zn.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:g.tracks})}if(h){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=h;l&&(l.elementaryStreams[ua]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(ua,t,e,s,i),this.bufferFragmentData(h,o,l,n)}if(null!=f&&null!=(e=f.samples)&&e.length){const t=Ta({id:s,frag:o,details:c},f);i.trigger(zn.FRAG_PARSING_METADATA,t)}if(u){const t=Ta({id:s,frag:o,details:c},u);i.trigger(zn.FRAG_PARSING_USERDATA,t)}}_bufferInitSegment(t,e,s,i){if(this.state!==$c)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const r=e.audio;r.id=ca;const n=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),1===(null==n?void 0:n.split(",").length)&&(r.levelCodec=n),this.hls.trigger(zn.BUFFER_CODECS,e);const a=r.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:a};this.hls.trigger(zn.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);var r;if(this.switchingTrack||i===od||i===dd)if(null!=(r=e.details)&&r.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=Vc;const s=this.mainDetails;s&&s.fragmentStart!==e.details.fragmentStart&&Pc(s,e.details,this)}else super.loadFragment(t,e,s);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack&&t.flushImmediate){const{name:e,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;Fl({name:e,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a},t,Nl)||(Bl(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:e}=this;this.bufferedTrack=t,this.switchingTrack=null,e.trigger(zn.AUDIO_TRACK_SWITCHED,Aa({},t))}get nextAudioTrack(){return this.nextTrackId}},audioTrackController:class AudioTrackController extends BasePlaylistController{constructor(t){super(t,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.on(zn.LEVEL_LOADING,this.onLevelLoading,this),t.on(zn.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(zn.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(zn.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.off(zn.LEVEL_LOADING,this.onLevelLoading,this),t.off(zn.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(zn.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(zn.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Audio track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} 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(!e)return;const s=e.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some(t=>-1===(null==i?void 0:i.indexOf(t)))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>$l(t.groupId,s));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!r&&e){const s=xl(e,t,Nl);if(s>-1)r=t[s];else{const t=xl(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const a={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(zn.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==i&&-1===o)this.setAudioTrack(i);else if(t.length&&-1===o){var n;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}}onError(t,e){!e.fatal&&e.context&&e.context.type===sa&&e.context.id===this.trackId&&$l(e.context.groupId,this.groupIds)&&this.checkRetry(e)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t,!1)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&Fl(t,i,Nl))return i;const r=xl(t,this.tracksInGroup,Nl);if(r>-1){const e=this.tracksInGroup[r];return this.setAudioTrack(r,"flushImmediate"in t&&t.flushImmediate),e}if(i){let i=e.loadLevel;-1===i&&(i=e.firstAutoLevel);const r=function(t,e,s,i,r){const n=e[i],a=e.reduce((t,e,s)=>{const i=e.uri;return(t[i]||(t[i]=[])).push(s),t},{}),o=a[n.uri];o.length>1&&(i=Math.max.apply(Math,o));const l=n.videoRange,d=n.frameRate,c=n.codecSet.substring(0,4),h=Ul(e,i,e=>{if(e.videoRange!==l||e.frameRate!==d||e.codecSet.substring(0,4)!==c)return!1;const i=e.audioGroups,n=s.filter(t=>$l(t.groupId,i));return xl(t,n,r)>-1});return h>-1?h:Ul(e,i,e=>{const i=e.audioGroups,n=s.filter(t=>$l(t.groupId,i));return xl(t,n,r)>-1})}(t,e.levels,s,i,Nl);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=xl(t,s);if(e>-1)return s[e]}}}return null}setAudioTrack(t,e=!0){const s=this.tracksInGroup;if(t<0||t>=s.length)return void this.warn(`Invalid audio track id: ${t}`);this.selectDefaultTrack=!1;const i=this.currentTrack,r=s[t],n=r.details&&!r.details.live;if(t===this.trackId&&r===i&&n)return;if(this.log(`Switching to audio-track ${t} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=t,this.currentTrack=r,this.hls.trigger(zn.AUDIO_TRACK_SWITCHING,Aa(Aa({},r),{},{flushImmediate:e})),n)return;const a=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(a)}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const i=e[s];if((!this.selectDefaultTrack||i.default)&&(!t||Fl(t,i,Nl)))return s}if(t){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(Fl({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o},e[t],Nl))return t}for(let s=0;s<e.length;s++){const i=e[s];if(iu(t.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const i=e[s];if(iu(t.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&Bl(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=t.id,i=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${s} "${t.name}" lang:${t.lang} group:${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(zn.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null,track:t})}},emeController:EMEController,cmcdController:class CMCDController{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(Cf)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(wf)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(Pf)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(Of)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(Df)},this.onSeeked=()=>{var t;this.initialized&&null!=(t=this.media)&&t.paused&&this.setPlayerState(Of)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=t=>{try{this.apply(t,{ot:_f,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const{frag:n,part:a}=t,o=this.hls.levels[n.level],l=this.getObjectType(n,o),d={d:1e3*(a||n).duration,ot:l};if(l===Lf||l===bf||l===Rf||null==l&&("main"===n.type||"audio"===n.type)){var e;const t=o.bitrate/1e3;d.br=[t];const{cmcd:i}=this.config,r=null!=(e=null==i?void 0:i.rtpSafetyFactor)?e:5;if(d.rtp=100*Math.round(t*r/100),l===Rf||null==l&&"main"===n.type){const t=this.getTopBandwidth()/1e3;Vn(t)&&(d.tb=[t]);const e=this.getLowestBandwidth()/1e3;Vn(e)&&(d.lb=[e])}const a=this.getBufferLength(n);if(Vn(a)){var s;d.bl=[a];const t=(null==(s=this.media)?void 0:s.playbackRate)||1;d.dl=100*Math.round(a/t/100)}this.playheadLevel&&(d.pb=[this.playheadLevel.bitrate/1e3]);const c=this.hls.maxAutoLevel;if(c>=0){const t=this.hls.levels[c];t&&(d.tpb=[t.bitrate/1e3])}}const c=a?this.getNextPart(a):this.getNextFrag(n);null!=c&&c.url&&c.url!==n.url&&(c.byteRange.length>0?d.nor=[(i=c.url,r={r:`${c.byteRange[0]}-${c.byteRange[1]}`},new uu(i,r))]:d.nor=[c.url]),this.apply(t,d)}catch(t){this.hls.logger.warn("Could not generate segment CMCD data.",t)}var i,r},this.recordFragmentResponse=(t,e,s)=>{var i;const{cmcd:r}=this.config,n=null==r||null==(i=r.eventTargets)?void 0:i.some(t=>{var e;return null==(e=t.events)?void 0:e.includes(Gu)});if(this.reporter&&s.loading.first>0&&n)try{this.reporter.recordResponseReceived({request:{url:t},status:e.code,resourceTiming:{startTime:s.loading.start,responseStart:s.loading.first,duration:s.loading.end-s.loading.start,encodedBodySize:s.total}})}catch(t){this.hls.logger.warn("Could not record fragment response 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.registerListeners())}createReporter(){var t,e;const{cmcd:s}=this.config;if(null==s)return;const i=s.version||1;if(this.reporter=new jf({sid:s.sessionId||this.hls.sessionId,cid:s.contentId,version:i,transmissionMode:!0===s.useHeaders?Uf:Nf,enabledKeys:null!=(t=s.includeKeys)?t:[...i>=Nu?Af:rf],eventTargets:(null!=(e=s.eventTargets)?e:[]).map(t=>{let{includeKeys:e}=t;return Aa(Aa({},_a(t,Qf)),{},{enabledKeys:null!=e?e:Af})})},s.loader),this.reporter.update({sf:qf,sta:this.playerState}),s.reporterCallback){const t=this.reporter,e={updateCustomData:e=>{Xf(e)&&t.update(e)},recordCustomEvent:(e,s={})=>{Xf(s)&&t.recordEvent(Hu,Aa({cen:e},s))}};s.reporterCallback(e)}this.reporter.start()}registerListeners(){const t=this.hls;t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(zn.MEDIA_DETACHED,this.onMediaDetached,this),t.on(zn.MEDIA_ENDED,this.onMediaEnded,this),t.on(zn.ERROR,this.onError,this),t.on(zn.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(zn.LEVEL_SWITCHED,this.onLevelSwitched,this),t.on(zn.BUFFER_APPENDED,this.onBufferInfoChange,this),t.on(zn.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){const t=this.hls;t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(zn.MEDIA_DETACHED,this.onMediaDetached,this),t.off(zn.MEDIA_ENDED,this.onMediaEnded,this),t.off(zn.ERROR,this.onError,this),t.off(zn.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(zn.LEVEL_SWITCHED,this.onLevelSwitched,this),t.off(zn.BUFFER_APPENDED,this.onBufferInfoChange,this),t.off(zn.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(t,e){const s=this.media=e.media;this.setPlayerState(this.media.autoplay?wf:Ff),Dc(s,"waiting",this.onWaiting),Dc(s,"play",this.onPlay),Dc(s,"playing",this.onPlaying),Dc(s,"pause",this.onPause),Dc(s,"seeking",this.onSeeking),Dc(s,"seeked",this.onSeeked),Dc(s,"ratechange",this.onRateChange)}onMediaDetached(){const t=this.media;t&&(Cc(t,"waiting",this.onWaiting),Cc(t,"play",this.onPlay),Cc(t,"playing",this.onPlaying),Cc(t,"pause",this.onPause),Cc(t,"seeking",this.onSeeking),Cc(t,"seeked",this.onSeeked),Cc(t,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(t,e){this.setPlayerState(Mf)}onManifestLoading(t,e){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(Ff)}onError(t,e){e.fatal&&(this.setPlayerState(xf),this.reporter&&this.reporter.recordEvent($u,{ec:[e.details]}))}onLevelSwitching(t,e){var s;if(!this.reporter)return;const i={br:[e.bitrate/1e3]},r=null==(s=e.details)?void 0:s.fragments[0];r&&(i.ot=this.getObjectType(r,e)),this.reporter.recordEvent(Bu,i)}onLevelSwitched(t,e){const s=this.hls.levels[e.level];s&&(this.playheadLevel=s)}setPlayerState(t){this.playerState=t,this.reporter&&this.reporter.update({sta:t})}getStreamType(){const t=this.hls.latestLevelDetails;if(t)return t.live?t.partList&&t.canBlockReload?zf:Yf:Wf}apply(t,e={}){var s;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:null==(s=this.media)?void 0:s.playbackRate,st:this.getStreamType()});const i=e.ot===If||e.ot===Lf||e.ot===Rf;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const r=this.reporter.createRequestReport({url:t.url,headers:t.headers},e);t.url=r.url,t.headers=r.headers}getNextFrag(t){var e;const s=null==(e=this.hls.levels[t.level])?void 0:e.details;if(s){const e=t.sn-s.startSN;return s.fragments[e+1]}}getNextPart(t){var e;const{index:s,fragment:i}=t,r=null==(e=this.hls.levels[i.level])||null==(e=e.details)?void 0:e.partList;if(r){const{sn:t}=i;for(let e=r.length-1;e>=0;e--){const i=r[e];if(i.index===s&&i.fragment.sn===t)return r[e+1]}}}getObjectType(t,e){const{type:s}=t;if("subtitle"===s)return kf;if("initSegment"===t.sn)return If;if("audio"===s)return bf;if("main"===s){if(t.hasStreams){const e=t.elementaryStreams;if(e.audiovideo)return Rf;if(e.video)return Lf;if(e.audio)return bf}if(e){const{audioCodec:t,videoCodec:s}=e;if(!this.hls.audioTracks.length){if(t&&s)return Rf;if(t)return bf}if(s)return Lf}}}getTopBandwidth(){let t=0;const e=this.hls,s=e.maxAutoLevel,i=s>-1?s+1:e.levels.length;return e.levels.slice(0,i).forEach(e=>{e.bitrate>t&&(t=e.bitrate)}),t>0?t:NaN}getLowestBandwidth(){let t=1/0;const e=this.hls,s=e.maxAutoLevel,i=s>-1?s+1:e.levels.length;return e.levels.slice(0,i).forEach(e=>{e.bitrate<t&&(t=e.bitrate)}),Vn(t)?t:NaN}getBufferLength(t){if(!this.media)return NaN;const e="audio"===t.type?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return e?1e3*e.len:NaN}getEventBufferLength(){if(!this.media)return NaN;const t=this.hls.mainForwardBufferInfo,e=this.hls.audioForwardBufferInfo;if(t&&e)return 1e3*Math.min(t.len,e.len);const s=t||e;return s?1e3*s.len:NaN}onBufferInfoChange(t,e){if(!this.reporter)return;const s=this.getEventBufferLength();Vn(s)&&this.reporter.update({bl:[s]})}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,i){e(t),this.loader.load(t,s,i)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,s=this.recordFragmentResponse,i=t||this.config.loader;return class CmcdFragmentLoader{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,r){e(t);const{onSuccess:n}=r;this.loader.load(t,i,Aa(Aa({},r),{},{onSuccess:(e,i,r,a)=>{n(e,i,r,a),s(t.url,e,i)}}))}}}},contentSteeringController:class ContentSteeringController extends Logger{constructor(t){super("content-steering",t.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.on(zn.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.off(zn.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(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)===zl&&s.flags&Jl){const t=this.levels;let i=this._pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:s,pathwayId:i,type:n}=e.context;s&&t?r=this.getPathwayForGroupId(s,n,r):i&&(r=i)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!i&&t&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==r,s.resolved||e.details===Yn.BUFFER_APPEND_ERROR&&!e.fatal||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${Dl(i)} penalized: ${Dl(this.penalizedPathways)}`))}}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}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){let e;this._pathwayPriority=t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(t=>{i-s[t]>3e5&&delete s[t]});for(let i=0;i<t.length;i++){const r=t[i];if(r in s)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(e=this.getLevelsForPathway(r),e.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,bc(e),this.hls.trigger(zn.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}}}getPathwayForGroupId(t,e,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s<i.length;s++)if(e===sa&&i[s].hasAudioGroup(t)||e===ia&&i[s].hasSubtitleGroup(t))return i[s].pathwayId;return s}clonePathways(t){const e=this.levels;if(!e)return;const s={},i={};t.forEach(t=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some(t=>t.pathwayId===r))return;const o=this.getLevelsForPathway(n).map(t=>{const e=new AttrList(t.attrs);e["PATHWAY-ID"]=r;const n=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;n&&(s[e.AUDIO]=n,e.AUDIO=n),o&&(i[e.SUBTITLES]=o,e.SUBTITLES=o);const l=Jf(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new Level({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e<t.audioGroups.length;e++)d.addGroupId("audio",`${t.audioGroups[e]}_clone_${r}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)d.addGroupId("text",`${t.subtitleGroups[e]}_clone_${r}`);return d});e.push(...o),Zf(this.audioTracks,s,a,r),Zf(this.subtitleTracks,i,a,r)})}loadSteeringManifest(t){const e=this.hls.config,s=e.loader;let i;this.loader&&this.loader.destroy(),this.loader=new s(e);try{i=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==i.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);Al(i,"_HLS_pathway",this.pathwayId),Al(i,"_HLS_throughput",""+t)}const r={type:aa,responseType:"json",url:i.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,r)=>{this.log(`Loaded steering manifest: "${i}"`);const n=t.data;if(1!==(null==n?void 0: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,i).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);const d={steeringManifest:n,url:i.toString()};this.hls.trigger(zn.STEERING_MANIFEST_LOADED,d),l&&this.updatePathwayPriority(l)},onError:(t,e,s,i)=>{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 r=1e3*this.timeToLoad;if(429===t.code){const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}return void this.log(`Steering manifest ${e.url} rate limited`)}this.scheduleRefresh(this.uri||e.url,r)},onTimeout:(t,e,s)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var e;const s=null==(e=this.hls)?void 0:e.media;!s||s.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)},e)}},iframeController:class IFrameController extends Logger{constructor(t,e){var s;super("iframes",t.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,Kg||(s=e,Kg=class HlsIFramesOnly extends s{constructor(t,e,s,i){t.streamController||(t.streamController=IFrameStreamController),super(t),this._url=e,this.streamController.setInitPts(s),this.streamController.initDetails=i}loadSource(){}loadMediaAt(t,e=Hg){if(t<0)return;const s=Aa(Aa({},Hg),e);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,s)}}),Vg||(Vg=function(t){return class HlsImageIFramesOnly extends t{constructor(t,e,s,i){t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=ImageIFrameStreamController),t.capLevelController=void 0,t.bufferController=void 0,super(t,e,s,i)}attachImage(t){this.streamController.image=t}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(Gg)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}(Kg)),this.hls=t,this.iframeInstances=[],this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(zn.MANIFEST_LOADING,this.clearAsset,this),t.on(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(zn.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(zn.FRAG_BUFFERED,this.onFragBuffered,this),t.on(zn.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(zn.MANIFEST_LOADING,this.clearAsset,this),t.off(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(zn.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(zn.FRAG_BUFFERED,this.onFragBuffered,this),t.off(zn.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(t=>t.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(t,e){this.stats=e.stats,this.variableList=e.variableList}onLevelsUpdated(t,{levels:e}){var s;const i=null==(s=this.hls)?void 0:s.pathwayPriority;e.length&&i&&this.iframeInstances.forEach(t=>{t.pathwayPriority=i})}onInitPtsFound(t,{id:e,timestampOffsets:s}){e===da&&(this.initPTS=s)}onFragBuffered(t,e){var s;const i=this.hls;i&&i.hasEnoughToStart&&((null==(s=i.mainForwardBufferInfo)?void 0:s.len)||0)>10&&this.iframeInstances.forEach(t=>{var e;t.loadingEnabled||t.startLoad((null==(e=this.hls)||null==(e=e.media)?void 0:e.currentTime)||0)})}createIFramePlayer(t){var e;return this.createInstance(Kg,null==(e=this.hls)?void 0:e.iframeVariants,t)}createImageIFramePlayer(t){var e;const s=null==(e=this.hls)?void 0:e.iframeVariants.filter(t=>t.imageCodec);return this.createInstance(Vg,s,t,"image-")}createInstance(t,e,s,i){const{hls:r}=this;if(!r)return null;const{url:n,userConfig:a,latestLevelDetails:o,loadLevelObj:l,loadLevel:d,bandwidthEstimate:c,sessionId:h}=r,{stats:u,variableList:f}=this;if(null==e||!e.length||!u||!n)return null;const g=`${i||""}iframe-player-${this.instanceCounter++}`,p=r.levels,m=l||p[d],v=Gl(m,a.videoPreference),y=(null==m?void 0:m.pathwayId)||".",E=new t(Aa(Aa({},a),{},{loggerId:g,primarySessionId:h,videoPreference:v,abrEwmaDefaultEstimate:c,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},s),n,this.initPTS,o);return this.iframeInstances=this.iframeInstances.filter(t=>!t.url),this.iframeInstances.push(E),E.trigger(zn.MANIFEST_LOADED,{levels:e,contentSteering:{uri:"",pathwayId:y},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:u,networkDetails:null,url:n,variableList:f}),E}},interstitialsController:class InterstitialsController extends Logger{constructor(t,e){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled||!this.schedule)return;const e=t-this.timelinePos;if(Math.abs(e)<1/7056e5)return;const s=e<=-.01;-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),this.timelinePos=t,this.bufferedPos=t;const i=this.playingItem;if(!i)return void this.checkBuffer();if(s){this.schedule.resetErrorsInRange(t,t-e)&&this.updateSchedule(!0)}if(this.checkBuffer(),s&&t<i.start||t>=i.end){var r;const e=this.findItemIndex(i);let n=this.schedule.findItemIndexAtTime(t);if(-1===n&&(n=e+(s?-1:1),this.log(`seeked ${s?"back ":""}to position not covered by schedule ${t} (resolving from ${e} to ${n})`)),!this.isInterstitial(i)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!s&&n>e){const t=this.schedule.findJumpRestrictedIndex(e+1,n);if(t>e)return void this.setSchedulePosition(t)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(i)){const e=i.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,e))}return}const a=n.timelineStart,o=n.duration||0;var l;(s&&t<a||t>=a+o)&&(null!=(l=i.event)&&l.appendInPlace&&(this.clearAssetPlayers(i.event,i),this.flushFrontBuffer(t)),this.setScheduleToAssetAtTime(t,n))},this.onTimeupdate=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;if(-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();const e=this.playingItem;if(!e||this.playingLastItem)return;if(t>=e.end){this.timelinePos=e.end;const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}const s=this.playingAsset;if(!s)return;t>=s.timelineStart+(s.duration||0)&&this.setScheduleToAssetAtTime(t,s)},this.onScheduleUpdate=(t,e)=>{const s=this.schedule;if(!s)return;const i=this.playingItem,r=s.events||[],n=s.items||[],a=s.durations,o=t.map(t=>t.identifier),l=!(!r.length&&!o.length);(l||e)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map(t=>tp(t))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let d=null,c=null;i&&(d=this.updateItem(i,this.timelinePos),this.itemsMatch(i,d)?this.playingItem=d:this.waitingItem=null),this.waitingItem=this.updateItem(this.waitingItem);const h=this.bufferingItem;if(h&&(c=this.updateItem(h,this.bufferedPos),this.itemsMatch(h,c)?this.bufferingItem=c:h.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(h.event,null))),t.forEach(t=>{t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,null)})}),this.playerQueue.forEach(t=>{if(t.interstitial.appendInPlace){const e=t.assetItem.timelineStart,s=t.timelineOffset-e;if(s)try{t.timelineOffset=e}catch(i){Math.abs(s)>jg&&this.warn(`${i} ("${t.assetId}" ${t.timelineOffset}->${e})`)}}}),l||e){if(this.hls.trigger(zn.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(i)&&o.indexOf(i.event.identifier)>-1)return this.warn(`Interstitial "${i.event.identifier}" removed while playing`),void this.primaryFallback(i.event);i&&this.trimInPlace(d,i),h&&c!==d&&this.trimInPlace(c,h),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new AssetListLoader(t),this.schedule=new InterstitialsSchedule(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(zn.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(zn.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(zn.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(zn.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(zn.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(zn.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(zn.BUFFER_APPENDED,this.onBufferAppended,this),t.on(zn.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(zn.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(zn.MEDIA_ENDED,this.onMediaEnded,this),t.on(zn.ERROR,this.onError,this),t.on(zn.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(zn.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(zn.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(zn.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(zn.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(zn.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(zn.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(zn.BUFFER_CODECS,this.onBufferCodecs,this),t.off(zn.BUFFER_APPENDED,this.onBufferAppended,this),t.off(zn.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(zn.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(zn.MEDIA_ENDED,this.onMediaEnded,this),t.off(zn.ERROR,this.onError,this),t.off(zn.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.getBufferingPlayer())||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){Cc(t,"play",this.onPlay),Cc(t,"pause",this.onPause),Cc(t,"seeking",this.onSeeking),Cc(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const s=this.media=e.media;Dc(s,"seeking",this.onSeeking),Dc(s,"timeupdate",this.onTimeupdate),Dc(s,"play",this.onPlay),Dc(s,"pause",this.onPause)}onMediaAttached(t,e){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===s)this.checkStart();else if(!i){this.clearScheduleState();const t=this.findItemIndex(s);this.setSchedulePosition(t)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const s=!!e.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.log(`Removing schedule state for detachedData and ${t}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,e=()=>t.bufferingItem||t.waitingItem,s=e=>e?t.getAssetPlayer(e.identifier):e,i=(e,i,n,a,o)=>{if(e){let l=e[i].start;const d=e.event;if(d){if("playout"===i||d.timelineOccupancy!==qg.Point){const t=s(n);(null==t?void 0:t.interstitial)===d&&(l+=t.assetItem.startOffset+t[o])}}else{l+=("bufferedPos"===a?r():t[a])-e.start}return l}return 0},r=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?n("primary"):Math.max(e,0)},n=e=>{var s,i;return null!=(s=t.primaryDetails)&&s.live?t.primaryDetails.edge:(null==(i=t.schedule)?void 0:i.durations[e])||0},a=(e,r)=>{var n,a;const o=t.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!t.schedule)return;t.log(`seek to ${e} "${r}"`);const l=t.effectivePlayingItem,d=t.schedule.findItemIndexAtTime(e,r),c=null==(a=t.schedule.items)?void 0:a[d],h=t.getBufferingPlayer(),u=null==h?void 0:h.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&t.itemsMatch(l,c);if(l&&(f||g)){const n=s(t.playingAsset),a=(null==n?void 0:n.media)||t.primaryMedia;if(a){const s="primary"===r?a.currentTime:i(l,r,t.playingAsset,"timelinePos","currentTime"),o=e-s,d=(f?s:a.currentTime)+o;if(d>=0&&(!n||f||d<=n.duration))return void(a.currentTime=d)}}if(c){let s=e;if("primary"!==r){const t=e-c[r].start;s=c.start+t}const i=!t.isInterstitial(c);if(t.isInterstitial(l)&&!l.event.appendInPlace||!i&&!c.event.appendInPlace){if(l){const n=t.findItemIndex(l);if(d>n){const e=t.schedule.findJumpRestrictedIndex(n+1,d);if(e>n)return void t.setSchedulePosition(e)}let a=0;if(i)t.timelinePos=s,t.checkBuffer();else{const t=c.event.assetList,s=e-(c[r]||c).start;for(let e=t.length;e--;){const i=t[e];if(i.duration&&s>=i.startOffset&&s<i.startOffset+i.duration){a=e;break}}}t.setSchedulePosition(d,a)}}else{const e=t.media||(f?null==h?void 0:h.media:null);e&&(e.currentTime=s)}}},o=()=>{const s=t.effectivePlayingItem;if(t.isInterstitial(s))return s;const i=e();return t.isInterstitial(i)?i:null},l={get bufferedEnd(){const s=e(),r=t.bufferingItem;var n;return r&&r===s&&(i(r,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(n=t.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const e=o(),s=t.effectivePlayingItem;return s&&s===e?i(s,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-s.playout.start:0},set currentTime(e){const s=o(),i=t.effectivePlayingItem;i&&i===s&&a(e+i.playout.start,"playout")},get duration(){const t=o();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var e;const s=null==(e=o())?void 0:e.event.assetList;return s?s.map(e=>t.getAssetPlayer(e.identifier)):[]},get playingIndex(){var e;const s=null==(e=o())?void 0:e.event;return s&&t.effectivePlayingAsset?s.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var e;return(null==(e=t.schedule)||null==(e=e.events)?void 0:e.slice(0))||[]},get schedule(){var e;return(null==(e=t.schedule)||null==(e=e.items)?void 0:e.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const s=e();return t.findItemIndex(s)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return r()},get currentTime(){const e=t.timelinePos;return e>0?e:0},set currentTime(t){a(t,"primary")},get duration(){return n("primary")},get seekableStart(){return t.seekableStart}},integrated:{get bufferedEnd(){return i(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){a(t,"integrated")},get duration(){return n("integrated")},get seekableStart(){return((e,s)=>{var i;if(0!==e&&"primary"!==s&&null!=(i=t.schedule)&&i.length){var r;const i=t.schedule.findItemIndexAtTime(e),n=null==(r=t.schedule.items)?void 0:r[i];if(n)return e+(n[s].start-n.start)}return e})(t.seekableStart,"integrated")}},skip:()=>{const e=t.effectivePlayingItem,s=null==e?void 0:e.event;if(s&&!s.restrictions.skip){const i=t.findItemIndex(e);if(s.appendInPlace){const t=e.playout.start+e.event.duration;a(t+.001,"playout")}else t.advanceAfterAssetEnded(s,i,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const e=this.playingItem,s=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&e&&s)&&this.findItemIndex(e)===s.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,e;if(null===this.mediaSelection)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(i=this.primaryMedia);const r=null==(e=i)?void 0:e.currentTime;return void 0!==r&&Vn(r)?r:void 0}get primaryMedia(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}isInterstitial(t){return!(null==t||!t.event)}retreiveMediaSource(t,e){const s=this.getAssetPlayer(t);s&&this.transferMediaFromPlayer(s,e)}transferMediaFromPlayer(t,e){const s=t.interstitial.appendInPlace,i=t.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&i)return void(this.detachedData={media:i});const s=t.transferMedia();this.log(`transfer MediaSource from ${t} ${Dl(s)}`),this.detachedData=s}else e&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(t,e){var s,i;if(t.media===e)return;let r=null;const n=this.hls,a=t!==n,o=a&&t.interstitial.appendInPlace,l=null==(s=this.detachedData)?void 0:s.mediaSource;let d;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),d="Primary";else{const t=this.getBufferingPlayer();t?(r=t.transferMedia(),this.detachedData=r,d=`${t}`):d=l?"detached MediaSource":"detached media"}if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${Dl(r)}`);else if(!this.detachedData||n.media===e){const t=this.playerQueue;t.length>1&&t.forEach(t=>{if(a&&t.interstitial.appendInPlace!==o){const e=t.interstitial;this.clearInterstitial(t.interstitial,null),e.appendInPlace=!1,e.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${e}`)}}),this.hls.detachMedia(),this.detachedData={media:e}}const c=r&&"mediaSource"in r&&"closed"!==(null==(i=r.mediaSource)?void 0:i.readyState);if(this.log(`${c?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${d} (media.currentTime: ${e.currentTime})`),!c&&!a)return void t.attachMedia(e);const h=c&&r?Aa({},r):{media:e},u=this.schedule;if(u&&a){const e=t.assetId===u.assetIdAtEnd;h.overrides={duration:u.duration,endOfStream:e||!1===t.appendInPlace}}if(!c&&o){const e=t,s=e.assetItem.timelineStart;if(s){const t=e.hls,i=Math.max(this.timelinePos-s,Number.EPSILON);t.startPosition!==i&&(this.log(`Set ${e} startPosition: ${i}`),t.config.startPosition=i,t.loadingEnabled&&t.startLoad(i))}}t.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,e=null==t?void 0:t.events,s=this.hls;if(!e||this.playbackDisabled||!this.media||!s)return;-1===this.bufferedPos&&(this.bufferedPos=0);const i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){if(!s.loadingEnabled)return void this.log("waiting for startLoad( <startPosition> )");const i=s.startPosition;if(this.timelinePos=i,0===e.length)this.setSchedulePosition(0);else if(e[0].cue.pre){this.log(sp("checkStart (preroll)",i));const s=t.findEventIndex(e[0].identifier);this.setSchedulePosition(s)}else if(i>=0||!this.primaryLive){this.log(sp("checkStart",i));const e=this.timelinePos=i>0?i:0,s=t.findItemIndexAtTime(e);this.setSchedulePosition(s)}else 0===s.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(r&&!this.playingItem){this.log(sp("checkStart (playing item)",r.start));const e=t.findItemIndex(r);this.setSchedulePosition(e)}}advanceAssetBuffering(t,e){const s=t.event,i=s.findAssetIndex(e),r=Xg(s,i);if(s.isAssetPastPlayoutLimit(r)){if(this.schedule){var n;const e=this.getNextItemIndex(t,!0),s=null==(n=this.schedule.items)?void 0:n[e];s&&this.bufferedToItem(s)}}else this.bufferedToEvent(t,r)}livePrerollResumption(t,e){if(t.cue.pre&&this.primaryLive&&!Vn(t.resumeOffset)&&this.hls){const t=this.getLiveStartPos();if(e){const e=this.getBufferingPlayer();return t+(null!=e&&e.interstitial.cue.pre?e.remaining:0)}return t}}getNextItemIndex(t,e){if(this.schedule){const s=this.livePrerollResumption(t.event,e);if(void 0!==s)return this.log(`find next item index @${s}`),this.schedule.findItemIndexAtTime(s)}return this.findItemIndex(t)+1}advanceAfterAssetEnded(t,e,s){const i=Xg(t,s);if(t.isAssetPastPlayoutLimit(i)){if(this.schedule){const s=this.schedule.items;if(s){const i=s[e],r=i.event?this.getNextItemIndex(i):e+1;if(r>=s.length)return void this.setSchedulePosition(-1);const n=t.resumeTime;this.timelinePos<n&&(this.log(sp("advanceAfterAssetEnded",n)),this.timelinePos=n,t.appendInPlace&&!s[r].event&&this.hls.startLoad(n+.01),this.checkBuffer(this.bufferedPos<n)),this.setSchedulePosition(r)}}}else{if(t.appendInPlace){const e=t.assetList[i];e&&this.advanceInPlace(e.timelineStart)}this.setSchedulePosition(e,i)}}setScheduleToAssetAtTime(t,e){const s=this.schedule;if(!s)return;const i=e.parentIdentifier,r=s.getEvent(i);if(r){const e=s.findEventIndex(i),n=s.findAssetIndex(r,t);this.advanceAfterAssetEnded(r,e,n-1)}}setSchedulePosition(t,e){var s;const i=null==(s=this.schedule)?void 0:s.items;if(!i||this.playbackDisabled)return;const r=t>=0?i[t]:null;this.log(`setSchedulePosition ${t}, ${e} (${r?tp(r):r}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const s=n.event,c=this.playingAsset,h=null==c?void 0:c.identifier,u=h?this.getAssetPlayer(h):null;if(u&&h&&(!this.eventItemsMatch(n,r)||void 0!==e&&h!==s.assetList[e].identifier)){var o;const e=s.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${e+1}/${s.assetList.length} ${Zg(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(zn.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:e,event:s,schedule:i.slice(0),scheduleIndex:t,player:u}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(s,this.findItemIndex(this.playingItem),e));this.retreiveMediaSource(h,r),!u.media||null!=(o=this.detachedData)&&o.mediaSource||u.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${s} ${tp(n)}`),s.hasPlayed=!0,this.hls.trigger(zn.INTERSTITIAL_ENDED,{event:s,schedule:i.slice(0),scheduleIndex:t}),s.cue.once&&this.hls)){var l;this.updateSchedule();const t=null==(l=this.schedule)?void 0:l.items;if(r&&t){const o=this.findItemIndex(r),l=this.livePrerollResumption(s);if(void 0!==l){let e=l;const r=this.getNextItemIndex(n);if(!this.isInterstitial(i[r])){var d;const t=null==(d=this.primaryDetails)?void 0:d.fragments;if(s.snapOptions.in&&t){const s=Kl(null,t,l);s&&(e=Math.min(Math.max(i[r].start,Yg(e,s)),i[r].end))}}if(this.log(sp("live join (preroll)",e)),this.timelinePos=e,r!==o&&(r||0===r))return void this.advanceSchedule(r,t,void 0,n,a)}this.advanceSchedule(o,t,e,n,a)}return}}this.advanceSchedule(t,i,e,n,a)}advanceSchedule(t,e,s,i,r){const n=this.schedule;if(!n)return;const a=e[t]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(e=>{const s=e.interstitial,i=n.findEventIndex(s.identifier);(i<t||i>t+1)&&this.clearInterstitial(s,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const r=a.event;if(void 0===s){const e=Xg(r,(s=r.cue.pre?0:n.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(e)||r.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(r,t,s);s=e}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let d=this.preloadAssets(r,s);if(this.eventItemsMatch(a,l||i)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${tp(a)} ${r.appendInPlace?"append in place":""}`),r.hasPlayed=!1,this.hls.trigger(zn.INTERSTITIAL_STARTED,{event:r,schedule:e.slice(0),scheduleIndex:t})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const c=r.assetList[s];if(!c)return void this.advanceAfterAssetEnded(r,t,s||0);if(d||(d=this.getAssetPlayer(c.identifier)),null===d||d.destroyed){const t=r.assetList.length;this.warn(`asset ${s+1}/${t} player destroyed ${r}`),d=this.createAssetPlayer(r,c,s),d.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(d,s,e,t,o),this.shouldPlay&&ep(d.media)}else a?(this.resumePrimary(a,t,i),this.shouldPlay&&ep(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var t;return null==(t=this.mediaSelection)?void 0:t.main.details}get primaryLive(){var t;return!(null==(t=this.primaryDetails)||!t.live)}resumePrimary(t,e,s){var i,r;this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(t),this.endedItem=null,this.log(`resuming ${tp(t)}`);let n=this.timelinePos;if(null!=(i=this.detachedData)&&i.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(n):((n<t.start||n>=t.end||n<this.seekableStart)&&(n=this.getPrimaryResumption(t,e),this.log(sp("resumePrimary",n)),this.timelinePos=n),this.attachPrimary(n,t)),!s)return;const a=null==(r=this.schedule)?void 0:r.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${tp(t)}`),this.hls.trigger(zn.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:e}),this.checkBuffer())}get seekableStart(){var t;return this.primaryLive&&(null==(t=this.primaryDetails)?void 0:t.fragmentStart)||0}getPrimaryResumption(t,e,s){const i=t.start;if(this.primaryLive){if(0===e)return this.hls.startPosition;const t=this.endedItem||this.playingItem,r=null!=t&&t.event?this.livePrerollResumption(t.event,s):void 0;if(void 0!==r)return r;const n=this.primaryDetails;if(n){const{fragmentStart:t,edge:e}=n;if(i<t||i>e&&!s){const s=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${i} [${t}-${e}]) snapping to liveSync ${s}`),s||t}}}return this.log(`primary resumption itemStart: ${i}`),i}getLiveStartPos(){var t;const e=this.hls.startPosition,s=this.hls.liveSyncPosition||0,i=3*((null==(t=this.primaryDetails)?void 0:t.targetduration)||10);return-1===e||s&&s-e<i?s||0:e}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);if(null!=e&&e.hls)return e.hls.bufferedToEnd;return BufferHelper.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,s){e?this.setBufferingItem(e):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(t,s)),s||(this.log(sp("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,s))}startLoadingPrimaryAt(t,e){const s=this.hls,{loadingEnabled:i,bufferingEnabled:r,startPosition:n}=s,a=s.hasEnoughToStart;if(this.log(`Start loading primary @${t} bufferedPos: ${this.bufferedPos} startPosition: ${n} skip seek: ${e} has enough ${a} loadingEnabled: ${i} bufferingEnabled: ${r}`),!e&&a||!i||Math.abs(n-t)>.1){const i=this.primaryDetails;if(null!=i&&i.live&&t+.5>=i.edge){const e=this.bufferingItem;return this.log(`Resume primary loading when live passes ${t} buffering item: ${e?tp(e):null}`),s.pauseBuffering(),void(this.bufferPastEdge=!0)}s.startLoad(t,e)}else r||s.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),null==(t=this.schedule)||t.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(zn.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(zn.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(-1===e.level||!this.schedule)return;const s=this.hls.levels[e.level];if(!s.details)return;const i=Aa(Aa({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i;const r=this.hls.startPosition;this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace,-1===r?0:r);if(this.schedule.items)if(this.effectivePlayingItem){if(this.bufferPastEdge){const t=this.primaryDetails,e=this.bufferedPos;if(null!=t&&t.live&&e+.5<t.edge){this.bufferPastEdge=!1;const s=this.bufferingItem;this.log(`Live edge ${t.edge} passed buffer: ${e} buffering item: ${s?tp(s):null}`);if((null==s?void 0:s.end)===1/0){const t=this.playingItem,i=this.isInterstitial(t)&&t.event.appendInPlace;this.hls.startLoad(Math.max(e,s.start),i)}else{const t=this.getBufferingPlayer();if(t){t.bufferedInPlaceToEnd(this.primaryMedia,t.currentTime)&&t.hls&&t.hls.trigger(zn.BUFFERED_TO_END,void 0)}}}}}else this.checkStart()}onAudioTrackUpdated(t,e){const s=this.hls.audioTracks[e.id],i=this.mediaSelection;if(!i)return void(this.altSelection=Aa(Aa({},this.altSelection),{},{audio:s}));const r=Aa(Aa({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(t,e){const s=this.hls.subtitleTracks[e.id],i=this.mediaSelection;if(!i)return void(this.altSelection=Aa(Aa({},this.altSelection),{},{subtitles:s}));const r=Aa(Aa({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(t,e){const s=Ml(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setAudioOption(e)||t.setAudioOption(s)))}onSubtitleTrackSwitch(t,e){const s=Ml(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setSubtitleOption(e)||-1!==e.id&&t.setSubtitleOption(s)))}onBufferCodecs(t,e){const s=e.tracks;s&&(this.requiredTracks=s)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const t=this.timelinePos;this.bufferedPos=t,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(let t=0;t<e.length;t++){const s=e[t];if(s.cue.post){const t=this.getEventItem(s.identifier);t&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){const e=this.playingItem;if(!this.playingLastItem&&e){const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}else this.shouldPlay=!1}updateItem(t,e){var s;const i=null==(s=this.schedule)?void 0:s.items;if(t&&i){return i[this.findItemIndex(t,e)]||null}return null}trimInPlace(t,e){if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach((e,s)=>{t.event.isAssetPastPlayoutLimit(s)&&this.clearAssetPlayer(e.identifier,null)});const s=t.end+.25,i=BufferHelper.bufferInfo(this.primaryMedia,s,0);if(i.end>s||(i.nextStart||0)>s){this.log(`trim buffered interstitial ${tp(t)} (was ${tp(e)})`);const i=!0;this.attachPrimary(s,null,i),this.flushFrontBuffer(s)}}}itemsMatch(t,e){return!!e&&(t===e||t.event&&e.event&&this.eventItemsMatch(t,e)||!t.event&&!e.event&&this.findItemIndex(t)===this.findItemIndex(e))}eventItemsMatch(t,e){var s;return!!e&&(t===e||t.event.identifier===(null==(s=e.event)?void 0:s.identifier))}findEventIndex(t){return this.schedule?this.schedule.findEventIndex(t):-1}getEventItem(t){if(this.schedule){var e;const s=null==(e=this.schedule.items)?void 0:e[this.findEventIndex(t)];if(this.isInterstitial(s)&&s.event.identifier===t)return s}}findItemIndex(t,e){return t&&this.schedule?this.schedule.findItemIndex(t,e):-1}updateSchedule(t=!1){var e,s;const i=this.mediaSelection;if(!i)return;const r=(null==(e=this.hls)?void 0:e.liveSyncPosition)||0;null==(s=this.schedule)||s.updateSchedule(i,[],r,t)}checkBuffer(t){var e;const s=null==(e=this.schedule)?void 0:e.items;if(!s)return;const i=BufferHelper.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=i.len<1),this.updateBufferedPos(i.end,s,t)}updateBufferedPos(t,e,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>t||!i)return;if(1===e.length&&this.itemsMatch(e[0],r))return void(this.bufferedPos=t);const n=this.playingItem,a=this.findItemIndex(n);let o=i.findItemIndexAtTime(t);if(this.bufferedPos<t){var l;const s=this.findItemIndex(r),i=Math.min(s+1,e.length-1),n=e[i];if((-1===o&&r&&t>=r.end||null!=(l=n.event)&&l.appendInPlace&&t+.01>=n.start)&&(o=i),this.isInterstitial(r)){const t=r.event;if(i-a>1&&!1===t.appendInPlace)return;if(0===t.assetList.length&&t.assetListLoader)return}if(this.bufferedPos=t,o>s&&o>a)this.bufferedToItem(n);else{const e=this.primaryDetails;this.primaryLive&&e&&t>e.edge-e.targetduration&&n.start<e.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else s&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(e[o]))}assetsBuffered(t,e){return 0!==t.event.assetList.length&&!t.event.assetList.some(t=>{const s=this.getAssetPlayer(t.identifier);return!(null!=s&&s.bufferedInPlaceToEnd(e))})}setBufferingItem(t){const e=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(t,e)&&s){const{items:i,events:r}=s;if(!i||!r)return e;const n=this.isInterstitial(t),a=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const o=a?a.remaining:e?e.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${tp(t)}`+(e?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const e=s.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((t,s)=>{const i=this.getAssetPlayer(t.identifier);i&&(s===e&&i.loadSource(),i.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(t=>t.pauseBuffering());this.hls.trigger(zn.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return e}bufferedToItem(t,e=0){const s=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==s){this.bufferingAsset=null;const e=this.getPrimaryResumption(t,this.findItemIndex(t),!0),s=this.bufferedPos=Math.max(e,Math.min(this.bufferedPos,t.end),this.timelinePos,t.start),i=this.detachedData;if(i)if(i.mediaSource){const e=!0;this.attachPrimary(s,t,e)}else this.startLoadingPrimaryAt(s);else{const t=this.playingItem,e=this.isInterstitial(t)&&t.event.appendInPlace;this.startLoadingPrimaryAt(s,e)}}}bufferedToEvent(t,e){const s=t.event,i=0===s.assetList.length&&!s.assetListLoader,r=s.cue.once;if(i||!r){const t=this.preloadAssets(s,e);if(null!=t&&t.interstitial.appendInPlace){const e=this.primaryMedia;e&&this.bufferAssetPlayer(t,e)}}}preloadAssets(t,e){const s=t.assetUrl,i=t.assetList.length,r=0===i&&!t.assetListLoader,n=t.cue.once;if(r){const r=t.timelineStart,n=this.playingItem,o=this.getBufferingPlayer();var a;if(t.appendInPlace)this.isInterstitial(n)||(null==n||null==(a=n.nextEvent)?void 0:a.identifier)!==t.identifier||this.flushFrontBuffer(r+.25);let l,d=0;if(o&&!o.interstitial.cue.pre||!this.primaryLive||(d=this.getLiveStartPos(),o&&(d+=o.remaining)),d&&!t.cue.pre&&!t.cue.post){const t=d-r;t>0&&(l=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${s?1:i} ${t}${d?` live-start: ${d} start-offset: ${l} (timeline-start: ${r})`:""}`),s)return this.createAsset(t,0,0,r,t.duration,s);const c=this.assetListLoader.loadAssetList(t,l);c&&(t.assetListLoader=c)}else if(!n&&i){for(let s=e;s<i;s++){const e=t.assetList[s],i=this.getAssetPlayerQueueIndex(e.identifier);-1!==i&&!this.playerQueue[i].destroyed||e.error||this.createAssetPlayer(t,e,s)}const s=t.assetList[e];if(s){const t=this.getAssetPlayer(s.identifier);return t&&t.loadSource(),t}}return null}flushFrontBuffer(t){const e=this.requiredTracks;if(!e)return;const s=this.primaryDetails;if(s&&t>=s.edge)return;this.log(`Removing front buffer starting at ${t}`);Object.keys(e).forEach(e=>{this.hls.trigger(zn.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:e})})}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let s=0;s<e.length;s++)if(t===e[s].assetId)return s;return-1}getAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);return this.playerQueue[e]||null}getBufferingPlayer(){const{playerQueue:t,primaryMedia:e}=this;if(e)for(let s=0;s<t.length;s++)if(t[s].media===e)return t[s];return null}createAsset(t,e,s,i,r,n){const a={parentIdentifier:t.identifier,identifier:Wg(t,n,e),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(t,a,e)}createAssetPlayer(t,e,s){const i=this.hls,r=i.userConfig,n=Gl(i.loadLevelObj||i.levels[i.currentLevel],r.videoPreference),a=i.audioTracks[i.audioTrack],o=i.subtitleTracks[i.subtitleTrack];let l=0;if(this.primaryLive||t.appendInPlace){const t=this.timelinePos-e.timelineStart;if(t>=0){const s=e.duration;s&&t<s&&(l=t)}}const d=e.identifier,c=Aa(Aa({},r),{},{maxMaxBufferLength:Math.min(15,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:l,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:a||r.audioPreference,subtitlePreference:o||r.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(c.timelineOffset=e.timelineStart));const h=c.cmcd;null!=h&&h.sessionId&&h.contentId&&(c.cmcd=Ta({},h,{contentId:dg(e.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${t} and asset ${d}`);const u=new HlsAssetPlayer(this.HlsPlayerClass,c,t,e);this.playerQueue.push(u),t.assetList[s]=e;let f=!0;const g=i=>{if(i.live){const e=new Error(`Interstitials MUST be VOD assets ${t}`),i={fatal:!0,type:Wn.OTHER_ERROR,details:Yn.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},r=this.findEventIndex(t.identifier);return void this.handleAssetItemError(i,t,r,s,e.message)}const r=i.edge-i.fragmentStart,n=e.duration;(f||null===n||r>n)&&(f=!1,this.log(`Interstitial asset "${d}" duration change ${n} > ${r}`),e.duration=r,this.updateSchedule())};u.on(zn.LEVEL_UPDATED,(t,{details:e})=>g(e)),u.on(zn.LEVEL_PTS_UPDATED,(t,{details:e})=>g(e)),u.on(zn.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const p=(t,e)=>{const s=this.getAssetPlayer(d);if(s&&e.tracks){s.off(zn.BUFFER_CODECS,p),s.tracks=e.tracks;const t=this.primaryMedia;this.bufferingAsset===s.assetItem&&t&&!s.media&&this.bufferAssetPlayer(s,t)}};u.on(zn.BUFFER_CODECS,p);u.on(zn.BUFFERED_TO_END,()=>{const e=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${e}`),!e||!this.schedule)return;const s=this.getEventItem(t.identifier);s&&this.advanceAssetBuffering(s,e.assetItem)});const m=e=>()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;this.shouldPlay=!0;const s=this.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,s,e)};return u.once(zn.MEDIA_ENDED,m(s)),u.once(zn.PLAYOUT_LIMIT_REACHED,m(1/0)),u.on(zn.ERROR,(e,i)=>{if(!this.schedule)return;const r=this.getAssetPlayer(d);if(i.details===Yn.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(t):(this.onTimeupdate(),void this.checkBuffer(!0));i.details!==Yn.BUFFER_SEEK_OVER_HOLE&&this.handleAssetItemError(i,t,this.findEventIndex(t.identifier),s,`Asset player error ${i.error} ${t}`)}),u.on(zn.DESTROYING,()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;const e=new Error(`Asset player destroyed unexpectedly ${d}`),i={fatal:!0,type:Wn.OTHER_ERROR,details:Yn.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(i,t,this.findEventIndex(t.identifier),s,e.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Zg(e)}`),this.hls.trigger(zn.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:s,event:t,player:u}),u}clearInterstitial(t,e){this.clearAssetPlayers(t,e),t.reset()}clearAssetPlayers(t,e){t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,e)})}resetAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);if(-1!==e){this.log(`reset asset player "${t}" after error`);const s=this.playerQueue[e];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(t,e){const s=this.getAssetPlayerQueueIndex(t);if(-1!==s){const t=this.playerQueue[s];this.log(`clear ${t} toSegment: ${e?tp(e):e}`),this.transferMediaFromPlayer(t,e),this.playerQueue.splice(s,1),t.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,s,i,r){const{interstitial:n,assetItem:a,assetId:o}=t,l=n.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(null==d?void 0:d.identifier)!==o&&(d&&(this.clearAssetPlayer(d.identifier,s[i]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${l} ${Zg(a)}`),this.hls.trigger(zn.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:e,event:n,schedule:s.slice(0),scheduleIndex:i,player:t})),this.bufferAssetPlayer(t,r)}bufferAssetPlayer(t,e){var s;if(!this.schedule)return;const{interstitial:i,assetItem:r}=t,n=this.getEventItem(i.identifier);if(!n)return;if(t.loadSource(),this.setBufferingItem(n),this.bufferingAsset=r,t.bufferedInPlaceToEnd(this.primaryMedia,t.currentTime))return void this.advanceAssetBuffering(n,r);const a=this.getBufferingPlayer();if(a===t)return;const o=i.appendInPlace;if(o&&!1===(null==a?void 0:a.interstitial.appendInPlace))return;const l=(null==a?void 0:a.tracks)||(null==(s=this.detachedData)?void 0:s.tracks)||this.requiredTracks;if(o&&r!==this.playingAsset){if(!t.tracks)return void this.log(`Waiting for track info before buffering ${t}`);if(l&&!$a(l,t.tracks)){const e=new Error(`Asset ${Zg(r)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(l)}')`),s={fatal:!0,type:Wn.OTHER_ERROR,details:Yn.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},n=i.findAssetIndex(r);return void this.handleAssetItemError(s,i,this.findEventIndex(i.identifier),n,e.message)}}this.transferMediaTo(t,e)}handleInPlaceStall(t){const e=this.schedule,s=this.primaryMedia;if(!e||!s)return;const i=s.currentTime,r=e.findAssetIndex(t,i),n=t.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||i-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${t} (media.currentTime: ${i})`),o&&(l/s.playbackRate<.5||a.bufferedInPlaceToEnd(s,a.currentTime))&&a.hls){const s=e.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,s,r)}}}}advanceInPlace(t){const e=this.primaryMedia;if(e&&e.currentTime<t){const s=`advance currentTime to ${t}, duration: ${e.duration}`;e.duration>t?(this.log(s),e.currentTime=t):this.log(`Cannot ${s}`)}}handleAssetItemError(t,e,s,i,r){if(t.details===Yn.BUFFER_STALLED_ERROR)return;const n=e.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n?Zg(n):n} ${t.error}`),!this.schedule)return;const a=(null==n?void 0:n.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,d=this.schedule.items,c=Ta({},t,{fatal:!1,errorAction:ad(!0),asset:n,assetListIndex:i,event:e,schedule:d,scheduleIndex:s,player:l});if(this.hls.trigger(zn.INTERSTITIAL_ASSET_ERROR,c),!t.fatal)return;const h=this.playingAsset,u=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(a,null),n.error=f),e.assetList.some(t=>!t.error))for(let t=i;t<e.assetList.length;t++)this.resetAssetPlayer(e.assetList[t].identifier);else e.error=f;this.updateSchedule(!0),e.error?this.primaryFallback(e):(null==h?void 0:h.identifier)===a?this.advanceAfterAssetEnded(e,s,i):(null==u?void 0:u.identifier)===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,u)}primaryFallback(t){const e=t.timelineStart,s=this.effectivePlayingItem,i=this.playingItem,r=this.seekableStart,n=this.hls.startPosition;let a=this.timelinePos;if(this.isInterstitial(s)){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${a} playing: ${tp(s)} startPosition: ${n} seekableStart: ${r} error: ${t.error}`),-1===a&&(a=n),a=Math.max(a,r);const i=this.updateItem(s,a);this.itemsMatch(s,i)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e))}else if(-1===a)return void this.checkStart();if(!this.schedule)return;if(!this.isInterstitial(i))return;const o=this.schedule.findItemIndexAtTime(a);this.setSchedulePosition(o)}onAssetListLoaded(t,e){var s,i;const r=e.event,n=r.identifier,a=e.assetListResponse.ASSETS;if(null==(s=this.schedule)||!s.hasEvent(n))return;const o=r.timelineStart,l=r.duration;let d=0;a.forEach((t,e)=>{const s=parseFloat(t.DURATION);this.createAsset(r,e,d,o+d,s,t.URI),d+=s}),r.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${l}) ${r}`);const c=this.waitingItem,h=(null==c?void 0:c.event.identifier)===n;this.updateSchedule();const u=null==(i=this.bufferingItem)?void 0:i.event;if(h){const t=this.findEventIndex(n),e=this.getEventItem(n);if(e){if(!this.playingItem&&this.timelinePos>e.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),void this.primaryFallback(r)}this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==u?void 0:u.identifier)===n){const t=r.assetList[0];if(t){const e=this.getAssetPlayer(t.identifier);if(u.appendInPlace){const t=this.primaryMedia;e&&t&&this.bufferAssetPlayer(e,t)}else e&&e.loadSource()}}}onError(t,e){if(this.schedule)switch(e.details){case Yn.ASSET_LIST_PARSING_ERROR:case Yn.ASSET_LIST_LOAD_ERROR:case Yn.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case Yn.BUFFER_STALLED_ERROR:{const t=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&t.event.appendInPlace)return void this.handleInPlaceStall(t.event);const e=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${null==e?void 0:e.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function _p(t,e,s){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"');if(void 0!==e.liveMaxUnchangedPlaylistRefresh){const t=e.liveMaxUnchangedPlaylistRefresh,a=(i=t,r=2,n=1/0,Math.max(r,Math.min(i,n)));a!==t&&s.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${t} to ${a}.`),e.liveMaxUnchangedPlaylistRefresh=a}var i,r,n;const a=bp(t),o=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const i=`${"level"===t?"playlist":t}LoadPolicy`,r=void 0===e[i],n=[];o.forEach(s=>{const o=`${t}Loading${s}`,l=e[o];if(void 0!==l&&r){n.push(o);const t=a[i].default;switch(e[i]={default:t},s){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}}}),n.length&&s.warn(`hls.js config: "${n.join('", "')}" setting(s) are deprecated, use "${i}": ${Dl(e[i])}`)}),Aa(Aa({},a),e)}function bp(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(bp):Object.keys(t).reduce((e,s)=>(e[s]=bp(t[s]),e),{}):t}function Lp(t,e){const s=t.loader;if(s!==FetchLoader&&s!==XhrLoader)e.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,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class LevelController extends BasePlaylistController{constructor(t,e){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.on(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(zn.FRAG_BUFFERED,this.onFragBuffered,this),t.on(zn.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.off(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(zn.FRAG_BUFFERED,this.onFragBuffered,this),t.off(zn.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let a=!1,o=!1,l=!1,d=!1;e.levels.forEach(t=>{const e=t.attrs,c=kp(t,s),{audioCodec:h,videoCodec:u,imageCodec:f,width:g,height:p}=t;if(!c)return void this.log(`Some or all CODECS not supported "${e.CODECS}"`);a||(a=!(!g||!p)),o||(o=!!u),l||(l=!!h),d||(d=!!f);const{CODECS:m,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=e,A=`${`${E||"."}-`}${t.bitrate}-${T}-${v}-${m}-${S}-${y}`;if(r[A])if(r[A].uri===t.url||t.attrs["PATHWAY-ID"])t.iframes||(r[A].addGroupId("audio",e.AUDIO),r[A].addGroupId("text",e.SUBTITLES));else{const e=n[A]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const s=this.createLevel(t);r[A]=s,i.push(s)}else{const e=this.createLevel(t);r[A]=e,n[A]=1,i.push(e)}}),this.filterAndSortMediaOptions(i,e,a,o,l,d)}createLevel(t){const e=new Level(t),s=t.supplemental;if(null!=s&&s.videoCodec&&!Ip(s.videoCodec,this.hls.config.preferManagedMediaSource)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(t.message),e.supportedResult=vl(t,[])}return e}filterAndSortMediaOptions(t,e,s,i,r,n){var a;let o=[],l=[],d=t;const c=(null==(a=e.stats)?void 0:a.parsing)||{},h=this.hls.config.preferManagedMediaSource;if((s||i)&&r&&(d=d.filter(({videoCodec:t,videoRange:e,width:s,height:i})=>{return(!!t||!(!s||!i))&&(!!(r=e)&&bl.indexOf(r)>-1);var r})),i&&n&&(d=d.filter(t=>!t.imageCodec)),0===d.length)return Promise.resolve().then(()=>{if(this.hls){let t="no level with compatible codecs found in manifest",s=t;e.levels.length&&(s=`one or more CODECS in variant not supported: ${Dl(e.levels.map(t=>t.attrs.CODECS).filter((t,e,s)=>s.indexOf(t)===e))}`,this.warn(s),t+=` (${s})`);const i=new Error(t);this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:i,reason:s})}}),void(c.end=performance.now());e.audioTracks&&(o=e.audioTracks.filter(t=>!t.audioCodec||Rp(t.audioCodec,h)),wp(o)),e.subtitles&&(l=e.subtitles,wp(l));const u=d.slice(0);d.sort((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return bl.indexOf(t.videoRange)-bl.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const s=nl(t.videoCodec),i=nl(e.videoCodec);if(s!==i)return i-s}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const s=al(t.codecSet),i=al(e.codecSet);if(s!==i)return i-s}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0});let f=u[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==u.length))for(let t=0;t<u.length;t++)if(u[t].pathwayId===d[0].pathwayId){f=u[t];break}this._levels=d;for(let t=0;t<d.length;t++)if(d[t]===f){var g;this._firstLevel=t;const e=f.bitrate,s=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${e}`),void 0===(null==(g=this.hls.userConfig)?void 0:g.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>s&&s===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const p=e.iframeVariants.filter(t=>kp(t,h));this._iframeVariants=p;const m=r&&!i,v=this.hls.config,y=!(!v.audioStreamController||!v.audioTrackController),E={levels:d,audioTracks:o,subtitleTracks:l,iframeVariants:p,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:i,altAudio:y&&!m&&o.some(t=>!!t.url)};c.end=performance.now(),this.hls.trigger(zn.MANIFEST_PARSED,E)}get iframeVariants(){return 0===this._iframeVariants.length?null:this._iframeVariants}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}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"),i=t<0;if(this.hls.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.LEVEL_SWITCH_ERROR,level:t,fatal:i,error:s,reason:s.message}),i)return;t=Math.min(t,e.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,s===t&&i&&r===a)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${r?" with Pathway "+r:""}`);const o={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(zn.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==i?void 0:i.details,l);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.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),s=t.filter(t=>-1!==e.indexOf(t));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);this.steering.pathwayPriority=s}}onError(t,e){!e.fatal&&e.context&&e.context.type===ea&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(e.type===da){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return;const s=this._levels[e.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(t,e){var s;const{level:i,details:r}=e,n=e.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||e.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let t=n.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(i,e,t)}else null!=(s=e.deliveryDirectives)&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=this.getUrlWithDirectives(t.uri,e),i=this.currentLevelIndex,r=t.attrs["PATHWAY-ID"],n=t.details,a=null==n?void 0:n.age;this.log(`Loading level index ${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger(zn.LEVEL_LOADING,{url:s,level:i,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){const e=this.currentLevelIndex;if(-1===this.manualLevelIndex&&t!==e&&-1!==t){const s=this.hls.config.abrSwitchInterval;if(s>0){const i=performance.now(),r=i-this.lastABRSwitchTime,n=1e3*s;if(this.lastABRSwitchTime>-1&&r<n)return void this.warn(`Preventing ABR level switch: ${e} -> ${t} (${Math.round(r)}ms < ${n}ms / ${s}s)`);this.lastABRSwitchTime=i,this.log(`Allowing ABR level switch: ${e} -> ${t} (${Math.round(r)}ms >= ${n}ms / ${s}s)`)}}this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(1===this._levels.length)return;const s=this._levels.filter((e,s)=>s!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach(t=>t.level=-1)),!1));bc(s),this._levels=s,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(zn.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(zn.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function Rp(t,e){return sl(t,"audio",e)}function Ip(t,e){return sl(t,"video",e)}function kp(t,e){let{audioCodec:s,videoCodec:i}=t;s&&(t.audioCodec=s=dl(s,e)||void 0),i&&(i=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&"avc1"===s[0]&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}(i));const{unknownCodecs:r}=t;return!((null==r?void 0:r.length)||0||s&&!Rp(s,e)||i&&!Ip(i,e))}function wp(t){const e={};t.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}class KeyLoader extends Logger{constructor(t,e){super("key-loader",e),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=t}abort(t){for(const s in this.keyLoaderInfo){const i=this.keyLoaderInfo[s].loader;if(i){var e;if(t&&t!==(null==(e=i.context)?void 0:e.frag.type))return;i.abort()}}}destroy(){for(const t in this.keyLoaderInfo){const e=this.keyLoaderInfo[t].loader;e&&e.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(t,e,s){return this.emeController?this.emeController.loadClear(t,e,s):null}load(t,e){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(s=>this.loadInternal(t,e,s)):this.loadInternal(t,e)}loadInternal(t,e,s){s&&t.setKeyFormat(s);const i=t.decryptdata;if(!i){const e=new Error(s?`Expected frag.decryptdata to be defined after setting format ${s}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Pp(t,Yn.KEY_LOAD_ERROR,e))}const r=t;switch(i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===i.keyFormat?this.loadKeyHTTP(r):e?e.then(()=>this.loadKeyEME(r)):this.loadKeyEME(r);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(r);default:return Promise.reject(Pp(t,Yn.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(t){if(this.emeController&&this.config.emeEnabled){var e;if(!t.decryptdata.keyId&&null!=(e=t.initSegment)&&e.data){const e=function(t){const e=[];return Oo(t,t=>e.push(t.subarray(8,24))),e}(t.initSegment.data);if(e.length){let s=e[0];const i=t.decryptdata.uri;if(s.some(t=>0!==t))this.log(`Using keyId found in init segment ${oo(s)} keyUri: ${i}`),LevelKey.setKeyIdForUri(i,s);else{const t=LevelKey.addKeyIdForUri(i);this.log(`Patching empty keyId with ${oo(t)} keyUri: ${i}`),s=t}t.decryptdata.keyId=s}}return this.emeController.loadKey(t).then(()=>({frag:t,keyInfo:{decryptdata:t.decryptdata}}))}return Promise.reject(Pp(t,Yn.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(t){const e=t.decryptdata,s=e.uri;if(!s)return Promise.reject(Pp(t,Yn.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${s}"`)));const i=this.keyLoaderInfo[s];if(i){if(i.decryptdata.key)return e.key=i.decryptdata.key,i.keyLoadPromise=null,Promise.resolve({frag:t,keyInfo:i});if(i.keyLoadPromise)return i.keyLoadPromise.then(s=>(e.key=i.decryptdata.key,Aa(Aa({},s),{},{frag:t})))}this.log(`Loading${e.keyId?" keyId: "+oo(e.keyId):""} URI: ${e.uri} from ${t.type} ${t.level}`);const r=this.config,n=new(0,r.loader)(r);t.keyLoader=n;const a=this.keyLoaderInfo[s]={decryptdata:e,keyLoadPromise:null,loader:n};return a.keyLoadPromise=new Promise((e,i)=>{const o={type:na,keyInfo:a,frag:t,responseType:"arraybuffer",url:s},l=r.keyLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,s,r,n)=>{const{frag:a,keyInfo:o,url:l}=r;if(!a.decryptdata||o!==this.keyLoaderInfo[l])return i(Pp(a,Yn.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),n));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=o.loader=o.keyLoadPromise=null,e({frag:a,keyInfo:o})},onError:(e,r,n,a)=>{this.resetLoader(r),i(Pp(t,Yn.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),n,Aa({url:s,data:void 0},e)))},onTimeout:(e,s,r)=>{this.resetLoader(s),i(Pp(t,Yn.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(e,s,r)=>{this.resetLoader(s),i(Pp(t,Yn.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};n.load(o,d,c)})}resetLoader(t){const{frag:e,keyInfo:s,url:i}=t,r=s.loader;e.keyLoader===r&&(e.keyLoader=s.loader=s.keyLoadPromise=null),delete this.keyLoaderInfo[i],r&&r.destroy()}}function Pp(t,e=Yn.KEY_LOAD_ERROR,s,i,r){return new LoadError({type:Wn.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:r,error:s,networkDetails:i||null})}function Dp(t){const{type:e}=t;switch(e){case sa:return ca;case ia:return ha;default:return da}}function Cp(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.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.LEVEL_LOADING,this.onLevelLoading,this),t.on(zn.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(zn.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(zn.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.LEVEL_LOADING,this.onLevelLoading,this),t.off(zn.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(zn.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(zn.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,s=e.pLoader,i=e.loader,r=new(s||i)(e);return this.loaders[t.type]=r,r}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:ta,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=e;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:ea,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:sa,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:ia,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){const s=this.loaders[ea];if(s){const t=s.context;t&&!e.levels.some(e=>e===t.levelOrTrack)&&(s.abort(),delete this.loaders[ea])}}load(t){var e;const s=this.hls.config;let i,r=this.getInternalLoader(t);if(r){const e=this.hls.logger,s=r.context;if((null==s?void 0:s.levelOrTrack)===t.levelOrTrack&&(s.url===t.url||s.deliveryDirectives&&!t.deliveryDirectives))return void(s.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${s.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),r.abort()}if(i=t.type===ta?s.manifestLoadPolicy.default:Ta({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(t),Vn(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===ea&&null!==t.level?e=this.hls.levels[t.level].details:t.type===sa&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===ia&&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);i=Ta({},i,{maxTimeToFirstByteMs:Math.min(e,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,i.maxTimeToFirstByteMs)})}}}const n=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(t,e,s,i)=>{const r=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=t.data;e.parsing.start=performance.now(),M3U8Parser.isMediaPlaylist(n)||s.type!==ta?this.handleTrackOrLevelPlaylist(t,e,s,i||null,r):this.handleMasterPlaylist(t,e,s,i)},onError:(t,e,s,i)=>{this.handleNetworkError(e,s,!1,t,i)},onTimeout:(t,e,s)=>{this.handleNetworkError(e,s,!0,void 0,t)}};r.load(t,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:s}=this.hls;(t||s)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,s,i){const r=this.hls,n=t.data,a=Cp(t,s),o=M3U8Parser.parseMasterPlaylist(n,a);if(o.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,s,o.playlistParsingError,i,e);const{contentSteering:l,levels:d,iframeVariants:c,sessionData:h,sessionKeys:u,startTimeOffset:f,variableList:g}=o;this.variableList=g,d.forEach(t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:s}=this.hls.config;let{audioCodec:i,videoCodec:r}=t;for(let n=e.length;n--;){const a=e[n];sl(a,"audio",s)?(t.audioCodec=i=i?`${i},${a}`:a,tl.audio[i.substring(0,4)]=2,e.splice(n,1)):sl(a,"video",s)&&(t.videoCodec=r=r?`${r},${a}`:a,tl.video[r.substring(0,4)]=2,e.splice(n,1))}}});const{AUDIO:p=[],SUBTITLES:m,"CLOSED-CAPTIONS":v}=M3U8Parser.parseMasterPlaylistMedia(n,a,o);if(p.length){p.some(t=>!t.url)||!d[0].audioCodec||d[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new AttrList({}),bitrate:0,url:""}))}r.trigger(zn.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:m,iframeVariants:c,captions:v,contentSteering:l,url:a,stats:e,networkDetails:i,sessionData:h,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(t,e,s,i,r){const n=this.hls,{id:a,level:o,type:l}=s,d=Cp(t,s),c=Vn(o)?o:Vn(a)?a:0,h=Dp(s),u=M3U8Parser.parseLevelPlaylist(t.data,d,c,h,0,this.variableList);if(l===ta){const t={attrs:new AttrList({}),bitrate:0,details:u,name:"",url:d};u.requestScheduled=e.loading.start+Tc(u,0),n.trigger(zn.MANIFEST_LOADED,{levels:[t],audioTracks:[],iframeVariants:[],url:d,stats:e,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),s.levelDetails=u,this.handlePlaylistLoaded(u,t,e,s,i,r)}handleManifestParsingError(t,e,s,i,r){this.hls.trigger(zn.ERROR,{type:Wn.NETWORK_ERROR,details:Yn.MANIFEST_PARSING_ERROR,fatal:e.type===ta,url:t.url,err:s,error:s,reason:s.message,response:t,context:e,networkDetails:i,stats:r})}handleNetworkError(t,e,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${t.type}`;t.type===ea?n+=`: ${t.level} id: ${t.id}`:t.type!==sa&&t.type!==ia||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=Yn.UNKNOWN,l=!1;const d=this.getInternalLoader(t);switch(t.type){case ta:o=s?Yn.MANIFEST_LOAD_TIMEOUT:Yn.MANIFEST_LOAD_ERROR,l=!0;break;case ea:o=s?Yn.LEVEL_LOAD_TIMEOUT:Yn.LEVEL_LOAD_ERROR,l=!1;break;case sa:o=s?Yn.AUDIO_TRACK_LOAD_TIMEOUT:Yn.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ia:o=s?Yn.SUBTITLE_TRACK_LOAD_TIMEOUT:Yn.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(t.type);const c={type:Wn.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:d,context:t,error:a,networkDetails:e,stats:r};if(i){let s=t.url;e&&"url"in e&&(s=e.url),c.response=Aa({url:s,data:void 0},i)}this.hls.trigger(zn.ERROR,c)}handlePlaylistLoaded(t,e,s,i,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:d,id:c,groupId:h,deliveryDirectives:u}=i,f=Cp(e,i),g=Dp(i);let p="number"==typeof i.level&&g===da?l:void 0;d&&"iframes"in d&&d.iframes&&!t.iframesOnly&&(t.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),t.iframesOnly=!0);const m=t.playlistParsingError;if(m){if(this.hls.logger.warn(`${m} ${t.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(zn.ERROR,{type:Wn.NETWORK_ERROR,details:Yn.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:m,reason:m.message,response:e,context:i,level:p,parent:g,networkDetails:r,stats:s});t.playlistParsingError=null}if(!t.fragments.length){const n=t.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(zn.ERROR,{type:Wn.NETWORK_ERROR,details:Yn.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:e,context:i,level:p,parent:g,networkDetails:r,stats:s})}switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case ta:case ea:if(p)if(d){if(d!==a.levels[p]){const t=a.levels.indexOf(d);t>-1&&(p=t)}}else p=0;a.trigger(zn.LEVEL_LOADED,{details:t,levelInfo:d||a.levels[0],level:p||0,id:c||0,stats:s,networkDetails:r,deliveryDirectives:u,withoutMultiVariant:o===ta,context:i});break;case sa:a.trigger(zn.AUDIO_TRACK_LOADED,{details:t,track:d,id:c||0,groupId:h||"",stats:s,networkDetails:r,deliveryDirectives:u,context:i});break;case ia:a.trigger(zn.SUBTITLE_TRACK_LOADED,{details:t,track:d,id:c||0,groupId:h||"",stats:s,networkDetails:r,deliveryDirectives:u,context:i})}}}class Hls{static get version(){return Zc}static isMSESupported(){return Ng()}static isSupported(){return function(){if(!Ng())return!1;const t=Ba();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(rl(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(rl(e,"audio"))))}()}static getMediaSource(){return Ba()}static get Events(){return zn}static get MetadataSchema(){return lh}static get ErrorTypes(){return Wn}static get ErrorDetails(){return Yn}static get DefaultConfig(){return Hls.defaultConfig?Hls.defaultConfig:Ap}static set DefaultConfig(t){Hls.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Xc,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const e=this.logger=function(t,e,s){const i=xa();if("object"==typeof console&&!0===t||"object"==typeof t){const r=["debug","log","info","warn","error"];r.forEach(e=>{i[e]=Fa(e,t,s)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.7.2`)}catch(t){return xa()}r.forEach(e=>{Na[e]=Fa(e,t)})}else Ta(Na,i);return i}(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),s=this.config=_p(Hls.DefaultConfig,t,e);this.userConfig=t,s.progressive&&Lp(s,e);const{streamController:i,abrController:r,bufferController:n,capLevelController:a,errorController:o,fpsController:l,id3TrackController:d,iframeController:c,gapController:h}=s,u=new o(this),f=this.abrController=new r(this),g=new FragmentTracker(this),p=s.interstitialsController,m=p?this.interstitialsController=new p(this,Hls):null,v=n?this.bufferController=new n(this,g):null,y=a?this.capLevelController=new a(this):null,E=l?new l(this):null,T=s.cmcdController,S=T?this.cmcdController=new T(this):null,A=new PlaylistLoader(this),_=s.contentSteeringController,b=_?new _(this):null,L=this.levelController=new LevelController(this,b),R=d?new d(this):void 0,I=new KeyLoader(this.config,this.logger),k=this.streamController=new i(this,g,I),w=this.gapController=h?new h(this,g):void 0;y&&y.setStreamController(k);const P=[A,L,k];m&&P.splice(1,0,m),b&&P.splice(1,0,b),this.networkControllers=P;const D=[f];v&&D.push(v),w&&D.push(w),y&&D.push(y),E&&(E.setStreamController(k),D.push(E)),R&&D.push(R),D.push(g),this.audioTrackController=this.createController(s.audioTrackController,P);const C=s.audioStreamController;C&&P.push(this.audioStreamController=new C(this,g,I)),this.subtitleTrackController=this.createController(s.subtitleTrackController,P);const O=s.subtitleStreamController;O&&P.push(this.subtititleStreamController=new O(this,g,I)),this.createController(s.timelineController,D),I.emeController=this.emeController=this.createController(s.emeController,D),S&&D.push(S),this.latencyController=this.createController(s.latencyController,D),this.coreComponents=D,this.iframeController=c?new c(this,Hls):void 0,P.push(u);const M=u.onErrorOut;"function"==typeof M&&this.on(zn.ERROR,M,u),this.on(zn.MANIFEST_LOADED,A.onManifestLoaded,A)}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,i){this._emitter.off(t,e,s,i)}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){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const s=t===zn.ERROR;this.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.INTERNAL_EXCEPTION,fatal:s,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(zn.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,this.iframeController=void 0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const e=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,s=e?t.media:t,i=e?t:{media:s};this._media=s,this.trigger(zn.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia");const t={};this.trigger(zn.MEDIA_DETACHING,t),this._media=null,this.trigger(zn.MEDIA_DETACHED,t)}transferMedia(){var t;this._media=null;const e=(null==(t=this.bufferController)?void 0:t.transferMedia())||null,s={transferMedia:e};return this.trigger(zn.MEDIA_DETACHING,s),this.trigger(zn.MEDIA_DETACHED,s),e}loadSource(t){var e;this.stopLoad();const s=this.media,i=this._url,r=this._url=Jn.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),s&&i&&(i!==r||null!=(e=this.bufferController)&&e.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(s)),this.trigger(zn.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(t,e),this.started&&this.networkControllers);s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started&&this.streamController.state!==Mc}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[da]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[ca]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[ha]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=this.started,s=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&(s?this.startLoad(s):this.config.autoStartLoad||this.startLoad()))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=qa()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.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){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.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=this.capLevelController,s=!!t;e&&s!==this.config.capLevelToPlayerSize&&(s?e.startCapping():(e.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=s)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return _l.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}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 i=0;i<s;i++)if(t[i].maxBitrate>=e)return i;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:s}=this;let i;if(i=-1===e&&null!=t&&t.length?t.length-1:e,s)for(let e=i;e--;){const i=t[e].attrs["HDCP-LEVEL"];if(i&&i<=s)return e}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var t;return(null==(t=this.audioStreamController)?void 0:t.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}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 nextAudioTrack(){var t,e;return null!=(t=null==(e=this.audioStreamController)?void 0:e.nextAudioTrack)?t:-1}set nextAudioTrack(t){const{audioTrackController:e}=this;e&&(e.nextAudioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}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(){var t,e;return null!=(t=null==(e=this.latencyController)?void 0:e.liveSyncPosition)?t:null}get latency(){var t;return(null==(t=this.latencyController)?void 0:t.latency)||0}get maxLatency(){var t;return(null==(t=this.latencyController)?void 0:t.maxLatency)||0}get targetLatency(){var t;return(null==(t=this.latencyController)?void 0:t.targetLatency)||null}set targetLatency(t){this.latencyController&&(this.latencyController.targetLatency=t)}get drift(){var t;return(null==(t=this.latencyController)?void 0:t.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){const t=this.levelController.iframeVariants;return t||[]}createIFramePlayer(t){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(t):null}createImageIFramePlayer(t){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(t):null}getMediaDecodingInfo(t,e=this.allAudioTracks){return El(t,Ol(e),navigator.mediaCapabilities)}}Hls.defaultConfig=void 0;const Op="hls:attached",Mp="hls:buffer_check";var xp=Object.freeze({__proto__:null,ATTACHED:Op,BUFFER_CHECK_TICK:Mp});const Fp="application/vnd.apple.mpegURL",Np=[Fp,"application/x-mpegurl"],Up=document.createElement("video").canPlayType(Fp);function Bp({src:t="",type:e="",drm:i},r){const n=null==r?void 0:r.hls,a=Boolean(null==n?void 0:n.native);return(!Up||!a)&&(!(i&&!Object.keys(i).find(t=>function(t){const e=s();switch(t){case"com.widevine.alpha":return e.chrome||e.firefox||e.edge||e.opera;case"org.w3.clearkey":return e.chrome||e.firefox;case"com.apple.fps.1_0":return e.safari;case"com.microsoft.playready":return e.edge}}(t)))&&(!(!e||!Np.includes(e))||function(t){const{pathname:e}=vi(t);return e.endsWith(".m3u8")}(t)))}const $p=window&&window.Hls||Hls;var Gp;!function(t){t[t.FRAGMENT_ERRORS=0]="FRAGMENT_ERRORS",t[t.STALE_MANIFEST=1]="STALE_MANIFEST"}(Gp||(Gp={}));const Hp=ci("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,s;this.reset();const i=this.hls;if(!i)return;const r=i.levelController,n=i.streamController,a=r.steering;if(!r||!n||!a)return;const o=r.currentLevel;if(!o)return;const l=a.levels.filter(t=>t.pathwayId!==o.pathwayId);l.length&&(null===(e=i.media)||void 0===e||e.dispatchEvent(new CustomEvent("hls/failover",{detail:{reason:t,from:null===(s=o.details)||void 0===s?void 0:s.url}})),r._levels=n.levels=l)}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 i=null===(t=s.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 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||(Hp(`${t} / no change in ${s.count} tries`,this.playlistCounts),this.failover(Gp.STALE_MANIFEST)))}trackFragmentError(t){const e=this.fragmentFailures[t]||0;this.fragmentFailures[t]=e+1,this.fragmentFailures[t]>2&&this.failover(Gp.FRAGMENT_ERRORS)}createPlaylistLoader(t){const e=this;return class extends Hls.DefaultConfig.loader{load(s,i,r){const n=r.onSuccess;r.onSuccess=({data:i,url:r},...a)=>{"manifest"===(null==s?void 0:s.type)&&(t.manifest=i),e.ensurePlaylistUpdating(r,i),n({data:i,url:r},...a)},super.load(s,i,r)}}}createFragmentLoader(){const t=this;return class extends Hls.DefaultConfig.loader{load(e,s,i){const r=i.onError;i.onError=e=>{t.trackFragmentError(e.url),r(...arguments)},super.load(e,s,i)}}}}const Kp="audio:tracks";const Vp="tracks:text:all";const jp=ci("hls");function qp(t){switch(t){case Yn.KEY_SYSTEM_NO_KEYS:return De.ContentProtectionKeySystemNoKeys;case Yn.KEY_SYSTEM_NO_ACCESS:return De.ContentProtectionKeySystemNoAccess;case Yn.KEY_SYSTEM_NO_SESSION:return De.ContentProtectionKeySystemNoSession;case Yn.KEY_SYSTEM_NO_CONFIGURED_LICENSE:return De.ContentProtectionKeySystemNoConfiguredLicense;case Yn.KEY_SYSTEM_LICENSE_REQUEST_FAILED:return De.ContentProtectionCDMLicenseRequestFailed;case Yn.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED:return De.ContentProtectionServerCertificateRequestFailed;case Yn.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED:return De.ContentProtectionKeySystemCertificateUpdateFailed;case Yn.KEY_SYSTEM_SESSION_UPDATE_FAILED:return De.ContentProtectionKeySystemSessionUpdateFailed;case Yn.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return De.ContentProtectionKeySystemStatusOutputRestricted;case Yn.KEY_SYSTEM_STATUS_INTERNAL_ERROR:return De.ContentProtectionKeySystemStatusInternalError;case Yn.MANIFEST_LOAD_ERROR:return De.PlaybackManifestLoadError;case Yn.MANIFEST_LOAD_TIMEOUT:return De.PlaybackManifestLoadTimeout;case Yn.MANIFEST_PARSING_ERROR:return De.PlaybackManifestParsingError;case Yn.MANIFEST_INCOMPATIBLE_CODECS_ERROR:return De.PlaybackManifestIncompatibleCodecs;case Yn.LEVEL_EMPTY_ERROR:return De.PlaybackLevelEmptyError;case Yn.LEVEL_LOAD_ERROR:return De.PlaybackLevelLoadError;case Yn.LEVEL_LOAD_TIMEOUT:return De.PlaybackLevelLoadTimeout;case Yn.LEVEL_PARSING_ERROR:return De.PlaybackManifestParsingError;case Yn.LEVEL_SWITCH_ERROR:return De.PlaybackLevelSwitchError;case Yn.AUDIO_TRACK_LOAD_ERROR:return De.PlaybackAudioTrackLoadError;case Yn.AUDIO_TRACK_LOAD_TIMEOUT:return De.PlaybackAudioTrackLoadTimeout;case Yn.SUBTITLE_LOAD_ERROR:return De.NetworkDownloadErrorIdContent;case Yn.SUBTITLE_TRACK_LOAD_TIMEOUT:return De.NetworkRequestTimeout;case Yn.FRAG_LOAD_ERROR:return De.PlaybackFragLoadError;case Yn.FRAG_LOAD_TIMEOUT:return De.PlaybackFragLoadTimeout;case Yn.FRAG_DECRYPT_ERROR:return De.PlaybackFragDecryptError;case Yn.FRAG_PARSING_ERROR:return De.PlaybackFragParsingError;case Yn.FRAG_GAP:return De.PlaybackFragGap;case Yn.REMUX_ALLOC_ERROR:return De.PlaybackRemuxAllocError;case Yn.KEY_LOAD_ERROR:return De.ContentProtectionKeyLoadError;case Yn.KEY_LOAD_TIMEOUT:return De.ContentProtectionKeyLoadTimeout;case Yn.BUFFER_ADD_CODEC_ERROR:return De.PlaybackBufferAddCodecError;case Yn.BUFFER_INCOMPATIBLE_CODECS_ERROR:return De.PlaybackBufferIncompatibleCodecs;case Yn.BUFFER_APPEND_ERROR:return De.PlaybackBufferAppendError;case Yn.BUFFER_APPENDING_ERROR:return De.PlaybackAppendError;case Yn.BUFFER_STALLED_ERROR:return De.PlaybackBufferStalledError;case Yn.BUFFER_FULL_ERROR:return De.PlaybackBufferFullError;case Yn.BUFFER_SEEK_OVER_HOLE:return De.PlaybackBufferSeekOverHole;case Yn.BUFFER_NUDGE_ON_STALL:return De.PlaybackBufferNudgeOnStall;case Yn.INTERNAL_EXCEPTION:return De.PlaybackInternalException;case Yn.INTERNAL_ABORTED:return De.PlaybackInternalAborted;case Yn.UNKNOWN:default:return De.Unknown}}function Wp(t,e,s){const i={},r={error_type:e.type,resource:e.url||t.original_src,isFatal:e.fatal};return e.fatal?(e.type===s.ErrorTypes.MEDIA_ERROR&&(r.showErrorUI=!1,i.retry=hi,i.retryTimeout=0),[s.ErrorTypes.KEY_SYSTEM_ERROR,s.ErrorTypes.MUX_ERROR,s.ErrorTypes.OTHER_ERROR].includes(e.type)&&(i.retry=fi),Object.assign(r,{retryOpts:i})):(i.retry=fi,Object.assign(r,{retryOpts:i}))}function Yp(t,e){e.on($p.Events.ERROR,function(e,s){var i;0!=t.reaper&&(!function(t,e,s){t.emit(at,{error:new FlowplayerError(e.error.message,qp(e.details),Wp(t,e,s))})}(t,s,$p),s.fatal&&([$p.ErrorTypes.NETWORK_ERROR,$p.ErrorTypes.MEDIA_ERROR].includes(s.type)||null===(i=t.hls)||void 0===i||i.destroy()))})}function zp(t,e){var s;!t.hasState(Vt)&&t.setState(jt,!0),null===(s=t.hls)||void 0===s||s.startLoad(e)}function Qp(t,e){if("object"==typeof t&&"object"==typeof e&&"number"==typeof t.bitrate&&"number"==typeof e.bitrate)return t.bitrate<e.bitrate}function Xp(t){const e=t.map((t,e)=>Object.assign(t,{level:e})).sort((t,e)=>e.width-t.width);return t.length>1&&t.every(t=>void 0!==t.bitrate)&&e.push({name:"AUTO",level:-1,width:0,height:0}),e}function Zp(t,e,s,i,r){let n;t.once(Hls.Events.LEVEL_LOADING,function(){e.emit(nt)}),t.on($p.Events.MANIFEST_PARSED,function(t,n){const a=Xp(n.levels);e.emit(U,a),e.emit("parse:video:tracks",{url:r.src,manifest:i.manifest}),function(t,e,s){if(!t.hls)return;jp("Initializer::maybe_start_load_with_quality (start_quality, preload): (%d, %s)",e.start_quality,e.preload),void 0!==e.start_quality&&s.length&&(ke.HIGH&e.start_quality&&(t.hls.startLevel=s[0].level),ke.LOW&e.start_quality&&(t.hls.startLevel=s[s.length-1].level),ke.MEDIUM&e.start_quality&&(t.hls.startLevel=s[Math.ceil(s.length/2)-1].level));(function(t,e){var s,i,r,n,a,o;if(!e.hls)return;if(null===(s=t.hls)||void 0===s?void 0:s.adaptive_buffer_control){const s=10,i=10,r=!0!==t.hls.adaptive_buffer_control&&t.hls.adaptive_buffer_control.initial_buffer_length?t.hls.adaptive_buffer_control.initial_buffer_length:s;!function(t,e){var s;const i=500,r=null===(s=t.hls)||void 0===s?void 0:s.config.maxBufferLength;let n=!1;const a=setInterval(()=>{t.emit(Mp)},i),o=()=>{n||t.currentTime>e&&(n=!0,t.hls&&r&&(t.hls.config.maxBufferLength=r))};t.on(F,()=>{clearInterval(a),t.off(Mp,o)}),t.on(Mp,o)}(e,!0!==(null===(n=t.hls)||void 0===n?void 0:n.adaptive_buffer_control)&&t.hls.adaptive_buffer_control.restore_buffer_player_time_threshold?null===(a=t.hls)||void 0===a?void 0:a.adaptive_buffer_control.restore_buffer_player_time_threshold:i),Jp(t,e,{maxBufferLength:r,maxBufferSize:null===(o=t.hls)||void 0===o?void 0:o.maxBufferSize})}else Jp(t,e,{maxBufferLength:null===(i=t.hls)||void 0===i?void 0:i.maxBufferLength,maxBufferSize:null===(r=t.hls)||void 0===r?void 0:r.maxBufferSize})})(e,t),("none"!==e.preload||e.autoplay&&t.hasState(ge))&&!t.hls.config.autoStartLoad&&zp(t,e.start_time||-1)}(e,s,a.slice(0,-1));const o=a.find(t=>t.videoCodec);!e.opt("ratio")&&o&&0!=o.width&&0!=o.height&&e.setOpts({ratio:o.width+":"+o.height})}),t.on($p.Events.LEVEL_SWITCHING,(s,i)=>{if(t.nextLoadLevel===n)return;n=t.nextLoadLevel;const r=t.levels[t.currentLevel],a=t.levels[i.level];e.emit(B,{before:r,after:a,plugin:"hls",automatic:t.autoLevelEnabled,downscale:Qp(a,r)})})}function Jp(t,e,s){if(!e.hls)return;const i=(null==s?void 0:s.maxBufferSize)||1024,r=(null==s?void 0:s.maxBufferLength)||30;jp("Setting maxBufferSize to %d",i),e.hls.config.maxBufferSize=i,"metadata"===t.preload&&jp("preload === metadata, setting maxBufferLength to 1sec"),e.hls.config.maxBufferLength="metadata"===t.preload?1:r,e.once(R,()=>{jp("Playback started, set maxBufferLenght to %d",r),e.hls&&(e.hls.config.maxBufferLength=r)})}function tm(t,e,s,i,r){!function(t,e){t.on(Hls.Events.AUDIO_TRACKS_UPDATED,function(t,s){e.emit(Kp,s.audioTracks)}),t.on(Hls.Events.AUDIO_TRACK_SWITCHING,function(t,s){e.emit("audio:update",s)}),t.on(Hls.Events.MANIFEST_PARSED,function(t,s){s.audioTracks&&e.emit(Kp,s.audioTracks)})}(t,i),function(t,e){t.on(Hls.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(s,i)=>{t.subtitleTracks.length||e.emit(Vp,i)}),t.on(Hls.Events.SUBTITLE_TRACKS_UPDATED,(t,s)=>{e.emit(Vp,{tracks:s.subtitleTracks.map(t=>Object.assign({},{subtitleTrack:t}))})}),t.on(Hls.Events.CUES_PARSED,(t,s)=>{e.emit("cues:parsed",s)})}(t,i),Yp(i,t),Zp(t,i,e,s,r),function(t,e){t.on(Hls.Events.FRAG_PARSING_METADATA,function(t,s){e.emit("ssai:hls:metadata",s)})}(t,i),function(t,e){t.on(Hls.Events.BUFFER_CREATED,(t,s)=>{if(!s.tracks.video&&!s.tracks.audiovideo)return e.emit(J)})}(t,i),function(t,e,s){const i="live"in s==0;e.on($p.Events.LEVEL_LOADED,function(s,r){var n,a,o,l,d;i&&t.setOpts({live:null===(n=null==r?void 0:r.details)||void 0===n?void 0:n.live});const c=null===(o=null===(a=e.levels[r.level])||void 0===a?void 0:a.details)||void 0===o?void 0:o.fragments;if(!c)return;const h=(null===(l=c[1])||void 0===l?void 0:l.start)||0,u=e.liveSyncPosition||(null===(d=c[c.length-1])||void 0===d?void 0:d.end)||0;t.emit("dvr/window",u-h)})}(i,t,e)}function em(t,e,s){!function(t){t.on("audio:set",function(e){var s,i;const r=null===(s=e.data)||void 0===s?void 0:s.id;"number"==typeof r&&r!=(null===(i=null==t?void 0:t.hls)||void 0===i?void 0:i.audioTrack)&&setTimeout(function(){(null==t?void 0:t.hls)&&(t.hls.audioTrack=r)},0)})}(t),function(t,e){t.on(F,function(){t.hls&&(t.hls.destroy(),delete t.hls,e.manifest=void 0)}),t.on(N,function(){var e;null===(e=t.hls)||void 0===e||e.destroy()})}(t,e),function(t){const e={media_recovers:0,audio_swaps:0};let s=0;t.on(n,e=>{var i,r,n;t.hls&&(null===(i=null==t?void 0:t.error)||void 0===i?void 0:i.code)===MediaError.MEDIA_ERR_DECODE&&(e.preventDefault(),++s,t.emit(at,{error:new FlowplayerError(null!==(n=null===(r=null==t?void 0:t.error)||void 0===r?void 0:r.message)&&void 0!==n?n:"An error occurred while decoding the media.",De.PlaybackVideoDecodeError,{isFatal:!0,showErrorUI:s>=5,retryOpts:{retry:s<5?hi:fi,retryTimeout:0}})}))}),t.on(w,()=>s=0),t.on(r,s=>{var i,r,n,a;if(!t.hls)return;s.preventDefault();const o=s.detail.error,l=o.config;return o.flowplayerErrorCode===De.PlaybackVideoDecodeError?(t.hls.config.autoStartLoad=!0,t.hls.recoverMediaError(),t.setState(te,!1)):l.error_type?l.error_type===$p.ErrorTypes.NETWORK_ERROR?(t.hls.config.autoStartLoad=!0,(null===(i=t.normalizedSrc)||void 0===i?void 0:i.src)&&t.hls.loadSource(t.original_src),!t.paused||t.hasState($t)?(t.setState(te,!0),t.togglePlay(!0)):(t.setState(te,!1),t.emit("retry/done"))):l.error_type===$p.ErrorTypes.MEDIA_ERROR?(jp(`recovering from ${l.error_type}`),e.media_recovers+5e3>Date.now()&&0==e.audio_swaps?(null===(r=t.hls)||void 0===r||r.swapAudioCodec(),jp(`calling swapAudioCodec() : {count=${e.audio_swaps}}`),e.audio_swaps++,e.media_recovers=Date.now(),null===(n=t.hls)||void 0===n||n.recoverMediaError(),t.setState(te,!1)):(e.media_recovers=Date.now(),e.audio_swaps=0,null===(a=t.hls)||void 0===a||a.recoverMediaError(),t.setState(te,!1))):void 0:void 0})}(t),function(t){t.on(z,()=>{t.hls&&(t.hls.stopLoad(),delete t.opts.start_time)}),t.on(Q,e=>{var s;if(!t.hls)return;if(!t.opts.live)return zp(t,e.detail.currentTime);e.preventDefault();const i=zs(t).progress,r=t.hls;null===(s=t.hls)||void 0===s||s.once($p.Events.LEVEL_LOADED,()=>{if(t.hls!==r)return;const e=t.live_state.dvr_window||0,s=(null==r?void 0:r.liveSyncPosition)||t.seekable.end(0);if(t.hasState(re)||isNaN(i))return t.currentTime=s;t.currentTime=s-e*((100-i)/100)}),zp(t)})}(t),function(t,e){t.on([it,M],s=>{if(!(!t.hls||t.hls.config.autoStartLoad||t.hasState($s)||t.hasState(Vt)||"none"!==e.preload||s.type===M&&!e.autoplay))return t.hls.levels.length?zp(t,e.start_time||-1):void t.hls.once($p.Events.MANIFEST_PARSED,()=>{setTimeout(()=>{zp(t,e.start_time||-1)},0)})}),t.on($,function(e){var s;if(!t.hls)return;const i=null===(s=e.data)||void 0===s?void 0:s.level;"number"==typeof i&&(t.hls.levels[i]||-1===i?t.hls.nextLevel=i:console.error(new Error("skipping invalid quality: "+e.data)))}),t.on(G,function(e){var s,i;const r=e.detail.track,n=null===(s=t.tracks)||void 0===s?void 0:s.find(t=>t.selected&&t!==r),a=t.hls;if(!n||!r||!a)return;n.selected=!1;const o=null===(i=r.data)||void 0===i?void 0:i.slice(0).map(t=>(t.details=void 0,t));a.stopLoad(),a.levelController._levels=a.streamController.levels=o,a.currentLevel=0,a.nextLevel=-1,t.emit(U,Xp(o)),t.hasState(qt)&&!t.hasState(jt)||a.startLoad()});const s=t.opt("start_time");s&&t.once(E,function(){t.currentTime=s})}(t,s),function(t){t.on("tracks:text:updated",e=>{const s=e.detail;t.hls&&s&&s.is_hls_embedded&&"number"==typeof s.track_id&&(t.hls.subtitleTrack=s.track_id)})}(t),((t,e)=>{t.on(Qe,()=>{var s;(null===(s=e.hls)||void 0===s?void 0:s.adaptive_buffer_control)&&Je(t,{feature_name:"adaptive-buffer-control",behavior:"used",sample_rate:Ze.Medium})})})(t,s)}function sm(t,e){if(t.drm&&"https:"!==location.protocol&&"localhost"!==location.hostname&&"127.0.0.1"!==location.hostname){const s=new FlowplayerError("drm is unavailable in http contexts",De.ContentProtectionKeySystemUnavailable,{resource:t.src,isFatal:!0,retryOpts:{retry:fi}});return e.emit(at,{error:s}),!1}return!0}function im(t,e,s,i){if(!t.reaper||!(null==s?void 0:s.src))return;if(t.hls&&t.hls.destroy(),!sm(s,t))return;const r=function(t,e,s,i){var r,n,a,o,l,d,c,h;const u=new FailoverLoaderController,f=function(t){return Object.assign(Object.assign({autoStartLoad:!1,levelLoadingMaxRetry:1},t.hls),{startPosition:t.start_time||-1})}(t);f.renderTextTracksNatively=!1,f.captionsTextTrack1Label=null!==(n=null===(r=null==t?void 0:t.hls)||void 0===r?void 0:r.captionsTextTrack1Label)&&void 0!==n?n:"CC1",f.captionsTextTrack2Label=null!==(o=null===(a=null==t?void 0:t.hls)||void 0===a?void 0:a.captionsTextTrack2Label)&&void 0!==o?o:"CC2",f.captionsTextTrack3Label=null!==(d=null===(l=null==t?void 0:t.hls)||void 0===l?void 0:l.captionsTextTrack3Label)&&void 0!==d?d:"CC3",f.captionsTextTrack4Label=null!==(h=null===(c=null==t?void 0:t.hls)||void 0===c?void 0:c.captionsTextTrack4Label)&&void 0!==h?h:"CC4",f.pLoader=u.createPlaylistLoader(e),f.fLoader=u.createFragmentLoader(),function(t,e){var s;const i=e;"1318f5da-2731-4bf1-b924-fad46cfce535"===i.opt("metadata.sitegroup_id")&&(t.cmcd={contentId:i.opt("metadata.media_id"),sessionId:null===(s=null==i?void 0:i.health)||void 0===s?void 0:s.media_session_id})}(f,s);const g=s.hls=new $p(f);return u.setHls(g),g.subtitleDisplay=!1,g.attachMedia(s),g.loadSource(i.src),setTimeout(()=>s.emit(Op,{hls:s.hls})),g}(e,i,t,s);tm(r,e,i,t,s)}var rm;const nm=((rm=class HLS{init(t,e,s){em(s,this,t)}onload(t,e,s,i){s.normalizedSrc=i,im(s,t,i,this)}wants(t,e,s){return Hls.isSupported()&&Bp(e,s)}}).pluginName="hls",rm.events=xp,rm.version=Hls.version,rm.failover={Reasons:Gp},rm),am=ws(window,nm),om=t=>"object"==typeof t&&null!==t&&!Array.isArray(t),lm=(...t)=>t.reduce((t,e)=>om(e)?(Object.keys(e).forEach(s=>{if(om(t[s])&&om(e[s]))return t[s]=lm(t[s],e[s]);t[s]=e[s]}),t):t,{});class Pipe{static of(t){return new Pipe(t)}static maybe(t,e,...s){return null==t?t:e.apply(t,[t,...s])}constructor(t){this.data=t}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}}const dm=window,cm=dm._flowplayerTimekeeper||(dm._flowplayerTimekeeper={});function hm(t){return fetch(t).then(t=>t.json())}function um(...t){let e=[].join.call(t,"/");return"/"!==e[0]&&(e="/"+e),fm()+"/web/public/native/config"+e}const fm=()=>"https://ljsp.lwcdn.com";function gm(t){(async function(){const t=cm.cachedServerOffset;if(t)return t;const e=cm.pendingRequest||(cm.pendingRequest=fetch("https://ljsp.lwcdn.com/web/public/countdown/time.json")),s=await e,i=parseInt(s.headers.get("age")||"0"),r=await s.json(),n=Date.now()-r.millisUtc-1e3*i;return cm.cachedServerOffset=n,cm.cachedServerOffset})().then(e=>Object.assign(t,{server_time_offset:e}))}function pm(t,e){var s,i;e="object"==typeof e?e:{};const r={title:null===(s=null==t?void 0:t.metadata)||void 0===s?void 0:s.title,description:null===(i=null==t?void 0:t.metadata)||void 0===i?void 0:i.description},n={ima:{parameters:function({media_id:t,duration:e,title:s,tags:i,category_name:r,ad_keywords:n}){return{ad_keywords:n||"",media_id:t||"",category:r||"",media_name:s||"",media_tags:i||"",media_duration:e||-1}}((null==t?void 0:t.metadata)||{})}},a=e.embed||{};return delete a.src,lm(n,r,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 mm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,vm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ym=/^[A-Za-z0-9]{8}$/,Em=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/[A-Za-z0-9]{8}$/;function Tm(t){return"object"==typeof t&&"ovp/base64"==t.type}function Sm(t,e){return function(t,e){return!(!mm.test(t)&&!vm.test(t)||(e.type="video/ovp",0))}(t,e)||function(t,e){return!(!ym.test(t)&&!Em.test(t)||(e&&(e.type="video/ovp"),0))}(t,e)||Tm(e)}function Am(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 _m(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 bm(t){var e;return null===(e=null==t?void 0:t.metadata)||void 0===e?void 0:e.live_start_time}const Lm="ovp:request:start",Rm="ovp:request:media:complete",Im="ovp:request:playlist:complete",km="ovp:live:countdown:tick",wm="ovp:live:countdown:start",Pm="ovp:live:countdown:complete",Dm="ovp:media:changed",Cm="ovp:message:realtime",Om="ovp:config:finalized";var Mm=Object.freeze({__proto__:null,OVP_ERROR:"ovp:error",OVP_MEDIA_REQUEST_START:Lm,OVP_MEDIA_REQUEST_COMPLETE:Rm,OVP_PLAYLIST_REQUEST_COMPLETE:Im,LIVE_COUNTDOWN_TICK:km,LIVE_COUNTDOWN_START:wm,LIVE_COUNTDOWN_COMPLETE:Pm,OVP_MEDIA_CHANGED:Dm,OVP_REALTIME_MESSAGE:Cm,OVP_CONFIG_FINALIZED:Om});function xm(t,e){const s=null==e?void 0:e.src;if(Tm(e))return function(t,e){const s=Am(e.src||"");if(function(t){return"string"==typeof t.err}(s))return console.error(s.err);Fm(t,s)}(t,e);if(!s)return;t.setState(ve,!0);const i=function(t){return~t.indexOf("/")?t:"/media/"+t}(s),r=um(i);fetch(r).then(async e=>e.ok?Fm(t,await e.json()):function(t,e,s,i){t.setState(ve,!1);const r=new FlowplayerError(i.message||"error loading ovp source",function(t){const e=`03-${t}`;return e in Ce?e:De.NetworkUnknown}(s),{resource:e,isFatal:!0,retryOpts:{retry:fi}});t.emit(at,{error:r})}(t,e.url,e.status,await e.json()))}function Fm(t,e){return delete e.live,t.emit(Dm,e),function(t){return Array.isArray(t.playlist)}(e)?function(t,e){t.emit(Im,function(t,e){"number"!=typeof e.delay&&"number"!=typeof t.delay&&(e.delay=5);const s=Object.assign({},t),i=(null==t?void 0:t.playlist)||{},r=lm(e,i),n=((null==r?void 0:r.playlist)||[]).map(t=>{e.ima&&Object.assign(t,{ima:e.ima});const i=pm(t,s);return delete i.playlist,i});return delete r.ima,Object.assign(r,{playlist:n})}(t.opts,e))}(t,e):bm(e)?function(t,e){var s,i;const r=(null===(s=null==e?void 0:e.metadata)||void 0===s?void 0:s.live_start_time)||(null===(i=null==e?void 0:e.metadata)||void 0===i?void 0:i.starttime);r&&(e.live_start_time=Pipe.of(r).fmap(_m).unwrap());t.emit(wm,Pipe.of(e).fmap(pm,t.opts).unwrap())}(t,e):function(t,e){t.emit(Rm,Pipe.of(e).fmap(pm,t.opts).unwrap())}(t,e)}const Nm={};function Um(t,e,s){"object"!=typeof Nm[e]&&(Nm[e]=s);const i=t.opts,r=(null==i?void 0:i.metadata)||{};r.player_id=e,i.metadata=r,s.title&&delete s.title,s.description&&delete s.description;const n=Object.assign(i,s);t.setOpts(n),s.autoplay&&t.togglePlay(!0)}const Bm="recommendationsready";let $m=!1;function Gm(t,e,s){Hm()||Pipe.of("recommendation").fmap(um,e,s).fmap(hm).fmap(e=>e.then(e=>function(t,e){const s=e.playlist,i=t.opts;if(i.recommendations=s,!s.length)return;t.emit(Bm,{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(Km))}function Hm(){return $m}function Km(t){$m=!0,console.error("Failed to load recommendations: %j",t)}function Vm(t){const e=Date.now()-(t.server_time_offset||0);return Math.floor(((t.live_start_time||0)-e)/1e3)}function jm(t,e){let s=0;function i(){const i=Vm(e);if(i<0||isNaN(i)||0===t.reaper||void 0===e.live_start_time)return clearInterval(s),function(t,e,s){t.emit(Pm);const i=Dr(t,Nt);if(i&&i.remove(),t.root.classList.remove("is-livecountdown"),s)return t.setState(ve,!1);t.emit(Rm,e)}(t,e,void 0===e.live_start_time);!function(t,e,s,i){s.classList.add("is-livecountdown"),e.emit(km,{remaining_time:qm(i+1)}),e.hasState(qt)||e.setState(qt,!0)}(0,t,t.root,i)}gm(e),i(),s=setInterval(i,250)}function qm(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 i=Math.floor(t/60);return{days:e,hours:s,minutes:i,seconds:t-=60*i}}(t);let s="";return e.days&&(s+=e.days+":"),s+ds(e.hours)+":"+ds(e.minutes)+":"+ds(e.seconds)}class WebsocketBridge{static of(t){return new WebsocketBridge(t)}constructor(t){this.manualDisconnect=!1,this.video=t,this.onClose=this.onClose.bind(this),this.onMessage=this.onMessage.bind(this)}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(Cm,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=Cr("fp-inner");this.append(e);const s=document.createElement("p");s.innerText=t.i18n("ovp.starting_in"),e.append(s);const i=document.createElement("p");i.classList.add("fp-countdown"),e.append(i),t.on(km,e=>{const s=e.detail.remaining_time;t.root.classList.add("is-livecountdown"),i.innerText=s})}}const Wm=["*.lwcdn.com","*.flowplayer.com","*.wowza.com"];var Ym;const zm=(Ym=class OVP{constructor(t){Re(t,Nt,FlowplayerLiveCountdown)}onload(t,e,s,i){if("string"==typeof(null==i?void 0:i.src))return"string"!=typeof t.player_id||0===i.src.indexOf(t.player_id)||Tm(i)||(i.src=[t.player_id,i.src].join("/")),xm(s,i)}wants(t,e,s){return Sm(t,e)}init(t,e,s){const i=new WebsocketBridge(s);let r=Object.assign({},t);const n=function(e){if(!r)return e;t.autoplay!==r.autoplay&&(r.autoplay=t.autoplay),delete r.src;const i=lm(e,r);return s.emit(Om,i),i};s.on(F,()=>{(s.currentSrc||s.root.classList.contains("is-livecountdown"))&&(r=!1)}),s.on(Lm,function(){s.setState(te,!0),t.recommendations&&(t.recommendations=!1)}),s.on(Dm,function({data:t}){var e,s;const r=null===(e=null==t?void 0:t.metadata)||void 0===e?void 0:e.media_id;(null===(s=null==t?void 0:t.metadata)||void 0===s?void 0:s.live_start_time)&&r&&(i.disconnect(),i.connect(r))}),s.on(Cm,function({data:e}){var i;const r=null==e?void 0:e.event,n=null==e?void 0:e.value,a=s.opt("metadata",{live_start_time:""});switch(r){case"METADATA":{const e=Object.assign(a,n),r=Object.assign(t,{metadata:e});(null===(i=null==r?void 0:r.metadata)||void 0===i?void 0:i.live_start_time)&&(r.live_start_time=_m(r.metadata.live_start_time)),s.setOpts(r);break}}}),s.on(it,function(e){const s=t;if(bm(s)){if(Qm(s))return;e.preventDefault()}}),s.on(Rm,function(t){const e=t.data;if(!e)return;if(e.src&&(e.src=is(e.src).map(t=>(t.src&&t.src.startsWith("//")&&(t.src="https:"+t.src),t))),0==s.reaper||"object"!=typeof e||Vm(e)>0)return;const i=n(e);s.setOpts(i),s.setAttrs(i),i.src&&s.setSrc(i.src),s.setState(ve,!1)}),s.on(et,function({data:i}){var r,n;if("string"==typeof t.src&&Sm(t.src,{}))return;if((null==i?void 0:i.domains)&&(null==i?void 0:i.domains.length)&&!((t,e)=>{const s=t.split(".").reverse();return e.concat(Wm).some(t=>{const e=t.split(".").reverse(),i="*"===e[e.length-1];return i&&e.pop(),(i||e.length===s.length)&&e.every((t,e)=>s[e]===t)})})(Ei(),i.domains))return Us({root:e,video:s,data:{details:`Hostname ${Ei()} is not allowed to load player ${null===(r=i.metadata)||void 0===r?void 0:r.player_id}.`,reason:"domain"}});if(t.src&&Xm(t.src))return;const a=null==i?void 0:i.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 Nm[e])return console.debug("using Cache(%s)",e),Um(t,e,Nm[e]);Pipe.of(e).fmap(um).fmap(hm).fmap(s=>s.then(s=>Um(t,e,s)).catch(console.error))}(s,t.player_id):void 0}),s.on(Im,function(t){var e;const i=t.data;if(!i||0==s.reaper)return;const{playlist:r}=i,a=Fe(i,["playlist"]),o=n(Object.assign(a,{playlist:Object.assign({},a)}));Array.isArray(o.playlist)&&(o.playlist=a),delete o.loop,o.playlist.playlist_title||(o.playlist.playlist_title=null===(e=a.metadata)||void 0===e?void 0:e.playlist_title),s.setOpts(o),s.setAttrs(o);const l={type:"flowplayer/playlist",items:r};s.setSrc(l),s.setState(ve,!1)}),s.on(wm,function(i){const r=i.data;if(!r||0==s.reaper)return;const a=n(r);if(s.setOpts(a),s.setAttrs(a),Vm(r)<=0)return s.emit(Rm,r);Dr(s,Nt)||(e.appendChild(Le(s,Nt)),jm(s,t))}),s.on(A,function(){var e,i,r;const n=t;bm(n)?Qm(n)||(s.togglePlay(!1),s.emit(P)):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||Hm()||(null===(i=null==t?void 0:t.metadata)||void 0===i?void 0:i.media_id)&&(null===(r=null==t?void 0:t.metadata)||void 0===r?void 0:r.player_id)&&Gm(s,t.metadata.media_id,t.metadata.player_id))}),s.on(N,function(){i.disconnect()}),function(t){const e=[];t.on(Qe,()=>{const s=t.opt("metadata.stream_target_id");s&&!e.includes(s)&&(e.push(s),Je(t,{feature_name:"ewv",behavior:"used"}))})}(s)}},Ym.pluginName="ovp",Ym.events=Mm,Ym);function Qm(t){var e,s;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===(s=null==t?void 0:t.metadata)||void 0===s?void 0:s.allow_after_stop_time)||_m(i)>Date.now()}const Xm=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)},Zm=ws(window,zm);function Jm(t){return{width:t.clientWidth,height:t.clientHeight}}function tv(t,e,s){return"number"==typeof s&&(s+="px"),t.style.setProperty(e,s),t}const ev="is-popped-out",sv="is-ad-loading",iv="is-ad-user-activated",rv=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"});let nv=null;function av(t,e=5e3){return new Promise(s=>{const i=document.createElement("video"),r={autoplay_sound:!1,autoplay_muted:!1},n=()=>{i.pause(),i.currentTime=0,i.src="",i.remove(),s(r)},a=setTimeout(n,e);i.setAttribute("playsinline",""),i.setAttribute("webkit-playsinline",""),i.setAttribute("disablepictureinpicture",""),i.preload="auto",i.playsInline=!0,i.muted=!1,Object.assign(i.style,{position:"fixed",left:"-9999px",top:"0",width:"1px",height:"1px",opacity:"0",pointerEvents:"none"}),document.body.appendChild(i),i.src=(nv||(nv=URL.createObjectURL(rv)),nv);(async()=>{try{return await i.play(),clearTimeout(a),r.autoplay_sound=!0,r.autoplay_muted=!0,n()}catch(e){if(t)return clearTimeout(a),n()}try{i.muted=!0,i.setAttribute("muted",""),await i.play(),r.autoplay_muted=!0}catch(t){}clearTimeout(a),n()})()})}const ov=ci("ads/lifecycle"),lv=[Fi,Ni,Zi];async function dv({config:t,root:e,content:s,ads:i,ima:r}){var n;ov("LifeCycle::initLifeCycle",t,e,s,i,r),s.autoplay=!1;const a=t.autoplay===we.AUDIO_REQUIRED,o=function(t,e){return{muted:!(e||!t.muted),volume:t.volume}}(s,a);s.on(b,()=>{o.volume=s.volume,o.muted=s.muted}),s.on(ur,()=>{ov("showFirstFrame"),e.classList.toggle("ad-hide-first-frame",!1)});const l=Le(s,on),d=l;s.emit(gr,{ui_flags:null===(n=t.ads)||void 0===n?void 0:n.ui}),s.renderPlugin(l);const c={listening:!1,preload:null==r?void 0:r.preload_ads};if(ov("initial",o),i.setVideoTag(s),t.autoplay){ov("Trying to autoplay"),e.classList.add("ad-hide-first-frame"),ov("hideFirstFrame");const n=await async function(t,e){const[s,i]=[t.muted,t.volume];ov("Lifecycle::peek_content(:muted => %s, :volume => %s)",s,i),await async function(t){return ov("Lifecycle::wait_for_source"),new Promise((e,s)=>{const i=50,r=2e3;let n=0;const a=setInterval(()=>{if(++n>r/i)return clearInterval(a),s(new Error(`No source in ${r}ms, giving up`));(t.currentSrc||"dash"in t)&&(e(null),clearInterval(a))},i)})}(t),await function(t){return new Promise(e=>{if(t.hasState(ge))return e(null);t.once(M,()=>e(null))})}(t);const r=Date.now();!e&&t.opts.muted||(t.muted=!1);t.volume=t.volume?t.volume:1;const{autoplay_sound:n,autoplay_muted:a}=await av(e);return ov("Lifecycle::peek_content:: ","audioRequired: "+e," autoplay_sound: "+n," autoplay_muted: "+a," peek_content_check_ms: "+(Date.now()-r)),t.opts.muted&&!e?a:!!n||!e&&(t.muted=!!a||s,a)}(s,a);n?(ov("Can autoplay, start ad"),s.opts.autoplay=1,s.setState(ee,!0),cv({ads:i,content:s,state:c,adContainer:d,ima:r,config:t})):(ov("cannot autoplay(audioRequired: %s), fallback to poster state",a),t.autoplay=0,s.emit(ur,{root:e}),s.setState("is-starting",!0))}s.root.classList.toggle(iv,!!t.autoplay||!i.hasPreroll()),!t.autoplay&&i.hasPreroll()&&function({content:t,ads:e,config:s,state:i,initial:r,adContainer:n,ima:a}){t.once(it,async function(o){t.root.classList.add(iv),(t.hasState(ge)||"touchend"!=o.type)&&e.shallPlayAd(0)&&(e.adapter.setAttemptingPrerollOnIOS(e.adapter.isCustomPlaybackEnabled()),e.adapter.isCustomPlaybackEnabled()||o.preventDefault(),gv({ads:e,content:t,state:i}),ov("user_gesture(:intercept) -> shallPlayAd(0: %s)",e.shallPlayAd(0)),s.muted=r.muted,await cv({ads:e,content:t,state:i,adContainer:n,ima:a,config:s}),pv({ads:e,content:t}))})}({content:s,ads:i,config:t,state:c,initial:o,adContainer:d,ima:r}),!t.autoplay&&i.hasPreroll()&&c.preload&&cv({ads:i,content:s,state:c,adContainer:d,ima:r,config:t}),fv({config:t,root:e,content:s,ads:i,state:c,adContainer:d,ui:l,ima:r,initial:o});const h=async t=>{s.removeEventListener(it,h),i.resetScheduleCounter(),i.hasPreroll()&&(i.adapter.setAttemptingPrerollOnIOS(i.adapter.isCustomPlaybackEnabled()),t.preventDefault(),await i.setCurrentTime(0))};s.on(F,()=>{s.currentSrc&&(s.removeEventListener(it,h),s.addEventListener(it,h))}),s.on(it,t=>{(i.adBreak||i.adPlaying)&&(!i.adBreak||i.adLinear||i.adapter.isAdPod())&&(ov("prevented content from starting because ad break is active"),t.preventDefault())})}async function cv(t){var e;t.state.started||((null===(e=t.config.ima)||void 0===e?void 0:e.preload_ads)||t.content.hasState(ge)?await hv(t):t.content.once(M,async()=>{await hv(t)}))}async function hv({ads:t,content:e,adContainer:s,ima:i,state:r,config:n}){var a;r.started=!0;const o=Fe(i,["ads"]),l=Jm(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,preload_ads:null===(a=null==n?void 0:n.ima)||void 0===a?void 0:a.preload_ads},o),l));ov("start():",c,r),await t.initialize(!1,c,r.preload)}function uv(t,e){var s,i;return{content_width:t.clientWidth||(null===(s=t.parentNode)||void 0===s?void 0:s.clientWidth)||e.clientWidth,content_height:t.clientHeight||(null===(i=t.parentNode)||void 0===i?void 0:i.clientHeight)||e.clientHeight}}function fv({config:t,root:e,content:s,ads:i,initial:r,adContainer:n,state:a,ui:o,ima:l}){ov("addUIListeners()");const d=async()=>{if(i){if(!(i.adapter.isAttemptingPrerollOnIOS()||i.adapter.isCustomPlaybackEnabled()&&s.currentSrc!==s.original_src)){if(s.off(R,d),ov("addUIListeners() -> content started playing"),gv({ads:i,content:s,state:a}),!i.shallPlayAd(0)||!i.adapter.isLinearAd())return ov("addUIListeners() -> no more preroll ads -> resume content"),s.emit(ur,{root:e}),await cv({ads:i,content:s,state:a,adContainer:n,ima:l,config:t});await cv({ads:i,content:s,state:a,adContainer:n,ima:l,config:t}),i.shallPlayAd(0)&&i.adapter.isLinearAd()&&(o.classList.add("on","linear"),e.classList.add(sv),pv({ads:i,content:s}))}}else s.off(R,d)};s.on(R,d),s.on([K,H],function(){if(!i)return;const{content_width:t,content_height:r}=uv(s,e);i.resize({height:r,width:t})}),s.on(m,t=>{if(!i||!t.detail)return;const{width:e,height:s}=t.detail.contentRect;i.resize({width:e,height:s})}),s.on(P,t=>{var r;const n=()=>{t.preventDefault(),Object.assign(t,{prevented:!0})};if(e.classList.contains("ad-linear")&&e.classList.contains("ads-custom-playback-enabled"))return n();i&&(ov("ui_listeners(:%s, event: %o)",t.type,t.detail),(null===(r=null==t?void 0:t.detail)||void 0===r?void 0:r.from)!==i&&(n(),i.finished(function(){s.emit(P,{from:i})})))}),i.on($i,()=>{e.classList.add(sv)}),i.once(Ki,()=>{s.on([it,rt],t=>{var e;if(!i.adBreak||!i.adapter.isLinearAd())return;t.preventDefault();const s=(null===(e=t.detail)||void 0===e?void 0:e.forced)?t.type===it:!i.adPlaying;s&&i.paused&&i.resume(),s||i.paused||i.pause()})}),i.on(Ki,t=>{const n=t.detail,{linear:a,ad:o,ad_type:l}=n;let d;if(ov(`Ad[linear: ${a}, currentTime: ${s.currentTime}] starting`,o),"preroll"==l&&!a&&s.paused&&s.togglePlay(!0),a&&(d=uv(s,e)),i.resize({width:d?d.content_width:o.width,height:d?d.content_height:o.height,linear:a,resize_non_linear:!0}),s.emit(fr,{opts:{linear:a,resizeContainerAlso:!0,width:a?void 0:o.width,height:a?void 0:o.height}}),e.classList.remove(sv),s.setState("ad-linear",a),s.setState("ad-non-linear",!a),!a){ov("non-linear ad / restarting content");try{s.togglePlay(!0),s.volume=r.volume,s.muted=r.muted}catch(t){ov(t)}}s.hasState(ge)||s.hasState(ev)||!a||i.pause()}),i.on(Hi,()=>{s.emit(fr,{opts:{linear:!0,width:0,height:0}})}),s.on(lv,t=>async function({root:t,content:e,ads:s,eventName:i,err:r={reason:""}}){ov("teardown(event: %s)",i),s.adapter.isAttemptingPrerollOnIOS()&&(s.adapter.setAttemptingPrerollOnIOS(!1),!e.paused&&e.hasState(qt)&&e.hasState($t)&&si(e,e.opts.start_time));t.classList.add("is-seamless"),t.classList.remove(sv),["ad-non-linear","ad-linear"].forEach(t=>e.setState(t,!1)),r.reason&&ov("teardown(:err, reason: %s) %o",r.reason);const n=s.getLastAd();if(e.emit(ur,{root:t}),!s.shouldRestartContent(i))return ov("Lifecycle.teardown(:skip_restart, reason: %s)","Ad prevented restarting content"),mv(t);if(e.currentTime>0&&e.currentTime>=e.duration||"postroll"==s.ad_type||!1===(null==n?void 0:n.restart))return ov("Lifecycle.teardown(:skip_restart, reason: %s)","was a postroll ad"),mv(t);""===e.currentSrc&&e.setSrc(e.original_src);e.paused&&s.shouldRestartContent(i)&&(ov("Lifecycle.teardown(:toggle_play, %s)","attempting to restart content"),await new Promise(t=>{if(e.hasState(ge))return t(null);e.once(M,t)}),await e.togglePlay(!0));if(!e.paused)return ov("Lifecycle.teardown(:ok)","restarted video content"),mv(t)}({root:e,content:s,ads:i,ui:o,err:t.detail,eventName:t.type}));let c=!!t.autoplay;s.on(M,()=>{c&&!1!==l.autopause&&s.hasState("ad-linear")&&i.resume()}),s.on(x,Bs(()=>{!1!==l.autopause&&(c=!i.paused,i.pause())}))}function gv({ads:t,content:e,state:s}){s.listening||(e.on([A,D,R,C],s=>{t.adapter.isCustomPlaybackEnabled()&&(t.adPlaying||t.paused)||e.played.length&&(t.adPlaying&&t.adapter.isLinearAd()&&!e.paused&&e.pause(),pv({ads:t,content:e,seek:s.type===C}))}),s.listening=!0)}function pv({ads:t,content:e,seek:s=!1}){t&&t.setCurrentTime(e.currentTime,void 0,s)}function mv(t){t.classList.remove("is-seamless")}const vv=ci("ads/timers");class TimerRegistry{constructor(t={},e={}){this.intervals=t,this.timers=e}}let yv=-1;function Ev(t,e,s){const i=setInterval(s,e);if(vv(`TimerRegistry.createInterval() -> ${i}`,t.intervals),"object"==typeof i){const e=++yv;return t.intervals[e]=e,e}return t.intervals[i]=i,i}function Tv(t){if(t)return vv("TimerRegistry.empty()",Object.keys(t.timers),Object.keys(t.intervals)),Object.keys(t.intervals).forEach(e=>function(t,e){return vv(`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 vv(`TimerRegistry.removeTimeout() -> ${e}`,t.timers),clearTimeout(t.timers[e]),delete t.timers[e],t}(t,e)),t}function Sv(t){try{return t.getAdPodInfo().getPodIndex()}catch(t){return}}class AdLoadingController{adRequestStart(t){"number"==typeof t&&"number"!=typeof this.requestStart&&(this.requestStart=performance.now())}adRequestEnd(){this.requestStart=void 0}getRemainingAdLoadTime(t,e){return"number"!=typeof e||"number"!=typeof this.requestStart?t:Math.max(0,e-(performance.now()-this.requestStart))}}function Av(t){return Mr(t)&&!t.root.classList.contains("no-fullscreen")}function _v(t){const e=null==t?void 0:t.ads;return!!(e&&Array.isArray(e)&&e.length>0)}class IMA{constructor(t){this.eventHandler=t,this.log=ci("ads/adapter/ima"),this.google=window.google,this._adHandlers=[],this._timers=new TimerRegistry,this._started=!1,this._volumeLevel=0,this._adLoaded=!1,this.customPlaybackEnabled=!1,this._paused=!1,this._all_ads_completed=!1,this._currentDuration=0,this._currentRemaining=0,this._currentDisplayTs=0,this._isInitialized=!1,this._adBreakTime=0,this._prepared=!1,this.opts={},this.loadingController=new AdLoadingController}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(nr)}}isReady(){return!!this._isInitialized}setVideoTag(t){this.videoTag=t,this.customPlaybackEnabled=Av(t),t.root.classList.toggle("ads-custom-playback-enabled",this.customPlaybackEnabled)}setAdBreakTime(t){this._adBreakTime=t}getAdBreakTime(){return this._adBreakTime}isCustomPlaybackEnabled(){return this.customPlaybackEnabled}isAttemptingPrerollOnIOS(){var t;return!!(null===(t=null==this?void 0:this.videoTag)||void 0===t?void 0:t.root.classList.contains("preroll-ios"))}setAttemptingPrerollOnIOS(t){var e;null===(e=null==this?void 0:this.videoTag)||void 0===e||e.root.classList.toggle("preroll-ios",t)}isLinearAd(){return!!this.currentAd()&&!!this._adLinear}getVideoTag(){return this.videoTag}getDimensions(){return this._dimensions||{}}getOpts(){return this.opts}isPaused(){return this._paused}destroy(){const t=this;Tv(this._timers),this._adHandlers&&this._adHandlers.forEach(t=>t()),t._adHandlers=void 0,this._adDisplayContainer&&this._adDisplayContainer.destroy(),t._adDisplayContainer=void 0,this._adsLoader&&this._adsLoader.destroy(),t._adsLoader=void 0,this._adsManager&&this._adsManager.destroy(),t._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 r=this.google.ima.settings;if(t.NumRedirects=t.NumRedirects||t.redirects,r.setVpaidMode(t.VpaidMode||this.google.ima.ImaSdkSettings.VpaidMode.INSECURE),r.setDisableCustomPlaybackForIOS10Plus(!this.customPlaybackEnabled),"NumRedirects"in t&&r.setNumRedirects(t.NumRedirects),"AutoPlayAdBreaks"in t&&r.setAutoPlayAdBreaks(t.AutoPlayAdBreaks),"Locale"in t&&r.setLocale(t.Locale),"Ppid"in t&&r.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,s.loadVideoTimeout=t.media_timeout||-1,s.restoreCustomPlaybackStateOnAdBreakComplete=this.customPlaybackEnabled,this.customPlaybackEnabled&&(s.playAdsAfterTime=this.videoTag.currentTime),this.eventHandler.trigger(rr,s);const i=this._adsManager=e.getAdsManager(this.videoTag,s);this.eventHandler.trigger(sr,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,s;const i=null===(e=t.getAdData())||void 0===e?void 0:e.duration,r=null===(s=t.getAdData())||void 0===s?void 0:s.currentTime;isNaN(i)||isNaN(r)||(this._currentRemaining=i-r,this.eventHandler.trigger(Wi,{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(Ki,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(Vi,e),Tv(this._timers)}),i.addEventListener(this.google.ima.AdEvent.Type.SKIPPED,t=>{this.debugEvent(t);const e=t.getAd();e&&this.emitWithAd(Yi,e)}),i.addEventListener(this.google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,t=>{if(this.isAdPod()&&this.videoTag){const t=Math.abs(this.videoTag.currentTime-this.videoTag.duration)<1?-1:this.videoTag.currentTime;this.setAdBreakTime(t)}this.debugEvent(t);const e=t.getAd();e&&this.emitWithAd(Hi,e)}),i.addEventListener(this.google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,t=>{this.debugEvent(t),this._started=!1,this._currentDisplayTs=0,this.eventHandler.trigger(Zi,{force:!0})}),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(Qi,e)});const r=t=>{this._paused=t,this.eventHandler.trigger(t?ji:qi)};i.addEventListener(this.google.ima.AdEvent.Type.PAUSED,()=>r(!0)),i.addEventListener(this.google.ima.AdEvent.Type.RESUMED,()=>r(!1)),i.addEventListener(this.google.ima.AdEvent.Type.STARTED,()=>r(!1)),i.addEventListener(this.google.ima.AdEvent.Type.VOLUME_MUTED,t=>{this.log("IMA::volume(type: %s, event: %o)","mute",t),this.eventHandler.trigger(zi)});const{width:n,height:a}=t;return n&&a?this.isAdPod()&&t.preload_ads&&!this.videoTag.root.classList.contains(iv)?t.autoplay?this.videoTag.hasState(ge)?this.initAdsManager(i,t):this.once(this.videoTag,M,()=>{i===this._adsManager&&this.initAdsManager(i,t)}):this.videoTag.once(it,()=>{i===this._adsManager&&this.initAdsManager(i,t)}):this.initAdsManager(i,t):void 0}),i&&(this.log("Event(reload: %s)",or),this.eventHandler.trigger(or,e)),this.eventHandler.trigger(xi,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(),this._adsManager=void 0}reset(){this.destroyManager("reset"),Tv(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)})})}initAdsManager(t,e){t.init(e.width,e.height,this.google.ima.ViewMode.NORMAL),this.log("ima.initialise: done initializing"),this.isAdPod()&&t.start()}async initAd(t,e=5e3){var s;this.log(`ima.initAd(adTag: ${t}, timeout: ${e})`),this.customPlaybackEnabled||this.loadingController.adRequestStart(this.opts.total_loading_timeout);try{if(await this.requestAd(t,this.loadingController.getRemainingAdLoadTime(e,this.opts.total_loading_timeout)),this._adLoaded=!0,this.customPlaybackEnabled)return;null===(s=this._adsManager)||void 0===s||s.updateAdsRenderingSettings({loadVideoTimeout:this.loadingController.getRemainingAdLoadTime(this.opts.media_timeout||-1,this.opts.total_loading_timeout)})}catch(t){throw this.log("ima.initAd:",t),this._adLoaded=!1,t}finally{Tv(this._timers)}}async requestAd(t,e){if(this.destroyManager("requestAd"),!this.videoTag)return;this.setAdBreakTime(this.videoTag.currentTime);const{autoplay:s=!1}=this.opts,i=Date.now(),r=this.videoTag.muted;this._volumeLevel=this.videoTag.volume;const n=r||0==this._volumeLevel;this._all_ads_completed=!1,this.log("ima.requestAd(%o)",Object.assign(Object.assign({},this.opts),{autoplay:s,muted:r,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;return 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(ir,{request:a}),this._adsLoader?new Promise(async(t,s)=>{var i;const r=this.waitForAdsManager();null===(i=this._adsLoader)||void 0===i||i.requestAds(a),this.once(this._adsLoader,this.google.ima.AdErrorEvent.Type.AD_ERROR,t=>{s(()=>(this.emitError(Bi,t),Promise.reject(new Error("Ad load failed"))))}),setTimeout(()=>{s(()=>{r.then(t=>{t.destroy(),this._adsManager===t&&(this._adsManager=void 0)});const t=new Error("Ad internal timeout reached");return this.eventHandler.trigger(Xi,t),Promise.reject(t)})},e),t(await r)}).then(t=>new Promise((e,s)=>{this.volume(n?0:this._volumeLevel),this.eventHandler.trigger(Qi,this._volumeLevel);const r=this.cuepoints();if(r&&r.length&&0!==r[0])return e({ad:!1,adsManager:t});this.once(t,this.google.ima.AdErrorEvent.Type.AD_ERROR,t=>{s(()=>(this.emitError(Bi,t),Promise.reject(t)))}),this.once(t,this.google.ima.AdEvent.Type.ALL_ADS_COMPLETED,()=>{this._all_ads_completed=!0,e(null)}),this.once(t,this.google.ima.AdEvent.Type.LOADED,t=>{this.eventHandler.trigger(Gi,{request_load_time:Date.now()-i});const s=t.getAd();s&&(this.log("ima.requestAd: AD_REQUEST_COMPLETED",s.getContentType()),"application/javascript"==s.getContentType()&&this.eventHandler.trigger(er,s),e(null))}),this.once(t,this.google.ima.AdEvent.Type.CLICK,()=>{this.log("ima.requestAd: click event"),this.pause()})}),t=>t()):void 0}async playAd(){if(this.log("ima.playAd()",this),!this._adsManager||!this._adLoaded)return;const t=this.currentAd();if(t&&(!this.customPlaybackEnabled||t.isLinear()))try{await this.startAndWaitForAdCompletion(this._adsManager,t.isLinear())}catch(t){throw this.log("ima.playAd",t),t}finally{this._adLoaded=!1,Tv(this._timers)}}startAndWaitForAdCompletion(t,e){if(!this._started)return this.log("ima.startAndWaitForAdCompletion(manager: %o)",{volume:t.getVolume()}),new Promise((s,i)=>{let r=!1;this.once(t,this.google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,()=>{if(this.log("ima.startAndWaitForAdCompletion: CONTENT_RESUME_REQUESTED <<< happened"),this._started=!1,r)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),r=!0;try{const{ok:e}=await IMA.pollForFatalError({err:t,ima:this});e&&(r=!1)}catch(e){this._started=!1,i(t)}});const n=this.getVideoTag();if(!n)return;const a=()=>{e&&(this._started=!0),t.start(),this.eventHandler.trigger(ar)};if(!e||n.hasState(ge)||n.hasState(ev))return a();n.paused||n.pause(),n.once(M,()=>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:i,resize_non_linear:r}){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||r)&&(i||this.log("ima.onResize %s x %s",t,e),this._adsManager.resize(t,e,this.google.ima.ViewMode.NORMAL))))}onAdRequestEnd(){var t;this.customPlaybackEnabled||(this.loadingController.adRequestEnd(),null===(t=this._adsManager)||void 0===t||t.updateAdsRenderingSettings({loadVideoTimeout:this.opts.media_timeout||-1}))}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>0)}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,[Zi,lr],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(),i=e.getInnerError(),r=i?IMA.unwrapError(i,e.message):"";s={reason:r,type:e.getType(),code:e.getErrorCode()}}catch(t){}const i=e._currentRemaining;return new Promise((t,r)=>{const n=setTimeout(()=>{e.eventHandler&&e.eventHandler.trigger(Fi,s),r(new Error("Ad not progressing"))},2500);e.eventHandler.once(Wi,e=>{const s=e.detail.remaining;-1!==s&&s<i&&(clearTimeout(n),t({ok:1}))})})}static pollRemaining({ima:t,adsManager:e}){let s=-1;return Ev(t._timers,250,function(){const i=e.getRemainingTime();-1!=t._currentRemaining&&t._currentRemaining<=i||(t._currentRemaining=e.getRemainingTime(),s!=t._currentRemaining&&(s=t._currentRemaining,t.eventHandler.trigger(Wi,{remaining:t._currentRemaining,duration:t._currentDuration})))})}once(t,e,s){this._adHandlers.push(function(t,e,s){const i=r=>{s(r),t.removeEventListener(e,i)};return t.addEventListener(e,i),()=>t.removeEventListener(e,i)}(t,e,s))}static race(t,e,s){e.forEach(i=>{const r=(...i)=>{e.forEach(e=>t.removeListener(e,r)),s(i)};t.on(i,r)})}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),i=function(t){try{return t.getAdPodInfo().getTotalAds()}catch(t){return}}(e),r={ad:{duration:e.getDuration(),width:e.getWidth(),height:e.getHeight(),position:s,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)`,r,e),this.eventHandler.trigger(t,r)}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:Sv(e),ad:e})}catch(t){}}}var bv=function(t){var e={exports:{}};return t(e,e.exports),e.exports}(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}(),i=Object.prototype.hasOwnProperty;e.arrayToObject=function(t,e){for(var s=e.plainObjects?Object.create(null):{},i=0;i<t.length;++i)void 0!==t[i]&&(s[i]=t[i]);return s},e.merge=function(t,s,r){if(!s)return t;if("object"!=typeof s){if(Array.isArray(t))t.push(s);else{if("object"!=typeof t)return[t,s];(r.plainObjects||r.allowPrototypes||!i.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,r)),Object.keys(s).reduce(function(t,n){var a=s[n];return i.call(t,n)?t[n]=e.merge(t[n],a,r):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),i="",r=0;r<e.length;++r){var n=e.charCodeAt(r);45===n||46===n||95===n||126===n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122?i+=e.charAt(r):n<128?i+=s[n]:n<2048?i+=s[192|n>>6]+s[128|63&n]:n<55296||n>=57344?i+=s[224|n>>12]+s[128|n>>6&63]+s[128|63&n]:(r+=1,n=65536+((1023&n)<<10|1023&e.charCodeAt(r)),i+=s[240|n>>18]+s[128|n>>12&63]+s[128|n>>6&63]+s[128|63&n])}return i},e.compact=function(t,s){if("object"!=typeof t||null===t)return t;var i=s||[],r=i.indexOf(t);if(-1!==r)return i[r];if(i.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],i)):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],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))}}),Lv={brackets:function(t){return t+"[]"},indices:function(t,e){return t+"["+e+"]"},repeat:function(t){return t}},Rv={delimiter:"&",strictNullHandling:!1,skipNulls:!1,encode:!0,encoder:bv.encode},Iv=function t(e,s,i,r,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(r)return a?a(s):s;c=""}if("string"==typeof c||"number"==typeof c||"boolean"==typeof c||bv.isBuffer(c))return a?[a(s)+"="+a(c)]:[s+"="+String(c)];var h,u=[];if(void 0===c)return u;if(Array.isArray(o))h=o;else{var f=Object.keys(c);h=l?f.sort(l):f}for(var g=0;g<h.length;++g){var p=h[g];n&&null===c[p]||(u=Array.isArray(c)?u.concat(t(c[p],i(s,p),i,r,n,a,o,l,d)):u.concat(t(c[p],s+(d?"."+p:"["+p+"]"),i,r,n,a,o,l,d)))}return u},kv=Object.prototype.hasOwnProperty,wv={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3,strictNullHandling:!1,plainObjects:!1,allowPrototypes:!1,allowDots:!1,decoder:bv.decode},Pv=function t(e,s,i){if(!e.length)return s;var r,n=e.shift();if("[]"===n)r=(r=[]).concat(t(e,s,i));else{r=i.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&&i.parseArrays&&o<=i.arrayLimit?(r=[])[o]=t(e,s,i):r[a]=t(e,s,i)}return r},Dv=function(t,e,s){if(t){var i=s.allowDots?t.replace(/\.([^.[]+)/g,"[$1]"):t,r=/(\[[^[\]]*])/g,n=/(\[[^[\]]*])/.exec(i),a=n?i.slice(0,n.index):i,o=[];if(a){if(!s.plainObjects&&kv.call(Object.prototype,a)&&!s.allowPrototypes)return;o.push(a)}for(var l=0;null!==(n=r.exec(i))&&l<s.depth;){if(l+=1,!s.plainObjects&&kv.call(Object.prototype,n[1].slice(1,-1))&&!s.allowPrototypes)return;o.push(n[1])}return n&&o.push("["+i.slice(n.index)+"]"),Pv(o,e,s)}},Cv=function(t,e){var s,i,r=t,n=e||{},a=void 0===n.delimiter?Rv.delimiter:n.delimiter,o="boolean"==typeof n.strictNullHandling?n.strictNullHandling:Rv.strictNullHandling,l="boolean"==typeof n.skipNulls?n.skipNulls:Rv.skipNulls,d=("boolean"==typeof n.encode?n.encode:Rv.encode)?"function"==typeof n.encoder?n.encoder:Rv.encoder:null,c="function"==typeof n.sort?n.sort:null,h=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?r=(i=n.filter)("",r):Array.isArray(n.filter)&&(s=i=n.filter);var u,f=[];if("object"!=typeof r||null===r)return"";u=n.arrayFormat in Lv?n.arrayFormat:"indices"in n?n.indices?"indices":"repeat":"indices";var g=Lv[u];s||(s=Object.keys(r)),c&&s.sort(c);for(var p=0;p<s.length;++p){var m=s[p];l&&null===r[m]||(f=f.concat(Iv(r[m],m,g,o,l,d,i,c,h)))}return f.join(a)},Ov=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||bv.isRegExp(s.delimiter)?s.delimiter:wv.delimiter,s.depth="number"==typeof s.depth?s.depth:wv.depth,s.arrayLimit="number"==typeof s.arrayLimit?s.arrayLimit:wv.arrayLimit,s.parseArrays=!1!==s.parseArrays,s.decoder="function"==typeof s.decoder?s.decoder:wv.decoder,s.allowDots="boolean"==typeof s.allowDots?s.allowDots:wv.allowDots,s.plainObjects="boolean"==typeof s.plainObjects?s.plainObjects:wv.plainObjects,s.allowPrototypes="boolean"==typeof s.allowPrototypes?s.allowPrototypes:wv.allowPrototypes,s.parameterLimit="number"==typeof s.parameterLimit?s.parameterLimit:wv.parameterLimit,s.strictNullHandling="boolean"==typeof s.strictNullHandling?s.strictNullHandling:wv.strictNullHandling,""===t||null==t)return s.plainObjects?Object.create(null):{};for(var i="string"==typeof t?function(t,e){for(var s={},i=t.split(e.delimiter,e.parameterLimit===1/0?void 0:e.parameterLimit),r=0;r<i.length;++r){var n,a,o=i[r],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))),kv.call(s,n)?s[n]=[].concat(s[n]).concat(a):s[n]=a}return s}(t,s):t,r=s.plainObjects?Object.create(null):{},n=Object.keys(i),a=0;a<n.length;++a){var o=n[a],l=Dv(o,i[o],s);r=bv.merge(r,l,s)}return bv.compact(r)};const Mv=ci("fpads:macros"),xv=/\[([\s\S]+?)\]/g;class Macros{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((i,r)=>{const n=Macros.process_str(r,e,s,!0),a=t[r];return null===a?(i[n]=a,i):"object"==typeof a?(i[n]=Macros.process_obj(a,e,s),i):"string"==typeof a?(i[n]=Macros.process_str(a,e,s),i):(console.error(new Error(`${a} at ${r} not a handled Macro type`)),i)},{})}static process_str(t,e,s,i=!1){return t.replace(e.pattern,(t,e)=>{const r=Macros.normalize(e);if(!(r in s)||void 0===s[r])return t;const n=s[r],a=i?n:Macros.cast(n);return Mv("Macro.replace(raw: %s, macro: %s, value: %s)",i,e,a),a})}constructor(t={},e=xv){this.vars=t,this.pattern=e}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),[i,r]=t.split("?"),n=Ov(r||"",{strictNullHandling:!0,decoder:t=>t}),a=Cv(Macros.process_obj(n,this,s),{encode:!1,strictNullHandling:!0});return Macros.process_str(i,this,s,!0)+"?"+a}}function Fv(t,e={width:0,height:0}){let s,i;try{const t=document.createElement("a");t.href=s=window.location!=window.parent.location?document.referrer:document.location.href,i=t.hostname}catch(t){console.error(t)}const{width:r,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:i,player_width:r,player_height:n,video_url:a,videourl:a},o)}Macros.patterns={BRACKETS:xv,CURLY:/\{([\s\S]+?)\}/g,UNDERSCORE:/__([\s\S]+?)__/g};const Nv=/^flowplayer:\/\/(.+)/;async function Uv(t){if("string"==typeof t&&Nv.test(t)){const e=Nv.exec(t),s=e&&window[e[1]];if(s)return Uv(s)}if("function"!=typeof t)return t;try{return await t()}catch(t){return""}}async function Bv(t){if("function"==typeof t)return[await Uv(t)];if("string"==typeof t)return[await Uv(t)];if(Array.isArray(t)){const e=t;return await Promise.all(e.map(Uv))}if("object"==typeof t&&t&&t.adTag)return await Bv(t.adTag);throw new Error(`\n unhandled ads type ${typeof t}:\n ${JSON.stringify(t)}\n can be:\n | Array<string>\n | string\n | function\n | {adTag: Array<string>|string|function}\n `)}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 i=s?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 $v=Object.prototype,Gv=Object.getPrototypeOf;const Hv=ci("fpads:ads:state");var Kv;!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"}(Kv||(Kv={}));class AdsState{static of(){return new AdsState}constructor(t=0){this._state=t}reset(){this._state=0}toggleState(t,e){return void 0===t&&Hv(new Error("AdState cannot toggleState for `undefined`")),void 0===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 Vv={ok:ci("fpads:analytics:request-queue"),err:ci("fpads:analytics:request-queue:err"),warn:ci("fpads:analytics:request-queue:warn")};class RequestQueue{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 Vv.ok("maybe_spawn_req called Queue that is EMPTY"),t;if(RequestQueue.is_high_water(t))return Vv.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){Vv.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,i]){if(Vv.ok(`Request[${i.event_type}] request`,i,t.stats),Date.now()<t.stats.ttl)return Vv.warn(`Request[${i.event_type}] skipping because too many errors too quickly`,t.stats);const r=new XMLHttpRequest;t.open.push(r),r.timeout=RequestQueue.REQUEST_TIMEOUT_MS,r.ontimeout=function(){RequestQueue.handle_error(t,r),Vv.warn(`Request[${i.event_type}] timed out in ${r.timeout}ms`,t.stats)},r.onerror=function(e){RequestQueue.handle_error(t,r),e&&Vv.err(e),Vv.warn(`Request[${i.event_type}] encountered an Error`,r.responseText,t.stats)},r.onreadystatechange=function(){r.readyState==XMLHttpRequest.DONE&&RequestQueue.rm(t,r),Math.floor(r.status/100)},r.onload=function(){RequestQueue.rm(t,r),t.stats.failures&&t.stats.failures--,Vv.ok(`Request[${i.event_type}] :ok`,r.status)},r.open(s,e),r.setRequestHeader("Content-Type","text/plain;charset=UTF-8");try{r.send(JSON.stringify(i))}catch(t){Vv.err(t)}}static rpush(t,...e){return e.forEach(e=>{if(RequestQueue.is_high_water(t))return Vv.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}constructor(t=[],e=[],s={failures:0,ttl:0}){this.pending=t,this.open=e,this.stats=s}}RequestQueue.MAX_OPEN_REQUESTS=3,RequestQueue.REQUEST_TIMEOUT_MS=4e3,RequestQueue.REQUEST_TTL_MS=5e3,RequestQueue.MAX_FAILURE_COUNT=3;const jv={"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"},qv={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"},Wv={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},Yv={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"},zv={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":case"NT 5.1":return"XP";case"NT 5.0":return"2000";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 i=Utils.getVersionPrecision(t),r=Utils.getVersionPrecision(e);let n=Math.max(i,r),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(i,r)),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 i;if(Array.prototype.map)return Array.prototype.map.call(t,e);for(i=0;i<t.length;i+=1)s.push(e(t[i]));return s}static find(t,e){let s,i;if(Array.prototype.find)return Array.prototype.find.call(t,e);for(s=0,i=t.length;s<i;s+=1){const i=t[s];if(e(i,s))return i}}static assign(t,...e){const s=t;let i,r;if(Object.assign)return Object.assign(t,...e);for(i=0,r=e.length;i<r;i+=1){const t=e[i];if("object"==typeof t&&null!==t){Object.keys(t).forEach(e=>{s[e]=t[e]})}}return t}static getBrowserAlias(t){return jv[t]}static getBrowserTypeByAlias(t){return qv[t]||""}}const Qv=/version\/(\d+(\.?_?\d+)+)/i,Xv=[{test:[/googlebot/i],describe(t){const e={name:"Googlebot"},s=Utils.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,t)||Utils.getFirstMatch(Qv,t);return s&&(e.version=s),e}},{test:[/opera/i],describe(t){const e={name:"Opera"},s=Utils.getFirstMatch(Qv,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(Qv,t);return s&&(e.version=s),e}},{test:[/SamsungBrowser/i],describe(t){const e={name:"Samsung Internet for Android"},s=Utils.getFirstMatch(Qv,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(Qv,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(Qv,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(Qv,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(Qv,t);return s&&(e.version=s),e}},{test:[/coast/i],describe(t){const e={name:"Opera Coast"},s=Utils.getFirstMatch(Qv,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(Qv,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(Qv,t);return s&&(e.version=s),e}},{test:[/ucbrowser/i],describe(t){const e={name:"UC Browser"},s=Utils.getFirstMatch(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,t);return s&&(e.version=s),e}},{test:[/playstation 4/i],describe(t){const e={name:"PlayStation 4"},s=Utils.getFirstMatch(Qv,t);return s&&(e.version=s),e}},{test:[/safari|applewebkit/i],describe(t){const e={name:"Safari"},s=Utils.getFirstMatch(Qv,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 Zv=[{test:[/Roku\/DVP/],describe(t){const e=Utils.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,t);return{name:Yv.Roku,version:e}}},{test:[/windows phone/i],describe(t){const e=Utils.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,t);return{name:Yv.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:Yv.Windows,version:e,versionName:s}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(t){const e={name:Yv.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),i={name:Yv.MacOS,version:e};return s&&(i.versionName=s),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:Yv.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),i={name:Yv.Android,version:e};return s&&(i.versionName=s),i}},{test:[/(web|hpw)[o0]s/i],describe(t){const e=Utils.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,t),s={name:Yv.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:Yv.BlackBerry,version:e}}},{test:[/bada/i],describe(t){const e=Utils.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,t);return{name:Yv.Bada,version:e}}},{test:[/tizen/i],describe(t){const e=Utils.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,t);return{name:Yv.Tizen,version:e}}},{test:[/linux/i],describe:()=>({name:Yv.Linux})},{test:[/CrOS/],describe:()=>({name:Yv.ChromeOS})},{test:[/PlayStation 4/],describe(t){const e=Utils.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,t);return{name:Yv.PlayStation4,version:e}}}],Jv=[{test:[/googlebot/i],describe:()=>({type:"bot",vendor:"Google"})},{test:[/huawei/i],describe(t){const e=Utils.getFirstMatch(/(can-l01)/i,t)&&"Nova",s={type:Wv.mobile,vendor:"Huawei"};return e&&(s.model=e),s}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:()=>({type:Wv.tablet,vendor:"Nexus"})},{test:[/ipad/i],describe:()=>({type:Wv.tablet,vendor:"Apple",model:"iPad"})},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:()=>({type:Wv.tablet,vendor:"Apple",model:"iPad"})},{test:[/kftt build/i],describe:()=>({type:Wv.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"})},{test:[/silk/i],describe:()=>({type:Wv.tablet,vendor:"Amazon"})},{test:[/tablet(?! pc)/i],describe:()=>({type:Wv.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:Wv.mobile,vendor:"Apple",model:e}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:()=>({type:Wv.mobile,vendor:"Nexus"})},{test:[/[^-]mobi/i],describe:()=>({type:Wv.mobile})},{test:t=>"blackberry"===t.getBrowserName(!0),describe:()=>({type:Wv.mobile,vendor:"BlackBerry"})},{test:t=>"bada"===t.getBrowserName(!0),describe:()=>({type:Wv.mobile})},{test:t=>"windows phone"===t.getBrowserName(),describe:()=>({type:Wv.mobile,vendor:"Microsoft"})},{test(t){const e=Number(String(t.getOSVersion()).split(".")[0]);return"android"===t.getOSName(!0)&&e>=3},describe:()=>({type:Wv.tablet})},{test:t=>"android"===t.getOSName(!0),describe:()=>({type:Wv.mobile})},{test:t=>"macos"===t.getOSName(!0),describe:()=>({type:Wv.desktop,vendor:"Apple"})},{test:t=>"windows"===t.getOSName(!0),describe:()=>({type:Wv.desktop})},{test:t=>"linux"===t.getOSName(!0),describe:()=>({type:Wv.desktop})},{test:t=>"playstation 4"===t.getOSName(!0),describe:()=>({type:Wv.tv})},{test:t=>"roku"===t.getOSName(!0),describe:()=>({type:Wv.tv})}],ty=[{test:t=>"microsoft edge"===t.getBrowserName(!0),describe(t){if(/\sedg\//i.test(t))return{name:zv.Blink};const e=Utils.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,t);return{name:zv.EdgeHTML,version:e}}},{test:[/trident/i],describe(t){const e={name:zv.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:zv.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:zv.Gecko},s=Utils.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:zv.Blink})},{test:[/(apple)?webkit/i],describe(t){const e={name:zv.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(Xv,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(Zv,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(Jv,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(ty,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 i={};let r=0;if(Object.keys(t).forEach(n=>{const a=t[n];"string"==typeof a?(i[n]=a,r+=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 i=Utils.find(t,t=>this.isPlatform(t));if(i){const t=this.satisfies(e[i]);if(void 0!==t)return t}}if(r>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 s=this.getBrowserName().toLowerCase();let i=t.toLowerCase();const r=Utils.getBrowserTypeByAlias(i);return e&&r&&(i=r.toLowerCase()),i===s}compareVersion(t){let e=[0],s=t,i=!1;const r=this.getBrowserVersion();if("string"==typeof r)return">"===t[0]||"<"===t[0]?(s=t.substr(1),"="===t[1]?(i=!0,s=t.substr(2)):e=[],">"===t[0]?e.push(1):e.push(-1)):"="===t[0]?s=t.substr(1):"~"===t[0]&&(i=!0,s=t.substr(1)),e.indexOf(Utils.compareVersions(r,s,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),i=/Android/.test(e)&&!/Firefox/.test(e),r=/^((?!chrome|android).)*safari/i.test(e),n=/chrome|crios/i.test(e)&&!/opr|opera|chromium|edg|ucbrowser|googlebot/i.test(e),a=/firefox|fxios/i.test(e)&&!/seamonkey/i.test(e),o=/edg/i.test(e),l=/opr|opera/i.test(e),d=/SamsungBrowser/.test(e),c=d&&/SMART-TV/.test(e);return{controls:!s,video:function(e){return t&&document.createElement("video").canPlayType(e)},lang:t&&window.navigator.language,android:i,iphone:s,safari:r,edge:o,opera:l,chrome:n,firefox:a,ios:t&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,samsung:d,samsung_tv:d&&c,touch:"ontouchstart"in window,tizen:"tizen"in window,webOS:"webos"in window,anyTv:"tizen"in window||"webos"in window}}const i="mount",r="retry",n="error",a="click",o="dblclick",l="mouseleave",d="mouseup",c="mousedown",h="mousemove",u="touchstart",f="touchmove",g="touchend",p="touchcancel",m="resize",v="fullscreenenter",y="fullscreenexit",E="loadedmetadata",T="loadeddata",S="progress",A="timeupdate",_="loadstart",b="volumechange",L="pause",R="playing",I="play",k="waiting",w="canplay",P="ended",D="seeked",C="seeking",O="durationchange",M="viewenter",x="viewleave",F="src",N="reap",U="qualities",B="qualitychange",$="quality:set",G="tracks:video:select",H="landscape",K="portrait",V="dvr",j="live",q="recover",W="seek:queued",Y="seek:cancel",z="remotesession:started",Q="remotesession:ended",X="intersectionchange",Z="renderplugin",J="audioonlysource",tt="error:fatal",et="config",st="state",it="beforeplay",rt="beforepause",nt="content:loadstart",at="flowplayer:error";var ot=Object.freeze({__proto__:null,MOUNT:i,RETRY:r,ERROR:n,CONTEXT_MENU:"contextmenu",CLICK:a,DBL_CLICK:o,KEYUP:"keyup",KEYDOWN:"keydown",LOAD:"load",MOUSE_ENTER:"mouseenter",MOUSE_LEAVE:l,MOUSE_UP:d,MOUSE_DOWN:c,MOUSE_MOVE:h,TOUCH_START:u,TOUCH_MOVE:f,TOUCH_END:g,TOUCH_CANCEL:p,RESIZE:m,SCROLL:"scroll",FULLSCREEN_ENTER:v,FULLSCREEN_EXIT:y,FULLSCREEN_CHANGE:"fullscreenchange",METADATA:E,DATA:T,PROGRESS:S,TIME_UPDATE:A,LOAD_START:_,VOLUME_CHANGE:b,PAUSE:L,PLAYING:R,PLAY:I,WAITING:k,CAN_PLAY:w,ENDED:P,SEEKED:D,SEEKING:C,DURATION_CHANGE:O,VIEW_ENTER:M,VIEW_LEAVE:x,SOURCE:F,REAP:N,QUALITIES:U,QUALITY_CHANGE:B,VIDEO_TRACKS:"videoTracks",SET_QUALITY:$,VIDEO_TRACK_SELECT:G,RECOMMENDATIONS_READY:"recommendationsready",LANDSCAPE:H,PORTRAIT:K,DVR:V,LIVE:j,RECOVER:q,SEEK_QUEUED:W,SEEK_CANCEL:Y,PLUGIN_REGISTERED:"plugin:registered",REMOTE_SESSION_STARTED:z,REMOTE_SESSION_ENDED:Q,INTERSECTIONCHANGE:X,WEBKIT_NEEDKEY:"webkitneedkey",RENDER_PLUGIN:Z,AUDIO_ONLY_SOURCE:J,NON_RECOVERABLE_ERROR:tt,CONFIG:et,STATE:st,BEFORE_PLAY:it,BEFORE_PAUSE:rt,CONTENT_REAL_LOAD_START:nt,CUEPOINTS:"cuepoints",CUEPOINT_START:"cuepointstart",CUEPOINT_END:"cuepointend",STANDARD_ERROR:at});const lt="flowplayer-ui",dt="flowplayer-logo",ct="flowplayer-control",ht="flowplayer-control-buttons",ut="flowplayer-live-status",ft="flowplayer-elapsed-time",gt="flowplayer-timeline-bar",pt="flowplayer-control-duration",mt="flowplayer-volume-control",vt="flowplayer-volume-bar",yt="flowplayer-header",Et="flowplayer-header-left-zone",Tt="flowplayer-header-right-zone",St="flowplayer-header-duration",At="flowplayer-middle",_t="flowplayer-middle-zone",bt="flowplayer-wait",Lt="flowplayer-middle-buttons",Rt="flowplayer-middle-left-zone",It="flowplayer-middle-right-zone",kt="flowplayer-small-play-icon",wt="flowplayer-small-pause-icon",Pt="flowplayer-play-icon",Dt="flowplayer-pause-icon",Ct="flowplayer-fullscreen-enter-icon",Ot="flowplayer-fullscreen-exit-icon",Mt="flowplayer-fast-forward-icon",xt="flowplayer-rewind-icon",Ft="flowplayer-volume-icon",Nt="flowplayer-live-countdown",Ut="flowplayer-error";var Bt=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",SETTINGS_MOUNT_ZONE:"flowplayer-settings-mount-zone",QSEL_MOUNT_ZONE:"flowplayer-qsel-mount-zone",ASEL_MOUNT_ZONE:"flowplayer-asel-mount-zone",VTSEL_MOUNT_ZONE:"flowplayer-vtsel-mount-zone",SPEED_MOUNT_ZONE:"flowplayer-speed-mount-zone",UI:lt,LOGO:dt,CONTROL:ct,CONTROL_BUTTONS:ht,LIVE_STATUS:ut,ELAPSED:ft,TIMELINE:gt,CHAPTERS_TIMELINE:"flowplayer-chapters-timeline-bar",CONTROL_DURATION:pt,VOLUME_CONTROL:mt,VOLUME_BAR:vt,HEADER:yt,HEADER_LEFT_ZONE:Et,HEADER_RIGHT_ZONE:Tt,HEADER_DURATION:St,MIDDLE:At,MIDDLE_ZONE:_t,WAIT:bt,MIDDLE_BUTTONS:Lt,MIDDLE_LEFT_ZONE:Rt,MIDDLE_RIGHT_ZONE:It,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:kt,SMALL_PAUSE_ICON:wt,PLAY_ICON:Pt,PAUSE_ICON:Dt,FULLSCREEN_ENTER_ICON:Ct,FULLSCREEN_EXIT_ICON:Ot,SKIP_NEXT_ICON:"flowplayer-skip-next-icon",SKIP_PREVIOUS_ICON:"flowplayer-skip-previous-icon",FAST_FORWARD_ICON:Mt,REWIND_ICON:xt,SHARE_ICON:"flowplayer-share-icon",SUBTITLES_MENU_ICON:"flowplayer-subs-menu-icon",SETTINGS_MENU_ICON:"flowplayer-settings-icon",MENU_BACK_ICON:"flowplayer-menu-back",VOLUME_ICON:Ft,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:Nt,PLAYLIST_CONTROLS:"flowplayer-playlist-controls",THUMBNAILS_CAROUSEL:"flowplayer-thumbnails-carousel",ERROR_COMPONENT:Ut,TV_MENU:"flowplayer-tv-menu",CUE_COMPONENT:"flowplayer-cue",SSAI_UI:"flowplayer-ssai-ui",SSAI_CONTROLS:"flowplayer-ssai-controls",SSAI_TIMELINE:"flowplayer-ssai-timeline",SSAI_INDICATOR:"flowplayer-ssai-indicator"});const $t="is-playing",Gt="is-fullscreen",Ht="is-paused",Kt="is-muted",Vt="is-loaded",jt="is-loading",qt="is-starting",Wt="is-seeking",Yt="is-disabled",zt="is-small",Qt="is-tiny",Xt="is-ended",Zt="is-live",Jt="is-error",te="is-waiting",ee="is-autoplay",se="is-toggling",ie="is-live-seeked",re="no-timeline",ne="has-poster",ae="will-play",oe="will-pause",le="has-menu-opened",de="is-touched",ce="is-hovered",he="is-touch-device",ue="will-seek",fe="is-seekable",ge="is-in-viewport",pe="no-controls",me="is-destroyed",ve="is-source-processing";var ye=Object.freeze({__proto__:null,PLAYING:$t,FULLSCREEN:Gt,PAUSED:Ht,MUTED:Kt,LOADED:Vt,LOADING:jt,STARTING:qt,SEEKING:Wt,DISABLED:Yt,SMALL:zt,TINY:Qt,TV:"is-tv",ENDED:Xt,LIVE:Zt,ERRORED:Jt,WAITING:te,AUTOPLAY:ee,SEAMLESS:"is-seamless",TOGGLING:se,LIVE_SEEKED:ie,NO_DVR:re,HAS_POSTER:ne,WILL_PLAY:ae,WILL_PAUSE:oe,MENU_OPENED:le,TOUCHED:de,HOVERED:ce,TOUCH_DEVICE:he,WILL_SEEK:ue,SEEKABLE:fe,IN_VIEWPORT:ge,NO_CONTROLS:pe,DESTROYED:me,IS_SOURCE_PROCESSING:ve});function Ee(t){this.message=t}Ee.prototype=new Error,Ee.prototype.name="InvalidCharacterError";var Te="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new Ee("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,i,r=0,n=0,a="";i=e.charAt(n++);~i&&(s=r%4?64*s+i:i,r++%4)?a+=String.fromCharCode(255&s>>(-2*r&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return a};var Se=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(Te(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 Te(e)}};function Ae(t){this.message=t}Ae.prototype=new Error,Ae.prototype.name="InvalidTokenError";var _e=function(t,e){if("string"!=typeof t)throw new Ae("Invalid token specified");var s=!0===(e=e||{}).header?0:1;try{return JSON.parse(Se(t.split(".")[s]))}catch(t){throw new Ae("Invalid token specified: "+t.message)}};_e.InvalidTokenError=Ae;const be=new Map,Le=(t,e)=>new(((t,e)=>{const s=t.get(e);if(!s)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 r=window.customElements.get(s);return"function"!=typeof r?i:r})(t._customElements,e))(t),Re=(t,e,s)=>{window.customElements.get(e)||window.customElements.define(e,s),t.customElements.get(e)||t.customElements.set(e,e)},Ie=(t,e)=>{const s=t.customElements.get(e),i=s&&s===e,r=Object.values(t.defaultElements).includes(e);return Boolean(r||i)};var ke,we;function Pe(t){return!0===t?we.ON:!1===t?we.OFF:t}!function(t){t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=4]="HIGH"}(ke||(ke={})),function(t){t[t.OFF=0]="OFF",t[t.ON=1]="ON",t[t.AUDIO_REQUIRED=2]="AUDIO_REQUIRED"}(we||(we={}));const De={Unknown:"00-00",MediaUnknown:"01-00",MediaUnavailable:"01-01",MediaUnsupportedVideoFormat:"01-02",MediaUnsupportedAudioFormat:"01-03",MediaBitrateExceeded:"01-04",MediaBufferOverread:"01-05",MediaIntegerOverflow:"01-06",MediaQuotaExceeded:"01-07",MediaInvalidCompositionDuration:"01-08",MediaInvalidCompositionSourceDuration:"01-09",MediaInvalidCompositionSourceStartTime:"01-10",MediaMalformedDepth:"01-11",PlaybackUnknown:"02-00",PlaybackVideoBufferUnderRun:"02-01",PlaybackAudioBufferUnderRun:"02-02",PlaybackVideoBufferingTimeout:"02-03",PlaybackAudioBufferingTimeout:"02-04",PlaybackManifestParseError:"02-05",PlaybackVideoDecodeError:"02-06",PlaybackAudioDecodeError:"02-07",PlaybackDroppedFramesExceeded:"02-08",PlaybackPlayheadExceedsDuration:"02-09",PlaybackUnsupportedDevice:"02-10",PlaybackManifestLoadError:"02-11",PlaybackManifestLoadTimeout:"02-12",PlaybackManifestParsingError:"02-13",PlaybackManifestIncompatibleCodecs:"02-14",PlaybackLevelEmptyError:"02-15",PlaybackLevelLoadError:"02-16",PlaybackLevelLoadTimeout:"02-17",PlaybackLevelSwitchError:"02-18",PlaybackAudioTrackLoadError:"02-19",PlaybackAudioTrackLoadTimeout:"02-20",PlaybackFragLoadError:"02-21",PlaybackFragLoadTimeout:"02-22",PlaybackFragDecryptError:"02-23",PlaybackFragParsingError:"02-24",PlaybackFragGap:"02-25",PlaybackRemuxAllocError:"02-26",PlaybackBufferAddCodecError:"02-27",PlaybackBufferIncompatibleCodecs:"02-28",PlaybackBufferAppendError:"02-29",PlaybackBufferStalledError:"02-30",PlaybackBufferFullError:"02-31",PlaybackBufferSeekOverHole:"02-32",PlaybackBufferNudgeOnStall:"02-33",PlaybackInternalException:"02-34",PlaybackInternalAborted:"02-35",PlaybackManifestLoaderFailure:"02-36",PlaybackSegmentBaseLoaderError:"02-37",PlaybackTimeSyncFailed:"02-38",PlaybackFragmentLoaderFailure:"02-39",PlaybackAppendError:"02-40",PlaybackRemoveError:"02-41",PlaybackDataUpdateFailed:"02-42",PlaybackManifestNoStreams:"02-43",PlaybackUnknownManifestType:"02-44",PlaybackDashInsufficientSegmentInfo:"02-45",PlaybackDashNoRepresentations:"02-46",PlaybackDashNoAdaptationSets:"02-47",PlaybackDashNoInitSegment:"02-48",PlaybackDashUnsupportedContainerFormat:"02-49",PlaybackDashKeySystemMismatch:"02-50",PlaybackMultipleKeyIDs:"02-51",PlaybackDashConflictingKeyIDs:"02-52",PlaybackRestrictedStreams:"02-53",PlaybackHlsMasterAndMediaTags:"02-54",PlaybackRepresentationIdConflict:"02-55",PlaybackHlsUnsupportedKeyFormats:"02-56",PlaybackManifestNoVariants:"02-57",PlaybackHlsUndeclaredVariables:"02-58",PlaybackAes128InvalidKeyLength:"02-59",PlaybackDashConflictingAes128Keys:"02-60",PlaybackDashUnsupportedAes128Encryption:"02-61",PlaybackManifestPatchMismatch:"02-62",PlaybackEmptyMediaPlaylist:"02-63",PlaybackNonContiguousCompositionTrack:"02-64",PlaybackDecoderNotFound:"02-65",PlaybackDecoderTemporarilyUnavailable:"02-66",PlaybackIncompatibleAsset:"02-67",PlaybackNoCompatibleExternalDisplay:"02-69",PlaybackOutOfMemory:"02-70",PlaybackToneMappingFailed:"02-71",PlaybackVideoCompositorFailed:"02-72",NetworkUnknown:"03-00",NetworkNoInternet:"03-01",NetworkRequestTimeout:"03-02",NetworkUnableToResolveHost:"03-03",NetworkResourceNotFound:"03-04",NetworkExpiredUrl:"03-05",NetworkUrlResolutionFailed:"03-06",NetworkDownloadErrorIdManifest:"03-07",NetworkDownloadErrorIdSidx:"03-08",NetworkDownloadErrorIdContent:"03-09",NetworkDownloadErrorIdInitialization:"03-10",NetworkDownloadErrorIdXlink:"03-11",NetworkHttpRequestFailed:"03-12",NetworkMaxRetriesExceeded:"03-13",NetworkSegmentMissing:"03-14",NetworkHttp400BadRequest:"03-400",NetworkHttp401Unauthorized:"03-401",NetworkHttp402PaymentRequired:"03-402",NetworkHttp403Forbidden:"03-403",NetworkHttp404NotFound:"03-404",NetworkHttp405MethodNotAllowed:"03-405",NetworkHttp406NotAcceptable:"03-406",NetworkHttp407ProxyAuthenticationRequired:"03-407",NetworkHttp408RequestTimeout:"03-408",NetworkHttp409Conflict:"03-409",NetworkHttp410Gone:"03-410",NetworkHttp411LengthRequired:"03-411",NetworkHttp412PreconditionFailed:"03-412",NetworkHttp413PayloadTooLarge:"03-413",NetworkHttp414URITooLong:"03-414",NetworkHttp415UnsupportedMediaType:"03-415",NetworkHttp416RangeNotSatisfiable:"03-416",NetworkHttp417ExpectationFailed:"03-417",NetworkHttp418ImATeapot:"03-418",NetworkHttp421MisdirectedRequest:"03-421",NetworkHttp422UnprocessableEntity:"03-422",NetworkHttp423Locked:"03-423",NetworkHttp424FailedDependency:"03-424",NetworkHttp425TooEarly:"03-425",NetworkHttp426UpgradeRequired:"03-426",NetworkHttp428PreconditionRequired:"03-428",NetworkHttp429TooManyRequests:"03-429",NetworkHttp431RequestHeaderFieldsTooLarge:"03-431",NetworkHttp451UnavailableForLegalReasons:"03-451",NetworkHttp500InternalServerError:"03-500",NetworkHttp501NotImplemented:"03-501",NetworkHttp502BadGateway:"03-502",NetworkHttp503ServiceUnavailable:"03-503",NetworkHttp504GatewayTimeout:"03-504",NetworkHttp505HTTPVersionNotSupported:"03-505",NetworkHttp506VariantAlsoNegotiates:"03-506",NetworkHttp507InsufficientStorage:"03-507",NetworkHttp508LoopDetected:"03-508",NetworkHttp510NotExtended:"03-510",NetworkHttp511NetworkAuthenticationRequired:"03-511",ContentProtectionUnknown:"04-00",ContentProtectionConcurrentStreamLimitExceeded:"04-01",ContentProtectionEntitlementRefused:"04-02",ContentProtectionLicenseExpired:"04-03",ContentProtectionBadLicenseRequest:"04-04",ContentProtectionLicenseServerTimeout:"04-05",ContentProtectionInsufficientHDCPSupport:"04-06",ContentProtectionGeoRestricted:"04-07",ContentProtectionParentalControlRestricted:"04-08",ContentProtectionCDNUnauthorized:"04-09",ContentProtectionInvalidAccessToken:"04-10",ContentProtectionKeySystemNoKeys:"04-11",ContentProtectionKeySystemNoAccess:"04-12",ContentProtectionKeySystemNoSession:"04-13",ContentProtectionKeySystemNoConfiguredLicense:"04-14",ContentProtectionKeySystemCertificateRequestFailed:"04-15",ContentProtectionKeySystemCertificateUpdateFailed:"04-16",ContentProtectionKeySystemSessionUpdateFailed:"04-17",ContentProtectionKeySystemStatusOutputRestricted:"04-18",ContentProtectionKeySystemStatusInternalError:"04-19",ContentProtectionKeyLoadError:"04-20",ContentProtectionKeyLoadTimeout:"04-21",ContentProtectionCapabilityMediaKeysError:"04-22",ContentProtectionManifestKeySystemUnknown:"04-23",ContentProtectionKeySystemUnavailable:"04-24",ContentProtectionCDMCreationFailed:"04-25",ContentProtectionCDMAttachFailed:"04-26",ContentProtectionCDMServerCertificateRejected:"04-27",ContentProtectionCDMSessionCreationFailed:"04-28",ContentProtectionCDMLicenseRequestFailed:"04-29",ContentProtectionCDMLicenseResponseRejected:"04-30",ContentProtectionManifestMissingDRMInfo:"04-31",ContentProtectionLicenseServerMissing:"04-32",ContentProtectionOfflineSessionRemoved:"04-33",ContentProtectionInitDataTransformationError:"04-34",ContentProtectionServerCertificateRequestFailed:"04-35",ContentProtectionInsufficientHDCPVersion:"04-36",ContentProtectionHDCPVersionCheckFailed:"04-37",AdsUnknown:"08-00",AdsVastParseError:"08-100",AdsInvalidVastSchema:"08-101",AdsVastVersionNotSupported:"08-102",AdsUnexpectedAdType:"08-200",AdsCreativeLinearityMismatch:"08-201",AdsCreativeDurationMismatch:"08-202",AdsCreativeSizeMismatch:"08-203",AdsWrapperVastError:"08-300",AdsVastResponseRedirectTimeout:"08-301",AdsWrapperLimitReached:"08-302",AdsVastResponseEmpty:"08-303",AdsLinearAdDisplayError:"08-400",AdsMediaFileNotFound:"08-401",AdsMediaFileUnavailable:"08-402",AdsUnsupportedMimeType:"08-403",AdsUnableToDisplayMediaFile:"08-405",AdsMezzanineFileMissing:"08-406",AdsMezzanineFileDownloaded:"08-407",AdsRejectedAd:"08-408",AdsInteractiveCreativeError:"08-409",AdsVerificationNodeExecutionError:"08-410",AdsNonLinearAdDisplayError:"08-500",AdsNonLinearAdSizeMismatch:"08-501",AdsNonLinearAdFetchError:"08-502",AdsNonLinearUnsupportedType:"08-503",AdsCompanionAdDisplayError:"08-600",AdsCompanionAdSizeMismatch:"08-601",AdsRequiredCompanionAdError:"08-602",AdsCompanionAdFetchError:"08-603",AdsUndefinedVastError:"08-900",AdsUnknownVpaidError:"08-901",AdsVastDocumentEmpty:"08-999"},Ce=Object.fromEntries(Object.entries(De).map(([t,e])=>[e,t]));function Oe(t,e,s){const i="boolean"==typeof s;if("boolean"!=typeof s&&(s=!!t.hasState(oe)||t.paused),function(t,e,s){const i=t.poll(e?it:rt,{forced:s});return i&&i.defaultPrevented}(t,s,i))return Promise.resolve();if(!s)return t.hasState(ae)?(t.setState(oe,!0),t.setState(ae,!1),Promise.resolve()):Promise.resolve(t.pause());if(0==t.reaper)return Promise.resolve();const r=t.reaper.get("__pending_play");return t.paused||r?r?(r.src!==xe(t.original_src)&&Me(t),r):(function(t){return(0==t.networkState||0==t.readyState)&&t.currentSrc==xe(t.original_src)}(t)&&Me(t),function(t){const e=t.hasState(ee),s=e&&(t=>t.autoplay&&we.AUDIO_REQUIRED&Pe(t.autoplay))(t.opts);s&&(t.muted&&t.toggleMute(!1),0==t.volume&&(t.volume=1));e&&t.setState(ee,!1);return t.play().then(()=>{t.hasState(oe)&&t.togglePlay(!1)}).catch(i=>{if(console.warn(e?s?"[flowplayer/play] autoplay audio required\n%s":"[flowplayer/play] attempting muted autoplay\n%s":"",i.message,"\ninstance:",t),e&&!s)return t.muted=!0,t.play()})}(t)):(t.setState(oe,!1),!t.hasState($t)&&t.setState(ae,!0),Promise.resolve())}function Me(t){t.opts.is_native&&(t.hasState(Vt)||(t.hasState(jt)||t.emit(nt),t.setState(jt,!0),t.load()))}function xe(t){const e=document.createElement("a");return e.href=t,e.href}function Fe(t,e){var s={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(s[i]=t[i]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(t);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r])&&(s[i[r]]=t[i[r]])}return s}function Ne(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 Ue(t){switch(t){case"video/mpd":return"application/dash+xml";case"video/m3u8":return"application/x-mpegurl";default:return t}}const Be=t=>{var{src:e}=t,s=Fe(t,["src"]);return[Object.assign({src:e,type:e?Ue("video/"+Ne(e)):""},s)]};function $e(t){return Be({src:t})}function Ge(t){var{src:e,type:s}=t,i=Fe(t,["src","type"]);return e&&s?[Object.assign({src:e,type:s},i)]:s&&!e?[Object.assign({type:s},i)]:Be(Object.assign({src:e},i))}const He="health:record",Ke="rebuffer",Ve="rebuffer:ended",je="display",qe="insights:ttff",We="insights:time_to_first_frag_loaded",Ye="insights:watched_interval",ze="flowplayer:feature",Qe="health:ready";var Xe=Object.freeze({__proto__:null,RECORD:He,REBUFFER:Ke,REBUFFER_ENDED:Ve,DISPLAY:je,TIME_TO_FIRST_FRAME:qe,TIME_TO_FIRST_FRAGMENT_LOADED:We,WATCHED_INTERVAL:Ye,FEATURE_USAGE:ze,HEALTH_SERVICE_READY:Qe});const Ze={All:1,High:.1,Medium:.01,Low:.001,None:0};function Je(t,{feature_name:e,behavior:s,sample_rate:i}){e&&(i||(i=Ze.All),t.emit(ze,{feature_name:e,behavior:s,sample_rate:i}))}const ts=new Map;var es;function ss(t,e,s,i={safari:!1}){const r=is(s);return function(t){[Wt,oe,ae,$t,Ht,jt,Vt,ie].forEach(e=>t.setState(e,!1)),t.setState(qt,!0)}(t),Array(...Array(r.length)).map((t,e)=>e).some(s=>{const n=r[s];if(es.Ok==function(t,e,s){t.emit(F,s),e.playback_token&&"string"==typeof s.src&&s.src.startsWith("https://")&&(s.src=function(t,e){const s=new URL(t);return s.pathname=`/pt:${e}${s.pathname}`,s.toString()}(s.src,e.playback_token),Je(t,{feature_name:"signed-urls",behavior:"used",sample_rate:.1}));"string"==typeof s.src&&(t.original_src=s.src);const i=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:!i}),i?(i.onload(e,t.root,t,s),es.Ok):es.Err}(t,e,n)||es.Ok==function(t,e,s,i={safari:!1}){var r;/^audio\//.test(s.type||"")&&t.emit(J);e.start_time&&(s.src=s.src+"#t="+e.start_time);if(""==t.canPlayType(s.type||""))return es.Err;if(s.drm&&(!s.drm["com.apple.fps.1_0"]||!i.safari))return es.Err;"string"==typeof s.src&&(t.preload=null!==(r=e.preload)&&void 0!==r?r:"auto",t.src=s.src);return es.Ok}(t,e,n,i))return!0;s==r.length-1&&"string"==typeof n.src&&(t.src=n.src)}),t}function is(t){return"string"==typeof t?$e(t):Array.isArray(t)||"object"!=typeof t?t.reduce(function(t,e){return"string"==typeof e&&(e=$e(e)),"object"!=typeof e||Array.isArray(e)||(e=Ge(e)),t.concat(e)},[]):Ge(t)}!function(t){t[t.Err=0]="Err",t[t.Ok=1]="Ok"}(es||(es={}));const rs=[N,C,F,Y];var ns;function as(t,e,s){return isNaN(t.duration)||isNaN(t.currentTime)?{}:(e.offset+=s,0==e.offset?os(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,os(t,e))},1e3),function(t,e){t.setState(ue,!0),t.setState(ns.BACKWARD,e.offset<0),t.setState(ns.FORWARD,e.offset>0)}(t,e),t.emit(W,e),e))}function os(t,e){e.timer&&clearTimeout(e.timer),e.timer=e.offset=0,function(t){t.setState(ns.FORWARD,!1),t.setState(ns.BACKWARD,!1),t.setState(ue,!1)}(t)}function ls(t,e,s){const i=function(t){return Array.isArray(t)?t.slice(0):t.split(".")}(e);for(;i.length;){if(null==t)return s;const e=i.shift();if("string"!=typeof e)return s;t=t[e]}return null==t?s:t}function ds(t){const e="number"==typeof t?t:parseInt(t,10);return(e>9?"":"0")+e}function cs(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 i=Math.floor(t/60);return t-=60*i,s>=1?(i-=60*s,e+s+":"+ds(i)+":"+ds(t)):e+ds(i)+":"+ds(t)}!function(t){t.FORWARD="forward",t.BACKWARD="backward"}(ns||(ns={}));const hs=navigator.languages||[navigator.language];function us(t,e,s,i){if((i=i||0)>=t.length)return s;return ls(t[i],e,us(t,e,s,i+1))}function fs(t,e,s){const i=new Map,r=e.lang;return r&&t[r]&&i.set(r,t[r]),function(){try{return hs.reduce((t,e)=>~e.indexOf("-")?t.concat(e,e.split("-")[0]):t.concat(e),[])}catch(t){return[]}}().forEach(function(e){t[e]&&!i.has(e)&&i.set(e,t[e])}),t[s]&&!i.has(s)&&i.set(s,t[s]),Array.from(i.values())}const gs=[1e7]+""+-1e3+-4e3+-8e3+-1e11,ps=()=>"undefined"==typeof crypto?"":gs.replace(/[018]/g,t=>(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)),ms="flowplayer/uuid";let vs="";!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 ys=["touchstart","touchmove"];function Es(t,e){const s=new CustomEvent(t,{detail:e,cancelable:!0});return e&&Object.defineProperty(s,"data",{get:()=>e}),s}function Ts(t,e,s){const i=Es(e,s);return t.dispatchEvent(i),t}function Ss(t,e,s){const i=Es(e,s);return t.dispatchEvent(i),i}function As(t,e,s,i){Array.isArray(e)?e.forEach(e=>_s(t,e,s,i)):_s(t,e,s,i)}function _s(t,e,s,i){if(r=e,!~ys.indexOf(r))return t.addEventListener(e,s,i),t;var r;const n=Object.assign(i||{},{passive:!0});return t.addEventListener(e,s,n),t}function bs(t,e,s,i){return As(t,e,s,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 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 Ls={preload:"auto",rtl:!1,controls:!0},Rs=["muted","preload"];function Is(t,i,r){let n;r.live_state={dvr_window:void 0,get dvr(){return n},set dvr(e){n=e;const s=!(!t.live||e);r.hasState(re)!=s&&r.setState(re,s)}},r._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),r.toJSON=function(){return{duration:r.duration,volume:r.volume,currentTime:r.currentTime,states:r.root.className}},r.setSrc=function(e){return ss(r,t,e,s())},r.playerState=r.playerState||{},r.setState=function(t,e){if(r.playerState[t]===!!e)return r;const s=Object.assign({},r.playerState,{[t]:e});return r.playerState=s,Ts(r,st,r.playerState),r},r.createComponents=function(...t){return Array.from({length:t.length}).map((e,s)=>Le(this,t[s]))},r.hasState=function(t){return!!r.playerState[t]},r.transitionState=function(t,e,s){!r.hasState(t)&&r.hasState(e)||(s=0),s&&r.setState(se,!0),r.setState(e,!1),r.setState(t,!0),s&&setTimeout(function(){r.setState(se,!1)},s)},r.emit=(t,e)=>(Ts(r,t,e),r),r.on=(t,e)=>(As(r,t,e),r),r.once=(t,e)=>(bs(r,t,e),r),r.off=(t,e)=>{var s,i;return s=t,i=e,r.removeEventListener(s,i),r},r.poll=(t,e)=>Ss(r,t,e),r.togglePlay=function(t){return r.hasState(Jt)?Promise.reject():Oe(r,0,t)},r.toggleMute=function(t){t=null==t?!r.muted:!!t,r.muted=t,r.muted||r.volume||(r.volume=1),Ts(r,b)},r.toggleDisable=function(t){t=null==t?!r.disabled:!!t,r.setState(Yt,t),r.disabled=t},r.destroy=function(){r.pause();const t=e.indexOf(r);~t&&e.splice(t,1),setTimeout(function(){r.setSrc([]),r.reaper&&r.reaper.clear(),Ts(r,N),r.setState(me,!0)},0)},r.setAttrs=function(t){return Rs.forEach(e=>{if(!(e in t))return;const s=t[e];s?r.setAttribute(e,s.toString()):r.removeAttribute(e)}),r},r.opt=function(e,s){return s=void 0===s?ls(Ls,e):s,ls(t,e,s)},r.i18n=function(t,e){if(!r.reaper)return"";const s=r.reaper.get("translations");return s?us(s,t,e||""):e||""},r.setOpts=function(e){Object.assign(t,e),t.live&&!r.hasState(Zt)&&(r.setState(re,!0),Ts(r,j)),"disabled"in e&&void 0!==e.disabled&&r.toggleDisable(e.disabled),"muted"in e&&void 0!==e.muted&&r.toggleMute(e.muted),"dvr"in t&&(r.live_state.dvr=r.opt("dvr")),r.setState(Zt,!!t.live),r.setState(ne,"string"==typeof t.poster&&t.poster.length>0),r.setState(fe,!!t.seekable),r.setState(pe,0==t.controls),i.style.backgroundImage=r.hasState(ne)?"url('"+t.poster+"')":"",Ts(r,et,t)},r.renderPlugin=function(t){Ss(r,Z,t).defaultPrevented||r.root.appendChild(t)};const a={offset:0,timer:0};var o,l;l=a,(o=r).on(rs,function(){os(o,l)}),r.enqueueSeek=function(t){if(0!=r.opts.seekable&&!(1==r.opts.disabled&&t>0))return as(r,a,t)},r.deviceId=function(){return function(t){if(vs)return vs;try{const e=t.getItem(ms);if(e)return e;const s=ps();return t.setItem(ms,s),s}catch(t){return vs=ps()}}(r._storage)}}var ks="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function ws(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 Ps(){return"undefined"!=typeof window?window:void 0!==ks?ks:{}}const Ds=["localhost","127.0.0.1","0.0.0.0","s.codepen.io","cdpn.io","try.flowplayer.com"];function Cs(t,e){return!!~Ds.indexOf(t)||t.indexOf(e)===t.length-e.length}Cs.check_whitelist=function(t){return!!~Ds.indexOf(t)};const Os="production";function Ms(t,e){const s={valid_jwt:!1,raw:"",data:{acl:0},exp:0};let i={c:"{}",exp:0};e=e||{};try{i=_e(t),s.valid_jwt=!0}catch(t){}return s.raw=t,s.data=JSON.parse(i.c),s.exp=i.exp,e.require_valid_token&&Ms.validate(s),s}var xs;function Fs(t){return{grant:t,is_granted:e=>(t&e)===e}}Ms.validate=function(t){if("string"==typeof t&&(t=Ms(t)),!t||!t.raw){if(Cs.check_whitelist(window.location.hostname)||"dev"===Os.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=Cs.bind(null,e);if("dev"!==Os.toString()&&t.data.domain&&t.data.domain.length&&!t.data.domain.some(s))throw new Error("Domain not allowed");if("dev"!==Os.toString()&&1e3*t.exp-Date.now()<0)throw new Error("Expired token");return!0},Ms.id=function(t){if(t)return"string"==typeof t&&(t=Ms(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"}(xs||(xs={})),Fs.of=Fs,Fs.from_token=function(t){const e=Ms(t,{require_valid_token:!0});return Fs.of(e.data.acl)},Fs.permissions=xs;const Ns=["Expired token","No token provided in configuration","Invalid token provided","Domain not allowed"];function Us({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 i=!!(r=s.details)&&Ns.some(t=>r.includes(t));var r;const n=document.createElement("h2");n.textContent=i?"No Valid Token":"Playback Error";const a=document.createElement("p");a.textContent="Are you the site owner?";const o=document.createElement("a");o.classList.add("troubleshoot"),o.target="_blank",i?(o.href="https://form.typeform.com/to/YKJpmJSy",o.textContent="Get Trial Token (Beta)"):(o.href="https://docs.flowplayer.com/troubleshooting/player#"+s.reason,o.textContent="Troubleshoot?");const l=document.createElement("img");l.src="https://flowplayer.com/user/pages/images/logo-white.png",l.alt="Flowplayer Logo",t.append(n,a,o,l)}function Bs(t){return e=>{setTimeout(function(){if(!e.defaultPrevented&&!e.prevented)return t(e)},0)}}const $s="is-casting";function Gs(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 Hs(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 Ks(t,e){t.style.width="0",e.style.display="none"}function Vs(t,e,s){isNaN(t)||isNaN(e.duration)||(Gs(s,t),s.textContent=cs(t/100*e.duration))}function js(t,e){const s=t.seekable;if("object"!=typeof t.opts||0==s.length)return{head:0,tail:0};const i=Ys(t),r=e||t.live_state.dvr_window;return{head:i,tail:"number"!=typeof r||i-r<0?s.start(0):i-r}}function qs(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:js(t).head}function Ys(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 zs(t){const e=t.currentTime,s=js(t);return{progress:Math.min(100,Math.max(0,(e-s.tail)/(s.head-s.tail)*100)),is_live:e-s.head>=-10}}function Qs(t,e,s){if(!e.seekable||0==e.seekable.length)return;Gs(s,t);const i=js(e),r=(100-Math.max(0,Math.min(t,100)))/100*(i.head-i.tail);s.innerText="-"+cs(r)}function Xs(t){t.currentTime=js(t).tail}function Zs(t){try{t.dvr_offset=0,t.currentTime=Ys(t)}catch(t){console.warn("failed to seek to now: %j",t)}}function Js(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=js(t);return s.tail+e*(s.head-s.tail)}(e,t)}function ti(t,e){t.style.width="0",e.style.display="none"}function ei(t,e){const s=e.clientWidth;e.classList.toggle(zt,s<600),e.classList.toggle(Qt,s<400)}function si(t,e){if(!t.hasState(Zt)||![void 0,0,-1].includes(e)||!t.seekable.length||t.hasState("has-casted"))return t.setState(qt,!1);t.once(D,()=>t.setState(qt,!1)),0===e?Xs(t):Zs(t)}const ii=[0].concat(Array.from({length:100}).map((t,e)=>(e+1)/100));function ri(){return e.find(t=>t.hasState($s))}const ni=.5625;function ai(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}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(R,this.render),null===(e=this.player)||void 0===e||e.once(P,this.wireUp)}cleanUp(){var t,e,s,i;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(R,this.render),null===(i=this.player)||void 0===i||i.off(P,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 i=(null===(s=this.root)||void 0===s?void 0:s.querySelector(".fp-ui"))||this.root;if(!i)return;const r=this._logo=document.createElement("a");r.href="https://developer.wowza.com/docs/wowza-flowplayer",r.target="_blank",r.className="fp-explorer-logo",i.appendChild(r)}}ExplorerPlan.pluginName="explorer-plan";const oi="flowplayer/"+R;function li(t,e){const s=[];t.addEventListener("contextmenu",i=>{const r=i.timeStamp;for(s.push(r);s.length>3;)s.shift();s.length>=3&&s.every(t=>t-r<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 i=document.createElement("div");i.classList.add("debug-info");const r=di("flowplayer.version","3.43.0");i.append(r);const n=null===(s=null==e?void 0:e.hls)||void 0===s?void 0:s.constructor;if(n&&n.version){const t=di("hls.version",n.version);i.append(t)}t.appendChild(i)}(t,e))})}const di=(t,e)=>{const s=document.createElement("div");s.classList.add("row",t);const i=document.createElement("span");i.classList.add("attr"),i.textContent=t;const r=document.createElement("span");return r.textContent=e,r.classList.add("value"),s.append(i,r),s};function ci(t,e){const s=function(){try{return localStorage.getItem("flowplayer/debug")}catch(t){return""}}(),i=(i,...r)=>{try{const n=(null==e?void 0:e.debug)||s;n&&t.match(n)&&console.log(`flowplayer/${t} -- ${i}`,...r)}catch(t){console.warn(t)}};return i.log=i,i}const hi="on",ui="without_recovery",fi="off";class FlowplayerError extends Error{static getErrorKey(t){return t in Ce?Ce[t]:Ce["00-00"]}constructor(t,e,s={}){super(t),this.message=t,this.flowplayerErrorCode=e,this.config=s,this.id=ps(),this.isFatal=!!s.isFatal,this.errorKey=FlowplayerError.getErrorKey(this.flowplayerErrorCode)||"unknown"}toJSON(){return{message:this.message,flowplayer_error_code:this.flowplayerErrorCode,id:this.id,root_error_id:this.config.rootErrorId,resource:this.config.resource,is_fatal:this.isFatal,is_retry:!!this.config.isRetry}}}const gi=ci("core/retry");function pi(t,e){const s={pending:void 0,count:0};t.on(at,i=>{var n,a,o,l,d;const c=null===(n=i.detail)||void 0===n?void 0:n.error;c.config.isRetry=!!s.count,void 0===s.pending&&(null===(o=null===(a=c.config)||void 0===a?void 0:a.retryOpts)||void 0===o?void 0:o.retry)!==fi&&(e.retry||(null===(d=null===(l=c.config)||void 0===l?void 0:l.retryOpts)||void 0===d?void 0:d.retry))&&(++s.count,s.pending=function(t,e,s){var i,n;return setTimeout(()=>{var i;t.hasState(me)||(e.pending=void 0,(null===(i=s.config.retryOpts)||void 0===i?void 0:i.retry)!==ui&&t.emit(q),t.emit(r,{error:s}),gi("%s try",e.count))},null!==(n=null===(i=s.config.retryOpts)||void 0===i?void 0:i.retryTimeout)&&void 0!==n?n:3e3*e.count)}(t,s,c))}),t.on(R,()=>{s.count=0}),t.on([F,q],t=>{t.type===F&&(s.count=0),clearTimeout(s.pending),s.pending=void 0}),t.on(r,Bs(()=>{t.load()}))}const mi=[nt,n,F];function vi(t){const e=document.createElement("a");return e.href=t,e}function yi(t){try{return!!new URL(t)}catch(t){return!1}}function Ei(){try{return window.location.hostname!==window.parent.location.hostname?vi(document.referrer).hostname:document.location.hostname}catch(t){return window.location.hostname}}const Ti=navigator;function Si(t){var e,s;const i=null===(e=t.hls)||void 0===e?void 0:e.bandwidthEstimate;return i?1e-6*i:(null===(s=Ti.connection)||void 0===s?void 0:s.downlink)||-1}function Ai(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 _i=t=>{switch(t){case!0:return we.ON;case!1:return we.OFF;default:return t}};function bi(){try{const t=window.location!==window.parent.location?document.referrer:document.location.href;return"string"==typeof t&&t.slice(0,200)}catch(t){return!1}}const Li=[],Ri="https://ihi.flowplayer.com/v1/health/events";function Ii(t){if(t.suspended)return;const e=Li.slice(0);Li.length=0,0!=e.length&&(t.logger.log(`:dispatch events={${e.length}}`),Ai(function(){try{return"undefined"==typeof window?Ri:window.__FLOWPLAYER_INSIGHTS_URL?window.__FLOWPLAYER_INSIGHTS_URL:Ri}catch(t){return Ri}}(),e))}async function ki(t,e,s){const i=await Pi();Li.push(Object.assign(e,i)),t.logger.log(":enqueue",e.event,e),Li.length<10&&!s||Ii(t)}const wi=()=>{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}},Pi=async()=>({client_time:Date.now()}),Di=(t,e)=>Object.assign(t,{detail:e}),Ci=(t,{event:e,media_session_id:s,session_id:i,play_range_id:r})=>({event:e,media_session_id:s,session_id:i,play_range_id:r,device_id:t.deviceId(),version:"3.43.0",commit:"300a1de793160b6c70a459a62e5508403b45a573",ima_sdk_version:wi(),preload:t.opt("preload"),autoplay:_i(t.opt("autoplay")),live:t.opt("live"),dvr:!!t.live_state.dvr,source:t.original_src,downlink_mbs:Si(t),page_url:bi(),player_id:t.opt("metadata.player_id"),media_id:t.opt("metadata.media_id")||t.opt("metadata.stream_target_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")}),Oi=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"]});const Mi=(t,e)=>{let s=null;return(...i)=>{null!==s&&(clearTimeout(s),s=null),s=setTimeout(()=>e(...i),t)}};const xi="ad-initialized",Fi="ad-playback-error",Ni="ad-teardown",Ui="ad-videotag-attached",Bi="ad-request-error",$i="ad-requested",Gi="ad-request-completed",Hi="ad-pause-content",Ki="ad-started",Vi="ad-completed",ji="ad-paused",qi="ad-resumed",Wi="ad-progress",Yi="ad-skipped",zi="ad-muted",Qi="ad-volume-changed",Xi="ad-timeout",Zi="ad-break-completed",Ji="ad-postroll-finished",tr="ad-preroll-finished",er="vpaid-init",sr="ad-ima-adapter-init",ir="ad-ima-before-ads-request",rr="ad-ima-rendering-settings",nr="ad-adapter-init-failed",ar="ad-play-requested",or="reload-ad-requested",lr="ad-error",dr="request/ad/pause",cr="request/ad/play",hr="request/ad/muteunmute",ur="ad/show-first-frame",fr="ad/resize",gr="ad/set-ui-flags",pr="ad/pbjs";var mr,vr=Object.freeze({__proto__:null,AD_INIT:xi,AD_PLAYBACK_ERROR:Fi,AD_TEARDOWN:Ni,AD_VIDEOTAG_ATTACHED:Ui,AD_BLOCKED:"ad-blocked",AD_REQUEST_ERROR:Bi,AD_REQUESTED:$i,AD_REQUEST_COMPLETED:Gi,AD_PAUSE_CONTENT:Hi,AD_STARTED:Ki,AD_COMPLETED:Vi,AD_PAUSED:ji,AD_RESUMED:qi,AD_WAITING:"ad-waiting",AD_PROGRESS:Wi,AD_SKIPPED:Yi,AD_MUTED:zi,AD_VOLUME_CHANGED:Qi,AD_FULLSCREEN:"ad-fullscreen",AD_TIMEOUT:Xi,AD_BREAK_COMPLETED:Zi,AD_POSTROLL_FINISHED:Ji,AD_PREROLL_FINSIHED:tr,AD_MIDROLL_FINISHED:"ad-midroll-finished",VPAID_INIT:er,IMA_ADAPTER_INIT:sr,IMA_BEFORE_ADS_REQUEST:ir,IMA_ADS_RENDERING_SETTINGS:rr,ADAPTER_INIT_FAILED:nr,AD_PLAY_REQUESTED:ar,RELOAD_AD_REQUESTED:or,AD_ERROR:lr,REQUEST_AD_PAUSE:dr,REQUEST_AD_PLAY:cr,REQUEST_AD_MUTE_UNMUTE:hr,AD_SHOW_FIRST_FRAME:ur,AD_RESIZE:fr,AD_SET_UI_FLAGS:gr,PBJS_AVAILABLE:pr});!function(t){t[t.Starting=0]="Starting",t[t.ConfigFinalized=1]="ConfigFinalized",t[t.TimerStartedWithAutoplay=2]="TimerStartedWithAutoplay",t[t.TimerStartedWithUserGesture=3]="TimerStartedWithUserGesture",t[t.MetricReported=4]="MetricReported"}(mr||(mr={}));const yr=[a,g];class TimeToFirstFrame{constructor(t=mr.Starting,e=!1){this.state=t,this.loadedAd=e}reset(){this.state=mr.Starting,this.loadedAd=!1,this.start=void 0,this.end=void 0,this.adDetails=void 0}adInfo(){const{ad_tag_id:t,vast_ad_id:e}=this.adDetails||{};return{ad_tag_id:t,vast_ad_id:e}}toJSON(){return Object.assign({ad_was_requested:this.loadedAd,ms_to_first_frame:Math.round(this.end&&this.start?this.end-this.start:-1)},this.adInfo())}startTimer(t){this.state==mr.ConfigFinalized&&(this.state=t,this.start=performance.now())}hasStarted(){return[mr.TimerStartedWithAutoplay,mr.TimerStartedWithUserGesture].includes(this.state)}stopTimer(t){this.hasStarted()&&(this.end||(this.end=performance.now()),this.state=mr.MetricReported,t())}}function Er(t){return Math.round(1e3*t)/1e3}class EWMA$1{constructor(t){this.tickInterval=t,this.ewma=0,this.startTime=Date.now()}decay(){const t=Date.now()-this.startTime;return Math.pow(2,-t/(4*this.tickInterval))}update(t){const e=this.decay();return this.ewma=e*this.ewma+(1-e)*t,this.ewma}toJSON(){return this.ewma}}const Tr={skipUnreliableSegments:!0};class WatchedState{constructor(t){this.player=t,this.marchingInterval=void 0,this.lastWatchedPoint=void 0,this.watchedSum=0,this.lastReportedSum=0,this.ewmaTickWatched=new EWMA$1(WatchedState.AccuracyMilliseconds)}reset(){this.onNotWatching(),this.watchedSum=0,this.lastReportedSum=0,this.lastWatchedPoint=void 0}onNotWatching(){this.marchingInterval&&(this.updateWatched(),this.marchingInterval=clearInterval(this.marchingInterval))}onWatching(){this.marchingInterval||(this.lastWatchedPoint=this.createWatchedPoint(),this.marchingInterval=setInterval(()=>{this.updateWatched()},WatchedState.AccuracyMilliseconds))}createWatchedPoint(){return{currentTime:this.player.currentTime,paused:this.player.paused}}updateWatched(){const t=this.createWatchedPoint();this.lastWatchedPoint&&this.calculateTimeWatched(this.lastWatchedPoint,t),this.lastWatchedPoint=t}calculateTimeWatched(t,e){var s,i;const r=e.currentTime-t.currentTime,n=this.ewmaTickWatched.update(r);if(!(r<0)&&!(!1!==(null===(i=null===(s=this.player.opts)||void 0===s?void 0:s.health)||void 0===i?void 0:i.skipUnreliableSegments)&&1e3*r>1.3*WatchedState.AccuracyMilliseconds)&&(this.watchedSum+=r,this.watchedSum!=this.lastReportedSum&&(this.watchedSum>this.lastReportedSum+WatchedState.ReportingIntervalSeconds||this.player.ended))){const t=Er(n),e={total_watched_seconds:Er(this.watchedSum),tick_watched_seconds:t,batch_watched_seconds:Er(this.watchedSum-this.lastReportedSum)};this.lastReportedSum=this.watchedSum,this.player.emit(Ye,e)}}}WatchedState.ReportingIntervalSeconds=5,WatchedState.AccuracyMilliseconds=160;const Sr=ps();class Health{constructor(t,e){let s;this.session_id=Sr,this.suspended=!1,this.logger=ci("health",e.opts),this.media_session_id=ps(),this.play_range_id=ps(),this.analyticsLoop=setInterval(()=>Ii(this),2e3),e.on(N,()=>clearInterval(this.analyticsLoop)),e.on(R,()=>{s!==this.media_session_id&&(s=this.media_session_id,this.first_playing_event_timestamp=Date.now()),this.play_range_id=ps()});let i=Date.now()-1e3;e.on(A,t=>{if(s!==this.media_session_id)return;const r=Date.now();if(r<i)return;i=Date.now()+5e3;const n=Ci(e,this.eventInfo(t.type)),a=Di(n,{duration:(o=e.duration,Number.isFinite(o)?o:o===1/0?-1:void 0)});var o;this.first_playing_event_timestamp&&(Object.assign(a,{ms_since_first_playing:r-this.first_playing_event_timestamp}),this.first_playing_event_timestamp=void 0),ki(this,a)});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(()=>Ii(this),2e3)}init(t,e,s){if(bi().toString().startsWith("data:"))return this.suspend();!function(t){let e=null;const s=()=>{e=null};t.on(k,function(e){t.seeking||t.networkState===t.NETWORK_LOADING&&(t.readyState<HTMLMediaElement.HAVE_CURRENT_DATA||t.emit(Ke))}),t.on(Ke,t=>{e=t}),t.on(w,i=>{if(e){const r=i.timeStamp-e.timeStamp;if(s(),r<31)return;if(r>3e5)return;t.emit(Ve,{rebuffer_duration:r/1e3})}}),mi.forEach(e=>t.on(e,s))}(s),function(t){let e;[w,nt].forEach(s=>{t.on(s,s=>{const i=Date.now();switch(s.type){case nt:return e=i;case w:if(e)return t.emit(We,{ms_since_loading_started:i-e}),e=null}})})}(s),function(t){if(void 0===window.performance)return;const e=new TimeToFirstFrame;t.on(F,()=>{if(!t.opt("metadata.media_id"))return e.reset();e.reset(),e.state=mr.ConfigFinalized}),t.on(nt,()=>{(t.root.classList.contains("ad-hide-first-frame")||t.opt("autoplay"))&&e.startTimer(mr.TimerStartedWithAutoplay)}),yr.forEach(s=>{t.on(s,()=>{t.opt("autoplay")||e.startTimer(mr.TimerStartedWithUserGesture)})}),t.on($i,()=>{e.loadedAd=!0}),t.on(A,()=>{if(!(t.readyState<HTMLMediaElement.HAVE_CURRENT_DATA)){if(t.root.classList.contains("ad-hide-first-frame"))return!e.end&&(e.end=performance.now());switch(e.state){case mr.TimerStartedWithAutoplay:case mr.TimerStartedWithUserGesture:return e.stopTimer(()=>t.emit(qe,e.toJSON()))}}}),t.on(Ki,s=>{switch(e.end=void 0,e.adDetails=s.detail,e.state){case mr.TimerStartedWithAutoplay:case mr.TimerStartedWithUserGesture:return e.stopTimer(()=>t.emit(qe,e.toJSON()))}})}(s),function(t){const e=new WatchedState(t);t.on(nt,()=>e.reset()),t.on(R,()=>e.onWatching()),t.on(Ve,()=>!t.paused&&e.onWatching()),t.on(Ke,()=>e.onNotWatching()),t.on(L,()=>e.onNotWatching()),t.on(C,()=>{t.currentTime>1&&e.updateWatched(),e.onNotWatching()}),t.on(D,()=>{t.paused||e.onWatching()}),t.on(P,()=>e.updateWatched()),t.on("visibilitychange",()=>e.updateWatched())}(s),s.on(je,t=>{ki(this,Ci(s,this.eventInfo(t.type)),!0)}),s.on(He,({detail:t})=>{const e=Ci(s,this.eventInfo(t.event));Object.assign(e,t.detail||{}),ki(this,e)}),s.on(ze,t=>{if(e=t.detail.sample_rate,!Object.values(Ze).includes(e))return console.debug(`sample_rate=${t.detail.sample_rate} is invalid`);var e,i;if(!(0!==(i=t.detail).sample_rate&&Math.random()<=i.sample_rate))return;const r=Ci(s,this.eventInfo(t.type));ki(this,Di(r,t.detail))}),s.on(F,()=>{s.opt("metadata.media_id")&&s.emit(Qe)}),[_,E,T,S,k,Ke].forEach(t=>{s.on(t,t=>{ki(this,Ci(s,this.eventInfo(t.type)))})}),[Ve,qe,We,Ye].forEach(t=>{s.on(t,t=>{const e=Ci(s,this.eventInfo(t.type));ki(this,Object.assign(e,t.detail))})}),[R,L,C,D,P,v,y,w,nt].forEach(t=>{s.on(t,t=>{ki(this,Ci(s,this.eventInfo(t.type)))})}),s.on(b,Mi(800,t=>{const e=Ci(s,this.eventInfo(t.type));ki(this,Di(e,{volume:parseFloat(s.volume.toFixed(2)),muted:s.muted}))})),s.on(m,Mi(800,t=>{const i=Ci(s,this.eventInfo(t.type));ki(this,Di(i,{height:e.clientHeight,width:e.clientWidth}))})),s.on("hls/failover",t=>{const e=Ci(s,this.eventInfo(t.type)),i=t.detail,{reason:r,from:n}=i;ki(this,Di(e,{reason:r,from:n}))}),s.on(B,({type:t,detail:e})=>{if("hls"===e.plugin)return function(t,e,s,i){const r=Ci(e,t.eventInfo(s)),n=Object.assign({before:Oi(i.before),after:Oi(i.after),automatic:i.automatic,downscale:i.downscale},i.before?{}:{start_quality:e.opts.start_quality});ki(t,Object.assign(Object.assign({},r),{state:n}))}(this,s,t,e)}),s.on(at,t=>{const e=Ci(s,this.eventInfo(t.type)),i=t.detail.error;if(!i)return ki(this,e,!0);return ki(this,Di(e,i.toJSON()),!0)}),s.on(F,t=>{var e;const i=null===(e=t.detail)||void 0===e?void 0:e.src;if("string"!=typeof i)return;if(!yi(s.original_src))return;if(!yi(i))return;if(i==s.original_src)return;this.media_session_id=ps();ki(this,Ci(s,this.eventInfo(t.type))),Ii(this),s.setOpts({health:Object.assign(Object.assign({},s.opts.health),Tr)})}),s.on("visibilitychange",t=>{ki(this,Ci(s,this.eventInfo(t.type))),Ii(this)})}}function Ar(t,e){return function(t){return t.extensions.reduce((t,e)=>t.find(t=>t.pluginName===e.pluginName)?(console.warn("flowplayer: duplicate plugin %s detected, plugin names should be unique",e.name),t):(t.push(e),t),[])}(t).map(s=>new s(t,e))}function _r(t,e={}){var s,i,r,n,a,o;switch(t.code){case MediaError.MEDIA_ERR_ABORTED:return new FlowplayerError(null!==(s=t.message)&&void 0!==s?s:"The playback was aborted, typically by the user.",De.PlaybackInternalAborted,Object.assign({isFatal:!1,retryOpts:{retry:fi}},e));case MediaError.MEDIA_ERR_NETWORK:return new FlowplayerError(null!==(i=t.message)&&void 0!==i?i:"A network error prevented media from being downloaded.",De.NetworkHttpRequestFailed,Object.assign({isFatal:!0},e));case MediaError.MEDIA_ERR_DECODE:return new FlowplayerError(null!==(r=t.message)&&void 0!==r?r:"An error occurred while decoding the media.",De.PlaybackVideoDecodeError,Object.assign({isFatal:!0},e));case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:return new FlowplayerError(null!==(n=t.message)&&void 0!==n?n:"The media could not be loaded because the format is not supported.",De.MediaUnsupportedVideoFormat,Object.assign({isFatal:!0},e));case 5:return new FlowplayerError(null!==(a=t.message)&&void 0!==a?a:"Encrypted content could not be played due to missing keys or unsupported protection scheme.",De.ContentProtectionKeySystemNoKeys,Object.assign({isFatal:!0},e));default:return new FlowplayerError(null!==(o=t.message)&&void 0!==o?o:"An unknown playback error occurred.",De.PlaybackUnknown,Object.assign({isFatal:!0},e))}}Health.pluginName="health",Health.events=Xe,Health._UNLOAD_SUBSCRIBED=!1;const br=function(){const t=Ps(),e=t.flowplayer?t.flowplayer:{extensions:[]};return Array.isArray(e.extensions)||(e.extensions=[]),e}();function Lr(s,r){if("function"==typeof s)return t.push(...[...arguments].filter(t=>"function"==typeof t)),Lr;"string"==typeof r&&(r={src:r}),r||(r={}),r.token||"string"!=typeof window.__FLOWPLAYER_TOKEN||(r.token=window.__FLOWPLAYER_TOKEN);const a="string"==typeof s?document.querySelector(s):s;if(!a)return console.error(new Error("Flowplayer: '"+s.toString()+"' not found"));const o=a.querySelector("video.fp-engine");if(o)return o;const l=function(t){try{return Ms.validate(t),{success:!0,message:""}}catch(t){return{success:!1,message:t.message}}}(r.token);if(!l.success)return Us({root:a,data:{reason:"token",details:l.message}});const d=new Map,c=function(t,e){const s=e.querySelector("video"),i=s||(t._video_element_callback?t._video_element_callback(t):document.createElement("video"));return i.classList.add("fp-engine"),i.playsInline=!0,s||e.append(i),i}(r,a);var h;c.reaper=d,c._customElements=be,Object.defineProperty(c,"token",{value:"string"==typeof r.token?Ms.id(r.token):"",writable:!1}),c.addEventListener(N,()=>{d.clear(),c.reaper=0,delete c.root}),c.root=a,r.token&&Fs.from_token(r.token).is_granted(Fs.permissions.DEVELOPER_PLAN)&&Lr.extensions.push(ExplorerPlan),!~e.indexOf(c)&&e.push(c),Is(r,a,c),c.setAttrs(r),c.plugins=Ar(Lr,c),function(t,e,s){let i=!0;e.classList.add("flowplayer"),ei(0,e),bs(s,_,()=>{void 0!==t.start_quality&&Je(s,{feature_name:"start-quality",behavior:String(t.start_quality),sample_rate:Ze.High})}),As(s,_,()=>{if(!s.hasState(jt)&&!s.hasState(Vt)&&t.is_native&&"none"!==t.preload)return"metadata"===t.preload?(s.setState(jt,!0),s.emit(nt)):void Me(s)}),As(s,E,()=>{t.is_native&&"metadata"===t.preload&&s.paused&&s.emit(w)}),As(s,[_,m],function(){ei(0,e)}),As(s,st,function(){Object.entries(s.playerState).forEach(function([t,s]){e.classList.toggle(t,s)})}),As(s,A,function(){s.setState(te,!s.hasState($s)&&!s.hasState(qt)&&s.readyState<3)}),As(s,P,function(e){const i=s.original_src;Bs(()=>{if(i===s.original_src){if(s.setState(Xt,!0),bs(s,A,function(){s.setState(Xt,!1),i===s.original_src&&s.setState(qt,!t.loop&&!!t.rewind&&s.paused)}),t.loop)return s.togglePlay(!0);t.rewind&&(s.currentTime=0)}})(e)}),As(s,[C,D],function(t){s.setState(Wt,t.type==C)}),As(s,Q,function(t){setTimeout(()=>{t.defaultPrevented||(s.currentTime=t.detail.currentTime)},0)}),As(s,P,function(){s.setState($t,!1),i=!0}),As(s,S,()=>{if(!s.opts.live||!s.opts.is_native)return;const t=s.seekable;0!=t.length&&s.emit("dvr/window",t.end(t.length-1)-t.start(0))}),As(s,T,function(){s.setState(Vt,!0),s.setState(jt,!1)}),As(s,I,()=>{s.setState(ae,!0)}),As(s,[k,w,_],function(e){if(!s.hasState(Wt)&&(e.type!=w||t.autoplay||s.setState(te,!1),e.type!=_||"none"!=s.opt("preload")||t.autoplay)){if(e.type==_&&t.autoplay)return bs(s,R,function(){s.setState(te,!1)});e.type!=k||s.hasState(Vt)||s.setState(jt,!0),s.setState(Xt,!1),s.setState(te,e.type==k)}}),As(s,[R,L],function(e){setTimeout(()=>{const t=new CustomEvent("flowplayer/"+e.type,{detail:s});document.dispatchEvent(t)},0);const r=e.type==R,n=s.currentTime==s.duration,a=r&&i&&t.autoplay||s.hasState(te);if(r&&(s.started=!0,i=!1),s.setState(te,!1).setState(ae,!1),!r&&s.setState(oe,!1),n)return;const o=r?$t:Ht,l=r?Ht:$t;s.transitionState(o,l,a?0:300),!s.hasState(qt)||s.root.classList.contains("ad-hide-first-frame")||s.root.classList.contains("preroll-ios")||si(s,t.start_time)})}(r,a,c),function(t,e,s){if(!window.IntersectionObserver)return;const i={should_resume:!!t.autoplay,locked:!1};As(s,I,function(){i.locked||(i.should_resume=!0)});const r=()=>{if(!t.autoplay)return;if(s.hasState(ge)&&i.should_resume)return s.togglePlay(!0);const e=s.currentSrc;t.autopause||s.hasState(ge)||!i.should_resume||bs(s,M,()=>{t.autoplay&&i.should_resume&&e===s.currentSrc&&s.togglePlay(!0)})},n=()=>{if(!t.autoplay)return;if(!t.is_native)return;if("auto"===t.preload)return;if(s.hasState(ge))return Me(s);const e=s.currentSrc;bs(s,M,()=>{e!==s.currentSrc||s.readyState>1||!s.paused||Me(s)})};As(s,F,function(){i.should_resume=!!t.autoplay,s.off(_,n),s.once(_,n),s.off(w,r),s.once(w,r)}),As(s,L,function(){i.locked||(i.should_resume=!1)});const a=new IntersectionObserver(t=>{t.forEach(t=>{setTimeout(()=>{const e=t.intersectionRatio,i=s.hasState(ge);if(s.setState(ge,e>=.2),s.emit(X,{ratio:e}),i===s.hasState(ge))return;const r=s.hasState(ge)?M:x;s.emit(r)},0)})},{threshold:ii});a.observe(e),s.on(N,()=>a.disconnect()),As(s,M,function(){!i.should_resume||!t.autopause||ri()||s.opts.autoplay&&!s.readyState||s.togglePlay(!0)}),As(s,x,function(){if(!t.autopause||ri())return;const e=!s.paused;i.locked=!0,s.pause(),setTimeout(function(){i.should_resume=e,i.locked=!1},0)})}(r,a,c),function(t,e){if(!window.ResizeObserver)return;const s=new ResizeObserver(t=>{const s=t[t.length-1];e.emit(m,s)});s.observe(t),e.on(N,()=>s.disconnect())}(a,c),function(t,e,s){const i=!!t.ratio,r=document.createElement("div");r.classList.add("fp-ratio"),e.append(r);let n=ai(t.ratio||ni);r.style.paddingTop=100*n+"%";const a=[T,E];s.on(a,function(){if(i)return;const t=s.videoHeight&&s.videoWidth&&s.videoHeight/s.videoWidth;t&&s.setOpts({ratio:t})}),s.on(et,function(){const e=s.videoHeight&&s.videoWidth&&s.videoHeight/s.videoWidth,i=ai((null==t?void 0:t.ratio)||e||ni);n!==i&&(n=i,r.style.paddingTop=100*i+"%")})}(r,a,c),function(t){const e=e=>{e.detail!==t&&!1===t.opt("multiplay")&&t.togglePlay(!1)};t.on(N,()=>document.removeEventListener(oi,e)),document.addEventListener(oi,e)}(c),li(a,c),pi(c,r),(h=c).on(n,Bs(t=>{const e=t instanceof MediaError?t:h.error;e&&h.emit(at,{error:_r(e,{resource:h.original_src})})})),c.plugins.forEach(t=>{try{t.init(r,a,c)}catch(e){console.log("Error(plugin/%s)",t.constructor.name,e)}}),c.setOpts(r),c.opts=r,r.src&&c.setSrc(r.src);const u=c.readyState;return u>0&&c.currentSrc&&c.emit(E),u>2&&c.currentSrc&&c.emit(w),c.emit(i),c.on(tt,function(t){Us({root:a,video:c,data:t.data||{}})}),setTimeout(Ts,0,document,"flowplayer:player:created",c),c}Object.assign(Lr,br),function(i){Array.isArray(i.extensions)&&i.extensions.forEach(e=>t.push(e)),i.customElements=be,i.defaultElements=Bt,i.version="3.43.0",i.commit="300a1de793160b6c70a459a62e5508403b45a573",i.instances=e,i.extensions=t,i.support=s,i.events=ot,i.states=ye,i.errors=De,i.jwt=_e,i.autoplay=we,i.quality=ke}(Lr),"object"==typeof document&&setTimeout(Ts,0,document,"flowplayer:umd",Lr),Lr.extensions.unshift.apply(Lr.extensions,[Health]),"undefined"!=typeof window&&"function"==typeof window.matchMedia&&[H,K].forEach(function(t){window.matchMedia("(orientation: "+t+")").addListener(function(s){e.length&&e.forEach(function(e){s.matches&&e.emit(t)})})});function Rr(t,e,s){"undefined"!=typeof window&&"ontouchstart"in window&&s.setState(he,!0),s.setState("is-accessibility",!1)}const Ir=[_,q];function kr(t,e){const s=Le(e,Ut);t.append(s),e.on(at,i=>{if(!document.body.contains(t))return;const r=i.detail.error;!1!==r.config.showErrorUI&&(r.isFatal||r.config.showErrorUI)&&(e.setState(Jt,!0),console.warn(r),Ts(s,at,{error:r}),Ts(s,n,{error:r}))}),Ir.forEach(t=>e.on(t,()=>{!function(t){if(!t.hasState(Jt))return;t.setState(te,!0),t.setState(Jt,!1)}(e)}))}const wr=16384;var Pr=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:wr,LOGO_ON_BOTTOM:32768});function Dr(t,e){const s=t._customElements.get(e);return s&&t.root.querySelector(s)||void 0}function Cr(...t){const e=document.createElement("div");return 0==t.length||e.classList.add(...t),e}function Or(t,e,s){let i=()=>document.fullscreenElement,r="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),r="webkit"+r,i=()=>e.webkitCurrentFullScreenElement}const n=()=>s.getFullsceenTarget?s.getFullsceenTarget():e;s.toggleFullScreen=function(t,e){if(s.ios_fullscreen_disabled)return;if("boolean"!=typeof t&&(t=!s.hasState(Gt)),Mr(s)&&(t?function(t,e){t.getAttribute("playsinline")&&t.removeAttribute("playsinline");t.getAttribute("webkit-playsinline")&&t.removeAttribute("webkit-playsinline");e||t.webkitEnterFullScreen()}(s,e):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(de)||t.setState(de,!0)}(s,e)),!document.fullscreenEnabled)return;const r=n();if(t)return r.requestFullscreen();i()===r&&document.exitFullscreen()},Mr(s)&&(s.ios_fullscreen_disabled=!0,s.once(it,function(){s.ios_fullscreen_disabled=!1}),s.on(["webkitendfullscreen","webkitbeginfullscreen"],t=>{const e="webkitbeginfullscreen"===t.type;s.setState(Gt,e).emit(e?v:y).toggleFullScreen(e,!0)})),setTimeout(()=>{const t=n();t.addEventListener(r,function(){const e=i(),r=e===t||e==s;s.emit(r?v:y),s.setState(Gt,r)})},0),!1!==t.doubleclick&&e.addEventListener(o,function(t){var e;t.target&&(null===(e=t.target)||void 0===e?void 0:e.classList.contains("fp-ui"))&&s.toggleFullScreen()})}function Mr(t){return!document.fullscreenEnabled&&"function"==typeof t.webkitEnterFullScreen&&"function"==typeof t.webkitExitFullScreen}const xr="use-play-",Fr="mute";function Nr(t,e,s){if(!s.reaper)return;const i=document.createDocumentFragment(),r=Le(s,lt),n=Le(s,dt);e.append(n),i.append(r),s.reaper.set("ui",r),~e.className.indexOf(xr)||e.classList.add(xr+1),function(t,e,s){const i=Cr("fp-footer");e.append(i),s.on(et,function(t){var e,s;const r=null===(e=t.data)||void 0===e?void 0:e.description,n=null===(s=t.data)||void 0===s?void 0:s.title;if(i.innerHTML="","string"==typeof n){const t=Cr("fp-title");t.innerText=n,i.append(t)}if("string"==typeof r){const t=r.split(" "),e=Cr("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,s),kr(r,s),e.appendChild(i);let a=null;[h,f,l].forEach(t=>{e.addEventListener(t,function(t){if(!s.hasState(he)||t.type===f){if(clearTimeout(a),t.type===l)return s.setState(ce,!1);s.setState(ce,!0),a=setTimeout(function(){s.setState("is-hovered",!1)},2e3)}})}),Or(t,e,s),s.on(b,function(){const t=0==s.volume||s.muted;s.muted=t,s.setState(Kt,t),s._storage.setItem(Fr,t.toString())}),"true"==s._storage.getItem(Fr)&&(s.muted=!0,s.setState(Kt,s.muted));const o=s._storage.getItem("volume");o&&!isNaN(Number(o))&&(s.volume=Number(o)),s.emit(b),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 i=js(t,s);return i.head-i.tail>=e}(s,t.seconds_to_dvr||60,e.detail),s.live_state.dvr_window=e.detail)}),s.on(j,()=>{const t=setInterval(()=>{if(!s.opts.live||0==s.reaper)return clearInterval(t);if(0==s.seekable.length||s.hasState(Jt))return;const e=zs(s);s.hasState(ie)==e.is_live&&s.setState(ie,!e.is_live),s.live_state.dvr&&s.emit(V,e.progress)},200)}),s.on(E,function(){s.setOpts({live:qs(s)})}),s.on(O,function(t){const e=qs(s),i=e?Ws(s):t.data||s.duration;isNaN(i)||s.setOpts({live:e,duration:i})}),s.on(["playlist/advance",F],e=>{if(s.setState(ee,!!t.autoplay),s.root.classList.contains("is-livecountdown"))return Ur(s,t);(s.currentSrc||s.srcObject)&&(e.type===F&&["is-playlist",ve].some(t=>s.root.classList.contains(t))||Ur(s,t))}),s.on(et,function(s){var i,r;t.seekable=void 0===(null===(i=null==s?void 0:s.data)||void 0===i?void 0:i.seekable)||s.data.seekable;const n=null===(r=s.data)||void 0===r?void 0:r.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",(wr&n)>0)})}function Ur(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,"metadata"in e&&delete e.metadata}function Br(t,e,s){if(Fs.from_token(t.token||"").is_granted(Fs.permissions.NO_METERING))return;Ms.id(t.token||"")&&s.once(R,async()=>await $r(s,t.token||""))}async function $r(t,e){const s=Ms.id(e||"");t.once(F,()=>{t.once(R,()=>$r(t,e))});if(401==(await fetch("https://pmi.flowplayer.com/in",{method:"POST",body:JSON.stringify({token_id:s,factor:1,rnd:Math.random().toString(36).substring(2)})})).status)return t.emit(tt,{reason:"token",details:"The token online validation failed"})}class I18n{init(t,e,s){var i;s.reaper&&s.reaper.set("translations",fs(I18n,t,"en")),(i=s).once(Qe,()=>{const t=I18n.languagesLoaded().filter(t=>"en"!==t);t.length>0&&t.forEach(t=>{Je(i,{feature_name:"translations",behavior:`loaded-lang-${t}`,sample_rate:Ze.Low})})}),i.on(Qe,()=>{i.opts.lang&&Je(i,{feature_name:"translations",behavior:`used-lang-${i.opts.lang}`,sample_rate:Ze.Medium})})}static languagesLoaded(){return Object.keys(I18n).filter(t=>!I18n._nonLanguageFields.includes(t)).concat(I18n.en?["en"]:[])}}I18n.pluginName="i18n",I18n.en={ads:{ad:"Ad",ads:"Ads",advertisement:"Advertisement",indicator:"Ads",adchoices:"AdChoices"},audio:{button_txt:"Audio",menu_title:"Audio"},cc:{button:"CC",menu_title:"Subtitles",options:"Options",tracks:"Tracks",reset:"Reset",colors:{Black:"Black",Blue:"Blue",Cyan:"Cyan",Green:"Green",Magenta:"Magenta",Red:"Red",White:"White",Yellow:"Yellow"},edgeStyle:{None:"None","Drop shadow":"Drop shadow",Raised:"Raised",Depressed:"Depressed",Outline:"Outline"},fontFamily:{"Monospaced Serif":"Monospaced Serif","Proportional Serif":"Proportional Serif","Monospaced Sans-Serif":"Monospaced Sans-Serif","Proportional Sans-Serif":"Proportional Sans-Serif",Casual:"Casual",Cursive:"Cursive"},properties:{fontFamily:"Font family",fontSize:"Font size",fontColor:"Font color",fontOpacity:"Font opacity",backgroundColor:"Background color",backgroundOpacity:"Background opacity",characterEdgeStyle:"Character edge style"}},chromecast:{start:"start casting",stop:"stop casting"},core:{exit_fullscreen:"Exit fullscreen",fullscreen:"Fullscreen",mute:"Mute",muted:"Muted",pause:"Pause",play:"Play",seconds:"Seconds",timeline_aria_label:"Seek slider",unmute:"Unmute",volume:"Volume",options:"Options",close:"Close","skip-next":"Next","skip-prev":"Previous"},ovp:{starting_in:"Countdown"},playlist:{cancel:"Cancel",up_next:"Up next",autoplay:"Autoplay",now_playing:"Now playing",turn_off_autoplay:"Turn off autoplay",playlist:"Playlist"},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"},vtsel:{button_txt:"Video",menu_title:"Video Track"},spins:{more:"More",less:"Less"}},I18n._nonLanguageFields=[],I18n._nonLanguageFields=Object.keys(I18n);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(et,t=>{var s;const i=e.logo,r=(null===(s=null==t?void 0:t.data)||void 0===s?void 0:s.logo)||"";i!=r&&(e.logo=r,this.set_logo(r,t.detail.logo_alt_text,t.detail.logo_href))})}set_logo(t,e,s){this.innerHTML="";const i=document.createElement("img");if(!t)return;if(i.src=t,i.alt=e||"Logo",!s)return this.append(i);const r=document.createElement("a");r.href=s,r.append(i),this.append(r)}}class FlowplayerHeaderDuration extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-duration"),t.on(et,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)?cs(s):""})}}const Gr={name:"fp-fullscreen",translation_key:"core.fullscreen"},Hr={name:"fp-fullscreen-exit",translation_key:"core.exit_fullscreen"},Kr={name:"fp-play",translation_key:"core.play"},Vr={name:"fp-pause",translation_key:"core.pause"},jr={translation_key:"core.mute",name:"fp-volume-mute-unmute"},qr={translation_key:"core.play",name:"fp-small-play"},Wr={translation_key:"core.pause",name:"fp-small-pause"},Yr={name:"fp-fast-forward"},zr={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")}}function Qr(){}const Xr="fp-menu-container",Zr="details[open]."+Xr;document.addEventListener(a,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(Zr);s&&(s.open=!1,null===(e=s.querySelector("summary"))||void 0===e||e.removeAttribute("aria-expanded"),t.root.classList.toggle(le,!1))}),this.active_menu=void 0)});const Jr={passive:!0};var tn;function en(t,e){let s=0,i=-1,r=-1;const n=Math.random().toString(36).replace(/[^a-z]+/g,"").substr(0,5),a=t.classList;t.id=n,a.remove(tn.GRABBING),a.remove(tn.TOUCHING);const o=e.onseek||Qr,l=e.onstart||Qr,m=e.onend||Qr,v=e.onmouse||Qr,y=e.ontouch||Qr,E=e.ontouchend||Qr;function T(e){!function(){const e=t.getBoundingClientRect();s=e.left,i=e.width}();let r=(function(t){return"function"==typeof window.TouchEvent&&t instanceof TouchEvent}(e)?e.changedTouches[0].pageX:e.pageX)-s;return r>i&&(r=i),r<0&&(r=0),r/i*100}function S(e){const s=T(e);s!=r&&(o(t,s),r=s)}return t.addEventListener(u,function(e){sn(t,e)&&(a.add(tn.TOUCHING),rn(t.parentElement)&&(a.add(tn.GRABBING),y(t,T(e)),l(t,T(e)),S(e)))},Jr),t.addEventListener(f,function(e){S(e),v(t,T(e))},Jr),t.addEventListener(g,function(e){setTimeout(function(){a.remove(tn.TOUCHING)},500),sn(t,e)&&(a.remove(tn.GRABBING),E(t,T(e)),m(t,T(e)),i=0)},Jr),t.addEventListener(p,function(){a.remove(tn.GRABBING,tn.TOUCHING),i=0},Jr),t.addEventListener(c,function(e){a.contains(tn.TOUCHING)||(document.addEventListener(h,S),a.add(tn.GRABBING),l(t,T(e)),e.preventDefault(),S(e))}),t.addEventListener(h,function(e){a.contains(tn.TOUCHING)||v(t,T(e))}),document.addEventListener(d,function(e){a.contains(tn.TOUCHING)||(document.removeEventListener(h,S),a.contains(tn.GRABBING)&&(a.remove(tn.GRABBING),m(t,T(e)),i=0))}),t}function sn(t,e){const s=e.target;return!!s&&(s&&!s.closest(t.id)||!rn(t.parentElement)||!t.classList.contains(tn.TOUCHING))}function rn(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"}(tn||(tn={}));const nn="fp-tick";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,i=Array.from({length:s}).map(()=>{const t=document.createElement("i");return t.className=nn,t});this.append(...i),en(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)},onend:()=>{Je(t,{feature_name:"volume-slider",sample_rate:Ze.High,behavior:String(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")),this.adjustVolumeSlider(t.volume),t.on(b,()=>{const e=0==t.volume||t.muted;e&&this.adjustVolumeSlider(0);const s=t.opt("ui");this.classList.contains(tn.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("."+nn)),s=Math.round(t*e.length);e.forEach((t,e)=>{t.classList.toggle("fp-color",e<s)})}}class FlowplayerTimelineBar extends FlowplayerComponent{constructor(t){let e;super(t),this.bufferEle=Cr("fp-buffer"),this.progress=Cr("fp-progress","fp-color"),this.tooltipEle=Cr("fp-timestamp"),this.proposedSeekBar=Cr("fp-hover"),this.dragger=Cr("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("core.timeline_aria_label","Seek slider")),this.setAttribute("aria-valuenow","0"),this.progress.append(this.dragger),this.append(this.bufferEle,this.progress,this.proposedSeekBar,this.tooltipEle);const s=requestAnimationFrame;let i;const r=()=>{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(tn.GRABBING)||i||(i=setTimeout(r,200)))},n=()=>!!this.player.opt("seekable",!0)&&!isNaN(this.player.duration);en(this,{onseek:(s,i)=>{if(n())switch(!!e.live){case!0:Qs(i,t,this.tooltipEle);break;case!1:!function(t,e,s){const i=e.duration*(t/100);if(e.disabled&&i>e.currentTime)return!1;s.style.width=t+"%",e.currentTime=i}(i,t,this.progress),Vs(i,t,this.tooltipEle)}},onstart:()=>{n()&&(t.emit("timeline/gesture/start"),!t.hasState($s)&&t.setState(Wt,!0),e.live||function(t){t.style.display="block"}(this.tooltipEle))},onend:function(i,n){s(r),0!=e.seekable&&e.live&&Js(n,t)},ontouchend:()=>{e.live?ti(this.proposedSeekBar,this.tooltipEle):Ks(this.proposedSeekBar,this.tooltipEle),setTimeout(()=>t.emit("timeline/gesture/end"),0)},onmouse:(s,i)=>{if(n()&&(t.emit("timeline/gesture/move",{percent:i}),!this.classList.contains(tn.GRABBING)))switch(!!e.live){case!0:!function(t,e){e.style.width=t+"%"}(i,this.proposedSeekBar),Qs(i,t,this.tooltipEle);break;case!1:!function(t,e){e.style.width=t+"%"}(i,this.proposedSeekBar),Vs(i,t,this.tooltipEle)}}}),t.on(et,function(t){t.data&&(e=t.data)}),t.on(R,()=>s(r)),t.on(S,()=>{0==t.reaper||e.live||Hs(t,this.bufferEle)}),t.on(V,t=>{this.progress.style.width=t.detail+"%"}),t.on(A,()=>{0!=t.reaper&&(s(r),this.setAttribute("aria-valuenow",t.currentTime+""),this.setAttribute("aria-valuetext",Math.round(t.currentTime)+" "+t.i18n("core.seconds","Seconds")),e.live||Hs(t,this.bufferEle))}),t.on(E,()=>{0!=t.reaper&&(e.live||Hs(t,this.bufferEle))}),t.on(O,e=>{if(0==t.reaper)return;const s=qs(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?ti(this.proposedSeekBar,this.tooltipEle):Ks(this.proposedSeekBar,this.tooltipEle)})}}class FlowplayerLiveStatus extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-live-status");const e=Cr("fp-live-text"),s=Cr("fp-live-indicator","fp-color");e.textContent="live",this.setAttribute("tabindex","0"),this.setAttribute("role","button"),this.append(s,e),this.addEventListener(a,function(){Zs(t)})}}class FlowplayerDuration extends FlowplayerComponent{constructor(t){let e;super(t),this.classList.add("fp-duration"),this.setAttribute("aria-hidden","true"),t.on(et,s=>{if(0==t.reaper||!s.data)return;e=s.data;const i=qs(t)?NaN:s.data.duration||0;if(isNaN(i)||i>=Number.MAX_SAFE_INTEGER)return this.style.display="none";this.style.display="inline-block",this.innerText=cs(i)}),t.on(E,()=>{0==t.reaper||e.live||function(t,e){t.duration&&(e.innerText=cs(t.duration))}(t,this)})}}class FlowplayerElapsedTime extends FlowplayerComponent{constructor(t){let e;super(t),this.classList.add("fp-elapsed"),this.innerText=cs(0),this.setAttribute("aria-hidden","true"),t.on(et,t=>{t.data&&(e=t.data)}),t.on(A,()=>{0!=t.reaper&&(e.live?function(t,e){e.innerText=cs(t.currentTime)}(t,this):function(t,e){e.innerText=cs(t.currentTime)}(t,this))})}}class FlowplayerControlButtons extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-btns","fp-small-switch");const e=Le(t,wt),s=Le(t,kt);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,i=document.createElement("span"),r=Le(t,this.classList.contains("fp-left-zone")?xt:Mt);r.removeAttribute("tabindex"),i.classList.add("fp-zone-seconds"),this.append(i,r);t.on(D,()=>{i.innerText=""}),t.on(W,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(Y,()=>{this.reset_zone()}),this.reset_zone(),this.addEventListener(g,function(e){isNaN(t.duration)||isNaN(t.currentTime)||wr&t.opt("ui")||t.hasState(re)||!t.hasState(ue)&&!t.hasState(de)||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 FlowplayerErrorView extends FlowplayerComponent{constructor(t){super(t),this.className="fp-error",this.message=document.createElement("p"),this.message.className="error-message",this.errorId=document.createElement("p"),this.errorId.className="error-id",this.errorKey=document.createElement("p"),this.errorKey.className="error-key",this.append(this.errorKey,this.message,this.errorId),this.addEventListener(at,e=>{var s;const i=!!(null===(s=t.opts)||void 0===s?void 0:s.metadata),r=t.opts.live,n=e.detail.error.flowplayerErrorCode==De.PlaybackManifestLoadError;if((i||r)&&n)return void(this.message.textContent="stream offline");const a=e.detail.error;this.message.textContent=a.message,this.errorKey.textContent=a.errorKey,console.warn("flowplayer encountered an %s error while loading %s id:%s",a.errorKey,a.config.resource,a.id)})}}class FlowplayerHeaderLeftRight extends FlowplayerComponent{constructor(t,e,...s){super(t),this.className=e;const i=t.createComponents(...s);this.append(...i),"fp-left"!==e&&i.forEach(e=>{e.addEventListener(a,()=>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(bt,Lt);this.append(...e)}}class FlowplayerMiddleButtons extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-switch"),[Pt,Dt].forEach(e=>{const s=Le(t,e);s.removeAttribute("tabindex"),this.append(s)})}}class FlowplayerVolumeControl extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-volume-control");const e=Le(t,Ft);this.append(e),!s().ios&&this.append(Le(t,vt)),e instanceof FlowplayerIcon&&e.addEventListener(a,function(){t.toggleMute()})}}class FlowplayerHeader extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-header"),this.append(...t.createComponents(Et,Tt)),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(ht,ut,ft,gt,pt,mt))}}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(Rt,_t,It)),this.setAttribute("tabindex","0"),t.reaper&&t.reaper.set("middle",this),this.handleClick(t),this.handleTouch(t),t.once(it,()=>{this.removeAttribute("tabindex"),this.removeAttribute("role"),this.removeAttribute("aria-label")})}handleClick(t){[a,o].forEach(e=>this.addEventListener(e,function(s){if(!(s.defaultPrevented||t.root.classList.contains("is-endscreen")||e===o&&t.root.classList.contains("no-fullscreen")))return s.preventDefault(),t.emit(s.type),!1})),t.on(a,function(e){setTimeout(function(){e.defaultPrevented||t.togglePlay()},0)}),t.on(o,function(e){setTimeout(function(){e.defaultPrevented||t.toggleFullScreen()},0)})}handleTouch(t){let e=!1;this.addEventListener(g,function(e){e.cancelable&&!t.hasState("is-endscreen")&&(e.preventDefault(),t.emit(e.type,{source:e}))}),t.on(g,function(s){setTimeout(function(){if(s.defaultPrevented)return;if(t.ended)return t.togglePlay(!0);const i=t.hasState(qt);e&&clearTimeout(e),(i||t.hasState(de))&&(t.hasState(de)&&(t.setState(de,!1),t.setState(ce,!1)),t.togglePlay(),i)||(t.setState(de,!0),t.paused||(e=setTimeout(function(){e=!1,t.setState(de,!1),t.setState(ce,!1)},2e3)))},0)})}}class FlowplayerUi extends FlowplayerComponent{constructor(t){super(t),this.classList.add("fp-ui"),this.append(...t.createComponents(yt,At,ct))}}const an=t=>{let e=!1;t.on(Qe,()=>{e||(t=>{const e=t.customElements.entries();for(var[s,i]of e)if(!Ie(t,i))return!0;return!1})(Lr)&&(Je(t,{feature_name:"custom-components",behavior:"used",sample_rate:Ze.High}),e=!0)})},on="flowplayer-ad-ui",ln="flowplayer-ad-controls",dn="flowplayer-ad-countdown",cn="flowplayer-ad-indicator",hn=t=>{const e=t.closest(`.${Xr}`);return e?((t,e)=>{var s,i;const r=`${((null===(s=e.parentElement)||void 0===s?void 0:s.localName)||"")+">"+t.localName}>${e.open?"open":"closed"}`;return t instanceof HTMLSpanElement?r+">"+(t.textContent||""):t instanceof HTMLLIElement?r+">"+((null===(i=t.querySelector("span"))||void 0===i?void 0:i.textContent)||""):r})(t,e):t.closest(gt)?gt:t.closest(vt)?vt:t.closest(bt)?bt:t.closest(on)?on+">"+t.localName:t.localName},un=new Set(["click","drag","quick-clicks"]),fn=t=>t.hasState(he)?t.hasState(de):t.hasState(ce),gn=(t,e,s,i)=>{const r=t=>"string"==typeof t?t:hn(t);return((t,e,s={})=>{const i=e.join(","),r=Object.entries(s).map(([t,e])=>`${t}=${e}`).join(",");return r?`${t}:${i}:${r}`:`${t}:${i}`})(t,s?[r(e),r(s)]:[r(e)],i||{})},pn=(t,e,s,i,r)=>{if(!function(t,e){var s;const i=null===(s=t.health)||void 0===s?void 0:s.session_id;if(!i)return Math.random()<=e;if(!ts.has(i)){const t=Math.random()<=e;return ts.set(i,t),t}return!!ts.get(i)}(t,Ze.Low))return;const n=un.has(e)?Object.assign({is_hovered:fn(t)?1:0},r):r;Je(t,{feature_name:"ui",behavior:gn(e,s,i,n),sample_rate:Ze.All})};class ClickTracker{constructor(t){this.handleTouchStart=t=>{const e=t.target,s=t.touches[0];e&&s&&this.touches.set(e,{startX:s.clientX,startY:s.clientY})},this.handleTouchEnd=t=>{const e=t.target;if(!this.shouldTrackElement(e))return;const s=this.touches.get(e),i=t.changedTouches[0];if(i){const t=Object.assign(Object.assign({},s),{endX:i.clientX,endY:i.clientY});if(((t,e)=>{if(void 0===t.startX||void 0===t.startY||void 0===t.endX||void 0===t.endY)return!1;const s=Math.abs(t.endX-t.startX),i=Math.abs(t.endY-t.startY);return s>e||i>e})(t,10)){const s=document.elementFromPoint(i.clientX,i.clientY);s&&this.shouldTrackElement(s)&&(this.touches.set(e,Object.assign(Object.assign({},t),{endTimestamp:Date.now()})),pn(this.video,"drag",e,s)),this.touches.delete(e)}else this.touches.set(e,Object.assign(Object.assign({},t),{endTimestamp:Date.now()})),pn(this.video,"click",e),this.handleQuickClickDetection(e,i.clientX,i.clientY)}else this.touches.set(e,Object.assign(Object.assign({},s),{endTimestamp:Date.now()})),pn(this.video,"click",e)},this.handleClick=t=>{const e=t.target;if(!this.shouldTrackElement(e))return;const s=this.touches.get(e);if((null==s?void 0:s.endTimestamp)&&Date.now()-s.endTimestamp<100)return;const i=t.clientX,r=t.clientY;pn(this.video,"click",e),this.handleQuickClickDetection(e,i,r)};const e=t.root;if(!e)throw new Error("Player root element is required for click tracking");this.root=e,this.video=t,this.touches=new WeakMap,this.lastClick={element:null,timestamp:null,x:null,y:null}}track(){this.root.addEventListener("touchstart",this.handleTouchStart,{capture:!0,passive:!0}),this.root.addEventListener("touchend",this.handleTouchEnd,{capture:!0,passive:!0}),this.root.addEventListener("click",this.handleClick,{capture:!0})}handleQuickClickDetection(t,e,s){const i=Date.now();if(this.lastClick.element&&this.lastClick.timestamp&&null!==this.lastClick.x&&null!==this.lastClick.y){const r=i-this.lastClick.timestamp;if(r<1200){const i=((t,e,s,i)=>{const r=s-t,n=i-e;return Math.sqrt(r*r+n*n)})(this.lastClick.x,this.lastClick.y,e,s);if(i<=50){const e=100*Math.ceil(r/100),s=10*Math.ceil(i/10);return pn(this.video,"quick-clicks",this.lastClick.element,t,{"time-diff":e,distance:s}),void this.clearClick()}}}this.lastClick.element=t,this.lastClick.timestamp=i,this.lastClick.x=e,this.lastClick.y=s}shouldTrackElement(t){return!(!t||!this.root.contains(t))&&t!==this.video}clearClick(){this.lastClick.element=null,this.lastClick.timestamp=null,this.lastClick.x=null,this.lastClick.y=null}}const mn=t=>50*Math.round(t/50),vn=t=>{if(!t.root)return;const e=e=>{var s;const i=null===(s=t.root)||void 0===s?void 0:s.getBoundingClientRect(),r=mn((null==i?void 0:i.width)||0),n=mn((null==i?void 0:i.height)||0),a=(()=>{var t,e;return(null===(e=null===(t=window.screen)||void 0===t?void 0:t.orientation)||void 0===e?void 0:e.type)?window.screen.orientation.type.includes("portrait")?"portrait":"landscape":"unknown"})(),o=(t=>{if(Mr(t)){const e=t.webkitDisplayingFullscreen;return"boolean"==typeof e&&e}return!!document.fullscreenElement})(t)?"true":"false";pn(t,"player-dimensions",`${r},${n}`,void 0,{delay:e}),pn(t,"orientation",a,void 0,{delay:e}),pn(t,"fullscreen-status",o,void 0,{delay:e})};t.once(R,()=>{e(0);const s=setTimeout(()=>{t.paused||e(5e3)},5e3);t.once(N,()=>clearTimeout(s))})},yn=(...t)=>t.reduce((t,e)=>Object.assign(Object.assign({},t),e),{}),En=(t,e)=>{const s=t.lastIndexOf(e);return~s&&t.splice(s,1),t};class RequestQueue$1{static of(){return new RequestQueue$1}static is_empty(t){return 0==t.pending.length}static is_high_water(t){return t.open.length==RequestQueue$1.MAX_OPEN_REQUESTS}static maybe_spawn_req(t){if(RequestQueue$1.is_empty(t))return t;if(RequestQueue$1.is_high_water(t))return t;try{const e=RequestQueue$1.lpop(t);e&&RequestQueue$1.request(t,e)}catch(t){}}static increment_failures(t){return t.stats.failures++,t.stats.failures>RequestQueue$1.MAX_FAILURE_COUNT&&(t.stats.ttl=Date.now()+RequestQueue$1.REQUEST_TTL_MS),t}static handle_error(t,e){RequestQueue$1.rm(t,e),RequestQueue$1.increment_failures(t)}static request(t,[e,s,i]){if(Date.now()<t.stats.ttl)return;const r=new XMLHttpRequest;t.open.push(r),r.timeout=RequestQueue$1.REQUEST_TIMEOUT_MS,r.ontimeout=function(){RequestQueue$1.handle_error(t,r)},r.onerror=function(e){RequestQueue$1.handle_error(t,r)},r.onreadystatechange=function(){r.readyState==XMLHttpRequest.DONE&&RequestQueue$1.rm(t,r),Math.floor(r.status/100)},r.onload=function(){RequestQueue$1.rm(t,r),t.stats.failures&&t.stats.failures--},r.open(s,e),r.setRequestHeader("Content-Type","text/plain;charset=UTF-8");try{r.send(JSON.stringify(i))}catch(t){}}static rpush(t,...e){return e.forEach(e=>{t.pending.length>=RequestQueue$1.MAX_PENDING||(t.pending.push(e),RequestQueue$1.maybe_spawn_req(t))}),t}static lpop(t){return t.pending.shift()}static rm(t,e){return En(t.open,e),t}constructor(){this.pending=[],this.open=[],this.stats={failures:0,ttl:0}}}RequestQueue$1.MAX_OPEN_REQUESTS=3,RequestQueue$1.MAX_PENDING=5,RequestQueue$1.REQUEST_TIMEOUT_MS=4e3,RequestQueue$1.REQUEST_TTL_MS=5e3,RequestQueue$1.MAX_FAILURE_COUNT=3;var Tn=RequestQueue$1.of();const Sn=/:([a-zA-Z_]+)/g;class Log$1{static prepare(t,e){const s=document.createEvent("Event");return s.initEvent(t,!1,!0),s.ns=t,s.data=e,s}static of(t){return new Log$1(t)}constructor(t){this.emitter=t}info(t){this.emitter.dispatchEvent(Log$1.prepare(Log$1.NAMESPACE.INFO,t))}error(t){this.emitter.dispatchEvent(Log$1.prepare(Log$1.NAMESPACE.ERROR,t))}warn(t){this.emitter.dispatchEvent(Log$1.prepare(Log$1.NAMESPACE.WARN,t))}}var An;Log$1.NAMESPACE={INFO:"tracker:info",ERROR:"tracker:err",WARN:"tracker:warn"},function(t){t.POST="POST",t.PUT="PUT",t.GET="GET"}(An||(An={}));class Tracker{static of(t,e){return new Tracker(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)=>yn(e,{[s]:t[s]}),{}))(e,...t.valid_keys)}static merge_metadata(t,e={}){return t.metadata=Tracker.pluck_valid_keys(t,yn(t.metadata,e)),t}static assert_emitter_api(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")}static create_listener(t,e,s){var i;t.listeners.push([e,s]),null===(i=t.emitter)||void 0===i||i.addEventListener(e,s)}constructor(t,e={}){const s=this;if(this.emitter=t,this.url=e.url,this.log=Log$1.of(this.emitter),this.verb=e.verb,this.metadata=yn({},e.metadata||{}),this.rq=e.rq||Tn,this.events=e.events||[],this.required_keys=e.required_keys||[],this.optional_keys=e.optional_keys||[],this.listeners=[],this.valid_keys=this.required_keys.slice(0).concat(this.optional_keys),Tracker.assert_emitter_api(this.emitter),void 0===Tracker.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`);Tracker.TRACKERS.push(this),s.events.forEach(t=>{Tracker.create_listener(this,t,(e={})=>{var i;if(null===(i=this.emitter)||void 0===i?void 0:i.hasState("consent-no-tracking"))return;const r=yn(s.metadata,{event_type:t},e.data||e),n=function(t,e){return t.replace(Sn,t=>{const s=t.slice(1,t.length);return s in e?e[s].toString():t})}(s.url,r),a=Tracker.pluck_valid_keys(s,r),o=Tracker.ensure_required_keys(s,a);if(o.length)return s.log.error(`Tracker.validate_metadata() failed for\n Event[${t}]\n missing keys: ${o}\n payload:\n ${JSON.stringify(a,null,2)}`);this.rq&&RequestQueue$1.rpush(this.rq,[n,this.verb,a])})})}destroy(){this.listeners.forEach(([t,e])=>{var s;return null===(s=this.emitter)||void 0===s?void 0:s.removeEventListener(t,e)}),delete this.rq,delete this.emitter,En(Tracker.TRACKERS,this)}put(t={}){return Tracker.merge_metadata(this,t),this}}Tracker.TRACKERS=[],Tracker.QUEUE=Tn,Tracker.verb=An;var _n="ping",bn="display",Ln="view";const Rn=["sitegroup_id","session_id","media_id","site_id","player_id","video_type"],In=["created","position"],kn=["player_version","created","source","category","category_id","autoplay","muted","customer_user_id"];const wn=100,Pn=1e3;function Dn(t,e){return t.duration/1===t.duration&&Object.assign(e,function(t){const e=t/wn;return{segment_duration:e,breakpoints:Array(...Array(wn)).map(function(t,s){return Math.floor(s*e*Pn)/Pn})}}(t.duration))}function Cn(t,e,s,i){if(!e.segment_duration&&!Dn(t,e))return;const r=function(t,e,s,i){const r=e.last_idx,n=s?100:On(t,e,i);return e.last_idx=n,n<=r?[]:e.breakpoints.slice(r,n).map(function(t){return e.breakpoints.indexOf(t)})}(t,e,s,i);0!=r.length&&t.emit(_n,{position:r})}function On(t,e,s){const i=void 0!==s?s:t.currentTime;return Math.min(100,Math.max(0,Math.floor(i/e.segment_duration-.8)+1))}var Mn;const xn="vod",Fn="live",Nn=[bn,_n,Ln];function Un(t,e,s,i){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(_n,{position:60*e.ticks}))}(t,e);case"vod":return Cn(t,e,"boolean"==typeof s&&s,i)}}function Bn(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))))}const $n=(Mn=class Analytics{init(t,e,s){if(!Fs.from_token(t.token||"").is_granted(Fs.permissions.ANALYTICS))return;if(s.analytics)return;const i=s.analytics={ticker:void 0,last_media_id:"",ended:!1,played:!1},r={locked:void 0,ttl:6e3,task:()=>{s.hasState(Wt)||Un(s,i.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.43.0"},a=Tracker.of(s,{verb:Tracker.verb.POST,url:"https://ptm.flowplayer.com/:video_type/:sitegroup_id/:event_type",events:Nn,required_keys:Rn,optional_keys:kn.concat(In).slice(0),metadata:n});s.on(N,function(){a&&a.destroy()});let o=0,l=0;s.on(et,function(e){if(!a)return;const r=ls(e,"data.metadata",{});if(!r.media_id&&r.stream_target_id&&(r.media_id=r.stream_target_id),!r.media_id)return i.last_media_id="";if(i.last_media_id===r.media_id)return;i.played=!1,i.last_media_id=r.media_id;const n=ls(t,"analytics",{});a.put(r),a.put(n);const l=ls(t,"metadata.live_start_time",t.live)?Fn:xn;a.put({video_type:l,source:t.source||bi()||""}),i.ticker=ls(t,"metadata.live_start_time",t.live)?{ticks:0,last_tracked_ts:Date.now(),kind:"live"}:{last_idx:0,segment_duration:0,breakpoints:[],kind:"vod"},o=0,i.ended=!1,s.emit(bn)}),s.on(R,function(){if(!a)return;if(l||i.played||!i.last_media_id)return;a.put({muted:s.muted});const t=Bn(s);if(t)return l=Promise.resolve(t).then(function(){i.played=!0,s.emit(Ln),l=0}).catch(function(){l=0});i.played=!0,s.emit(Ln)}),s.on(A,function(){var e;a&&(o=s.currentTime,l||Bn(s)||i.ended||!i.last_media_id||s.hasState(Wt)||(!t.live&&s.currentTime+.25>=s.duration&&Un(s,i.ticker,!0),(e=r).locked||(e.locked=setTimeout(function(){return e.task(),function(t){return t.locked=void 0,t}(e)},e.ttl))))}),s.on(D,function(){var t;a&&i.last_media_id&&(i.ended&&(i.ended=!1,o=0,"vod"===(null===(t=i.ticker)||void 0===t?void 0:t.kind)&&(i.ticker.last_idx=0)),i.ticker&&"vod"==i.ticker.kind&&function(t,e){Dn(t,e),e.last_idx=On(t,e)}(s,i.ticker))}),s.on("timeline/gesture/start",function(){Un(s,i.ticker,!1,o)}),s.on(P,function(){a&&i.last_media_id&&function(t,e){e.ended||(e.ended=!0,Un(t,e.ticker))}(s,i)})}},Mn.pluginName="analytics",Mn),Gn=ws(Ps(),$n),Hn=t=>0==t.volume||t.muted?"true":"false";class Default{constructor(t){Re(t,lt,FlowplayerUi),Re(t,Ut,FlowplayerErrorView),Re(t,ct,FlowplayerControls),Re(t,ut,FlowplayerLiveStatus),Re(t,pt,FlowplayerDuration),Re(t,gt,FlowplayerTimelineBar),Re(t,ft,FlowplayerElapsedTime),Re(t,vt,FlowplayerVolumeBar),Re(t,mt,FlowplayerVolumeControl),Re(t,ht,FlowplayerControlButtons),Re(t,yt,FlowplayerHeader),Re(t,dt,FlowplayerLogo),Re(t,St,FlowplayerHeaderDuration),Re(t,Et,class extends FlowplayerHeaderLeftRight{constructor(t){super(t,"fp-left",St)}}),Re(t,Tt,class extends FlowplayerHeaderLeftRight{constructor(t){super(t,"fp-right fp-togglable",Ct,Ot)}}),Re(t,At,FlowplayerMiddle),Re(t,_t,FlowplayerMiddleZone),Re(t,bt,FlowplayerMiddleWait),Re(t,Lt,FlowplayerMiddleButtons),Re(t,It,class extends FlowplayerLeftRightZone{constructor(t){super(t,"fp-right-zone")}}),Re(t,Rt,class extends FlowplayerLeftRightZone{constructor(t){super(t,"fp-left-zone")}}),Re(t,kt,class extends FlowplayerIcon{constructor(t){super(t,qr),this.setAttribute("role","button")}}),Re(t,wt,class extends FlowplayerIcon{constructor(t){super(t,Wr),this.setAttribute("role","button")}}),Re(t,Pt,class extends FlowplayerIcon{constructor(t){super(t,Kr),this.setAttribute("role","button")}}),Re(t,Dt,class extends FlowplayerIcon{constructor(t){super(t,Vr),this.setAttribute("role","button")}}),Re(t,Ct,class extends FullscreenIcon{constructor(t){super(t,Gr)}}),Re(t,Ot,class extends FullscreenIcon{constructor(t){super(t,Hr)}}),Re(t,Mt,class extends FlowplayerIcon{constructor(t){super(t,Yr)}}),Re(t,xt,class extends FlowplayerIcon{constructor(t){super(t,zr)}}),Re(t,Ft,class extends FlowplayerIcon{constructor(t){super(t,jr),this.classList.add("fp-volumebtn"),this.setAttribute("role","switch"),this.setAttribute("aria-checked",Hn(t)),t.on(b,()=>{this.setAttribute("aria-label",t.i18n("core.muted","Muted")),this.setAttribute("aria-checked",Hn(t))})}})}init(t,e,s){Br(t,0,s),Nr(t,e,s),Rr(0,0,s),an(s),(t=>{if(!t.root)return;new ClickTracker(t).track(),vn(t)})(s)}}Default.pluginName="default",Lr.extensions.unshift.apply(Lr.extensions,[I18n,Gn,Default]);var Kn=Object.assign(Lr,{ui:Pr,i18n:I18n});const Vn=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},jn=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=qn},qn=Number.MAX_SAFE_INTEGER||9007199254740991;let Wn=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}({}),Yn=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.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",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.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",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_APPEND_NO_PROGRESS="bufferAppendNoProgress",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",t.UNKNOWN="unknown",t}({}),zn=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",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.BUFFERED_TO_END="hlsBufferedToEnd",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.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",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_TRACK_UPDATED="hlsSubtitleTrackUpdated",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.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",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.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});function Qn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Xn,Zn={exports:{}};var Jn=(Xn||(Xn=1,function(t){var e,s,i,r,n;e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,n={buildAbsoluteURL:function(t,e,i){if(i=i||{},t=t.trim(),!(e=e.trim())){if(!i.alwaysNormalize)return t;var r=n.parseURL(t);if(!r)throw new Error("Error trying to parse base URL.");return r.path=n.normalizePath(r.path),n.buildURLFromParts(r)}var a=n.parseURL(e);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return i.alwaysNormalize?(a.path=n.normalizePath(a.path),n.buildURLFromParts(a)):e;var o=n.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=s.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 c=o.path,h=c.substring(0,c.lastIndexOf("/")+1)+a.path;d.path=n.normalizePath(h)}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?n.normalizePath(a.path):a.path),n.buildURLFromParts(d)},parseURL:function(t){var s=e.exec(t);return s?{scheme:s[1]||"",netLoc:s[2]||"",path:s[3]||"",params:s[4]||"",query:s[5]||"",fragment:s[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(i,"");t.length!==(t=t.replace(r,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=n}(Zn)),Zn.exports);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 ta="manifest",ea="level",sa="audioTrack",ia="subtitleTrack",ra="media-fragment",na="key",aa="steering-manifest",oa="server-certificate",la="interstitial-asset-list",da="main",ca="audio",ha="subtitle",ua="audio",fa="video",ga="audiovideo";class BaseSegment{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,e){const s=ya(t,e);s&&(s.enumerable=!0,Object.defineProperty(t,e,s))}(this,"stats")}setByteRange(t,e){const s=t.split("@",2);let i;i=1===s.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[ua]:null,[fa]:null,[ga]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new LoadStats),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.relurl&&(this._url=Jn.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[ua]=null,t[fa]=null,t[ga]=null,this.url=null}}function pa(t){return"initSegment"!==t.sn}function ma(t,e){return t.sn===(null==e?void 0:e.sn)&&t.level===e.level}function va(t,e){return t.sn===(null==e?void 0:e.sn)&&t.level===e.level&&t.cc===e.cc}class Fragment extends BaseSegment{constructor(t,e){super(e),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const t=this.byteRange[0],e=this.byteRange[1];if(Vn(t)&&Vn(e))return e-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(null==(t=this._decryptdata)||!t.keyId){const t=Object.keys(e);if(1===t.length){const s=this._decryptdata=e[t[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const t=Vn(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){var e;const t=Object.keys(this.levelkeys),s=t.length;if(s>1||1===s&&null!=(e=this.levelkeys[t[0]])&&e.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){Vn(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return pa(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var s;const i=e[t];!i||null!=(s=this._decryptdata)&&s.keyId||(this._decryptdata=i.getDecryptData(this.sn,e))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,s,i,r,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,i),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:s,startDTS:i,endDTS:r,partial:n}}}class Part extends BaseSegment{constructor(t,e,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,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=i;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo||this.fragment.type===ha&&this.stats.loading.end>0)}}function ya(t,e){const s=Object.getPrototypeOf(t);if(s){const t=Object.getOwnPropertyDescriptor(s,e);return t||ya(s,e)}}function Ea(t,e,s){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var s=t[Symbol.toPrimitive];if(void 0!==s){var i=s.call(t,e);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function Ta(){return Ta=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var s=arguments[e];for(var i in s)({}).hasOwnProperty.call(s,i)&&(t[i]=s[i])}return t},Ta.apply(null,arguments)}function Sa(t,e){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),s.push.apply(s,i)}return s}function Aa(t){for(var e=1;e<arguments.length;e++){var s=null!=arguments[e]?arguments[e]:{};e%2?Sa(Object(s),!0).forEach(function(e){Ea(t,e,s[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):Sa(Object(s)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(s,e))})}return t}function _a(t,e){if(null==t)return{};var s,i,r=function(t,e){if(null==t)return{};var s={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(-1!==e.indexOf(i))continue;s[i]=t[i]}return s}(t,e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);for(i=0;i<n.length;i++)s=n[i],-1===e.indexOf(s)&&{}.propertyIsEnumerable.call(t,s)&&(r[s]=t[s])}return r}function ba(t){switch(t.details){case Yn.FRAG_LOAD_TIMEOUT:case Yn.KEY_LOAD_TIMEOUT:case Yn.LEVEL_LOAD_TIMEOUT:case Yn.MANIFEST_LOAD_TIMEOUT:case Yn.AUDIO_TRACK_LOAD_TIMEOUT:case Yn.SUBTITLE_TRACK_LOAD_TIMEOUT:case Yn.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function La(t){return t.details.startsWith("key")}function Ra(t){return La(t)&&!!t.frag&&!t.frag.decryptdata}function Ia(t,e){const s=ba(e);return t.default[(s?"timeout":"error")+"Retry"]}function ka(t,e){const s="linear"===t.backoff?1:Math.pow(2,e);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function wa(t){return Aa(Aa({},t),{errorRetry:null,timeoutRetry:null})}function Pa(t,e,s,i){if(!t)return!1;const r=null==i?void 0:i.code,n=e<t.maxNumRetry&&(function(t){return Da(t)||!!t&&(t<400||t>499)}(r)||!!s);return t.shouldRetry?t.shouldRetry(t,e,s,i,n):n}function Da(t){return 0===t&&!1===navigator.onLine}function Ca(t,e){return e>0&&t.loadError>0&&0!==t.loadErrorTime&&self.performance.now()-t.loadErrorTime>e}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,i=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_=i,this.ttfb_=new EWMA(t)}update(t,e){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==t&&(this.slow_=new EWMA(t,s.getEstimate(),s.getTotalWeight())),i.halfLife!==e&&(this.fast_=new EWMA(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new EWMA(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){if(e<=0)return;const s=Math.min(this.minDelayMs_,e/1e5),i=8*e,r=Math.max(t,s)/1e3,n=i/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}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_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}class Logger{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${t}]:`;this.trace=Oa,this.debug=e.debug.bind(null,s),this.log=e.log.bind(null,s),this.warn=e.warn.bind(null,s),this.info=e.info.bind(null,s),this.error=e.error.bind(null,s)}}const Oa=function(){},Ma={trace:Oa,debug:Oa,log:Oa,warn:Oa,info:Oa,error:Oa};function xa(){return Ta({},Ma)}function Fa(t,e,s){return e[t]?e[t].bind(e):function(t,e){const s=self.console[t];return s?s.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):Oa}(t,s)}const Na=xa();const Ua=Na;function Ba(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function $a(t,e){const s=Object.keys(t),i=Object.keys(e),r=s.length,n=i.length;return!r||!n||r===n&&!s.some(t=>-1===i.indexOf(t))}function Ga(t){return t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer}const Ha="utf-16be",Ka="utf-16le",Va="utf-8";function ja(t,e){if(t<0)return-ja(-t,e);const s=Math.pow(10,e);if(Math.abs(t*s%1-.5)<Number.EPSILON){const e=Math.floor(t*s);return(e%2==0?e:e+1)/s}return Math.round(t*s)/s}function qa(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const s=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?s:3&s|8).toString(16)})}}}function Wa(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}function Ya(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}function za(t,e){return Wa(t,e)&&Ya(t,e+6)+10<=t.length-e}function Qa(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}function Xa(t,e){const s=e;let i=0;for(;Wa(t,e);){i+=10;i+=Ya(t,e+6),Qa(t,e+10)&&(i+=10),e+=i}if(i>0)return t.subarray(s,s+i)}function Za(t,e=0,s=1/0){return function(t,e,s,i){const r=(n=t,Ga(n)?n:n.buffer);var n;let a=1;"BYTES_PER_ELEMENT"in i&&(a=i.BYTES_PER_ELEMENT);const o=(h=t,h&&Ga(h.buffer)&&void 0!==h.byteLength&&void 0!==h.byteOffset?t.byteOffset:0),l=(o+t.byteLength)/a,d=(o+e)/a,c=Math.floor(Math.max(0,Math.min(d,l)));var h;return new i(r,c,Math.floor(Math.min(c+Math.max(s,0),l))-c)}(t,e,s,Uint8Array)}function Ja(t,e=!1){const s=e?t.indexOf(0):t.length,i=function(t,e={}){let s;s=Ga(t)?new DataView(t):new DataView(t.buffer,t.byteOffset,t.byteLength);let i=0,{encoding:r}=e;if(!r){const t=s.getUint8(0),e=s.getUint8(1);239==t&&187==e&&191==s.getUint8(2)?(r=Va,i=3):254==t&&255==e?(r=Ha,i=2):255==t&&254==e?(r=Ka,i=2):r=Va}if("undefined"!=typeof TextDecoder)return new TextDecoder(r).decode(s);const{byteLength:n}=s,a=r!==Ha;let o,l="";for(;i<n;){switch(r){case Va:if(o=s.getUint8(i),o<128)i++;else if(o>=194&&o<=223)if(i+1<n){const t=s.getUint8(i+1);t>=128&&t<=191?(o=(31&o)<<6|63&t,i+=2):i++}else i++;else if(o>=224&&o<=239)if(i+2<=n-1){const t=s.getUint8(i+1),e=s.getUint8(i+2);t>=128&&t<=191&&e>=128&&e<=191?(o=(15&o)<<12|(63&t)<<6|63&e,i+=3):i++}else i++;else if(o>=240&&o<=244)if(i+3<=n-1){const t=s.getUint8(i+1),e=s.getUint8(i+2),r=s.getUint8(i+3);t>=128&&t<=191&&e>=128&&e<=191&&r>=128&&r<=191?(o=(7&o)<<18|(63&t)<<12|(63&e)<<6|63&r,i+=4):i++}else i++;else i++;break;case Ha:case"utf-16":case Ka:o=s.getUint16(i,a),i+=2}l+=String.fromCodePoint(o)}return l}(new DataView(t.buffer,t.byteOffset,s),{encoding:Va});return e?i:i.replace(/\0/g,"")}function to(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const s=t.data.subarray(1).indexOf(0);if(-1===s)return;const i=Ja(Za(t.data,1,s)),r=t.data[2+s],n=t.data.subarray(3+s).indexOf(0);if(-1===n)return;const a=Ja(Za(t.data,3+s,n));let o;var l;return"--\x3e"===i?o=Ja(Za(t.data,4+s+n)):o=Ga(l=t.data.subarray(4+s+n))?l:0==l.byteOffset&&l.byteLength==l.buffer.byteLength?l.buffer:new Uint8Array(l).buffer,e.mimeType=i,e.pictureType=r,e.description=a,e.data=o,e}function eo(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=Ja(t.data,!0),s=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:s.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const s=Ja(t.data.subarray(e),!0);e+=s.length+1;const i=Ja(t.data.subarray(e));return{key:t.type,info:s,data:i}}const e=Ja(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?to(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const{data:s}=t,i=Ja(s.subarray(e),!0);e+=i.length+1;const r=Ja(s.subarray(e));return{key:t.type,info:i,data:r}}const e=Ja(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function so(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),s=Ya(t,4);return{type:e,size:s,data:t.subarray(10,10+s)}}function io(t){let e=0;const s=[];for(;Wa(t,e);){const i=Ya(t,e+6);t[e+5]>>6&1&&(e+=10),e+=10;const r=e+i;for(;e+10<r;){const i=so(t.subarray(e)),r=eo(i);r&&s.push(r),e+=i.size+10}Qa(t,e)&&(e+=10)}return s}function ro(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function no(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),s=1&e[3];let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,s&&(i+=47721858.84),Math.round(i)}}function ao(t){const e=io(t);for(const t of e)if(ro(t))return no(t)}function oo(t){let e="";for(let s=0;s<t.length;s++){let i=t[s].toString(16);i.length<2&&(i="0"+i),e+=i}return e}function lo(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function co(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function ho(t){return String.fromCharCode.apply(null,t)}const uo=Math.pow(2,32)-1,fo={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},go={video:1,audio:2,id3:3,text:4};function po(t,e){const s=t[e]<<8|t[e+1];return s<0?65536+s:s}function mo(t,e){const s=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3];return s<0?4294967296+s:s}function vo(t,e){let s=mo(t,e);return s*=Math.pow(2,32),s+=mo(t,e+4),s}function yo(t,e){let s="";for(let i=e;i<t.length;i++)if(s+=String.fromCharCode(t[i]),0===t[i])return s;return null}function Eo(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function To(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 So(t,e,s){const i=e.byteOffset-t.byteOffset-8,r=8+s,n=e.byteLength+8-r;n<8||(To(t,i,r),To(t,i+r,n),To(t,i+r+4,fo.free))}function Ao(t,e){return[t.byteOffset-e-8,t.byteOffset-e+t.byteLength]}function _o(t,e){e.sort((t,e)=>t[0]-e[0]);const s=e.reduce((t,[e,s])=>t+s-e,0),i=new Uint8Array(t.byteLength-s);let r=0,n=0;for(let s=0;s<e.length;s++){const[a,o]=e[s];i.set(t.subarray(r,a),n),n+=a-r,r=o}i.set(t.subarray(r),n);return{result:i,dropped:s,droppedBefore:t=>e.reduce((e,[s,i])=>i<=t?e+i-s:e,0)}}function bo(t,e){const s=[];return e.length?(Lo(t,e,0,0,t.byteLength,s),s):s}function Lo(t,e,s,i,r,n){const a=e[s];if(4!==(null==a?void 0:a.length))return;const o=a.charCodeAt(0),l=a.charCodeAt(1),d=a.charCodeAt(2),c=a.charCodeAt(3),h=e.length-1;for(let a=i;a<r;){const i=a+8<=r,u=a+4<=r?16777216*t[a]+(t[a+1]<<16|t[a+2]<<8|t[a+3]):mo(t,a),f=u>1?a+u:r;if(i&&t[a+4]===o&&t[a+5]===l&&t[a+6]===d&&t[a+7]===c){const i=Math.min(f,r);s===h?n.push(t.subarray(a+8,i)):Lo(t,e,s+1,a+8,i,n)}a=f}}function Ro(t){const e=[],s=t[0];let i=8;const r=mo(t,i);i+=4;let n=0,a=0;0===s?(n=mo(t,i),a=mo(t,i+4),i+=8):(n=vo(t,i),a=vo(t,i+8),i+=16),i+=2;let o=t.length+a;const l=po(t,i);i+=2;for(let s=0;s<l;s++){let s=i;const n=mo(t,s);s+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return Ua.warn("SIDX has hierarchical references (not supported)"),null;const l=mo(t,s);s+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,s+=4,i=s}return{earliestPresentationTime:n,timescale:r,version:s,referencesCount:l,references:e}}function Io(t){const e=[],s=bo(t,["moov","trak"]);for(let t=0;t<s.length;t++){const i=s[t],r=bo(i,["tkhd"])[0];if(r){let t=r[0];const s=mo(r,0===t?12:20),n=bo(i,["mdia","mdhd"])[0];if(n){t=n[0];const r=mo(n,0===t?12:20),a=bo(i,["mdia","hdlr"])[0];if(a){const t=ho(a.subarray(8,12)),n={soun:ua,vide:fa}[t],o=ko(bo(i,["mdia","minf","stbl","stsd"])[0]);n?(e[s]={timescale:r,type:n,stsd:o},e[n]=Aa({timescale:r,id:s},o)):e[s]={timescale:r,type:t,stsd:o}}}}}return bo(t,["moov","mvex","trex"]).forEach(t=>{const s=mo(t,4),i=e[s];i&&(i.default={duration:mo(t,12),sampleSize:mo(t,16),flags:mo(t,20)})}),e}function ko(t){const e=t.subarray(8),s=e.subarray(86),i=ho(e.subarray(4,8));let r,n=i;const a="enca"===i||"encv"===i;if(a){const t=bo(e,[i])[0];bo(t.subarray("enca"===i?28:78),["sinf"]).forEach(t=>{const e=bo(t,["schm"])[0];if(e){const s=ho(e.subarray(4,8));if("cbcs"===s||"cenc"===s){const e=bo(t,["frma"])[0];e&&(n=ho(e))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=bo(s,["avcC"])[0];t&&t.length>3&&(n+="."+Do(t[1])+Do(t[2])+Do(t[3]),r=wo("avc1"===o?"dva1":"dvav",s));break}case"mp4a":{const t=bo(e,[i])[0],s=bo(t.subarray(28),["esds"])[0];if(s&&s.length>7){let t=4;if(3!==s[t++])break;t=Po(s,t),t+=2;const e=s[t++];if(128&e&&(t+=2),64&e&&(t+=s[t++]),4!==s[t++])break;t=Po(s,t);const i=s[t++];if(64!==i)break;if(n+="."+Do(i),t+=12,5!==s[t++])break;t=Po(s,t);const r=s[t++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&s[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=bo(s,["hvcC"])[0];if(t&&t.length>12){const e=t[1],s=["","A","B","C"][e>>6],i=31&e,r=mo(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);n+="."+s+i,n+="."+function(t){let e=0;for(let s=0;s<32;s++)e|=(t>>s&1)<<31-s;return e>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let d="";for(let t=l.length;t--;){const e=l[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}n+=d}r=wo("hev1"==o?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=wo(n,s)||n;break;case"vp09":{const t=bo(s,["vpcC"])[0];if(t&&t.length>6){const e=t[4],s=t[5],i=t[6]>>4&15;n+="."+Co(e)+"."+Co(s)+"."+Co(i)}break}case"av01":{const t=bo(s,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,i=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,d=2===e&&o?l?12:10:o?10:8,c=(16&t[2])>>4,h=(8&t[2])>>3,u=(4&t[2])>>2,f=3&t[2],g=1,p=1,m=1,v=0;n+="."+e+"."+Co(i)+a+"."+Co(d)+"."+c+"."+h+u+f+"."+Co(g)+"."+Co(p)+"."+Co(m)+"."+v,r=wo("dav1",s)}break}}return{codec:n,encrypted:a,supplemental:r}}function wo(t,e){const s=bo(e,["dvvC"]),i=s.length?s[0]:bo(e,["dvcC"])[0];if(i){const e=i[2]>>1&127,s=i[2]<<5&32|i[3]>>3&31;return t+"."+Co(e)+"."+Co(s)}}function Po(t,e){const s=e+5;for(;128&t[e++]&&e<s;);return e}function Do(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function Co(t){return(t<10?"0":"")+t}function Oo(t,e){bo(t,["moov","trak"]).forEach(t=>{const s=bo(t,["mdia","minf","stbl","stsd"])[0];if(!s)return;const i=s.subarray(8);let r=bo(i,["enca"]);const n=r.length>0;n||(r=bo(i,["encv"])),r.forEach(t=>{bo(n?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const s=Mo(t);s&&e(s,n)})})})}function Mo(t){const e=bo(t,["schm"])[0];if(e){const s=ho(e.subarray(4,8));if("cbcs"===s||"cenc"===s){const e=bo(t,["schi","tenc"])[0];if(e)return e}}}let xo;function Fo(t){if("undefined"==typeof TextDecoder)return Ja(t);return(xo||(xo=new TextDecoder("utf-8"))).decode(t).replace(/\0/g,"")}function No(t,e,s,i,r){const n={};let a=!1;const o=function(t){const e=t.byteLength,s=[];for(let i=0;i<e;){const r=i+8<=e,n=i+4<=e?16777216*t[i]+(t[i+1]<<16|t[i+2]<<8|t[i+3]):mo(t,i),a=n>1?i+n:e;if(r&&109===t[i+4]&&111===t[i+5]&&111===t[i+6]&&102===t[i+7]){const r=Math.min(a,e);for(let e=i+8;e<r;){const n=e+8<=r,a=e+4<=r?16777216*t[e]+(t[e+1]<<16|t[e+2]<<8|t[e+3]):mo(t,e),o=a>1?e+a:r;if(n&&116===t[e+4]&&114===t[e+5]&&97===t[e+6]&&102===t[e+7]){const n=Math.min(o,r);let a,l;const d=[];for(let s=e+8;s<n;){const e=s+8<=n,i=s+4<=n?16777216*t[s]+(t[s+1]<<16|t[s+2]<<8|t[s+3]):mo(t,s),r=i>1?s+i:n;if(e&&116===t[s+4]){const e=Math.min(r,n);102===t[s+5]&&104===t[s+6]&&100===t[s+7]?l||(l=t.subarray(s+8,e)):102===t[s+5]&&100===t[s+6]&&116===t[s+7]?a||(a=t.subarray(s+8,e)):114===t[s+5]&&117===t[s+6]&&110===t[s+7]&&d.push(t.subarray(s+8,e))}s=r}s.push({moofOffset:t.byteOffset+i,tfdt:a,tfhd:l,truns:d})}e=o}}i=a}return s}(t),l=t.byteLength;for(let h=0;h<o.length;h++){const{moofOffset:u,tfdt:f,tfhd:g,truns:p}=o[h],m=mo(g,4),v=e[m];if(!v)continue;const y=n[m]||(n[m]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:v.timescale,type:v.type});let E;if(f){const t=f[0];E=mo(f,4),1===t&&(E===uo?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(E*=uo+1,E+=mo(f,8))),Vn(E)&&(!Vn(y.start)||E<y.start)&&(y.start=E),r&&Vn(E)&&(r.timeOffset=E/r.timescale)}const T=(null==r?void 0:r.trackId)===m&&v.type===fa,S=v.default,A=16777215&mo(g,0);let _,b=(null==S?void 0:S.duration)||0,L=(null==S?void 0:S.sampleSize)||0,R=8;1&A&&(R+=8),2&A&&(R+=4),8&A&&(b=mo(g,R),_=g.byteOffset-t.byteOffset+R,R+=4),16&A&&(L=mo(g,R));let I=0;const k=!!(1&A),w=!k&&!!(131072&A);k?(I=mo(g,8),I*=Math.pow(2,32),I+=mo(g,12)):w&&(I=u);let P=E||0,D=0,C=b;for(let e=0;e<p.length;e++){const s=p[e],n=mo(s,4),a=y.sampleCount;y.sampleCount+=n;const o=1&s[3];let h=0;const u=4&s[3],f=1&s[2],g=2&s[2],m=4&s[2],v=8&s[2];let E=8;if(o&&(h=Eo(s,E),E+=4),u){1&s[E+1]||void 0!==y.keyFrameIndex||(y.keyFrameIndex=a),E+=4}let S,A,R,k=I+h;if(!i&&0===s[1]&&6===s[2]&&1===s[3]){var d,c;const e=P,i=k,a=E;let o=-1,h=0,u=0,f=null!=(d=null==r?void 0:r.timeOffset)?d:0;const g=b/(null!=(c=null==r?void 0:r.timescale)?c:1),p=!0===(null==r?void 0:r.isHEVCFlavor),m=p?2:1;for(let e=0;e<n;e++){const i=0===s[E]?s[E+1]<<16|s[E+2]<<8|s[E+3]:mo(s,E),n=-1===o&&void 0===y.keyFrameIndex&&!(1&s[E+5]);E+=8;const a=k+i;if(T){if(i>0){let e=k;do{const s=0===t[e]?t[e+1]<<16|t[e+2]<<8|t[e+3]:mo(t,e);e+=4;const i=t[e],n=p?i>>1&63:31&i;(p?39===n||40===n:6===n)&&Go(t.subarray(e,e+s),m,f,r.samples),e+=s}while(e<a)}f+=g}k=a,n&&(o=e,h=k)}if(k<=l)u=n;else{let t=i,e=a;for(let i=0;i<n;i++){if(t+=0===s[e]?s[e+1]<<16|s[e+2]<<8|s[e+3]:mo(s,e),t>l)break;u=i+1,e+=8}}if(T&&(r.timeOffset=f),-1!==o&&h<=l&&void 0===y.keyFrameIndex&&(y.keyFrameIndex=o,y.keyFrameStart=e+o*b),u){(!Vn(y.ptsMin)||e<y.ptsMin)&&(y.ptsMin=e);const t=e+u*b;(!Vn(y.ptsMax)||t>y.ptsMax)&&(y.ptsMax=t)}const v=b*n;P=e+v,D+=v;continue}i&&(S=[],A={sampleOffset:k,samples:S,defaultSampleDurationOffset:_},k<=l&&y.trun.push(A));for(let e=0;e<n;e++){let n,a,o;f?(i&&(n=s.byteOffset-t.byteOffset+E),C=mo(s,E),E+=4):C=b,g?(R=mo(s,E),E+=4):R=L,m&&(o=1&s[E+1]?1:0,i&&(a={isNonSync:o,dependsOn:1==(3&s[E])?1:2}),E+=4);let d=0;if(v){d=0===s[0]?mo(s,E):Eo(s,E),E+=4}if(T){let e=k,s=0;for(;s<R;){const i=mo(t,e);e+=4,$o(r.isHEVCFlavor,t[e])&&Go(t.subarray(e,e+i),r.isHEVCFlavor?2:1,r.timeOffset+d/r.timescale,r.samples),e+=i,s+=i+4}r.timeOffset+=C/r.timescale}if(k+=R,k<=l){A&&void 0!==n&&(A.lastSampleDurationOffset=n),0===o&&void 0===y.keyFrameIndex&&(y.keyFrameIndex=e,y.keyFrameStart=P);const t=P+d;(!Vn(y.ptsMin)||t<y.ptsMin)&&(y.ptsMin=t),(!Vn(y.ptsMax)||t+C>y.ptsMax)&&(y.ptsMax=t+C),S&&(S[e]={cts:d,duration:C,flags:a,size:R})}P+=C,D+=C}!D&&b&&(D+=b*n)}y.duration+=D,y.duration&&(a=!0)}if(!a){let e=1/0,s=0;const i=bo(t,["sidx"]);for(let t=0;t<i.length;t++){const r=Ro(i[t]);if(null!=r&&r.references){e=Math.min(e,r.earliestPresentationTime/r.timescale);const t=r.references.reduce((t,e)=>t+e.info.duration||0,0);s=Math.max(s,t+r.earliestPresentationTime/r.timescale)}}s&&Vn(s)&&Object.keys(n).forEach(t=>{n[t].duration||(n[t].duration=s*n[t].timescale-n[t].start)})}return n}function Uo(t,e){const s=new Uint8Array(t.length+e.length);return s.set(t),s.set(e,t.length),s}function Bo(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function $o(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function Go(t,e,s,i){const r=Ho(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const t=r.length-n;let e=n;if(o<t)n+=o;else if(o>t){Ua.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=po(r,e);if(e+=2,49===t){const t=mo(r,e);if(e+=4,1195456820===t){const t=r[e++];if(3===t){const n=r[e++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let t=1;t<l;t++)d[t]=r[e++]}i.push({type:t,payloadType:a,pts:s,bytes:d})}}}}}else if(5===a&&o>16){const t=[];for(let s=0;s<16;s++){const i=r[e++].toString(16);t.push(1==i.length?"0"+i:i),3!==s&&5!==s&&7!==s&&9!==s||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=r[e++];i.push({payloadType:a,pts:s,uuid:t.join(""),userData:Fo(l),userDataBytes:l})}}}function Ho(t){const e=t.byteLength;let s,i=t.indexOf(3,3);for(;-1!==i;)0===t[i-1]&&0===t[i-2]&&(s||(s=[])).push(i),i=t.indexOf(3,i+1);if(!s)return t;const r=e-s.length,n=new Uint8Array(r);let a=0,o=0;for(let e=0;e<r;o++,e++)o===s[a]&&(o++,a++),n[e]=t[o];return n}function Ko(t,e,s){if(16!==t.byteLength)throw new RangeError("Invalid system id");let i,r,n;i=0,r=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),function(t,...e){const s=e.length;let i=8,r=s;for(;r--;)i+=e[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(t,4),r=0,i=8;r<s;r++)n.set(e[r],i),i+=e[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),t,n,r,a,s)}function Vo(t){const e=[];if(t instanceof ArrayBuffer){const s=t.byteLength;let i=0;for(;i+32<s;){const s=jo(new DataView(t,i));e.push(s),i+=s.size}}return e}function jo(t){const e=t.getUint32(0),s=t.byteOffset,i=t.byteLength;if(i<e)return{offset:s,size:i};if(1886614376!==t.getUint32(4))return{offset:s,size:e};const r=t.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:s,size:e};const n=t.buffer,a=oo(new Uint8Array(n,s+12,16));let o=null,l=null,d=0;if(0===r)d=28;else{const r=t.getUint32(28);if(!r||i<32+16*r)return{offset:s,size:e};o=[];for(let t=0;t<r;t++)o.push(new Uint8Array(n,s+32+16*t,16));d=32+16*r}if(!d)return{offset:s,size:e};const c=t.getUint32(d);return e-32<c?{offset:s,size:e}:(l=new Uint8Array(n,s+d+4,c),0===r&&(o=function(t){const e=[];for(let s=0;s<t.length;){const i=t[s++],r=7&i;if(0===r){for(;128&t[s++];);continue}if(2!==r){s+=1===r?8:4;continue}let n=0;for(let e=0,i=128;128&i;e+=7)n|=(127&(i=t[s++]))<<e;if(i>>3==2)if(32===n){const i=new Uint8Array(16);for(let e=0;e<16;e++)i[e]=parseInt(String.fromCharCode(t[s+2*e],t[s+2*e+1]),16);e.push(i)}else 16===n&&e.push(t.subarray(s,s+16));s+=n}return e}(l)),{version:r,systemId:a,kids:o,data:l,offset:s,size:e})}const qo=Xo("userAgent"),Wo=Xo("vendor");let Yo,zo,Qo;function Xo(t){try{return navigator[t]||""}catch(t){}return""}function Zo(){if(void 0===Yo){const t=qo.match(/Chrome\/(\d+)/i);Yo=t?parseInt(t[1]):0}return Yo}function Jo(){return/\(Windows.+Firefox\//i.test(qo)}const tl={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function el(t,e){const s=tl[e];return!!s&&!!s[t.slice(0,4)]}function sl(t,e,s=!0){return!t.split(",").some(t=>!il(t,e,s))}function il(t,e,s=!0){var i;const r=Ba(s);return null!=(i=null==r?void 0:r.isTypeSupported(rl(t,e)))&&i}function rl(t,e){return`${e}/mp4;codecs=${t}`}function nl(t){if(t){const e=t.substring(0,4);return tl.video[e]}return 2}function al(t){const e=Jo();return t.split(",").reduce((t,s)=>{const i=e&&Bo(s)?9:tl.video[s];return i?(2*i+t)/(t?3:2):(tl.audio[s]+t)/(t?2:1)},0)}const ol={};const ll=/flac|opus|mp4a\.40\.34/i;function dl(t,e=!0){return t.replace(ll,t=>function(t,e=!0){if(ol[t])return ol[t];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let r=0;r<s.length;r++){var i;if(il(s[r],"audio",e))return ol[t]=s[r],s[r];if("mp3"===s[r]&&null!=(i=Ba(e))&&i.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e))}function cl(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(hl(t,"audio")||hl(t,"video")))return t;if(e){const s=e.split(",");if(s.length>1){if(t)for(let e=s.length;e--;)if(s[e].substring(0,4)===t.substring(0,4))return s[e];return s[0]}}return e||t}function hl(t,e){return el(t,e)&&il(t,e)}function ul(t){if(t.startsWith("av01.")){const e=t.split("."),s=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=s[t-4];return e.join(".")}return t}function fl(t){const e=Ba(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function gl(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const pl={supported:!1,smooth:!1,powerEfficient:!1},ml={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function vl(t,e){return{supported:!1,configurations:e,decodingInfoResults:[pl],error:t}}function yl(t,e,s,i,r,n){const a=t.videoCodec,o=t.audioCodec?t.audioGroups:null,l=null==n?void 0:n.audioCodec,d=null==n?void 0:n.channels,c=d?parseInt(d):l?1/0:2;let h=null;if(null!=o&&o.length)try{h=1===o.length&&o[0]?e.groups[o[0]].channels:o.reduce((t,s)=>{if(s){const i=e.groups[s];if(!i)throw new Error(`Audio track group ${s} not found`);Object.keys(i.channels).forEach(e=>{t[e]=(t[e]||0)+i.channels[e]})}return t},{2:0})}catch(t){return!0}return void 0!==a&&(a.split(",").some(t=>Bo(t))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(i,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(r,8e6))||!!h&&Vn(c)&&Object.keys(h).some(t=>parseInt(t)>c)}function El(t,e,s,i={}){const r=t.videoCodec;if(!r&&!t.audioCodec||!s)return Promise.resolve(ml);const n=[],a=function(t){var e;const s=null==(e=t.videoCodec)?void 0:e.split(","),i=Sl(t),r=t.width||640,n=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return s?s.map(t=>{const e={contentType:rl(ul(t),"video"),width:r,height:n,bitrate:i,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e}):[]}(t),o=a.length,l=function(t,e,s){var i;const r=null==(i=t.audioCodec)?void 0:i.split(","),n=Sl(t);if(r&&t.audioGroups)return t.audioGroups.reduce((t,i)=>{var a;const o=i?null==(a=e.groups[i])?void 0:a.tracks:null;return o?o.reduce((t,e)=>{if(e.groupId===i){const i=parseFloat(e.channels||"");r.forEach(e=>{const r={contentType:rl(e,"audio"),bitrate:s?Tl(e,n):n};i&&(r.channels=""+i),t.push(r)})}return t},t):t},[]);return[]}(t,e,o>0),d=l.length;for(let t=o||1*d||1;t--;){const e={type:"media-source"};if(o&&(e.video=a[t%o]),d){e.audio=l[t%d];const s=e.audio.bitrate;e.video&&s&&(e.video.bitrate-=s)}n.push(e)}if(r){const t=navigator.userAgent;if(r.split(",").some(t=>Bo(t))&&Jo())return Promise.resolve(vl(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),n))}return Promise.all(n.map(t=>{const e=function(t){let e="";const{audio:s,video:i}=t;if(i){e+=`${gl(i.contentType)}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(s){e+=`${i?"_":""}${gl(s.contentType)}_c${s.channels}`}return e}(t);return i[e]||(i[e]=s.decodingInfo(t))})).then(t=>({supported:!t.some(t=>!t.supported),configurations:n,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:n,decodingInfoResults:[],error:t}))}function Tl(t,e){if(e<=1)return 1;let s=128e3;return"ec-3"===t?s=768e3:"ac-3"===t&&(s=64e4),Math.min(e/2,s)}function Sl(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}function Al(t,e,s){const i=encodeURIComponent(e),r=`${i}=${encodeURIComponent(s)}`;let n=!1;const a=[];t.search.substring(1).split("&").forEach(t=>{t===i||t.startsWith(i+"=")?n||(a.push(r),n=!0):t&&a.push(t)}),n||a.push(r),t.search=a.join("&")}const _l=["NONE","TYPE-0","TYPE-1",null];const bl=["SDR","PQ","HLG"];var Ll="",Rl="YES",Il="v2";function kl(t){const{canSkipUntil:e,canSkipDateRanges:s,age:i}=t;return e&&i<e/2?s?Il:Rl:Ll}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&&Al(e,"_HLS_msn",this.msn.toString()),void 0!==this.part&&Al(e,"_HLS_part",this.part.toString()),this.skip&&Al(e,"_HLS_skip",this.skip),e.href}}class Level{constructor(t){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[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.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,"imageCodec"in t&&(this.imageCodec=t.imageCodec),this.codecSet=[t.videoCodec,t.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const s=null==(e=t.supplemental)?void 0:e.videoCodec;s&&s!==t.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}"iframes"in t&&t.iframes?this.iframes=!0:(this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return wl(this._audioGroups,t)}hasSubtitleGroup(t){return wl(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function wl(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function Pl(t,e){let s=!1,i=[];if(t&&(s="SDR"!==t,i=[t]),e){i=e.allowedVideoRanges||bl.slice(0);const t="SDR"!==i.join("")&&!e.videoCodec;s=void 0!==e.preferHDR?e.preferHDR:t&&function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),s||(i=["SDR"])}return{preferHDR:s,allowedVideoRanges:i}}const Dl=(t,e)=>JSON.stringify(t,(t=>{const e=new WeakSet;return(s,i)=>{if(t&&(i=t(s,i)),"object"==typeof i&&null!==i){if(e.has(i))return;e.add(i)}return i}})(e));function Cl(t,e){Ua.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function Ol(t){return t.reduce((t,e)=>{let s=t.groups[e.groupId];s||(s=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(e);const i=e.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||e.default,s.hasAutoSelect=s.hasAutoSelect||e.autoselect,s.hasDefault&&(t.hasDefaultAudio=!0),s.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Ml(t){if(!t)return t;const{lang:e,assocLang:s,characteristics:i,channels:r,audioCodec:n}=t;return{lang:e,assocLang:s,characteristics:i,channels:r,audioCodec:n}}function xl(t,e,s){if("attrs"in t){const s=e.indexOf(t);if(-1!==s)return s}for(let i=0;i<e.length;i++){if(Fl(t,e[i],s))return i}return-1}function Fl(t,e,s){const{groupId:i,name:r,lang:n,assocLang:a,default:o}=t,l=t.forced;return(void 0===i||e.groupId===i)&&(void 0===r||e.name===r)&&(void 0===n||function(t,e="--"){if(t.length===e.length)return t===e;return t.startsWith(e)||e.startsWith(t)}(n,e.lang))&&(void 0===n||e.assocLang===a)&&(void 0===o||e.default===o)&&(void 0===l||e.forced===l)&&(!("characteristics"in t)||function(t,e=""){const s=t.split(","),i=e.split(",");return s.length===i.length&&!s.some(t=>-1===i.indexOf(t))}(t.characteristics||"",e.characteristics))&&(void 0===s||s(t,e))}function Nl(t,e){const{audioCodec:s,channels:i}=t;return!(void 0!==s&&(e.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==i&&i!==(e.channels||"2"))}function Ul(t,e,s){for(let i=e;i>-1;i--)if(s(t[i]))return i;for(let i=e+1;i<t.length;i++)if(s(t[i]))return i;return-1}function Bl(t,e){var s;return!!t&&t!==(null==(s=e.loadLevelObj)?void 0:s.uri)}function $l(t,e){return!e||-1!==e.indexOf(t)}function Gl(t,e){if(e||t){const s=Ta({},e);return t&&(t.videoCodec&&(s.videoCodec=t.videoCodec),t.videoRange&&(s.allowedVideoRanges=[t.videoRange])),s}}const Hl=function(t,e){let s=0,i=t.length-1,r=null,n=null;for(;s<=i;){r=(s+i)/2|0,n=t[r];const a=e(n);if(a>0)s=r+1;else{if(!(a<0))return n;i=r-1}}return null};function Kl(t,e,s=0,i=0,r=.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;const i=t.endDTS-s;i>0&&i<15e-7&&(s+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===s&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===Vl(s,i,n)||function(t,e,s){if(0===(null==e?void 0:e.start)&&e.level<t.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t),s);return t.start<=i}return!1}(n,t,Math.min(r,i))))return n;const a=Hl(e,Vl.bind(null,s,i));return!a||a===t&&n?n:a}function Vl(t=0,e=0,s){if(s.start<=t&&s.start+s.duration>t)return 0;const i=Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-i<=t?1:s.start-i>t&&s.start?-1:0}function jl(t,e,s){const i=1e3*Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-i>t}function ql(t,e,s){if(t&&t.startCC<=e&&t.endCC>=e){let i=t.fragments;const{fragmentHint:r}=t;let n;return r&&(i=i.concat(r)),Hl(i,t=>t.cc<e?1:t.cc>e?-1:(n=t,t.end<=s?1:t.start>s?-1:0)),n||null}return null}function Wl(t,e){return e===t.endSN&&t.fragmentHint?t.fragmentHint:t.fragments[1+e-t.startSN]||null}var Yl=0,zl=2,Ql=3,Xl=5,Zl=0,Jl=1,td=2,ed=4,sd=8,id=16;function rd(t){const e=t.details;return e===Yn.BUFFER_ADD_CODEC_ERROR||e===Yn.MEDIA_SOURCE_REQUIRES_RESET||e===Yn.BUFFER_APPEND_ERROR&&!nd(t)}function nd(t){return t.details===Yn.BUFFER_APPEND_ERROR&&("QuotaExceededError"===t.error.name||"InvalidStateError"===t.error.name)}function ad(t){const e={action:Yl,flags:Zl};return t&&(e.resolved=!0),e}var od="NOT_LOADED",ld="APPENDING",dd="PARTIAL",cd="OK";class FragmentTracker{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t&&(t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.BUFFER_APPENDED,this.onBufferAppended,this),t.on(zn.FRAG_BUFFERED,this.onFragBuffered,this),t.on(zn.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.BUFFER_APPENDED,this.onBufferAppended,this),t.off(zn.FRAG_BUFFERED,this.onFragBuffered,this),t.off(zn.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const s=this.activePartLists[e];if(s)for(let e=s.length;e--;){const i=s[e];if(!i)break;if(i.start<=t&&t<=i.end&&i.loaded)return i}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const a=i[r[n]];if((null==a?void 0:a.body.type)===e&&(!s||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,s,i,r,n){this.timeRanges&&(this.timeRanges[t]=e);const a=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(r=>{const o=this.fragments[r];if(!o||!this.hls)return;const l=o.body;if(a>=l.sn)return;if(!o.buffered&&(!o.loaded||n))return void(l.type===s&&this.removeFragment(l));const d=o.range[t];if(d)if(0!==d.time.length){if(d.time.some(t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return s&&this.removeFragment(l),s}),i&&i!==l&&Zo()){const t=i.endPTS,e=l.startPTS;if(t&&e&&o.range.video){const s=e-t;s<0&&s>-.1&&(this.removeFragment(l),this.hls.trigger(zn.BUFFER_FLUSHING,{startOffset:t+.004,endOffset:1/0,type:"video"}))}}}else this.removeFragment(l)})}detectPartialFragments(t){const e=this.timeRanges,{frag:s,part:i,id:r}=t;if(!e||!pa(s))return;const n=ud(s),a=this.fragments[n];if(!a||a.buffered&&s.gap)return;const o=!s.relurl;Object.keys(e).forEach(t=>{const n=s.elementaryStreams[t];if(!n)return;const l=e[t],d=o||!0===n.partial;a.range[t]=this.getBufferedTimes(s,i,d,l),this.detectEvictedFragments(t,l,r,s,i)}),a.loaded=null;const l=Object.keys(a.range);if(l.length){if(this.bufferedEnd(a,s),hd(a)||this.removeParts(s.sn-1,s.type),!i){const t=Math.min(.004,s.duration);l.some(e=>{var i;const r=null==(i=a.range[e])?void 0:i.time,n=0===r.length||1===r.length&&r[0].endPTS-r[0].startPTS<t;return n&&this.addAsGap(s),n})}}else this.removeFragment(s)}addAsGap(t){t.gap=!0,this.removeFragment(t),this.fragBuffered(t,!0)}bufferedEnd(t,e){t.buffered=!0;(t.body.endList=e.endList||t.body.endList)&&!e.gap&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const s=this.activePartLists[e];s&&(this.activePartLists[e]=fd(s,e=>e.fragment.sn>=t))}fragBuffered(t,e){const s=ud(t);let i=this.fragments[s];return!i&&e&&(i=this.fragments[s]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,t)),i}getBufferedTimes(t,e,s,i){const r={time:[],partial:s},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<i.length;t++){const e=i.start(t)-this.bufferPadding,s=i.end(t)+this.bufferPadding;if(l>=e&&o<=s){r.time.push({startPTS:Math.max(n,i.start(t)),endPTS:Math.min(a,i.end(t))});break}if(n<s&&a>e){const e=Math.max(n,i.start(t)),s=Math.min(a,i.end(t));s>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:s}))}else if(a<=e)break}return r}getPartialFragment(t){let e,s,i,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&hd(d)&&(s=d.body.start-a,i=d.body.end+a,t>=s&&t<=i&&(e=Math.min(t-s,i-t),n<=e&&(r=d.body,n=e)))}),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||hd(e))}getState(t){const e=ud(t),s=this.fragments[e];return s?s.buffered?hd(s)?dd:cd:ld:od}isTimeBuffered(t,e,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,t>=i&&e<=r)return!0;if(e<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if(!pa(e.frag)||e.frag.bitrateTest)return;const s=e.frag,i=e.part?null:e,r=ud(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:s,part:i,timeRanges:r}=e;if(!pa(s))return;const n=s.type;if(i){let t=this.activePartLists[n];t||(this.activePartLists[n]=t=[]),t.push(i)}this.timeRanges=r}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=ud(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,s=Object.keys(e);if(!t)return s.length>0;for(let i=s.length;i--;){const r=e[s[i]];if((null==r?void 0:r.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}getBackBufferEvictionEnd(t,e,s){const{fragments:i}=this;let r=0,n=0;const a=Object.keys(i);for(let o=0;o<a.length;o++){const l=i[a[o]];if(!l||!l.buffered||l.body.type!==e)continue;const d=l.body;if(d.gap)return 0;const c=d.hasStats&&d.stats.loaded||d.byteLength||d.bitrate&&8*d.bitrate*d.duration;if(d.end<=t&&c&&(r+=c,n=Math.max(n,d.end),r>=s))return n}return n>0?n:0}removeFragmentsInRange(t,e,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||i&&!o.gap||o.start<e&&o.end>t&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(t){const e=ud(t);t.clearElementaryStreamInfo();const s=this.activePartLists[t.type];if(s){const e=t.sn;this.activePartLists[t.type]=fd(s,t=>t.fragment.sn!==e)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach(t=>t.clearElementaryStreamInfo())}}function hd(t){var e,s,i,r;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(s=t.range.audio)&&s.partial||null!=(i=t.range.audiovideo)&&i.partial||null!=(r=t.range.subs)&&r.partial)}function ud(t){return`${t.type}_${t.level}_${t.sn}`}function fd(t,e){return t.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var gd=0,pd=1;class AESCrypto{constructor(t,e,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=s}decrypt(t,e){switch(this.aesMode){case gd:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case pd:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}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,i=s[0],r=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],d=o[1],c=o[2],h=o[3],u=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)u[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=u[f],p=u[o],m=u[p];let v=257*u[s]^16843008*s;i[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*m^65537*p^257*o^16843008*f,l[s]=v<<24|v>>>8,d[s]=v<<16|v>>>16,c[s]=v<<8|v>>>24,h[s]=v,f?(f=o^u[u[u[m^o]]],g^=u[u[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let s=!0,i=0;for(;i<e.length&&s;)s=e[i]===this.key[i],i++;if(s)return;this.key=e;const r=this.keySize=e.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),c=this.sBox,h=this.rcon,u=this.invSubMix,f=u[0],g=u[1],p=u[2],m=u[3];let v,y;for(a=0;a<n;a++)a<r?v=l[a]=e[a]:(y=v,a%r===0?(y=y<<8|y>>>24,y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y],y^=h[a/r|0]<<24):r>6&&a%r===4&&(y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?y:f[c[y>>>24]]^g[c[y>>>16&255]]^p[c[y>>>8&255]]^m[c[255&y]],d[o]=d[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],c=a[3],h=this.uint8ArrayToUint32Array_(s);let u=h[0],f=h[1],g=h[2],p=h[3];const m=new Int32Array(t),v=new Int32Array(m.length);let y,E,T,S,A,_,b,L,R,I,k,w,P,D;const C=this.networkToHostOrderSwap;for(;e<m.length;){for(R=C(m[e]),I=C(m[e+1]),k=C(m[e+2]),w=C(m[e+3]),A=R^r[0],_=w^r[1],b=k^r[2],L=I^r[3],P=4,D=1;D<i;D++)y=o[A>>>24]^l[_>>16&255]^d[b>>8&255]^c[255&L]^r[P],E=o[_>>>24]^l[b>>16&255]^d[L>>8&255]^c[255&A]^r[P+1],T=o[b>>>24]^l[L>>16&255]^d[A>>8&255]^c[255&_]^r[P+2],S=o[L>>>24]^l[A>>16&255]^d[_>>8&255]^c[255&b]^r[P+3],A=y,_=E,b=T,L=S,P+=4;y=n[A>>>24]<<24^n[_>>16&255]<<16^n[b>>8&255]<<8^n[255&L]^r[P],E=n[_>>>24]<<24^n[b>>16&255]<<16^n[L>>8&255]<<8^n[255&A]^r[P+1],T=n[b>>>24]<<24^n[L>>16&255]<<16^n[A>>8&255]<<8^n[255&_]^r[P+2],S=n[L>>>24]<<24^n[A>>16&255]<<16^n[_>>8&255]<<8^n[255&b]^r[P+3],v[e]=C(y^u),v[e+1]=C(S^f),v[e+2]=C(T^g),v[e+3]=C(E^p),u=R,f=I,g=k,p=w,e+=4}return v.buffer}}class FastAESKey{constructor(t,e,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=s}expandKey(){const t=function(t){switch(t){case gd:return"AES-CBC";case pd:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}class Decrypter{constructor(t,e){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,!0!==e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const s=new Uint8Array(t);this.reset();const i=this.decryptRange;return i?0===i.start&&i.end>=s.length?s:s.slice(i.start,i.end):function(t){const e=t.byteLength,s=e&&new DataView(t.buffer).getUint8(e-1);return s?t.slice(0,e-s):t}(s)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,s,i,r){return this.decryptRange=r,this.useSoftware||r?new Promise((r,n)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,s,i);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,s,i)}softwareDecrypt(t,e,s,i){const{currentIV:r,currentResult:n,remainderData:a}=this;if(i!==gd||16!==e.byteLength)return Ua.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=Uo(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new AESDecryptor),l.expandKey(e);const d=n;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(t,e,s,i){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,s,i));this.key=e,this.fastAesKey=new FastAESKey(this.subtle,e,i)}return this.fastAesKey.expandKey().then(e=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new AESCrypto(this.subtle,new Uint8Array(s),i).decrypt(t.buffer,e)}).catch(r=>(Ua.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,s,i)))}onWebCryptoError(t,e,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,s,i);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const s=t.length-t.length%16;return s!==t.length&&(e=t.slice(0,s),this.remainderData=t.slice(s)),e}logOnce(t){this.logEnabled&&(Ua.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const md=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,s,i){const r=t.url;if(!r)return Promise.reject(new LoadError({type:Wn.NETWORK_ERROR,details:Yn.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();const n=this.config,a=n.fLoader,o=n.loader;return new Promise((l,d)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some(t=>"GAP"===t[0]))return void d(Ed(t));t.gap=!1}const c=this.loader=a?new a(n):new o(n),h=vd(t,null,e);t.loader=c;const u=wa(n.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:md};c.stats.retry=t.stats.retry,t.stats=c.stats;const g={onSuccess:(e,s,i,r)=>{this.resetLoader(t,c);let n=e.data;i.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),l({frag:t,part:null,payload:n,networkDetails:r})},onError:(e,s,i,n)=>{this.resetLoader(t,c),d(new LoadError({type:Wn.NETWORK_ERROR,details:Yn.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:Aa({url:r,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:i,stats:n}))},onAbort:(e,s,i)=>{this.resetLoader(t,c),d(new LoadError({type:Wn.NETWORK_ERROR,details:Yn.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:i,stats:e}))},onTimeout:(e,s,i)=>{this.resetLoader(t,c),d(new LoadError({type:Wn.NETWORK_ERROR,details:Yn.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:i,stats:e}))}};if(s){const e=this.gateProgress(s,i);g.onProgress=(s,i,r,n)=>e({frag:t,part:null,payload:r,networkDetails:n})}c.load(h,f,g)})}gateProgress(t,e){let s=t;if(e){const i=[];let r=!1;e.then(()=>{r=!0,i.forEach(e=>t(e)),i.length=0}).catch(()=>{}),s=e=>{r?t(e):i.push(e)}}return s}loadPart(t,e,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(Ed(t,e));const l=this.loader=r?new r(i):new n(i),d=vd(t,e);t.loader=l;const c=wa(i.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:md};e.stats=l.stats,l.load(d,h,{onSuccess:(i,r,n,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const d={frag:t,part:e,payload:i.data,networkDetails:o};s(d),a(d)},onError:(s,i,r,n)=>{this.resetLoader(t,l),o(new LoadError({type:Wn.NETWORK_ERROR,details:Yn.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:Aa({url:d.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:r,stats:n}))},onAbort:(s,i,r)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new LoadError({type:Wn.NETWORK_ERROR,details:Yn.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:r,stats:s}))},onTimeout:(s,i,r)=>{this.resetLoader(t,l),o(new LoadError({type:Wn.NETWORK_ERROR,details:Yn.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:r,stats:s}))}})})}updateStatsFromPart(t,e){const s=t.stats,i=e.stats,r=i.total;if(s.loaded+=i.loaded,r){const i=Math.round(t.duration/e.duration),n=Math.min(Math.round(s.loaded/r),i),a=(i-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=i.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,t.url=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function vd(t,e=null,s){const i={type:ra,frag:t,part:e,responseType:"arraybuffer",url:(e||t).url,headers:{},rangeStart:0,rangeEnd:0},r=yd(t,e,s);return r.resetIV&&(i.resetIV=!0),r.byteRange&&(i.rangeStart=r.byteRange.start,i.rangeEnd=r.byteRange.end),i}function yd(t,e=null,s){const i={},r=e||t,n=r.byteRangeStartOffset,a=r.byteRangeEndOffset;var o,l;if(Vn(n)&&Vn(a))if("initSegment"!==t.sn&&!s||"AES-128"!==(l=null==(o=t.decryptdata)?void 0:o.method)&&"AES-256"!==l)i.byteRange={start:n,end:a};else{let t=16*Math.floor(n/16);const e=16*Math.ceil(a/16);i.decryptRange={start:n-t,end:a-t},t>=16&&(i.resetIV=!0,t-=16),i.byteRange={start:t,end:e}}return i}function Ed(t,e){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),i={type:Wn.MEDIA_ERROR,details:Yn.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return e&&(i.part=e),(e||t).stats.aborted=!0,new LoadError(i)}class LoadError extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class TaskLoop extends Logger{constructor(t,e){super(t,e),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):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class ChunkMetadata{constructor(t,e,s,i=0,r=-1,n=!1,a,o,l){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.iframe=void 0,this.duration=void 0,this.decryptRange=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=i,this.part=r,this.partial=n,this.duration=a||0,this.decryptRange=l,this.iframe=o||!1}}const Td={length:0,start:()=>0,end:()=>0};class BufferHelper{static isBuffered(t,e){if(t){const s=BufferHelper.getBuffered(t);for(let t=s.length;t--;)if(e>=s.start(t)&&e<=s.end(t))return!0}return!1}static bufferedRanges(t){if(t){const e=BufferHelper.getBuffered(t);return BufferHelper.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let s=0;s<t.length;s++)e.push({start:t.start(s),end:t.end(s)});return e}static bufferInfo(t,e,s){if(t){const i=BufferHelper.bufferedRanges(t);if(i.length)return BufferHelper.bufferedInfo(i,e,s)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,s){e=Math.max(0,e),t.length>1&&t.sort((t,e)=>t.start-e.start||e.end-t.end);let i=-1,r=[];if(s)for(let n=0;n<t.length;n++){e>=t[n].start&&e<=t[n].end&&(i=n);const a=r.length;if(a){const e=r[a-1].end;t[n].start-e<s?t[n].end>e&&(r[a-1].end=t[n].end):r.push(t[n])}else r.push(t[n])}else r=t;let n,a=0,o=e,l=e;for(let t=0;t<r.length;t++){const d=r[t].start,c=r[t].end;if(-1===i&&e>=d&&e<=c&&(i=t),e+s>=d&&e<c)o=d,l=c,a=l-e;else if(e+s<d){n=d;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:t,bufferedIndex:i}}static getBuffered(t){try{return t.buffered||Td}catch(t){return Ua.log("failed to get media.buffered",t),Td}}}const Sd=/\{\$([a-zA-Z0-9-_]+)\}/g;function Ad(t){return Sd.lastIndex=0,Sd.test(t)}function _d(t,e){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return e.replace(Sd,e=>{const i=e.substring(2,e.length-1),r=null==s?void 0:s[i];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),e):r})}return e}function bd(t,e,s){let i,r,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){i=e.QUERYPARAM;try{const t=new self.URL(s).searchParams;if(!t.has(i))throw new Error(`"${i}" does not match any query parameter in URI: "${s}"`);r=t.get(i)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else i=e.NAME,r=e.VALUE;i in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=r||""}function Ld(t,e,s){const i=e.IMPORT;if(s&&i in s){let e=t.variableList;e||(t.variableList=e={}),e[i]=s[i]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const Rd=/^(\d+)x(\d+)$/,Id=/(.+?)=(".*?"|.*?)(?:,|$)/g;class AttrList{constructor(t,e){"string"==typeof t&&(t=AttrList.parseAttrList(t,e)),Ta(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>"X-"===t.substring(0,2))}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]}enumeratedStringList(t,e){const s=this[t];return(s?s.split(/[ ,]+/):[]).reduce((t,e)=>(t[e.toLowerCase()]=!0,t),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=Rd.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let s;const i={};for(Id.lastIndex=0;null!==(s=Id.exec(t));){const r=s[1].trim();let n=s[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(a||o))n=_d(e,n);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Ua.warn(`${t}: attribute ${r} is missing quotes`)}i[r]=n}return i}}function kd(t){return"ID"!==t&&"CLASS"!==t&&"CUE"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function wd(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class DateRange{constructor(t,e,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==e?void 0:e.tagAnchor)||null,this.tagOrder=null!=(i=null==e?void 0:e.tagOrder)?i:s,e){const s=e.attr;for(const e in s)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==s[e]){Ua.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=Ta(new AttrList({}),s,t)}if(this.attr=t,e?(this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in t){const s=(null==e?void 0:e.endDate)||new Date(t["END-DATE"]);Vn(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(Ua.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(Vn(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 isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&Vn(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:Vn(this.startDate.getTime())?!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr?this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Interstitial Date range missing X-ASSET-(LIST|URI)":"Date range invalid start date":"Missing ID"}}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.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=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.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&s>0,this.updated||this.advanced?this.misses=0:this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(e=>{let s=e.decryptdata;return s||(e.setKeyFormat(t.keyFormat),s=e.decryptdata),!!s&&t.matches(s)})}get hasProgramDateTime(){return!!this.fragments.length&&Vn(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(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(-1!==e){for(let s=t.length;s--;)if(t[s].index>e)return t[s].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function Pd(t,e){return t.length===e.length&&!t.some((t,s)=>t!==e[s])}function Dd(t,e){return!t&&!e||!(!t||!e)&&Pd(t,e)}function Cd(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function Od(t){switch(t){case"AES-128":case"AES-256":return gd;case"AES-256-CTR":return pd;default:throw new Error(`invalid full segment method ${t}`)}}function Md(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}function xd(t){const e=function(t,e,s){const i=t[e];t[e]=t[s],t[s]=i};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function Fd(t){const e=t.split(":");let s=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),i=t[t.length-1].split(",");if(2===i.length){const e="base64"===i[0],r=i[1];e?(t.splice(-1,1),s=co(r)):s=function(t){const e=Md(t).subarray(0,16),s=new Uint8Array(16);return s.set(e,16-e.length),s}(r)}}return s}const Nd="undefined"!=typeof self?self:void 0;var Ud={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Bd="org.w3.clearkey",$d="com.apple.streamingkeydelivery",Gd="com.microsoft.playready",Hd="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Kd(t){switch(t){case $d:return Ud.FAIRPLAY;case Gd:return Ud.PLAYREADY;case Hd:return Ud.WIDEVINE;case Bd:return Ud.CLEARKEY}}var Vd="edef8ba979d64acea3c827dcd51d21ed";function jd(t){switch(t){case Ud.FAIRPLAY:return $d;case Ud.PLAYREADY:return Gd;case Ud.WIDEVINE:return Hd;case Ud.CLEARKEY:return Bd}}function qd(t){const{drmSystems:e,widevineLicenseUrl:s}=t,i=e?[Ud.FAIRPLAY,Ud.WIDEVINE,Ud.PLAYREADY,Ud.CLEARKEY].filter(t=>!!e[t]):[];return!i[Ud.WIDEVINE]&&s&&i.push(Ud.WIDEVINE),i}const Wd=null!=Nd&&null!=(Yd=Nd.navigator)&&Yd.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var Yd;function zd(t){const e=ho(new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2)),s=e.substring(e.indexOf("<"),e.length),i=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(i){const t=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(t){const e=co(t).subarray(0,16);return xd(e),e}}return null}let Qd={};class LevelKey{static clearKeyUriToKeyIdMap(){Qd={}}static setKeyIdForUri(t,e){Qd[t]=e}static addKeyIdForUri(t){const e=Object.keys(Qd).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,e),Qd[t]=s,s}constructor(t,e,s,i=[1],r=null,n){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.scheme=void 0,this.method=t,this.uri=e,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!Cd(t),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(lo(n)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&Pd(t.keyFormatVersions,this.keyFormatVersions)&&Dd(t.iv,this.iv)&&Dd(t.keyId,this.keyId)}isSupported(){if(this.method){if(Cd(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case $d:case Hd:case Gd:case Bd:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t,e){var s;if(!this.encrypted||!this.uri)return null;if(Cd(this.method)){let e=this.iv;e||("number"!=typeof t&&(Ua.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),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)}if(this.keyId){const t=Qd[this.uri];if(t&&!Pd(this.keyId,t)&&LevelKey.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=Fd(this.uri);if(i)switch(this.keyFormat){case Hd:if(this.pssh=i,!this.keyId){const t=Vo(i.buffer).filter(t=>t.systemId===Vd);if(t.length){var r;const e=t[0];this.keyId=null!=(r=e.kids)&&r.length?e.kids[0]:null}}this.keyId||(this.keyId=Xd(e));break;case Gd:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Ko(t,0,i),this.keyId=zd(i);break}default:{let t=i.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(16!==(null==(s=this.keyId)?void 0:s.byteLength)){let t;t=function(t){const e=null==t?void 0:t[Hd];if(e)return e.keyId;return null}(e),t||(t=Xd(e),t||(t=Qd[this.uri])),t&&(this.keyId=t,LevelKey.setKeyIdForUri(this.uri,t))}return this}}function Xd(t){const e=null==t?void 0:t[Gd];if(e){const t=Fd(e.uri);if(t)return zd(t)}return null}const Zd=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,Jd=/#EXT-X-MEDIA:(.*)/g,tc=/^#EXT(?:INF|-X-TARGETDURATION):/m,ec=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),sc=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class M3U8Parser{static findGroup(t,e){for(let s=0;s<t.length;s++){const i=t[s];if(i.id===e)return i}}static resolve(t,e){return Jn.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return tc.test(t)}static parseMasterPlaylist(t,e){const s={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Ad(t)},i=[];if(Zd.lastIndex=0,!t.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let r;for(;null!=(r=Zd.exec(t));)if(r[1]){const t=ic(new AttrList(r[1],s),r[2],e,s,i);t&&s.levels.push(t)}else if(r[3]){const t=r[3],n=r[4];switch(t){case"I-FRAME-STREAM-INF":{const t=new AttrList(n,s),r=ic(t,t.URI,e,s,i,!0);r&&s.iframeVariants.push(r)}break;case"SESSION-DATA":{const t=new AttrList(n,s),e=t["DATA-ID"];e&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[e]=t);break}case"SESSION-KEY":{const t=ac(n,e,s);t.encrypted&&t.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(t)):Ua.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${n}"`);break}case"DEFINE":bd(s,new AttrList(n,s),e);break;case"CONTENT-STEERING":{const t=new AttrList(n,s);s.contentSteering={uri:M3U8Parser.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=oc(n)}}const n=i.length>0&&i.length<s.levels.length;return s.levels=n?i:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,e,s){let i;const r={},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(Jd.lastIndex=0;null!==(i=Jd.exec(t));){const t=new AttrList(i[1],s),n=t.TYPE;if(n){const s=a[n],i=r[n]||[];r[n]=i;const l=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],c=t.CHANNELS,h=t.CHARACTERISTICS,u=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?M3U8Parser.resolve(t.URI,e):""};if(d&&(f.assocLang=d),c&&(f.channels=c),h&&(f.characteristics=h),u&&(f.instreamId=u),null!=s&&s.length){const t=M3U8Parser.findGroup(s,f.groupId)||s[0];dc(f,t,"audioCodec"),dc(f,t,"textCodec")}i.push(f)}}return r}static parseLevelPlaylist(t,e,s,i,r,n){var a;const o={url:e},l=new LevelDetails(e),d=l.fragments,c=[];let h,u,f,g,p=null,m=0,v=0,y=0,E=0,T=0,S=null,A=new Fragment(i,o),_=-1,b=!1,L=null;if(ec.lastIndex=0,l.m3u8=t,l.hasVariableRefs=Ad(t),"#EXTM3U"!==(null==(a=ec.exec(t))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(h=ec.exec(t));){b&&(b=!1,A=new Fragment(i,o),A.playlistOffset=y,A.setStart(y),A.sn=m,A.cc=E,T&&(A.bitrate=T),A.level=s,p&&(A.initSegment=p,p.rawProgramDateTime&&(A.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),L&&(A.setByteRange(L),L=null)));const t=h[1];if(t){A.duration=parseFloat(t);const e=(" "+h[2]).slice(1);A.title=e||null,A.tagList.push(e?["INF",t,e]:["INF",t])}else if(h[3]){if(Vn(A.duration)){var R;A.playlistOffset=y,A.setStart(y),f&&uc(A,f,l),A.sn=m,A.level=s,A.cc=E;const t=(" "+h[3]).slice(1);A.relurl=_d(l,t),cc(A,S,c),S=A,y+=A.duration,m++,v=0;const e=A.byteRange;if(2===e.length&&(A.bitrate=8*(e[1]-e[0])/A.duration|0),l.iframesOnly&&e[0]&&(null==(R=p)?void 0:R.cc)!==E){const t=new Fragment(i,o);t.relurl=A.relurl,t.setByteRange(`${Math.min(e[0],1316)}@0`),t.level=s,t.sn="initSegment",f&&(t.levelkeys=f,f.identity&&(t._decryptdata=f.identity.getDecryptData(0))),p=t,A.initSegment=p}d.push(A),b=!0}}else{if(h=h[0].match(sc),!h){Ua.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u<h.length&&void 0===h[u];u++);const t=(" "+h[u]).slice(1),r=(" "+h[u+1]).slice(1),a=h[u+2]?(" "+h[u+2]).slice(1):null;switch(t){case"BYTERANGE":S?A.setByteRange(r,S):A.setByteRange(r);break;case"PROGRAM-DATE-TIME":A.rawProgramDateTime=r,A.tagList.push(["PROGRAM-DATE-TIME",r]),-1===_&&(_=d.length);break;case"PLAYLIST-TYPE":l.type&&fc(l,t,h),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?fc(l,t,h):null!==S&&gc(l,t,h),l.startSN=parseInt(r),m=l.startSN+l.skippedSegments;break;case"SKIP":{l.skippedSegments&&fc(l,t,h);const e=new AttrList(r,l),s=e.decimalInteger("SKIPPED-SEGMENTS");if(Vn(s)){l.skippedSegments+=s;for(let t=s;t--;)d.push(null);m+=s}const i=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(i.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&fc(l,t,h),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&fc(l,t,h),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":l.iframesOnly=!0;break;case"ENDLIST":l.live||fc(l,t,h),l.live=!1;break;case"#":(r||a)&&A.tagList.push(a?[r,a]:[r]);break;case"DISCONTINUITY":E++,A.tagList.push(["DIS"]);break;case"GAP":A.gap=!0,A.tagList.push([t]);break;case"BITRATE":A.tagList.push([t,r]),T=1e3*parseInt(r),Vn(T)?A.bitrate=T:T=0;break;case"DATERANGE":{const t=new AttrList(r,l),e=new DateRange(t,l.dateRanges[t.ID],l.dateRangeTagCount);l.dateRangeTagCount++,e.isValid||l.skippedSegments?l.dateRanges[e.id]=e:Ua.log(`Ignoring invalid DATERANGE tag: ${e.invalidReason}: ${r}`),A.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const t=new AttrList(r,l);"IMPORT"in t?Ld(l,t,n):bd(l,t,e)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC&&fc(l,t,h),l.startCC=E=parseInt(r),d.forEach(t=>t&&(t.cc=E));break;case"KEY":{const t=ac(r,e,l);if(t.isSupported()){if("NONE"===t.method){f=void 0;break}f||(f={});const e=f[t.keyFormat];null!=e&&e.matches(t)||(e&&(f=Ta({},f)),f[t.keyFormat]=t)}else Ua.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":l.startTimeOffset=oc(r);break;case"MAP":{const t=new AttrList(r,l);if(A.duration){const e=new Fragment(i,o);hc(e,t,s,f),p=e,A.initSegment=p,p.rawProgramDateTime&&!A.rawProgramDateTime&&(A.rawProgramDateTime=p.rawProgramDateTime)}else{const e=A.byteRangeEndOffset;if(e){const t=A.byteRangeStartOffset;L=`${e-t}@${t}`}else L=null;hc(A,t,s,f),p=A,b=!0}p.cc=E;break}case"SERVER-CONTROL":g&&fc(l,t,h),g=new AttrList(r),l.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),l.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&fc(l,t,h);const e=new AttrList(r);l.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=l.partList;t||(t=l.partList=[]);const e=v>0?t[t.length-1]:void 0,s=v++,i=new AttrList(r,l),n=new Part(i,A,o,s,e);t.push(n),A.duration+=n.duration;break}case"PRELOAD-HINT":{const t=new AttrList(r,l);l.preloadHint=t;break}case"RENDITION-REPORT":{const t=new AttrList(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(t);break}default:Ua.warn(`line parsed but not handled: ${h}`)}}}S&&!S.relurl?(d.pop(),y-=S.duration,l.partList&&(l.fragmentHint=S)):l.partList&&(cc(A,S,c),A.cc=E,l.fragmentHint=A,f&&uc(A,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const I=d.length,k=d[0],w=d[I-1];if(y+=l.skippedSegments*l.targetduration,y>0&&I&&w){l.averagetargetduration=y/I;const t=w.sn;l.endSN="initSegment"!==t?t:0,l.live||(w.endList=!0),_>0&&(!function(t,e,s){if(s||(s=t[e]),!s)return;for(let i=e;i--;){const e=t[i];if(!e)return;e.programDateTime=s.programDateTime-1e3*e.duration,s=e}}(d,_,_>I-1?A:null),k&&c.unshift(k))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,c.length&&l.dateRangeTagCount&&k&&rc(c,l),l.endCC=E,l}}function ic(t,e,s,i,r,n){var a;if(void 0===e)return null;const o=_d(i,e),l={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:M3U8Parser.resolve(o,s)},d=t.decimalResolution("RESOLUTION");d&&(l.width=d.width,l.height=d.height),lc(t.CODECS,l);const c=t["SUPPLEMENTAL-CODECS"];return c&&(l.supplemental={},lc(c,l.supplemental)),null!=(a=l.unknownCodecs)&&a.length||r.push(l),n&&(l.iframes=!0),l}function rc(t,e){let s=t.length;if(!s){if(!e.hasProgramDateTime)return;{const i=e.fragments[e.fragments.length-1];t.push(i),s++}}const i=t[s-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=i.ref;for(let i=s;i--;){var a;if((null==(a=t[i])?void 0:a.sn)<e.startSN)break;const s=nc(e,d,t,i,r);if(s){l.tagAnchor=s.ref;break}}}}function nc(t,e,s,i,r){const n=s[i];if(n){const o=n.programDateTime;if(e>=o||0===i){var a;if(e<=o+1e3*(((null==(a=s[i+1])?void 0:a.start)||r)-n.start)){const r=n.sn-t.startSN,a=t.fragments;if(r>=0&&r<a.length){if(a.length>s.length){const n=s[i+1]||a[a.length-1];for(let s=Math.min(n.sn-t.startSN,a.length-1);s>r;s--){const t=a[s].programDateTime;if(e>=t&&e<t+1e3*a[s].duration)return a[s]}}return a[r]}}}}return null}function ac(t,e,s){var i,r;const n=new AttrList(t,s),a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,c=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&Ua.error(`Invalid IV: ${n.IV}`);const h=o?M3U8Parser.resolve(o,e):"",u=(d||"1").split("/").map(Number).filter(Number.isFinite);return new LevelKey(a,h,c,u,l,n.KEYID)}function oc(t){const e=new AttrList(t).decimalFloatingPoint("TIME-OFFSET");return Vn(e)?e:null}function lc(t,e){let s=(t||"").split(/[ ,]+/).filter(t=>t);["video","audio","text","image"].forEach(t=>{const i=s.filter(e=>el(e,t));i.length&&(e[`${t}Codec`]=i.map(t=>t.split("/")[0]).join(","),s=s.filter(t=>-1===i.indexOf(t)))}),e.unknownCodecs=s}function dc(t,e,s){const i=e[s];i&&(t[s]=i)}function cc(t,e,s){t.rawProgramDateTime?s.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function hc(t,e,s,i){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=s,t.sn="initSegment",i&&(t.levelkeys=i),t.initSegment=null}function uc(t,e,s){t.levelkeys=e;const{encryptedFragments:i}=s;i.length&&i[i.length-1].levelkeys===e||!Object.keys(e).some(t=>e[t].isCommonEncryption)||i.push(t)}function fc(t,e,s){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${s[0]})`)}function gc(t,e,s){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${s[0]})`)}function pc(t,e){const s=e.startPTS;if(Vn(s)){let i,r=0;e.sn>t.sn?(r=s-t.start,i=t):(r=t.start-s,i=e),i.duration!==r&&i.setDuration(r)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration)}else e.setStart(Math.max(t.start-e.duration,0))}function mc(t,e,s,i,r,n,a,o){i-s<=0&&(o.warn("Fragment should have a positive duration",e),i=s+e.duration,n=r+e.duration);let l=s,d=i;const c=e.startPTS,h=e.endPTS;if(Vn(c)){const a=Math.abs(c-s);t&&a>t.totalduration?o.warn(`media timestamps and playlist times differ by ${a}s for level ${e.level} ${t.url}`):Vn(e.deltaPTS)?e.deltaPTS=Math.max(a,e.deltaPTS):e.deltaPTS=a,l=Math.max(s,c),s=Math.min(s,c),r=void 0!==e.startDTS?Math.min(r,e.startDTS):r,d=Math.min(i,h),i=Math.max(i,h),n=void 0!==e.endDTS?Math.max(n,e.endDTS):n}const u=s-e.start;0!==e.start&&e.setStart(s),e.setDuration(i-e.start),e.startPTS=s,e.maxStartPTS=l,e.startDTS=r,e.endPTS=i,e.minEndPTS=d,e.endDTS=n;const f=e.sn;if(!t||f<t.startSN||f>t.endSN)return 0;let g;const p=f-t.startSN,m=t.fragments;for(m[p]=e,g=p;g>0;g--)pc(m[g],m[g-1]);for(g=p;g<m.length-1;g++)pc(m[g],m[g+1]);return t.fragmentHint&&pc(m[m.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,u}function vc(t,e,s){if(t===e)return;let i=null;const r=t.fragments;for(let t=r.length-1;t>=0;t--){const e=r[t].initSegment;if(e){i=e;break}}let n;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,s){var i;const r=e.skippedSegments,n=Math.max(t.startSN,e.startSN)-e.startSN,a=(t.fragmentHint?1:0)+(r?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,o=e.startSN-t.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,d=null!=(i=t.fragmentHint)&&i.duration?t.fragments.concat(t.fragmentHint):t.fragments;for(let i=n;i<=a;i++){const n=d[o+i];let a=l[i];if(r&&!a&&n&&(a=e.fragments[i]=n),n&&a){s(n,a,i,l);const r=n.relurl,o=a.relurl;if(r&&Lc(r,o))return void(e.playlistParsingError=yc(`media sequence mismatch ${a.sn}:`,t,e,n,a));if(n.cc!==a.cc)return void(e.playlistParsingError=yc(`discontinuity sequence mismatch (${n.cc}!=${a.cc})`,t,e,n,a))}}}(t,e,(t,s,r,a)=>{if((!e.startCC||e.skippedSegments)&&s.cc!==t.cc){const i=t.cc-s.cc;for(let t=r;t<a.length;t++)a[t].cc+=i;e.endCC=a[a.length-1].cc}Vn(t.startPTS)&&Vn(t.endPTS)&&(s.setStart(s.startPTS=t.startPTS),s.startDTS=t.startDTS,s.maxStartPTS=t.maxStartPTS,s.endPTS=t.endPTS,s.endDTS=t.endDTS,s.minEndPTS=t.minEndPTS,s.setDuration(t.endPTS-t.startPTS),s.duration&&(n=s),e.PTSKnown=e.alignedSliding=!0),t.hasStreams&&(s.elementaryStreams=t.elementaryStreams),s.loader=t.loader,t.hasStats&&(s.stats=t.stats),t.initSegment&&(s.initSegment=t.initSegment,i=t.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(i&&o.forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=i)?void 0:e.relurl)||(t.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(t=>!t),e.deltaUpdateFailed){s.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=function(t,e,s){const{dateRanges:i,recentlyRemovedDateranges:r}=e,n=Ta({},t);r&&r.forEach(t=>{delete n[t]});const a=Object.keys(n).length;if(!a)return i;return Object.keys(i).forEach(t=>{const e=n[t],r=new DateRange(i[t].attr,e);r.isValid?(n[t]=r,e||(r.tagOrder+=a)):s.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Dl(i[t].attr)}"`)}),n}(t.dateRanges,e,s));const i=t.fragments.filter(t=>t.rawProgramDateTime);if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let t=1;t<o.length;t++)null===o[t].programDateTime&&cc(o[t],o[t-1],i);rc(i,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const s=Sc(t,e.startSN-1);e.startCC=null!=(l=null==s?void 0:s.cc)?l:a[0].cc}if(function(t,e,s){if(t&&e){let i=0;for(let r=0,n=t.length;r<n;r++){const n=t[r],a=e[r+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):i--}}}(t.partList,e.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats,e.gap=t.gap||e.gap}),n){e.iframesOnly&&n.type;mc(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,0,s)}else Ec(t,e);a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const d=e.advancedDateTime;if(e.advanced&&d){const t=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=t),e.driftEndTime=d,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;-1===e.requestScheduled&&(e.requestScheduled=t.requestScheduled)}function yc(t,e,s,i,r){return new Error(`${t} ${r.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${s.startSN}\n${s.m3u8}`)}function Ec(t,e,s=!0,i){const r=e.startSN+e.skippedSegments-t.startSN,n=t.fragments,a=r>=0;let o=0;if(a&&r<n.length)o=n[r].start,null==i||i.log(`Aligning playlists based on SN ${e.startSN} (diff: ${o})`);else if(a&&e.startSN===t.endSN+1)o=t.fragmentEnd,null==i||i.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${o})`);else if(a&&s)o=t.fragmentStart+r*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return o;o=t.fragmentStart,null==i||i.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${o})`)}return function(t,e){if(e){const s=t.fragments;for(let i=t.skippedSegments;i<s.length;i++)s[i].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}(e,o),o}function Tc(t,e=1/0){let s=1e3*t.targetduration;if(t.updated){const i=t.fragments,r=4;if(i.length&&s*r>e){const t=1e3*i[i.length-1].duration;t<s&&(s=t)}}else s/=2;return Math.round(s)}function Sc(t,e,s){var i;if(!t)return null;let r=t.fragments[e-t.startSN];return r||(r=t.fragmentHint,(null==(i=r)?void 0:i.sn)===e?r:s&&e<t.startSN&&s.sn===e?s:null)}function Ac(t,e,s){return t?_c(t.partList,e,s):null}function _c(t,e,s){if(t)for(let i=t.length;i--;){const r=t[i];if(r.index===s&&r.fragment.sn===e)return r}return null}function bc(t){t.forEach((t,e)=>{var s;null==(s=t.details)||s.fragments.forEach(t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)})})}function Lc(t,e){return!(t===e||!e)&&Rc(t)!==Rc(e)}function Rc(t){return t.replace(/\?[^?]*$/,"")}function Ic(t,e){for(let i=0,r=t.length;i<r;i++){var s;if((null==(s=t[i])?void 0:s.cc)===e)return t[i]}return null}function kc(t,e){const s=t.start+e;t.setStart(s)}function wc(t,e){const s=e.fragments;for(let e=0,i=s.length;e<i;e++)kc(s[e],t);e.fragmentHint&&kc(e.fragmentHint,t),e.alignedSliding=!0}function Pc(t,e,s){t&&(!function(t,e,s){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const i=Math.min(e.endCC,t.endCC),r=Ic(e.fragments,i),n=Ic(t.fragments,i);if(!r||!n)return;const a=r.start-n.start;s.log(`Aligning playlists using dicontinuity sequence ${i} (diff: ${a})`),wc(a,t)}(e,t,s),e.alignedSliding||function(t,e,s){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const i=t.fragments,r=e.fragments;if(!i.length||!r.length)return;let n,a;const o=Math.min(e.endCC,t.endCC);e.startCC<o&&t.startCC<o&&(n=Ic(r,o),a=Ic(i,o));n&&a||(n=r[Math.floor(r.length/2)]||r.filter(t=>!!t)[0],a=Ic(i,n.cc)||i[Math.floor(i.length/2)]);const l=n.programDateTime,d=a.programDateTime;if(!l||!d)return;const c=(d-l)/1e3;if(Math.abs(c)>Math.max(60,t.totalduration))return void s.log(`Cannot align playlists using PDT without overlap (${Math.abs(c)} > ${t.totalduration})`);const h=c-(a.start-n.start);s.log(`Aligning playlists using PDT (diff: ${h})`),wc(h,t)}(e,t,s),e.alignedSliding||e.skippedSegments||Ec(t,e,!1,s))}function Dc(t,e,s){Cc(t,e,s),t.addEventListener(e,s)}function Cc(t,e,s){t.removeEventListener(e,s)}function Oc(t){let e="";const s=t.length;for(let i=0;i<s;i++)e+=`[${t.start(i).toFixed(3)}-${t.end(i).toFixed(3)}]`;return e}const Mc="STOPPED",xc="IDLE",Fc="KEY_LOADING",Nc="FRAG_LOADING",Uc="FRAG_LOADING_WAITING_RETRY",Bc="WAITING_TRACK",$c="PARSING",Gc="PARSED",Hc="ENDED",Kc="ERROR",Vc="WAITING_INIT_PTS",jc="WAITING_LEVEL";class BaseStreamController extends TaskLoop{constructor(t,e,s,i,r){super(i,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Mc,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=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:t,fragCurrent:e,media:s,mediaBuffer:i,state:r}=this,n=s?s.currentTime:0,a=BufferHelper.bufferInfo(i||s,n,t.maxBufferHole),o=a.len;if(this.log(`Media seeking to ${n}, state: ${r}, ${o?"in":"out of"} buffer`),this.state===Hc)this.resetLoadingState();else if(e){const s=t.maxFragLookUpTolerance,i=e.start-s,r=e.start+e.duration+s;if(!o||r<a.start||i>a.end){const t=n<i,s=n>r;(t||s)&&(!e.loader||!s&&this.isFragmentNearlyDownloaded(e)?this.fragPrevious=null:(this.log(`Cancelling fragment load for seek (sn: ${e.sn}) - ${t?"backward":"forward"} seek`),e.abortRequests(),this.resetLoadingState()))}}if(s){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const t=Math.max(a.end,n),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${n} with buffer @${t}`),this.loadingParts=e)}}const l=!BufferHelper.isBuffered(s,n);this.hls.hasEnoughToStart&&!l||(this.log(`Setting ${l?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,l&&(this.startPosition=n)),o<1&&this.state===xc&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=t,this.fragmentLoader=new FragmentLoader(t.config),this.initFragmentLoader=new FragmentLoader(t.config),this.keyLoader=s,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Decrypter(t.config)}registerListeners(){const{hls:t}=this;t.on(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(zn.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(zn.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===Mc)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);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=Mc}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;if(-1===e&&t){const e=this.getLevelDetails();if(null!=e&&e.live){return(this.hls.liveSyncPosition||e.fragmentStart)+this.timelineOffset}return t}return e}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(t){}get couldBacktrack(){return!1}set couldBacktrack(t){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const s=t.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=t.buffered;this.config.maxBufferHole&&r&&r.length>1&&(t=BufferHelper.bufferedInfo(r,t.start,0));const n=t.nextStart;if(n&&n>i&&n<e.edge)return!1;if(this.media.currentTime<t.start)return!1;const a=e.partList;if(null!=a&&a.length){const t=a[a.length-1];return BufferHelper.isBuffered(this.media,t.start+t.duration/2)}const o=e.fragments[e.fragments.length-1];return this.fragmentTracker.isEndListAppended(o.type)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;var e;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}onMediaAttached(t,e){const s=this.media=this.mediaBuffer=e.media;Dc(s,"seeking",this.onMediaSeeking),Dc(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===Mc&&this.startLoad(i.startPosition)}onMediaDetaching(t,e){this.fragPlaying=null;const s=!!e.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Cc(i,"seeking",this.onMediaSeeking),Cc(i,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,s)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}onError(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Mc,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,s){this.startFragRequested=!0,this._loadFragForPlayback(t,e,s)}_loadFragForPlayback(t,e,s){this._doFragLoad(t,e,s,t=>{const e=t.frag;if(this.fragContextChanged(e))return this.warn(`${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)} was dropped during download.`),void this.fragmentTracker.removeFragment(e);const s=++e.stats.chunkCount;this.log(`load progress ${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)} chunk: ${s}`),this._handleFragmentLoadProgress(t)}).then(t=>{if(!t)return;const e=this.state,s=t.frag;this.fragContextChanged(s)?(e===Nc||!this.fragCurrent&&e===$c)&&(this.fragmentTracker.removeFragment(s),this.state=xc):("payload"in t&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level} (bytes ${s.stats.loaded})`),this.hls.trigger(zn.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))}).catch(e=>{this.state!==Mc&&this.state!==Kc&&(this.log(`Frag error ${t.type} sn:${t.sn} cc:${t.cc}: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:s}=this;if(s.getState(t)===ld){const e=t.type,i=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(r,t.duration))&&s.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?s.removeAllFragments():s.hasParts(t.type)&&(s.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),s.getState(t)===dd&&s.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=this.fragmentTracker,s=t.fragments[t.fragments.length-1];if(s.endList&&!e.isEndListAppended(this.playlistType)){const t=e.getPartialFragment(s.end);t&&(e.removeFragment(t),e.fragBuffered(s,!0))}e.detectPartialFragments({frag:s,part:null,stats:s.stats,id:s.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e,s=null){if(!(t-e))return;const i={startOffset:t,endOffset:e,type:s};this.hls.trigger(zn.BUFFER_FLUSHING,i)}_loadInitSegment(t){const{hls:e}=this;return this.initFragmentLoader.abort(),e.trigger(zn.FRAG_LOADING,{frag:t,targetBufferTime:0}),this.initFragmentLoader.load(t).then(t=>{var e;const s=t.frag;if(!this.levels||!va(s,null==(e=this.fragCurrent)?void 0:e.initSegment))throw new LoadError({type:Wn.NETWORK_ERROR,details:Yn.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:s,networkDetails:null});return t}).then(t=>{const{frag:s,payload:i}=t,r=s.decryptdata;if(i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&Cd(r.method)){const n=self.performance.now(),{decryptRange:a}=yd(s,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,Od(r.method),a).catch(t=>{throw e.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:s}),this.fragmentLoader.abort(),t}).then(i=>{const r=self.performance.now();return e.trigger(zn.FRAG_DECRYPTED,{frag:s,part:null,payload:i,stats:{tstart:n,tdecrypt:r}}),t.payload=i,this.completeInitSegmentLoad(t)})}return this.completeInitSegmentLoad(t)})}completeInitSegmentLoad(t){const e=t.frag.stats;t.frag.data=new Uint8Array(t.payload),e.parsing.start=e.buffering.start=self.performance.now(),e.parsing.end=e.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(t){const{initSegment:e}=t;if(!this.bitrateTest&&pa(t)&&e&&!e.data){var s;return(!e.encrypted||null!=(s=e.decryptdata)&&s.key?this._loadInitSegment(e):this.keyLoader.load(e).then(()=>this._loadInitSegment(e))).catch(e=>{if(this.state===Mc||this.state===Kc)throw e;throw"data"in e&&(e.data.frag=t,this.fragmentLoader.abort(),this.handleFragLoadError(e)),this.resetFragmentLoading(t),e})}}unhandledEncryptionError(t,e){var s,i;const r=t.tracks;if(r&&!e.encrypted&&(null!=(s=r.audio)&&s.encrypted||null!=(i=r.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const t=this.media,s=new Error(`Encrypted track with no key in ${this.fragInfo(e)} (media ${t?"attached mediaKeys: "+t.mediaKeys:"detached"})`);return this.warn(s.message),!t||t.mediaKeys?!1:(this.hls.trigger(zn.ERROR,{type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!va(t,e)}fragBufferedComplete(t,e){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${s?Oc(BufferHelper.getBuffered(s)):"(detached)"})`),pa(t)){var i;if(t.type!==ha){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return void(this.state=xc)}const s=null==(i=this.levels)?void 0:i[t.level];null!=s&&s.fragmentError&&(e||this.fragmentTracker.getState(t)!==dd)&&(this.log(`Resetting level fragment error count of ${s.fragmentError} on frag buffered`),s.fragmentError=0,t.stats.retry=0)}this.state=xc}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const s=t.frag,{part:i,partsLoaded:r}=t,n=!r||0===r.length||r.some(t=>!t),{decryptRange:a}=yd(s,i),o=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n,s.duration,this.iframesOnly,a);this.log(`load complete ${s.type} sn: ${s.sn}${i?" part: "+i.index:""} of ${this.fragInfo(s,!1,i)}`),e.flush(o)}_handleFragmentLoadProgress(t){}loadKeyFor(t,e,s){var i;let r=null;return!t.encrypted||null!=(i=t.decryptdata)&&i.key?t.encrypted||(r=this.keyLoader.loadClear(t,e.encryptedFragments,this.startFragRequested),r&&this.log(`[eme] blocking frag sn: ${t.sn} load until media-keys acquired`)):(this.log(`Loading key for ${t.sn} of [${e.startSN}-${e.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=Fc,r=this.keyLoader.load(t,s).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(zn.KEY_LOADED,t),this.state===Fc&&(this.state=xc),t}),this.hls.trigger(zn.KEY_LOADING,{frag:t})),r}_doFragLoad(t,e,s=null,i){this.fragCurrent=t;const r=e.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" detail"}s`);const n=this.fragPrevious;if(!ma(t,n)){const s=this.shouldLoadParts(e.details,t.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?"ON":"OFF"} loading sn ${null==n?void 0:n.sn}->${t.sn}`),this.loadingParts=s)}if(s=Math.max(t.start,s||0),this.loadingParts){const a=r.partList;if(a&&i){s>r.fragmentEnd&&r.fragmentHint&&(t=r.fragmentHint);const o=this.getNextPart(a,t,s);if(o>-1){const l=a[o];if(!ma(t=this.fragCurrent=l.fragment,n)&&!this.shouldLoadParts(e.details,t.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(t,!1,l)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(l,e.details))return Promise.resolve(null);const d=this.loadKeyFor(t,r);if(this.fragContextChanged(t))return Promise.resolve(null);let c;this.log(`Loading ${t.type} sn: ${t.sn} part: ${l.index} (${o}/${a.length-1}) of ${this.fragInfo(t,!1,l)} cc: ${t.cc} [${r.startSN}-${r.endSN}], target: ${s}${l.byteRange.length?` range:${l.byteRange.join("-")}`:""}`),this.nextLoadPosition=l.start+l.duration,this.state=Nc;const h=this.loadInitSegmentIfNeeded(t);if(d||h){const s=!!d;c=Promise.all([d,h]).then(([r])=>!s||r&&!this.fragContextChanged(r.frag)?this.doFragPartsLoad(t,l,e,i):null).catch(t=>this.handleFragLoadError(t))}else c=this.doFragPartsLoad(t,l,e,i).catch(t=>this.handleFragLoadError(t));return this.hls.trigger(zn.FRAG_LOADING,{frag:t,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):c}if(!t.url||this.loadedEndOfParts(a,s))return Promise.resolve(null)}}var a;if(this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s} Check buffer at sn: ${t.sn} loaded parts: ${null==(a=r.partList)?void 0:a.filter(t=>t.loaded).map(t=>`[${t.start}-${t.end}]`)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(t,e.details))return Promise.resolve(null);const o=this.loadInitSegmentIfNeeded(t),l=this.loadKeyFor(t,r,o);var d;if(this.fragContextChanged(t))return this.log(`Context changed in KEY_LOADING sn: ${t.sn} ${t.relurl} > ${null==(d=this.fragCurrent)?void 0:d.relurl}`),null==o||o.catch(()=>null),null==l||l.catch(()=>null),Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)} cc: ${t.cc} ${"["+r.startSN+"-"+r.endSN+"]"}, target: ${s}${t.byteRange.length?` range:${t.byteRange.join("-")}`:""}`),Vn(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Nc;const c=this.config.progressive&&t.type!==ha;let h;return h=c&&l?l.then(e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,this.iframesOnly,i,o)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,this.iframesOnly,c?i:void 0,c?o:void 0),l,o]).then(([t])=>(!c&&i&&i(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(zn.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([h,o]).then(([t])=>t)}doFragPartsLoad(t,e,s,i){return new Promise((r,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,d=e=>{this.fragmentLoader.loadPart(t,e,i).then(i=>{o[e.index]=i;const n=i.part;this.hls.trigger(zn.FRAG_LOADED,i);const a=Ac(s.details,t.sn,e.index+1)||_c(l,t.sn,e.index+1);if(!a)return r({frag:t,part:n,partsLoaded:o});d(a)}).catch(n)};d(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;e.frag&&e.details===Yn.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):e.frag&&e.type===Wn.KEY_SYSTEM_ERROR&&!e.fatal&&(e.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e.frag)),this.hls.trigger(zn.ERROR,e)}else this.hls.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==$c)return void(this.fragCurrent||this.state===Mc||this.state===Kc||(this.state=xc));const{frag:s,part:i,level:r}=e,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&s.sn>a.endSN||this.shouldLoadParts(a,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end}`),this.loadingParts=o),this.updateLevelTiming(s,i,r,t)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList&&!this.iframesOnly){var s;const i=t.partList[0];if(e>=i.end+((null==(s=t.fragmentHint)?void 0:s.duration)||0)){if(this.playhead>i.start-i.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:s}=this,{level:i,sn:r,part:n}=t;if(null==e||!e[i])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=e[i],o=a.details,l=n>-1?Ac(o,r,n):null,d=l?l.fragment:Sc(o,r,s);return d?(s&&s!==d&&(d.stats=s.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(t,e,s,i,r){if(this.state!==$c)return;pa(e)&&!this.fragContextChanged(e)&&(this.fragPrevious=e);const{data1:n,data2:a}=t;let o=n;if(a&&(o=Uo(n,a)),!o.length)return;const l=this.initPTS[e.cc],d=l?-l.baseTime/l.timescale:void 0,c={type:t.type,frag:e,part:s,chunkMeta:i,offset:d,parent:e.type,data:o};if(this.hls.trigger(zn.BUFFER_APPENDING,c),t.dropped&&t.independent&&!s){if(r)return;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,i=BufferHelper.bufferInfo(e,s,0),r=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(t.start-n,i.end-n),s+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var s;const i=this.playhead,r=this.lastCurrentTime>i||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,i,e,r)}getFwdBufferInfoAtPos(t,e,s,i){const r=BufferHelper.bufferInfo(t,e,i);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,s);if(n&&(r.nextStart<=n.end||n.gap)){const s=Math.max(Math.min(r.nextStart,n.end)-e,i);return BufferHelper.bufferInfo(t,e,s)}}return r}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)}exceedsMaxBuffer(t,e,s){const i=t.nextStart;if(i&&s.start>i){const i=t.buffered;if(i){let r=t.len;const n=t.bufferedIndex;for(let t=i.length-1;t>n;t--)i[t].start<s.start&&(r+=i[t].end-i[t].start);return r>=e}}return!1}reduceMaxBufferLength(t,e){const s=this.config,i=Math.max(Math.min(t-e,s.maxBufferLength),e/2),r=Math.max(t-3*e,s.maxMaxBufferLength/2,i);return r>=i&&(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(t){const e=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,this.playlistType):null;return e&&"fragment"in e?e.fragment:e}getNextFragment(t,e){const s=e.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=e.fragmentStart,a=r.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const s=r.initialLiveManifestSize;if(i<s)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${s})`),null;if(this.startFragRequested||!a||this.loadingParts||(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n){var l;o=this.getInitialLiveFragment(e);const s=this.config.startPosition,i=this.hls.startPosition,r=this.hls.liveSyncPosition,a=(null==(l=o)?void 0:l.start)||0;let d,c;if(-1!==i&&i>=n?(d=i,c=i===s?"config":"next load start"):r?(d=r,c="live edge"):(d=t,c="buffer pos"),d<a&&(d=a,c="live frag start"),d<n&&(d=n,c="playlist start"),this.startPosition!=d||this.nextLoadPosition!=d){const l=e.live&&!this.filterReplacedPrimary(o,e)?-1:d;this.log(`Setting startPosition to ${l} next load ${d} ${-1===i?"":`(from ${s}) `}based on ${c}. live edge: ${r} live frag start: ${a} playlist start: ${n} buffer pos: ${t}`),this.startPosition=l,this.nextLoadPosition=d}}}else t<=n&&(o=s[0]);if(!o){const s=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,s,e)}let d=this.filterReplacedPrimary(o,e);return!d&&o&&(d=Wl(e,o.sn),d&&(this.nextLoadPosition=d.start)),d}isLoopLoading(t,e){if(this.nextLoadPosition<=e)return!1;const s=this.fragmentTracker.getState(t);if(s===cd)return!0;if(s===dd){if(t.gap)return!0;if(t.stats.retry>1)return!0}return!1}getNextFragmentLoopLoading(t,e,s,i,r){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&s.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(null!==t&&s.len+t.len>=r){const t=n.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(Wc(this.config)){var t;if(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,e){if(!t)return t;if(Wc(this.config)&&("type"in t?t:t.fragment).type!==ha){const s=this.hls.interstitialsManager,i=null==s?void 0:s.bufferingItem;if(i){const s=i.event;if(s){if(!s.appendInPlace&&(Math.abs(t.start-i.start)>1||0===i.start))return null}else{if(t.end<=i.start&&!1===(null==e?void 0:e.live))return null;if(t.start>=i.end&&i.nextEvent&&(i.nextEvent.appendInPlace&&!i.nextEvent.hasPlayed||t.start-i.end>1))return null}}if(qc(t,null==s?void 0:s.playerQueue,this.playhead))return null}return t}getNextPart(t,e,s){let i=-1,r=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,i>-1&&s<o.start)break;const l=o.loaded||o.gap;l?i=-1:(r||(o.independent||n)&&o.fragment===e)&&(i=a),r=l&&!o.gap}const a=t[i];return a&&a.fragment!==e&&this.log(`Need buffer at ${s} but next unloaded part starts at ${a.start} (sn: ${e.sn} -> ${a.fragment.sn})`),i}loadedEndOfParts(t,e){let s;for(let i=t.length;i--;){if(s=t[i],!s.loaded)return!1;if(e>s.start)return!0}return!1}getInitialLiveFragment(t){const e=t.fragments,s=this.fragPrevious;let i=null;if(s){if(t.hasProgramDateTime&&(i=function(t,e,s){if(null===e||!Array.isArray(t)||!t.length||!Vn(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;for(let i=0;i<t.length;++i){const r=t[i];if(jl(e,s,r))return r}return null}(e,s.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!i){const r=s.sn+1;if(r>=t.startSN&&r<=t.endSN){const n=e[r-t.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=ql(t,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(i=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i}getFragmentAtPosition(t,e,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=i,d=s.partList,c=!!(this.loadingParts&&null!=d&&d.length&&o);let h;if(c&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),r&&this.fragmentTracker.getState(r)===od&&(r=null),t<e){var u;h=Kl(r,n,t,t<this.lastCurrentTime||t>e-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l)}else h=n[n.length-1];if(h){const t=h.sn-s.startSN,e=this.fragmentTracker.getState(h);if((e===cd||e===dd&&h.gap)&&(r=h),ma(h,r)&&(!c||d[0].fragment.sn>h.sn||!s.live)){const e=n[t+1];h=h.sn<a&&this.fragmentTracker.getState(e)!==cd?e:null}}return h}alignPlaylists(t,e,s){const i=t.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=t.fragmentStart,n=!e,a=t.alignedSliding&&Vn(r);if(n||!a&&!r){Pc(s,t,this);const r=t.fragmentStart;return this.log(`Live playlist sliding: ${r} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${i}`),r}return r}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;s<e&&(s=-1);const i=this.timelineOffset;if(-1===s){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:t.startTimeOffset;if(null!==n&&Vn(n))s=e+n,n<0&&(s+=t.edge),s=Math.min(Math.max(e,s),e+t.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s;else if(t.live){const t=this.hls.liveSyncPosition;s=t||e,this.log(`Setting startPosition to -1 to start at ${t?"live edge":"playlist start"} ${s}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=s=0;this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var t;const{media:e}=this;let s=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e&&!this.iframesOnly?s=e.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}get playhead(){var t;if(null!=(t=this.hls)&&t.hasEnoughToStart){var e;const t=null==(e=this.media)?void 0:e.currentTime;return Vn(t)?t:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var t;if(this.playlistType!==da)return!1;const e=this.getLevelDetails();return e?e.iframesOnly:null==(t=this.levelLastLoaded)?void 0:t.iframes}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&pa(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===Uc)||(this.state=xc)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const{frag:s,part:i}=e;if(!s||!this.levels||s.type!==t)return;var r;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.relurl} > ${null==(r=this.fragCurrent)?void 0:r.relurl}`);const n=e.details===Yn.FRAG_GAP;n&&this.fragmentTracker.addAsGap(s);const a=e.errorAction;if(!a)return void(this.state=Kc);const{action:o,flags:l,retryCount:d=0,retryConfig:c}=a,h=!!c,u=h&&o===Xl,f=h&&!a.resolved&&l&Jl,g=this.hls.latestLevelDetails,p=null==g?void 0:g.live;if(!u&&f&&pa(s)&&p&&s.sn<g.endSN&&!Ra(e))this.resetFragmentErrors(t),i?i.gap=!0:this.treatAsGap(s),a.resolved=!0;else if((u||f)&&d<c.maxNumRetry){var m;const i=Da(null==(m=e.response)?void 0:m.code),r=ka(c,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=Uc,a.resolved=!0,i)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(e.reason="offline");this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${d+1}/${c.maxNumRetry} in ${r}ms`)}else if(c){if(this.resetFragmentErrors(t),!(d<c.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${d})`);n||o===Ql||(a.resolved=!0)}else this.state=o===zl?jc:Kc;this.tickImmediate()}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,s=e===1/0;(!e||t>=e||s&&!Da(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=xc)}reduceLengthAndFlushBuffer(t){if(this.state===$c||this.state===Gc){const e=t.frag,s=t.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(null==e?void 0:e.duration)||10);const n=!r;return n?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${s} buffer`):i.nextStart&&e&&i.nextStart>e.start&&this.flushMainBuffer(i.nextStart,Number.POSITIVE_INFINITY,s===ca?s:void 0),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===ca&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Mc&&(this.state=xc)}afterBufferFlushed(t,e){if(!t)return;const s=BufferHelper.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,s,this.playlistType),this.state===Hc&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Mc&&(this.state=xc)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.getLevelDetails();null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${-1===t.level?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,s,i){const r=s.details;if(!r)return void this.warn("level.details undefined");this.log(`update level timing ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`);const n=Object.keys(t.elementaryStreams).reduce((e,n)=>{const a=t.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${n} duration reliably (${o})`),e||!1;const l=i.partial?0:mc(r,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this.iframesOnly,this);return this.hls.trigger(zn.LEVEL_PTS_UPDATED,{details:r,level:s,drift:l,type:n,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e},!1);if(!n){var a,o,l,d;const i=null===(null==(a=this.transmuxer)?void 0:a.error),r=null!=(null==(o=this.transmuxer)?void 0:o.error),n=(null!=(l=null==(d=this.levels)?void 0:d.length)?l:0)>1;if((0===s.fragmentError||i&&(s.fragmentError<2||t.endList)||r&&n)&&this.treatAsGap(t,s),i){const i=new Error(`Found no media in ${this.playlistLabel()} ${t.level} ${e?`part: ${e.index} of `:""}sn: ${t.sn} at playlist time: ${t.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(i.message),this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.FRAG_PARSING_ERROR,fatal:!1,error:i,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Gc,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`),this.hls.trigger(zn.FRAG_PARSED,{frag:t,part:e,chunkMeta:i})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(t,e=!0,s){var i,r;return`${this.playlistLabel()} ${t.level} (${s?"part":"frag"}:[${null!=(i=e&&!s?t.startPTS:(s||t).start)?i:NaN}-${null!=(r=e&&!s?t.endPTS:(s||t).end)?r:NaN}]${s&&"main"===t.type?"INDEPENDENT="+(s.independent?"YES":"NO"):""})`}treatAsGap(t,e){e&&e.fragmentError++,this.fragmentTracker.addAsGap(t)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}isFragmentNearlyDownloaded(t){var e;const s=null==(e=t.loader)?void 0:e.stats;if(!s)return!1;const i=s.loading.first>0,r=(s.total-s.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return i&&r<=.15}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}calculateOptimalSwitchPoint(t,e){let s=0;const{hls:i,media:r,config:n,levels:a,playlistType:o}=this,l=this.getLevelDetails();if(r&&!r.paused&&a){var d;const e=o===ca?Tl(t.audioCodec,128e3):t.maxBitrate,r=1+i.ttfbEstimate/1e3,a=i.bandwidthEstimate*n.abrBandWidthUpFactor;s=r+e*(l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||(null==(d=this.fragCurrent)?void 0:d.duration)||6)/a,t.details||(s+=r)}const c=this.playhead;return{fetchdelay:s,okToFlushForwardBuffer:!(null!=l&&l.live)||e.end-c>1.5*s}}scheduleTrackSwitch(t,e,s){const{media:i,playlistType:r}=this;if(!i||!t)return;const n=s?this.getBufferedFrag(this.playhead+e):null;if(n){const t=this.followingBufferedFrag(n);if(t){var a;this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,s=t.duration,i=Math.max(n.end,e+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));if(((null==(a=this.getLevelDetails())?void 0:a.fragmentStart)||0)>i)return;const o=r===da?null:"audio";this.flushMainBuffer(i,Number.POSITIVE_INFINITY,o),this.cleanupBackBuffer()}}}cleanupBackBuffer(){const{media:t,playlistType:e}=this;if(!t)return;const s=this.getAppendedFrag(this.playhead);if(s&&s.start>1){const t=e===ca;this.flushMainBuffer(0,s.start-(t?0:1),t?"audio":null)}}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,this.playlistType)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case Fc:case Nc:case Uc:case $c:case Gc:this.state=xc}this.nextLoadPosition=this.playhead}checkFragPlaying(){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=void 0,!ma(e,this.fragPlaying)))return this.fragPlaying=e,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){const{levels:t,media:e,hls:s,config:i,playlistType:r}=this;if(null!=e&&e.readyState&&t&&s&&i){const e=this.getBufferOutput(),i=this.getFwdBufferInfo(e,r);if(!i)return;const n=t[r===ca?s.nextAudioTrack:s.nextLoadLevel],{fetchdelay:a,okToFlushForwardBuffer:o}=this.calculateOptimalSwitchPoint(n,i);this.scheduleTrackSwitch(i,a,o)}this.tickImmediate()}}function qc(t,e,s){if(e)for(let i=e.length;i--;){const r=e[i].interstitial,n=r.startTime,a=Math.min(n+r.duration,r.resumeTime);if(r.appendInPlace){if(t.start>=n&&t.end<=a)return!0;if(s>t.start&&t.end>n&&t.start<a)return!0}}return!1}function Wc(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}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 i=0;for(let e=0;e<t.length;e++){const r=t[e];s.set(r,i),i+=r.length}return s}(t,e),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Yc,zc={exports:{}};var Qc=(Yc||(Yc=1,function(t){var e=Object.prototype.hasOwnProperty,s="~";function i(){}function r(t,e,s){this.fn=t,this.context=e,this.once=s||!1}function n(t,e,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new r(i,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 i:delete t._events[e]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function(){var t,i,r=[];if(0===this._eventsCount)return r;for(i in t=this._events)e.call(t,i)&&r.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=s?s+t:t,i=this._events[e];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,a=new Array(n);r<n;r++)a[r]=i[r].fn;return a},o.prototype.listenerCount=function(t){var e=s?s+t:t,i=this._events[e];return i?i.fn?1:i.length:0},o.prototype.emit=function(t,e,i,r,n,a){var o=s?s+t:t;if(!this._events[o])return!1;var l,d,c=this._events[o],h=arguments.length;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),h){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,i),!0;case 4:return c.fn.call(c.context,e,i,r),!0;case 5:return c.fn.call(c.context,e,i,r,n),!0;case 6:return c.fn.call(c.context,e,i,r,n,a),!0}for(d=1,l=new Array(h-1);d<h;d++)l[d-1]=arguments[d];c.fn.apply(c.context,l)}else{var u,f=c.length;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(t,c[d].fn,void 0,!0),h){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,i);break;case 4:c[d].fn.call(c[d].context,e,i,r);break;default:if(!l)for(u=1,l=new Array(h-1);u<h;u++)l[u-1]=arguments[u];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,i,r){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||r&&!o.once||i&&o.context!==i||a(this,n);else{for(var l=0,d=[],c=o.length;l<c;l++)(o[l].fn!==e||r&&!o[l].once||i&&o[l].context!==i)&&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 i,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}(zc)),zc.exports),Xc=Qn(Qc);const Zc="1.7.2",Jc={};function th(t,e){return 255===t[e]&&240==(246&t[e+1])}function eh(t,e){return 1&t[e+1]?7:9}function sh(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function ih(t,e){return e+1<t.length&&th(t,e)}function rh(t,e){if(ih(t,e)){const s=eh(t,e);if(e+s>=t.length)return!1;const i=sh(t,e);if(i<=s)return!1;const r=e+i;return r===t.length||ih(t,r)}return!1}function nh(t,e,s,i,r){if(!t.samplerate){const n=function(t,e,s,i){const r=e[s+2],n=r>>2&15;if(n>12){const e=new Error(`invalid ADTS sampling index:${n}`);return void t.emit(zn.ERROR,zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const a=1+(r>>6&3),o=e[s+3]>>6&3|(1&r)<<2,l=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let d,c=n;5!==a&&29!==a||(c-=3);const h=(14&c)>>1,u=(1&c)<<7|o<<3;let f=0;if(1===a&&n>=6){f=5;const t=n-3;d=[f<<3|h,u|(14&t)>>1,(1&t)<<7|8,0]}else d=[a<<3|h,u];const g="mp4a.40."+(f||a);return Ua.log(`manifest codec:${i}, parsed codec:${g}, channels:${o}, rate:${l} (ADTS object type:${a} sampling index:${n} esds config:[${d.join(",")}])`),{config:d,samplerate:l,channelCount:o,codec:g,parsedCodec:g,manifestCodec:i}}(e,s,i,r);if(!n)return;Ta(t,n)}}function ah(t){return 9216e4/t}function oh(t,e,s,i,r){const n=i+r*ah(t.samplerate),a=function(t,e){const s=eh(t,e);if(e+s<=t.length){const i=sh(t,e)-s;if(i>0)return{headerLength:s,frameLength:i}}}(e,s);let o;if(a){const{frameLength:i,headerLength:r}=a,l=r+i,d=Math.max(0,s+l-e.length);d?(o=new Uint8Array(l-r),o.set(e.subarray(s+r,e.length),0)):o=e.subarray(s+r,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}}let lh=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function dh(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,i){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=Uo(this.cachedData,t),this.cachedData=null);let s,i=Xa(t,0),r=i?i.length:0;const n=this._audioTrack,a=this._id3Track,o=i?ao(i):void 0,l=t.length;for((null===this.basePTS||0===this.frameIndex&&Vn(o))&&(this.basePTS=ch(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:lh.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(t,r)){const e=this.appendFrame(n,t,r);e?(this.frameIndex++,this.lastPTS=e.sample.pts,r+=e.length,s=r):r=l}else za(t,r)?(i=Xa(t,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:lh.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,s=r):r++;if(r===l&&s!==l){const e=t.slice(s);this.cachedData?this.cachedData=Uo(this.cachedData,e):this.cachedData=e}}return{audioTrack:n,videoTrack:dh(),id3Track:a,textTrack:dh()}}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:dh(),id3Track:this._id3Track,textTrack:dh()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const ch=(t,e,s)=>{if(Vn(t))return 90*t;return 9e4*e+(s?9e4*s.baseTime/s.timescale:0)},hh=[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],uh=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],fh=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],gh=[0,1,1,4];function ph(t,e,s,i,r){if(s+24>e.length)return;const n=mh(e,s);if(n&&s+n.frameLength<=e.length){const a=i+r*(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 mh(t,e){const s=t[e+1]>>3&3,i=t[e+1]>>1&3,r=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==s&&0!==r&&15!==r&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*hh[14*(3===s?3-i:3===i?3:4)+r-1],d=uh[3*(3===s?0:2===s?1:2)+n],c=3===o?1:2,h=fh[s][i],u=gh[i],f=8*h*u,g=Math.floor(h*l/d+a)*u,p=Zo();return!!p&&p<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:d,channelCount:c,frameLength:g,samplesPerFrame:f}}}function vh(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function yh(t,e){return e+1<t.length&&vh(t,e)}function Eh(t,e){if(e+1<t.length&&vh(t,e)){const s=4,i=mh(t,e);let r=s;null!=i&&i.frameLength&&(r=i.frameLength);const n=e+r;return n===t.length||yh(t,n)}return!1}class SampleAesDecrypter{constructor(t,e,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Decrypter(e,!0)}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,gd,{start:0,end:t.byteLength})}decryptAacSample(t,e,s){const i=t[e].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(r=>{const n=new Uint8Array(r);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,s)}).catch(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 i=0;for(let e=32;e<t.length-16;e+=160,i+=16)s.set(t.subarray(e,e+16),i);return s}getAvcDecryptedUnit(t,e){const s=new Uint8Array(e);let i=0;for(let e=32;e<t.length-16;e+=160,i+=16)t.set(s.subarray(i,i+16),e);return t}decryptAvcSample(t,e,s,i,r){const n=Ho(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,s+1,i)}).catch(i)}decryptAvcSamples(t,e,s,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,s=0){if(e>=t.length)return void i();const r=t[e].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,s,i,n),this.decrypter.isSync())))return}}}}const Th=(t,e)=>{let s=0,i=5;e+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=t[e];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,s=s?s<<o|r[0]:r[0],e+=1,i-=o}return s};class AC3Demuxer extends BaseAudioDemuxer{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,s){const i=Sh(t,e,s,this.basePTS,this.frameIndex);if(-1!==i){return{sample:t.samples[t.samples.length-1],length:i,missing:0}}}static probe(t){if(!t)return!1;const e=Xa(t,0);if(!e)return!1;const s=e.length;if(11===t[s]&&119===t[s+1]&&void 0!==ao(e)){if(Th(t,s)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}}function Sh(t,e,s,i,r){if(s+8>e.length)return-1;if(11!==e[s]||119!==e[s+1])return-1;const n=e[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[s+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(s+l>e.length)return-1;const d=e[s+6]>>5;let c=0;2===d?c+=2:(1&d&&1!==d&&(c+=2),4&d&&(c+=2));const h=(e[s+6]<<8|e[s+7])>>12-c&1,u=[2,1,2,3,3,4,4,5][d]+h,f=e[s+5]>>3,g=7&e[s+5],p=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|d<<3|h<<2|o>>4,o<<4&224]),m=i+r*(1536/a*9e4),v=e.subarray(s,s+l);return t.config=p,t.channelCount=u,t.samplerate=a,t.samples.push({unit:v,pts:m}),l}const Ah=/\/emsg[-/]ID3/i;function _h(t,e){return Vn(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class BaseVideoParser{constructor(){this.VideoSample=null}createVideoSample(t,e,s){return{key:t,frame:!1,pts:e,dts:s,units:[],length:0}}getLastNalUnit(t){var e;let s,i=this.VideoSample;if(i&&0!==i.units.length||(i=t[t.length-1]),null!=(e=i)&&e.units){const t=i.units;s=t[t.length-1]}return s}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const s=e.samples,i=s.length;if(!i)return void e.dropped++;{const e=s[i-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,s){const i=e.byteLength;if(0===i)return[];const r=t.naluState||0,n=-1===r?0:r,a=[];let o=0,l=0,d=-1,c=0;for(-1===r&&(d=0,c=this.getNALuType(e,0),l=1);l<i;){const s=e.indexOf(1,l);if(-1===s)break;l=s+1;let r=s;for(;r>0&&0===e[r-1];)r--;if(!(s-r+(0===r?n:0)<2)){if(d>=0)a.push({data:e.subarray(d,r),type:c});else{const s=this.getLastNalUnit(t.samples);s&&(r>0?s.data=Uo(s.data,e.subarray(0,r)):n>0&&(s.data=s.data.subarray(0,s.data.byteLength-n)),s.state=0)}if(!(l<i)){o=-1,d=-1;break}d=l,c=this.getNALuType(e,l)}}if(-1!==o){let t=i;for(;t>0&&0===e[t-1];)t--;o=i-t+(0===t?n:0)}if(d>=0)a.push({data:e.subarray(d),type:c,state:o});else if(0===a.length&&-1!==o){const s=this.getLastNalUnit(t.samples);s&&(s.data=Uo(s.data,e),s.state=o)}return t.naluState=o,a}}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,i=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");i.set(t.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}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&&Ua.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(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)}}class AvcVideoParser extends BaseVideoParser{parsePES(t,e,s,i,r){const n=r.iframe,a=this.parseNALu(t,s.data,i);let o,l=this.VideoSample,d=!1;s.data=null,l&&a.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.forEach(i=>{var r,a;switch(i.type){case 1:{if(n)break;let e=!1;o=!0;const r=i.data;if(d&&r.length>4){const t=this.readSliceType(r);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var c;if(e)null!=(c=l)&&c.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null);l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.frame=!0,l.key=e;break}case 5:o=!0,null!=(r=l)&&r.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.key=!0,l.frame=!0;break;case 6:if(n)break;o=!0,Go(i.data,1,s.pts,e.samples);break;case 7:{var h,u;o=!0,d=!0;const e=i.data,s=this.readSPS(e);if(!t.sps||t.width!==s.width||t.height!==s.height||(null==(h=t.pixelRatio)?void 0:h[0])!==s.pixelRatio[0]||(null==(u=t.pixelRatio)?void 0:u[1])!==s.pixelRatio[1]){t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[e];const i=e.subarray(1,4);let r="avc1.";for(let t=0;t<3;t++){let e=i[t].toString(16);e.length<2&&(e="0"+e),r+=e}t.codec=r}break}case 8:o=!0,t.pps=[i.data];break;case 9:o=!0,t.audFound=!0,null!=(a=l)&&a.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1}if(l&&o){l.units.push(i)}}),i&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new ExpGolomb(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let s,i=8,r=8;for(let n=0;n<t;n++)0!==r&&(s=e.readEG(),r=(i+s+256)%256),i=0===r?i:r}readSPS(t){const e=new ExpGolomb(t);let s,i,r,n=0,a=0,o=0,l=0;const d=e.readUByte.bind(e),c=e.readBits.bind(e),h=e.readUEG.bind(e),u=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),p=e.skipUEG.bind(e),m=this.skipScalingList.bind(this);d();const v=d();if(c(5),f(3),d(),p(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const t=h();if(3===t&&f(1),p(),p(),f(1),u())for(i=3!==t?8:12,r=0;r<i;r++)u()&&m(r<6?16:64,e)}p();const y=h();if(0===y)h();else if(1===y)for(f(1),g(),g(),s=h(),r=0;r<s;r++)g();p(),f(1);const E=h(),T=h(),S=c(1);0===S&&f(1),f(1),u()&&(n=h(),a=h(),o=h(),l=h());let A=[1,1];if(u()&&u()){switch(d()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:A=[d()<<8|d(),d()<<8|d()]}}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:A}}}class HevcVideoParser extends BaseVideoParser{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,s,i){const r=this.parseNALu(t,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null;const l=t=>(a=this.VideoSample=this.createVideoSample(t,s.pts,s.dts),a);r.forEach((i,r)=>{var d,c;if(this.startsNewAccessUnit(a,t,i,r)){this.pushAccessUnit(a,t);const e=i.type>=16&&i.type<=23;a=l(e),o=!1}switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=l(!1)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:var h;if(n=!0,o)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 39:n=!0,Go(i.data,2,s.pts,e.samples);break;case 32:n=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=Ta(t.params,this.readVPS(i.data)),this.initVPS=i.data),t.vps=[i.data];break;case 33:if(n=!0,o=!0,void 0===t.vps||t.vps[0]===this.initVPS||void 0===t.sps||this.matchSPS(t.sps[0],i.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const e=this.readSPS(i.data);t.width=e.width,t.height=e.height,t.pixelRatio=e.pixelRatio,t.codec=e.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={});for(const s in e.params)t.params[s]=e.params[s]}this.pushParameterSet(t.sps,i.data,t.vps),a||(a=l(!1));break;case 34:if(n=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const e=this.readPPS(i.data);for(const s in e)t.params[s]=e[s]}this.pushParameterSet(t.pps,i.data,t.vps)}break;case 35:n=!0,t.audFound=!0,null!=(c=a)&&c.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=l(!1));break;default:n=!1}if(a&&n){a.units.push(i)}}),i&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}pushParameterSet(t,e,s){(s&&s[0]===this.initVPS||!s&&!t.length)&&t.push(e)}startsNewAccessUnit(t,e,s,i){if(!t)return!1;if(!e.audFound&&0===i)return!0;if(!t.frame)return!1;const{type:r,data:n}=s;return!!(r>=32&&r<=35||39===r||r>=41&&r<=44||r>=48&&r<=55)||r<=31&&n.length>2&&!!(128&n[2])}getNALuType(t,e){return(126&t[e])>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let s=0;for(let i=0;i<t.byteLength;i++)i>=2&&3===t[i]&&0===t[i-1]&&0===t[i-2]||(e[s]=t[i],s++);return new Uint8Array(e.buffer,0,s)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new ExpGolomb(t);e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6);return{numTemporalLayers:e.readBits(3)+1,temporalIdNested:e.readBoolean()}}readSPS(t){const e=new ExpGolomb(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const s=e.readBits(3);e.readBoolean();const i=e.readBits(2),r=e.readBoolean(),n=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),d=e.readUByte(),c=e.readUByte(),h=e.readUByte(),u=e.readUByte(),f=e.readUByte(),g=e.readUByte(),p=e.readUByte(),m=e.readUByte(),v=[],y=[];for(let t=0;t<s;t++)v.push(e.readBoolean()),y.push(e.readBoolean());if(s>0)for(let t=s;t<8;t++)e.readBits(2);for(let t=0;t<s;t++)v[t]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),y[t]&&e.readUByte();e.readUEG();const E=e.readUEG();3==E&&e.skipBits(1);const T=e.readUEG(),S=e.readUEG(),A=e.readBoolean();let _=0,b=0,L=0,R=0;A&&(_+=e.readUEG(),b+=e.readUEG(),L+=e.readUEG(),R+=e.readUEG());const I=e.readUEG(),k=e.readUEG(),w=e.readUEG();for(let t=e.readBoolean()?0:s;t<=s;t++)e.skipUEG(),e.skipUEG(),e.skipUEG();e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.readBoolean()){if(e.readBoolean())for(let t=0;t<4;t++)for(let s=0;s<(3===t?2:6);s++){if(e.readBoolean()){const s=Math.min(64,1<<4+(t<<1));t>1&&e.readEG();for(let t=0;t<s;t++)e.readEG()}else e.readUEG()}}e.readBoolean(),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const P=e.readUEG();let D=0;for(let t=0;t<P;t++){let s=!1;if(0!==t&&(s=e.readBoolean()),s){t===P&&e.readUEG(),e.readBoolean(),e.readUEG();let s=0;for(let t=0;t<=D;t++){const t=e.readBoolean();let i=!1;t||(i=e.readBoolean()),(t||i)&&s++}D=s}else{const t=e.readUEG(),s=e.readUEG();D=t+s;for(let s=0;s<t;s++)e.readUEG(),e.readBoolean();for(let t=0;t<s;t++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const t=e.readUEG();for(let s=0;s<t;s++){for(let t=0;t<w+4;t++)e.readBits(1);e.readBits(1)}}let C=0,O=1,M=1,x=!0,F=1,N=0;e.readBoolean(),e.readBoolean();let U=!1;if(e.readBoolean()){if(e.readBoolean()){const t=e.readUByte();t>0&&t<16?(O=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(O=e.readBits(16),M=e.readBits(16))}e.readBoolean()&&e.readBoolean();if(e.readBoolean()){e.readBits(3),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.readUByte(),e.readUByte())}e.readBoolean()&&(e.readUEG(),e.readUEG()),e.readBoolean(),e.readBoolean(),e.readBoolean(),U=e.readBoolean(),U&&(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG());if(e.readBoolean()){F=e.readBits(32),N=e.readBits(32);e.readBoolean()&&e.readUEG();if(e.readBoolean()){const t=e.readBoolean(),i=e.readBoolean();let r=!1;(t||i)&&(r=e.readBoolean(),r&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),r&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=s;n++){x=e.readBoolean();let s=!1;x||e.readBoolean()?e.readEG():s=e.readBoolean();const n=s?1:e.readUEG()+1;if(t)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(i)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),C=e.readUEG())}let B=T,$=S;if(A){let t=1,e=1;1===E?t=e=2:2==E&&(t=2),B=T-t*b-t*_,$=S-e*R-e*L}const G=i?["A","B","C"][i]:"",H=a<<24|o<<16|l<<8|d;let K=0;for(let t=0;t<32;t++)K=(K|(H>>t&1)<<31-t)>>>0;let V=K.toString(16);1===n&&"2"===V&&(V="6");return{codecString:`hvc1.${G}${n}.${V}.${r?"H":"L"}${m}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[a,o,l,d],general_constraint_indicator_flags:[c,h,u,f,g,p],general_level_idc:m,bit_depth:I+8,bit_depth_luma_minus8:I,bit_depth_chroma_minus8:k,min_spatial_segmentation_idc:C,chroma_format_idc:E,frame_rate:{fixed:x,fps:N/F}},width:B,height:$,pixelRatio:[O,M]}}readPPS(t){const e=new ExpGolomb(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.skipUEG(),e.skipUEG(),e.skipBits(2),e.skipBits(3),e.skipBits(2),e.skipUEG(),e.skipUEG(),e.skipEG(),e.skipBits(2);e.readBoolean()&&e.skipUEG(),e.skipEG(),e.skipEG(),e.skipBits(4);const s=e.readBoolean(),i=e.readBoolean();let r=1;return i&&s?r=0:i?r=3:s&&(r=2),{parallelismType:r}}matchSPS(t,e){return ho(t).substring(3)===ho(e).substring(3)}}const bh=188;class TSDemuxer{constructor(t,e,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=t,this.config=e,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(t,e){const s=TSDemuxer.syncOffset(t);return s>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),-1!==s}static syncOffset(t){const e=t.length;let s=Math.min(940,e-bh)+1,i=0;for(;i<s;){let r=!1,n=-1,a=0;for(let o=i;o<e;o+=bh){if(71!==t[o]||e-o!==bh&&71!==t[o+bh]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(s=Math.min(n+18612,t.length-bh)+1)),r||(r=0===Lh(t,o)),r&&a>1&&(0===n&&a>2||o+bh>s))return n}i++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:go[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,s,i,r,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=TSDemuxer.createTrack("video"),this._videoTrack.duration=i,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new PacketsIntegrityChecker(this.logger):null,this._audioTrack=TSDemuxer.createTrack("audio",i),this._id3Track=TSDemuxer.createTrack("id3"),this._txtTrack=TSDemuxer.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=s,t&&this.demux(t,0,n,"SAMPLE-AES"===(null==r?void 0:r.method))}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:s}=this;t&&(t.pesData=null),e&&(e.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,s,i=!1,r=!1){let n;i||(this.sampleAes=null);const a=this._videoTrack,o=this.videoIntegrityChecker,l=this._audioTrack,d=this._id3Track,c=this._txtTrack,h=s.iframe;let u=a.pid,f=a.pesData,g=l.pid,p=d.pid,m=this._klvPid,v=l.pesData,y=d.pesData,E=null,T=null,S=this.pmtParsed,A=this._pmtId,_=t.length;if(this.remainderData&&(_=(t=Uo(this.remainderData,t)).length,this.remainderData=null),_<bh&&!r)return this.remainderData=t,{audioTrack:l,videoTrack:a,id3Track:d,textTrack:c};const b=Math.max(0,TSDemuxer.syncOffset(t));_-=(_-b)%bh,_<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,_,t.buffer.byteLength-_));let L=0;for(let e=b;e<_;e+=bh)if(71===t[e]){const r=!!(64&t[e+1]),_=Lh(t,e);let L;if((48&t[e+3])>>4>1){if(L=e+5+t[e+4],L===e+bh)continue}else L=e+4;switch(_){case u:r&&(!f||null!=o&&o.isCorrupted||!(n=Ph(f,this.logger))||(this.readyVideoParser(a.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(a,c,n,!1,s)),f={data:[],size:0},null==o||o.reset(u)),null==o||o.handlePacket(t.subarray(e)),f&&(f.data.push(t.subarray(L,e+bh)),f.size+=e+bh-L);break;case g:if(h)break;if(r){if(v&&(n=Ph(v,this.logger)))switch(l.segmentCodec){case"aac":this.parseAACPES(l,n,s);break;case"mp3":this.parseMPEGPES(l,n);break;case"ac3":this.parseAC3PES(l,n)}v={data:[],size:0}}v&&(v.data.push(t.subarray(L,e+bh)),v.size+=e+bh-L);break;case p:if(h)break;r&&(y&&(n=Ph(y,this.logger))&&this.parseID3PES(d,n),y={data:[],size:0}),y&&(y.data.push(t.subarray(L,e+bh)),y.size+=e+bh-L);break;case m:if(h)break;r&&(E&&(n=Ph(E,this.logger))&&this.parseKlvPES(d,n),E={data:[],size:0}),E&&(E.data.push(t.subarray(L,e+bh)),E.size+=e+bh-L);break;case 0:r&&(L+=t[L]+1),A=this._pmtId=Rh(t,L);break;case A:{r&&(L+=t[L]+1);const n=Ih(t,L,this.typeSupported,i,this.observer,this.logger,this.config,s);u=n.videoPid,u>0&&(a.pid=u,a.segmentCodec=n.segmentVideoCodec),g=n.audioPid,g>0&&(l.pid=g,l.segmentCodec=n.segmentAudioCodec),p=n.id3Pid,p>0&&(d.pid=p),m=n.klvPid,m>0&&(this._klvPid=m),null===T||S||(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${T}'. Backtracking to sync byte @${b} to parse all TS packets.`),T=null,e=b-188),S=this.pmtParsed=!0;break}case 17:case 8191:break;default:T=_}}else L++;L>0&&kh(this.observer,new Error(`Found ${L} TS packet/s that do not start with 0x47`),s,void 0,this.logger),a.pesData=f,l.pesData=v,d.pesData=y;const R={audioTrack:l,videoTrack:a,id3Track:d,textTrack:c};return r&&this.extractRemainingSamples(R,s),R}flush(t,e){const{remainderData:s}=this;let i;return this.remainderData=null,i=s?this.demux(s,0,e,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(i,e),this.sampleAes?this.decrypt(i,this.sampleAes):i}extractRemainingSamples(t,e){const{audioTrack:s,videoTrack:i,id3Track:r,textTrack:n}=t,a=i.pesData,o=s.pesData,l=r.pesData,d=this.videoIntegrityChecker;let c;if(!a||null!=d&&d.isCorrupted||!(c=Ph(a,this.logger))?i.pesData=a:(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,n,c,!0,e),i.pesData=null)),o&&(c=Ph(o,this.logger))){switch(s.segmentCodec){case"aac":this.parseAACPES(s,c,e);break;case"mp3":this.parseMPEGPES(s,c);break;case"ac3":this.parseAC3PES(s,c)}s.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),s.pesData=o;l&&(c=Ph(l,this.logger))?(this.parseID3PES(r,c),r.pesData=null):r.pesData=l}demuxSampleAes(t,e,s,i){const r=this.demux(t,s,i,!0,!this.config.progressive),n=this.sampleAes=new SampleAesDecrypter(this.observer,this.config,e);return this.decrypt(r,n)}readyVideoParser(t){null===this.videoParser&&("avc"===t?this.videoParser=new AvcVideoParser:"hevc"===t&&(this.videoParser=new HevcVideoParser))}decrypt(t,e){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=t;i.samples&&"aac"===i.segmentCodec?e.decryptAacSamples(i.samples,0,()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,()=>{s(t)}):s(t)}):r.samples&&e.decryptAvcSamples(r.samples,0,0,()=>{s(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(t,e,s){let i=0;const r=this.aacOverFlow;let n,a,o,l=e.data;if(r){this.aacOverFlow=null;const e=r.missing,s=r.sample.unit.byteLength;if(-1===e)l=Uo(r.sample.unit,l);else{const n=s-e;r.sample.unit.set(l.subarray(0,e),n),t.samples.push(r.sample),i=r.missing}}for(n=i,a=l.length;n<a-1&&!ih(l,n);n++);if(n!==i){let t;const e=n<a-1;if(t=e?`AAC PES did not start with ADTS header,offset:${n}`:"No ADTS header found in AAC PES",kh(this.observer,new Error(t),s,e,this.logger),!e)return}if(nh(t,this.observer,l,n,this.audioCodec),void 0!==e.pts)o=e.pts;else{if(!r)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=ah(t.samplerate);o=r.sample.pts+e}}let d,c=0;for(;n<a;){if(d=oh(t,l,n,o,c),n+=d.length,d.missing){this.aacOverFlow=d;break}for(c++;n<a-1&&!ih(l,n);n++);}}parseMPEGPES(t,e){const s=e.data,i=s.length;let r=0,n=0;const a=e.pts;if(void 0!==a)for(;n<i;)if(yh(s,n)){const e=ph(t,s,n,a,r);if(!e)break;n+=e.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const s=e.data,i=e.pts;if(void 0===i)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=s.length;let n,a=0,o=0;for(;o<r&&(n=Sh(t,s,o,i,a++))>0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=Ta({},e,{type:this._videoTrack?lh.emsg:lh.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}parseKlvPES(t,e){var s;const i=null!=(s=e.pts)?s:e.dts;if(void 0===i)return void this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");const r=e.data;if(r.length<16)return void this.logger.warn("[tsdemuxer]: KLV PES payload too short");let n=0;for(;n<r.length;){var a;if(n+16>r.length)break;const s=n;if(n+=16,n>=r.length)break;const o=r[n];n+=1;let l=0;if(128&o){const t=127&o;if(0===t||t>4||n+t>r.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let e=0;e<t;e++)l=l<<8|r[n+e];n+=t}else l=o;if(n+l>r.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const d=n+l,c=r.subarray(s,d),h={data:c,len:c.byteLength,pts:i,dts:null!=(a=e.dts)?a:i,type:lh.misbklv,duration:Number.POSITIVE_INFINITY};t.samples.push(h),n=d}}}function Lh(t,e){return((31&t[e+1])<<8)+t[e+2]}function Rh(t,e){return(31&t[e+10])<<8|t[e+11]}function Ih(t,e,s,i,r,n,a,o){const l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},d=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<d;){const d=Lh(t,e),c=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!i){wh("ADTS AAC",n);break}case 15:-1===l.audioPid&&(l.audioPid=d);break;case 21:-1===l.id3Pid&&(l.id3Pid=d);break;case 219:if(!i){wh("H.264",n);break}case 27:-1===l.videoPid&&(l.videoPid=d);break;case 3:case 4:s.mpeg||s.mp3?-1===l.audioPid&&(l.audioPid=d,l.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){wh("AC-3",n);break}case 129:s.ac3?-1===l.audioPid&&(l.audioPid=d,l.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(c>0){let i=e+5,r=c;for(;r>2;){switch(t[i]){case 106:-1===l.audioPid&&(!0!==s.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=d,l.segmentAudioCodec="ac3"));break;case 5:-1===l.klvPid&&a.enableEmsgKLVMetadata&&(l.klvPid=d,n.log(`KLV metadata PID found: ${d}`))}const e=t[i+1]+2;i+=e,r-=e}}break;case 194:case 135:return kh(r,new Error("Unsupported EC-3 in M2TS found"),o,void 0,n),l;case 36:-1===l.videoPid&&(l.videoPid=d,l.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}e+=c+5}return l}function kh(t,e,s,i,r){r.warn(`parsing error: ${e.message}`),t.emit(zn.ERROR,zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,chunkMeta:s,error:e,reason:e.message})}function wh(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Ph(t,e){let s,i,r,n,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Uo(l[0],l[1]),l.splice(1,1);s=l[0];if(1===(s[0]<<16)+(s[1]<<8)+s[2]){if(i=(s[4]<<8)+s[5],i&&i>t.size-6)return null;const d=s[7];192&d&&(n=536870912*(14&s[9])+4194304*(255&s[10])+16384*(254&s[11])+128*(255&s[12])+(254&s[13])/2,64&d?(a=536870912*(14&s[14])+4194304*(255&s[15])+16384*(254&s[16])+128*(255&s[17])+(254&s[18])/2,n-a>54e5&&(e.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=s[8];let c=r+9;if(t.size<=c)return null;t.size-=c;const h=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){s=l[t];let e=s.byteLength;if(c){if(c>e){c-=e;continue}s=s.subarray(c),e-=c,c=0}h.set(s,o),o+=e}return i&&(i-=r+3),{data:h,pts:n,dts:a,len:i}}return null}class PacketsIntegrityChecker{constructor(t){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=t}get isCorrupted(){return"ok"!==this.integrityState}reset(t){this.pid=t,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(t){if(t.byteLength<4)return;const e=Lh(t,0);if(e!==this.pid)return void this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${e}`);const s=(48&t[3])>>4;if(0===s)return;const i=15&t[3],r=this.lastContinuityCounter;this.lastContinuityCounter=i;const n=!!(1&s);if(!!(2&s)&&0!=t[4]&&!!(128&t[5]))return;if(r<0)return;const a=n?r+1&15:r;return i!==a?(this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${e}', CC=${i}, Expected-CC=${a} Last-CC=${r}`),void(this.integrityState="cc-failed")):128&t[1]?(this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${e}'`),void(this.integrityState="tei-bit")):void 0}}class AAC{static getSilentFrame(t,e){if("mp4a.40.2"===t){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])}else{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])}}}var Dh;const Ch={video: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]),audio: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])},Oh=new Uint8Array([0,0,0,0,0,0,0,0]),Mh=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),xh=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Fh=new Uint8Array([0,0,0,0,0,0,0,0]),Nh=new Uint8Array([0,0,0,0,0,0,0,1]),Uh=new Uint8Array([105,115,111,109]),Bh=new Uint8Array([97,118,99,49]),$h=new Uint8Array([0,0,0,1]);class MP4{static box(t,...e){let s=8,i=e.length;const r=i;for(;i--;)s+=e[i].byteLength;const n=new Uint8Array(s);for(To(n,0,s),To(n,4,t),i=0,s=8;i<r;i++)n.set(e[i],s),s+=e[i].byteLength;return n}static hdlr(t){return MP4.box(fo.hdlr,Ch[t])}static mdat(t){return MP4.box(fo.mdat,t)}static mdhd(t,e){e*=t;const s=Math.floor(e/(uo+1)),i=Math.floor(e%(uo+1));return MP4.box(fo.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,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}static mdia(t){return MP4.box(fo.mdia,MP4.mdhd(t.timescale||0,t.duration||0),MP4.hdlr(t.type),MP4.minf(t))}static mfhd(t){return MP4.box(fo.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(fo.minf,MP4.box(fo.smhd,Fh),MP4.DINF,MP4.stbl(t)):MP4.box(fo.minf,MP4.box(fo.vmhd,xh),MP4.DINF,MP4.stbl(t))}static moof(t,e,s){return MP4.box(fo.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,[fo.moov,MP4.mvhd(t[0].timescale||0,t[0].duration||0)].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,[fo.mvex,...s])}static mvhd(t,e){e*=t;const s=Math.floor(e/(uo+1)),i=Math.floor(e%(uo+1)),r=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,i>>24,i>>16&255,i>>8&255,255&i,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(fo.mvhd,r)}static sdtp(t){const e=t.samples||[],s=new Uint8Array(4+e.length);let i,r;for(i=0;i<e.length;i++)r=e[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return MP4.box(fo.sdtp,s)}static stbl(t){return MP4.box(fo.stbl,MP4.stsd(t),MP4.box(fo.stts,Oh),MP4.box(fo.stsc,Oh),MP4.box(fo.stsz,Mh),MP4.box(fo.stco,Oh))}static avc1(t){let e,s,i,r=[],n=[];for(e=0;e<t.sps.length;e++)s=t.sps[e],i=s.byteLength,r.push(i>>>8&255),r.push(255&i),r=r.concat(Array.prototype.slice.call(s));for(e=0;e<t.pps.length;e++)s=t.pps[e],i=s.byteLength,n.push(i>>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(s));const a=MP4.box(fo.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,d=t.pixelRatio[0],c=t.pixelRatio[1];return MP4.box(fo.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(fo.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),MP4.box(fo.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,s=e.length;return new Uint8Array([0,0,0,0,3,23+s,0,1,0,4,15+s,64,21,0,0,0,0,0,0,0,0,0,0,0,5,s,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return MP4.box(fo.mp4a,MP4.audioStsd(t),MP4.box(fo.esds,MP4.esds(t)))}static mp3(t){return MP4.box(fo[".mp3"],MP4.audioStsd(t))}static ac3(t){return MP4.box(fo["ac-3"],MP4.audioStsd(t),MP4.box(fo.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return MP4.box(fo.stsd,Nh,MP4.mp4a(t));if("ac3"===e&&t.config)return MP4.box(fo.stsd,Nh,MP4.ac3(t));if("mp3"===e&&"mp3"===t.codec)return MP4.box(fo.stsd,Nh,MP4.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return MP4.box(fo.stsd,Nh,MP4.avc1(t));if("hevc"===e&&t.vps)return MP4.box(fo.stsd,Nh,MP4.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,s=(t.duration||0)*(t.timescale||0),i=t.width||0,r=t.height||0,n=Math.floor(s/(uo+1)),a=Math.floor(s%(uo+1));return MP4.box(fo.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,i>>8&255,255&i,0,0,r>>8&255,255&r,0,0]))}static traf(t,e){const s=MP4.sdtp(t),i=t.id,r=Math.floor(e/(uo+1)),n=Math.floor(e%(uo+1));return MP4.box(fo.traf,MP4.box(fo.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),MP4.box(fo.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,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(fo.trak,MP4.tkhd(t),MP4.mdia(t))}static trex(t){const e=t.id;return MP4.box(fo.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||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let a,o,l,d,c,h;for(e+=8+r,n.set(["video"===t.type?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<i;a++)o=s[a],l=o.duration,d=o.size,c=o.flags,h=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,h>>>24&255,h>>>16&255,h>>>8&255,255&h],12+16*a);return MP4.box(fo.trun,n)}static initSegment(t){const e=MP4.moov(t);return Uo(MP4.FTYP,e)}static hvc1(t){const e=t.params,s=[t.vps,t.sps,t.pps],i=new Uint8Array([1,e.general_profile_space<<6|(e.general_tier_flag?32:0)|e.general_profile_idc,e.general_profile_compatibility_flags[0],e.general_profile_compatibility_flags[1],e.general_profile_compatibility_flags[2],e.general_profile_compatibility_flags[3],e.general_constraint_indicator_flags[0],e.general_constraint_indicator_flags[1],e.general_constraint_indicator_flags[2],e.general_constraint_indicator_flags[3],e.general_constraint_indicator_flags[4],e.general_constraint_indicator_flags[5],e.general_level_idc,240|e.min_spatial_segmentation_idc>>8,255&e.min_spatial_segmentation_idc,252|e.parallelismType,252|e.chroma_format_idc,248|e.bit_depth_luma_minus8,248|e.bit_depth_chroma_minus8,0,parseInt(e.frame_rate.fps),3|e.temporal_id_nested<<2|e.num_temporal_layers<<3|(e.frame_rate.fixed?64:0),s.length]);let r=i.length;for(let t=0;t<s.length;t+=1){r+=3;for(let e=0;e<s[t].length;e+=1)r+=2+s[t][e].length}const n=new Uint8Array(r);n.set(i,0),r=i.length;const a=s.length-1;for(let t=0;t<s.length;t+=1){n.set(new Uint8Array([32+t|(t===a?128:0),0,s[t].length]),r),r+=3;for(let e=0;e<s[t].length;e+=1)n.set(new Uint8Array([s[t][e].length>>8,255&s[t][e].length]),r),r+=2,n.set(s[t][e],r),r+=s[t][e].length}const o=MP4.box(fo.hvcC,n),l=t.width,d=t.height,c=t.pixelRatio[0],h=t.pixelRatio[1];return MP4.box(fo.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,d>>8&255,255&d,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,MP4.box(fo.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),MP4.box(fo.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,h>>24,h>>16&255,h>>8&255,255&h])))}}Dh=MP4,MP4.FTYP=Dh.box(fo.ftyp,Uh,$h,Uh,Bh),MP4.DINF=Dh.box(fo.dinf,Dh.box(fo.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));function Gh(t,e,s=1,i=!1){const r=t*e*s;return i?Math.round(r):r}function Hh(t,e=!1){return Gh(t,1e3,1/9e4,e)}function Kh(t){const{baseTime:e,timescale:s,trackId:i}=t;return`${e/s} (${e}/${s}) trackId: ${i}`}const Vh=8589934592;function jh(t,e,s,i){return{duration:e,size:s,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1,paddingValue:0}}}class MP4Remuxer extends Logger{constructor(t,e,s,i){super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=s,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;e&&t&&t.trackId===e.trackId&&t.baseTime===e.baseTime&&t.timescale===e.timescale||this.log(`Reset initPTS: ${e?Kh(e):e} > ${t?Kh(t):t}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const s=t[0].pts,i=t.reduce((t,i)=>{let r=i.pts,n=r-t;return n<-4294967296&&(e=!0,r=qh(r,s),n=r-t),n>0?t:r},s);return e&&this.debug("PTS rollover detected"),i}remux(t,e,s,i,r,n,a,o,l){let d,c,h,u,f,g,p=r,m=r;const v=!l.iframe&&t.pid>-1,y=e.pid>-1,E=e.samples.length,T=t.samples.length>0,S=a&&E>0||E>1;if((!v||T)&&(!y||S)||this.ISGenerated||a){if(this.ISGenerated){var A,_,b,L;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(A=e.pixelRatio)?void 0:A[0])!==(null==(_=t.pixelRatio)?void 0:_[0])||(null==(b=e.pixelRatio)?void 0:b[1])!==(null==(L=t.pixelRatio)?void 0:L[1]))||!t&&S||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,e,r,n));const s=this.isVideoContiguous;let i,a=-1;if(S&&(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(g=!0,a>0){this.warn(`Dropped ${a} out of ${E} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,m+=(e.samples[0].pts-t)/e.inputTimeScale,i=m}else-1===a&&(this.warn(`No keyframe found out of ${E} video samples`),g=!1);if(this.ISGenerated){if(T&&S&&r){const s=this.getVideoStartPts(e.samples),i=(qh(t.samples[0].pts,s)-s)/e.inputTimeScale;p+=Math.max(0,i),m+=Math.max(0,-i)}if(T){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(t,e,r,n)),c=this.remuxAudio(t,p,this.isAudioContiguous,n,y||S||o===ca?m:void 0,l),S){const i=c?c.endPTS-c.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(t,e,r,n)),d=this.remuxVideo(e,m,s,i,l)}}else S&&(d=this.remuxVideo(e,m,s,0,l));d&&(d.firstKeyFrame=a,d.independent=-1!==a,d.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=Wh(s,r,this._initPTS,this._initDTS)),i.samples.length&&(u=Yh(i,r,this._initPTS))),{audio:c,video:d,initSegment:h,independent:g,text:u,id3:f}}computeInitPts(t,e,s,i){const r=Math.round(s*e);let n=qh(t,r);if(n<r)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/e} ${i}`);n<r;)n+=Vh;return n-r}generateIS(t,e,s,i){const r=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS,d=!l||i;let c,h,u,f="audio/mp4",g=-1;if(d&&(c=h=1/0),t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}if(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}},d){g=t.id,u=t.inputTimeScale;const e=this.computeInitPts(r[0].pts,u,s,"audio");(!l||u!==l.timescale||0===s&&e<l.baseTime)&&(c=h=e)}}if(e.sps&&e.pps&&n.length){if(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}},d){g=e.id,u=e.inputTimeScale;const t=this.getVideoStartPts(n),i=qh(n[0].dts,t),r=this.computeInitPts(i,u,s,"video"),a=this.computeInitPts(t,u,s,"video");(!l||u!==l.timescale||Vn(c)||0===s&&a<l.baseTime)&&(h=Math.min(h,r),c=Math.min(c,r))}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,d&&Vn(c)?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${c/u} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${c/u} (${c}/${u}) trackId: ${g}`),this._initPTS={baseTime:c,timescale:u,trackId:g},this._initDTS={baseTime:h,timescale:u,trackId:g}):c=u=void 0,{tracks:o,initPTS:c,timescale:u,trackId:g}}remuxVideo(t,e,s,i,r){const n=t.inputTimeScale,a=t.samples,o=[],l=a.length,d=this._initPTS,c=d.baseTime*n/d.timescale;let h,u,f=this.nextVideoTs,g=8,p=this.videoSampleDuration,m=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,y=!1;if(!s||null===f){const t=c+e*n,i=a[0].pts-qh(a[0].dts,a[0].pts);Zo()&&null!==f&&Math.abs(t-i-(f+c))<15e3?s=!0:f=t-i-c}const E=f+c;for(let t=0;t<l;t++){const e=a[t];e.pts=qh(e.pts,E),e.dts=qh(e.dts,E),e.dts<a[t>0?t-1:t].dts&&(y=!0)}y&&a.sort(function(t,e){const s=t.dts-e.dts,i=t.pts-e.pts;return s||i}),h=a[0].dts,u=a[a.length-1].dts;const T=u-h,S=T?Math.round(T/(l-1)):p||t.inputTimeScale/30;if(s){const s=h-E,i=s>S,r=s<-1;if((i||r)&&(i?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Hh(s,!0)} ms (${s}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Hh(-s,!0)} ms (${s}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||E>=a[0].pts||Zo())){h=E;const t=a[0].pts-s;if(i)a[0].dts=h,a[0].pts=t;else{let e=!0;for(let i=0;i<a.length&&!(a[i].dts>t&&e);i++){const t=a[i].pts;if(a[i].dts-=s,a[i].pts-=s,i<a.length-1){const s=a[i+1].pts;e=s<=a[i].pts==s<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${Hh(t,!0)}/${Hh(h,!0)}, delta: ${Hh(s,!0)} ms`)}}h=Math.max(0,h);let A=0,_=0,b=h;for(let t=0;t<l;t++){const e=a[t],s=e.units,i=s.length;let r=0;for(let t=0;t<i;t++)r+=s[t].data.length;_+=r,A+=i,e.length=r,e.dts<b?(e.dts=b,b+=S/4|0||1):b=e.dts,m=Math.min(e.pts,m),v=Math.max(e.pts,v)}u=a[l-1].dts;const L=_+4*A+8;let R;try{R=new Uint8Array(L)}catch(t){return void this.observer.emit(zn.ERROR,zn.ERROR,{type:Wn.MUX_ERROR,details:Yn.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:r,error:t,bytes:L,reason:`fail allocating video mdat ${L}`})}To(R,0,L),To(R,4,fo.mdat);let I=!1,k=Number.POSITIVE_INFINITY,w=Number.POSITIVE_INFINITY,P=Number.NEGATIVE_INFINITY,D=Number.NEGATIVE_INFINITY;for(let t=0;t<l;t++){const e=a[t],d=e.units;let h,u=0;for(let t=0,e=d.length;t<e;t++){const e=d[t],s=e.data,i=e.data.byteLength;To(R,g,i),g+=4,R.set(s,g),g+=i,u+=4+i}if(t<l-1)p=a[t+1].dts-e.dts,h=a[t+1].pts-e.pts;else{const s=this.config,r=t>0?e.dts-a[t-1].dts:S;if(h=t>0?e.pts-a[t-1].pts:S,s.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(s.maxBufferHole*n),a=(i?m+i*n:this.nextAudioTs+c)-e.pts;a>t?(p=a-r,p<0?p=r:I=!0,this.log(`It is approximately ${a/90} ms to the next segment; using duration ${p/90} ms for the last video frame.`)):p=r}else p=r}let f=Math.round(e.pts-e.dts);if(k=Math.min(k,p),P=Math.max(P,p),w=Math.min(w,h),D=Math.max(D,h),!s&&0===t&&f>p){const t=Math.round(f/S)*S;t-f===1&&(this.log(`pad first CTS ${f} -> ${t} of sn: ${r.sn}`),f=t)}o.push(jh(e.key,p,u,f))}if(o.length){const t=Zo();if(t){if(t<70){const t=o[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(function(){if(void 0===Qo){const t=qo.match(/Safari\/(\d+)/i);Qo=t?parseInt(t[1]):0}return Qo}()&&D-w<P-k&&S/P<.025&&0===o[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=h;for(let e=0,s=o.length;e<s;e++){const i=t+o[e].duration,r=t+o[e].cts;if(e<s-1){const t=i+o[e+1].cts;o[e].duration=t-r}else o[e].duration=e?o[e-1].duration:S;o[e].cts=0,t=i}}}p=I||!p?S:p;const C=u+p;this.nextVideoTs=f=C-c,this.videoSampleDuration=p,this.isVideoContiguous=!0,r.iframe&&(1===o.length?(o[0].duration=p=r.duration*n,this.nextVideoTs=f=h+p-c):this.warn(`Not adjusting IFrame duration (sample count ${o.length})`));const O={data1:MP4.moof(r.sn,h,Ta(t,{samples:o})),data2:R,startPTS:(m-c)/n,endPTS:(v+p-c)/n,startDTS:(h-c)/n,endDTS:f/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:t.dropped};return t.samples=[],t.dropped=0,O}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,s,i,r,n){const a=t.inputTimeScale,o=a/(t.samplerate?t.samplerate:a),l=this.getSamplesPerFrame(t),d=l*o,c=this._initPTS,h="mp3"===t.segmentCodec&&this.typeSupported.mpeg,u=[],f=void 0!==r;let g=t.samples,p=h?0:8,m=this.nextAudioTs||-1;const v=c.baseTime*a/c.timescale,y=v+e*a;if(this.isAudioContiguous=s=s||g.length&&m>0&&(i&&Math.abs(y-(m+v))<9e3||Math.abs(qh(g[0].pts,y)-(m+v))<20*d),g.forEach(function(t){t.pts=qh(t.pts,y)}),!s||m<0){const t=g.length;if(g=g.filter(t=>t.pts>=0),t!==g.length&&this.warn(`Removed ${g.length-t} of ${t} samples (initPTS ${v} / ${a})`),!g.length)return;m=0===r?0:i&&!f?Math.max(0,y-v):g[0].pts-v}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let s=0,i=m+v;s<g.length;s++){const r=g[s],n=r.pts,o=n-i,l=Math.abs(1e3*o/a);if(o<=-e*d&&f)0===s&&(this.warn(`Audio frame @ ${(n/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/a)} ms.`),this.nextAudioTs=m=n-v,i=n);else if(o>=e*d&&l<1e4&&f){let e=Math.round(o/d);for(i=n-e*d;i<0&&e&&d;)e--,i+=d;0===s&&(this.nextAudioTs=m=i-v),this.warn(`Injecting ${e} audio frames @ ${((i-v)/a).toFixed(3)}s due to ${Math.round(1e3*o/a)} ms gap.`);for(let n=0;n<e;n++){let e=AAC.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);e||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),e=r.unit.subarray()),g.splice(s,0,{unit:e,pts:i}),i+=d,s++}}r.pts=i,i+=d}}let E,T=null,S=null,A=0,_=g.length;for(;_--;)A+=g[_].unit.byteLength;for(let e=0,i=g.length;e<i;e++){const i=g[e],r=i.unit;let a=i.pts;if(null!==S){u[e-1].duration=Math.round((a-S)/o)}else{if(s&&"aac"===t.segmentCodec&&(a=m+v),T=a,!(A>0))return;A+=p;try{E=new Uint8Array(A)}catch(t){return void this.observer.emit(zn.ERROR,zn.ERROR,{type:Wn.MUX_ERROR,details:Yn.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:n,error:t,bytes:A,reason:`fail allocating audio mdat ${A}`})}h||(To(E,0,A),To(E,4,fo.mdat))}E&&E.set(r,p);const d=r.byteLength;p+=d,u.push(jh(!0,l,d,0)),S=a}const b=u.length;if(!b)return;const L=u[u.length-1];m=S-v,this.nextAudioTs=m+o*L.duration;const R=h?new Uint8Array(0):MP4.moof(t.sequenceNumber++,T/o,Ta({},t,{samples:u}));t.samples=[];const I=(T-v)/a,k=this.nextAudioTs/a,w={data1:R,data2:E,startPTS:I,endPTS:k,startDTS:I,endDTS:k,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,w}}function qh(t,e){let s;if(null===e)return t;for(s=e<t?-8589934592:Vh;Math.abs(t-e)>4294967296;)t+=s;return t}function Wh(t,e,s,i){const r=t.samples.length;if(!r)return;const n=t.inputTimeScale;for(let a=0;a<r;a++){const r=t.samples[a];r.pts=qh(r.pts-s.baseTime*n/s.timescale,e*n)/n,r.dts=qh(r.dts-i.baseTime*n/i.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function Yh(t,e,s){const i=t.samples.length;if(!i)return;const r=t.inputTimeScale;for(let n=0;n<i;n++){const i=t.samples[n];i.pts=qh(i.pts-s.baseTime*r/s.timescale,e*r)/r}t.samples.sort((t,e)=>t.pts-e.pts);const n=t.samples;return t.samples=[],{samples:n}}function zh(t,e,s=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(s?t.duration:0))/t.timescale:e}function Qh(t,e,s){const i=t.codec;if(i&&i.length>4)return i;if(e===ua){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return dl(i,!1)}return s.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"}return"mjpg"===i?i:(s.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}let Xh;try{Xh=self.performance.now.bind(self.performance)}catch(t){Xh=Date.now}const Zh=[{demux:class MP4Demuxer{constructor(t,e,s,i=Ua){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.initData=void 0,this.logger=void 0,this.config=e,this.logger=i}resetTimeStamp(){}resetInitSegment(t,e,s,i){const r=this.videoTrack=dh("video",1),n=this.audioTrack=dh("audio",1),a=this.txtTrack=dh("text",1);if(this.id3Track=dh("id3",1),this.initData=void 0,this.timeOffset=0,null==t||!t.byteLength)return;const o=this.initData=Io(t);if(o.video){const{id:t,timescale:e,codec:s,supplemental:i}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=s,r.supplemental=i}if(o.audio){const{id:t,timescale:e,codec:s}=o.audio;n.id=t,n.timescale=e,n.codec=s}a.id=go.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(t){return function(t,e){const s=t.byteLength;for(let i=0;i<s;){const r=mo(t,i);if(r>8&&mo(t,i+4)===fo[e])return!0;i=r>1?i+r:s}return!1}(t,"moof")}demux(t,e,s){this.timeOffset=e;let i=t;const r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Uo(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},s=bo(t,["moof"]);if(s.length<2)return e.remainder=t,e;const i=s[s.length-1];return e.valid=t.slice(0,i.byteOffset-8),e.remainder=t.slice(i.byteOffset-8),e}(i);this.remainderData=e.remainder,r.samples=e.valid||new Uint8Array}else r.samples=i;const a=this.extractID3Track(r,e),o=this.parseFragment(r,n,e,s);return{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack,initData:this.initData,sampleData:o}}flush(t,e){const s=this.timeOffset,i=this.videoTrack,r=this.txtTrack;i.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(i,this.timeOffset),a=this.parseFragment(i,r,s,e);return{videoTrack:i,audioTrack:dh(),id3Track:n,textTrack:dh(),initData:this.initData,sampleData:a}}parseFragment(t,e,s,i){const r=this.initData;if(r&&i){const{samples:n,sampleData:a}=function(t,e,s,i,r=!1){const n=[];return{samples:n,sampleData:{includeSampleDetails:r,tracks:No(e.samples,s,i,r,{isHEVCFlavor:Bo(e.codec),samples:n,timeOffset:t,timescale:e.timescale,trackId:e.id})}}}(s,t,r,this.logger,i.iframe);return e.samples=n,a}e.samples=function(t,e){const s=[],i=e.samples,r=e.timescale,n=e.id;let a=!1;return bo(i,["moof"]).map(o=>{const l=o.byteOffset-8;bo(o,["traf"]).map(o=>{const d=bo(o,["tfdt"]).map(t=>{const e=t[0];let s=mo(t,4);return 1===e&&(s*=Math.pow(2,32),s+=mo(t,8)),s/r})[0];return void 0!==d&&(t=d),bo(o,["tfhd"]).map(d=>{const c=mo(d,4),h=16777215&mo(d,0),u=!!(1&h);let f=0;const g=!!(2&h),p=!!(8&h);let m=0;const v=!!(16&h);let y=0;const E=!!(32&h),T=!u&&!!(131072&h);let S=8;c===n&&(u?(f=mo(d,S),S+=4,f*=Math.pow(2,32),f+=mo(d,S),S+=4):T&&(f=l),g&&(S+=4),p&&(m=mo(d,S),S+=4),v&&(y=mo(d,S),S+=4),E&&(S+=4),"video"===e.type&&(a=Bo(e.codec)),bo(o,["trun"]).map(n=>{const o=n[0],l=16777215&mo(n,0),d=!!(1&l);let c=0;const h=!!(4&l),u=!!(256&l);let g=0;const p=!!(512&l);let v=0;const E=!!(1024&l),T=!!(2048&l);let S=0;const A=mo(n,4);let _=8;d&&(c=mo(n,_),_+=4),h&&(_+=4);let b=f+c;for(let l=0;l<A;l++){if(u?(g=mo(n,_),_+=4):g=m,p?(v=mo(n,_),_+=4):v=y,E&&(_+=4),T&&(S=0===o?mo(n,_):Eo(n,_),_+=4),e.type===fa){let e=0;for(;e<v;){const n=mo(i,b);b+=4,$o(a,i[b])&&Go(i.subarray(b,b+n),a?2:1,t+S/r,s),b+=n,e+=n+4}}t+=g/r}}))})})}),s}(s,t)}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const i=bo(t.samples,["emsg"]);i&&i.forEach(t=>{const i=function(t){const e=t[0];let s,i="",r="",n=0,a=0,o=0,l=0,d=4;if(0===e){const e=yo(t,d),s=null!==e?yo(t,d+e.length):null;null!==e&&null!==s?(i=e,r=s,d+=e.length+s.length,n=mo(t,d),d+=4,a=mo(t,d),d+=4,o=mo(t,d),d+=4,l=mo(t,d),d+=4):(Ua.warn(`Unterminated ${null===e?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),d=t.length)}else if(1===e){n=mo(t,d),d+=4;const e=mo(t,d);d+=4;const a=mo(t,d);d+=4,s=2**32*e+a,jn(s)||(s=Number.MAX_SAFE_INTEGER,Ua.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=mo(t,d),d+=4,l=mo(t,d),d+=4;const c=yo(t,d),h=null!==c?yo(t,d+c.length):null;null!==c&&(i=c,d+=c.length),null!==h?(r=h,d+=h.length):(Ua.warn(`Unterminated ${null===c?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${null===c?"strings and payload":"value and payload"}`),d=t.length)}return{schemeIdUri:i,value:r,timeScale:n,presentationTime:s,presentationTimeDelta:a,eventDuration:o,id:l,payload:t.subarray(d,t.byteLength)}}(t);if(Ah.test(i.schemeIdUri)){const t=_h(i,e);let r=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=i.payload;s.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:lh.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata){const t=this.config.emsgKLVSchemaUri||lh.misbklv;if(i.schemeIdUri.startsWith(t)){const t=_h(i,e);s.samples.push({data:i.payload,len:i.payload.byteLength,dts:t,pts:t,type:lh.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return s}demuxSampleAes(t,e,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}},remux:class PassThroughRemuxer extends Logger{constructor(t,e,s,i){super("passthrough-remuxer",i),this.observer=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=t}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(t){this.lastEndTime=null;const e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,s,i){this.audioCodec=e,this.videoCodec=s,this.decryptdata=i,this.pendingInitSegment=t,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(t,e,s){this.videoOnlyRemux=!1;let{audioCodec:i,videoCodec:r}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:n,video:a}=this.initData=s||Io(t);if(e)!function(t,e){if(!t||!e)return;const s=e.keyId;16===(null==s?void 0:s.byteLength)&&e.isCommonEncryption&&Oo(t,(t,e)=>{const i=t.subarray(8,24);i.some(t=>0!==t)||(Ua.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${oo(i)} -> ${oo(s)}`),t.set(s,8))})}(t,e);else{const t=n||a;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}n&&(i=Qh(n,ua,this)),a&&(r=Qh(a,fa,this));const o={};n&&a?o.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:n?o.audio={container:"audio/mp4",codec:i,encrypted:n.encrypted,initSegment:t,id:"audio"}:a?o.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(t,e,s,i,r,n,a,o,l,d,c){var h,u;let{initPTS:f,lastEndTime:g}=this;const p={audio:void 0,video:void 0,text:void 0,id3:s,initSegment:void 0};Vn(g)||(g=this.lastEndTime=r||0);const m=e.samples;if(!m.length)return p;const v=this.pendingInitSegment;v&&(this.pendingInitSegment=void 0,this.generateInitSegment(v,this.decryptdata,d));const y={initPTS:void 0,timescale:void 0,trackId:void 0};let E=this.initData;if(null!=(h=E)&&h.length||(this.generateInitSegment(m),E=this.initData),null==(u=E)||!u.length)return this.warn("Failed to generate initSegment."),p;if(l.iframe&&E.audio&&E.video){var T;const t=null==(T=this.initTracks)||null==(T=T.audiovideo)?void 0:T.initSegment,e=t?function(t){const e=bo(t,["moov"]);if(1!==e.length||bo(t,["moof"]).length)return null;const s=t.byteOffset,i=[],r=[];let n=!1;const a=bo(e[0],["trak"]);for(let t=0;t<a.length;t++){const e=a[t],o=bo(e,["mdia","hdlr"])[0];if("vide"===(o?ho(o.subarray(8,12)):"")){n=!0;continue}const l=bo(e,["tkhd"])[0];if(!l)return null;const d=l[0];r.push(mo(l,0===d?12:20)),i.push(Ao(e,s))}if(!n||!i.length)return null;const o=bo(e[0],["mvex"])[0];let l=0;if(o){const t=bo(o,["trex"]);for(let e=0;e<t.length;e++){const n=t[e];-1!==r.indexOf(mo(n,4))&&(i.push(Ao(n,s)),l+=n.byteLength+8)}}const{result:d,dropped:c,droppedBefore:h}=_o(t,i);if(To(d,e[0].byteOffset-s-8,e[0].byteLength+8-c),o&&l){const t=o.byteOffset-s-8;To(d,t-h(t),o.byteLength+8-l)}return d}(t):null;var S;if(e)this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(e,this.decryptdata),null!=(S=this.initData)&&S.length&&(E=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}this.emitInitSegment&&(y.tracks=this.initTracks,p.initSegment=y,this.emitInitSegment=!1);const A=l.iframe,_=!c||A&&!c.includeSampleDetails?function(t,e,s,i,r=!0){return No(t,e,i,r)}(m,E,0,this,A):c.tracks,b=E.audio?_[E.audio.id]:null,L=E.video?_[E.video.id]:null,R=!!E.audio,I=!!E.video;let k="";R&&(k+="audio"),I&&(k+="video");const w=zh(L,1/0),P=zh(b,1/0),D=zh(L,0,!0),C=zh(b,0,!0);let O=r,M=0;L&&b&&E.audio&&(P>D||w>C)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${w}-${D} a: ${P}-${C}}`,L,b);const x=!!b&&(!L||!f&&P<w||!!f&&f.trackId===E.audio.id),F=x?b:L;if(!F)return this.log(`No media samples found in ${o} ${l.level} ${-1===l.part?"":`part: ${l.part} of`} sn: ${l.sn} at playlist time: ${r}`),p;let N,U=m;if(L&&L.sampleCount>=1&&E.video&&l.iframe){const{trun:t,start:e}=L,s=1===t.length,i=t.length?s?t[0].samples:t[0].samples.concat(...t.slice(1).map(t=>t.samples)):[];if(i.length){const r=t[0];let n=r;for(let e=t.length;e--;)if(t[e].samples.length){n=t[e];break}const a=n.lastSampleDurationOffset,{defaultSampleDurationOffset:o}=r,d=Math.abs(l.duration-(D-w))>.05,c=i.length<L.sampleCount;if(d||c||this.videoOnlyRemux||!s){const t=c?n.sampleOffset+n.samples.reduce((t,e)=>t+e.size,0):void 0,s=d?l.duration:D-w,r=function(t,e,s,i){if(void 0!==s){const i=t[t.length-1];let r=e;for(let e=0;e<t.length-1;e++)r-=t[e].duration;return r<=0&&(r=i.duration),i.duration=r,{durationOffset:s,value:r}}if(void 0===i)return;const r=Math.round(e/t.length);for(let e=0;e<t.length;e++)t[e].duration=r;return{durationOffset:i,value:r}}(i,s*E.video.timescale,a,o),h=function(t,e,s,i,r){if(s<1)return null;const n=bo(t,["moof"]);if(1!==n.length)return null;const a=n[0],o=t.byteOffset,l=[],d=[],c=bo(a,["traf"]);let h=!0;for(let t=0;t<c.length;t++){const s=c[t],i=bo(s,["tfhd"])[0];if(!i)return null;mo(i,4)===e?(l.push(s),131072&mo(i,0)||(h=!1)):d.push(Ao(s,o))}if(!l.length)return null;if(d.length&&!h)return null;if(void 0!==i){let e=s;for(let s=0;s<l.length;s++){const i=l[s];let r=0;const n=bo(i,["trun"]);for(let s=0;s<n.length;s++){const i=n[s],a=Math.min(e,mo(i,4));if(a){To(t,i.byteOffset-o+4,a);const e=16777215&mo(i,0);So(t,i,8+(1&e?4:0)+(4&e?4:0)+a*((256&e?4:0)+(512&e?4:0)+(1024&e?4:0)+(2048&e?4:0)))}else To(t,i.byteOffset-o-4,fo.free);e-=a,r+=a}const a=bo(i,["senc"])[0];a&&To(t,a.byteOffset-o+4,r);const d=bo(i,["saiz"])[0];if(d){let e=4;1&(d[1]<<16|d[2]<<8|d[3])&&(e+=8);const s=d[e];e+=1,To(t,d.byteOffset-o+e,r),So(t,d,e+4+(0===s?r:0))}}const r=bo(t,["mdat"]);if(1===r.length){const e=r[0].byteOffset-o-8;To(t,e,i-e)}}let u=t,f=0,g=()=>0;if(d.length){({result:u,dropped:f,droppedBefore:g}=_o(t,d)),To(u,a.byteOffset-o-8,a.byteLength+8-f);for(let t=0;t<l.length;t++){const e=l[t],s=g(e.byteOffset-o),i=bo(e,["trun"]);for(let t=0;t<i.length;t++){const e=i[t];1&mo(e,0)&&To(u,e.byteOffset-o-s+8,mo(e,8)-f)}if(s){const t=bo(e,["saio"]);for(let e=0;e<t.length;e++){const i=t[e],r=0===i[0]?4:8;let n=1&mo(i,0)?12:4,a=mo(i,n);for(n+=4;a--;n+=r){const t=n+r-4;To(u,i.byteOffset-o-s+t,mo(i,t)-s)}}}}}if(r){const{durationOffset:t,value:e}=r;To(u,t-g(t),e)}return void 0!==i?u.subarray(0,i-f):u}(m,E.video.id,i.length,t,r);h?(U=h,N=function(t,e){let s=t,i=t;for(let t=0;t<e.length;t++){const{cts:r,duration:n}=e[t];i=Math.max(i,s+(r||0)+n),s+=n}return i}(e,i)):this.warn(`IFrame remux skipped (sn ${l.sn}); using native sample duration`),M=h&&r?s:D-w}else M=D-w}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${t.length})`),M=D-w}else M=x?C-P:D-w;if(this.videoOnlyRemux&&U===m)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${l.sn})`),p;const B=F.timescale,$=F.start-r*B,G=x?E.audio.id:E.video.id;if(O=F.start/B,(n||!f)&&(function(t,e,s,i){if(null===t)return!0;const r=Math.max(i,1),n=e-t.baseTime/t.timescale;return Math.abs(n-s)>=r}(f,O,r,M)||B!==f.timescale)){let t=!1;const e=x?"audio":"video";if(f){const s=0!==r?O/r:1+O/1;t=O>=0&&Math.abs(1-s)<.001,this.log(`${e} timestamps in track ${G} at playlist time: ${n?"":"~"}${r} maps to ${O} with initPTS: ${f.baseTime/f.timescale} (${$/B-f.baseTime/f.timescale}s diff) (${k}) drift estimate: ${s} ${t?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}t||(this.log(`Found initPTS in ${e} track ${G} at playlist time: ${r} offset: ${O-r} (${$}/${B})`),f=null,y.initPTS=$,y.timescale=B,y.trackId=G)}f?(y.initPTS=f.baseTime,y.timescale=f.timescale,y.trackId=f.trackId):(y.timescale&&void 0!==y.trackId&&void 0!==y.initPTS||(this.warn("Could not set initPTS"),y.initPTS=O,y.timescale=1,y.trackId=-1),this.initPTS=f={baseTime:y.initPTS,timescale:y.timescale,trackId:y.trackId});const H=O-f.baseTime/f.timescale,K=H+M,V=I&&void 0!==(null==F?void 0:F.ptsMin)?F.ptsMin/F.timescale-f.baseTime/f.timescale:H,j=void 0!==N&&L?N/L.timescale-f.baseTime/f.timescale:I&&null!=F&&F.ptsMax?F.ptsMax/F.timescale-f.baseTime/f.timescale:K;M>0?this.lastEndTime=K:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const q={data1:U,data2:undefined,startPTS:V,startDTS:H,endPTS:j,endDTS:K,type:k,hasAudio:R,hasVideo:I,nb:1,dropped:0,encrypted:!!E.audio&&E.audio.encrypted||!!E.video&&E.video.encrypted};p.audio=R&&!I?q:void 0,p.video=I?q:void 0;const W=this.isVideoContiguous,Y=null==L?void 0:L.sampleCount;if(Y){const t=L.keyFrameIndex,e=-1!==t;q.nb=Y,q.dropped=0===t||W?0:e?t:Y,q.independent=e,q.firstKeyFrame=t,e&&L.keyFrameStart&&(q.firstKeyFramePTS=(L.keyFrameStart-f.baseTime)/f.timescale),W||(p.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),q.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${Y} dropped: ${q.dropped} start: ${q.firstKeyFramePTS||"NA"}`)}return p.initSegment=y,p.id3=Wh(s,r,f,f),i.samples.length&&(p.text=Yh(i,r,f)),p}}},{demux:TSDemuxer,remux:MP4Remuxer},{demux:class AACDemuxer extends BaseAudioDemuxer{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=t,this.config=e}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const s=Xa(t,0);let i=(null==s?void 0:s.length)||0;if(Eh(t,i))return!1;for(let s=t.length;i<s;i++)if(rh(t,i))return e.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)&&th(t,e)&&sh(t,e)<=t.length-e}(t,e)}appendFrame(t,e,s){nh(t,this.observer,e,s,t.manifestCodec);const i=oh(t,e,s,this.basePTS,this.frameIndex);if(0===(null==i?void 0:i.missing))return i}demuxSampleAes(t,e,s){const i=this.demux(t,s),r=this.sampleAes=new SampleAesDecrypter(this.observer,this.config,e);return new Promise(t=>{r.decryptAacSamples(i.audioTrack.samples,0,()=>{t(i)})})}},remux:MP4Remuxer},{demux:class MP3Demuxer extends BaseAudioDemuxer{resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=Xa(t,0);let s=(null==e?void 0:e.length)||0;if(e&&11===t[s]&&119===t[s+1]&&void 0!==ao(e)&&Th(t,s)<=16)return!1;for(let e=t.length;s<e;s++)if(Eh(t,s))return Ua.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return vh(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,s){if(null!==this.basePTS)return ph(t,e,s,this.basePTS,this.frameIndex)}},remux:MP4Remuxer}];Zh.splice(2,0,{demux:AC3Demuxer,remux:MP4Remuxer});class Transmuxer{constructor(t,e,s,i,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=e,this.config=s,this.id=r,this.logger=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,s,i){if(!this.observer)return Jh(s);const r=s.transmuxing;r.executeStart=Xh();const n=new Uint8Array(t),{currentTransmuxState:a,transmuxConfig:o}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:d,trackSwitch:c,accurateTimeOffset:h,timeOffset:u,initSegmentChange:f}=i||a,{audioCodec:g,videoCodec:p,defaultInitPts:m,duration:v,initSegmentData:y}=o,E=function(t,e){let s=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(s=e);return s}(n,e);if(E&&Cd(E.method)){const t=this.getDecrypter(),e=Od(E.method);return this.asyncResult=!0,this.decryptionPromise=t.decrypt(n,E.key.buffer,E.iv.buffer,e,s.decryptRange).then(t=>{const e=this.push(t,null,s);return this.decryptionPromise=null,e}),this.decryptionPromise}const T=this.needsProbing(d,c);if(T){const t=s.iframe&&y&&TSDemuxer.probe(y,this.logger)?y:n,e=this.configureTransmuxer(t);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(zn.ERROR,zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),r.executeEnd=Xh(),Jh(s)}(d||c||f||T)&&this.resetInitSegment(y,g,p,v,e,s),(d||f||T)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const S=this.transmux(n,E,u,h,s);this.asyncResult=tu(S);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=Xh(),S}flush(t){const e=t.transmuxing;e.executeStart=Xh();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(t));const n=[],{timeOffset:a}=i;if(s){const e=s.flush();e&&n.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Xh();const s=[Jh(t)];return this.asyncResult?Promise.resolve(s):s}const d=o.flush(a,t);return tu(d)?(this.asyncResult=!0,d.then(e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,d,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,s){if(!this.remuxer)return;const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id} playlist ${s.level}`);const d=this.remuxer.remux(i,r,n,a,l,o,!0,this.id,s,e.initData,e.sampleData);t.push({remuxResult:d,chunkMeta:s}),s.transmuxing.executeEnd=Xh()}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,i,r,n){const{demuxer:a,remuxer:o}=this;a&&o&&(a.resetInitSegment(t,e,s,i,r,n),o.resetInitSegment(t,e,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(t,e,s,i,r){let n;return n="SAMPLE-AES"===(null==e?void 0:e.method)?this.transmuxSampleAes(t,e,s,i,r):this.transmuxUnencrypted(t,s,i,r),n}transmuxUnencrypted(t,e,s,i){const{demuxer:r,remuxer:n}=this;if(!r||!n)return Jh(i);const a=r.demux(t,e,i,!1,!this.config.progressive),{audioTrack:o,videoTrack:l,id3Track:d,textTrack:c}=a;return{remuxResult:n.remux(o,l,d,c,e,s,!1,this.id,i,a.initData,a.sampleData),chunkMeta:i}}transmuxSampleAes(t,e,s,i,r){return this.demuxer?this.demuxer.demuxSampleAes(t,e,s,r).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,s,i,!1,this.id,r,t.initData,t.sampleData),chunkMeta:r})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(t){const{config:e,observer:s,typeSupported:i}=this;if(!s)return;let r;try{for(let e=0,s=Zh.length;e<s;e++){var n;if(null!=(n=Zh[e].demux)&&n.probe(t,this.logger)){r=Zh[e];break}}}catch(t){return t}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.demux,d=r.remux;a&&a instanceof l||(this.logger.log(`Using ${l.name}`),this.demuxer=new l(s,e,i,this.logger),this.probe=l.probe),o&&o instanceof d||(this.logger.log(`Using ${d.name}`),this.remuxer=new d(s,e,i,this.logger))}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 Jh=t=>({remuxResult:{},chunkMeta:t});function tu(t){return"then"in t&&t.then instanceof Function}class TransmuxConfig{constructor(t,e,s,i,r){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=i,this.defaultInitPts=r||null}}class TransmuxState{constructor(t,e,s,i,r,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=i,this.timeOffset=r,this.initSegmentChange=n}}let eu=0;class TransmuxerInterface{constructor(t,e,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=eu++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=t=>{const e=t.data,s=this.hls;if(s&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var i;const t=null==(i=this.workerContext)?void 0:i.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":s.logger[e.data.logType]&&s.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,s.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;const e=new Error(`${t.message} (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const r=t.config;this.hls=t,this.id=e,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===zn.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new Xc,this.observer.on(zn.FRAG_DECRYPTED,n),this.observer.on(zn.ERROR,n);const a=fl(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const s=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(s.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=function(t){const e=Jc[t];if(e)return e.clientCount++,e;const s=new self.URL(t,self.location.href).href,i={worker:new self.Worker(s),scriptURL:s,clientCount:1};return Jc[t]=i,i}(r.workerPath)):(s.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=Jc[Zc];if(t)return t.clientCount++,t;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),s=self.URL.createObjectURL(e),i={worker:new self.Worker(s),objectURL:s,clientCount:1};return Jc[Zc]=i,i}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:e,config:Dl(r)})}catch(i){s.warn(`Error setting up "${e}" Web Worker, fallback to inline`,i),this.terminateWorker(),this.error=null,this.transmuxer=new Transmuxer(this.observer,a,r,"",e,t.logger)}return}}this.transmuxer=new Transmuxer(this.observer,a,r,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=eu++;const e=this.hls.config,s=fl(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:s,id:this.id,config:Dl(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const e=Jc[t||Zc];if(e&&1===e.clientCount--){const{worker:s,objectURL:i}=e;delete Jc[t||Zc],i&&self.URL.revokeObjectURL(i),s.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,s,i,r,n,a,o,l,d){var c,h;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:r.start,p=r.decryptdata,m=this.frag,v=!m||r.cc!==m.cc,y=!m||l.level!==m.level,E=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),A=!y&&(1===E||0===E&&(1===T||S&&T<=0)),_=self.performance.now();(y||E||0===r.stats.parsing.start)&&(r.stats.parsing.start=_),!n||!T&&A||(n.stats.parsing.start=_);const b=!(m&&(null==(c=r.initSegment)?void 0:c.url)===(null==(h=m.initSegment)?void 0:h.url)),L=new TransmuxState(v,A,o,y,g,b);if(!A||v||b){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id} playlist: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${A}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${b}`);const t=new TransmuxConfig(s,i,e,a,d);this.configureTransmuxer(t)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:t,decryptdata:p,chunkMeta:l,state:L},t instanceof ArrayBuffer?[t]:[]);else if(f){const e=f.push(t,p,l,L);tu(e)?e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(s){const e=s.flush(t);tu(e)?e.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}):this.handleFlushResult(e,t)}}transmuxerError(t,e,s){this.hls&&(this.error=t,this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):s&&s.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class BasePlaylistController extends Logger{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}destroy(){this.clearTimer(),this.hls=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,s){const i=null==e?void 0:e.renditionReports;if(i){let r=-1;for(let s=0;s<i.length;s++){const n=i[s];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){this.warn(`Could not construct new URL for Rendition Report: ${t}`),a=n.URI||""}if(a===t){r=s;break}a===t.substring(0,a.length)&&(r=s)}if(-1!==r){const t=i[r],n=parseInt(t["LAST-MSN"])||e.lastPartSn;let a=parseInt(t["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);a>=0&&t>e.partTarget&&(a+=1)}const o=s&&kl(s);return new HlsUrlParameters(n,a>=0?a:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}return t}playlistLoaded(t,e,s){const{details:i,stats:r}=e,n=i.fragments,a=self.performance.now(),o=r.loading.first?Math.max(0,Math.floor(a-r.loading.first)):0;i.advancedDateTime=Date.now()-o;const l=this.hls.config.timelineOffset;if(l!==i.appliedTimelineOffset){const t=Math.max(l||0,0);i.appliedTimelineOffset=t,n.forEach(e=>{null==e||e.setStart(e.playlistOffset+t)})}if(i.live||null!=s&&s.live){var d;const l="levelInfo"in e?e.levelInfo:e.track;i.reloaded(s);const c=null==(d=n[n.length-1])?void 0:d.type;if(i.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){const t=new Error(`${c} playlist ${l.id} hit max allowed unchanged reloads.`);this.warn(t);const{networkDetails:s,context:n}=e;return void this.hls.trigger(zn.ERROR,{type:Wn.NETWORK_ERROR,details:Yn.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:i.url,error:t,reason:t.message,level:e.level,parent:c,context:n,networkDetails:s,stats:r})}if(s){vc(s,i,this);const t=i.playlistParsingError;if(t){this.warn(t);const s=this.hls;if(!s.config.ignorePlaylistParsingErrors){const{networkDetails:n}=e;return void s.trigger(zn.ERROR,{type:Wn.NETWORK_ERROR,details:Yn.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:t,reason:t.message,level:e.level,parent:c,networkDetails:n,stats:r})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=r.loading.start);const h=this.hls.mainForwardBufferInfo,u=h?h.end-h.len:0,f=Tc(i,1e3*(i.edge-u));i.requestScheduled+f<a?i.requestScheduled=a:i.requestScheduled<=a&&(i.requestScheduled+=f);const g=e.deliveryDirectives;if(this.log(`live playlist ${t} ${i.advanced?`REFRESHED ${i.lastPartSn} - ${i.lastPartIndex}`:i.updated?"UPDATED":`MISSED (received ${i.lastPartSn} - ${i.lastPartIndex}${g?` | requested ${g.msn} - ${g.part}`:""})`}`),!this.canLoad||!i.live)return;let p,m,v;if(i.canBlockReload&&i.advanced){const t=this.hls.config.lowLatencyMode,r=i.lastPartSn,n=i.endSN,o=i.lastPartIndex,d=r===n;-1!==o?d?(m=n+1,v=t?0:o):(m=r,v=t?o+1:i.maxPartIndex):m=n+1;const c=i.age,h=c+i.ageHeader;let u=Math.min(h-i.partTarget,1.5*i.targetduration);if(u>0){if(h>3*i.targetduration)this.log(`Playlist last advanced ${c.toFixed(2)}s ago. Omitting segment and part directives.`),m=void 0,v=void 0;else if(null!=s&&s.tuneInGoal&&h-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${u} with playlist age: ${i.age}`),u=0;else{const t=Math.floor(u/i.targetduration);if(m+=t,void 0!==v){v+=Math.round(u%i.targetduration/i.partTarget)}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${c.toFixed(2)}s goal: ${u} skip sn ${t} to part ${v}`)}i.tuneInGoal=u}if(p=this.getDeliveryDirectives(i,e.deliveryDirectives,m,v),t||!d)return i.requestScheduled=a,void this.loadingPlaylist(l,p)}else(i.canBlockReload||i.canSkipUntil)&&(p=this.getDeliveryDirectives(i,e.deliveryDirectives,m,v));p&&void 0!==m&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(f-2*o,f/2)),this.scheduleLoading(l,p,i)}else this.clearTimer()}scheduleLoading(t,e,s){const i=s||t.details;if(!i)return void this.loadingPlaylist(t,e);const r=self.performance.now(),n=i.requestScheduled;if(r>=n)return void this.loadingPlaylist(t,e);const a=n-r;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),a)}getDeliveryDirectives(t,e,s,i){let r=kl(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(s=e.msn,i=e.part,r=Ll),new HlsUrlParameters(s,i,r)}checkRetry(t){const e=t.details,s=ba(t),i=t.errorAction,{action:r,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(r===Xl||!i.resolved&&r===zl);if(o){var l;if(n>=a.maxNumRetry)return!1;if(s&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{var d;const s=Da(null==(d=t.response)?void 0:d.code);if(this.clearTimer(),s)this.log("Waiting for connection (offline)"),t.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const t=ka(a,n);this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),t)}}t.levelRetry=!0,i.resolved=!0}return o}checkOfflineStatus(){this.clearTimer(),Da(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}function su(t,e){if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!iu(t[s].attrs,e[s].attrs))return!1;return!0}function iu(t,e,s){const i=t["STABLE-RENDITION-ID"];return i&&!s?i===e["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>t[s]!==e[s])}class BufferOperationQueue{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,s){if(null===this.queues||null===this.tracks)return;const i=this.queues[e];i.push(t),1!==i.length||s||this.executeNext(e)}appendBlocker(t){return new Promise(e=>{const s={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,t)})}prependBlocker(t){return new Promise(e=>{if(this.queues){const s={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(s)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const s=null==(e=t[0])?void 0:e.label;"async-blocker"===s||"async-blocker-prepend"===s?(t[0].execute(),t.splice(0,1)):"block-audio"===s&&t.splice(0,1)})}insertNext(t,e){null!==this.queues&&this.queues[e].splice(1,0,...t)}unblockAudio(){var t;null!==this.queues&&"block-audio"===(null==(t=this.current("audio"))?void 0:t.label)&&this.shiftAndExecuteNext("audio")}audioBlocking(){return null!==this.queues&&this.queues.audio.some(t=>"block-audio"===t.label)}executeNext(t){if(null===this.queues||null===this.tracks)return;const e=this.queues[t];if(e.length){const i=e[0];try{i.execute()}catch(e){var s;if(i.onError(e),null===this.queues||null===this.tracks)return;const r=null==(s=this.tracks[t])?void 0:s.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return null===t||null===e?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var e,s;return null!=(e=this.queues)&&e[t]||null!=(s=this.tracks)&&s[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const s=null==(e=this.tracks)?void 0:e[t],i=null==s?void 0:s.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map(t=>t.label).join(", "))||""}}const ru=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,nu="HlsJsTrackRemovedError";class HlsJsTrackRemovedError extends Error{constructor(t){super(t),this.name=nu}}function au(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}function ou(t){return"audio"===t?1:0}function lu(t,e){return`${t?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function du(t){return`${t.type}_${t.sn}_${t.level}`}function cu(t,e){const{start:s,end:i}=e;let r=0;for(let e=0;e<t.length;e++){const n=t[e];if(n.start>=i)break;const a=Math.max(s,n.start),o=Math.min(i,n.end);o>a&&(r+=o-a)}return r}function hu(t,e){return e.duration-t<=.05}class CapLevelController{constructor(t){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){const{hls:t}=this;t&&(t.on(zn.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.on(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(zn.BUFFER_CODECS,this.onBufferCodecs,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){const{hls:t}=this;t&&(t.off(zn.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.off(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(zn.BUFFER_CODECS,this.onBufferCodecs,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(t,e){if(!this.hls)return;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){const s=e.media;this.clientRect=null,this.hls&&(s instanceof HTMLVideoElement?(this.media=s,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(t,e){this.restrictedLevels=[],e.video&&this.startCapping(),this.onLevelsUpdated()}onLevelsUpdated(){if(this.hls)if((this.timer||this.observer)&&(Vn(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(void 0===this.observer&&void 0===this.timer){const t=this.hls.levels;t.length>1&&t.some(t=>!!t.videoCodec)&&this.startCapping()}}onBufferCodecs(t,e){e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls)return void(this.clientRect=null);const t=this.hls.levels;if(t.length>1){const e=this.hls,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=s,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}else 1===t.length&&this.stopCapping()}}getMaxLevel(t){if(!this.hls)return-1;const e=this.hls.levels;if(!e.length)return-1;const s=e.filter((e,s)=>this.isLevelAllowed(e)&&s<=t);return this.observer||(this.clientRect=null),CapLevelController.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}observe(){const t=self.ResizeObserver;t&&(this.observer=new t(t=>{var e;const s=null==(e=t[0])?void 0:e.contentRect;s&&(this.clientRect=s,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var t;this.timer||this.observer||null==(t=this.hls)||!t.config.capLevelToPlayerSize||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=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)return t;const{ignoreDevicePixelRatio:e,maxDevicePixelRatio:s}=this.hls.config;if(!e)try{t=self.devicePixelRatio}catch(t){}return Math.min(t,s)}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;const i=(t,e)=>!e||(t.width!==e.width||t.height!==e.height);let r=t.length-1;const n=Math.max(e,s);for(let e=0;e<t.length;e+=1){const s=t[e];if((s.width>=n||s.height>=n)&&i(s,t[e+1])){r=e;break}}return r}}var uu=class SfItem{constructor(t,e){Array.isArray(t)&&(t=t.map(t=>t instanceof SfItem?t:new SfItem(t))),this.value=t,this.params=e}};function fu(t,e,s,i){return new Error(`failed to ${t} "${r=e,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${s}`,{cause:i});var r}const gu="Bare Item";const pu=/[\x00-\x1f\x7f]+/;var mu=class{constructor(t){this.description=t}};function vu(t,e,s){return fu("serialize",t,e,s)}function yu(t){if(!1===ArrayBuffer.isView(t))throw vu(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function Eu(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw vu(t,"Integer");return t.toString()}function Tu(t){const e=ja(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw vu(t,"Decimal");const s=e.toString();return s.includes(".")?s:`${s}.0`}function Su(t){const e=(s=t).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw vu(e,"Token");return e}function Au(t){switch(typeof t){case"number":if(!Vn(t))throw vu(t,gu);return Number.isInteger(t)?Eu(t):Tu(t);case"string":return function(t){if(pu.test(t))throw vu(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return Su(t);case"boolean":return function(t){if("boolean"!=typeof t)throw vu(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${Eu(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return yu(t);if(t instanceof mu)return Su(t);default:throw vu(t,gu)}}function _u(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw vu(t,"Key");return t}function bu(t){return null==t?"":Object.entries(t).map(([t,e])=>!0===e?`;${_u(t)}`:`;${_u(t)}=${Au(e)}`).join("")}function Lu(t){return t instanceof uu?`${Au(t.value)}${bu(t.params)}`:Au(t)}function Ru(t,e={whitespace:!0}){if("object"!=typeof t||null==t)throw vu(t,"Dict");const s=t instanceof Map?t.entries():Object.entries(t),i=null!=e&&e.whitespace?" ":"";return Array.from(s).map(([t,e])=>{e instanceof uu==!1&&(e=new uu(e));let s=_u(t);var i;return!0===e.value?s+=bu(e.params):(s+="=",Array.isArray(e.value)?s+=`(${(i=e).value.map(Lu).join(" ")})${bu(i.params)}`:s+=Lu(e)),s}).join(`,${i}`)}function Iu(t,e){return Ru(t,e)}const ku=["url"],wu=["version","eventTargets","sid","transmissionMode"],Pu=["customData","headers"],Du=t=>t instanceof uu?new uu(Math.round(t.value),t.params):Math.round(t),Cu=t=>Array.isArray(t)?t.map(Du):Du(t),Ou=(t,e)=>Array.isArray(t)?t.map(t=>Ou(t,e)):t instanceof uu&&"string"==typeof t.value?new uu(Ou(t.value,e),t.params):(e.baseUrl&&(t=function(t,e){let s;try{s=new URL(t)}catch(e){return t}const i=new URL(e);if(s.origin!==i.origin)return t;const r=s.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1),a=Math.min(r.length,n.length);for(let t=0;t<a&&r[t]===n[t];t++)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+s.search+s.hash}(t,function(t){const e="string"==typeof t?new URL(t):t;return e.origin+e.pathname.substring(0,e.pathname.lastIndexOf("/")+1)}(e.baseUrl))),1===e.version?encodeURIComponent(t):t),Mu=t=>t instanceof uu?new uu(100*Math.round(t.value/100),t.params):100*Math.round(t/100),xu=t=>Array.isArray(t)?t.map(Mu):Mu(t),Fu={br:Cu,d:Cu,bl:xu,dl:xu,mtp:xu,nor:(t,e)=>{let s=t;return e.version>=2&&(t instanceof uu&&"string"==typeof t.value?s=new uu([t]):"string"==typeof t&&(s=[t])),Ou(s,e)},rtp:xu,tb:Cu},Nu=2,Uu="rr",Bu="bc",$u="e",Gu=Uu,Hu="ce",Ku=new Map([["ps","sta"],["pr","pr"],["c","cid"],["b","bg"],["bc","br"]]),Vu="event",ju="request",qu=["cen","e","h","ts"],Wu=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],Yu=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function zu(t){return Yu.test(t)}const Qu=new Set(Wu);function Xu(t){return Qu.has(t)||zu(t)}const Zu=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Ju=new Set(Zu);function tf(t){return Ju.has(t)}const ef=new Set(qu);const sf=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),rf=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],nf=new Set(rf);function af(t){return nf.has(t)||zu(t)}const of=new Set(["ot","sf","st","e","sta"]);function lf(t){return of.has(t)}function df(t){return"number"==typeof t?Vn(t):null!=t&&""!==t&&!1!==t}const cf={[Vu]:function(t){return Xu(t)||tf(t)||ef.has(t)},[ju]:Xu};function hf(t,e){if(Array.isArray(t)){let s;return e&&(s=t.find(t=>{var s;return(null==(s=t.params)?void 0:s.ot)===e})),s||(s=t[0]),hf(s)}return t instanceof uu?t.value:t}function uf(t,e={}){const s={};if(null==t||"object"!=typeof t)return s;const i=e.version||t.v||Nu,r=e.reportingMode||ju,n=1===i?function(t){const e={};for(const[i,r]of Object.entries(t))if(null!=r)if("nor"===i){const t=(Array.isArray(r)?r:[r])[0];var s;t instanceof uu?(e.nor=t.value,null!=(s=t.params)&&s.r&&(e.nrr=t.params.r)):e.nor=t}else sf.has(i)?e[i]=hf(r,t.ot):e[i]=r;else e[i]=r;return e}(t):t,a=1===i?af:cf[r];let o=Object.keys(n).filter(a);n.e&&n.e!==Uu&&(o=o.filter(t=>!tf(t)));const l=e.filter;"function"==typeof l&&(o=o.filter(l));const d=r===Vu;if(d){const t=n.e;o.includes("e")||null==t||o.push("e"),o.includes("ts")||o.push("ts"),o.includes("cen")||null==n.cen||"ce"!==t||o.push("cen");const e=t?Ku.get(t):void 0;e&&null!=n[e]&&!o.includes(e)&&o.push(e)}if(0===o.length)return s;i>1&&!o.includes("v")&&o.push("v");const c={version:i,reportingMode:r,baseUrl:e.baseUrl};o.sort();for(const t of o){var h,u;let r=n[t];const a=null!=(h=null==(u=e.formatters)?void 0:u[t])?h:Fu[t];if("function"==typeof a&&(r=a(r,c)),"v"===t){if(1===i)continue;r=i}if("pr"===t&&1===r&&(!d||"pr"!==n.e))continue;d&&"ts"===t&&!Vn(r)&&(r=Date.now());const o=d&&!1===r&&"bg"===t&&"b"===n.e;(df(r)||o)&&(lf(t)&&"string"==typeof r&&(r=new mu(r)),s[t]=r)}return s}const ff="CMCD-Object",gf="CMCD-Request",pf="CMCD-Session",mf="CMCD-Status",vf=gf,yf={ab:ff,br:ff,d:ff,lab:ff,lb:ff,ot:ff,tab:ff,tb:ff,tpb:ff,bl:gf,cs:gf,dfa:gf,dl:gf,ltc:gf,mtp:gf,nor:gf,nrr:gf,pb:gf,sn:gf,sta:gf,su:gf,tbl:gf,cid:pf,msd:pf,sf:pf,sid:pf,st:pf,v:pf,bg:mf,bs:mf,bsa:mf,bsd:mf,bsda:mf,cdn:mf,ec:mf,nr:mf,pr:mf,pt:mf,rtp:mf};function Ef(t,e){const s={};if(!t)return s;const i=Object.keys(t),r=e?(n=e,Object.keys(n).reduce((t,e)=>{var s;return null==(s=n[e])||s.forEach(s=>t[s]=e),t},{})):{};var n;for(const e of i){var a;const i=yf[e]||r[e]||vf;(null!=(a=s[i])?a:s[i]={})[e]=t[e]}return s}const Tf="CMCD";function Sf(t){return Iu(t,{whitespace:!1})}const Af=[...rf,...Wu,...Zu,...qu].filter((t,e,s)=>s.indexOf(t)===e),_f="m",bf="a",Lf="v",Rf="av",If="i",kf="tt",wf="s",Pf="p",Df="k",Cf="r",Of="a",Mf="e",xf="f",Ff="d",Nf="query",Uf="headers";function Bf(t,e,s){var i;const r=new Set(null!=(i=e.enabledKeys)?i:[]);return{version:e.version||Nu,reportingMode:t,filter:t=>r.has(t),baseUrl:s}}const $f=Object.is,Gf=t=>t,Hf=Array.from(Ku,([t,e])=>"br"===e?{event:t,field:e,equal:(t,e)=>void 0===t||void 0===e?t===e:function(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++){const i=t[s],r=e[s];if(i===r)continue;if("number"==typeof i||"number"==typeof r)return!1;if(i.value!==r.value)return!1;const n=i.params,a=r.params,o=n&&Object.keys(n)[0],l=a&&Object.keys(a)[0];if(o!==l)return!1;if(void 0!==o&&void 0!==l&&n&&a&&n[o]!==a[l])return!1}return!0}(t,e),snapshot:t=>t.slice()}:{event:t,field:e,equal:$f,snapshot:Gf}),Kf=new Map(Hf.map(t=>[t.event,t]));function Vf(t){const{url:e}=t,s=_a(t,ku);return fetch(e,s)}var jf=class{constructor(t,e=Vf){var s;this.timeOrigin=performance.timeOrigin||(null==(s=performance.timing)?void 0:s.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=function(t){const{version:e=Nu,eventTargets:s=[],sid:i=qa(),transmissionMode:r=Nf}=t;return Aa(Aa({},_a(t,wu)),{},{version:e,transmissionMode:r,sid:i,eventTargets:s.reduce((t,e)=>{var s,i,r;return null!=e&&e.url&&null!=(s=e.events)&&s.length&&t.push({version:e.version||Nu,enabledKeys:(null==(i=e.enabledKeys)?void 0:i.slice())||[],url:e.url,events:e.events.slice(),interval:null!=(r=e.interval)?r:30,batchSize:e.batchSize||1}),t},[])})}(t),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=e;for(const t of this.config.eventTargets)this.eventTargets.set(t,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((t,e)=>{if(this.disarmInterval(t),0===e.interval||!e.events.includes("t"))return;const s=()=>{this.recordTargetEvent(t,e,"t"),this.processEventTargets()};t.intervalId=setInterval(s,1e3*e.interval),s()})}stop(t=!1){t&&this.flush(),this.eventTargets.forEach(t=>{this.disarmInterval(t)})}flush(){this.processEventTargets(!0)}update(t){t.sid&&t.sid!==this.data.sid&&this.resetSession(),t.msd&&!isNaN(t.msd)&&(this.msd=t.msd),this.data=Aa(Aa(Aa({},this.data),t),{},{msd:void 0});for(const e of Hf)e.field in t&&!e.equal(this.data[e.field],this.lastEmitted[e.field])&&this.recordEvent(e.event)}recordEvent(t,e={}){const s=Kf.get(t);if(s){const t=s.field,i=e[t];void 0!==i&&Ta(this.data,{[t]:i});const r=this.data[t];if(void 0===r)return;if(s.equal(r,this.lastEmitted[t]))return;Ta(this.lastEmitted,{[t]:s.snapshot(r)})}this.eventTargets.forEach((s,i)=>{this.recordTargetEvent(s,i,t,e)}),this.processEventTargets()}recordTargetEvent(t,e,s,i={}){var r;if(!e.events.includes(s))return;const n=Aa(Aa(Aa({},this.data),i),{},{e:s,ts:null!=(r=i.ts)?r:Date.now(),sn:t.sn++});isNaN(this.msd)||t.msdSent||(n.msd=this.msd,t.msdSent=!0),t.queue.push(n)}recordResponseReceived(t,e={}){var s,i,r;const{request:n}=t,a=null!=(s=e.url)?s:null==n?void 0:n.url;if(!a)return;const o=new URL(a);o.searchParams.delete(Tf);const l={url:o.toString(),rc:t.status},d=t.resourceTiming;d&&(null!=d.startTime&&(l.ts=Math.round(this.timeOrigin+d.startTime),null!=d.responseStart&&(l.ttfb=Math.round(d.responseStart-d.startTime))),null!=d.duration&&(l.ttlb=Math.round(d.duration)));const c=null!=(i=null==(r=n.customData)?void 0:r.cmcd)?i:{};this.recordEvent(Uu,Aa(Aa(Aa({},c),l),e))}applyRequestReport(t){var e;return null!=(e=this.createRequestReport(t))?e:t}isRequestReportingEnabled(){var t;return!(null==(t=this.config.enabledKeys)||!t.length)}createRequestReport(t,e){var s;const{customData:i={},headers:r={}}=t,n=Aa(Aa({},_a(t,Pu)),{},{headers:Aa({},r),customData:Aa(Aa({},i),{},{cmcd:{}})});if(null==(s=this.config.enabledKeys)||!s.length||!n.url)return n;const a=new URL(n.url),o=Aa(Aa(Aa({},this.data),e),{},{sn:this.requestTarget.sn++}),l=Bf(ju,this.config,n.url);isNaN(this.msd)||this.requestTarget.msdSent||(o.msd=this.msd,this.requestTarget.msdSent=!0);const d=n.customData.cmcd=uf(o,l);switch(this.config.transmissionMode){case Nf:const t=Sf(d);t&&(a.searchParams.set(Tf,t),n.url=a.toString());break;case Uf:Ta(n.headers,function(t,e){const s={},i=Ef(t,e);for(const[t,e]of Object.entries(i)){const i=Iu(e,{whitespace:!1});i&&(s[t]=i)}return s}(d,l.customHeaderMap))}return n}processEventTargets(t=!1){let e=!1;this.eventTargets.forEach((s,i)=>{const{queue:r}=s;if(!r.length)return;if(r.length<i.batchSize&&!t)return;const n=t?r.length:i.batchSize,a=r.splice(0,n);this.sendEventReport(i,a).catch(()=>{s.queue.unshift(...a)}),e||(e=r.length>0)}),e&&this.processEventTargets()}async sendEventReport(t,e){const s=Bf(Vu,t),{status:i}=await this.requester({url:t.url,method:"POST",headers:{"Content-Type":"application/cmcd"},body:e.map(t=>function(t,e={}){return t?Sf(uf(t,e)):""}(t,s)).join("\n")+"\n"});if(410===i)this.disposeEventTarget(t);else if(429===i||i>499&&i<600)throw new Error(`Event report failed with status ${i}`)}disarmInterval(t){clearInterval(t.intervalId),t.intervalId=void 0}disposeEventTarget(t){const e=this.eventTargets.get(t);e&&(this.disarmInterval(e),this.eventTargets.delete(t))}resetSession(){this.eventTargets.forEach(t=>t.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}};const qf="h",Wf="v",Yf="l",zf="ll";const Qf=["includeKeys"];function Xf(t){return Object.keys(t).every(zu)}function Zf(t,e,s,i){t&&Object.keys(e).forEach(r=>{const n=t.filter(t=>t.groupId===r).map(t=>{const n=Ta({},t);return n.details=void 0,n.attrs=new AttrList(n.attrs),n.url=n.attrs.URI=Jf(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=e[r],n.attrs["PATHWAY-ID"]=i,n});t.push(...n)})}function Jf(t,e,s,i){if(e){const{[s]:t}=i;if(t){const s=t[e];if(s)return s}}const{HOST:r,PARAMS:n}=i,a=new self.URL(t);return r&&(a.hostname=r),n&&Object.keys(n).sort().forEach(t=>{t&&Al(a,t,n[t])}),a.href}class LicenseAndKeysRequestEmitter{constructor(){this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new Xc,this.error=void 0,this.ok=void 0}get errored(){return this.error}set errored(t){this.error=t,this.emitter.eventNames().length&&this.emitter.emit("error",t)}get hasListeners(){return this.emitter.eventNames().length>0}get resolved(){return this.ok}resolve(){this.ok=!0,this.emitter.emit("resolved")}get useable(){return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise((t,e)=>{this.emitter.on("error",e),this.emitter.on("resolved",t)})}reset(){this.emitter.removeAllListeners();const t=this.licenseXhr;t&&(t.readyState!==XMLHttpRequest.DONE&&t.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=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}}class EMEController extends Logger{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysQueue=EMEController.CDMCleanupPromise?[EMEController.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:e,initData:s}=t,i=`"${t.type}" event: init data type: "${e}"`;if(this.log(i),null!==s){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=qd(this.config));const e=t.map(jd).filter(t=>!!t);this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then(r=>{let n;const a=Kd(r),o=this.activeLevelKeys();if(a===Ud.FAIRPLAY&&"sinf"===e)try{const t=ho(new Uint8Array(s)),e=Mo(co(JSON.parse(t).sinf));if(!e)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");n=new Uint8Array(e.subarray(8,24))}catch(t){return void this.warn(`${i} Failed to parse sinf: ${t}`)}else if(a===Ud.PLAYREADY)n=zd(new Uint8Array(s));else if(a===Ud.WIDEVINE){const t=Vo(s).filter(t=>t.systemId===Vd);if(t.length){var l;const e=t[0];n=null!=(l=e.kids)&&l.length?e.kids[0]:null}}let d;if(n){const t=oo(n);for(let i=0;i<o.length;i++){const r=o[i];if(r.keyId&&(Pd(n,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(t))){r.pssh||(r.scheme=e,r.pssh=new Uint8Array(s),r.keyId=n,LevelKey.setKeyIdForUri(r.uri,n)),d=this.getSessionForKey(r,"encrypted-event-key-match");break}}}if(!d){var c,h;if(o.length)return(c=o[0]).scheme||(c.scheme=e),(h=o[0]).pssh||(h.pssh=new Uint8Array(s)),this.getSessionForKey(o[0],"encrypted-event-no-match");if(n)throw new Error(`Key ID ${oo(n)} not encountered in playlist`);this.log(`Ignoring "${t.type}" event - could not determine keyId`)}return d}).catch(t=>this.handleError(t))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){const{hls:t}=this;t&&(t.on(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(zn.MEDIA_DETACHED,this.onMediaDetached,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(zn.DESTROYING,this.onDestroying,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(zn.MEDIA_DETACHED,this.onMediaDetached,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(zn.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(t){if(!this.hls)return Promise.reject(new Error("destroyed"));const e=this.hls.levels,s=(t,e,s)=>!!t&&s.indexOf(t)===e,i=e.map(t=>t.audioCodec).filter(s),r=e.map(t=>t.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((e,s)=>{const n=t=>{const a=t.shift();this.getMediaKeysPromise(a,i,r).then(t=>e({keySystem:a,mediaKeys:t})).catch(e=>{t.length?n(t):s(e instanceof EMEKeyError?e:new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:Yn.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===Wd&&"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){var i;const r=function(t,e,s,i){let r;switch(t){case Ud.FAIRPLAY:r=["cenc","sinf"];break;case Ud.WIDEVINE:case Ud.PLAYREADY:r=["cenc"];break;case Ud.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,s,i){return[{initDataTypes:t,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(t=>({contentType:`audio/mp4; codecs=${t}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:s.map(t=>({contentType:`video/mp4; codecs=${t}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}(r,e,s,i)}(t,e,s,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[t],a=null==(i=n)?void 0:i.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${Dl(r)}`),a=this.requestMediaKeySystemAccess(t,r);const e=n=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch(e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)}),a.then(s=>{this.throwIfDestroyed(),this.log(`Access for key-system "${s.keySystem}" obtained`);const i=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const r=e.mediaKeys=s.createMediaKeys().then(s=>(this.log(`Media-keys created for "${t}"`),e.hasMediaKeys=!0,i.then(e=>e?this.setMediaKeysServerCertificate(s,t,e):s)));return r.catch(e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)}),r})}return a.then(()=>n.mediaKeys)}getMediaKeySessionContext(t,e,s,i){const{mediaKeySessions:r}=this,n=` key-session "${t}" keyId: ${oo(s.keyId||[])} keyUri: ${s.uri} for "${i}"`;for(let t=0;t<r.length;t++){const e=r[t];if(!e.initialized&&e.createdFor.levelKey.uri===s.uri)return this.log(`Reusing${n}`),e}this.log(`Creating${n}`);const a=e.createSession(),o={keySystem:t,mediaKeys:e,mediaKeysSession:a,keyRequests:{},keyStatuses:{},createdFor:{levelKey:s,reason:i},initialized:!1};return r.push(o),o}resetMediaKeys(){var t;const e=null==(t=this.mediaKeySessions[0])?void 0:t.keySystem,s=this.keySystemAccessPromises[e];s&&(this.log("reset mediaKeys"),this.mediaKeys=null,s.hasMediaKeys=!1,delete s.mediaKeys,delete this.keySystemAccessPromises[e])}updateKeySession(t,e,s){const i=t.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${oo(e.keyId||[])}\n } (data length: ${s.byteLength})`),i.update(s)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>jd(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:t,mediaKeys:e})=>this.attemptSetMediaKeys(t,e))}selectKeySystem(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:t})=>{const e=jd(t);if(!e)throw new Error(`Unable to find format for key-system "${t}"`);return 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){const e=qd(this.config),s=t.map(Kd).filter(t=>!!t&&-1!==e.indexOf(t));return this.selectKeySystem(s)}loadClear(t,e,s){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(e.length)for(let i=0,r=e.length;i<r;i++){const n=e[i];if(t.cc<=n.cc&&(!pa(t)||!pa(n)||t.sn<n.sn)||!s&&i==r-1)return this.selectKeySystemFormat(n).then(t=>{if(!this.hls)return;n.setKeyFormat(t);const e=Kd(t);return e?this.getKeySystemAccess([e]):void 0})}if(this.config.requireKeySystemAccessOnStart){const t=qd(this.config);if(t.length)return this.getKeySystemAccess(t)}}return null}getKeyStatus(t){const{mediaKeySessions:e}=this;for(let s=0;s<e.length;s++){const i=tg(t,e[s]);if(i)return i}}loadKey(t){const e=t.decryptdata,s=this.getKeyStatus(e);if("internal-error"===s){const i=eg(s,e);return i.data.frag=t,this.error(`${i.message} (${oo(e.keyId||[])})`),Promise.reject(i)}const i=t.type,r=this.activeKeys,n=r[i];n&&!e.matches(n.decryptdata)&&(r.previous||(r.previous=[]),r.previous.push(n),delete r[i]),r[i]||(r[i]=t);for(let t=this.mediaKeySessions.length;t--;){const s=this.mediaKeySessions[t];if(e.keyId&&"expired"===s.keyStatuses[oo(e.keyId)])return this.renewKeySession(e,s)}return this.updateUsablePromise(e,"playlist-key",t)}renewKeySession(t,e){return this.resetMediaKeys(),this.removeSession(e).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(t,"expired")))}updateUsablePromise(t,e,s){const i=this.getSessionForKey(t,e);return i.catch(t=>this.handleError(t,s)),i.then(e=>t)}getSessionForKey(t,e){const s=this.findContextForKey(t);if(void 0!==s)return Promise.resolve(s);const i=t.uri,r=this.sessionSetupByUri[i];let n;n=void 0===r?this.resolveSessionForKey(t,e):r.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(t,e))),this.sessionSetupByUri[i]=n;const a=()=>{this.sessionSetupByUri[i]===n&&delete this.sessionSetupByUri[i]};return n.then(a,a),n}findContextForKey(t){const{mediaKeySessions:e}=this;for(let s=e.length;s--;){const i=e[s];if(tg(t,i))return i}}resolveSessionForKey(t,e){return this.getKeySystemForKeyPromise(t).then(({keySystem:s,mediaKeys:i})=>{this.throwIfDestroyed();for(let s=this.mediaKeySessions.length;s--;){const i=this.mediaKeySessions[s];if(tg(t,i))return i;const r=this.getUsableKeyPromise(i,t,e);if(r)return r}return this.attemptSetMediaKeys(s,i).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(s,i,t,e))).then(s=>{this.throwIfDestroyed();const i=t.scheme||"cenc",r=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(s,t,i,r,e)})})}getUsableKeyPromise(t,e,s){const i=t.keyRequests[e.uri];if(i)return this.log(`Waiting for usable key (${s} keyId: ${function(t){if(t.keyFormat===$d)return t.uri;if(null===t.keyId)throw new Error("keyId is null");return oo(t.keyId)}(e)} format: "${e.keyFormat}" URI: ${e.uri})`),i.useable.then(()=>t)}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,e){if(this.hls)if(t instanceof EMEKeyError){e&&(t.data.frag=e);const s=t.data.decryptdata;this.error(`${t.message}${s?` (${oo(s.keyId||[])})`:""}`),this.hls.trigger(zn.ERROR,t.data)}else this.error(t.message),this.hls.trigger(zn.ERROR,{type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const e=Kd(t.keyFormat),s=e?[e]:qd(this.config);return this.attemptKeySystemAccess(s)}getKeySystemSelectionPromise(t){if(t.length||(t=qd(this.config)),0===t.length)throw new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Dl({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}activeLevelKeys(){const t=this.activeKeys,e=(t.previous||[]).map(t=>t.decryptdata);return t.audio&&e.unshift(t.audio.decryptdata),t.main&&e.unshift(t.main.decryptdata),e}attemptSetMediaKeys(t,e){if(this.mediaResolved=void 0,this.mediaKeys===e)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(e):new Promise((t,s)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return s(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=e,this.media.setMediaKeys(e).then(t).catch(s)}}));return this.mediaKeys=e,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${t}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(t=>-1===s.indexOf(t))})}filterInitData(t,e,s,i,r){var n;const a=null==(n=this.config.drmSystems)||null==(n=n[t.keySystem])?void 0:n.generateRequest;if(a)try{const n=a.call(this.hls,s,i,Ta({},t,{decryptdata:e,reason:r}),r);if(!n)throw new Error("Invalid response from configured generateRequest filter");e.scheme=n.initDataType?n.initDataType:"cenc";const o=n.initData?n.initData:null;return e.pssh=o?new Uint8Array(o):null,n}catch(t){var o;if(this.warn(t.message),null!=(o=this.hls)&&o.config.debug)throw t}return{initDataType:s,initData:i}}generateRequestWithPreferredKeySession(t,e,s,i,r){const n=this.getUsableKeyPromise(t,e,r);if(n)return n;const a=this.filterInitData(t,e,s,i,r);if(a&&(i=a.initData?a.initData:null,s=a.initDataType),null===i)return r.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${r}"`)):(this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t));const o=e.uri,l=new LicenseAndKeysRequestEmitter;t.keyRequests[o]=l;const d=s=>{const i=t.mediaKeysSession;if(!i){const t=new Error("invalid state");return void(l.errored=t)}const{messageType:r,message:n}=s;l.status=r,this.log(`"${r}" message event for session "${i.sessionId}" message size: ${n.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(t,e,n).catch(e=>{l.errored=e,l.hasListeners||this.handleError(e),this.removeSession(t)}):"license-release"===r?t.keySystem===Ud.FAIRPLAY&&this.updateKeySession(t,e,Md("acknowledged")).then(()=>this.removeSession(t)).catch(t=>this.handleError(t)):this.warn(`unhandled media key message type "${r}"`)};l.onmessage=d,Dc(t.mediaKeysSession,"message",d);return this.generateRequest(t,e,s,i,r,!1)}generateRequest(t,e,s,i,r,n){if(n){const n=this.filterInitData(t,e,s,i,r);n&&(i=n.initData?n.initData:i,s=n.initDataType)}const a=e.uri,o=t.keyRequests[a],l=oo(e.keyId||[]),d=t=>{let s;t.startsWith("usable")?o.resolve():"internal-error"===t||"output-restricted"===t||"output-downscaled"===t?s=eg(t,e):"expired"===t?s=new Error(`key expired (keyId: ${l})`):"released"===t?s=new Error("key released"):"status-pending"===t||this.warn(`unhandled key status change "${t}" (keyId: ${l})`),s&&(o.errored=s,o.hasListeners||this.handleError(s))},c=s=>{if(!t.mediaKeysSession){const t=new Error("invalid state");return void(o.errored=t)}const i=t.keyStatuses=this.getKeyStatuses(t);if(!Object.keys(i).some(t=>"status-pending"!==i[t]))return;const r=this.activeLevelKeys();for(let s=0;s<r.length;s++){const a=oo(r[s].keyId||[]);if("expired"===i[a]){var n;this.log(`Expired key ${Dl(i)} in key-session "${null==(n=t.mediaKeysSession)?void 0:n.sessionId}"`),this.renewKeySession(e,t).catch(t=>this.handleError(t));break}}let a=i[l];if(a)d(a);else{var c;const s=1e3;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(c=t.keyStatusTimeouts)[l]||(c[l]=self.setTimeout(()=>{var i;if(!t.mediaKeysSession)return;const r=this.getKeyStatus(e);var n;if(r&&"status-pending"!==r)return this.log(`No status for keyId ${l} in key-session "${null==(n=t.mediaKeysSession)?void 0:n.sessionId}". Using session key-status ${r} from other session.`),d(r);this.log(`key status for ${l} in key-session "${null==(i=t.mediaKeysSession)?void 0:i.sessionId}" timed out after ${s}ms`),a="internal-error",d(a)},s)),this.log(`No status for keyId ${l} (${Dl(i)}).`)}};o.onkeystatuseschange=c,Dc(t.mediaKeysSession,"keystatuseschange",c);const h=o.useable;return this.log(`Generating key-session request for "${r}" keyId: ${l} URI: ${a} (init data type: ${s} length: ${i.byteLength})`),o.status="started",t.initialized=!0,t.mediaKeysSession.generateRequest(s,i).then(()=>{var e;o.status="generated",this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${l} URI: ${a}`)}).catch(t=>{throw this.log(`mediaKeysSession.generateRequest failed: ${t}`),new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>h).catch(e=>{var s;this.log(`mediaKeysSession.generateRequest failed: ${e}`);const i=null==(s=e.data)?void 0:s.details;return i!==Yn.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED&&i!==Yn.KEY_SYSTEM_STATUS_INTERNAL_ERROR||!Object.keys(t.keyStatuses).some(e=>"usable"===t.keyStatuses[e])?this.removeSession(t).then(()=>{throw e}):(this.handleError(e),t)}).then(()=>t)}getKeyStatuses(t){const e={},s=t.mediaKeysSession.sessionId;return t.mediaKeysSession.keyStatuses.forEach((i,r)=>{if("string"==typeof r&&"object"==typeof i){const t=r;r=i,i=t}const n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(t.keySystem===Ud.PLAYREADY&&16===n.length){const t=oo(n);e[t]=i,xd(n)}const a=oo(n);this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${s}"`),e[a]=i}),e}fetchServerCertificate(t){const e=this.config,s=new(0,e.loader)(e),i=function(t,e){const{drmSystems:s}=e,i=null==s?void 0:s[t];if(i)return i.serverCertificateUrl}(t,e);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise((r,n)=>{const a={type:oa,responseType:"arraybuffer",url:i},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,e,s,i)=>{r(t.data)},onError:(e,s,r,o)=>{n(new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:Aa({url:a.url,data:void 0},e)},`"${t}" certificate request failed (${i}). Status: ${e.code} (${e.text})`))},onTimeout:(e,s,r)=>{n(new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(t,e,s)=>{n(new Error("aborted"))}};s.load(a,l,d)})):(this.log(`No Server Certificate in config.drmSystems["${t}"]`),Promise.resolve())}setMediaKeysServerCertificate(t,e,s){return new Promise((i,r)=>{t.setServerCertificate(s).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${s.byteLength}) on "${e}"`),i(t)}).catch(t=>{r(new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))})})}renewLicense(t,e,s){return this.requestLicense(t,e,new Uint8Array(s)).then(s=>this.updateKeySession(t,e,new Uint8Array(s)).catch(t=>{throw new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(t,e){const s=ho(new Uint16Array(e.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const i=(new DOMParser).parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let s=0,i=r.length;s<i;s++){var n,a;e=r[s];const i=null==(n=e.querySelector("name"))?void 0:n.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;i&&o&&t.setRequestHeader(i,o)}}const o=i.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Md(atob(l))}setupLicenseXHR(t,e,s,i,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>(this.throwIfDestroyed(),n.call(this.hls,t,e,Aa(Aa({},s),{},{decryptdata:i}),r))).catch(a=>{if(!s.mediaKeysSession)throw a;return t.open("POST",e,!0),n.call(this.hls,t,e,Aa(Aa({},s),{},{decryptdata:i}),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,s){return new Promise((i,r)=>{const n=function(t,e){const{drmSystems:s,widevineLicenseUrl:i}=e,r=null==s?void 0:s[t];if(r)return r.licenseUrl;if(t===Ud.WIDEVINE&&i)return i}(t.keySystem,this.config);if(!n)return r(new Error(`no license server URL configured for key-system "${t.keySystem}"`));const a=t.keyRequests[e.uri];if(!a)return r(new Error("License emitter removed"));this.log(`Sending license request to URL: ${n}`);const o=this.config.keyLoadPolicy.default,l=new XMLHttpRequest;l.responseType="arraybuffer",l.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return r(new Error("invalid state"));if(4===l.readyState)if(200===l.status){a.requestErrors=[];let s=l.response;this.log(`License received ${s instanceof ArrayBuffer?s.byteLength:s}`);const r=this.config.licenseResponseCallback;if(r)try{s=r.call(this.hls,l,n,Aa(Aa({},t),{},{decryptdata:e}))}catch(t){this.error(t)}i(s)}else{const d=o.errorRetry,c=d?d.maxNumRetry:0;if(a.requestErrors.push({status:l.status,message:l.statusText}),a.requestErrors.length>c||l.status>=400&&l.status<500)r(new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:Yn.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e,fatal:!0,networkDetails:l,response:{url:n,data:void 0,code:l.status,text:l.statusText}},`License Request XHR failed (${n}). Status: ${l.status} (${l.statusText})`));else{const n=c-a.requestErrors.length;this.warn(`Retrying license request, ${n} attempts left`),this.requestLicense(t,e,s).then(i,r)}}},a.licenseXhr&&a.licenseXhr.readyState!==XMLHttpRequest.DONE&&a.licenseXhr.abort(),a.licenseXhr=l,this.setupLicenseXHR(l,n,t,e,s).then(({xhr:e,licenseChallenge:s})=>{t.keySystem==Ud.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(e,s)),e.send(s)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const s=e.media;this.media=s,Dc(s,"encrypted",this.onMediaEncrypted),Dc(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const t=this.media;t&&(Cc(t,"encrypted",this.onMediaEncrypted),Cc(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};const e=this.mediaResolved;if(e&&e(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,LevelKey.clearKeyUriToKeyIdMap();const r=i.length;EMEController.CDMCleanupPromise=Promise.all(i.map(t=>this.removeSession(t)).concat((null==s||null==(t=s.setMediaKeys(null))?void 0:t.catch(t=>{this.log(`Could not clear media keys: ${t}`),this.hls&&this.hls.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})}))||Promise.resolve())).catch(t=>{this.log(`Could not close sessions and clear media keys: ${t}`),this.hls&&this.hls.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear(),this.keyFormatPromise=null}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),this.keyFormatPromise.catch(()=>{})}}removeSession(t){const{mediaKeysSession:e}=t;if(e){this.log(`Remove licenses and keys and close session "${e.sessionId}"`),Object.keys(t.keyRequests).forEach(s=>{const i=t.keyRequests[s];i.onmessage&&e.removeEventListener("message",i.onmessage),i.onkeystatuseschange&&e.removeEventListener("keystatuseschange",i.onkeystatuseschange),i.reset(),t.keyRequests[s]=void 0}),t.mediaKeysSession=void 0;const s=this.mediaKeySessions.indexOf(t);s>-1&&this.mediaKeySessions.splice(s,1);const{keyStatusTimeouts:i}=t;i&&Object.keys(i).forEach(t=>self.clearTimeout(i[t]));const{drmSystemOptions:r}=this.config,n=function(t){var e;return!(!t||"persistent-license"!==t.sessionType&&(null==(e=t.sessionTypes)||!e.some(t=>"persistent-license"===t)))}(r)?new Promise((t,s)=>{self.setTimeout(()=>s(new Error("MediaKeySession.remove() timeout")),8e3),e.remove().then(t).catch(s)}):Promise.resolve();return n.catch(t=>{this.log(`Could not remove session: ${t}`),this.hls&&this.hls.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})}).then(()=>e.close()).then(()=>e.closed).catch(t=>{this.log(`Could not close session: ${t}`),this.hls&&this.hls.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})})}return Promise.resolve()}}function tg(t,e){const s=t.keyId,i=e.mediaKeysSession;if(s&&i){const t=e.mediaKeysSession.keyStatuses;if(t.size)return t.has(s)?t.get(s):e.keyStatuses[oo(s)]}}function eg(t,e){const s="output-restricted"===t,i=s?Yn.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Yn.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new EMEKeyError({type:Wn.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},s?"HDCP level output restricted":`key status changed to "${t}"`)}EMEController.CDMCleanupPromise=void 0;var sg=function(){if(null!=Nd&&Nd.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 i(t){return s(e,t)}function r(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,h=e,u=n,f=a,g=null,p="",m=!0,v="auto",y="start",E=50,T="middle",S=50,A="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return d},set:function(t){d=""+t}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return c},set:function(t){c=!!t}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return h},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");h=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return p},set:function(e){const i=function(e){return s(t,e)}(e);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");p=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return m},set:function(t){m=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},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",r({},l,{get:function(){return T},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return A},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");A=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 ig(t){function e(t,e,s,i){return 3600*(0|t)+60*(0|e)+(0|s)+parseFloat(i||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 i=0;i<s.length;++i)if(e===s[i]){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 rg(t,e,s,i){const r=i?t.split(i):[t];for(const t in r){if("string"!=typeof r[t])continue;const i=r[t].split(s);if(2!==i.length)continue;e(i[0],i[1])}}const ng=new sg(0,0,""),ag="middle"===ng.align?"middle":"center";function og(t,e,s){const i=t;function r(){const e=ig(t);if(null===e)throw new Error("Malformed timestamp: "+i);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=r(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);t=t.slice(3),n(),e.endTime=r(),n(),function(t,e){const i=new Settings;rg(t,function(t,e){let r;switch(t){case"region":for(let r=s.length-1;r>=0;r--)if(s[r].id===e){i.set(t,s[r].region);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),i.integer(t,r[0]),i.percent(t,r[0])&&i.set("snapToLines",!1),i.alt(t,r[0],["auto"]),2===r.length&&i.alt("lineAlign",r[1],["start",ag,"end"]);break;case"position":r=e.split(","),i.percent(t,r[0]),2===r.length&&i.alt("positionAlign",r[1],["start",ag,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",ag,"end","left","right"])}},/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");let r=i.get("line","auto");"auto"===r&&-1===ng.line&&(r=-1),e.line=r,e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100),e.align=i.get("align",ag);let n=i.get("position","auto");"auto"===n&&50===ng.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function lg(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=lg(t);s<t.length&&"\r"!==t[s]&&"\n"!==t[s];)++s;const i=t.slice(0,s);return"\r"===t[s]&&++s,"\n"===t[s]&&++s,e.buffer=t.slice(s),i}function i(t){rg(t,function(t,e){},/:/)}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 i=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==i||!i[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)?i(t):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 sg(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{og(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}}function dg(t){let e=5381,s=t.length;for(;s;)e=33*e^t.charCodeAt(--s);return(e>>>0).toString()}const cg=/\r\n|\n\r|\n|\r/g,hg="Missing initPTS for VTT ";function ug(t,e,s){return dg(t.toString())+dg(e.toString())+dg(s)}function fg(t,e,s,i,r,n,a){const o=new VTTParser,l=Ja(new Uint8Array(t)).trim().replace(cg,"\n").split("\n"),d=[],c=e?function(t,e=1){return Gh(t,9e4,1/e)}(e.baseTime,e.timescale):0;let h,u="00:00.000",f=0,g=0,p=!1,m=!0;o.oncue=function(t){const n=s[i];let a=s.ccOffset;const o=(f-c)/9e4;if(p){if(null!=n&&n.new&&(a=s.ccOffset=n.start),o){if(!e)return void(h=new Error(hg+"MPEGTS"));a=o-s.presentationOffset}}else{if(!e)return void(h=new Error(hg+"without X-TIMESTAMP-MAP"));a=-e.baseTime/e.timescale}const l=t.endTime-t.startTime,u=qh(9e4*(t.startTime+a-g),9e4*r)/9e4;t.startTime=Math.max(u,0),t.endTime=Math.max(u+l,0);const m=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(m)),t.id?i&&(t.id=`hlsjscc${i}_${t.id}`):t.id=ug(t.startTime,t.endTime,m),t.endTime>0&&d.push(t)},o.onparsingerror=function(t){h=t},o.onflush=function(){h?a(h):n(d)},l.forEach(t=>{if(m){if(t.startsWith("X-TIMESTAMP-MAP=")){m=!1,p=!0,t.slice(16).split(",").forEach(t=>{t.startsWith("LOCAL:")?u=t.slice(6):t.startsWith("MPEGTS:")&&(f=parseInt(t.slice(7)))});try{g=function(t){let e=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),i=parseInt(t.slice(-9,-7)),r=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(Vn(e)&&Vn(s)&&Vn(i)&&Vn(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*s,e+=6e4*i,e+=36e5*r,e}(u)/1e3}catch(t){h=t}return}""===t&&(m=!1)}o.parse(t+"\n")}),o.flush()}const gg="stpp.ttml.im1t",pg=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,mg=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,vg={left:"start",center:"center",right:"end",start:"start",end:"end"};function yg(t,e,s,i){const r=bo(new Uint8Array(t),["mdat"]);if(0===r.length)return void i(new Error("Could not parse IMSC1 mdat"));const n=r.map(t=>Ja(t)),a=function(t,e,s=1,i=!1){return Gh(t,e,1/s,i)}(e.baseTime,1,e.timescale);try{n.forEach(t=>s(function(t,e){const s=new DOMParser,i=s.parseFromString(t,"text/xml"),r=i.getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:1},a=Object.keys(n).reduce((t,e)=>(t[e]=r.getAttribute(`ttp:${e}`)||n[e],t),{});!r.getAttribute("ttp:tickRate")&&r.getAttribute("ttp:frameRate")&&(a.tickRate=Number(a.frameRate)*Number(a.subFrameRate));const o="preserve"!==r.getAttribute("xml:space"),l=Tg(Eg(r,"styling","style")),d=Tg(Eg(r,"layout","region")),c=Eg(r,"body","[begin]");return[].map.call(c,t=>{const s=Sg(t,o);if(!s||!t.hasAttribute("begin"))return null;const i=bg(t.getAttribute("begin"),a),r=bg(t.getAttribute("dur"),a);let n=bg(t.getAttribute("end"),a);if(null===i)throw _g(t);if(null===n){if(null===r)throw _g(t);n=i+r}const c=new sg(i-e,n-e,s);c.id=ug(c.startTime,c.endTime,c.text);const h=function(t,e,s){const i="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&s.hasOwnProperty(a)&&(r=s[a]);return n.reduce((s,n)=>{const a=Ag(e,i,n)||Ag(t,i,n)||Ag(r,i,n);return a&&(s[n]=a),s},{})}(d[t.getAttribute("region")],l[t.getAttribute("style")],l),{textAlign:u}=h;if(u){const t=vg[u];t&&(c.lineAlign=t),c.align=u}return Ta(c,h),c}).filter(t=>null!==t)}(t,a)))}catch(t){i(t)}}function Eg(t,e,s){const i=t.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(s)):[]}function Tg(t){return t.reduce((t,e)=>{const s=e.getAttribute("xml:id");return s&&(t[s]=e),t},{})}function Sg(t,e){return[].slice.call(t.childNodes).reduce((t,s,i)=>{var r;return"br"===s.nodeName&&i?t+"\n":null!=(r=s.childNodes)&&r.length?Sg(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function Ag(t,e,s){return t&&t.hasAttributeNS(e,s)?t.getAttributeNS(e,s):null}function _g(t){return new Error(`Could not parse ttml timestamp ${t}`)}function bg(t,e){if(!t)return null;let s=ig(t);return null===s&&(pg.test(t)?s=function(t,e){const s=pg.exec(t),i=(0|s[4])+(0|s[5])/e.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+i/e.frameRate}(t,e):mg.test(t)&&(s=function(t,e){const s=mg.exec(t),i=Number(s[1]);switch(s[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return i/1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}(t,e))),s}function Lg(t,e,s,i="",r="disabled"){const n=t.ownerDocument.createElement("track");return n.kind=e,n.label=s,i&&(n.srclang=i),n.src="data:,WEBVTT",n.track.mode=r,t.appendChild(n),n}function Rg(t){return t.forced&&(Wo.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(qo))?"forced":t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Ig(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){Ua.debug(`[texttrack-utils]: ${s}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,t.addCue(s)}catch(t){Ua.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===s&&(t.mode=s)}function kg(t,e,s,i){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,s){const i=[],r=function(t,e){if(e<=t[0].startTime)return 0;const s=t.length-1;if(e>t[s].endTime)return-1;let i,r=0,n=s;for(;r<=n;)if(i=Math.floor((n+r)/2),e<t[i].startTime)n=i-1;else{if(!(e>t[i].startTime&&r<s))return i;r=i+1}return t[r].startTime-e<e-t[n].startTime?r:n}(t,e);if(r>-1)for(let n=r,a=t.length;n<a;n++){const r=t[n];if(r.startTime>=e&&r.endTime<=s)i.push(r);else if(r.startTime>s)return i}return i}(t.cues,e,s);for(let e=0;e<r.length;e++)i&&!i(r[e])||t.removeCue(r[e])}"disabled"===r&&(t.mode=r)}function wg(t,e){const s=Pg(t.main);if(s&&s.start<=e)return s;const i=Pg(t.audio);return i&&i.start<=e?i:null}function Pg(t){if(!t)return null;switch(t.state){case xc:case Mc:case Hc:case Kc:return null}return t.frag}function Dg(t,e){return e.getAppendedFrag(t,da)||e.getPartialFragment(t)}function Cg(t,e,s,i){const r=i.latestLevelDetails,n=Dg(e,s);if(Wc(i.config)&&!t.nextStart&&r&&n&&i.interstitialsManager){const s="type"in n?n:n.fragment,a=Wl(r,s.sn);(null==a?void 0:a.level)===s.level&&qc(a,i.interstitialsManager.playerQueue,e)&&(t.nextStart=a.start)}}function Og(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Mg(t,e,s,i,r){let n=new t(e,s,"");try{n.value=i,r&&(n.type=r)}catch(a){n=new t(e,s,Dl(r?Aa({type:r},i):i))}return n}const xg=(()=>{const t=Og();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Fg(){return self.SourceBuffer||self.WebKitSourceBuffer}function Ng(){if(!Ba())return!1;const t=Fg();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}var Ug=0,Bg=1,$g=2;class StreamController extends BaseStreamController{constructor(t,e,s){super(t,e,s,"stream-controller",da),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=Ug,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const t=this.media,e=t?t.currentTime:null;if(null===e||!Vn(e))return;if(this.log(`Media seeked to ${e}`),!this.getBufferedFrag(e))return;const s=this.getFwdBufferInfoAtPos(t,e,da,0);s&&0!==s.len?this.tick():this.log(`Main buffer empty at ${e} on "seeked" event: ${s?s.len:s}`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.on(zn.LEVEL_LOADING,this.onLevelLoading,this),t.on(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.on(zn.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(zn.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(zn.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(zn.BUFFER_CREATED,this.onBufferCreated,this),t.on(zn.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(zn.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.off(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.off(zn.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(zn.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(zn.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(zn.BUFFER_CREATED,this.onBufferCreated,this),t.off(zn.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(zn.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=i.startLevel;-1===t&&(i.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=i.firstAutoLevel),i.nextLoadLevel=t,this.level=i.loadLevel,this._hasEnoughToStart=!!e}s>0&&-1===t&&!e&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s}`),t=s),this.state=xc,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,e||this.fragmentTracker.hasFragments(this.playlistType)||(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=Mc}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case jc:{const{levels:t,level:e}=this,s=null==t?void 0:t[e],i=null==s?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=xc;break}if(this.hls.nextLoadLevel!==this.level){this.state=xc;break}break}case Uc:this.checkRetryDate()}this.state===xc&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:s,media:i}=this;if(null===e||!i&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==s||!s[r])return;const n=s[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={type:this.targetBufferType()};return this.hls.trigger(zn.BUFFER_EOS,t),void(this.state=Hc)}if(!this.buffering)return;t.loadLevel!==r&&-1===t.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const l=n.details;if(!l||this.state===jc||this.waitForLive(n))return this.level=r,this.state=jc,void(this.startFragRequested=!1);const d=a.len,c=this.getMaxBufferLength(n.maxBitrate);if(d>=c)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=void 0);const h=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(h,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&pa(u)&&this.fragmentTracker.getState(u)!==cd){var f;const t=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,e=l.fragments[t-1];e&&u.cc===e.cc&&(u=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=void 0);if(u&&this.isLoopLoading(u,h)){if(!u.gap){const t=this.audioOnly&&!this.altAudio?ua:fa,e=(t===fa?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t)}u=this.getNextFragmentLoopLoading(u,l,a,da,c)}u&&(this.exceedsMaxBuffer(a,c,u)||this.loadFragment(u,n,h))}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);i===od||i===dd?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)):super.loadFragment(t,e,s):this.clearTrackerIfNeeded(t)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==Ug){var t;((null==(t=this.getLevelDetails())?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===$g?this.mediaBuffer:this.media}checkFragmentChanged(){const t=this.fragPlaying;if(!this.checkFragPlaying())return!1;const e=this.fragPlaying;if(e){const s=e.level;this.hls.trigger(zn.FRAG_CHANGED,{frag:e,previousFrag:t}),(null==t?void 0:t.level)!==s&&this.hls.trigger(zn.LEVEL_SWITCHED,{level:s})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(t){this._backtrackFragment=t}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(t){this._couldBacktrack=t}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.targetBufferType())}targetBufferType(){return this.altAudio!==$g||this.audioOnly?null:"video"}onMediaAttached(t,e){super.onMediaAttached(t,e);const s=e.media;Dc(s,"playing",this.onMediaPlaying),Dc(s,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:s}=this;s&&(Cc(s,"playing",this.onMediaPlaying),Cc(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(t,e);!!e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(zn.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=Ug,this.audioOnly=!1}onManifestParsed(t,e){let s=!1,i=!1;for(let t=0;t<e.levels.length;t++){const r=e.levels[t].audioCodec;r&&(s=s||-1!==r.indexOf("mp4a.40.2"),i=i||-1!==r.indexOf("mp4a.40.5"))}this.audioCodecSwitch=s&&i&&!function(){var t;const e=Fg();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!==xc)return;const i=e.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=jc)}onLevelLoaded(t,e){var s;const{levels:i,startFragRequested:r}=this,n=e.level,a=e.details,o=a.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=e.levelInfo,d=this.fragCurrent;!d||this.state!==Nc&&this.state!==Uc||d.level!==e.level&&d.loader&&this.abortCurrentFrag();let c=0;if(a.live||null!=(s=l.details)&&s.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,null==(h=this.levelLastLoaded)?void 0:h.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,c),this.hls.trigger(zn.LEVEL_UPDATED,{details:a,level:n}),this.state===jc){if(this.waitForCdnTuneIn(a))return;this.state=xc}r&&a.live&&this.synchronizeToLiveEdge(a),this.initPTS.some((t,e)=>{if(e>=a.startCC)return!0;delete this.initPTS[e]}),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.playhead,n=t.fragmentStart,a=t.edge,o=r>=n-e.maxFragLookUpTolerance&&r<=a;if(null!==i&&s.duration>i&&(r<i||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!o&&s.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i}`),"buffered"===this.config.liveSyncMode){var l;const t=BufferHelper.bufferInfo(s,i,0);if(null==(l=t.buffered)||!l.length)return void(s.currentTime=i);if(t.start<=r)return void(s.currentTime=i);const{nextStart:e}=BufferHelper.bufferedInfo(t.buffered,r,0);e&&(s.currentTime=e)}else s.currentTime=i}}_handleFragmentLoadProgress(t){var e;const s=t.frag,{part:i,payload:r}=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];if(!a)return void this.warn(`Level ${s.level} not found on progress`);const 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,h=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new TransmuxerInterface(this.hls,da,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,{decryptRange:p,byteRange:m}=yd(s,i,this.iframesOnly),v=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount,m?m.end-m.start:r.byteLength,f,g,s.duration,this.iframesOnly,p),y=this.initPTS[s.cc];u.push(r,c,h,l,s,i,o.totalduration,d,v,y)}onAudioTrackSwitching(t,e){const s=this.hls,i=this.altAudio!==Ug;if(Bl(e.url,s))this.altAudio=Bg;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const 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();if(i)return this.altAudio=Ug,this.fragmentTracker.removeAllFragments(),s.once(zn.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(zn.AUDIO_TRACK_SWITCHED,e)}),void s.trigger(zn.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});s.trigger(zn.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const s=Bl(e.url,this.hls);if(s){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=s?$g:Ug,this.tick()}onBufferCreated(t,e){const s=e.tracks;let i,r,n=!1;for(const t in s){const e=s[t];if("main"===e.id){if(r=t,i=e,"video"===t){const e=s[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:s,part:i}=e,r=s.type===da;if(r){if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Gc&&(this.state=xc));let t=!1;if(pa(s)&&(t=!!s.gap&&!s.tagList.some(t=>"GAP"===t[0])),this.fragBufferedComplete(s,i),t){var n;s.stats.retry++;const t=null==(n=this.levels)?void 0:n[s.level];t&&t.fragmentError++}}const a=this.media;a&&(!this._hasEnoughToStart&&BufferHelper.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var s;if(e.fatal)this.state=Kc;else switch(e.details){case Yn.FRAG_GAP:case Yn.FRAG_PARSING_ERROR:case Yn.FRAG_DECRYPT_ERROR:case Yn.FRAG_LOAD_ERROR:case Yn.FRAG_LOAD_TIMEOUT:case Yn.KEY_LOAD_ERROR:case Yn.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(da,e);break;case Yn.LEVEL_LOAD_ERROR:case Yn.LEVEL_LOAD_TIMEOUT:case Yn.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==jc||(null==(s=e.context)?void 0:s.type)!==ea||(this.state=xc);break;case Yn.BUFFER_APPEND_NO_PROGRESS:if("main"!==e.parent)return;e.frag&&(e.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${e.frag.sn} of level ${e.frag.level} as a gap after ${e.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(e.frag));break;case Yn.BUFFER_ADD_CODEC_ERROR:case Yn.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case Yn.BUFFER_FULL_ERROR:if("main"!==e.parent)return;if(this.reduceLengthAndFlushBuffer(e)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case Yn.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=xc,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==ua||!this.altAudio){const t=(e===fa?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),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 i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=BufferHelper.getBuffered(t),a=n.length?n.start(0):0,o=a-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),s+=o,this.startPosition=s),e<s&&(this.log(`seek to target start position ${s} from current time ${e} buffer start ${a}`),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(t=>{const{hls:s}=this,i=null==t?void 0:t.frag;if(!i||this.fragContextChanged(i))return;e.fragmentError=0,this.state=xc,this.startFragRequested=!1,this.bitrateTest=!1;const r=i.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger(zn.FRAG_LOADED,t),i.bitrateTest=!1}).catch(e=>{this.state!==Mc&&this.state!==Kc&&(this.warn(e),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const e=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=t,n=this.getCurrentContext(r);if(!n)return void this.resetWhenMissingContext(r);const{frag:a,part:o,level:l}=n,{video:d,text:c,id3:h,initSegment:u}=i,{details:f}=l,g=this.altAudio?void 0:i.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=$c,u){const t=u.tracks;if(t){const i=a.initSegment||a;if(this.unhandledEncryptionError(u,a))return;this._bufferInitSegment(l,t,i,r),s.trigger(zn.FRAG_PARSING_INIT_SEGMENT,{frag:i,id:e,tracks:t})}const i=u.initPTS,n=u.timescale,o=this.initPTS[a.cc];if(Vn(i)&&(!o||o.baseTime!==i||o.timescale!==n)){const t=u.trackId;this.initPTS[a.cc]={baseTime:i,timescale:n,trackId:t};const r=this.initPTS.slice(0);s.trigger(zn.INIT_PTS_FOUND,{timestampOffsets:r,frag:a,id:e,initPTS:i,timescale:n,trackId:t})}}if(d&&f){g&&"audiovideo"===d.type&&this.logMuxedErr(a);const t=f.fragments[a.sn-1-f.startSN],e=a.sn===f.startSN,s=!t||a.cc>t.cc;if(!1!==i.independent){const{startPTS:t,endPTS:i,startDTS:n,endDTS:l}=d;if(o)o.elementaryStreams[d.type]={startPTS:t,endPTS:i,startDTS:n,endDTS:l};else if(d.firstKeyFrame&&d.independent&&1===r.id&&!s&&(this.couldBacktrack=!0),d.dropped&&d.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=d.firstKeyFramePTS?d.firstKeyFramePTS:t;if(!e&&n<o-this.config.maxBufferHole&&!s)return void this.backtrack(a);s&&(a.gap=!0),a.setElementaryStreamInfo(d.type,a.start,i,a.start,l,!0)}else e&&t-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(d.type,t,i,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(d,a,o,r,e||s)}else{if(!e&&!s)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=g;o&&(o.elementaryStreams[ua]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),a.setElementaryStreamInfo(ua,t,e,s,i),this.bufferFragmentData(g,a,o,r)}if(f&&null!=h&&h.samples.length){const t={id:e,frag:a,details:f,samples:h.samples};s.trigger(zn.FRAG_PARSING_METADATA,t)}if(f&&c){const t={id:e,frag:a,details:f,samples:c.samples};s.trigger(zn.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${pa(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,s,i){if(this.state!==$c)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:a}=e;if(r){const s=t.audioCodec;let i=cl(r.codec,s);if("mp4a"===i&&(i="mp4a.40.5"),this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=r.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&!function(){if(void 0===zo){const t=qo.match(/Firefox\/(\d+)/i);zo=t?parseInt(t[1]):0}return zo}()&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&/Android/.test(qo)&&"audio/mpeg"!==r.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),s&&s!==i&&this.log(`Swapping manifest audio codec "${s}" for "${i}"`),r.levelCodec=i,r.id=da,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${i||""}/${s||""}/${r.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=da;const s=n.codec;if(4===(null==s?void 0:s.length))switch(s){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${s}]${n.codec!==s?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete e.audiovideo}a&&(this.iframesOnly&&this.logMuxedErr(s),this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),delete e.video,delete e.audio);const o=Object.keys(e);if(o.length){if(this.hls.trigger(zn.BUFFER_CODECS,e),!this.hls)return;o.forEach(t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger(zn.BUFFER_APPENDING,{type:t,data:r,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.getBufferOutput();return this.getFwdBufferInfo(t,da)}get maxBufferLength(){const{levels:t,level:e}=this,s=null==t?void 0:t[e];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}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=xc}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return Vn(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(Vn(e)){const t=this.getLevelDetails(),s=this.currentFrag||(t?Kl(null,t.fragments,e):null);if(s){const t=s.programDateTime;if(null!==t){const i=t+1e3*(e-s.start);return new Date(i)}}}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 IFrameStreamController extends StreamController{constructor(...t){super(...t),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{const t=this.media;null!=t&&t.seeking&&(t.currentTime=t.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(t){this.initPTS=t.slice()}loadMediaAt(t,e){if(!this.hls)return;const{seekOnAppend:s}=e,i=t+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=i,this.startPosition=t,this.state){case Mc:case Hc:case Kc:this.state=xc}this.state===xc?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[i,e]):this.nextOp=[i,e],this.hls.off(zn.BUFFERED_TO_END,this.onBufferedToEnd);const r=this.media;if(s&&r){this.seekTo(i)&&(this.currentOp=[i,e],this.nextOp=void 0,this.flushPipeline(i,!0))}}seekTo(t){const e=this.media;if(e){var s;const i=null==(s=this.getLevelDetails())?void 0:s.edge,r=void 0!==i?i:e.duration;t>=r&&(t=r-.01);if(BufferHelper.bufferInfo(e,t,0).len>0&&this.getBufferedAt(t))return e.currentTime=t,!0}return!1}getBufferedAt(t){return this.fragmentTracker.getBufferedFrag(t,da)}cacheSet(t,e){if(!this.hls)return;t.data=e;const s=this.cached;s.push(t),this.cachedSize+=e.buffer.byteLength;const i=this.hls.config.iframeCacheLimit;for(;this.cachedSize>i&&s.length>1;){const t=s.shift();if(!t.data){this.cached=s.filter(t=>!!t.data),this.cachedSize=s.reduce((t,{data:e})=>e?e.buffer.byteLength:0,0);break}this.cachedSize-=t.data.byteLength,t.data=void 0}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(t){const e=t.frag,{part:s,payload:i}=t;this.cacheFragmentData&&!s&&null!=i&&i.byteLength&&!e.data&&pa(e)&&this.cacheSet(e,new Uint8Array(i.slice(0))),super._handleFragmentLoadProgress(t)}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);i!==od&&i!==dd||!this.canReplayCached(t)?super.loadFragment(t,e,s):this.replayCachedFragment(t)}canReplayCached(t){var e;if(!this.cacheFragmentData||null==(e=t.data)||!e.byteLength)return!1;const s=t.decryptdata;return"identity"!==(null==s?void 0:s.keyFormat)||!!s.key}replayCachedFragment(t){const e=t.data.slice().buffer;this.log(`Buffering cached ${t.type} sn: ${t.sn} of level ${t.level} (${e.byteLength} bytes)`),this.fragCurrent=t,this.startFragRequested=!0;const s=t.stats=new LoadStats;s.loading.start=s.loading.first=s.loading.end=self.performance.now(),s.loaded=s.total=e.byteLength,s.chunkCount=1,this.state=Nc;const i={frag:t,part:null,payload:e,networkDetails:null};this._handleFragmentLoadProgress(i),this.hls.trigger(zn.FRAG_LOADED,i),this._handleFragmentLoadComplete(i)}fragBufferedComplete(t,e){super.fragBufferedComplete(t,e);const{currentOp:s,nextOp:i}=this;this.currentOp=this.nextOp=void 0,this.state=Mc,null!=s&&s[1].seekOnAppend&&(this.flushPipeline(s[0],!i),this.seekTo(s[0])||this.log(`Could not seek to ${s[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?Oc(BufferHelper.getBuffered(this.media)):"none"}`)),i&&this.loadMediaAt.apply(this,i)}flushPipeline(t,e){if(e){const e=this.media;if(e){const s=BufferHelper.bufferInfo(e,t,0),i=s.len?s.nextStart:0;i&&(this.fragmentTracker.removeFragmentsInRange(i,1/0,da),this.flushMainBuffer(i,1/0))}this.hls.once(zn.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(zn.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){const t=this.hls;t.nextLoadLevel=-1===t.startLevel?0:t.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(t,e,s){const i=this.initDetails;return this.initDetails=null,super.alignPlaylists(t,e,s||i||void 0)}getMainFwdBufferInfo(){const t=this.playhead,e=this.getBufferedAt(t);if(e){const s=e.duration;return{len:s,start:t,end:t+s,bufferedIndex:-1}}return{len:0,start:t,end:t,bufferedIndex:-1}}_streamEnded(){const t=this.playhead,e=this.fragmentTracker.getBufferedFrag(t,da);return!(null==e||!e.endList)}}class ImageIFrameStreamController extends IFrameStreamController{constructor(...t){super(...t),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(t){var e;const s=null==(e=this._img)?void 0:e.src;s&&self.URL.revokeObjectURL(s),this._img=t}loadMediaAt(t){if(!this.hls)return;const e=t+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=e,this.startPosition=t,this.state){case Mc:case Hc:case Kc:this.state=xc}if(this.state===xc){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===xc){const e=this.getBufferedAt(t);e&&(this.fragCurrent=e,this.updateImage(e,null))}}else{const s=this.fragCurrent;(!s||t>=s.start&&t<s.end)&&(this.queued=[e])}}updateImage(t,e,s){const i=t.data;i||this.fragmentTracker.removeFragment(t);const r=this._img;if(r&&i){const n=self.performance.now();(e?e.stats:t.stats).buffering.start=t.stats.buffering.start=n,r.onload=()=>{if(!this.hls)return;const i=this.hls.levels[t.level];null!=i&&i.fragmentError&&(i.fragmentError=0,t.stats.retry=0);const r=self.performance.now(),n=e?e.stats:t.stats;n.buffering.end=t.stats.buffering.end=r,this.hls.trigger(zn.FRAG_BUFFERED,{frag:t,part:e,stats:n,id:t.type,chunkMeta:s})},r.onerror=()=>{this.handleError("Image decode error",t,e,s)};const a=r.src;a&&self.URL.revokeObjectURL(a);const o=new Blob([i],{type:"image/jpeg"});r.src=self.URL.createObjectURL(o)}else this.state=Mc,this.processQueued()}processQueued(){const t=this.queued;this.queued=void 0,t&&this.loadMediaAt.apply(this,t)}handleError(t,e,s,i){if(!this.hls)return;const r=new Error(t);this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.FRAG_PARSING_ERROR,chunkMeta:i,frag:e,part:s,fatal:!1,error:r,err:r})}_bufferInitSegment(){}bufferFragmentData(t,e,s,i){super.bufferFragmentData(t,e,s,i,!0);const r=bo(new Uint8Array(t.data1),["mdat"]);if(0===r.length)return void this.handleError("Could not find I-Frame mdat",e,s,i);const n=e;this.cacheSet(n,r[0]),this.updateImage(n,s,i)}fragBufferedComplete(t,e){this.fragmentTracker.fragBuffered(t,!0),super.fragBufferedComplete(t,e),this.processQueued()}checkFragPlaying(){var t;const e=null==(t=this.fragPrevious)?void 0:t.start;if(void 0!==e){const t=this.getAppendedFrag(e);if(t&&!ma(t,this.fragPlaying))return this.fragPlaying=t,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}const Gg="Image I-Frame player does not accept HTMLMediaElements",Hg={seekOnAppend:!0};let Kg,Vg;const jg=.025;let qg=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function Wg(t,e,s){return`${t.identifier}-${s+1}-${dg(e)}`}class InterstitialEvent{constructor(t,e){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=e,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,null==(t=this.assetListLoader)||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var e;if(t>0&&t>=this.assetList.length)return!0;const s=this.playoutLimit;if(t<=0||isNaN(s))return!1;if(0===s)return!0;return((null==(e=this.assetList[t])?void 0:e.startOffset)||0)>s}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const e=this.dateRange.tagAnchor;if(e)return zg(e,t)?Yg(t,e):t}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const e=this.dateRange.startTime;return e-Yg(e,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,e=Vn(t)?t:this.duration;return this.cumulativeDuration+e}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const e=this.resumeAnchor;if(e)return zg(e,t)?Yg(t,e):t}return t}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<jg))}set appendInPlace(t){this.appendInPlaceStarted?this.resetOnResume=!t:this.appendInPlaceDisabled=!t}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let e;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e}set duration(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?qg.Range:qg.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(t=this).identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`;var t}}function Yg(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<jg)?e.start:e.start+e.duration}function zg(t,e){return e>t.start-jg&&e<t.start+t.duration+jg}function Qg(t,e,s){const i=new self.URL(t,s);return"data:"!==i.protocol&&Al(i,"_HLS_primary_id",e),i}function Xg(t,e){for(;null!=(s=t.assetList[++e])&&s.error;)var s;return e}function Zg(t){const e=t.timelineStart,s=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+s).toFixed(2)}]`}class HlsAssetPlayer{constructor(t,e,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(zn.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new t(e);this.interstitial=s,this.assetItem=i;const n=()=>{this.hasDetails=!0};r.once(zn.LEVEL_LOADED,n),r.once(zn.AUDIO_TRACK_LOADED,n),r.once(zn.SUBTITLE_TRACK_LOADED,n),r.on(zn.MEDIA_ATTACHING,(t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e;this.interstitial.playoutLimit&&(e.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(zn.BUFFER_APPENDED,()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,r.trigger(zn.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let e=this.assetItem.uri;try{e=Qg(e,t.config.primarySessionId||"").href}catch(t){}t.loadSource(e)}}bufferedInPlaceToEnd(t,e){var s;if(!this.appendInPlace)return!1;if(null!=(s=this.hls)&&s.bufferedToEnd)return!0;if(!t)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset+(e||0),n=BufferHelper.bufferInfo(t,r,.02);return this.getAssetTime(n.end)>=i-.02}reachedPlayout(t){const e=this.interstitial.playoutLimit;return this.startOffset+t>=e}get destroyed(){var t;return!(null!=(t=this.hls)&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return(null==(t=this.hls)?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const e=BufferHelper.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const e=this.interstitial.playoutLimit;if(e){const s=e-this.startOffset;if(s>0&&s<t)return s}return t}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const e=this.timelineOffset;if(t!==e){const s=t-e;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const e=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,t-e),s)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var t;this.mediaAttached&&(null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var e;this.loadSource(),null==(e=this.hls)||e.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,null==(t=this.hls)||t.detachMedia()}resumeBuffering(){var t;null==(t=this.hls)||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.hls)||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),(null==(t=this.hls)?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const e=t=>delete t.details;t.levels.forEach(e),t.allAudioTracks.forEach(e),t.allSubtitleTracks.forEach(e),this.hasDetails=!1}}on(t,e,s){var i;null==(i=this.hls)||i.on(t,e)}once(t,e,s){var i;null==(i=this.hls)||i.once(t,e)}off(t,e,s){var i;null==(i=this.hls)||i.off(t,e)}toString(){var t;return`HlsAssetPlayer: ${Zg(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Jg=.033;class InterstitialsSchedule extends Logger{constructor(t,e){super("interstitials-sched",e),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,e){return this.events?this.events.reduce((s,i)=>t<=i.startOffset&&e>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,e){if(t.event)return this.findEventIndex(t.event.identifier);let s=-1;t.nextEvent?s=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(s=this.findEventIndex(t.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(void 0===e&&(e=t.start),s=this.findItemIndexAtTime(e));s>=0&&null!=(r=i[s])&&r.event;){var r;s--}return s}findItemIndexAtTime(t,e){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];e&&"primary"!==e&&(r=r[e]);const n=r.start,a=s[i].event,o=null!=a&&a.cue.pre?a.duration:r.end;if(t===n||t>n&&t<o)return i}return-1}findJumpRestrictedIndex(t,e){const s=this.items;if(s)for(let i=t;i<=e&&s[i];i++){const t=s[i].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return i}return-1}findEventIndex(t){const e=this.items;if(e)for(let i=e.length;i--;){var s;if((null==(s=e[i].event)?void 0:s.identifier)===t)return i}return-1}findAssetIndex(t,e){const s=t.assetList,i=s.length;if(i>1)for(let t=0;t<i;t++){const r=s[t];if(!r.error){const s=r.timelineStart;if(e===s||e>s&&(e<s+(r.duration||0)||t===i-1))return t}}return 0}get assetIdAtEnd(){var t;const e=null==(t=this.items)||null==(t=t[this.length-1])?void 0:t.event;if(e){const t=e.assetList,s=t[t.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(t,e,s=0){const i=t.main.details,{dateRanges:r}=i,n=this.events,a=this.parseDateRanges(r,{url:i.url},e),o=Object.keys(r),l=n?n.filter(t=>-1===o.indexOf(t.identifier)):[];a.length&&a.sort((t,e)=>{const s=t.cue.pre,i=t.cue.post,r=e.cue.pre,n=e.cue.post;if(s&&!r)return-1;if(r&&!s)return 1;if(i&&!n)return 1;if(n&&!i)return-1;if(!(s||r||i||n)){const s=t.startTime,i=e.startTime;if(s!==i)return s-i}return t.dateRange.tagOrder-e.dateRange.tagOrder}),this.events=a,l.forEach(t=>{this.removeEvent(t)}),this.updateSchedule(t,l,s)}updateSchedule(t,e=[],s=0,i=!1){const r=this.events||[];if(r.length||e.length||this.length<2){const n=this.items,a=this.parseSchedule(r,t,s);(i||e.length||(null==n?void 0:n.length)!==a.length||a.some((t,e)=>Math.abs(t.playout.start-n[e].playout.start)>.005||Math.abs(t.playout.end-n[e].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(e,n))}}parseDateRanges(t,e,s){const i=[],r=Object.keys(t);for(let n=0;n<r.length;n++){const a=r[n],o=t[a];if(o.isInterstitial){let t=this.eventMap[a];t?t.setDateRange(o):(t=new InterstitialEvent(o,e),this.eventMap[a]=t,!1===s&&(t.appendInPlace=s)),i.push(t)}}return i}parseSchedule(t,e,s=0){const i=[],r=e.main.details,n=r.live?1/0:r.edge;let a=0;if((t=t.filter(t=>!(t.error||t.cue.once&&t.hasPlayed))).length){this.resolveOffsets(t,e);let l=0,d=0;if(t.forEach((e,o)=>{const c=e.cue.pre,h=e.cue.post,u=t[o-1]||null,f=e.appendInPlace,g=h?n:e.startOffset,p=e.duration,m=e.timelineOccupancy===qg.Range?p:0,v=c&&r.live?s+(e.resumeOffset||0):0,y=v||e.resumptionOffset,E=(null==u?void 0:u.startTime)===g,T=g+e.cumulativeDuration;let S=f?T+p:g+y;if(c||!h&&g<=0){const t=d;d+=m,e.timelineStart=T;const s=a;a+=p,i.push({event:e,start:T,end:S,playout:{start:s,end:a},integrated:{start:t,end:d}})}else{if(!(g<=n))return;{if(!E){const s=g-l;if(s>Jg){const r=l,n=d;d+=s;const c=a;a+=s;const h={previousEvent:t[o-1]||null,nextEvent:e,start:r,end:r+s,playout:{start:c,end:a},integrated:{start:n,end:d}};i.push(h)}else s>0&&u&&(u.cumulativeDuration+=s,i[i.length-1].end=g)}h&&(S=T),e.timelineStart=T;const s=d;d+=m;const r=a;a+=p,i.push({event:e,start:T,end:S,playout:{start:r,end:a},integrated:{start:s,end:d}})}}const A=v||e.resumeTime;l=h||A>n?n:!c&&S&&e.appendInPlaceStarted&&A-S>Jg?S:A}),l<n){var o;const t=l,e=d,s=n-l;d+=s;const r=a;a+=s,i.push({previousEvent:(null==(o=i[i.length-1])?void 0:o.event)||null,nextEvent:null,start:l,end:t+s,playout:{start:r,end:a},integrated:{start:e,end:d}})}this.setDurations(n,a,d)}else{const t=0;i.push({previousEvent:null,nextEvent:null,start:t,end:n,playout:{start:t,end:n},integrated:{start:t,end:n}}),this.setDurations(n,n,n)}return i}setDurations(t,e,s){this.durations={primary:t,playout:e,integrated:s}}resolveOffsets(t,e){const s=e.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;t.forEach((a,o)=>{const l=a.cue.pre,d=a.cue.post,c=l?0:d?i:a.startTime;this.updateAssetDurations(a);if(n===c?a.cumulativeDuration=r:(r=0,n=c),!d&&a.snapOptions.in&&(a.resumeAnchor=Kl(null,s.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,e)||(a.appendInPlace=!1)}if(!a.appendInPlace&&o+1<t.length){t[o+1].startTime-t[o].resumeTime<Jg&&(t[o+1].appendInPlace=!1,t[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`))}const h=Vn(a.resumeOffset)?a.resumeOffset:a.duration;r+=h})}primaryCanResumeInPlaceAt(t,e){const s=t.resumeTime,i=t.startTime+t.resumptionOffset;if(Math.abs(s-i)>jg)return this.log(`"${t.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1;return!Object.keys(e).some(i=>{const r=e[i].details,n=r.edge;if(s>=n)return this.log(`"${t.identifier}" resumption ${s} past ${i} playlist end ${n}`),!1;const a=Kl(null,r.fragments,s);if(!a)return this.log(`"${t.identifier}" resumption ${s} does not align with any fragments in ${i} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===i?.175:0;return!(Math.abs(a.start-s)<jg+o||Math.abs(a.end-s)<jg+o)&&(this.log(`"${t.identifier}" resumption ${s} not aligned with ${i} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})}updateAssetDurations(t){if(!t.assetListLoaded)return;const e=t.timelineStart;let s=0,i=!1,r=!1;for(let n=0;n<t.assetList.length;n++){const a=t.assetList[n],o=e+s;a.startOffset=s,a.timelineStart=o,i||(i=null===a.duration),r||(r=!!a.error);s+=a.error?0:a.duration||0}t.duration=i&&!r?Math.max(s,t.duration):s}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function tp(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class AssetListLoader{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const s=t.assetListUrl;let i;try{i=Qg(s,this.hls.sessionId,t.baseUrl)}catch(e){const i=this.assignAssetListError(t,Yn.ASSET_LIST_LOAD_ERROR,e,s);return void this.hls.trigger(zn.ERROR,i)}e&&"data:"!==i.protocol&&Al(i,"_HLS_start_offset",""+e);const r=this.hls.config,n=new(0,r.loader)(r),a={type:la,responseType:"json",url:i.href},o=r.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,s,i,r)=>{const n=e.data,a=null==n?void 0:n.ASSETS;if(!Array.isArray(a)){const e=this.assignAssetListError(t,Yn.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),i.url,s,r);return void this.hls.trigger(zn.ERROR,e)}t.assetListResponse=n,this.hls.trigger(zn.ASSET_LIST_LOADED,{event:t,assetListResponse:n,networkDetails:r})},onError:(e,s,i,r)=>{const n=this.assignAssetListError(t,Yn.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${s.url})`),s.url,r,i);this.hls.trigger(zn.ERROR,n)},onTimeout:(e,s,i)=>{const r=this.assignAssetListError(t,Yn.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${s.url})`),s.url,e,i);this.hls.trigger(zn.ERROR,r)}};return n.load(a,l,d),this.hls.trigger(zn.ASSET_LIST_LOADING,{event:t}),n}assignAssetListError(t,e,s,i,r,n){return t.error=s,{type:Wn.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:i,error:s,networkDetails:n,stats:r}}}function ep(t){var e;null==t||null==(e=t.play())||e.catch(()=>{})}function sp(t,e){return`[${t}] Advancing timeline position to ${e}`}class BufferableInstance{constructor(t){this.buffered=void 0;const e=(e,s,i)=>{if((s>>>=0)>i-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${i})`);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)}}}const ip={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},rp=t=>String.fromCharCode(ip[t]||t),np=15,ap=42,op={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},lp={17:2,18:4,21:6,22:8,23:10,19:13,20:15},dp={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},cp={25:2,26:4,29:6,30:8,31:10,27:13,28:15},hp=["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;Ua.log(`${this.time} [${t}] ${s}`)}}}const up=function(t){const e=[];for(let s=0;s<t.length;s++)e.push(t[s].toString(16));return e},fp=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1});class PenState{constructor(){this.styles=fp}get foreground(){return this.styles.foreground}set foreground(t){const e=this.styles;this.styles={foreground:t,underline:e.underline,italics:e.italics,background:e.background,flash:e.flash}}get underline(){return this.styles.underline}set underline(t){const e=this.styles;this.styles={foreground:e.foreground,underline:t,italics:e.italics,background:e.background,flash:e.flash}}get italics(){return this.styles.italics}set italics(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:t,background:e.background,flash:e.flash}}get background(){return this.styles.background}set background(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:e.italics,background:t,flash:e.flash}}get flash(){return this.styles.flash}set flash(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:e.italics,background:e.background,flash:t}}reset(){this.styles=fp}setStyles(t){const e=this.styles,s=Object.prototype.hasOwnProperty;this.styles={foreground:s.call(t,"foreground")?t.foreground:e.foreground,underline:s.call(t,"underline")?t.underline:e.underline,italics:s.call(t,"italics")?t.italics:e.italics,background:s.call(t,"background")?t.background:e.background,flash:s.call(t,"flash")?t.flash:e.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class StyledUnicodeChar{constructor(){this.uchar=" ",this.penState=new PenState}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.styles=e.styles}setPenState(t){this.penState.styles=t.styles}copy(t){this.uchar=t.uchar,this.penState.styles=t.penState.styles}}class Row{constructor(t){this.chars=[],this.pos=0,this.currPenState=new PenState,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<ap;t++)this.chars.push(new StyledUnicodeChar);this.logger=t}equals(t){const e=this.chars,s=t.chars;for(let t=0;t<ap;t++){const i=e[t],r=s[t];if(i.uchar!==r.uchar)return!1;const n=i.penState.styles,a=r.penState.styles;if(n!==a&&(n.foreground!==a.foreground||n.underline!==a.underline||n.italics!==a.italics||n.background!==a.background||n.flash!==a.flash))return!1}return!0}copy(t){for(let e=0;e<ap;e++)this.chars[e].copy(t.chars[e])}isEmpty(){const t=this.chars;for(let e=0;e<ap;e++){const s=t[e];if(" "!==s.uchar)return!1;const i=s.penState.styles;if(i!==fp&&("white"!==i.foreground||i.underline||i.italics||"black"!==i.background||i.flash))return!1}return!0}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>=ap&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=41)}moveCursor(t){const e=Math.min(this.pos+t,ap);if(t>1)for(let t=this.pos+1;t<e;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=rp(t);this.pos>=ap?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<ap;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<ap;s++){const i=this.chars[s].uchar;" "!==i&&(e=!1),t.push(i)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class CaptionScreen{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<np;e++)this.rows.push(new Row(t));this.logger=t}reset(){for(let t=0;t<np;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let s=0;s<np;s++)if(!this.rows[s].equals(t.rows[s])){e=!1;break}return e}copy(t){for(let e=0;e<np;e++){const s=this.rows[e].chars,i=t.rows[e].chars;for(let t=0;t<ap;t++){const e=s[t],r=i[t];e.uchar=r.uchar,e.penState.styles=r.penState.styles}}}isEmpty(){let t=!0;for(let e=0;e<np;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 = "+Dl(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<np;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const i=s.rows[t].cueStartTime,r=this.logger.time;if(null!==i&&null!==r&&i<r)for(let i=0;i<this.nrRollUpRows;i++)this.rows[e-this.nrRollUpRows+i+1].copy(s.rows[t+i])}}this.currRow=e;const s=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,i=Math.max(e-1,0);s.setCursor(t.indent),t.color=s.chars[i].penState.foreground}const i={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+Dl(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="",i=-1;for(let s=0;s<np;s++){const r=this.rows[s].getTextString();r&&(i=s+1,t?e.push("Row "+i+": '"+r+"'"):e.push(r.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,i=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=i[s]}this.logger.log(2,"MIDROW: "+Dl(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=[null,null,null],this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new CaptionsLogger,this.field=t,this.outputFilters=[null,e,s]}getHandler(t){return this.outputFilters[t]}setHandler(t,e){var s;this.outputFilters[t]=e,null==(s=this.channels[t])||s.setHandler(e)}getChannel(t){let e=this.channels[t];return e||(e=this.channels[t]=new Cea608Channel(this.field+t-1,this.outputFilters[t],this.logger)),e}addData(t,e){this.logger.time=t;for(let t=0;t<e.length;t+=2){const s=127&e[t],i=127&e[t+1];let r=!1,n=null;if(0===s&&0===i)continue;this.logger.log(3,()=>"["+up([e[t],e[t+1]])+"] -> ("+up([s,i])+")");const a=this.cmdHistory;if(s>=16&&s<=31){if(pp(s,i,a)){gp(null,null,a),this.logger.log(3,()=>"Repeated command ("+up([s,i])+") is dropped");continue}gp(s,i,this.cmdHistory),r=this.parseCmd(s,i),r||(r=this.parseMidrow(s,i)),r||(r=this.parsePAC(s,i)),r||(r=this.parseBackgroundAttributes(s,i))}else gp(null,null,a);if(!r&&(n=this.parseChars(s,i),n)){const t=this.currentChannel;if(t&&t>0){this.getChannel(t).insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+up([s,i])+" orig: "+up([e[t],e[t+1]]))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;const s=20===t||21===t||23===t?1:2,i=this.getChannel(s);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),this.currentChannel=s,!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 i=this.channels[s];return!!i&&(i.ccMIDROW(e),this.logger.log(3,()=>"MIDROW ("+up([t,e])+")"),!0)}return!1}parsePAC(t,e){let s;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const i=t<=23?1:2;s=e>=64&&e<=95?1===i?op[t]:dp[t]:1===i?lp[t]:cp[t];return this.getChannel(i).setPAC(this.interpretPAC(s,e)),this.currentChannel=i,!0}interpretPAC(t,e){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:t};return s=e>95?e-96:e-64,i.underline=!(1&~s),s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((s-16)/2),i}parseChars(t,e){let s,i=null,r=null;if(t>=25?(s=2,r=t-8):(s=1,r=t),r>=17&&r<=19){let t;t=17===r?e+80:18===r?e+112:e+144,this.logger.log(2,()=>"Special char '"+rp(t)+"' in channel "+s),i=[t]}else t>=32&&t<=127&&(i=0===e?[t]:[t,e]);return i&&this.logger.log(3,()=>"Char codes = "+up(i).join(",")),i}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 i={};16===t||24===t?(s=Math.floor((e-32)/2),i.background=hp[s],e%2==1&&(i.background=i.background+"_semi")):45===e?i.background="transparent":(i.foreground="black",47===e&&(i.underline=!0));const r=t<=23?1:2;return this.getChannel(r).setBkgData(i),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}gp(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const s=this.channels[e];s&&s.cueSplitAtTime(t)}}}function gp(t,e,s){s.a=t,s.b=e}function pp(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}}function mp(t,e,s,i){return Math.min(e,i)-Math.max(t,s)}const vp=/\s/,yp={newCue(t,e,s,i){const r=[];let n,a,o,l,d;const c=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=!0,l=0,d="",!n.isEmpty()){var h;for(let t=0;t<n.chars.length;t++)vp.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 i=lg(d.trim()),f=ug(e,s,i);null!=t&&null!=(h=t.cues)&&h.getCueById(f)||(a=new c(e,s,i),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return t&&r.length&&(r.sort((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line),r.forEach(e=>Ig(t,e))),r}};class BaseLoader{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new LoadStats}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(t,e,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=s,this.loadInternal()}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(Pa(t,this.stats.retry,!0))this.retry(t);else{var e;Ua.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(t){const{context:e,stats:s}=this;this.retryDelay=ka(t,s.retry),s.retry++,Ua.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${s.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}}const Ep=/(\d+)-(\d+)\/(\d+)/;class FetchLoader extends BaseLoader{constructor(t){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=t.fetchSetup||Tp}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){const{config:t,context:e,stats:s}=this;if(!t||!e)return;s.loading.first=0,s.loaded=0,s.aborted=!1,this.controller=new self.AbortController;const i=function(t,e){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Ta({},t.headers))};t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return s}(e,this.controller.signal),r="arraybuffer"===e.responseType,n=r?"byteLength":"length",{maxTimeToFirstByteMs:a,maxLoadTimeMs:o}=t.loadPolicy;this.request=this.fetchSetup(e,i),self.clearTimeout(this.requestTimeout),t.timeout=a&&Vn(a)?a:o,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},t.timeout);(tu(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(i=>{var n;this.response=i;const a=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=o,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},o-(a-s.loading.start)),!i.ok){const{status:t,statusText:e}=i;throw new FetchError(e||"fetch, bad network response",t,i)}s.loading.first=a,s.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=Ep.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(Vn(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(i.headers)||s.total;const l=null==(n=this.callbacks)?void 0:n.onProgress;return l&&Vn(t.highWaterMark)?this.loadProgressively(i,s,e,t.highWaterMark,l):r?i.arrayBuffer():"json"===e.responseType?i.json():i.text()}).then(i=>{var r,a;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const l=i[n];l&&(s.loaded=s.total=l);const d={url:o.url,data:i,code:o.status},c=null==(r=this.callbacks)?void 0:r.onProgress;c&&!Vn(t.highWaterMark)&&c(s,e,i,o),null==(a=this.callbacks)||a.onSuccess(d,s,e,o)}).catch(i=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const r=i&&i.code||0,n=i?i.message:null,a=t.loadPolicy.errorRetry;var o;Pa(a,s.retry,!1,{url:e.url,data:void 0,code:r})?this.retry(a):(Ua.error(`${r} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:r,text:n},e,i?i.details:null,s))})}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,i=0,r){const n=new ChunkCache,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&r(e,s,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return e.loaded+=d,d<i||n.dataLength?(n.push(l),n.dataLength>=i&&r(e,s,n.flush().buffer,t)):r(e,s,l.buffer,t),o()}).catch(()=>Promise.reject());return o()}}function Tp(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 Sp=/^age:\s*[\d.]+\s*$/im;class XhrLoader extends BaseLoader{constructor(t){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=t.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=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()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===s&&!this.stats.aborted)return r.call(this,s,e.url,e)}).catch(t=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",e.url,!0),r.call(this,s,e.url,e)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,e,t)}).catch(t=>{var r;null==(r=this.callbacks)||r.onError({code:s.status,text:t.message},e,s,i)}):this.openAndSendXhr(s,e,t)}openAndSendXhr(t,e,s){t.readyState||t.open("GET",e.url,!0);const i=e.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const e in i)t.setRequestHeader(e,i[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=r&&Vn(r)?r: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 i=e.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const i=e.status,l="text"===e.responseType?e.responseText:null;if(i>=200&&i<300){const r=null!=l?l:e.response;if(null!=r){var n,a;s.loading.end=Math.max(self.performance.now(),s.loading.first);const o="arraybuffer"===e.responseType?r.byteLength:r.length;s.loaded=s.total=o,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(s,t,r,e);const d={url:e.responseURL,data:r,code:i};return t.rangeEnd&&o!==t.rangeEnd-t.rangeStart&&Ua.warn(`Payload length ${o} does not match requested Range: bytes=${t.rangeStart}-${t.rangeEnd-1}`),void(null==(a=this.callbacks)||a.onSuccess(d,s,t,e))}}const d=r.loadPolicy.errorRetry;var o;if(Pa(d,s.retry,!1,{url:t.url,data:void 0,code:i}))this.retry(d);else Ua.error(`${i} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:i,text:e.statusText},t,e,s)}}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&Sp.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 Ap=Aa(Aa({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh: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,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:XhrLoader,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Wd,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:StreamController,abrController:class AbrController extends Logger{constructor(t){super("abr",t.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var e;const{fragCurrent:s,partCurrent:i,hls:r}=this;if(!r)return;const{autoLevelEnabled:n,media:a}=r;if(!s||!a)return;const o=performance.now(),l=i?i.stats:s.stats,d=i?i.duration:s.duration,c=o-l.loading.start,h=r.minAutoLevel,u=s.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||u<=h)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==u,p=!!t||g;if(!p&&(a.paused||!a.playbackRate||!a.readyState))return;const m=r.mainForwardBufferInfo;if(!p&&null===m)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(c<=Math.max(v,d/(2*y)*1e3))return;const E=m?m.len/y:0,T=l.loading.first?l.loading.first-l.loading.start:-1,S=l.loaded&&T>-1,A=this.getBwEstimate(),_=r.levels,b=_[u],L=Math.max(l.loaded,Math.round(d*(s.bitrate||b.averageBitrate)/8));let R=S?c-T:c;R<1&&S&&(R=Math.min(c,8*l.loaded/A));const I=S?1e3*l.loaded/R:0,k=v/1e3,w=I?(L-l.loaded)/I:8*L/A+k;if(w<=E)return;const P=I?8*I:A,D=!0===(null==(e=(null==t?void 0:t.details)||r.latestLevelDetails)?void 0:e.live),C=r.config.abrBandWidthUpFactor;let O,M=Number.POSITIVE_INFINITY;for(O=u-1;O>h;O--){const t=_[O].maxBitrate,e=!_[O].details||D;if(M=this.getTimeToLoadFrag(k,P,d*t,e),M<Math.min(E,d+k))break}if(M>=w)return;if(M>10*d)return;S?this.bwEstimator.sample(c-Math.min(v,T),l.loaded):this.bwEstimator.sampleTTFB(c);const x=_[O].maxBitrate;this.getBwEstimate()*C>x&&(this.firstAutoFloor=Math.min(O,r.firstLevel),this.resetEstimator(x));const F=this.findBestLevel(x,h,O,0,E,1,1);F>-1&&(O=F),this.warn(`Fragment ${s.sn}${i?" part "+i.index:""} of level ${u} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${E.toFixed(3)} s\n Estimated load time for current fragment: ${w.toFixed(3)} s\n Estimated load time for down switch fragment: ${M.toFixed(3)} s\n TTFB estimate: ${0|T} ms\n Current BW estimate: ${Vn(A)?0|A:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${O} @ ${0|x} bps`),r.nextLoadLevel=r.nextAutoLevel=O,this.clearTimer();const N=()=>{this.clearTimer();const t=this.hls;if(this.fragCurrent===s&&t.loadLevel===O&&O>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${O>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,O>h){let s=this.findBestLevel(t.levels[h].bitrate,h,O,0,e,1,1);-1===s&&(s=h),t.nextLoadLevel=t.nextAutoLevel=s,this.firstAutoFloor=Math.min(s,t.firstLevel),this.resetEstimator(t.levels[s].bitrate)}}};g||w>2*M?N():this.timer=self.setInterval(N,1e3*M),r.trigger(zn.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:i,stats:l})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){this.hls&&(t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){const t=this.hls.config;return new EwmaBandWidthEstimator(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const t=this.hls;t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.FRAG_LOADING,this.onFragLoading,this),t.on(zn.FRAG_LOADED,this.onFragLoaded,this),t.on(zn.FRAG_BUFFERED,this.onFragBuffered,this),t.on(zn.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.on(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(zn.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(zn.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.FRAG_LOADING,this.onFragLoading,this),t.off(zn.FRAG_LOADED,this.onFragLoaded,this),t.off(zn.FRAG_BUFFERED,this.onFragBuffered,this),t.off(zn.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.off(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(zn.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(zn.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const s=e.frag;if(!this.ignoreFragment(s)){var i;if(!s.bitrateTest)this.fragCurrent=s,this.partCurrent=null!=(i=e.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case Yn.BUFFER_ADD_CODEC_ERROR:case Yn.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Yn.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:s,partCurrent:i}=this;if(t&&va(t,s)){const e=performance.now(),s=i?i.stats:t.stats,r=e-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(t,n),s.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,s,i){return t+s/e+(i?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const s=this.hls.config,{loading:i}=e.stats,r=i.end-i.first;Vn(r)&&(this.lastLevelLoadSec=r/1e3),e.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,e){var s;const{frag:i,part:r}=e,n=r?r.stats:i.stats;if(i.type===da&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,null!=(s=this.hls)&&s.config.abrMaxWithRealBitrate){const t=r?r.duration:i.duration,e=this.hls.levels[i.level],s=(e.loaded?e.loaded.bytes:0)+n.loaded,a=(e.loaded?e.loaded.duration:0)+t;e.loaded={bytes:s,duration:a},e.realBitrate=Math.round(8*s/a)}if(i.bitrateTest){const t={stats:n,frag:i,part:r,id:i.type};this.onFragBuffered(zn.FRAG_BUFFERED,t),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}}onFragBuffered(t,e){const{frag:s,part:i}=e,r=null!=i&&i.stats.loaded?i.stats:s.stats;if(r.aborted)return;if(this.ignoreFragment(s))return;const n=((s.bitrate||0)>=1e5?r.parsing.end:r.loading.end)-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(t){return t.type!==da||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{hls:t}=this;if(!t)return 0;const{maxAutoLevel:e,minAutoLevel:s}=t,i=this.getBwEstimate(),r=this.getStarvationDelay(),n=t.config.maxStarvationDelay,a=this.findBestLevel(i,s,e,r/2,n,1,1);if(a>-1)return a;const o=t.firstLevel,l=-1===this.firstAutoFloor?1/0:this.firstAutoFloor,d=Math.min(Math.max(o,s),e,l);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${d}`),d}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const i=e&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,i)&&e[t].loadError<=e[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:s}=this;if(!s)return-1;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=r.abrBandWidthFactor,c=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,i,l,0,d,c);if(t>=0)return this.rebufferNotice=-1,t}let h=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){h=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),d=c=1}}const u=this.findBestLevel(o,n,i,l,h,d,c);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=s.levels[n],g=s.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:s.loadLevel}getStarvationDelay(){const t=this.hls,e=null==t?void 0:t.media;if(!e)return 1/0;const s=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,i=t.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(t,e,s,i,r,n,a){const{hls:o,lastLoadedFragLevel:l,fragCurrent:d,partCurrent:c}=this;if(!o)return-1;const h=i+r,u=-1===l?o.firstLevel:l,{levels:f,allAudioTracks:g,loadLevel:p,latestLevelDetails:m,config:v}=o;if(1===f.length)return 0;const y=f[u],E=!(null==m||!m.live),T=-1===p||-1===l;let S,A="SDR",_=(null==y?void 0:y.frameRate)||0;const{audioPreference:b,videoPreference:L}=v,R=this.audioTracksByGroup||(this.audioTracksByGroup=Ol(g));let I=-1;if(T){if(-1!==this.firstSelection)return this.firstSelection;const i=this.codecTiers||(this.codecTiers=function(t,e,s,i){return t.slice(s,i+1).reduce((t,s,i)=>{if(!s.codecSet)return t;const r=s.audioGroups;let n=t[s.codecSet];n||(t[s.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,s.bitrate);const a=Math.min(s.height,s.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,s.frameRate),n.minIndex=Math.min(n.minIndex,i),n.maxScore=Math.max(n.maxScore,s.score),n.fragmentError+=s.fragmentError,n.videoRanges[s.videoRange]=(n.videoRanges[s.videoRange]||0)+1,r&&r.forEach(t=>{if(!t)return;const s=e.groups[t];s&&(n.hasDefaultAudio=n.hasDefaultAudio||e.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(s.channels).forEach(t=>{n.channels[t]=(n.channels[t]||0)+s.channels[t]}))}),t},{})}(f,R,e,s)),r=function(t,e,s,i,r){const n=Object.keys(t),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==r?void 0:r.videoCodec,d=a&&2===parseInt(a);let c=!1,h=!1,u=1/0,f=1/0,g=1/0,p=1/0,m=0,v=[];const{preferHDR:y,allowedVideoRanges:E}=Pl(e,r);for(let e=n.length;e--;){const s=t[n[e]];c||(c=s.channels[2]>0),u=Math.min(u,s.minHeight),f=Math.min(f,s.minFramerate),g=Math.min(g,s.minBitrate),E.filter(t=>s.videoRanges[t]>0).length>0&&(h=!0)}u=Vn(u)?u:0,f=Vn(f)?f:0;const T=Math.max(1080,u),S=Math.max(30,f);g=Vn(g)?g:s,s=Math.max(g,s),h||(e=void 0);const A=n.length>1;return{codecSet:n.reduce((e,i)=>{const r=t[i];if(i===e)return e;if(v=h?E.filter(t=>r.videoRanges[t]>0):[],A){if(r.minBitrate>s)return Cl(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),e;if(!r.hasDefaultAudio)return Cl(i,"no renditions with default or auto-select sound found"),e;if(o&&i.indexOf(o.substring(0,4))%5!=0)return Cl(i,`audio codec preference "${o}" not found`),e;if(a&&!d){if(!r.channels[a])return Cl(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!o||d)&&c&&0===r.channels[2])return Cl(i,"no renditions with stereo sound found"),e;if(r.minHeight>T)return Cl(i,`min resolution of ${r.minHeight} > maximum of ${T}`),e;if(r.minFramerate>S)return Cl(i,`min framerate of ${r.minFramerate} > maximum of ${S}`),e;if(!v.some(t=>r.videoRanges[t]>0))return Cl(i,`no variants with VIDEO-RANGE of ${Dl(v)} found`),e;if(l&&i.indexOf(l.substring(0,4))%5!=0)return Cl(i,`video codec preference "${l}" not found`),e;if(r.maxScore<m)return Cl(i,`max score of ${r.maxScore} < selected max of ${m}`),e}return e&&(al(i)>=al(e)||r.fragmentError>t[e].fragmentError)?e:(p=r.minIndex,m=r.maxScore,i)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:p}}(i,A,t,b,L),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:d,preferHDR:c}=r;I=d,S=n,A=c?a[a.length-1]:a[0],_=o,t=Math.max(t,l),this.log(`picked start tier ${Dl(r)}`)}else S=null==y?void 0:y.codecSet,A=null==y?void 0:y.videoRange;const k=c?c.duration:d?d.duration:0,w=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let o=s;o>=e;o--){var D;const e=f[o],d=o>u;if(!e)continue;if(v.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&yl(e,R,A,_,t,b)?(e.supportedPromise=El(e,R,s,this.supportedCache),e.supportedPromise.then(t=>{if(!this.hls)return;e.supportedResult=t;const s=this.hls.levels,i=s.indexOf(e);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${i} ${Dl(t)}`):t.supported?t.decodingInfoResults.some(t=>!1===t.smooth||!1===t.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${i} not smooth or powerEfficient: ${Dl(t)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${i} ${Dl(t)}`),i>-1&&s.length>1&&(this.log(`Removing unsupported level ${i}`),this.hls.removeLevel(i),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(t=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${t}`)})):e.supportedResult=ml}if((S&&e.codecSet!==S||A&&e.videoRange!==A||d&&_>e.frameRate||!d&&_>0&&_<e.frameRate||null!=(D=e.supportedResult)&&null!=(D=D.decodingInfoResults)&&D.some(t=>!1===t.smooth))&&(!T||o!==I)){P.push(o);continue}const g=e.details,m=(c?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||k||1;let y;y=d?a*t:n*t;const L=k&&i>=2*k&&0===r?e.averageBitrate:e.maxBitrate,C=this.getTimeToLoadFrag(w,y,L*m,!g||g.live);if(y>=L&&(o===l||0===e.loadError&&0===e.fragmentError||Ca(e,v.errorPenaltyExpireMs))&&(C<=w||!Vn(C)||E&&!this.bitrateTestDelay||C<h)){const t=this.forcedAutoLevel;return o===p||-1!==t&&t===p||(P.length&&this.trace(`Skipped level(s) ${P.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[P[0]].codecs}" ${f[P[0]].videoRange}; not compatible with "${S}" ${A}`),this.info(`switch candidate:${u}->${o} adjustedbw(${Math.round(y)})-bitrate=${Math.round(y-L)} ttfb:${w.toFixed(1)} avgDuration:${m.toFixed(1)} maxFetchDuration:${h.toFixed(1)} fetchDuration:${C.toFixed(1)} firstSelection:${T} codecSet:${e.codecSet} videoRange:${e.videoRange} hls.loadLevel:${p}`)),T&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){if(!this.hls)return-1;const{maxAutoLevel:e,minAutoLevel:s}=this.hls;return Math.min(Math.max(t,s),e)}},bufferController:class BufferController extends Logger{constructor(t,e){var s;super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=t=>{var e;this.hls&&"open"===(null==(e=this.mediaSource)?void 0:e.readyState)&&this.media&&!this.media.seeking&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:e,mediaSource:s}=this;t&&this.log("Media source opened"),e&&s&&(Cc(s,"sourceopen",this._onMediaSourceOpen),Cc(e,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(zn.MEDIA_ATTACHED,{media:e,mediaSource:s}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){const t=this.media.error,{appendError:e,appendErrors:s}=this;let i=!1;if(!e&&t){i=Math.max(++s.audio,++s.video,++s.audiovideo)>=this.hls.config.appendErrorMaxRetry}const r=new Error(`MediaSource closed while media attached${lu(i,t)}`);this.warn(r),this.hls.trigger(zn.ERROR,Ta({fatal:i},e,{type:Wn.MEDIA_ERROR,details:Yn.MEDIA_SOURCE_REQUIRES_RESET,error:r}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&this.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this._onMediaError=()=>{const{media:t}=this;var e,s;t&&this.log(`Media error (code: ${null==(e=t.error)?void 0:e.code}): ${null==(s=t.error)?void 0:s.message}`)},this.hls=t,this.fragmentTracker=e,this.appendSource=(s=Ba(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null,this._onMediaEmptied=this._onMediaError=null}registerListeners(){const{hls:t}=this;t.on(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.on(zn.BUFFER_RESET,this.onBufferReset,this),t.on(zn.BUFFER_APPENDING,this.onBufferAppending,this),t.on(zn.BUFFER_CODECS,this.onBufferCodecs,this),t.on(zn.BUFFER_EOS,this.onBufferEos,this),t.on(zn.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(zn.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(zn.FRAG_PARSED,this.onFragParsed,this),t.on(zn.FRAG_CHANGED,this.onFragChanged,this),t.on(zn.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.off(zn.BUFFER_RESET,this.onBufferReset,this),t.off(zn.BUFFER_APPENDING,this.onBufferAppending,this),t.off(zn.BUFFER_CODECS,this.onBufferCodecs,this),t.off(zn.BUFFER_EOS,this.onBufferEos,this),t.off(zn.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(zn.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(zn.FRAG_PARSED,this.onFragParsed,this),t.off(zn.FRAG_CHANGED,this.onFragChanged,this),t.off(zn.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const s={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const e=this.isQueued();(t||e)&&this.warn(`Transfering MediaSource with${e?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return i&&!this.sourceBufferCount&&i.mediaSource===e?Ta(s,i.tracks):this.sourceBuffers.forEach(t=>{const[e]=t;e&&(s[e]=Ta({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null}),{media:t,mediaSource:e,tracks:s}}initTracks(){this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(t,e){var s;let i=2;(e.audio&&!e.video||!e.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),null!=(s=this.transferData)&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(t,e){const s=this.media=e.media;this.transferData=this.overrides=void 0;const i=Ba(this.appendSource);if(i){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const r=this.mediaSource=e.mediaSource||new i;if(this.assignMediaSource(r),t)this._objectUrl=s.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{s.removeAttribute("src");const e=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||e&&r instanceof e,au(s),function(t,e){const s=self.document.createElement("source");s.type="video/mp4",s.src=e,t.appendChild(s)}(s,t),s.load()}catch(e){s.src=t}else s.src=t}Dc(s,"emptied",this._onMediaEmptied),Dc(s,"error",this._onMediaError),this.appendSource&&Dc(s,"seeking",this._onStartStreaming)}}assignMediaSource(t){var e,s;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(s=t.constructor)?void 0:s.name}`),Dc(t,"sourceopen",this._onMediaSourceOpen),Dc(t,"sourceended",this._onMediaSourceEnded),Dc(t,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Dc(t,"startstreaming",this._onStartStreaming),Dc(t,"endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const s=this.tracks,i=e.tracks,r=i?Object.keys(i):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${Dl(s,(t,e)=>"initSegment"===t?void 0:e)};\ntransfer tracks: ${Dl(i,(t,e)=>"initSegment"===t?void 0:e)}}`),!$a(i,s)){e.mediaSource=null,e.tracks=void 0;const r=t.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching(zn.MEDIA_DETACHING,{}),this.onMediaAttaching(zn.MEDIA_ATTACHING,e),void(t.currentTime=a))}this.transferData=void 0,r.forEach(t=>{const e=t,s=i[e];if(s){const t=s.buffer;if(t){const i=this.fragmentTracker,r=s.id;if(i.hasFragments(r)||i.hasParts(r)){const s=BufferHelper.getBuffered(t);i.detectEvictedFragments(e,s,r,null,null,!0)}const n=ou(e),a=[e,t];this.sourceBuffers[n]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,s)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const s=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(s?"transferring":"detaching")),s)this.sourceBuffers.forEach(([t])=>{t&&this.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===r.readyState;try{const e=r.sourceBuffers;for(let s=e.length;s--;)t&&e[s].abort(),r.removeSourceBuffer(e[s]);t&&r.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}Cc(r,"sourceopen",this._onMediaSourceOpen),Cc(r,"sourceended",this._onMediaSourceEnded),Cc(r,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Cc(r,"startstreaming",this._onStartStreaming),Cc(r,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(Cc(i,"emptied",this._onMediaEmptied),Cc(i,"error",this._onMediaError),Cc(i,"seeking",this._onStartStreaming),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&au(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const s=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),s)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(e){this.warn(`onBufferReset ${t}`,e)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[ou(t)]=[null,null];const e=this.tracks[t];e&&(this.clearBufferAppendTimeoutId(e),e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new BufferOperationQueue(this.tracks)}onBufferCodecs(t,e){var s;const i=this.tracks,r=Object.keys(e);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in e&&(i.audio||i.video)||i.audiovideo&&("audio"in e||"video"in e),a=!n&&this.sourceBufferCount&&this.media&&r.some(t=>!i[t]);n||a?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`):(r.forEach(t=>{var s,r;const n=e[t],{id:a,codec:o,levelCodec:l,container:d,metadata:c,supplemental:h}=n;let u=i[t];const f=null==(s=this.transferData)||null==(s=s.tracks)?void 0:s[t],g=null!=f&&f.buffer?f:u,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;u||(u=i[t]={buffer:void 0,listeners:[],codec:o,supplemental:h,container:d,levelCodec:l,metadata:c,id:a});const v=cl(p,m),y=null==v?void 0:v.replace(ru,"$1");let E=cl(o,l);const T=null==(r=E)?void 0:r.replace(ru,"$1");E&&v&&y!==T&&("audio"===t.slice(0,5)&&(E=dl(E,this.appendSource)),this.log(`switching codec ${p} to ${E}`),E!==(u.pendingCodec||u.codec)&&(u.pendingCodec=E),u.container=d,this.appendChangeType(t,d,E))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&"main"===(null==(s=e.audio)?void 0:s.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,e)=>{const s=this.tracks[e];return t[e]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},t},{})}appendChangeType(t,e,s){const i=`${e};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const r=this.tracks[t];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${t} sourceBuffer type to ${i}`),n.changeType(i),r.codec=s,r.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(r,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const s=t.start,i=s+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(s,da))?void 0:e.gap))return;const r={label:"block-audio",execute:()=>{var t,e;(this.lastVideoAppendEnd>i||BufferHelper.isBuffered(null==(t=this.tracks.video)?void 0:t.buffer,i)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,da))?void 0:e.gap))&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.append(r,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(t,e){const{tracks:s}=this,{data:i,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:d}=e,c=l.buffering[r],h=pa(a)&&!o&&!a.gap&&!l.partial&&!l.iframe;let u=null,f=!1;const{sn:g,cc:p}=a,m=self.performance.now();c.start=m;const v=a.stats.buffering,y=o?o.stats.buffering:null;0===v.start&&(v.start=m),0===(null==y?void 0:y.start)&&(y.start=m);const E=s.audio;let T=!1;"audio"===r&&"audio/mpeg"===(null==E?void 0:E.container)&&(T=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const S=s.video,A=null==S?void 0:S.buffer;if(A&&"initSegment"!==g&&void 0!==d){const t=null==E?void 0:E.buffer,e=o||a;if("audio"===r&&"main"!==n&&!S.ending&&!S.ended&&t&&BufferHelper.getBuffered(t).length){const t=e.start+.05*e.duration,s=BufferHelper.getBuffered(A),i=this.currentOp("video");s.length||i?!BufferHelper.isBuffered(A,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}else if("video"===r){const t=e.end,s=this.lastVideoAppendEnd-t;this.lastVideoAppendEnd=t,s<0||s>e.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}const _=(o||a).start,b={label:`append-${r}`,execute:()=>{var t;c.executeStart=self.performance.now();const e=null==(t=this.tracks[r])?void 0:t.buffer;e&&(h&&(u=BufferHelper.timeRangesToArray(BufferHelper.getBuffered(e)),f=hu(cu(u,a),a)),T?this.updateTimestampOffset(e,_,.1,r,g,p):void 0!==d&&Vn(d)&&this.updateTimestampOffset(e,d,1e-6,r,g,p)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[r]);const t=self.performance.now();c.executeEnd=c.end=t,0===v.first&&(v.first=t),0===(null==y?void 0:y.first)&&(y.first=t);const e={};if(this.sourceBuffers.forEach(([t,s])=>{t&&(e[t]=BufferHelper.getBuffered(s))}),h){const t=this.getFragmentAppendProgress(a),s=e[r];if(s&&u){const e=cu(BufferHelper.timeRangesToArray(s),a);t.progressed||(t.progressed=e-cu(u,a)>.001);const i=f&&hu(e,a);t.fullyBuffered[r]=(void 0===t.fullyBuffered[r]||t.fullyBuffered[r])&&i}}this.hls.trigger(zn.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:n,timeRanges:e})},onError:t=>{var e;this.clearBufferAppendTimeoutId(this.tracks[r]);const s=t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t;if(s&&!this._quotaEvictionPending[r]){const t=this.getBackBufferEvictionTarget(r,i.byteLength,a.type);if(t>0){this._quotaEvictionPending[r]=!0,this.log(`QuotaExceededError on "${r}" append sn: ${g} - evicting back buffer to ${t.toFixed(3)}s and retrying`);const e=this.getFlushOp(r,0,t),s=this.getClearEvictionPendingOp(r);return void this.insertNext([e,b,s],r)}this.warn(`QuotaExceededError on "${r}" sn: ${g} - no back buffer available to evict`)}h&&(this.getFragmentAppendProgress(a).errored=!0);const d={type:Wn.MEDIA_ERROR,parent:n,details:Yn.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:t,err:t,fatal:!1},c=null==(e=this.media)?void 0:e.error;if(t.name!==nu||0!==this.sourceBufferCount||this.media&&0!==this.pendingTrackCount){var u;s&&(d.details=Yn.BUFFER_FULL_ERROR);const e=++this.appendErrors[r],i=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${e}/${i+1} times to append segment in "${r}" sourceBuffer with error: ${t.message}`),e>=i&&(d.fatal=!s);const n=null==(u=this.mediaSource)?void 0:u.readyState;("ended"===n||"closed"===n||c)&&(this.warn(`MediaSource readyState "${n}" during SourceBuffer${lu(d.fatal,c)}`),d.details=Yn.MEDIA_SOURCE_REQUIRES_RESET)}else d.errorAction=ad(!0);this.appendError=d,this.hls.trigger(zn.ERROR,d),s&&this.hls&&this.trimBuffers(a.start,1)}};this.log(`queuing "${r}" append sn: ${g}${o?" p: "+o.index:""} of ${n} playlist ${a.level} cc: ${p} offset: ${d} bytes: ${i.byteLength}`),this.append(b,r,this.isPending(this.tracks[r]))}getClearEvictionPendingOp(t){return{label:"clear",execute:()=>{this._quotaEvictionPending[t]=!1,this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(t,e,s){return this.log(`queuing "${t}" remove ${e}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,s)},onStart:()=>{},onComplete:()=>{var i;const r=null==(i=this.tracks[t])?void 0:i.buffer;this.log(`Remove request ${e}-${s} from ${t} Source Buffer complete > buffer: ${r?Oc(BufferHelper.getBuffered(r)):"(detached)"}`),this.hls.trigger(zn.BUFFER_FLUSHED,{type:t,start:e,end:s})},onError:i=>{this.warn(`Failed to remove ${e}-${s} from "${t}" SourceBuffer`,i),this.hls.trigger(zn.BUFFER_FLUSHED,{type:t,start:0,end:0,error:i})}}}onBufferFlushing(t,e){const{type:s,startOffset:i,endOffset:r}=e;s&&"audio"!==s||this.unblockAudio(),s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([t])=>{t&&this.append(this.getFlushOp(t,i,r),t)})}onFragParsed(t,e){const{frag:s,part:i,chunkMeta:r}=e,n=[],a=i?i.elementaryStreams:s.elementaryStreams;a[ga]?n.push("audiovideo"):(a[ua]&&n.push("audio"),a[fa]&&n.push("video"));0===n.length&&this.log(`Fragments must have at least one ElementaryStreamType set. ${s.type} ${s.level} ${i?`part: ${i.index} of `:""}sn: ${s.sn}`),this.blockBuffers(()=>{const t=self.performance.now();s.stats.buffering.end=t,i&&(i.stats.buffering.end=t);const e=i?i.stats:s.stats;this.checkAppendProgress(s,i,r,n),this.hls&&(this.hls.trigger(zn.FRAG_BUFFERED,{frag:s,part:i,stats:e,id:s.type,chunkMeta:r}),!i&&s.gap&&e.retry&&this.log(`Nothing buffered for ${s.type} level: ${s.level} sn: ${s.sn} retries ${e.retry}`))},n).catch(t=>{this.warn(`Fragment buffered callback ${t.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){var s,i;const r=null==(s=this.hls)?void 0:s.config;if(!r)return;const{backBufferLength:n,frontBufferFlushThreshold:a}=r;this.trimBuffers(a,n,e.frag,e.previousFrag);const o=e.frag.elementaryStreams,{appendErrors:l}=this,d=null==(i=this.appendError)?void 0:i.sourceBufferName;Object.keys(o).forEach(t=>{o[t]&&(l[t]=0,t===d&&(this.appendError=void 0),"audio"===t||"video"===t?(l.audiovideo=0,"audiovideo"===d&&(this.appendError=void 0)):(l.audio=0,l.video=0,"audiovideo"!==d&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const e=this.tracks[t];if(e)return!e.ended||e.ending}return!1})}onBufferEos(t,e){var s;this.sourceBuffers.forEach(([t])=>{if(t){const s=this.tracks[t];e.type&&e.type!==t||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${t} buffer reached EOS`)))}});const i=!1!==(null==(s=this.overrides)?void 0:s.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)})?(this.unblockAudio(),i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:t}=this;"open"===(null==t?void 0:t.readyState)?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(zn.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})):(this.tracksEnded(),this.hls.trigger(zn.BUFFERED_TO_END,void 0))):"video"===e.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(null!==t){const e=this.tracks[t];e&&(e.ending=!1)}})}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,e){if(e.details===Yn.BUFFER_APPEND_ERROR&&e.frag){var s;const t=null==(s=e.errorAction)?void 0:s.nextAutoLevel;Vn(t)&&t!==e.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(t,e,s){const{media:i}=this;return i?this.fragmentTracker.getBackBufferEvictionEnd(i.currentTime,s,e):0}getFragmentAppendProgress(t){var e;const s=du(t);let i=this.fragmentAppendProgress[s];return(null==(e=i)?void 0:e.stats)!==t.stats&&(i={stats:t.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[s]=i),i}checkAppendProgress(t,e,s,i){if(e||!pa(t)||t.gap||s.iframe||s.partial)return;const r=du(t),n=this.fragmentAppendProgress[r];delete this.fragmentAppendProgress[r];const a=t.stats.buffering;if(a.start&&!a.first)return;const o=(null==n?void 0:n.stats)===t.stats?n:void 0;if(null!=o&&o.errored)return;const l=i.length>0&&i.every(t=>!0===(null==o?void 0:o.fullyBuffered[t]));if(null!=o&&o.progressed||l)return void delete this.appendsWithoutProgress[r];if(!o&&0===i.length)return;const d=(this.appendsWithoutProgress[r]||0)+1,c=this.hls;d>=c.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[r]:this.appendsWithoutProgress[r]=d,this.warn(`Fragment ${t.sn} of ${t.type} playlist ${t.level} appended ${d} time${d>1?"s":""} without buffered range growth`),c.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:t,chunkMeta:s,parent:t.type,appendsWithoutProgress:d,error:new Error(`Fragment append did not increase buffered coverage (${d})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(t,e,s,i){const{hls:r,details:n,media:a}=this;if(!a||null===n)return;if(!this.sourceBufferCount)return;const o=r.config,l=a.currentTime,d=n.levelTargetDuration;e=n.live&&null!==o.liveBackBufferLength?o.liveBackBufferLength:e;let c=-1/0;if(Vn(e)&&e>=0){const t=Math.max(e,d);c=Math.floor(l/d)*d-t}if(s){const t=this.getLoopBackBufferFlushEnd(s,null!=i?i:null);t>0&&(c=Math.max(c,t))}if(c>0&&this.flushBackBuffer(l,d,c),Vn(t)&&t>0){const e=Math.max(o.maxBufferLength,t),s=Math.max(e,d),i=Math.floor(l/d)*d+s;this.flushFrontBuffer(l,d,i)}}getLoopBackBufferFlushEnd(t,e){var s;const{media:i}=this;if(!1===(null==(s=this.hls)?void 0:s.config.loopBackBufferFlush)||null==i||!i.loop||!e||t.level<=e.level)return 0;const{video:r,audiovideo:n}=t.elementaryStreams;if(null!=r&&r.partial||null!=n&&n.partial)return 0;const a=this.getEarliestElementaryStreamStart(t)-.25;return a<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${t.level}, range [0-${a.toFixed(3)}]`),a)}getEarliestElementaryStreamStart(t){const{audio:e,video:s,audiovideo:i}=t.elementaryStreams;let r=t.start;return i?r=Math.min(r,i.startDTS):(e&&(r=Math.min(r,e.startDTS)),s&&(r=Math.min(r,s.startDTS))),r}flushBackBuffer(t,e,s){this.sourceBuffers.forEach(([t,e])=>{if(e){const a=BufferHelper.getBuffered(e);if(a.length>0&&s>a.start(0)){var i,r,n;this.hls.trigger(zn.BACK_BUFFER_REACHED,{bufferEnd:s});const e=this.tracks[t];if(null!=(i=this.details)&&i.live)this.hls.trigger(zn.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(null!=e&&e.ended&&(null==(r=this.media)||!r.loop||!1===(null==(n=this.hls)?void 0:n.config.loopBackBufferFlush)))return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(zn.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:t})}}})}flushFrontBuffer(t,e,s){this.sourceBuffers.forEach(([e,i])=>{if(i){const r=BufferHelper.getBuffered(i),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(s>a||t>=a&&t<=o)return;this.hls.trigger(zn.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:e})}})}getDurationAndRange(){var t;const{details:e,mediaSource:s}=this;if(!e||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const i=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&s.setLiveSeekableRange){const t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,i)}}return{duration:1/0}}const r=null==(t=this.overrides)?void 0:t.duration;if(r)return Vn(r)?{duration:r}:null;const n=this.media.duration;return i>(Vn(s.duration)?s.duration:0)&&i>n||!Vn(n)?{duration:i}:null}updateMediaSource({duration:t,start:e,end:s}){const i=this.mediaSource;i&&this.media&&"open"===i.readyState&&(i.duration!==t&&(Vn(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),i.duration=t),void 0!==e&&void 0!==s&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${e}-${s}.`),i.setLiveSeekableRange(e,s)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${Dl(s)}`),this.tracksReady){var i;const t=null==(i=this.transferData)?void 0:i.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,s])=>{if(e){const i=this.tracks[e];t[e]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(zn.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in t){const n=r,a=t[n];if(this.isPending(a)){const t=this.getTrackCodec(a,n),r=`${a.container};codecs=${t}`;a.codec=t,this.log(`creating sourceBuffer(${r})${this.currentOp(n)?" Queued":""} ${Dl(a)}`);try{const t=s.addSourceBuffer(r),i=ou(n),o=[n,t];e[i]=o,a.buffer=t}catch(t){var i;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(n),null==(i=this.operationQueue)||i.removeBlockers(),delete this.tracks[n],void this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:n,mimeType:r,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}clearBufferAppendTimeoutId(t){t&&(self.clearTimeout(t.bufferAppendTimeoutId),t.bufferAppendTimeoutId=void 0)}getTrackCodec(t,e){const s=t.supplemental;let i=t.codec;s&&("video"===e||"audiovideo"===e)&&sl(s,"video")&&(i=function(t,e){const s=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)el(e[t],"video")||s.push(e[t])}return e&&s.push(e),s.join(",")}(i,s));const r=cl(i,t.levelCodec);return r?"audio"===e.slice(0,5)?dl(r,this.appendSource):r:""}trackSourceBuffer(t,e){const s=e.buffer;if(!s)return;const i=this.getTrackCodec(e,t);this.tracks[t]={buffer:s,codec:i,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(t,e)=>{const s=e.removedRanges;null!=s&&s.length&&(this.log(`${t} buffer removed ${Oc(s)}`),this.hls.trigger(zn.BUFFER_FLUSHED,{type:t,start:s.start(0),end:s.end(s.length-1)}))})}get mediaSrc(){var t,e;const s=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==s?void 0:s.src}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e,s;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const i=this.currentOp(t);if(!i)return;i.onComplete();if(null==(s=this.tracks[t])||null==(s=s.buffer)?void 0:s.updating)return this.log(`${t} SourceBuffer updating on "updateend"`),void this.blockUntilOpen(()=>{this.shiftAndExecuteNext(t)});this.shiftAndExecuteNext(t)}onSBUpdateError(t,e){var s;const i=null==(s=this.mediaSource)?void 0:s.readyState,r=new Error(`${t} SourceBuffer error. MediaSource readyState: ${i}`);this.error(`${r.message}`,e),this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:r,fatal:!1});const n=this.currentOp(t);n&&n.onError(r)}updateTimestampOffset(t,e,s,i,r,n){const a=e-t.timestampOffset;Math.abs(a)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${e} (sn: ${r} cc: ${n})`),t.timestampOffset=e)}removeExecutor(t,e,s){const{media:i,mediaSource:r}=this,n=this.tracks[t],a=null==n?void 0:n.buffer;if(!i||!r||!a)throw new Error(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`);const o=Vn(i.duration)?i.duration:1/0,l=Vn(r.duration)?r.duration:1/0,d=Math.max(0,e);var c;if(d>=l)return null==(c=this.currentOp(t))||c.onComplete(),void this.shiftAndExecuteNext(t);const h=Math.min(s,o,l);if(!(h>d)||n.ending&&!n.ended)throw new Error(`Cannot remove ${h<=d?`invalid range (${d} >= ${h}) `:""}from the ${t} SourceBuffer${n.ending?" while track ending":""}`);n.ended=!1,this.log(`Removing [${d},${h}] from the ${t} SourceBuffer`),a.remove(d,h)}appendExecutor(t,e){const s=this.tracks[e],i=null==s?void 0:s.buffer;if(!i)throw new HlsJsTrackRemovedError(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);if(s.ending=!1,s.ended=!1,this.hls.config.appendTimeout!==1/0){const t=this.calculateAppendTimeoutTime(i);s.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(e,i,t),t)}i.appendBuffer(t)}appendTimeoutHandler(t,e,s){this.log(`Received timeout after ${s}ms for append on ${t} source buffer. Aborting and triggering error.`);try{e.abort()}catch(e){this.log(`Failed to abort append on ${t} source buffer after timeout.`)}const i=this.currentOp(t);i&&i.onError(new Error(`${t}-append-timeout`))}calculateAppendTimeoutTime(t){let e=10;this.details&&(e=this.details.levelTargetDuration);let s=2*e*1e3;if(null===this.media)return s;const i=BufferHelper.bufferInfo(t,this.media.currentTime,0);return i.len?(s=Math.max(1e3*i.len,s),Math.max(this.hls.config.appendTimeout,s)):s}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}isAudioBlocked(){var t;return"block-audio"===(null==(t=this.currentOp("audio"))?void 0:t.label)}isAudioBlocking(){return!!this.operationQueue&&this.operationQueue.audioBlocking()}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:s}=this,i=2===e.length&&this.isAudioBlocking()?[this.appendBlocker("video")]:e.map(t=>this.appendBlocker(t));return Promise.all(i).then(e=>{s===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(t=>{var e;const s=null==(e=this.tracks[t])?void 0:e.buffer;!s||s.updating||"audio"===t&&this.isAudioBlocked()||this.shiftAndExecuteNext(t)})}append(t,e,s){this.operationQueue&&this.operationQueue.append(t,e,s)}insertNext(t,e){this.operationQueue&&this.operationQueue.insertNext(t,e)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[e])=>t+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,e,s){const i=this.tracks[t];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,t);i.listeners.push({event:e,listener:n}),Dc(r,e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const s=e.buffer;s&&(e.listeners.forEach(t=>{Cc(s,t.event,t.listener)}),e.listeners.length=0)}},capLevelController:CapLevelController,errorController:class ErrorController extends Logger{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(zn.ERROR,this.onError,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(zn.ERROR,this.onError,this),t.off(zn.ERROR,this.onErrorOut,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===da?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,s=e.currentLevel;return null!=(t=e.loadLevelObj)&&t.details||-1===s?e.loadLevel:s}variantHasKey(t,e){if(t){var s;if(null!=(s=t.details)&&s.hasKey(e))return!0;const i=t.audioGroups;if(i){return this.hls.allAudioTracks.filter(t=>i.indexOf(t.groupId)>=0).some(t=>{var s;return null==(s=t.details)?void 0:s.hasKey(e)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var s;if(e.fatal)return;const i=this.hls,r=e.context;switch(e.details){case Yn.FRAG_LOAD_ERROR:case Yn.FRAG_LOAD_TIMEOUT:case Yn.KEY_LOAD_ERROR:case Yn.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case Yn.FRAG_PARSING_ERROR:if(null!=(s=e.frag)&&s.gap)return void(e.errorAction=ad());case Yn.FRAG_GAP:case Yn.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=zl);case Yn.PLAYLIST_UNCHANGED_ERROR:case Yn.LEVEL_EMPTY_ERROR:case Yn.LEVEL_PARSING_ERROR:{var n;const t=e.parent===da?e.level:i.loadLevel;e.details===Yn.LEVEL_EMPTY_ERROR&&null!=(n=e.context)&&null!=(n=n.levelDetails)&&n.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case Yn.LEVEL_LOAD_ERROR:case Yn.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.level)));case Yn.AUDIO_TRACK_LOAD_ERROR:case Yn.AUDIO_TRACK_LOAD_TIMEOUT:case Yn.SUBTITLE_LOAD_ERROR:case Yn.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const t=i.loadLevelObj;if(t&&(r.type===sa&&t.hasAudioGroup(r.groupId)||r.type===ia&&t.hasSubtitleGroup(r.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,i.loadLevel),e.errorAction.action=zl,void(e.errorAction.flags=Jl)}return;case Yn.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:zl,flags:td});case Yn.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Yn.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Yn.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:zl,flags:ed});case Yn.BUFFER_ADD_CODEC_ERROR:case Yn.REMUX_ALLOC_ERROR:case Yn.BUFFER_APPEND_ERROR:return void(e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)));case Yn.MEDIA_SOURCE_REQUIRES_RESET:return e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)),void(e.errorAction.flags|=id|sd);case Yn.INTERNAL_EXCEPTION:case Yn.BUFFER_APPENDING_ERROR:case Yn.BUFFER_APPEND_NO_PROGRESS:case Yn.BUFFER_FULL_ERROR:case Yn.LEVEL_SWITCH_ERROR:case Yn.BUFFER_STALLED_ERROR:case Yn.BUFFER_SEEK_OVER_HOLE:case Yn.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=ad())}e.type===Wn.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=ad())}getPlaylistRetryOrSwitchAction(t,e){const s=Ia(this.hls.config.playlistLoadPolicy,t),i=this.playlistError++;if(Pa(s,i,ba(t),t.response))return{action:Xl,flags:Zl,retryConfig:s,retryCount:i};const r=this.getLevelSwitchAction(t,e);return s&&(r.retryConfig=s,r.retryCount=i),r}getFragRetryOrSwitchAction(t){const e=this.hls,s=this.getVariantLevelIndex(t.frag),i=e.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=e.config,a=Ia(La(t)?n:r,t),o=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(i&&(t.details!==Yn.FRAG_GAP&&i.fragmentError++,!Ra(t))){if(Pa(a,o,ba(t),t.response))return{action:Xl,flags:Zl,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(t,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const s=this.hls;null==e&&(e=s.loadLevel);const i=this.hls.levels[e];if(i){var r,n;const e=t.details;i.loadError++,i.loadErrorTime=self.performance.now(),e===Yn.BUFFER_APPEND_ERROR&&i.fragmentError++;let l=-1;const{levels:d,loadLevel:c,minAutoLevel:h,maxAutoLevel:u}=s;s.autoLevelEnabled||s.config.preserveManualLevelOnError||(s.loadLevel=-1);const f=null==(r=t.frag)?void 0:r.type,g=(f===ca&&e===Yn.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&rd(t))&&d.some(({audioCodec:t})=>i.audioCodec!==t),p="video"===t.sourceBufferName&&rd(t)&&d.some(({codecSet:t,audioCodec:e})=>i.codecSet!==t&&i.audioCodec===e),{type:m,groupId:v}=null!=(n=t.context)?n:{};for(let r=d.length;r--;){const n=(r+c)%d.length;if(n!==c&&n>=h&&n<=u&&(0===d[n].loadError||Ca(d[n],s.config.errorPenaltyExpireMs))){var a,o;const s=d[n];if(e===Yn.FRAG_GAP&&f===da&&t.frag){const e=d[n].details;if(e){const s=Kl(t.frag,e.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(m===sa&&s.hasAudioGroup(v)||m===ia&&s.hasSubtitleGroup(v))continue;if(f===ca&&null!=(a=i.audioGroups)&&a.some(t=>s.hasAudioGroup(t))||f===ha&&null!=(o=i.subtitleGroups)&&o.some(t=>s.hasSubtitleGroup(t))||g&&i.audioCodec===s.audioCodec||p&&i.codecSet===s.codecSet||!g&&i.audioCodec!==s.audioCodec)continue}l=n;break}}if(l>-1&&s.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:zl,flags:Zl,nextAutoLevel:l}}return{action:zl,flags:Jl}}onErrorOut(t,e){var s,i;switch(null==(s=e.errorAction)?void 0:s.action){case Yl:break;case zl:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===Yn.FRAG_GAP||e.details===Yn.PLAYLIST_UNCHANGED_ERROR||nd(e)||(e.fatal=!0)}((null==(i=e.errorAction)?void 0:i.flags)||0)&id&&this.hls.recoverMediaError(),e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,s=t.errorAction;if(!s)return;let i=s.nextAutoLevel;if(s.flags===Zl)this.switchLevel(t,i);else if(s.flags&sd){const t=this.hls.levels;for(let e=t.length;e--;)"SDR"!==t[e].videoRange?(t[e].fragmentError++,t[e].loadError++):void 0===i&&(i=e)}else if(s.flags&td){const i=this.getVariantLevelIndex(t.frag),r=e.levels[i],n=null==r?void 0:r.attrs["HDCP-LEVEL"];s.hdcpLevel=n;const a="NONE"===n;n&&!a?(e.maxHdcpLevel=_l[_l.indexOf(n)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)):(a&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),s.flags|=ed)}if(s.flags&ed){const e=t.decryptdata;if(e){const i=this.hls.levels,a=i.length;for(let s=a;s--;){var r,n;if(this.variantHasKey(i[s],e))this.log(`Banned key found in level ${s} (${i[s].bitrate}bps) or audio group "${null==(r=i[s].audioGroups)?void 0:r.join(",")}" (${null==(n=t.frag)?void 0:n.type} fragment) ${oo(e.keyId||[])}`),i[s].fragmentError++,i[s].loadError++,this.log(`Removing level ${s} with key error (${t.error})`),this.hls.removeLevel(s)}const o=t.frag;if(this.hls.levels.length<a)s.resolved=!0;else if(o&&o.type!==da){const t=o.decryptdata;t&&!e.matches(t)&&(s.resolved=!0)}}}s.resolved||this.switchLevel(t,i)}switchLevel(t,e){if(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,t.details===Yn.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=gl(t.mimeType),s=this.hls.levels;for(let i=s.length;i--;)s[i][`${t.sourceBufferName}Codec`]===e&&(this.log(`Removing level ${i} for ${t.details} ("${e}" not supported)`),this.hls.removeLevel(i))}}},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(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(zn.MEDIA_DETACHING,this.onMediaDetaching,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)}}onMediaDetaching(){this.media=null}checkFPS(t,e,s){const i=performance.now();if(e){if(this.lastTime){const t=i-this.lastTime,r=s-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*r/t,o=this.hls;if(o.trigger(zn.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:s}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(zn.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=i,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)}},id3TrackController:class ID3TrackController{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(zn.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(zn.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(zn.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(zn.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(zn.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(zn.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(zn.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){this.media=e.media}onMediaAttached(){var t;const e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null;!!e.transferMedia||(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){return Lg(t,"metadata","id3","","hidden")}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Og();if(n)for(let t=0;t<r.length;t++){const e=r[t].type;if(e===lh.emsg&&!s||!i)continue;const a=io(r[t].data),o=r[t].pts;let l=o+r[t].duration;l>xg&&(l=xg);l-o<=0&&(l=o+.25);for(let t=0;t<a.length;t++){const s=a[t];if(!ro(s)){this.updateId3CueEnds(o,e);const t=Mg(n,o,l,s,e);t&&this.id3Track.track.addCue(t)}}}}updateId3CueEnds(t,e){var s;const i=null==(s=this.id3Track)?void 0:s.track.cues;if(i)for(let s=i.length;s--;){const r=i[s];r.type===e&&r.startTime<t&&r.endTime===xg&&(r.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let t;t="audio"===i?t=>t.type===lh.audioId3&&o:"video"===i?t=>t.type===lh.emsg&&a:t=>t.type===lh.audioId3&&o||t.type===lh.emsg&&a,kg(r.track,e,s,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=Og();if(s&&i&&!n){const{fragmentStart:e,fragmentEnd:i}=t;let r=this.assetCue;r?(r.startTime=e,r.endTime=i):a&&(r=this.assetCue=Mg(a,e,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=t,d=Object.keys(l);let c=this.dateRangeCuesAppended;var h;if(o&&e)if(null!=(h=o.track.cues)&&h.length){const t=Object.keys(c).filter(t=>-1===d.indexOf(t));for(let e=t.length;e--;){var u;const s=t[e],i=null==(u=c[s])?void 0:u.cues;delete c[s],i&&Object.keys(i).forEach(t=>{const e=i[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{o.track.removeCue(e)}catch(t){}}})}}else c=this.dateRangeCuesAppended={};const f=t.fragments[t.fragments.length-1];if(0!==d.length&&Vn(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<d.length;t++){const e=d[t],s=l[e],i=s.startTime,r=c[e],o=(null==r?void 0:r.cues)||{};let h=(null==r?void 0:r.durationKnown)||!1,u=xg;const{duration:f,endDate:g}=s;if(g&&null!==f)u=i+f,h=!0;else if(s.endOnNext&&!h){const t=d.reduce((t,e)=>{if(e!==s.id){const i=l[e];if(i.class===s.class&&i.startDate>s.startDate&&(!t||s.startDate<t.startDate))return i}return t},null);t&&(u=t.startTime,h=!0)}const p=Object.keys(s.attr);for(let t=0;t<p.length;t++){const l=p[t];if(!kd(l))continue;const d=o[l];if(d)!h||null!=r&&r.durationKnown?Math.abs(d.startTime-i)>.01&&(d.startTime=i,d.endTime=u):d.endTime=u;else if(a){let t=s.attr[l];wd(l)&&(t=lo(t));const r=Mg(a,i,u,{key:l,data:t},lh.dateRange);r&&(r.id=e,this.id3Track.track.addCue(r),o[l]=r,n&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||r.addEventListener("enter",this.onEventCueEnter)))}}c[e]={cues:o,dateRange:s,durationKnown:h}}}}},gapController:class GapController extends TaskLoop{constructor(t,e){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(zn.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(zn.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(zn.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;const s=this.media=e.media;Dc(s,"playing",this.onMediaPlaying),Dc(s,"waiting",this.onMediaWaiting),Dc(s,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:s}=this;s&&(Cc(s,"playing",this.onMediaPlaying),Cc(s,"waiting",this.onMediaWaiting),Cc(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var t;const e=(null==(t=this.hls)?void 0:t.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,e):e}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const e=this.getCurrentTime();this.media.currentTime<e||(this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e)}poll(t,e){var s,i;const r=null==(s=this.hls)?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,d=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,t!==e)return e&&(this.ended=0),this.moved=!0,a||(this.skipRetry=this.nudgeRetry=0,r.nudgeOnVideoHole&&!d&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(l||o)return void(o&&this.stallResolved(t));if(d)return this.skipRetry=this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(zn.MEDIA_ENDED,{stalled:!1})));if(!BufferHelper.getBuffered(n).length)return void(this.skipRetry=this.nudgeRetry=0);const c=BufferHelper.bufferInfo(n,t,0),h=this.fragmentTracker;h&&this.hls&&Cg(c,t,h,this.hls);const u=c.nextStart||0;if(a&&h&&this.hls){const e=wg(this.hls.inFlightFragments,t),s=c.len>2,i=!u||e||u-t>2&&!h.getPartialFragment(t);if(s||i)return;this.moved=!1}const f=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&h){if(!(c.len>0)&&!u)return;const e=Math.max(u,c.start||0)-t,s=!(null==f||!f.live)?2*f.targetduration:2,i=Dg(t,h);if(e>0&&(e<=s||i))return void(n.paused||this._trySkipBufferHole(i))}const g=r.detectStallWithCurrentTimeMs,p=self.performance.now(),m=this.waiting;let v=this.stalled;if(null===v){if(!(m>0&&p-m<g))return void(this.stalled=p);v=this.stalled=m}const y=p-v;if(!a&&(y>=g||m&&this.moved)&&this.hls){var E;if("ended"===(null==(E=this.mediaSource)?void 0:E.readyState)&&(null==f||!f.live)&&Math.abs(t-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(zn.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return;if(n.currentTime!==t){const e=t;return t=n.currentTime,this.moved=!0,void this.log(`currentTime changed ${e} > ${t}`)}}const T=BufferHelper.bufferInfo(n,t,r.maxBufferHole);this._tryFixBufferStall(T,y,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(zn.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(s=this.buffered.audio)&&s.length&&i&&i.length>1&&t>i.end(0)){const s=BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio),t,0);if(s.len>1&&e>=s.start){const s=BufferHelper.timeRangesToArray(i),r=BufferHelper.bufferedInfo(s,e,0).bufferedIndex;if(r>-1&&r<s.length-1){const e=BufferHelper.bufferedInfo(s,t,0).bufferedIndex,i=s[r].end,n=s[r+1].start;if((-1===e||e>r)&&n-i<1&&t-i<2){const s=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${i} -> ${n} buffered index: ${e}`);this.warn(s.message),this.media.currentTime+=1e-6;let r=Dg(t,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);const a=BufferHelper.bufferInfo(this.media,t,0);this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(t,e,s){var i,r;const{fragmentTracker:n,media:a}=this,o=null==(i=this.hls)?void 0:i.config;if(!a||!n||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,d=Dg(s,n);if(d||null!=l&&l.live&&s<l.fragmentStart){if(this._trySkipBufferHole(d)||!this.media)return}const c=t.buffered,h=this.adjacentTraversal(t,s);(c&&c.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-s<o.maxBufferHole||h))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const s=this.fragmentTracker,i=t.nextStart;if(s&&i){const t=s.getFragAtPos(e,da),r=s.getFragAtPos(i,da);if(t&&r)return r.sn-t.sn<2}return!1}_reportStall(t){const{hls:e,media:s,stallReported:i,stalled:r}=this;if(!i&&null!==r&&s&&e){this.stallReported=!0;const i=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${Dl(t)})`);this.warn(i.message),e.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:t.len,bufferInfo:t,stalled:{start:r}})}}_trySkipBufferHole(t){const{fragmentTracker:e,media:s,hls:i}=this,r=null==i?void 0:i.config;if(!s||!e||!r)return 0;const n=s.currentTime,a=BufferHelper.bufferInfo(s,n,0);Cg(a,n,e,i);const o=n<a.start?a.start:a.nextStart;if(o){const d=a.len<=r.maxBufferHole,c=a.len>0&&a.len<1&&s.readyState<3,h=o-n;if(h>0&&(d||c)){if(h>r.maxBufferHole){let s=!1;if(0===n){const t=e.getAppendedFrag(0,da);t&&o<t.end&&(s=!0)}if(!s&&t){var l;if(null==(l=i.loadLevelObj)||!l.details)return 0;if(wg(i.inFlightFragments,o))return 0;let s=!1,r=t.end;for(;r<o;){const t=Dg(r,e),i=t?t.duration:0;if(!(i>0)){s=!0;break}r+=i}if(s)return 0}}const{nudgeMaxRetry:d,skipBufferHolePadding:c}=r,u=++this.skipRetry>d,f=Math.max(o,n)+c;if(u||(this.warn(`skipping hole, adjusting currentTime from ${n} to ${f}`),this.moved=!0,s.currentTime=f),null==t||!t.gap||u){const e=new Error(u?`Playhead still not moving after seeking over buffer hole from ${n} to ${f} after ${r.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${n} to ${f}`),s={type:Wn.MEDIA_ERROR,details:Yn.BUFFER_SEEK_OVER_HOLE,fatal:u,error:e,reason:e.message,buffer:a.len,bufferInfo:a};t&&("fragment"in t?s.part=t:s.frag=t),i.trigger(zn.ERROR,s)}return f}}return 0}_tryNudgeBuffer(t){const{hls:e,media:s,nudgeRetry:i}=this,r=null==e?void 0:e.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const a=n+(i+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),s.currentTime=a,e.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:t.len,bufferInfo:t})}else{const s=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(s.message),e.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.BUFFER_STALLED_ERROR,error:s,fatal:!0,buffer:t.len,bufferInfo:t})}}},latencyController:class LatencyController{constructor(t){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var t;const{media:e}=this,s=this.levelDetails;if(!e||!s||!this.hls)return;this.currentTime=e.currentTime;const i=this.hls.config,r=this.computeLatency();if(null===r)return;this._latency=r;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=i;if(!n||1===a||!s.live)return;const o=this.targetLatency;if(null===o)return;const l=r-o,d=l<Math.min(this.maxLatency,o+s.targetduration),c=Wc(i)&&!(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)||!t.event);if(d&&l>.05&&this.forwardBufferLength>1&&!c){const t=Math.min(2,Math.max(1,a)),s=Math.round(2/(1+Math.exp(-.75*l-this.edgeStalled))*20)/20,i=Math.min(t,Math.max(1,s));this.changeMediaPlaybackRate(e,i)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=t,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var t;const e=null==(t=this.hls)?void 0:t.config;if(!e)return 0;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const s=this.levelDetails;return s?e.liveMaxLatencyDurationCount*s.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||!this.hls)return null;const e=this.hls.config,{holdBack:s,partHoldBack:i,targetduration:r}=t,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=e,l=this.hls.userConfig;let d=o&&i||s;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===d)&&(d=void 0!==n?n:a*r);const c=r;return d+Math.min(this.stallCount*e.liveSyncOnStallIncrease,c)}set targetLatency(t){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=t,this._targetLatencyUpdated=!0)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e||!this.hls)return null;const s=this.levelDetails;if(null===s)return null;const i=s.edge,r=t-e-this.edgeStalled,n=i-s.totalduration,a=i-(this.hls.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(null===t||!this.hls)return 0;const e=3*(this.hls.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t}=this,e=this.levelDetails;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.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(zn.ERROR,this.onError,this),t.on(zn.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(zn.ERROR,this.onError,this),t.off(zn.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(t,e){var s;const i=this.hls,r=this.media||e.event.appendInPlace&&(null==i||null==(s=i.interstitialsManager)?void 0:s.playerQueue.reduce((t,e)=>t||e.media,null));i&&r&&r.playbackRate>1&&r.playbackRate<=i.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(r,1)}onError(t,e){var s;e.details===Yn.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(s=this.levelDetails)&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var s,i;t.playbackRate!==e&&(null==(s=this.hls)||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(i=this.targetLatency)?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}},{cueHandler:yp,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",ha),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.on(zn.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(zn.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(zn.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(zn.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(zn.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.off(zn.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(zn.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(zn.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(zn.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(zn.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,e){this.stopLoad(),this.state=xc,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,e){this.tracksBuffered=[],super.onMediaDetaching(t,e)}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:s,part:i,success:r}=e;if(!r)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a;const o=(i||s).start;for(let t=0;t<n.length;t++)if(o>=n[t].start&&o<=n[t].end){a=n[t];break}const l=o+(i||s).duration;if(a?a.end=l:(a={start:o,end:l},n.push(a)),!i||l>=s.end){const t=this.fragmentTracker.fragBuffered(s);i&&t&&(t.range.subs={time:[{startPTS:s.start,endPTS:l}],partial:!0}),pa(s)&&!this.fragContextChanged(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i),this.media&&this.tickImmediate()}}onBufferFlushing(t,e){const{startOffset:s,endOffset:i}=e;if(0===s&&i!==Number.POSITIVE_INFINITY){const t=i-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach(e=>{if(e)for(let s=0;s<e.length;)if(e[s].end<=t)e.shift();else{if(!(e[s].start<t))break;e[s].start=t,s++}}),this.fragmentTracker.removeFragmentsInRange(s,t,ha)}}onError(t,e){const s=e.frag;(null==s?void 0:s.type)===ha&&(e.details===Yn.FRAG_GAP&&this.fragmentTracker.addAsGap(s),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Mc&&(this.state=xc))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&su(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,ha),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var s;if(this.currentTrackId=e.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const i=this.levels[this.currentTrackId];null!=i&&i.details?(this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==Mc&&this.setInterval(500)):this.mediaBuffer=null}onSubtitleTrackLoaded(t,e){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:a}=e;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;const l=this.mainDetails;let d=0;if(n.live||null!=(s=o.details)&&s.live){if(n.deltaUpdateFailed)return;if(!l)return void(this.startFragRequested=!1);var c;if(o.details)d=this.alignPlaylists(n,o.details,null==(c=this.levelLastLoaded)?void 0:c.details);n.alignedSliding||(Pc(l,n,this),d=n.fragmentStart)}o.details=n,this.levelLastLoaded=o,l&&!this.startFragRequested&&this.setStartPosition(l,d),a===i&&(this.hls.trigger(zn.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:e.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(t){const{frag:e,part:s,payload:i}=t;s&&null!=i&&i.byteLength&&this.shouldDecrypt(e)&&this.decryptPayload(i,e,s)}_handleFragmentLoadComplete(t){const{frag:e,payload:s}=t;!this.fragContextChanged(e)&&null!=s&&s.byteLength&&this.shouldDecrypt(e)&&this.decryptPayload(s,e,null)}shouldDecrypt(t){const e=t.decryptdata;return!!(null!=e&&e.key&&e.iv&&Cd(e.method))}decryptPayload(t,e,s){const i=e.decryptdata,r=performance.now();this.decrypter.decrypt(new Uint8Array(t),i.key.buffer,i.iv.buffer,Od(i.method)).then(t=>{this.fragContextChanged(e)||this.hls.trigger(zn.FRAG_DECRYPTED,{frag:e,part:s,payload:t,stats:{tstart:r,tdecrypt:performance.now()}})}).catch(t=>{this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e,part:s}),s||(this.warn(`${t.name}: ${t.message}`),this.state=xc)})}doTick(){if(this.state===xc&&this.levels){var t;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;const{currentTrackId:s,levels:i}=this,r=i[s],n=null==r?void 0:r.details;if(!n||this.waitForLive(r)||this.waitForCdnTuneIn(n))return void(this.startFragRequested=!1);const{config:a}=this,o=this.playhead,l=BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],o,a.maxBufferHole),{end:d,len:c}=l;if(c>Math.max(this.hls.maxBufferLength+n.levelTargetDuration,(null==(t=this.hls.mainForwardBufferInfo)?void 0:t.len)||0)||c&&!this.buffering)return;let h=this.getNextFragment(d,n);if(!h)return;if(pa(h)){var e;const t=h.sn-n.startSN,s=n.fragments[t-1];h.cc!==(null==s?void 0:s.cc)||null!=(e=n.partList)&&e.length||this.fragmentTracker.getState(s)!==od||(h=s)}this.loadFragment(h,r,d)}}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);i!==od&&i!==dd||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.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1,e=!1;if(this.currentTrack){var s;const i=null==(s=this.currentTrack.trackNode)?void 0:s.track.mode;"showing"===i?(t=this.trackId,e=!0):"hidden"===i&&(t=this.trackId)}if(!e)for(let e=0;e<this.tracksInGroup.length;e++){var i;const s=null==(i=this.tracksInGroup[e].trackNode)?void 0:i.track.mode;if("showing"===s){t=e;break}t<0&&"hidden"===s&&(t=e)}var r;t>-1&&(this._subtitleDisplay="showing"===(null==(r=this.tracksInGroup[t].trackNode)?void 0:r.track.mode));this.setSubtitleTrack(t,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.on(zn.LEVEL_LOADING,this.onLevelLoading,this),t.on(zn.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(zn.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(zn.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.off(zn.LEVEL_LOADING,this.onLevelLoading,this),t.off(zn.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(zn.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(zn.ERROR,this.onError,this)}createTracksInGroup(){var t;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(t=>{t.trackNode||(t.trackNode=Lg(this.media,Rg(t),t.name,t.lang))});const e=null==(t=this.currentTrack)||null==(t=t.trackNode)?void 0:t.track;"disabled"===(null==e?void 0:e.mode)&&(e.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(t,e){const s=e.media;this.media=s;let i=this.trackId;this.queuedDefaultTrack>-1&&(i=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(i),this.createTracksInGroup(),this.useTextTrackPolling=!(s.textTracks&&"onchange"in s.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):s.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,e){const s=this.media;if(!s)return;const i=!!e.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,i||this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(t=>{const e=t.trackNode;e&&(e.track.mode="hidden",e.remove(),t.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} 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(!e)return;const s=e.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some(t=>-1===(null==i?void 0:i.indexOf(t)))){this.groupIds=s;const t=[];if(this.tracks.forEach(e=>{(e.textCodec===gg?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!s||s.indexOf(e.groupId)>-1?(e.id=t.length,t.push(e)):e.trackNode&&(e.trackNode.remove(),e.trackNode=void 0))}),t.length===this.tracksInGroup.length){let e=!1;for(let s=0;s<t.length;s++)if(t[s]!==this.tracksInGroup[s]){e=!0;break}if(!e)return}t.length&&this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=t,this.trackId=-1,this.currentTrack=null;const e=this.hls.config.subtitlePreference;if(!r&&e){this.selectDefaultTrack=!1;const s=xl(e,t);if(s>-1)r=t[s];else{const t=xl(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(zn.SUBTITLE_TRACKS_UPDATED,n),this.setSubtitleTrack(i),this.createTracksInGroup()}}findTrackId(t){const e=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<e.length;i++){const r=e[i];if((!s||r.default)&&(s||t)&&(!t||Fl(r,t)))return i}if(t){for(let s=0;s<e.length;s++){const i=e[s];if(iu(t.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const i=e[s];if(iu(t.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}onError(t,e){!e.fatal&&e.context&&e.context.type===ia&&e.context.id===this.trackId&&$l(e.context.groupId,this.groupIds)&&this.checkRetry(e)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t,!0)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){if(-1===t.id)return this.setSubtitleTrack(-1,!0),null;const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const s=this.currentTrack;if(s&&Fl(t,s))return s;const i=xl(t,this.tracksInGroup);if(i>-1){const t=this.tracksInGroup[i];return this.setSubtitleTrack(i,!0),t}if(s)return null;{const s=xl(t,e);if(s>-1)return e[s]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=t.id,i=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${s} "${t.name}" lang:${t.lang} group:${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(zn.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null,track:t})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;const t=this.currentTrack;this.tracksInGroup.forEach(e=>{if(e.trackNode){const s=e===t?this._subtitleDisplay?"showing":"hidden":"disabled",i=e.trackNode.track;i.mode!==s&&(i.mode=s)}})}setSubtitleTrack(t,e=!1){const s=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=t),t<-1||t>=s.length||!Vn(t))return void this.warn(`Invalid subtitle track id: ${t}`);const i=this.currentTrack,r=s[t]||null;if(this.trackId=t,this.currentTrack=r,e&&this.toggleTrackModes(),!r)return void(i&&this.hls.trigger(zn.SUBTITLE_TRACK_SWITCH,{id:t}));const n=!!r.details&&!r.details.live;if(r===i&&n)return;this.log(`Switching to subtitle-track ${t}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:a,groupId:o="",name:l,type:d,url:c}=r;this.hls.trigger(zn.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:d,url:c});const h=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(h)}},timelineController:class TimelineController{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.cueCache={},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}},t.on(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(zn.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(zn.FRAG_LOADING,this.onFragLoading,this),t.on(zn.FRAG_LOADED,this.onFragLoaded,this),t.on(zn.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(zn.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(zn.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(zn.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(zn.BUFFER_APPENDED,this.onBufferAppended,this),t.on(zn.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(zn.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(zn.FRAG_LOADING,this.onFragLoading,this),t.off(zn.FRAG_LOADED,this.onFragLoaded,this),t.off(zn.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(zn.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(zn.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(zn.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(zn.BUFFER_APPENDED,this.onBufferAppended,this),t.off(zn.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new OutputFilter(this,"textTrack1"),e=new OutputFilter(this,"textTrack2"),s=new OutputFilter(this,"textTrack3"),i=new OutputFilter(this,"textTrack4");this.cea608Parser1=new Cea608Parser(1,t,e),this.cea608Parser2=new Cea608Parser(3,s,i)}addCues(t,e,s,i,r){let n=!1;for(let t=r.length;t--;){const i=r[t],a=mp(i[0],i[1],e,s);if(a>=0&&(i[0]=Math.min(i[0],e),i[1]=Math.max(i[1],s),n=!0,a/(s-e)>.5))return}if(n||r.push([e,s]),this.config.renderTextTracksNatively){const r=this.cueCache[t];if(r){const t=this.Cues.newCue(null,e,s,i);t.length&&r.push.apply(r,t)}else{const r=this.captionsTracks[t].track;this.Cues.newCue(r,e,s,i)}}else{var a;const r=this.Cues.newCue(null,e,s,i),n=null==(a=this.captionsProperties[t])?void 0:a.media;this.hls.trigger(zn.CUES_PARSED,{type:"captions",cues:r,track:t,closedCaptions:n})}}onInitPtsFound(t,{id:e,timestampOffsets:s}){const{unparsedVttFrags:i}=this;e===da&&(this.initPTS=s),i.length&&(this.unparsedVttFrags=[],i.forEach(t=>{this.initPTS[t.frag.cc]?this.onFragLoaded(zn.FRAG_LOADED,t):this.hls.trigger(zn.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:s,cueCache:i,media:r}=this,{label:n,languageCode:a}=e[t];r&&(i[t]=[],s[t]=Lg(r,"captions",n,a,"hidden"))}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(zn.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}onMediaAttaching(t,e){this.media=e.media}onMediaDetaching(t,e){const s=!!e.transferMedia;if(this.media=null,!s){if(this.config.renderTextTracksNatively){const{captionsTracks:t,cueCache:e}=this;for(const s in t)t[s].remove(),delete e[s]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(t,e){const s=e.subtitleTracks||[];if(s.length&&!this.config.renderTextTracksNatively&&!su(this.tracks,s)){const t=s.map(t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}));this.hls.trigger(zn.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}this.tracks=s}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]}`,i=this.captionsProperties[s];i&&(i.label=t.name,t.lang&&(i.languageCode=t.lang),i.media=t)})}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===da){var s,i;const{cea608Parser1:t,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(s=null==(i=e.part)?void 0:i.index)?s:-1;t&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:s,payload:i}=e;var r;if(s.level<this.tracks.length&&s.type===ha)if(i.byteLength||null!=(r=s.initSegment)&&null!=(r=r.data)&&r.byteLength){const t=s.decryptdata,i="stats"in e;if(null==t||!t.encrypted||i){const t=this.tracks[s.level],i=this.vttCCs;i[s.cc]||(i[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),(null==t?void 0:t.textCodec)===gg?this._parseIMSC1(e):this._parseVTTs(e)}}else{const t="part"in e?e.part:null;this.hls.trigger(zn.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:t,error:new Error("Empty subtitle payload")})}}_parseIMSC1(t){const{frag:e,payload:s}=t,i="part"in t?t.part:null,r=this.hls;yg(s,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),r.trigger(zn.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e,part:i})},t=>{r.logger.log(`Cannot parse IMSC1 (sn: ${e.sn} @${e.start}): ${t}`),r.trigger(zn.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,part:i,error:t})})}_parseVTTs(t){var e;const{frag:s,payload:i}=t,r="part"in t?t.part:null,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[s.cc]&&-1===o)return void a.push(t);const l=this.hls,d=null==(e=s.initSegment)?void 0:e.data;fg(d?Uo(d,new Uint8Array(i)).buffer:i,this.initPTS[s.cc],this.vttCCs,s.cc,(r&&!d?r:s).start,t=>{this._appendCues(t,s.level),l.trigger(zn.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s,part:r})},e=>{const i=e.message.startsWith("Missing initPTS");l.logger.log(`${i?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${s.sn} @${s.start}): ${e}`),i?a.push(t):(this.config.enableIMSC1&&this._fallbackToIMSC1(t),l.trigger(zn.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:r,error:e}))})}_fallbackToIMSC1(t){const{frag:e,payload:s}=t,i=this.tracks[e.level];i.textCodec||yg(s,this.initPTS[e.cc],()=>{i.textCodec=gg,this._parseIMSC1(t)},()=>{i.textCodec="wvtt"})}_appendCues(t,e){const s=this.hls;if(this.config.renderTextTracksNatively){var i;const s=null==(i=this.tracks[e].trackNode)?void 0:i.track;if(!s||"disabled"===s.mode)return;t.forEach(t=>Ig(s,t))}else{const i=this.tracks[e];if(!i)return;const r=i.default?"default":"subtitles"+e;s.trigger(zn.CUES_PARSED,{type:"subtitles",cues:t,track:r,subtitleTrack:i})}}onFragDecrypted(t,e){const{frag:s}=e;s.type===ha&&this.onFragLoaded(zn.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=e;if(s.type!==da||"NONE"!==this.closedCaptionsForLevel(s))for(let t=0;t<i.length;t++){const e=i[t].bytes;if(e){this.cea608Parser1||this.initCea608Parsers();const s=this.extractCea608Data(e);this.cea608Parser1.addData(i[t].pts,s[0]),this.cea608Parser2.addData(i[t].pts,s[1])}}}onBufferAppended(t,e){if(this.config.renderTextTracksNatively){var s;const{type:t,timeRanges:i}=e;if("video"===t&&null!=(s=i[t])&&s.length){const{captionsTracks:t,cueCache:e}=this;Object.keys(e).forEach(s=>{var i;const r=null==(i=t[s])?void 0:i.track;if(r){const t=e[s];for(let e=0;e<t.length;e++)Ig(r,t[e])}delete e[s]})}}}onBufferFlushing(t,e){const{startOffset:s,endOffset:i,endOffsetSubtitles:r,type:n}=e,{media:a}=this;if(a&&!(a.currentTime<i)){if(!n||"video"===n){const{captionsTracks:t,cueCache:e}=this;Object.keys(t).forEach(e=>kg(t[e].track,s,i)),Object.keys(e).forEach(t=>{const r=e[t];for(let t=r.length;t--;){const e=r[t];e.startTime>=s&&e.endTime<=i&&r.splice(t,1)}})}this.config.renderTextTracksNatively&&0===s&&void 0!==r&&this.tracks.forEach(t=>{var e;const i=null==(e=t.trackNode)?void 0:e.track;i&&kg(i,s,r)})}}extractCea608Data(t){const e=[[],[]],s=31&t[0];let i=2;for(let r=0;r<s;r++){const s=t[i++],r=127&t[i++],n=127&t[i++];if(0===r&&0===n)continue;if(!!(4&s)){const t=3&s;0!==t&&1!==t||(e[t].push(r),e[t].push(n))}}return e}},audioStreamController:class AudioStreamController extends BaseStreamController{constructor(t,e,s){super(t,e,s,"audio-stream-controller",ca),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.on(zn.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(zn.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(zn.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(zn.BUFFER_RESET,this.onBufferReset,this),t.on(zn.BUFFER_CREATED,this.onBufferCreated,this),t.on(zn.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(zn.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(zn.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(zn.FRAG_LOADING,this.onFragLoading,this),t.on(zn.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.off(zn.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(zn.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(zn.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(zn.BUFFER_RESET,this.onBufferReset,this),t.off(zn.BUFFER_CREATED,this.onBufferCreated,this),t.off(zn.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(zn.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(zn.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(zn.FRAG_LOADING,this.onFragLoading,this),t.off(zn.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,e){const{frag:s,id:i,initPTS:r,timescale:n,trackId:a,timestampOffsets:o}=e;if(i===da){const t=s.cc,e=this.fragCurrent;if(this.initPTS=o,this.log(`InitPTS for cc: ${t} found from main: ${r/n} (${r}/${n}) trackId: ${a}`),this.mainAnchor=s,this.state===Vc){const e=this.waitingData;(!e&&!this.loadingParts||e&&e.frag.cc!==t)&&this.syncWithAnchor(s,null==e?void 0:e.frag)}else!this.hls.hasEnoughToStart&&e&&e.cc!==t?(e.abortRequests(),this.syncWithAnchor(s,e)):this.state===xc&&this.tick()}}getLoadPosition(){var t;return!this.startFragRequested&&this.nextLoadPosition>=0&&!1!==(null==(t=this.switchingTrack)?void 0:t.flushImmediate)?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,e){var s;const i=(null==(s=this.mainFragLoading)?void 0:s.frag)||null;if(e&&(null==i?void 0:i.cc)===e.cc)return;const r=(i||t).cc,n=ql(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===xc&&this.doTickIdle())}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=Mc);const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),s>0&&-1===t&&!e&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),t=s),this.state=xc,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,e||this.fragmentTracker.hasFragments(this.playlistType)||(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case xc:this.doTickIdle();break;case Bc:{const{levels:t,trackId:e}=this,s=null==t?void 0:t[e],i=null==s?void 0:s.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=Vc}break}case Uc:this.checkRetryDate();break;case Vc:{const t=this.waitingData;if(t){const{frag:e,part:s,cache:i,complete:r}=t,n=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=Nc;const t={frag:e,part:s,payload:i.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else n&&n.cc!==t.frag.cc&&this.syncWithAnchor(n,t.frag)}else this.state=xc}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime,this.checkFragmentChanged())}doTickIdle(){var t;const{hls:e,levels:s,media:i,trackId:r}=this,n=e.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==s||!s[r])return;const a=s[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=Bc,void(this.startFragRequested=!1);const l=this.getBufferOutput();this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,ua));const d=this.getFwdBufferInfo();if(null===d)return;if(!this.switchingTrack&&this._streamEnded(d,o))return e.trigger(zn.BUFFER_EOS,{type:"audio"}),void(this.state=Hc);const c=d.len,h=e.maxBufferLength,u=o.fragments,f=u[0].start,g=this.getLoadPosition(),p=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?g:d.end;if(this.switchingTrack&&i){const t=g;o.PTSKnown&&t<f&&t>=this.timelineOffset&&(d.end>f||d.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${t} -> ${f} + 0.05`),i.currentTime=f+.05)}if(c>=h&&!this.switchingTrack&&p<u[u.length-1].start)return;let m=this.getNextFragment(p,o);if(m&&this.isLoopLoading(m,p)&&(m=this.getNextFragmentLoopLoading(m,o,d,da,h)),!m)return void(this.bufferFlushed=!0);if(this.exceedsMaxBuffer(d,h,m))return;let v=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&pa(m)&&!m.endList&&(!o.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===cd&&(this.mainFragLoading=v=null),v&&pa(v))){if(m.start>v.end){const t=this.fragmentTracker.getFragAtPos(p,da);t&&t.end>v.end&&(v=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(m.start>v.end)return}this.loadFragment(m,a,p)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}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:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=e,e.flushImmediate||(this.nextTrackId=e.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(e),this.state!==Mc&&(this.setInterval(100),this.state=xc,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,e){this.mainDetails=e.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(zn.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(t,e){var s;const{levels:i}=this,{details:r,id:n,groupId:a,track:o}=e;if(!i)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=e,void(this.state!==Mc&&(this.state=Bc));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const d=i[n];let c=0;if(r.live||null!=(s=d.details)&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var h;if(d.details)c=this.alignPlaylists(r,d.details,null==(h=this.levelLastLoaded)?void 0:h.details);r.alignedSliding||(Pc(l,r,this),c=r.fragmentStart)}d.details=r,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(zn.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:e.groupId}),this.state!==Bc||this.waitForCdnTuneIn(r)||(this.state=xc),this.tick()}_handleFragmentLoadProgress(t){var e;const s=t.frag,{part:i,payload:r}=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 h=this.transmuxer;h||(h=this.transmuxer=new TransmuxerInterface(this.hls,ca,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(e=s.initSegment)?void 0:e.data;if(void 0!==u){const t=!1,e=i?i.index:-1,n=-1!==e,a=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount,r.byteLength,e,n,s.duration);h.push(r,f,c,"",s,i,d.totalduration,t,a,u)}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:i,cache:new ChunkCache,complete:!1};t.push(new Uint8Array(r)),this.state!==Mc&&(this.state=Vc)}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;const s=e.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===da&&pa(e.frag)&&(this.mainFragLoading=e,this.state===xc&&this.tick())}onFragBuffered(t,e){const{frag:s,part:i}=e;if(s.type===ca)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(pa(s)){const t=this.switchingTrack;t&&(this.bufferedTrack=t)}this.fragBufferedComplete(s,i),this.media&&this.tick()}else this.audioOnly||s.type!==da||s.elementaryStreams.video||s.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}getFwdBufferInfo(){const t=this.getBufferOutput();return super.getFwdBufferInfo(t,ca)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){const t=this.fragPlaying;if(!this.checkFragPlaying())return!1;const e=this.fragPlaying,s=null==t?void 0:t.level;return e&&e.level===s||(t&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(t,e){var s;if(e.fatal)this.state=Kc;else switch(e.details){case Yn.FRAG_GAP:case Yn.FRAG_PARSING_ERROR:case Yn.FRAG_DECRYPT_ERROR:case Yn.FRAG_LOAD_ERROR:case Yn.FRAG_LOAD_TIMEOUT:case Yn.KEY_LOAD_ERROR:case Yn.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ca,e);break;case Yn.AUDIO_TRACK_LOAD_ERROR:case Yn.AUDIO_TRACK_LOAD_TIMEOUT:case Yn.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Bc||(null==(s=e.context)?void 0:s.type)!==sa||(this.state=xc);break;case Yn.BUFFER_APPEND_NO_PROGRESS:if("audio"!==e.parent)return;e.frag&&(e.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${e.frag.sn} of track ${e.frag.level} as a gap after ${e.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(e.frag));break;case Yn.BUFFER_ADD_CODEC_ERROR:case Yn.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case Yn.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Yn.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==fa&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==fa){this.flushing=!1,this.bufferFlushed=!0,this.state===Hc&&(this.state=xc);const t=this.getBufferOutput();t&&(this.afterBufferFlushed(t,e),this.tick())}}_handleTransmuxComplete(t){var e;const s="audio",{hls:i}=this,{remuxResult:r,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:h,text:u,id3:f,initSegment:g}=r;if(this.fragContextChanged(o)||!c)return this.fragmentTracker.removeFragment(o),void(null!=g&&g.tracks&&this.resetTransmuxer());if(this.state=$c,h&&this.switchingTrack&&!this.switchingTrack.flushImmediate){const{config:t}=this,e=t.nextAudioTrackBufferFlushForwardOffset,s=Math.max(this.getLoadPosition()+e,o.start);super.flushMainBuffer(s,Number.POSITIVE_INFINITY,ca)}if(null!=g&&g.tracks){const t=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(d,g.tracks,t,n),i.trigger(zn.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:g.tracks})}if(h){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=h;l&&(l.elementaryStreams[ua]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(ua,t,e,s,i),this.bufferFragmentData(h,o,l,n)}if(null!=f&&null!=(e=f.samples)&&e.length){const t=Ta({id:s,frag:o,details:c},f);i.trigger(zn.FRAG_PARSING_METADATA,t)}if(u){const t=Ta({id:s,frag:o,details:c},u);i.trigger(zn.FRAG_PARSING_USERDATA,t)}}_bufferInitSegment(t,e,s,i){if(this.state!==$c)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const r=e.audio;r.id=ca;const n=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),1===(null==n?void 0:n.split(",").length)&&(r.levelCodec=n),this.hls.trigger(zn.BUFFER_CODECS,e);const a=r.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:a};this.hls.trigger(zn.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);var r;if(this.switchingTrack||i===od||i===dd)if(null!=(r=e.details)&&r.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=Vc;const s=this.mainDetails;s&&s.fragmentStart!==e.details.fragmentStart&&Pc(s,e.details,this)}else super.loadFragment(t,e,s);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack&&t.flushImmediate){const{name:e,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;Fl({name:e,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a},t,Nl)||(Bl(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:e}=this;this.bufferedTrack=t,this.switchingTrack=null,e.trigger(zn.AUDIO_TRACK_SWITCHED,Aa({},t))}get nextAudioTrack(){return this.nextTrackId}},audioTrackController:class AudioTrackController extends BasePlaylistController{constructor(t){super(t,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.on(zn.LEVEL_LOADING,this.onLevelLoading,this),t.on(zn.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(zn.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(zn.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.off(zn.LEVEL_LOADING,this.onLevelLoading,this),t.off(zn.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(zn.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(zn.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Audio track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} 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(!e)return;const s=e.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some(t=>-1===(null==i?void 0:i.indexOf(t)))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>$l(t.groupId,s));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!r&&e){const s=xl(e,t,Nl);if(s>-1)r=t[s];else{const t=xl(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const a={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(zn.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==i&&-1===o)this.setAudioTrack(i);else if(t.length&&-1===o){var n;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}}onError(t,e){!e.fatal&&e.context&&e.context.type===sa&&e.context.id===this.trackId&&$l(e.context.groupId,this.groupIds)&&this.checkRetry(e)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t,!1)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&Fl(t,i,Nl))return i;const r=xl(t,this.tracksInGroup,Nl);if(r>-1){const e=this.tracksInGroup[r];return this.setAudioTrack(r,"flushImmediate"in t&&t.flushImmediate),e}if(i){let i=e.loadLevel;-1===i&&(i=e.firstAutoLevel);const r=function(t,e,s,i,r){const n=e[i],a=e.reduce((t,e,s)=>{const i=e.uri;return(t[i]||(t[i]=[])).push(s),t},{}),o=a[n.uri];o.length>1&&(i=Math.max.apply(Math,o));const l=n.videoRange,d=n.frameRate,c=n.codecSet.substring(0,4),h=Ul(e,i,e=>{if(e.videoRange!==l||e.frameRate!==d||e.codecSet.substring(0,4)!==c)return!1;const i=e.audioGroups,n=s.filter(t=>$l(t.groupId,i));return xl(t,n,r)>-1});return h>-1?h:Ul(e,i,e=>{const i=e.audioGroups,n=s.filter(t=>$l(t.groupId,i));return xl(t,n,r)>-1})}(t,e.levels,s,i,Nl);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=xl(t,s);if(e>-1)return s[e]}}}return null}setAudioTrack(t,e=!0){const s=this.tracksInGroup;if(t<0||t>=s.length)return void this.warn(`Invalid audio track id: ${t}`);this.selectDefaultTrack=!1;const i=this.currentTrack,r=s[t],n=r.details&&!r.details.live;if(t===this.trackId&&r===i&&n)return;if(this.log(`Switching to audio-track ${t} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=t,this.currentTrack=r,this.hls.trigger(zn.AUDIO_TRACK_SWITCHING,Aa(Aa({},r),{},{flushImmediate:e})),n)return;const a=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(a)}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const i=e[s];if((!this.selectDefaultTrack||i.default)&&(!t||Fl(t,i,Nl)))return s}if(t){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(Fl({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o},e[t],Nl))return t}for(let s=0;s<e.length;s++){const i=e[s];if(iu(t.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const i=e[s];if(iu(t.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&Bl(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=t.id,i=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${s} "${t.name}" lang:${t.lang} group:${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(zn.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null,track:t})}},emeController:EMEController,cmcdController:class CMCDController{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(Cf)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(wf)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(Pf)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(Of)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(Df)},this.onSeeked=()=>{var t;this.initialized&&null!=(t=this.media)&&t.paused&&this.setPlayerState(Of)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=t=>{try{this.apply(t,{ot:_f,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const{frag:n,part:a}=t,o=this.hls.levels[n.level],l=this.getObjectType(n,o),d={d:1e3*(a||n).duration,ot:l};if(l===Lf||l===bf||l===Rf||null==l&&("main"===n.type||"audio"===n.type)){var e;const t=o.bitrate/1e3;d.br=[t];const{cmcd:i}=this.config,r=null!=(e=null==i?void 0:i.rtpSafetyFactor)?e:5;if(d.rtp=100*Math.round(t*r/100),l===Rf||null==l&&"main"===n.type){const t=this.getTopBandwidth()/1e3;Vn(t)&&(d.tb=[t]);const e=this.getLowestBandwidth()/1e3;Vn(e)&&(d.lb=[e])}const a=this.getBufferLength(n);if(Vn(a)){var s;d.bl=[a];const t=(null==(s=this.media)?void 0:s.playbackRate)||1;d.dl=100*Math.round(a/t/100)}this.playheadLevel&&(d.pb=[this.playheadLevel.bitrate/1e3]);const c=this.hls.maxAutoLevel;if(c>=0){const t=this.hls.levels[c];t&&(d.tpb=[t.bitrate/1e3])}}const c=a?this.getNextPart(a):this.getNextFrag(n);null!=c&&c.url&&c.url!==n.url&&(c.byteRange.length>0?d.nor=[(i=c.url,r={r:`${c.byteRange[0]}-${c.byteRange[1]}`},new uu(i,r))]:d.nor=[c.url]),this.apply(t,d)}catch(t){this.hls.logger.warn("Could not generate segment CMCD data.",t)}var i,r},this.recordFragmentResponse=(t,e,s)=>{var i;const{cmcd:r}=this.config,n=null==r||null==(i=r.eventTargets)?void 0:i.some(t=>{var e;return null==(e=t.events)?void 0:e.includes(Gu)});if(this.reporter&&s.loading.first>0&&n)try{this.reporter.recordResponseReceived({request:{url:t},status:e.code,resourceTiming:{startTime:s.loading.start,responseStart:s.loading.first,duration:s.loading.end-s.loading.start,encodedBodySize:s.total}})}catch(t){this.hls.logger.warn("Could not record fragment response 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.registerListeners())}createReporter(){var t,e;const{cmcd:s}=this.config;if(null==s)return;const i=s.version||1;if(this.reporter=new jf({sid:s.sessionId||this.hls.sessionId,cid:s.contentId,version:i,transmissionMode:!0===s.useHeaders?Uf:Nf,enabledKeys:null!=(t=s.includeKeys)?t:[...i>=Nu?Af:rf],eventTargets:(null!=(e=s.eventTargets)?e:[]).map(t=>{let{includeKeys:e}=t;return Aa(Aa({},_a(t,Qf)),{},{enabledKeys:null!=e?e:Af})})},s.loader),this.reporter.update({sf:qf,sta:this.playerState}),s.reporterCallback){const t=this.reporter,e={updateCustomData:e=>{Xf(e)&&t.update(e)},recordCustomEvent:(e,s={})=>{Xf(s)&&t.recordEvent(Hu,Aa({cen:e},s))}};s.reporterCallback(e)}this.reporter.start()}registerListeners(){const t=this.hls;t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(zn.MEDIA_DETACHED,this.onMediaDetached,this),t.on(zn.MEDIA_ENDED,this.onMediaEnded,this),t.on(zn.ERROR,this.onError,this),t.on(zn.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(zn.LEVEL_SWITCHED,this.onLevelSwitched,this),t.on(zn.BUFFER_APPENDED,this.onBufferInfoChange,this),t.on(zn.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){const t=this.hls;t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(zn.MEDIA_DETACHED,this.onMediaDetached,this),t.off(zn.MEDIA_ENDED,this.onMediaEnded,this),t.off(zn.ERROR,this.onError,this),t.off(zn.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(zn.LEVEL_SWITCHED,this.onLevelSwitched,this),t.off(zn.BUFFER_APPENDED,this.onBufferInfoChange,this),t.off(zn.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(t,e){const s=this.media=e.media;this.setPlayerState(this.media.autoplay?wf:Ff),Dc(s,"waiting",this.onWaiting),Dc(s,"play",this.onPlay),Dc(s,"playing",this.onPlaying),Dc(s,"pause",this.onPause),Dc(s,"seeking",this.onSeeking),Dc(s,"seeked",this.onSeeked),Dc(s,"ratechange",this.onRateChange)}onMediaDetached(){const t=this.media;t&&(Cc(t,"waiting",this.onWaiting),Cc(t,"play",this.onPlay),Cc(t,"playing",this.onPlaying),Cc(t,"pause",this.onPause),Cc(t,"seeking",this.onSeeking),Cc(t,"seeked",this.onSeeked),Cc(t,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(t,e){this.setPlayerState(Mf)}onManifestLoading(t,e){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(Ff)}onError(t,e){e.fatal&&(this.setPlayerState(xf),this.reporter&&this.reporter.recordEvent($u,{ec:[e.details]}))}onLevelSwitching(t,e){var s;if(!this.reporter)return;const i={br:[e.bitrate/1e3]},r=null==(s=e.details)?void 0:s.fragments[0];r&&(i.ot=this.getObjectType(r,e)),this.reporter.recordEvent(Bu,i)}onLevelSwitched(t,e){const s=this.hls.levels[e.level];s&&(this.playheadLevel=s)}setPlayerState(t){this.playerState=t,this.reporter&&this.reporter.update({sta:t})}getStreamType(){const t=this.hls.latestLevelDetails;if(t)return t.live?t.partList&&t.canBlockReload?zf:Yf:Wf}apply(t,e={}){var s;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:null==(s=this.media)?void 0:s.playbackRate,st:this.getStreamType()});const i=e.ot===If||e.ot===Lf||e.ot===Rf;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const r=this.reporter.createRequestReport({url:t.url,headers:t.headers},e);t.url=r.url,t.headers=r.headers}getNextFrag(t){var e;const s=null==(e=this.hls.levels[t.level])?void 0:e.details;if(s){const e=t.sn-s.startSN;return s.fragments[e+1]}}getNextPart(t){var e;const{index:s,fragment:i}=t,r=null==(e=this.hls.levels[i.level])||null==(e=e.details)?void 0:e.partList;if(r){const{sn:t}=i;for(let e=r.length-1;e>=0;e--){const i=r[e];if(i.index===s&&i.fragment.sn===t)return r[e+1]}}}getObjectType(t,e){const{type:s}=t;if("subtitle"===s)return kf;if("initSegment"===t.sn)return If;if("audio"===s)return bf;if("main"===s){if(t.hasStreams){const e=t.elementaryStreams;if(e.audiovideo)return Rf;if(e.video)return Lf;if(e.audio)return bf}if(e){const{audioCodec:t,videoCodec:s}=e;if(!this.hls.audioTracks.length){if(t&&s)return Rf;if(t)return bf}if(s)return Lf}}}getTopBandwidth(){let t=0;const e=this.hls,s=e.maxAutoLevel,i=s>-1?s+1:e.levels.length;return e.levels.slice(0,i).forEach(e=>{e.bitrate>t&&(t=e.bitrate)}),t>0?t:NaN}getLowestBandwidth(){let t=1/0;const e=this.hls,s=e.maxAutoLevel,i=s>-1?s+1:e.levels.length;return e.levels.slice(0,i).forEach(e=>{e.bitrate<t&&(t=e.bitrate)}),Vn(t)?t:NaN}getBufferLength(t){if(!this.media)return NaN;const e="audio"===t.type?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return e?1e3*e.len:NaN}getEventBufferLength(){if(!this.media)return NaN;const t=this.hls.mainForwardBufferInfo,e=this.hls.audioForwardBufferInfo;if(t&&e)return 1e3*Math.min(t.len,e.len);const s=t||e;return s?1e3*s.len:NaN}onBufferInfoChange(t,e){if(!this.reporter)return;const s=this.getEventBufferLength();Vn(s)&&this.reporter.update({bl:[s]})}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,i){e(t),this.loader.load(t,s,i)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,s=this.recordFragmentResponse,i=t||this.config.loader;return class CmcdFragmentLoader{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,r){e(t);const{onSuccess:n}=r;this.loader.load(t,i,Aa(Aa({},r),{},{onSuccess:(e,i,r,a)=>{n(e,i,r,a),s(t.url,e,i)}}))}}}},contentSteeringController:class ContentSteeringController extends Logger{constructor(t){super("content-steering",t.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.on(zn.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(zn.MANIFEST_PARSED,this.onManifestParsed,this),t.off(zn.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(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)===zl&&s.flags&Jl){const t=this.levels;let i=this._pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:s,pathwayId:i,type:n}=e.context;s&&t?r=this.getPathwayForGroupId(s,n,r):i&&(r=i)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!i&&t&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==r,s.resolved||e.details===Yn.BUFFER_APPEND_ERROR&&!e.fatal||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${Dl(i)} penalized: ${Dl(this.penalizedPathways)}`))}}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}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){let e;this._pathwayPriority=t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(t=>{i-s[t]>3e5&&delete s[t]});for(let i=0;i<t.length;i++){const r=t[i];if(r in s)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(e=this.getLevelsForPathway(r),e.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,bc(e),this.hls.trigger(zn.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}}}getPathwayForGroupId(t,e,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s<i.length;s++)if(e===sa&&i[s].hasAudioGroup(t)||e===ia&&i[s].hasSubtitleGroup(t))return i[s].pathwayId;return s}clonePathways(t){const e=this.levels;if(!e)return;const s={},i={};t.forEach(t=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some(t=>t.pathwayId===r))return;const o=this.getLevelsForPathway(n).map(t=>{const e=new AttrList(t.attrs);e["PATHWAY-ID"]=r;const n=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;n&&(s[e.AUDIO]=n,e.AUDIO=n),o&&(i[e.SUBTITLES]=o,e.SUBTITLES=o);const l=Jf(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new Level({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e<t.audioGroups.length;e++)d.addGroupId("audio",`${t.audioGroups[e]}_clone_${r}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)d.addGroupId("text",`${t.subtitleGroups[e]}_clone_${r}`);return d});e.push(...o),Zf(this.audioTracks,s,a,r),Zf(this.subtitleTracks,i,a,r)})}loadSteeringManifest(t){const e=this.hls.config,s=e.loader;let i;this.loader&&this.loader.destroy(),this.loader=new s(e);try{i=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==i.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);Al(i,"_HLS_pathway",this.pathwayId),Al(i,"_HLS_throughput",""+t)}const r={type:aa,responseType:"json",url:i.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,r)=>{this.log(`Loaded steering manifest: "${i}"`);const n=t.data;if(1!==(null==n?void 0: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,i).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);const d={steeringManifest:n,url:i.toString()};this.hls.trigger(zn.STEERING_MANIFEST_LOADED,d),l&&this.updatePathwayPriority(l)},onError:(t,e,s,i)=>{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 r=1e3*this.timeToLoad;if(429===t.code){const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}return void this.log(`Steering manifest ${e.url} rate limited`)}this.scheduleRefresh(this.uri||e.url,r)},onTimeout:(t,e,s)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var e;const s=null==(e=this.hls)?void 0:e.media;!s||s.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)},e)}},iframeController:class IFrameController extends Logger{constructor(t,e){var s;super("iframes",t.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,Kg||(s=e,Kg=class HlsIFramesOnly extends s{constructor(t,e,s,i){t.streamController||(t.streamController=IFrameStreamController),super(t),this._url=e,this.streamController.setInitPts(s),this.streamController.initDetails=i}loadSource(){}loadMediaAt(t,e=Hg){if(t<0)return;const s=Aa(Aa({},Hg),e);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,s)}}),Vg||(Vg=function(t){return class HlsImageIFramesOnly extends t{constructor(t,e,s,i){t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=ImageIFrameStreamController),t.capLevelController=void 0,t.bufferController=void 0,super(t,e,s,i)}attachImage(t){this.streamController.image=t}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(Gg)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}(Kg)),this.hls=t,this.iframeInstances=[],this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(zn.MANIFEST_LOADING,this.clearAsset,this),t.on(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(zn.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(zn.FRAG_BUFFERED,this.onFragBuffered,this),t.on(zn.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(zn.MANIFEST_LOADING,this.clearAsset,this),t.off(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(zn.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(zn.FRAG_BUFFERED,this.onFragBuffered,this),t.off(zn.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(t=>t.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(t,e){this.stats=e.stats,this.variableList=e.variableList}onLevelsUpdated(t,{levels:e}){var s;const i=null==(s=this.hls)?void 0:s.pathwayPriority;e.length&&i&&this.iframeInstances.forEach(t=>{t.pathwayPriority=i})}onInitPtsFound(t,{id:e,timestampOffsets:s}){e===da&&(this.initPTS=s)}onFragBuffered(t,e){var s;const i=this.hls;i&&i.hasEnoughToStart&&((null==(s=i.mainForwardBufferInfo)?void 0:s.len)||0)>10&&this.iframeInstances.forEach(t=>{var e;t.loadingEnabled||t.startLoad((null==(e=this.hls)||null==(e=e.media)?void 0:e.currentTime)||0)})}createIFramePlayer(t){var e;return this.createInstance(Kg,null==(e=this.hls)?void 0:e.iframeVariants,t)}createImageIFramePlayer(t){var e;const s=null==(e=this.hls)?void 0:e.iframeVariants.filter(t=>t.imageCodec);return this.createInstance(Vg,s,t,"image-")}createInstance(t,e,s,i){const{hls:r}=this;if(!r)return null;const{url:n,userConfig:a,latestLevelDetails:o,loadLevelObj:l,loadLevel:d,bandwidthEstimate:c,sessionId:h}=r,{stats:u,variableList:f}=this;if(null==e||!e.length||!u||!n)return null;const g=`${i||""}iframe-player-${this.instanceCounter++}`,p=r.levels,m=l||p[d],v=Gl(m,a.videoPreference),y=(null==m?void 0:m.pathwayId)||".",E=new t(Aa(Aa({},a),{},{loggerId:g,primarySessionId:h,videoPreference:v,abrEwmaDefaultEstimate:c,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},s),n,this.initPTS,o);return this.iframeInstances=this.iframeInstances.filter(t=>!t.url),this.iframeInstances.push(E),E.trigger(zn.MANIFEST_LOADED,{levels:e,contentSteering:{uri:"",pathwayId:y},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:u,networkDetails:null,url:n,variableList:f}),E}},interstitialsController:class InterstitialsController extends Logger{constructor(t,e){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled||!this.schedule)return;const e=t-this.timelinePos;if(Math.abs(e)<1/7056e5)return;const s=e<=-.01;-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),this.timelinePos=t,this.bufferedPos=t;const i=this.playingItem;if(!i)return void this.checkBuffer();if(s){this.schedule.resetErrorsInRange(t,t-e)&&this.updateSchedule(!0)}if(this.checkBuffer(),s&&t<i.start||t>=i.end){var r;const e=this.findItemIndex(i);let n=this.schedule.findItemIndexAtTime(t);if(-1===n&&(n=e+(s?-1:1),this.log(`seeked ${s?"back ":""}to position not covered by schedule ${t} (resolving from ${e} to ${n})`)),!this.isInterstitial(i)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!s&&n>e){const t=this.schedule.findJumpRestrictedIndex(e+1,n);if(t>e)return void this.setSchedulePosition(t)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(i)){const e=i.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,e))}return}const a=n.timelineStart,o=n.duration||0;var l;(s&&t<a||t>=a+o)&&(null!=(l=i.event)&&l.appendInPlace&&(this.clearAssetPlayers(i.event,i),this.flushFrontBuffer(t)),this.setScheduleToAssetAtTime(t,n))},this.onTimeupdate=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;if(-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();const e=this.playingItem;if(!e||this.playingLastItem)return;if(t>=e.end){this.timelinePos=e.end;const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}const s=this.playingAsset;if(!s)return;t>=s.timelineStart+(s.duration||0)&&this.setScheduleToAssetAtTime(t,s)},this.onScheduleUpdate=(t,e)=>{const s=this.schedule;if(!s)return;const i=this.playingItem,r=s.events||[],n=s.items||[],a=s.durations,o=t.map(t=>t.identifier),l=!(!r.length&&!o.length);(l||e)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map(t=>tp(t))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let d=null,c=null;i&&(d=this.updateItem(i,this.timelinePos),this.itemsMatch(i,d)?this.playingItem=d:this.waitingItem=null),this.waitingItem=this.updateItem(this.waitingItem);const h=this.bufferingItem;if(h&&(c=this.updateItem(h,this.bufferedPos),this.itemsMatch(h,c)?this.bufferingItem=c:h.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(h.event,null))),t.forEach(t=>{t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,null)})}),this.playerQueue.forEach(t=>{if(t.interstitial.appendInPlace){const e=t.assetItem.timelineStart,s=t.timelineOffset-e;if(s)try{t.timelineOffset=e}catch(i){Math.abs(s)>jg&&this.warn(`${i} ("${t.assetId}" ${t.timelineOffset}->${e})`)}}}),l||e){if(this.hls.trigger(zn.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(i)&&o.indexOf(i.event.identifier)>-1)return this.warn(`Interstitial "${i.event.identifier}" removed while playing`),void this.primaryFallback(i.event);i&&this.trimInPlace(d,i),h&&c!==d&&this.trimInPlace(c,h),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new AssetListLoader(t),this.schedule=new InterstitialsSchedule(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(zn.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(zn.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(zn.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(zn.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(zn.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(zn.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(zn.BUFFER_APPENDED,this.onBufferAppended,this),t.on(zn.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(zn.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(zn.MEDIA_ENDED,this.onMediaEnded,this),t.on(zn.ERROR,this.onError,this),t.on(zn.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(zn.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(zn.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(zn.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(zn.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(zn.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(zn.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(zn.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(zn.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(zn.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(zn.BUFFER_CODECS,this.onBufferCodecs,this),t.off(zn.BUFFER_APPENDED,this.onBufferAppended,this),t.off(zn.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(zn.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(zn.MEDIA_ENDED,this.onMediaEnded,this),t.off(zn.ERROR,this.onError,this),t.off(zn.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.getBufferingPlayer())||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){Cc(t,"play",this.onPlay),Cc(t,"pause",this.onPause),Cc(t,"seeking",this.onSeeking),Cc(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const s=this.media=e.media;Dc(s,"seeking",this.onSeeking),Dc(s,"timeupdate",this.onTimeupdate),Dc(s,"play",this.onPlay),Dc(s,"pause",this.onPause)}onMediaAttached(t,e){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===s)this.checkStart();else if(!i){this.clearScheduleState();const t=this.findItemIndex(s);this.setSchedulePosition(t)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const s=!!e.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.log(`Removing schedule state for detachedData and ${t}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,e=()=>t.bufferingItem||t.waitingItem,s=e=>e?t.getAssetPlayer(e.identifier):e,i=(e,i,n,a,o)=>{if(e){let l=e[i].start;const d=e.event;if(d){if("playout"===i||d.timelineOccupancy!==qg.Point){const t=s(n);(null==t?void 0:t.interstitial)===d&&(l+=t.assetItem.startOffset+t[o])}}else{l+=("bufferedPos"===a?r():t[a])-e.start}return l}return 0},r=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?n("primary"):Math.max(e,0)},n=e=>{var s,i;return null!=(s=t.primaryDetails)&&s.live?t.primaryDetails.edge:(null==(i=t.schedule)?void 0:i.durations[e])||0},a=(e,r)=>{var n,a;const o=t.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!t.schedule)return;t.log(`seek to ${e} "${r}"`);const l=t.effectivePlayingItem,d=t.schedule.findItemIndexAtTime(e,r),c=null==(a=t.schedule.items)?void 0:a[d],h=t.getBufferingPlayer(),u=null==h?void 0:h.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&t.itemsMatch(l,c);if(l&&(f||g)){const n=s(t.playingAsset),a=(null==n?void 0:n.media)||t.primaryMedia;if(a){const s="primary"===r?a.currentTime:i(l,r,t.playingAsset,"timelinePos","currentTime"),o=e-s,d=(f?s:a.currentTime)+o;if(d>=0&&(!n||f||d<=n.duration))return void(a.currentTime=d)}}if(c){let s=e;if("primary"!==r){const t=e-c[r].start;s=c.start+t}const i=!t.isInterstitial(c);if(t.isInterstitial(l)&&!l.event.appendInPlace||!i&&!c.event.appendInPlace){if(l){const n=t.findItemIndex(l);if(d>n){const e=t.schedule.findJumpRestrictedIndex(n+1,d);if(e>n)return void t.setSchedulePosition(e)}let a=0;if(i)t.timelinePos=s,t.checkBuffer();else{const t=c.event.assetList,s=e-(c[r]||c).start;for(let e=t.length;e--;){const i=t[e];if(i.duration&&s>=i.startOffset&&s<i.startOffset+i.duration){a=e;break}}}t.setSchedulePosition(d,a)}}else{const e=t.media||(f?null==h?void 0:h.media:null);e&&(e.currentTime=s)}}},o=()=>{const s=t.effectivePlayingItem;if(t.isInterstitial(s))return s;const i=e();return t.isInterstitial(i)?i:null},l={get bufferedEnd(){const s=e(),r=t.bufferingItem;var n;return r&&r===s&&(i(r,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(n=t.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const e=o(),s=t.effectivePlayingItem;return s&&s===e?i(s,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-s.playout.start:0},set currentTime(e){const s=o(),i=t.effectivePlayingItem;i&&i===s&&a(e+i.playout.start,"playout")},get duration(){const t=o();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var e;const s=null==(e=o())?void 0:e.event.assetList;return s?s.map(e=>t.getAssetPlayer(e.identifier)):[]},get playingIndex(){var e;const s=null==(e=o())?void 0:e.event;return s&&t.effectivePlayingAsset?s.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var e;return(null==(e=t.schedule)||null==(e=e.events)?void 0:e.slice(0))||[]},get schedule(){var e;return(null==(e=t.schedule)||null==(e=e.items)?void 0:e.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const s=e();return t.findItemIndex(s)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return r()},get currentTime(){const e=t.timelinePos;return e>0?e:0},set currentTime(t){a(t,"primary")},get duration(){return n("primary")},get seekableStart(){return t.seekableStart}},integrated:{get bufferedEnd(){return i(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){a(t,"integrated")},get duration(){return n("integrated")},get seekableStart(){return((e,s)=>{var i;if(0!==e&&"primary"!==s&&null!=(i=t.schedule)&&i.length){var r;const i=t.schedule.findItemIndexAtTime(e),n=null==(r=t.schedule.items)?void 0:r[i];if(n)return e+(n[s].start-n.start)}return e})(t.seekableStart,"integrated")}},skip:()=>{const e=t.effectivePlayingItem,s=null==e?void 0:e.event;if(s&&!s.restrictions.skip){const i=t.findItemIndex(e);if(s.appendInPlace){const t=e.playout.start+e.event.duration;a(t+.001,"playout")}else t.advanceAfterAssetEnded(s,i,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const e=this.playingItem,s=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&e&&s)&&this.findItemIndex(e)===s.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,e;if(null===this.mediaSelection)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(i=this.primaryMedia);const r=null==(e=i)?void 0:e.currentTime;return void 0!==r&&Vn(r)?r:void 0}get primaryMedia(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}isInterstitial(t){return!(null==t||!t.event)}retreiveMediaSource(t,e){const s=this.getAssetPlayer(t);s&&this.transferMediaFromPlayer(s,e)}transferMediaFromPlayer(t,e){const s=t.interstitial.appendInPlace,i=t.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&i)return void(this.detachedData={media:i});const s=t.transferMedia();this.log(`transfer MediaSource from ${t} ${Dl(s)}`),this.detachedData=s}else e&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(t,e){var s,i;if(t.media===e)return;let r=null;const n=this.hls,a=t!==n,o=a&&t.interstitial.appendInPlace,l=null==(s=this.detachedData)?void 0:s.mediaSource;let d;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),d="Primary";else{const t=this.getBufferingPlayer();t?(r=t.transferMedia(),this.detachedData=r,d=`${t}`):d=l?"detached MediaSource":"detached media"}if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${Dl(r)}`);else if(!this.detachedData||n.media===e){const t=this.playerQueue;t.length>1&&t.forEach(t=>{if(a&&t.interstitial.appendInPlace!==o){const e=t.interstitial;this.clearInterstitial(t.interstitial,null),e.appendInPlace=!1,e.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${e}`)}}),this.hls.detachMedia(),this.detachedData={media:e}}const c=r&&"mediaSource"in r&&"closed"!==(null==(i=r.mediaSource)?void 0:i.readyState);if(this.log(`${c?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${d} (media.currentTime: ${e.currentTime})`),!c&&!a)return void t.attachMedia(e);const h=c&&r?Aa({},r):{media:e},u=this.schedule;if(u&&a){const e=t.assetId===u.assetIdAtEnd;h.overrides={duration:u.duration,endOfStream:e||!1===t.appendInPlace}}if(!c&&o){const e=t,s=e.assetItem.timelineStart;if(s){const t=e.hls,i=Math.max(this.timelinePos-s,Number.EPSILON);t.startPosition!==i&&(this.log(`Set ${e} startPosition: ${i}`),t.config.startPosition=i,t.loadingEnabled&&t.startLoad(i))}}t.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,e=null==t?void 0:t.events,s=this.hls;if(!e||this.playbackDisabled||!this.media||!s)return;-1===this.bufferedPos&&(this.bufferedPos=0);const i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){if(!s.loadingEnabled)return void this.log("waiting for startLoad( <startPosition> )");const i=s.startPosition;if(this.timelinePos=i,0===e.length)this.setSchedulePosition(0);else if(e[0].cue.pre){this.log(sp("checkStart (preroll)",i));const s=t.findEventIndex(e[0].identifier);this.setSchedulePosition(s)}else if(i>=0||!this.primaryLive){this.log(sp("checkStart",i));const e=this.timelinePos=i>0?i:0,s=t.findItemIndexAtTime(e);this.setSchedulePosition(s)}else 0===s.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(r&&!this.playingItem){this.log(sp("checkStart (playing item)",r.start));const e=t.findItemIndex(r);this.setSchedulePosition(e)}}advanceAssetBuffering(t,e){const s=t.event,i=s.findAssetIndex(e),r=Xg(s,i);if(s.isAssetPastPlayoutLimit(r)){if(this.schedule){var n;const e=this.getNextItemIndex(t,!0),s=null==(n=this.schedule.items)?void 0:n[e];s&&this.bufferedToItem(s)}}else this.bufferedToEvent(t,r)}livePrerollResumption(t,e){if(t.cue.pre&&this.primaryLive&&!Vn(t.resumeOffset)&&this.hls){const t=this.getLiveStartPos();if(e){const e=this.getBufferingPlayer();return t+(null!=e&&e.interstitial.cue.pre?e.remaining:0)}return t}}getNextItemIndex(t,e){if(this.schedule){const s=this.livePrerollResumption(t.event,e);if(void 0!==s)return this.log(`find next item index @${s}`),this.schedule.findItemIndexAtTime(s)}return this.findItemIndex(t)+1}advanceAfterAssetEnded(t,e,s){const i=Xg(t,s);if(t.isAssetPastPlayoutLimit(i)){if(this.schedule){const s=this.schedule.items;if(s){const i=s[e],r=i.event?this.getNextItemIndex(i):e+1;if(r>=s.length)return void this.setSchedulePosition(-1);const n=t.resumeTime;this.timelinePos<n&&(this.log(sp("advanceAfterAssetEnded",n)),this.timelinePos=n,t.appendInPlace&&!s[r].event&&this.hls.startLoad(n+.01),this.checkBuffer(this.bufferedPos<n)),this.setSchedulePosition(r)}}}else{if(t.appendInPlace){const e=t.assetList[i];e&&this.advanceInPlace(e.timelineStart)}this.setSchedulePosition(e,i)}}setScheduleToAssetAtTime(t,e){const s=this.schedule;if(!s)return;const i=e.parentIdentifier,r=s.getEvent(i);if(r){const e=s.findEventIndex(i),n=s.findAssetIndex(r,t);this.advanceAfterAssetEnded(r,e,n-1)}}setSchedulePosition(t,e){var s;const i=null==(s=this.schedule)?void 0:s.items;if(!i||this.playbackDisabled)return;const r=t>=0?i[t]:null;this.log(`setSchedulePosition ${t}, ${e} (${r?tp(r):r}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const s=n.event,c=this.playingAsset,h=null==c?void 0:c.identifier,u=h?this.getAssetPlayer(h):null;if(u&&h&&(!this.eventItemsMatch(n,r)||void 0!==e&&h!==s.assetList[e].identifier)){var o;const e=s.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${e+1}/${s.assetList.length} ${Zg(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(zn.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:e,event:s,schedule:i.slice(0),scheduleIndex:t,player:u}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(s,this.findItemIndex(this.playingItem),e));this.retreiveMediaSource(h,r),!u.media||null!=(o=this.detachedData)&&o.mediaSource||u.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${s} ${tp(n)}`),s.hasPlayed=!0,this.hls.trigger(zn.INTERSTITIAL_ENDED,{event:s,schedule:i.slice(0),scheduleIndex:t}),s.cue.once&&this.hls)){var l;this.updateSchedule();const t=null==(l=this.schedule)?void 0:l.items;if(r&&t){const o=this.findItemIndex(r),l=this.livePrerollResumption(s);if(void 0!==l){let e=l;const r=this.getNextItemIndex(n);if(!this.isInterstitial(i[r])){var d;const t=null==(d=this.primaryDetails)?void 0:d.fragments;if(s.snapOptions.in&&t){const s=Kl(null,t,l);s&&(e=Math.min(Math.max(i[r].start,Yg(e,s)),i[r].end))}}if(this.log(sp("live join (preroll)",e)),this.timelinePos=e,r!==o&&(r||0===r))return void this.advanceSchedule(r,t,void 0,n,a)}this.advanceSchedule(o,t,e,n,a)}return}}this.advanceSchedule(t,i,e,n,a)}advanceSchedule(t,e,s,i,r){const n=this.schedule;if(!n)return;const a=e[t]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(e=>{const s=e.interstitial,i=n.findEventIndex(s.identifier);(i<t||i>t+1)&&this.clearInterstitial(s,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const r=a.event;if(void 0===s){const e=Xg(r,(s=r.cue.pre?0:n.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(e)||r.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(r,t,s);s=e}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let d=this.preloadAssets(r,s);if(this.eventItemsMatch(a,l||i)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${tp(a)} ${r.appendInPlace?"append in place":""}`),r.hasPlayed=!1,this.hls.trigger(zn.INTERSTITIAL_STARTED,{event:r,schedule:e.slice(0),scheduleIndex:t})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const c=r.assetList[s];if(!c)return void this.advanceAfterAssetEnded(r,t,s||0);if(d||(d=this.getAssetPlayer(c.identifier)),null===d||d.destroyed){const t=r.assetList.length;this.warn(`asset ${s+1}/${t} player destroyed ${r}`),d=this.createAssetPlayer(r,c,s),d.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(d,s,e,t,o),this.shouldPlay&&ep(d.media)}else a?(this.resumePrimary(a,t,i),this.shouldPlay&&ep(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var t;return null==(t=this.mediaSelection)?void 0:t.main.details}get primaryLive(){var t;return!(null==(t=this.primaryDetails)||!t.live)}resumePrimary(t,e,s){var i,r;this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(t),this.endedItem=null,this.log(`resuming ${tp(t)}`);let n=this.timelinePos;if(null!=(i=this.detachedData)&&i.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(n):((n<t.start||n>=t.end||n<this.seekableStart)&&(n=this.getPrimaryResumption(t,e),this.log(sp("resumePrimary",n)),this.timelinePos=n),this.attachPrimary(n,t)),!s)return;const a=null==(r=this.schedule)?void 0:r.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${tp(t)}`),this.hls.trigger(zn.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:e}),this.checkBuffer())}get seekableStart(){var t;return this.primaryLive&&(null==(t=this.primaryDetails)?void 0:t.fragmentStart)||0}getPrimaryResumption(t,e,s){const i=t.start;if(this.primaryLive){if(0===e)return this.hls.startPosition;const t=this.endedItem||this.playingItem,r=null!=t&&t.event?this.livePrerollResumption(t.event,s):void 0;if(void 0!==r)return r;const n=this.primaryDetails;if(n){const{fragmentStart:t,edge:e}=n;if(i<t||i>e&&!s){const s=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${i} [${t}-${e}]) snapping to liveSync ${s}`),s||t}}}return this.log(`primary resumption itemStart: ${i}`),i}getLiveStartPos(){var t;const e=this.hls.startPosition,s=this.hls.liveSyncPosition||0,i=3*((null==(t=this.primaryDetails)?void 0:t.targetduration)||10);return-1===e||s&&s-e<i?s||0:e}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);if(null!=e&&e.hls)return e.hls.bufferedToEnd;return BufferHelper.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,s){e?this.setBufferingItem(e):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(t,s)),s||(this.log(sp("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,s))}startLoadingPrimaryAt(t,e){const s=this.hls,{loadingEnabled:i,bufferingEnabled:r,startPosition:n}=s,a=s.hasEnoughToStart;if(this.log(`Start loading primary @${t} bufferedPos: ${this.bufferedPos} startPosition: ${n} skip seek: ${e} has enough ${a} loadingEnabled: ${i} bufferingEnabled: ${r}`),!e&&a||!i||Math.abs(n-t)>.1){const i=this.primaryDetails;if(null!=i&&i.live&&t+.5>=i.edge){const e=this.bufferingItem;return this.log(`Resume primary loading when live passes ${t} buffering item: ${e?tp(e):null}`),s.pauseBuffering(),void(this.bufferPastEdge=!0)}s.startLoad(t,e)}else r||s.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),null==(t=this.schedule)||t.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(zn.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(zn.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(-1===e.level||!this.schedule)return;const s=this.hls.levels[e.level];if(!s.details)return;const i=Aa(Aa({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i;const r=this.hls.startPosition;this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace,-1===r?0:r);if(this.schedule.items)if(this.effectivePlayingItem){if(this.bufferPastEdge){const t=this.primaryDetails,e=this.bufferedPos;if(null!=t&&t.live&&e+.5<t.edge){this.bufferPastEdge=!1;const s=this.bufferingItem;this.log(`Live edge ${t.edge} passed buffer: ${e} buffering item: ${s?tp(s):null}`);if((null==s?void 0:s.end)===1/0){const t=this.playingItem,i=this.isInterstitial(t)&&t.event.appendInPlace;this.hls.startLoad(Math.max(e,s.start),i)}else{const t=this.getBufferingPlayer();if(t){t.bufferedInPlaceToEnd(this.primaryMedia,t.currentTime)&&t.hls&&t.hls.trigger(zn.BUFFERED_TO_END,void 0)}}}}}else this.checkStart()}onAudioTrackUpdated(t,e){const s=this.hls.audioTracks[e.id],i=this.mediaSelection;if(!i)return void(this.altSelection=Aa(Aa({},this.altSelection),{},{audio:s}));const r=Aa(Aa({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(t,e){const s=this.hls.subtitleTracks[e.id],i=this.mediaSelection;if(!i)return void(this.altSelection=Aa(Aa({},this.altSelection),{},{subtitles:s}));const r=Aa(Aa({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(t,e){const s=Ml(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setAudioOption(e)||t.setAudioOption(s)))}onSubtitleTrackSwitch(t,e){const s=Ml(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setSubtitleOption(e)||-1!==e.id&&t.setSubtitleOption(s)))}onBufferCodecs(t,e){const s=e.tracks;s&&(this.requiredTracks=s)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const t=this.timelinePos;this.bufferedPos=t,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(let t=0;t<e.length;t++){const s=e[t];if(s.cue.post){const t=this.getEventItem(s.identifier);t&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){const e=this.playingItem;if(!this.playingLastItem&&e){const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}else this.shouldPlay=!1}updateItem(t,e){var s;const i=null==(s=this.schedule)?void 0:s.items;if(t&&i){return i[this.findItemIndex(t,e)]||null}return null}trimInPlace(t,e){if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach((e,s)=>{t.event.isAssetPastPlayoutLimit(s)&&this.clearAssetPlayer(e.identifier,null)});const s=t.end+.25,i=BufferHelper.bufferInfo(this.primaryMedia,s,0);if(i.end>s||(i.nextStart||0)>s){this.log(`trim buffered interstitial ${tp(t)} (was ${tp(e)})`);const i=!0;this.attachPrimary(s,null,i),this.flushFrontBuffer(s)}}}itemsMatch(t,e){return!!e&&(t===e||t.event&&e.event&&this.eventItemsMatch(t,e)||!t.event&&!e.event&&this.findItemIndex(t)===this.findItemIndex(e))}eventItemsMatch(t,e){var s;return!!e&&(t===e||t.event.identifier===(null==(s=e.event)?void 0:s.identifier))}findEventIndex(t){return this.schedule?this.schedule.findEventIndex(t):-1}getEventItem(t){if(this.schedule){var e;const s=null==(e=this.schedule.items)?void 0:e[this.findEventIndex(t)];if(this.isInterstitial(s)&&s.event.identifier===t)return s}}findItemIndex(t,e){return t&&this.schedule?this.schedule.findItemIndex(t,e):-1}updateSchedule(t=!1){var e,s;const i=this.mediaSelection;if(!i)return;const r=(null==(e=this.hls)?void 0:e.liveSyncPosition)||0;null==(s=this.schedule)||s.updateSchedule(i,[],r,t)}checkBuffer(t){var e;const s=null==(e=this.schedule)?void 0:e.items;if(!s)return;const i=BufferHelper.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=i.len<1),this.updateBufferedPos(i.end,s,t)}updateBufferedPos(t,e,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>t||!i)return;if(1===e.length&&this.itemsMatch(e[0],r))return void(this.bufferedPos=t);const n=this.playingItem,a=this.findItemIndex(n);let o=i.findItemIndexAtTime(t);if(this.bufferedPos<t){var l;const s=this.findItemIndex(r),i=Math.min(s+1,e.length-1),n=e[i];if((-1===o&&r&&t>=r.end||null!=(l=n.event)&&l.appendInPlace&&t+.01>=n.start)&&(o=i),this.isInterstitial(r)){const t=r.event;if(i-a>1&&!1===t.appendInPlace)return;if(0===t.assetList.length&&t.assetListLoader)return}if(this.bufferedPos=t,o>s&&o>a)this.bufferedToItem(n);else{const e=this.primaryDetails;this.primaryLive&&e&&t>e.edge-e.targetduration&&n.start<e.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else s&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(e[o]))}assetsBuffered(t,e){return 0!==t.event.assetList.length&&!t.event.assetList.some(t=>{const s=this.getAssetPlayer(t.identifier);return!(null!=s&&s.bufferedInPlaceToEnd(e))})}setBufferingItem(t){const e=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(t,e)&&s){const{items:i,events:r}=s;if(!i||!r)return e;const n=this.isInterstitial(t),a=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const o=a?a.remaining:e?e.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${tp(t)}`+(e?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const e=s.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((t,s)=>{const i=this.getAssetPlayer(t.identifier);i&&(s===e&&i.loadSource(),i.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(t=>t.pauseBuffering());this.hls.trigger(zn.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return e}bufferedToItem(t,e=0){const s=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==s){this.bufferingAsset=null;const e=this.getPrimaryResumption(t,this.findItemIndex(t),!0),s=this.bufferedPos=Math.max(e,Math.min(this.bufferedPos,t.end),this.timelinePos,t.start),i=this.detachedData;if(i)if(i.mediaSource){const e=!0;this.attachPrimary(s,t,e)}else this.startLoadingPrimaryAt(s);else{const t=this.playingItem,e=this.isInterstitial(t)&&t.event.appendInPlace;this.startLoadingPrimaryAt(s,e)}}}bufferedToEvent(t,e){const s=t.event,i=0===s.assetList.length&&!s.assetListLoader,r=s.cue.once;if(i||!r){const t=this.preloadAssets(s,e);if(null!=t&&t.interstitial.appendInPlace){const e=this.primaryMedia;e&&this.bufferAssetPlayer(t,e)}}}preloadAssets(t,e){const s=t.assetUrl,i=t.assetList.length,r=0===i&&!t.assetListLoader,n=t.cue.once;if(r){const r=t.timelineStart,n=this.playingItem,o=this.getBufferingPlayer();var a;if(t.appendInPlace)this.isInterstitial(n)||(null==n||null==(a=n.nextEvent)?void 0:a.identifier)!==t.identifier||this.flushFrontBuffer(r+.25);let l,d=0;if(o&&!o.interstitial.cue.pre||!this.primaryLive||(d=this.getLiveStartPos(),o&&(d+=o.remaining)),d&&!t.cue.pre&&!t.cue.post){const t=d-r;t>0&&(l=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${s?1:i} ${t}${d?` live-start: ${d} start-offset: ${l} (timeline-start: ${r})`:""}`),s)return this.createAsset(t,0,0,r,t.duration,s);const c=this.assetListLoader.loadAssetList(t,l);c&&(t.assetListLoader=c)}else if(!n&&i){for(let s=e;s<i;s++){const e=t.assetList[s],i=this.getAssetPlayerQueueIndex(e.identifier);-1!==i&&!this.playerQueue[i].destroyed||e.error||this.createAssetPlayer(t,e,s)}const s=t.assetList[e];if(s){const t=this.getAssetPlayer(s.identifier);return t&&t.loadSource(),t}}return null}flushFrontBuffer(t){const e=this.requiredTracks;if(!e)return;const s=this.primaryDetails;if(s&&t>=s.edge)return;this.log(`Removing front buffer starting at ${t}`);Object.keys(e).forEach(e=>{this.hls.trigger(zn.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:e})})}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let s=0;s<e.length;s++)if(t===e[s].assetId)return s;return-1}getAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);return this.playerQueue[e]||null}getBufferingPlayer(){const{playerQueue:t,primaryMedia:e}=this;if(e)for(let s=0;s<t.length;s++)if(t[s].media===e)return t[s];return null}createAsset(t,e,s,i,r,n){const a={parentIdentifier:t.identifier,identifier:Wg(t,n,e),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(t,a,e)}createAssetPlayer(t,e,s){const i=this.hls,r=i.userConfig,n=Gl(i.loadLevelObj||i.levels[i.currentLevel],r.videoPreference),a=i.audioTracks[i.audioTrack],o=i.subtitleTracks[i.subtitleTrack];let l=0;if(this.primaryLive||t.appendInPlace){const t=this.timelinePos-e.timelineStart;if(t>=0){const s=e.duration;s&&t<s&&(l=t)}}const d=e.identifier,c=Aa(Aa({},r),{},{maxMaxBufferLength:Math.min(15,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:l,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:a||r.audioPreference,subtitlePreference:o||r.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(c.timelineOffset=e.timelineStart));const h=c.cmcd;null!=h&&h.sessionId&&h.contentId&&(c.cmcd=Ta({},h,{contentId:dg(e.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${t} and asset ${d}`);const u=new HlsAssetPlayer(this.HlsPlayerClass,c,t,e);this.playerQueue.push(u),t.assetList[s]=e;let f=!0;const g=i=>{if(i.live){const e=new Error(`Interstitials MUST be VOD assets ${t}`),i={fatal:!0,type:Wn.OTHER_ERROR,details:Yn.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},r=this.findEventIndex(t.identifier);return void this.handleAssetItemError(i,t,r,s,e.message)}const r=i.edge-i.fragmentStart,n=e.duration;(f||null===n||r>n)&&(f=!1,this.log(`Interstitial asset "${d}" duration change ${n} > ${r}`),e.duration=r,this.updateSchedule())};u.on(zn.LEVEL_UPDATED,(t,{details:e})=>g(e)),u.on(zn.LEVEL_PTS_UPDATED,(t,{details:e})=>g(e)),u.on(zn.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const p=(t,e)=>{const s=this.getAssetPlayer(d);if(s&&e.tracks){s.off(zn.BUFFER_CODECS,p),s.tracks=e.tracks;const t=this.primaryMedia;this.bufferingAsset===s.assetItem&&t&&!s.media&&this.bufferAssetPlayer(s,t)}};u.on(zn.BUFFER_CODECS,p);u.on(zn.BUFFERED_TO_END,()=>{const e=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${e}`),!e||!this.schedule)return;const s=this.getEventItem(t.identifier);s&&this.advanceAssetBuffering(s,e.assetItem)});const m=e=>()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;this.shouldPlay=!0;const s=this.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,s,e)};return u.once(zn.MEDIA_ENDED,m(s)),u.once(zn.PLAYOUT_LIMIT_REACHED,m(1/0)),u.on(zn.ERROR,(e,i)=>{if(!this.schedule)return;const r=this.getAssetPlayer(d);if(i.details===Yn.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(t):(this.onTimeupdate(),void this.checkBuffer(!0));i.details!==Yn.BUFFER_SEEK_OVER_HOLE&&this.handleAssetItemError(i,t,this.findEventIndex(t.identifier),s,`Asset player error ${i.error} ${t}`)}),u.on(zn.DESTROYING,()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;const e=new Error(`Asset player destroyed unexpectedly ${d}`),i={fatal:!0,type:Wn.OTHER_ERROR,details:Yn.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(i,t,this.findEventIndex(t.identifier),s,e.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Zg(e)}`),this.hls.trigger(zn.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:s,event:t,player:u}),u}clearInterstitial(t,e){this.clearAssetPlayers(t,e),t.reset()}clearAssetPlayers(t,e){t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,e)})}resetAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);if(-1!==e){this.log(`reset asset player "${t}" after error`);const s=this.playerQueue[e];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(t,e){const s=this.getAssetPlayerQueueIndex(t);if(-1!==s){const t=this.playerQueue[s];this.log(`clear ${t} toSegment: ${e?tp(e):e}`),this.transferMediaFromPlayer(t,e),this.playerQueue.splice(s,1),t.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,s,i,r){const{interstitial:n,assetItem:a,assetId:o}=t,l=n.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(null==d?void 0:d.identifier)!==o&&(d&&(this.clearAssetPlayer(d.identifier,s[i]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${l} ${Zg(a)}`),this.hls.trigger(zn.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:e,event:n,schedule:s.slice(0),scheduleIndex:i,player:t})),this.bufferAssetPlayer(t,r)}bufferAssetPlayer(t,e){var s;if(!this.schedule)return;const{interstitial:i,assetItem:r}=t,n=this.getEventItem(i.identifier);if(!n)return;if(t.loadSource(),this.setBufferingItem(n),this.bufferingAsset=r,t.bufferedInPlaceToEnd(this.primaryMedia,t.currentTime))return void this.advanceAssetBuffering(n,r);const a=this.getBufferingPlayer();if(a===t)return;const o=i.appendInPlace;if(o&&!1===(null==a?void 0:a.interstitial.appendInPlace))return;const l=(null==a?void 0:a.tracks)||(null==(s=this.detachedData)?void 0:s.tracks)||this.requiredTracks;if(o&&r!==this.playingAsset){if(!t.tracks)return void this.log(`Waiting for track info before buffering ${t}`);if(l&&!$a(l,t.tracks)){const e=new Error(`Asset ${Zg(r)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(l)}')`),s={fatal:!0,type:Wn.OTHER_ERROR,details:Yn.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},n=i.findAssetIndex(r);return void this.handleAssetItemError(s,i,this.findEventIndex(i.identifier),n,e.message)}}this.transferMediaTo(t,e)}handleInPlaceStall(t){const e=this.schedule,s=this.primaryMedia;if(!e||!s)return;const i=s.currentTime,r=e.findAssetIndex(t,i),n=t.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||i-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${t} (media.currentTime: ${i})`),o&&(l/s.playbackRate<.5||a.bufferedInPlaceToEnd(s,a.currentTime))&&a.hls){const s=e.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,s,r)}}}}advanceInPlace(t){const e=this.primaryMedia;if(e&&e.currentTime<t){const s=`advance currentTime to ${t}, duration: ${e.duration}`;e.duration>t?(this.log(s),e.currentTime=t):this.log(`Cannot ${s}`)}}handleAssetItemError(t,e,s,i,r){if(t.details===Yn.BUFFER_STALLED_ERROR)return;const n=e.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n?Zg(n):n} ${t.error}`),!this.schedule)return;const a=(null==n?void 0:n.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,d=this.schedule.items,c=Ta({},t,{fatal:!1,errorAction:ad(!0),asset:n,assetListIndex:i,event:e,schedule:d,scheduleIndex:s,player:l});if(this.hls.trigger(zn.INTERSTITIAL_ASSET_ERROR,c),!t.fatal)return;const h=this.playingAsset,u=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(a,null),n.error=f),e.assetList.some(t=>!t.error))for(let t=i;t<e.assetList.length;t++)this.resetAssetPlayer(e.assetList[t].identifier);else e.error=f;this.updateSchedule(!0),e.error?this.primaryFallback(e):(null==h?void 0:h.identifier)===a?this.advanceAfterAssetEnded(e,s,i):(null==u?void 0:u.identifier)===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,u)}primaryFallback(t){const e=t.timelineStart,s=this.effectivePlayingItem,i=this.playingItem,r=this.seekableStart,n=this.hls.startPosition;let a=this.timelinePos;if(this.isInterstitial(s)){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${a} playing: ${tp(s)} startPosition: ${n} seekableStart: ${r} error: ${t.error}`),-1===a&&(a=n),a=Math.max(a,r);const i=this.updateItem(s,a);this.itemsMatch(s,i)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e))}else if(-1===a)return void this.checkStart();if(!this.schedule)return;if(!this.isInterstitial(i))return;const o=this.schedule.findItemIndexAtTime(a);this.setSchedulePosition(o)}onAssetListLoaded(t,e){var s,i;const r=e.event,n=r.identifier,a=e.assetListResponse.ASSETS;if(null==(s=this.schedule)||!s.hasEvent(n))return;const o=r.timelineStart,l=r.duration;let d=0;a.forEach((t,e)=>{const s=parseFloat(t.DURATION);this.createAsset(r,e,d,o+d,s,t.URI),d+=s}),r.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${l}) ${r}`);const c=this.waitingItem,h=(null==c?void 0:c.event.identifier)===n;this.updateSchedule();const u=null==(i=this.bufferingItem)?void 0:i.event;if(h){const t=this.findEventIndex(n),e=this.getEventItem(n);if(e){if(!this.playingItem&&this.timelinePos>e.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),void this.primaryFallback(r)}this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==u?void 0:u.identifier)===n){const t=r.assetList[0];if(t){const e=this.getAssetPlayer(t.identifier);if(u.appendInPlace){const t=this.primaryMedia;e&&t&&this.bufferAssetPlayer(e,t)}else e&&e.loadSource()}}}onError(t,e){if(this.schedule)switch(e.details){case Yn.ASSET_LIST_PARSING_ERROR:case Yn.ASSET_LIST_LOAD_ERROR:case Yn.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case Yn.BUFFER_STALLED_ERROR:{const t=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&t.event.appendInPlace)return void this.handleInPlaceStall(t.event);const e=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${null==e?void 0:e.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function _p(t,e,s){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"');if(void 0!==e.liveMaxUnchangedPlaylistRefresh){const t=e.liveMaxUnchangedPlaylistRefresh,a=(i=t,r=2,n=1/0,Math.max(r,Math.min(i,n)));a!==t&&s.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${t} to ${a}.`),e.liveMaxUnchangedPlaylistRefresh=a}var i,r,n;const a=bp(t),o=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const i=`${"level"===t?"playlist":t}LoadPolicy`,r=void 0===e[i],n=[];o.forEach(s=>{const o=`${t}Loading${s}`,l=e[o];if(void 0!==l&&r){n.push(o);const t=a[i].default;switch(e[i]={default:t},s){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}}}),n.length&&s.warn(`hls.js config: "${n.join('", "')}" setting(s) are deprecated, use "${i}": ${Dl(e[i])}`)}),Aa(Aa({},a),e)}function bp(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(bp):Object.keys(t).reduce((e,s)=>(e[s]=bp(t[s]),e),{}):t}function Lp(t,e){const s=t.loader;if(s!==FetchLoader&&s!==XhrLoader)e.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,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class LevelController extends BasePlaylistController{constructor(t,e){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.on(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(zn.FRAG_BUFFERED,this.onFragBuffered,this),t.on(zn.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(zn.LEVEL_LOADED,this.onLevelLoaded,this),t.off(zn.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(zn.FRAG_BUFFERED,this.onFragBuffered,this),t.off(zn.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let a=!1,o=!1,l=!1,d=!1;e.levels.forEach(t=>{const e=t.attrs,c=kp(t,s),{audioCodec:h,videoCodec:u,imageCodec:f,width:g,height:p}=t;if(!c)return void this.log(`Some or all CODECS not supported "${e.CODECS}"`);a||(a=!(!g||!p)),o||(o=!!u),l||(l=!!h),d||(d=!!f);const{CODECS:m,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=e,A=`${`${E||"."}-`}${t.bitrate}-${T}-${v}-${m}-${S}-${y}`;if(r[A])if(r[A].uri===t.url||t.attrs["PATHWAY-ID"])t.iframes||(r[A].addGroupId("audio",e.AUDIO),r[A].addGroupId("text",e.SUBTITLES));else{const e=n[A]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const s=this.createLevel(t);r[A]=s,i.push(s)}else{const e=this.createLevel(t);r[A]=e,n[A]=1,i.push(e)}}),this.filterAndSortMediaOptions(i,e,a,o,l,d)}createLevel(t){const e=new Level(t),s=t.supplemental;if(null!=s&&s.videoCodec&&!Ip(s.videoCodec,this.hls.config.preferManagedMediaSource)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(t.message),e.supportedResult=vl(t,[])}return e}filterAndSortMediaOptions(t,e,s,i,r,n){var a;let o=[],l=[],d=t;const c=(null==(a=e.stats)?void 0:a.parsing)||{},h=this.hls.config.preferManagedMediaSource;if((s||i)&&r&&(d=d.filter(({videoCodec:t,videoRange:e,width:s,height:i})=>{return(!!t||!(!s||!i))&&(!!(r=e)&&bl.indexOf(r)>-1);var r})),i&&n&&(d=d.filter(t=>!t.imageCodec)),0===d.length)return Promise.resolve().then(()=>{if(this.hls){let t="no level with compatible codecs found in manifest",s=t;e.levels.length&&(s=`one or more CODECS in variant not supported: ${Dl(e.levels.map(t=>t.attrs.CODECS).filter((t,e,s)=>s.indexOf(t)===e))}`,this.warn(s),t+=` (${s})`);const i=new Error(t);this.hls.trigger(zn.ERROR,{type:Wn.MEDIA_ERROR,details:Yn.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:i,reason:s})}}),void(c.end=performance.now());e.audioTracks&&(o=e.audioTracks.filter(t=>!t.audioCodec||Rp(t.audioCodec,h)),wp(o)),e.subtitles&&(l=e.subtitles,wp(l));const u=d.slice(0);d.sort((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return bl.indexOf(t.videoRange)-bl.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const s=nl(t.videoCodec),i=nl(e.videoCodec);if(s!==i)return i-s}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const s=al(t.codecSet),i=al(e.codecSet);if(s!==i)return i-s}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0});let f=u[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==u.length))for(let t=0;t<u.length;t++)if(u[t].pathwayId===d[0].pathwayId){f=u[t];break}this._levels=d;for(let t=0;t<d.length;t++)if(d[t]===f){var g;this._firstLevel=t;const e=f.bitrate,s=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${e}`),void 0===(null==(g=this.hls.userConfig)?void 0:g.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>s&&s===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const p=e.iframeVariants.filter(t=>kp(t,h));this._iframeVariants=p;const m=r&&!i,v=this.hls.config,y=!(!v.audioStreamController||!v.audioTrackController),E={levels:d,audioTracks:o,subtitleTracks:l,iframeVariants:p,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:i,altAudio:y&&!m&&o.some(t=>!!t.url)};c.end=performance.now(),this.hls.trigger(zn.MANIFEST_PARSED,E)}get iframeVariants(){return 0===this._iframeVariants.length?null:this._iframeVariants}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}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"),i=t<0;if(this.hls.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.LEVEL_SWITCH_ERROR,level:t,fatal:i,error:s,reason:s.message}),i)return;t=Math.min(t,e.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,s===t&&i&&r===a)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${r?" with Pathway "+r:""}`);const o={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(zn.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==i?void 0:i.details,l);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.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),s=t.filter(t=>-1!==e.indexOf(t));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);this.steering.pathwayPriority=s}}onError(t,e){!e.fatal&&e.context&&e.context.type===ea&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(e.type===da){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return;const s=this._levels[e.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(t,e){var s;const{level:i,details:r}=e,n=e.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||e.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let t=n.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(i,e,t)}else null!=(s=e.deliveryDirectives)&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=this.getUrlWithDirectives(t.uri,e),i=this.currentLevelIndex,r=t.attrs["PATHWAY-ID"],n=t.details,a=null==n?void 0:n.age;this.log(`Loading level index ${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger(zn.LEVEL_LOADING,{url:s,level:i,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){const e=this.currentLevelIndex;if(-1===this.manualLevelIndex&&t!==e&&-1!==t){const s=this.hls.config.abrSwitchInterval;if(s>0){const i=performance.now(),r=i-this.lastABRSwitchTime,n=1e3*s;if(this.lastABRSwitchTime>-1&&r<n)return void this.warn(`Preventing ABR level switch: ${e} -> ${t} (${Math.round(r)}ms < ${n}ms / ${s}s)`);this.lastABRSwitchTime=i,this.log(`Allowing ABR level switch: ${e} -> ${t} (${Math.round(r)}ms >= ${n}ms / ${s}s)`)}}this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(1===this._levels.length)return;const s=this._levels.filter((e,s)=>s!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach(t=>t.level=-1)),!1));bc(s),this._levels=s,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(zn.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(zn.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function Rp(t,e){return sl(t,"audio",e)}function Ip(t,e){return sl(t,"video",e)}function kp(t,e){let{audioCodec:s,videoCodec:i}=t;s&&(t.audioCodec=s=dl(s,e)||void 0),i&&(i=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&"avc1"===s[0]&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}(i));const{unknownCodecs:r}=t;return!((null==r?void 0:r.length)||0||s&&!Rp(s,e)||i&&!Ip(i,e))}function wp(t){const e={};t.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}class KeyLoader extends Logger{constructor(t,e){super("key-loader",e),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=t}abort(t){for(const s in this.keyLoaderInfo){const i=this.keyLoaderInfo[s].loader;if(i){var e;if(t&&t!==(null==(e=i.context)?void 0:e.frag.type))return;i.abort()}}}destroy(){for(const t in this.keyLoaderInfo){const e=this.keyLoaderInfo[t].loader;e&&e.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(t,e,s){return this.emeController?this.emeController.loadClear(t,e,s):null}load(t,e){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(s=>this.loadInternal(t,e,s)):this.loadInternal(t,e)}loadInternal(t,e,s){s&&t.setKeyFormat(s);const i=t.decryptdata;if(!i){const e=new Error(s?`Expected frag.decryptdata to be defined after setting format ${s}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Pp(t,Yn.KEY_LOAD_ERROR,e))}const r=t;switch(i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===i.keyFormat?this.loadKeyHTTP(r):e?e.then(()=>this.loadKeyEME(r)):this.loadKeyEME(r);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(r);default:return Promise.reject(Pp(t,Yn.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(t){if(this.emeController&&this.config.emeEnabled){var e;if(!t.decryptdata.keyId&&null!=(e=t.initSegment)&&e.data){const e=function(t){const e=[];return Oo(t,t=>e.push(t.subarray(8,24))),e}(t.initSegment.data);if(e.length){let s=e[0];const i=t.decryptdata.uri;if(s.some(t=>0!==t))this.log(`Using keyId found in init segment ${oo(s)} keyUri: ${i}`),LevelKey.setKeyIdForUri(i,s);else{const t=LevelKey.addKeyIdForUri(i);this.log(`Patching empty keyId with ${oo(t)} keyUri: ${i}`),s=t}t.decryptdata.keyId=s}}return this.emeController.loadKey(t).then(()=>({frag:t,keyInfo:{decryptdata:t.decryptdata}}))}return Promise.reject(Pp(t,Yn.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(t){const e=t.decryptdata,s=e.uri;if(!s)return Promise.reject(Pp(t,Yn.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${s}"`)));const i=this.keyLoaderInfo[s];if(i){if(i.decryptdata.key)return e.key=i.decryptdata.key,i.keyLoadPromise=null,Promise.resolve({frag:t,keyInfo:i});if(i.keyLoadPromise)return i.keyLoadPromise.then(s=>(e.key=i.decryptdata.key,Aa(Aa({},s),{},{frag:t})))}this.log(`Loading${e.keyId?" keyId: "+oo(e.keyId):""} URI: ${e.uri} from ${t.type} ${t.level}`);const r=this.config,n=new(0,r.loader)(r);t.keyLoader=n;const a=this.keyLoaderInfo[s]={decryptdata:e,keyLoadPromise:null,loader:n};return a.keyLoadPromise=new Promise((e,i)=>{const o={type:na,keyInfo:a,frag:t,responseType:"arraybuffer",url:s},l=r.keyLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,s,r,n)=>{const{frag:a,keyInfo:o,url:l}=r;if(!a.decryptdata||o!==this.keyLoaderInfo[l])return i(Pp(a,Yn.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),n));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=o.loader=o.keyLoadPromise=null,e({frag:a,keyInfo:o})},onError:(e,r,n,a)=>{this.resetLoader(r),i(Pp(t,Yn.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),n,Aa({url:s,data:void 0},e)))},onTimeout:(e,s,r)=>{this.resetLoader(s),i(Pp(t,Yn.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(e,s,r)=>{this.resetLoader(s),i(Pp(t,Yn.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};n.load(o,d,c)})}resetLoader(t){const{frag:e,keyInfo:s,url:i}=t,r=s.loader;e.keyLoader===r&&(e.keyLoader=s.loader=s.keyLoadPromise=null),delete this.keyLoaderInfo[i],r&&r.destroy()}}function Pp(t,e=Yn.KEY_LOAD_ERROR,s,i,r){return new LoadError({type:Wn.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:r,error:s,networkDetails:i||null})}function Dp(t){const{type:e}=t;switch(e){case sa:return ca;case ia:return ha;default:return da}}function Cp(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.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.on(zn.LEVEL_LOADING,this.onLevelLoading,this),t.on(zn.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(zn.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(zn.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(zn.MANIFEST_LOADING,this.onManifestLoading,this),t.off(zn.LEVEL_LOADING,this.onLevelLoading,this),t.off(zn.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(zn.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(zn.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,s=e.pLoader,i=e.loader,r=new(s||i)(e);return this.loaders[t.type]=r,r}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:ta,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=e;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:ea,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:sa,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:ia,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){const s=this.loaders[ea];if(s){const t=s.context;t&&!e.levels.some(e=>e===t.levelOrTrack)&&(s.abort(),delete this.loaders[ea])}}load(t){var e;const s=this.hls.config;let i,r=this.getInternalLoader(t);if(r){const e=this.hls.logger,s=r.context;if((null==s?void 0:s.levelOrTrack)===t.levelOrTrack&&(s.url===t.url||s.deliveryDirectives&&!t.deliveryDirectives))return void(s.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${s.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),r.abort()}if(i=t.type===ta?s.manifestLoadPolicy.default:Ta({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(t),Vn(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===ea&&null!==t.level?e=this.hls.levels[t.level].details:t.type===sa&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===ia&&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);i=Ta({},i,{maxTimeToFirstByteMs:Math.min(e,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,i.maxTimeToFirstByteMs)})}}}const n=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(t,e,s,i)=>{const r=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=t.data;e.parsing.start=performance.now(),M3U8Parser.isMediaPlaylist(n)||s.type!==ta?this.handleTrackOrLevelPlaylist(t,e,s,i||null,r):this.handleMasterPlaylist(t,e,s,i)},onError:(t,e,s,i)=>{this.handleNetworkError(e,s,!1,t,i)},onTimeout:(t,e,s)=>{this.handleNetworkError(e,s,!0,void 0,t)}};r.load(t,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:s}=this.hls;(t||s)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,s,i){const r=this.hls,n=t.data,a=Cp(t,s),o=M3U8Parser.parseMasterPlaylist(n,a);if(o.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,s,o.playlistParsingError,i,e);const{contentSteering:l,levels:d,iframeVariants:c,sessionData:h,sessionKeys:u,startTimeOffset:f,variableList:g}=o;this.variableList=g,d.forEach(t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:s}=this.hls.config;let{audioCodec:i,videoCodec:r}=t;for(let n=e.length;n--;){const a=e[n];sl(a,"audio",s)?(t.audioCodec=i=i?`${i},${a}`:a,tl.audio[i.substring(0,4)]=2,e.splice(n,1)):sl(a,"video",s)&&(t.videoCodec=r=r?`${r},${a}`:a,tl.video[r.substring(0,4)]=2,e.splice(n,1))}}});const{AUDIO:p=[],SUBTITLES:m,"CLOSED-CAPTIONS":v}=M3U8Parser.parseMasterPlaylistMedia(n,a,o);if(p.length){p.some(t=>!t.url)||!d[0].audioCodec||d[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new AttrList({}),bitrate:0,url:""}))}r.trigger(zn.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:m,iframeVariants:c,captions:v,contentSteering:l,url:a,stats:e,networkDetails:i,sessionData:h,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(t,e,s,i,r){const n=this.hls,{id:a,level:o,type:l}=s,d=Cp(t,s),c=Vn(o)?o:Vn(a)?a:0,h=Dp(s),u=M3U8Parser.parseLevelPlaylist(t.data,d,c,h,0,this.variableList);if(l===ta){const t={attrs:new AttrList({}),bitrate:0,details:u,name:"",url:d};u.requestScheduled=e.loading.start+Tc(u,0),n.trigger(zn.MANIFEST_LOADED,{levels:[t],audioTracks:[],iframeVariants:[],url:d,stats:e,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),s.levelDetails=u,this.handlePlaylistLoaded(u,t,e,s,i,r)}handleManifestParsingError(t,e,s,i,r){this.hls.trigger(zn.ERROR,{type:Wn.NETWORK_ERROR,details:Yn.MANIFEST_PARSING_ERROR,fatal:e.type===ta,url:t.url,err:s,error:s,reason:s.message,response:t,context:e,networkDetails:i,stats:r})}handleNetworkError(t,e,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${t.type}`;t.type===ea?n+=`: ${t.level} id: ${t.id}`:t.type!==sa&&t.type!==ia||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=Yn.UNKNOWN,l=!1;const d=this.getInternalLoader(t);switch(t.type){case ta:o=s?Yn.MANIFEST_LOAD_TIMEOUT:Yn.MANIFEST_LOAD_ERROR,l=!0;break;case ea:o=s?Yn.LEVEL_LOAD_TIMEOUT:Yn.LEVEL_LOAD_ERROR,l=!1;break;case sa:o=s?Yn.AUDIO_TRACK_LOAD_TIMEOUT:Yn.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ia:o=s?Yn.SUBTITLE_TRACK_LOAD_TIMEOUT:Yn.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(t.type);const c={type:Wn.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:d,context:t,error:a,networkDetails:e,stats:r};if(i){let s=t.url;e&&"url"in e&&(s=e.url),c.response=Aa({url:s,data:void 0},i)}this.hls.trigger(zn.ERROR,c)}handlePlaylistLoaded(t,e,s,i,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:d,id:c,groupId:h,deliveryDirectives:u}=i,f=Cp(e,i),g=Dp(i);let p="number"==typeof i.level&&g===da?l:void 0;d&&"iframes"in d&&d.iframes&&!t.iframesOnly&&(t.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),t.iframesOnly=!0);const m=t.playlistParsingError;if(m){if(this.hls.logger.warn(`${m} ${t.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(zn.ERROR,{type:Wn.NETWORK_ERROR,details:Yn.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:m,reason:m.message,response:e,context:i,level:p,parent:g,networkDetails:r,stats:s});t.playlistParsingError=null}if(!t.fragments.length){const n=t.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(zn.ERROR,{type:Wn.NETWORK_ERROR,details:Yn.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:e,context:i,level:p,parent:g,networkDetails:r,stats:s})}switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case ta:case ea:if(p)if(d){if(d!==a.levels[p]){const t=a.levels.indexOf(d);t>-1&&(p=t)}}else p=0;a.trigger(zn.LEVEL_LOADED,{details:t,levelInfo:d||a.levels[0],level:p||0,id:c||0,stats:s,networkDetails:r,deliveryDirectives:u,withoutMultiVariant:o===ta,context:i});break;case sa:a.trigger(zn.AUDIO_TRACK_LOADED,{details:t,track:d,id:c||0,groupId:h||"",stats:s,networkDetails:r,deliveryDirectives:u,context:i});break;case ia:a.trigger(zn.SUBTITLE_TRACK_LOADED,{details:t,track:d,id:c||0,groupId:h||"",stats:s,networkDetails:r,deliveryDirectives:u,context:i})}}}class Hls{static get version(){return Zc}static isMSESupported(){return Ng()}static isSupported(){return function(){if(!Ng())return!1;const t=Ba();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(rl(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(rl(e,"audio"))))}()}static getMediaSource(){return Ba()}static get Events(){return zn}static get MetadataSchema(){return lh}static get ErrorTypes(){return Wn}static get ErrorDetails(){return Yn}static get DefaultConfig(){return Hls.defaultConfig?Hls.defaultConfig:Ap}static set DefaultConfig(t){Hls.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Xc,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const e=this.logger=function(t,e,s){const i=xa();if("object"==typeof console&&!0===t||"object"==typeof t){const r=["debug","log","info","warn","error"];r.forEach(e=>{i[e]=Fa(e,t,s)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.7.2`)}catch(t){return xa()}r.forEach(e=>{Na[e]=Fa(e,t)})}else Ta(Na,i);return i}(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),s=this.config=_p(Hls.DefaultConfig,t,e);this.userConfig=t,s.progressive&&Lp(s,e);const{streamController:i,abrController:r,bufferController:n,capLevelController:a,errorController:o,fpsController:l,id3TrackController:d,iframeController:c,gapController:h}=s,u=new o(this),f=this.abrController=new r(this),g=new FragmentTracker(this),p=s.interstitialsController,m=p?this.interstitialsController=new p(this,Hls):null,v=n?this.bufferController=new n(this,g):null,y=a?this.capLevelController=new a(this):null,E=l?new l(this):null,T=s.cmcdController,S=T?this.cmcdController=new T(this):null,A=new PlaylistLoader(this),_=s.contentSteeringController,b=_?new _(this):null,L=this.levelController=new LevelController(this,b),R=d?new d(this):void 0,I=new KeyLoader(this.config,this.logger),k=this.streamController=new i(this,g,I),w=this.gapController=h?new h(this,g):void 0;y&&y.setStreamController(k);const P=[A,L,k];m&&P.splice(1,0,m),b&&P.splice(1,0,b),this.networkControllers=P;const D=[f];v&&D.push(v),w&&D.push(w),y&&D.push(y),E&&(E.setStreamController(k),D.push(E)),R&&D.push(R),D.push(g),this.audioTrackController=this.createController(s.audioTrackController,P);const C=s.audioStreamController;C&&P.push(this.audioStreamController=new C(this,g,I)),this.subtitleTrackController=this.createController(s.subtitleTrackController,P);const O=s.subtitleStreamController;O&&P.push(this.subtititleStreamController=new O(this,g,I)),this.createController(s.timelineController,D),I.emeController=this.emeController=this.createController(s.emeController,D),S&&D.push(S),this.latencyController=this.createController(s.latencyController,D),this.coreComponents=D,this.iframeController=c?new c(this,Hls):void 0,P.push(u);const M=u.onErrorOut;"function"==typeof M&&this.on(zn.ERROR,M,u),this.on(zn.MANIFEST_LOADED,A.onManifestLoaded,A)}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,i){this._emitter.off(t,e,s,i)}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){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const s=t===zn.ERROR;this.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.INTERNAL_EXCEPTION,fatal:s,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(zn.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,this.iframeController=void 0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const e=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger(zn.ERROR,{type:Wn.OTHER_ERROR,details:Yn.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,s=e?t.media:t,i=e?t:{media:s};this._media=s,this.trigger(zn.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia");const t={};this.trigger(zn.MEDIA_DETACHING,t),this._media=null,this.trigger(zn.MEDIA_DETACHED,t)}transferMedia(){var t;this._media=null;const e=(null==(t=this.bufferController)?void 0:t.transferMedia())||null,s={transferMedia:e};return this.trigger(zn.MEDIA_DETACHING,s),this.trigger(zn.MEDIA_DETACHED,s),e}loadSource(t){var e;this.stopLoad();const s=this.media,i=this._url,r=this._url=Jn.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),s&&i&&(i!==r||null!=(e=this.bufferController)&&e.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(s)),this.trigger(zn.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(t,e),this.started&&this.networkControllers);s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started&&this.streamController.state!==Mc}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[da]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[ca]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[ha]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=this.started,s=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&(s?this.startLoad(s):this.config.autoStartLoad||this.startLoad()))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=qa()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.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){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.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=this.capLevelController,s=!!t;e&&s!==this.config.capLevelToPlayerSize&&(s?e.startCapping():(e.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=s)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return _l.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}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 i=0;i<s;i++)if(t[i].maxBitrate>=e)return i;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:s}=this;let i;if(i=-1===e&&null!=t&&t.length?t.length-1:e,s)for(let e=i;e--;){const i=t[e].attrs["HDCP-LEVEL"];if(i&&i<=s)return e}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var t;return(null==(t=this.audioStreamController)?void 0:t.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}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 nextAudioTrack(){var t,e;return null!=(t=null==(e=this.audioStreamController)?void 0:e.nextAudioTrack)?t:-1}set nextAudioTrack(t){const{audioTrackController:e}=this;e&&(e.nextAudioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}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(){var t,e;return null!=(t=null==(e=this.latencyController)?void 0:e.liveSyncPosition)?t:null}get latency(){var t;return(null==(t=this.latencyController)?void 0:t.latency)||0}get maxLatency(){var t;return(null==(t=this.latencyController)?void 0:t.maxLatency)||0}get targetLatency(){var t;return(null==(t=this.latencyController)?void 0:t.targetLatency)||null}set targetLatency(t){this.latencyController&&(this.latencyController.targetLatency=t)}get drift(){var t;return(null==(t=this.latencyController)?void 0:t.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){const t=this.levelController.iframeVariants;return t||[]}createIFramePlayer(t){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(t):null}createImageIFramePlayer(t){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(t):null}getMediaDecodingInfo(t,e=this.allAudioTracks){return El(t,Ol(e),navigator.mediaCapabilities)}}Hls.defaultConfig=void 0;const Op="hls:attached",Mp="hls:buffer_check";var xp=Object.freeze({__proto__:null,ATTACHED:Op,BUFFER_CHECK_TICK:Mp});const Fp="application/vnd.apple.mpegURL",Np=[Fp,"application/x-mpegurl"],Up=document.createElement("video").canPlayType(Fp);function Bp({src:t="",type:e="",drm:i},r){const n=null==r?void 0:r.hls,a=Boolean(null==n?void 0:n.native);return(!Up||!a)&&(!(i&&!Object.keys(i).find(t=>function(t){const e=s();switch(t){case"com.widevine.alpha":return e.chrome||e.firefox||e.edge||e.opera;case"org.w3.clearkey":return e.chrome||e.firefox;case"com.apple.fps.1_0":return e.safari;case"com.microsoft.playready":return e.edge}}(t)))&&(!(!e||!Np.includes(e))||function(t){const{pathname:e}=vi(t);return e.endsWith(".m3u8")}(t)))}const $p=window&&window.Hls||Hls;var Gp;!function(t){t[t.FRAGMENT_ERRORS=0]="FRAGMENT_ERRORS",t[t.STALE_MANIFEST=1]="STALE_MANIFEST"}(Gp||(Gp={}));const Hp=ci("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,s;this.reset();const i=this.hls;if(!i)return;const r=i.levelController,n=i.streamController,a=r.steering;if(!r||!n||!a)return;const o=r.currentLevel;if(!o)return;const l=a.levels.filter(t=>t.pathwayId!==o.pathwayId);l.length&&(null===(e=i.media)||void 0===e||e.dispatchEvent(new CustomEvent("hls/failover",{detail:{reason:t,from:null===(s=o.details)||void 0===s?void 0:s.url}})),r._levels=n.levels=l)}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 i=null===(t=s.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 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||(Hp(`${t} / no change in ${s.count} tries`,this.playlistCounts),this.failover(Gp.STALE_MANIFEST)))}trackFragmentError(t){const e=this.fragmentFailures[t]||0;this.fragmentFailures[t]=e+1,this.fragmentFailures[t]>2&&this.failover(Gp.FRAGMENT_ERRORS)}createPlaylistLoader(t){const e=this;return class extends Hls.DefaultConfig.loader{load(s,i,r){const n=r.onSuccess;r.onSuccess=({data:i,url:r},...a)=>{"manifest"===(null==s?void 0:s.type)&&(t.manifest=i),e.ensurePlaylistUpdating(r,i),n({data:i,url:r},...a)},super.load(s,i,r)}}}createFragmentLoader(){const t=this;return class extends Hls.DefaultConfig.loader{load(e,s,i){const r=i.onError;i.onError=e=>{t.trackFragmentError(e.url),r(...arguments)},super.load(e,s,i)}}}}const Kp="audio:tracks";const Vp="tracks:text:all";const jp=ci("hls");function qp(t){switch(t){case Yn.KEY_SYSTEM_NO_KEYS:return De.ContentProtectionKeySystemNoKeys;case Yn.KEY_SYSTEM_NO_ACCESS:return De.ContentProtectionKeySystemNoAccess;case Yn.KEY_SYSTEM_NO_SESSION:return De.ContentProtectionKeySystemNoSession;case Yn.KEY_SYSTEM_NO_CONFIGURED_LICENSE:return De.ContentProtectionKeySystemNoConfiguredLicense;case Yn.KEY_SYSTEM_LICENSE_REQUEST_FAILED:return De.ContentProtectionCDMLicenseRequestFailed;case Yn.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED:return De.ContentProtectionServerCertificateRequestFailed;case Yn.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED:return De.ContentProtectionKeySystemCertificateUpdateFailed;case Yn.KEY_SYSTEM_SESSION_UPDATE_FAILED:return De.ContentProtectionKeySystemSessionUpdateFailed;case Yn.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return De.ContentProtectionKeySystemStatusOutputRestricted;case Yn.KEY_SYSTEM_STATUS_INTERNAL_ERROR:return De.ContentProtectionKeySystemStatusInternalError;case Yn.MANIFEST_LOAD_ERROR:return De.PlaybackManifestLoadError;case Yn.MANIFEST_LOAD_TIMEOUT:return De.PlaybackManifestLoadTimeout;case Yn.MANIFEST_PARSING_ERROR:return De.PlaybackManifestParsingError;case Yn.MANIFEST_INCOMPATIBLE_CODECS_ERROR:return De.PlaybackManifestIncompatibleCodecs;case Yn.LEVEL_EMPTY_ERROR:return De.PlaybackLevelEmptyError;case Yn.LEVEL_LOAD_ERROR:return De.PlaybackLevelLoadError;case Yn.LEVEL_LOAD_TIMEOUT:return De.PlaybackLevelLoadTimeout;case Yn.LEVEL_PARSING_ERROR:return De.PlaybackManifestParsingError;case Yn.LEVEL_SWITCH_ERROR:return De.PlaybackLevelSwitchError;case Yn.AUDIO_TRACK_LOAD_ERROR:return De.PlaybackAudioTrackLoadError;case Yn.AUDIO_TRACK_LOAD_TIMEOUT:return De.PlaybackAudioTrackLoadTimeout;case Yn.SUBTITLE_LOAD_ERROR:return De.NetworkDownloadErrorIdContent;case Yn.SUBTITLE_TRACK_LOAD_TIMEOUT:return De.NetworkRequestTimeout;case Yn.FRAG_LOAD_ERROR:return De.PlaybackFragLoadError;case Yn.FRAG_LOAD_TIMEOUT:return De.PlaybackFragLoadTimeout;case Yn.FRAG_DECRYPT_ERROR:return De.PlaybackFragDecryptError;case Yn.FRAG_PARSING_ERROR:return De.PlaybackFragParsingError;case Yn.FRAG_GAP:return De.PlaybackFragGap;case Yn.REMUX_ALLOC_ERROR:return De.PlaybackRemuxAllocError;case Yn.KEY_LOAD_ERROR:return De.ContentProtectionKeyLoadError;case Yn.KEY_LOAD_TIMEOUT:return De.ContentProtectionKeyLoadTimeout;case Yn.BUFFER_ADD_CODEC_ERROR:return De.PlaybackBufferAddCodecError;case Yn.BUFFER_INCOMPATIBLE_CODECS_ERROR:return De.PlaybackBufferIncompatibleCodecs;case Yn.BUFFER_APPEND_ERROR:return De.PlaybackBufferAppendError;case Yn.BUFFER_APPENDING_ERROR:return De.PlaybackAppendError;case Yn.BUFFER_STALLED_ERROR:return De.PlaybackBufferStalledError;case Yn.BUFFER_FULL_ERROR:return De.PlaybackBufferFullError;case Yn.BUFFER_SEEK_OVER_HOLE:return De.PlaybackBufferSeekOverHole;case Yn.BUFFER_NUDGE_ON_STALL:return De.PlaybackBufferNudgeOnStall;case Yn.INTERNAL_EXCEPTION:return De.PlaybackInternalException;case Yn.INTERNAL_ABORTED:return De.PlaybackInternalAborted;case Yn.UNKNOWN:default:return De.Unknown}}function Wp(t,e,s){const i={},r={error_type:e.type,resource:e.url||t.original_src,isFatal:e.fatal};return e.fatal?(e.type===s.ErrorTypes.MEDIA_ERROR&&(r.showErrorUI=!1,i.retry=hi,i.retryTimeout=0),[s.ErrorTypes.KEY_SYSTEM_ERROR,s.ErrorTypes.MUX_ERROR,s.ErrorTypes.OTHER_ERROR].includes(e.type)&&(i.retry=fi),Object.assign(r,{retryOpts:i})):(i.retry=fi,Object.assign(r,{retryOpts:i}))}function Yp(t,e){e.on($p.Events.ERROR,function(e,s){var i;0!=t.reaper&&(!function(t,e,s){t.emit(at,{error:new FlowplayerError(e.error.message,qp(e.details),Wp(t,e,s))})}(t,s,$p),s.fatal&&([$p.ErrorTypes.NETWORK_ERROR,$p.ErrorTypes.MEDIA_ERROR].includes(s.type)||null===(i=t.hls)||void 0===i||i.destroy()))})}function zp(t,e){var s;!t.hasState(Vt)&&t.setState(jt,!0),null===(s=t.hls)||void 0===s||s.startLoad(e)}function Qp(t,e){if("object"==typeof t&&"object"==typeof e&&"number"==typeof t.bitrate&&"number"==typeof e.bitrate)return t.bitrate<e.bitrate}function Xp(t){const e=t.map((t,e)=>Object.assign(t,{level:e})).sort((t,e)=>e.width-t.width);return t.length>1&&t.every(t=>void 0!==t.bitrate)&&e.push({name:"AUTO",level:-1,width:0,height:0}),e}function Zp(t,e,s,i,r){let n;t.once(Hls.Events.LEVEL_LOADING,function(){e.emit(nt)}),t.on($p.Events.MANIFEST_PARSED,function(t,n){const a=Xp(n.levels);e.emit(U,a),e.emit("parse:video:tracks",{url:r.src,manifest:i.manifest}),function(t,e,s){if(!t.hls)return;jp("Initializer::maybe_start_load_with_quality (start_quality, preload): (%d, %s)",e.start_quality,e.preload),void 0!==e.start_quality&&s.length&&(ke.HIGH&e.start_quality&&(t.hls.startLevel=s[0].level),ke.LOW&e.start_quality&&(t.hls.startLevel=s[s.length-1].level),ke.MEDIUM&e.start_quality&&(t.hls.startLevel=s[Math.ceil(s.length/2)-1].level));(function(t,e){var s,i,r,n,a,o;if(!e.hls)return;if(null===(s=t.hls)||void 0===s?void 0:s.adaptive_buffer_control){const s=10,i=10,r=!0!==t.hls.adaptive_buffer_control&&t.hls.adaptive_buffer_control.initial_buffer_length?t.hls.adaptive_buffer_control.initial_buffer_length:s;!function(t,e){var s;const i=500,r=null===(s=t.hls)||void 0===s?void 0:s.config.maxBufferLength;let n=!1;const a=setInterval(()=>{t.emit(Mp)},i),o=()=>{n||t.currentTime>e&&(n=!0,t.hls&&r&&(t.hls.config.maxBufferLength=r))};t.on(F,()=>{clearInterval(a),t.off(Mp,o)}),t.on(Mp,o)}(e,!0!==(null===(n=t.hls)||void 0===n?void 0:n.adaptive_buffer_control)&&t.hls.adaptive_buffer_control.restore_buffer_player_time_threshold?null===(a=t.hls)||void 0===a?void 0:a.adaptive_buffer_control.restore_buffer_player_time_threshold:i),Jp(t,e,{maxBufferLength:r,maxBufferSize:null===(o=t.hls)||void 0===o?void 0:o.maxBufferSize})}else Jp(t,e,{maxBufferLength:null===(i=t.hls)||void 0===i?void 0:i.maxBufferLength,maxBufferSize:null===(r=t.hls)||void 0===r?void 0:r.maxBufferSize})})(e,t),("none"!==e.preload||e.autoplay&&t.hasState(ge))&&!t.hls.config.autoStartLoad&&zp(t,e.start_time||-1)}(e,s,a.slice(0,-1));const o=a.find(t=>t.videoCodec);!e.opt("ratio")&&o&&0!=o.width&&0!=o.height&&e.setOpts({ratio:o.width+":"+o.height})}),t.on($p.Events.LEVEL_SWITCHING,(s,i)=>{if(t.nextLoadLevel===n)return;n=t.nextLoadLevel;const r=t.levels[t.currentLevel],a=t.levels[i.level];e.emit(B,{before:r,after:a,plugin:"hls",automatic:t.autoLevelEnabled,downscale:Qp(a,r)})})}function Jp(t,e,s){if(!e.hls)return;const i=(null==s?void 0:s.maxBufferSize)||1024,r=(null==s?void 0:s.maxBufferLength)||30;jp("Setting maxBufferSize to %d",i),e.hls.config.maxBufferSize=i,"metadata"===t.preload&&jp("preload === metadata, setting maxBufferLength to 1sec"),e.hls.config.maxBufferLength="metadata"===t.preload?1:r,e.once(R,()=>{jp("Playback started, set maxBufferLenght to %d",r),e.hls&&(e.hls.config.maxBufferLength=r)})}function tm(t,e,s,i,r){!function(t,e){t.on(Hls.Events.AUDIO_TRACKS_UPDATED,function(t,s){e.emit(Kp,s.audioTracks)}),t.on(Hls.Events.AUDIO_TRACK_SWITCHING,function(t,s){e.emit("audio:update",s)}),t.on(Hls.Events.MANIFEST_PARSED,function(t,s){s.audioTracks&&e.emit(Kp,s.audioTracks)})}(t,i),function(t,e){t.on(Hls.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(s,i)=>{t.subtitleTracks.length||e.emit(Vp,i)}),t.on(Hls.Events.SUBTITLE_TRACKS_UPDATED,(t,s)=>{e.emit(Vp,{tracks:s.subtitleTracks.map(t=>Object.assign({},{subtitleTrack:t}))})}),t.on(Hls.Events.CUES_PARSED,(t,s)=>{e.emit("cues:parsed",s)})}(t,i),Yp(i,t),Zp(t,i,e,s,r),function(t,e){t.on(Hls.Events.FRAG_PARSING_METADATA,function(t,s){e.emit("ssai:hls:metadata",s)})}(t,i),function(t,e){t.on(Hls.Events.BUFFER_CREATED,(t,s)=>{if(!s.tracks.video&&!s.tracks.audiovideo)return e.emit(J)})}(t,i),function(t,e,s){const i="live"in s==0;e.on($p.Events.LEVEL_LOADED,function(s,r){var n,a,o,l,d;i&&t.setOpts({live:null===(n=null==r?void 0:r.details)||void 0===n?void 0:n.live});const c=null===(o=null===(a=e.levels[r.level])||void 0===a?void 0:a.details)||void 0===o?void 0:o.fragments;if(!c)return;const h=(null===(l=c[1])||void 0===l?void 0:l.start)||0,u=e.liveSyncPosition||(null===(d=c[c.length-1])||void 0===d?void 0:d.end)||0;t.emit("dvr/window",u-h)})}(i,t,e)}function em(t,e,s){!function(t){t.on("audio:set",function(e){var s,i;const r=null===(s=e.data)||void 0===s?void 0:s.id;"number"==typeof r&&r!=(null===(i=null==t?void 0:t.hls)||void 0===i?void 0:i.audioTrack)&&setTimeout(function(){(null==t?void 0:t.hls)&&(t.hls.audioTrack=r)},0)})}(t),function(t,e){t.on(F,function(){t.hls&&(t.hls.destroy(),delete t.hls,e.manifest=void 0)}),t.on(N,function(){var e;null===(e=t.hls)||void 0===e||e.destroy()})}(t,e),function(t){const e={media_recovers:0,audio_swaps:0};let s=0;t.on(n,e=>{var i,r,n;t.hls&&(null===(i=null==t?void 0:t.error)||void 0===i?void 0:i.code)===MediaError.MEDIA_ERR_DECODE&&(e.preventDefault(),++s,t.emit(at,{error:new FlowplayerError(null!==(n=null===(r=null==t?void 0:t.error)||void 0===r?void 0:r.message)&&void 0!==n?n:"An error occurred while decoding the media.",De.PlaybackVideoDecodeError,{isFatal:!0,showErrorUI:s>=5,retryOpts:{retry:s<5?hi:fi,retryTimeout:0}})}))}),t.on(w,()=>s=0),t.on(r,s=>{var i,r,n,a;if(!t.hls)return;s.preventDefault();const o=s.detail.error,l=o.config;return o.flowplayerErrorCode===De.PlaybackVideoDecodeError?(t.hls.config.autoStartLoad=!0,t.hls.recoverMediaError(),t.setState(te,!1)):l.error_type?l.error_type===$p.ErrorTypes.NETWORK_ERROR?(t.hls.config.autoStartLoad=!0,(null===(i=t.normalizedSrc)||void 0===i?void 0:i.src)&&t.hls.loadSource(t.original_src),!t.paused||t.hasState($t)?(t.setState(te,!0),t.togglePlay(!0)):(t.setState(te,!1),t.emit("retry/done"))):l.error_type===$p.ErrorTypes.MEDIA_ERROR?(jp(`recovering from ${l.error_type}`),e.media_recovers+5e3>Date.now()&&0==e.audio_swaps?(null===(r=t.hls)||void 0===r||r.swapAudioCodec(),jp(`calling swapAudioCodec() : {count=${e.audio_swaps}}`),e.audio_swaps++,e.media_recovers=Date.now(),null===(n=t.hls)||void 0===n||n.recoverMediaError(),t.setState(te,!1)):(e.media_recovers=Date.now(),e.audio_swaps=0,null===(a=t.hls)||void 0===a||a.recoverMediaError(),t.setState(te,!1))):void 0:void 0})}(t),function(t){t.on(z,()=>{t.hls&&(t.hls.stopLoad(),delete t.opts.start_time)}),t.on(Q,e=>{var s;if(!t.hls)return;if(!t.opts.live)return zp(t,e.detail.currentTime);e.preventDefault();const i=zs(t).progress,r=t.hls;null===(s=t.hls)||void 0===s||s.once($p.Events.LEVEL_LOADED,()=>{if(t.hls!==r)return;const e=t.live_state.dvr_window||0,s=(null==r?void 0:r.liveSyncPosition)||t.seekable.end(0);if(t.hasState(re)||isNaN(i))return t.currentTime=s;t.currentTime=s-e*((100-i)/100)}),zp(t)})}(t),function(t,e){t.on([it,M],s=>{if(!(!t.hls||t.hls.config.autoStartLoad||t.hasState($s)||t.hasState(Vt)||"none"!==e.preload||s.type===M&&!e.autoplay))return t.hls.levels.length?zp(t,e.start_time||-1):void t.hls.once($p.Events.MANIFEST_PARSED,()=>{setTimeout(()=>{zp(t,e.start_time||-1)},0)})}),t.on($,function(e){var s;if(!t.hls)return;const i=null===(s=e.data)||void 0===s?void 0:s.level;"number"==typeof i&&(t.hls.levels[i]||-1===i?t.hls.nextLevel=i:console.error(new Error("skipping invalid quality: "+e.data)))}),t.on(G,function(e){var s,i;const r=e.detail.track,n=null===(s=t.tracks)||void 0===s?void 0:s.find(t=>t.selected&&t!==r),a=t.hls;if(!n||!r||!a)return;n.selected=!1;const o=null===(i=r.data)||void 0===i?void 0:i.slice(0).map(t=>(t.details=void 0,t));a.stopLoad(),a.levelController._levels=a.streamController.levels=o,a.currentLevel=0,a.nextLevel=-1,t.emit(U,Xp(o)),t.hasState(qt)&&!t.hasState(jt)||a.startLoad()});const s=t.opt("start_time");s&&t.once(E,function(){t.currentTime=s})}(t,s),function(t){t.on("tracks:text:updated",e=>{const s=e.detail;t.hls&&s&&s.is_hls_embedded&&"number"==typeof s.track_id&&(t.hls.subtitleTrack=s.track_id)})}(t),((t,e)=>{t.on(Qe,()=>{var s;(null===(s=e.hls)||void 0===s?void 0:s.adaptive_buffer_control)&&Je(t,{feature_name:"adaptive-buffer-control",behavior:"used",sample_rate:Ze.Medium})})})(t,s)}function sm(t,e){if(t.drm&&"https:"!==location.protocol&&"localhost"!==location.hostname&&"127.0.0.1"!==location.hostname){const s=new FlowplayerError("drm is unavailable in http contexts",De.ContentProtectionKeySystemUnavailable,{resource:t.src,isFatal:!0,retryOpts:{retry:fi}});return e.emit(at,{error:s}),!1}return!0}function im(t,e,s,i){if(!t.reaper||!(null==s?void 0:s.src))return;if(t.hls&&t.hls.destroy(),!sm(s,t))return;const r=function(t,e,s,i){var r,n,a,o,l,d,c,h;const u=new FailoverLoaderController,f=function(t){return Object.assign(Object.assign({autoStartLoad:!1,levelLoadingMaxRetry:1},t.hls),{startPosition:t.start_time||-1})}(t);f.renderTextTracksNatively=!1,f.captionsTextTrack1Label=null!==(n=null===(r=null==t?void 0:t.hls)||void 0===r?void 0:r.captionsTextTrack1Label)&&void 0!==n?n:"CC1",f.captionsTextTrack2Label=null!==(o=null===(a=null==t?void 0:t.hls)||void 0===a?void 0:a.captionsTextTrack2Label)&&void 0!==o?o:"CC2",f.captionsTextTrack3Label=null!==(d=null===(l=null==t?void 0:t.hls)||void 0===l?void 0:l.captionsTextTrack3Label)&&void 0!==d?d:"CC3",f.captionsTextTrack4Label=null!==(h=null===(c=null==t?void 0:t.hls)||void 0===c?void 0:c.captionsTextTrack4Label)&&void 0!==h?h:"CC4",f.pLoader=u.createPlaylistLoader(e),f.fLoader=u.createFragmentLoader(),function(t,e){var s;const i=e;"1318f5da-2731-4bf1-b924-fad46cfce535"===i.opt("metadata.sitegroup_id")&&(t.cmcd={contentId:i.opt("metadata.media_id"),sessionId:null===(s=null==i?void 0:i.health)||void 0===s?void 0:s.media_session_id})}(f,s);const g=s.hls=new $p(f);return u.setHls(g),g.subtitleDisplay=!1,g.attachMedia(s),g.loadSource(i.src),setTimeout(()=>s.emit(Op,{hls:s.hls})),g}(e,i,t,s);tm(r,e,i,t,s)}var rm;const nm=((rm=class HLS{init(t,e,s){em(s,this,t)}onload(t,e,s,i){s.normalizedSrc=i,im(s,t,i,this)}wants(t,e,s){return Hls.isSupported()&&Bp(e,s)}}).pluginName="hls",rm.events=xp,rm.version=Hls.version,rm.failover={Reasons:Gp},rm),am=ws(window,nm),om=t=>"object"==typeof t&&null!==t&&!Array.isArray(t),lm=(...t)=>t.reduce((t,e)=>om(e)?(Object.keys(e).forEach(s=>{if(om(t[s])&&om(e[s]))return t[s]=lm(t[s],e[s]);t[s]=e[s]}),t):t,{});class Pipe{static of(t){return new Pipe(t)}static maybe(t,e,...s){return null==t?t:e.apply(t,[t,...s])}constructor(t){this.data=t}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}}const dm=window,cm=dm._flowplayerTimekeeper||(dm._flowplayerTimekeeper={});function hm(t){return fetch(t).then(t=>t.json())}function um(...t){let e=[].join.call(t,"/");return"/"!==e[0]&&(e="/"+e),fm()+"/web/public/native/config"+e}const fm=()=>"https://ljsp.lwcdn.com";function gm(t){(async function(){const t=cm.cachedServerOffset;if(t)return t;const e=cm.pendingRequest||(cm.pendingRequest=fetch("https://ljsp.lwcdn.com/web/public/countdown/time.json")),s=await e,i=parseInt(s.headers.get("age")||"0"),r=await s.json(),n=Date.now()-r.millisUtc-1e3*i;return cm.cachedServerOffset=n,cm.cachedServerOffset})().then(e=>Object.assign(t,{server_time_offset:e}))}function pm(t,e){var s,i;e="object"==typeof e?e:{};const r={title:null===(s=null==t?void 0:t.metadata)||void 0===s?void 0:s.title,description:null===(i=null==t?void 0:t.metadata)||void 0===i?void 0:i.description},n={ima:{parameters:function({media_id:t,duration:e,title:s,tags:i,category_name:r,ad_keywords:n}){return{ad_keywords:n||"",media_id:t||"",category:r||"",media_name:s||"",media_tags:i||"",media_duration:e||-1}}((null==t?void 0:t.metadata)||{})}},a=e.embed||{};return delete a.src,lm(n,r,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 mm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,vm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ym=/^[A-Za-z0-9]{8}$/,Em=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/[A-Za-z0-9]{8}$/;function Tm(t){return"object"==typeof t&&"ovp/base64"==t.type}function Sm(t,e){return function(t,e){return!(!mm.test(t)&&!vm.test(t)||(e.type="video/ovp",0))}(t,e)||function(t,e){return!(!ym.test(t)&&!Em.test(t)||(e&&(e.type="video/ovp"),0))}(t,e)||Tm(e)}function Am(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 _m(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 bm(t){var e;return null===(e=null==t?void 0:t.metadata)||void 0===e?void 0:e.live_start_time}const Lm="ovp:request:start",Rm="ovp:request:media:complete",Im="ovp:request:playlist:complete",km="ovp:live:countdown:tick",wm="ovp:live:countdown:start",Pm="ovp:live:countdown:complete",Dm="ovp:media:changed",Cm="ovp:message:realtime",Om="ovp:config:finalized";var Mm=Object.freeze({__proto__:null,OVP_ERROR:"ovp:error",OVP_MEDIA_REQUEST_START:Lm,OVP_MEDIA_REQUEST_COMPLETE:Rm,OVP_PLAYLIST_REQUEST_COMPLETE:Im,LIVE_COUNTDOWN_TICK:km,LIVE_COUNTDOWN_START:wm,LIVE_COUNTDOWN_COMPLETE:Pm,OVP_MEDIA_CHANGED:Dm,OVP_REALTIME_MESSAGE:Cm,OVP_CONFIG_FINALIZED:Om});function xm(t,e){const s=null==e?void 0:e.src;if(Tm(e))return function(t,e){const s=Am(e.src||"");if(function(t){return"string"==typeof t.err}(s))return console.error(s.err);Fm(t,s)}(t,e);if(!s)return;t.setState(ve,!0);const i=function(t){return~t.indexOf("/")?t:"/media/"+t}(s),r=um(i);fetch(r).then(async e=>e.ok?Fm(t,await e.json()):function(t,e,s,i){t.setState(ve,!1);const r=new FlowplayerError(i.message||"error loading ovp source",function(t){const e=`03-${t}`;return e in Ce?e:De.NetworkUnknown}(s),{resource:e,isFatal:!0,retryOpts:{retry:fi}});t.emit(at,{error:r})}(t,e.url,e.status,await e.json()))}function Fm(t,e){return delete e.live,t.emit(Dm,e),function(t){return Array.isArray(t.playlist)}(e)?function(t,e){t.emit(Im,function(t,e){"number"!=typeof e.delay&&"number"!=typeof t.delay&&(e.delay=5);const s=Object.assign({},t),i=(null==t?void 0:t.playlist)||{},r=lm(e,i),n=((null==r?void 0:r.playlist)||[]).map(t=>{e.ima&&Object.assign(t,{ima:e.ima});const i=pm(t,s);return delete i.playlist,i});return delete r.ima,Object.assign(r,{playlist:n})}(t.opts,e))}(t,e):bm(e)?function(t,e){var s,i;const r=(null===(s=null==e?void 0:e.metadata)||void 0===s?void 0:s.live_start_time)||(null===(i=null==e?void 0:e.metadata)||void 0===i?void 0:i.starttime);r&&(e.live_start_time=Pipe.of(r).fmap(_m).unwrap());t.emit(wm,Pipe.of(e).fmap(pm,t.opts).unwrap())}(t,e):function(t,e){t.emit(Rm,Pipe.of(e).fmap(pm,t.opts).unwrap())}(t,e)}const Nm={};function Um(t,e,s){"object"!=typeof Nm[e]&&(Nm[e]=s);const i=t.opts,r=(null==i?void 0:i.metadata)||{};r.player_id=e,i.metadata=r,s.title&&delete s.title,s.description&&delete s.description;const n=Object.assign(i,s);t.setOpts(n),s.autoplay&&t.togglePlay(!0)}const Bm="recommendationsready";let $m=!1;function Gm(t,e,s){Hm()||Pipe.of("recommendation").fmap(um,e,s).fmap(hm).fmap(e=>e.then(e=>function(t,e){const s=e.playlist,i=t.opts;if(i.recommendations=s,!s.length)return;t.emit(Bm,{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(Km))}function Hm(){return $m}function Km(t){$m=!0,console.error("Failed to load recommendations: %j",t)}function Vm(t){const e=Date.now()-(t.server_time_offset||0);return Math.floor(((t.live_start_time||0)-e)/1e3)}function jm(t,e){let s=0;function i(){const i=Vm(e);if(i<0||isNaN(i)||0===t.reaper||void 0===e.live_start_time)return clearInterval(s),function(t,e,s){t.emit(Pm);const i=Dr(t,Nt);if(i&&i.remove(),t.root.classList.remove("is-livecountdown"),s)return t.setState(ve,!1);t.emit(Rm,e)}(t,e,void 0===e.live_start_time);!function(t,e,s,i){s.classList.add("is-livecountdown"),e.emit(km,{remaining_time:qm(i+1)}),e.hasState(qt)||e.setState(qt,!0)}(0,t,t.root,i)}gm(e),i(),s=setInterval(i,250)}function qm(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 i=Math.floor(t/60);return{days:e,hours:s,minutes:i,seconds:t-=60*i}}(t);let s="";return e.days&&(s+=e.days+":"),s+ds(e.hours)+":"+ds(e.minutes)+":"+ds(e.seconds)}class WebsocketBridge{static of(t){return new WebsocketBridge(t)}constructor(t){this.manualDisconnect=!1,this.video=t,this.onClose=this.onClose.bind(this),this.onMessage=this.onMessage.bind(this)}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(Cm,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=Cr("fp-inner");this.append(e);const s=document.createElement("p");s.innerText=t.i18n("ovp.starting_in"),e.append(s);const i=document.createElement("p");i.classList.add("fp-countdown"),e.append(i),t.on(km,e=>{const s=e.detail.remaining_time;t.root.classList.add("is-livecountdown"),i.innerText=s})}}const Wm=["*.lwcdn.com","*.flowplayer.com","*.wowza.com"];var Ym;const zm=(Ym=class OVP{constructor(t){Re(t,Nt,FlowplayerLiveCountdown)}onload(t,e,s,i){if("string"==typeof(null==i?void 0:i.src))return"string"!=typeof t.player_id||0===i.src.indexOf(t.player_id)||Tm(i)||(i.src=[t.player_id,i.src].join("/")),xm(s,i)}wants(t,e,s){return Sm(t,e)}init(t,e,s){const i=new WebsocketBridge(s);let r=Object.assign({},t);const n=function(e){if(!r)return e;t.autoplay!==r.autoplay&&(r.autoplay=t.autoplay),delete r.src;const i=lm(e,r);return s.emit(Om,i),i};s.on(F,()=>{(s.currentSrc||s.root.classList.contains("is-livecountdown"))&&(r=!1)}),s.on(Lm,function(){s.setState(te,!0),t.recommendations&&(t.recommendations=!1)}),s.on(Dm,function({data:t}){var e,s;const r=null===(e=null==t?void 0:t.metadata)||void 0===e?void 0:e.media_id;(null===(s=null==t?void 0:t.metadata)||void 0===s?void 0:s.live_start_time)&&r&&(i.disconnect(),i.connect(r))}),s.on(Cm,function({data:e}){var i;const r=null==e?void 0:e.event,n=null==e?void 0:e.value,a=s.opt("metadata",{live_start_time:""});switch(r){case"METADATA":{const e=Object.assign(a,n),r=Object.assign(t,{metadata:e});(null===(i=null==r?void 0:r.metadata)||void 0===i?void 0:i.live_start_time)&&(r.live_start_time=_m(r.metadata.live_start_time)),s.setOpts(r);break}}}),s.on(it,function(e){const s=t;if(bm(s)){if(Qm(s))return;e.preventDefault()}}),s.on(Rm,function(t){const e=t.data;if(!e)return;if(e.src&&(e.src=is(e.src).map(t=>(t.src&&t.src.startsWith("//")&&(t.src="https:"+t.src),t))),0==s.reaper||"object"!=typeof e||Vm(e)>0)return;const i=n(e);s.setOpts(i),s.setAttrs(i),i.src&&s.setSrc(i.src),s.setState(ve,!1)}),s.on(et,function({data:i}){var r,n;if("string"==typeof t.src&&Sm(t.src,{}))return;if((null==i?void 0:i.domains)&&(null==i?void 0:i.domains.length)&&!((t,e)=>{const s=t.split(".").reverse();return e.concat(Wm).some(t=>{const e=t.split(".").reverse(),i="*"===e[e.length-1];return i&&e.pop(),(i||e.length===s.length)&&e.every((t,e)=>s[e]===t)})})(Ei(),i.domains))return Us({root:e,video:s,data:{details:`Hostname ${Ei()} is not allowed to load player ${null===(r=i.metadata)||void 0===r?void 0:r.player_id}.`,reason:"domain"}});if(t.src&&Xm(t.src))return;const a=null==i?void 0:i.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 Nm[e])return console.debug("using Cache(%s)",e),Um(t,e,Nm[e]);Pipe.of(e).fmap(um).fmap(hm).fmap(s=>s.then(s=>Um(t,e,s)).catch(console.error))}(s,t.player_id):void 0}),s.on(Im,function(t){var e;const i=t.data;if(!i||0==s.reaper)return;const{playlist:r}=i,a=Fe(i,["playlist"]),o=n(Object.assign(a,{playlist:Object.assign({},a)}));Array.isArray(o.playlist)&&(o.playlist=a),delete o.loop,o.playlist.playlist_title||(o.playlist.playlist_title=null===(e=a.metadata)||void 0===e?void 0:e.playlist_title),s.setOpts(o),s.setAttrs(o);const l={type:"flowplayer/playlist",items:r};s.setSrc(l),s.setState(ve,!1)}),s.on(wm,function(i){const r=i.data;if(!r||0==s.reaper)return;const a=n(r);if(s.setOpts(a),s.setAttrs(a),Vm(r)<=0)return s.emit(Rm,r);Dr(s,Nt)||(e.appendChild(Le(s,Nt)),jm(s,t))}),s.on(A,function(){var e,i,r;const n=t;bm(n)?Qm(n)||(s.togglePlay(!1),s.emit(P)):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||Hm()||(null===(i=null==t?void 0:t.metadata)||void 0===i?void 0:i.media_id)&&(null===(r=null==t?void 0:t.metadata)||void 0===r?void 0:r.player_id)&&Gm(s,t.metadata.media_id,t.metadata.player_id))}),s.on(N,function(){i.disconnect()}),function(t){const e=[];t.on(Qe,()=>{const s=t.opt("metadata.stream_target_id");s&&!e.includes(s)&&(e.push(s),Je(t,{feature_name:"ewv",behavior:"used"}))})}(s)}},Ym.pluginName="ovp",Ym.events=Mm,Ym);function Qm(t){var e,s;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===(s=null==t?void 0:t.metadata)||void 0===s?void 0:s.allow_after_stop_time)||_m(i)>Date.now()}const Xm=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)},Zm=ws(window,zm);function Jm(t){return{width:t.clientWidth,height:t.clientHeight}}function tv(t,e,s){return"number"==typeof s&&(s+="px"),t.style.setProperty(e,s),t}const ev="is-popped-out",sv="is-ad-loading",iv="is-ad-user-activated",rv=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"});let nv=null;function av(t,e=5e3){return new Promise(s=>{const i=document.createElement("video"),r={autoplay_sound:!1,autoplay_muted:!1},n=()=>{i.pause(),i.currentTime=0,i.src="",i.remove(),s(r)},a=setTimeout(n,e);i.setAttribute("playsinline",""),i.setAttribute("webkit-playsinline",""),i.setAttribute("disablepictureinpicture",""),i.preload="auto",i.playsInline=!0,i.muted=!1,Object.assign(i.style,{position:"fixed",left:"-9999px",top:"0",width:"1px",height:"1px",opacity:"0",pointerEvents:"none"}),document.body.appendChild(i),i.src=(nv||(nv=URL.createObjectURL(rv)),nv);(async()=>{try{return await i.play(),clearTimeout(a),r.autoplay_sound=!0,r.autoplay_muted=!0,n()}catch(e){if(t)return clearTimeout(a),n()}try{i.muted=!0,i.setAttribute("muted",""),await i.play(),r.autoplay_muted=!0}catch(t){}clearTimeout(a),n()})()})}const ov=ci("ads/lifecycle"),lv=[Fi,Ni,Zi];async function dv({config:t,root:e,content:s,ads:i,ima:r}){var n;ov("LifeCycle::initLifeCycle",t,e,s,i,r),s.autoplay=!1;const a=t.autoplay===we.AUDIO_REQUIRED,o=function(t,e){return{muted:!(e||!t.muted),volume:t.volume}}(s,a);s.on(b,()=>{o.volume=s.volume,o.muted=s.muted}),s.on(ur,()=>{ov("showFirstFrame"),e.classList.toggle("ad-hide-first-frame",!1)});const l=Le(s,on),d=l;s.emit(gr,{ui_flags:null===(n=t.ads)||void 0===n?void 0:n.ui}),s.renderPlugin(l);const c={listening:!1,preload:null==r?void 0:r.preload_ads};if(ov("initial",o),i.setVideoTag(s),t.autoplay){ov("Trying to autoplay"),e.classList.add("ad-hide-first-frame"),ov("hideFirstFrame");const n=await async function(t,e){const[s,i]=[t.muted,t.volume];ov("Lifecycle::peek_content(:muted => %s, :volume => %s)",s,i),await async function(t){return ov("Lifecycle::wait_for_source"),new Promise((e,s)=>{const i=50,r=2e3;let n=0;const a=setInterval(()=>{if(++n>r/i)return clearInterval(a),s(new Error(`No source in ${r}ms, giving up`));(t.currentSrc||"dash"in t)&&(e(null),clearInterval(a))},i)})}(t),await function(t){return new Promise(e=>{if(t.hasState(ge))return e(null);t.once(M,()=>e(null))})}(t);const r=Date.now();!e&&t.opts.muted||(t.muted=!1);t.volume=t.volume?t.volume:1;const{autoplay_sound:n,autoplay_muted:a}=await av(e);return ov("Lifecycle::peek_content:: ","audioRequired: "+e," autoplay_sound: "+n," autoplay_muted: "+a," peek_content_check_ms: "+(Date.now()-r)),t.opts.muted&&!e?a:!!n||!e&&(t.muted=!!a||s,a)}(s,a);n?(ov("Can autoplay, start ad"),s.opts.autoplay=1,s.setState(ee,!0),cv({ads:i,content:s,state:c,adContainer:d,ima:r,config:t})):(ov("cannot autoplay(audioRequired: %s), fallback to poster state",a),t.autoplay=0,s.emit(ur,{root:e}),s.setState("is-starting",!0))}s.root.classList.toggle(iv,!!t.autoplay||!i.hasPreroll()),!t.autoplay&&i.hasPreroll()&&function({content:t,ads:e,config:s,state:i,initial:r,adContainer:n,ima:a}){t.once(it,async function(o){t.root.classList.add(iv),(t.hasState(ge)||"touchend"!=o.type)&&e.shallPlayAd(0)&&(e.adapter.setAttemptingPrerollOnIOS(e.adapter.isCustomPlaybackEnabled()),e.adapter.isCustomPlaybackEnabled()||o.preventDefault(),gv({ads:e,content:t,state:i}),ov("user_gesture(:intercept) -> shallPlayAd(0: %s)",e.shallPlayAd(0)),s.muted=r.muted,await cv({ads:e,content:t,state:i,adContainer:n,ima:a,config:s}),pv({ads:e,content:t}))})}({content:s,ads:i,config:t,state:c,initial:o,adContainer:d,ima:r}),!t.autoplay&&i.hasPreroll()&&c.preload&&cv({ads:i,content:s,state:c,adContainer:d,ima:r,config:t}),fv({config:t,root:e,content:s,ads:i,state:c,adContainer:d,ui:l,ima:r,initial:o});const h=async t=>{s.removeEventListener(it,h),i.resetScheduleCounter(),i.hasPreroll()&&(i.adapter.setAttemptingPrerollOnIOS(i.adapter.isCustomPlaybackEnabled()),t.preventDefault(),await i.setCurrentTime(0))};s.on(F,()=>{s.currentSrc&&(s.removeEventListener(it,h),s.addEventListener(it,h))}),s.on(it,t=>{(i.adBreak||i.adPlaying)&&(!i.adBreak||i.adLinear||i.adapter.isAdPod())&&(ov("prevented content from starting because ad break is active"),t.preventDefault())})}async function cv(t){var e;t.state.started||((null===(e=t.config.ima)||void 0===e?void 0:e.preload_ads)||t.content.hasState(ge)?await hv(t):t.content.once(M,async()=>{await hv(t)}))}async function hv({ads:t,content:e,adContainer:s,ima:i,state:r,config:n}){var a;r.started=!0;const o=Fe(i,["ads"]),l=Jm(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,preload_ads:null===(a=null==n?void 0:n.ima)||void 0===a?void 0:a.preload_ads},o),l));ov("start():",c,r),await t.initialize(!1,c,r.preload)}function uv(t,e){var s,i;return{content_width:t.clientWidth||(null===(s=t.parentNode)||void 0===s?void 0:s.clientWidth)||e.clientWidth,content_height:t.clientHeight||(null===(i=t.parentNode)||void 0===i?void 0:i.clientHeight)||e.clientHeight}}function fv({config:t,root:e,content:s,ads:i,initial:r,adContainer:n,state:a,ui:o,ima:l}){ov("addUIListeners()");const d=async()=>{if(i){if(!(i.adapter.isAttemptingPrerollOnIOS()||i.adapter.isCustomPlaybackEnabled()&&s.currentSrc!==s.original_src)){if(s.off(R,d),ov("addUIListeners() -> content started playing"),gv({ads:i,content:s,state:a}),!i.shallPlayAd(0)||!i.adapter.isLinearAd())return ov("addUIListeners() -> no more preroll ads -> resume content"),s.emit(ur,{root:e}),await cv({ads:i,content:s,state:a,adContainer:n,ima:l,config:t});await cv({ads:i,content:s,state:a,adContainer:n,ima:l,config:t}),i.shallPlayAd(0)&&i.adapter.isLinearAd()&&(o.classList.add("on","linear"),e.classList.add(sv),pv({ads:i,content:s}))}}else s.off(R,d)};s.on(R,d),s.on([K,H],function(){if(!i)return;const{content_width:t,content_height:r}=uv(s,e);i.resize({height:r,width:t})}),s.on(m,t=>{if(!i||!t.detail)return;const{width:e,height:s}=t.detail.contentRect;i.resize({width:e,height:s})}),s.on(P,t=>{var r;const n=()=>{t.preventDefault(),Object.assign(t,{prevented:!0})};if(e.classList.contains("ad-linear")&&e.classList.contains("ads-custom-playback-enabled"))return n();i&&(ov("ui_listeners(:%s, event: %o)",t.type,t.detail),(null===(r=null==t?void 0:t.detail)||void 0===r?void 0:r.from)!==i&&(n(),i.finished(function(){s.emit(P,{from:i})})))}),i.on($i,()=>{e.classList.add(sv)}),i.once(Ki,()=>{s.on([it,rt],t=>{var e;if(!i.adBreak||!i.adapter.isLinearAd())return;t.preventDefault();const s=(null===(e=t.detail)||void 0===e?void 0:e.forced)?t.type===it:!i.adPlaying;s&&i.paused&&i.resume(),s||i.paused||i.pause()})}),i.on(Ki,t=>{const n=t.detail,{linear:a,ad:o,ad_type:l}=n;let d;if(ov(`Ad[linear: ${a}, currentTime: ${s.currentTime}] starting`,o),"preroll"==l&&!a&&s.paused&&s.togglePlay(!0),a&&(d=uv(s,e)),i.resize({width:d?d.content_width:o.width,height:d?d.content_height:o.height,linear:a,resize_non_linear:!0}),s.emit(fr,{opts:{linear:a,resizeContainerAlso:!0,width:a?void 0:o.width,height:a?void 0:o.height}}),e.classList.remove(sv),s.setState("ad-linear",a),s.setState("ad-non-linear",!a),!a){ov("non-linear ad / restarting content");try{s.togglePlay(!0),s.volume=r.volume,s.muted=r.muted}catch(t){ov(t)}}s.hasState(ge)||s.hasState(ev)||!a||i.pause()}),i.on(Hi,()=>{s.emit(fr,{opts:{linear:!0,width:0,height:0}})}),s.on(lv,t=>async function({root:t,content:e,ads:s,eventName:i,err:r={reason:""}}){ov("teardown(event: %s)",i),s.adapter.isAttemptingPrerollOnIOS()&&(s.adapter.setAttemptingPrerollOnIOS(!1),!e.paused&&e.hasState(qt)&&e.hasState($t)&&si(e,e.opts.start_time));t.classList.add("is-seamless"),t.classList.remove(sv),["ad-non-linear","ad-linear"].forEach(t=>e.setState(t,!1)),r.reason&&ov("teardown(:err, reason: %s) %o",r.reason);const n=s.getLastAd();if(e.emit(ur,{root:t}),!s.shouldRestartContent(i))return ov("Lifecycle.teardown(:skip_restart, reason: %s)","Ad prevented restarting content"),mv(t);if(e.currentTime>0&&e.currentTime>=e.duration||"postroll"==s.ad_type||!1===(null==n?void 0:n.restart))return ov("Lifecycle.teardown(:skip_restart, reason: %s)","was a postroll ad"),mv(t);""===e.currentSrc&&e.setSrc(e.original_src);e.paused&&s.shouldRestartContent(i)&&(ov("Lifecycle.teardown(:toggle_play, %s)","attempting to restart content"),await new Promise(t=>{if(e.hasState(ge))return t(null);e.once(M,t)}),await e.togglePlay(!0));if(!e.paused)return ov("Lifecycle.teardown(:ok)","restarted video content"),mv(t)}({root:e,content:s,ads:i,ui:o,err:t.detail,eventName:t.type}));let c=!!t.autoplay;s.on(M,()=>{c&&!1!==l.autopause&&s.hasState("ad-linear")&&i.resume()}),s.on(x,Bs(()=>{!1!==l.autopause&&(c=!i.paused,i.pause())}))}function gv({ads:t,content:e,state:s}){s.listening||(e.on([A,D,R,C],s=>{t.adapter.isCustomPlaybackEnabled()&&(t.adPlaying||t.paused)||e.played.length&&(t.adPlaying&&t.adapter.isLinearAd()&&!e.paused&&e.pause(),pv({ads:t,content:e,seek:s.type===C}))}),s.listening=!0)}function pv({ads:t,content:e,seek:s=!1}){t&&t.setCurrentTime(e.currentTime,void 0,s)}function mv(t){t.classList.remove("is-seamless")}const vv=ci("ads/timers");class TimerRegistry{constructor(t={},e={}){this.intervals=t,this.timers=e}}let yv=-1;function Ev(t,e,s){const i=setInterval(s,e);if(vv(`TimerRegistry.createInterval() -> ${i}`,t.intervals),"object"==typeof i){const e=++yv;return t.intervals[e]=e,e}return t.intervals[i]=i,i}function Tv(t){if(t)return vv("TimerRegistry.empty()",Object.keys(t.timers),Object.keys(t.intervals)),Object.keys(t.intervals).forEach(e=>function(t,e){return vv(`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 vv(`TimerRegistry.removeTimeout() -> ${e}`,t.timers),clearTimeout(t.timers[e]),delete t.timers[e],t}(t,e)),t}function Sv(t){try{return t.getAdPodInfo().getPodIndex()}catch(t){return}}class AdLoadingController{adRequestStart(t){"number"==typeof t&&"number"!=typeof this.requestStart&&(this.requestStart=performance.now())}adRequestEnd(){this.requestStart=void 0}getRemainingAdLoadTime(t,e){return"number"!=typeof e||"number"!=typeof this.requestStart?t:Math.max(0,e-(performance.now()-this.requestStart))}}function Av(t){return Mr(t)&&!t.root.classList.contains("no-fullscreen")}function _v(t){const e=null==t?void 0:t.ads;return!!(e&&Array.isArray(e)&&e.length>0)}class IMA{constructor(t){this.eventHandler=t,this.log=ci("ads/adapter/ima"),this.google=window.google,this._adHandlers=[],this._timers=new TimerRegistry,this._started=!1,this._volumeLevel=0,this._adLoaded=!1,this.customPlaybackEnabled=!1,this._paused=!1,this._all_ads_completed=!1,this._currentDuration=0,this._currentRemaining=0,this._currentDisplayTs=0,this._isInitialized=!1,this._adBreakTime=0,this._prepared=!1,this.opts={},this.loadingController=new AdLoadingController}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(nr)}}isReady(){return!!this._isInitialized}setVideoTag(t){this.videoTag=t,this.customPlaybackEnabled=Av(t),t.root.classList.toggle("ads-custom-playback-enabled",this.customPlaybackEnabled)}setAdBreakTime(t){this._adBreakTime=t}getAdBreakTime(){return this._adBreakTime}isCustomPlaybackEnabled(){return this.customPlaybackEnabled}isAttemptingPrerollOnIOS(){var t;return!!(null===(t=null==this?void 0:this.videoTag)||void 0===t?void 0:t.root.classList.contains("preroll-ios"))}setAttemptingPrerollOnIOS(t){var e;null===(e=null==this?void 0:this.videoTag)||void 0===e||e.root.classList.toggle("preroll-ios",t)}isLinearAd(){return!!this.currentAd()&&!!this._adLinear}getVideoTag(){return this.videoTag}getDimensions(){return this._dimensions||{}}getOpts(){return this.opts}isPaused(){return this._paused}destroy(){const t=this;Tv(this._timers),this._adHandlers&&this._adHandlers.forEach(t=>t()),t._adHandlers=void 0,this._adDisplayContainer&&this._adDisplayContainer.destroy(),t._adDisplayContainer=void 0,this._adsLoader&&this._adsLoader.destroy(),t._adsLoader=void 0,this._adsManager&&this._adsManager.destroy(),t._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 r=this.google.ima.settings;if(t.NumRedirects=t.NumRedirects||t.redirects,r.setVpaidMode(t.VpaidMode||this.google.ima.ImaSdkSettings.VpaidMode.INSECURE),r.setDisableCustomPlaybackForIOS10Plus(!this.customPlaybackEnabled),"NumRedirects"in t&&r.setNumRedirects(t.NumRedirects),"AutoPlayAdBreaks"in t&&r.setAutoPlayAdBreaks(t.AutoPlayAdBreaks),"Locale"in t&&r.setLocale(t.Locale),"Ppid"in t&&r.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,s.loadVideoTimeout=t.media_timeout||-1,s.restoreCustomPlaybackStateOnAdBreakComplete=this.customPlaybackEnabled,this.customPlaybackEnabled&&(s.playAdsAfterTime=this.videoTag.currentTime),this.eventHandler.trigger(rr,s);const i=this._adsManager=e.getAdsManager(this.videoTag,s);this.eventHandler.trigger(sr,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,s;const i=null===(e=t.getAdData())||void 0===e?void 0:e.duration,r=null===(s=t.getAdData())||void 0===s?void 0:s.currentTime;isNaN(i)||isNaN(r)||(this._currentRemaining=i-r,this.eventHandler.trigger(Wi,{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(Ki,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(Vi,e),Tv(this._timers)}),i.addEventListener(this.google.ima.AdEvent.Type.SKIPPED,t=>{this.debugEvent(t);const e=t.getAd();e&&this.emitWithAd(Yi,e)}),i.addEventListener(this.google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,t=>{if(this.isAdPod()&&this.videoTag){const t=Math.abs(this.videoTag.currentTime-this.videoTag.duration)<1?-1:this.videoTag.currentTime;this.setAdBreakTime(t)}this.debugEvent(t);const e=t.getAd();e&&this.emitWithAd(Hi,e)}),i.addEventListener(this.google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,t=>{this.debugEvent(t),this._started=!1,this._currentDisplayTs=0,this.eventHandler.trigger(Zi,{force:!0})}),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(Qi,e)});const r=t=>{this._paused=t,this.eventHandler.trigger(t?ji:qi)};i.addEventListener(this.google.ima.AdEvent.Type.PAUSED,()=>r(!0)),i.addEventListener(this.google.ima.AdEvent.Type.RESUMED,()=>r(!1)),i.addEventListener(this.google.ima.AdEvent.Type.STARTED,()=>r(!1)),i.addEventListener(this.google.ima.AdEvent.Type.VOLUME_MUTED,t=>{this.log("IMA::volume(type: %s, event: %o)","mute",t),this.eventHandler.trigger(zi)});const{width:n,height:a}=t;return n&&a?this.isAdPod()&&t.preload_ads&&!this.videoTag.root.classList.contains(iv)?t.autoplay?this.videoTag.hasState(ge)?this.initAdsManager(i,t):this.once(this.videoTag,M,()=>{i===this._adsManager&&this.initAdsManager(i,t)}):this.videoTag.once(it,()=>{i===this._adsManager&&this.initAdsManager(i,t)}):this.initAdsManager(i,t):void 0}),i&&(this.log("Event(reload: %s)",or),this.eventHandler.trigger(or,e)),this.eventHandler.trigger(xi,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(),this._adsManager=void 0}reset(){this.destroyManager("reset"),Tv(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)})})}initAdsManager(t,e){t.init(e.width,e.height,this.google.ima.ViewMode.NORMAL),this.log("ima.initialise: done initializing"),this.isAdPod()&&t.start()}async initAd(t,e=5e3){var s;this.log(`ima.initAd(adTag: ${t}, timeout: ${e})`),this.customPlaybackEnabled||this.loadingController.adRequestStart(this.opts.total_loading_timeout);try{if(await this.requestAd(t,this.loadingController.getRemainingAdLoadTime(e,this.opts.total_loading_timeout)),this._adLoaded=!0,this.customPlaybackEnabled)return;null===(s=this._adsManager)||void 0===s||s.updateAdsRenderingSettings({loadVideoTimeout:this.loadingController.getRemainingAdLoadTime(this.opts.media_timeout||-1,this.opts.total_loading_timeout)})}catch(t){throw this.log("ima.initAd:",t),this._adLoaded=!1,t}finally{Tv(this._timers)}}async requestAd(t,e){if(this.destroyManager("requestAd"),!this.videoTag)return;this.setAdBreakTime(this.videoTag.currentTime);const{autoplay:s=!1}=this.opts,i=Date.now(),r=this.videoTag.muted;this._volumeLevel=this.videoTag.volume;const n=r||0==this._volumeLevel;this._all_ads_completed=!1,this.log("ima.requestAd(%o)",Object.assign(Object.assign({},this.opts),{autoplay:s,muted:r,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;return 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(ir,{request:a}),this._adsLoader?new Promise(async(t,s)=>{var i;const r=this.waitForAdsManager();null===(i=this._adsLoader)||void 0===i||i.requestAds(a),this.once(this._adsLoader,this.google.ima.AdErrorEvent.Type.AD_ERROR,t=>{s(()=>(this.emitError(Bi,t),Promise.reject(new Error("Ad load failed"))))}),setTimeout(()=>{s(()=>{r.then(t=>{t.destroy(),this._adsManager===t&&(this._adsManager=void 0)});const t=new Error("Ad internal timeout reached");return this.eventHandler.trigger(Xi,t),Promise.reject(t)})},e),t(await r)}).then(t=>new Promise((e,s)=>{this.volume(n?0:this._volumeLevel),this.eventHandler.trigger(Qi,this._volumeLevel);const r=this.cuepoints();if(r&&r.length&&0!==r[0])return e({ad:!1,adsManager:t});this.once(t,this.google.ima.AdErrorEvent.Type.AD_ERROR,t=>{s(()=>(this.emitError(Bi,t),Promise.reject(t)))}),this.once(t,this.google.ima.AdEvent.Type.ALL_ADS_COMPLETED,()=>{this._all_ads_completed=!0,e(null)}),this.once(t,this.google.ima.AdEvent.Type.LOADED,t=>{this.eventHandler.trigger(Gi,{request_load_time:Date.now()-i});const s=t.getAd();s&&(this.log("ima.requestAd: AD_REQUEST_COMPLETED",s.getContentType()),"application/javascript"==s.getContentType()&&this.eventHandler.trigger(er,s),e(null))}),this.once(t,this.google.ima.AdEvent.Type.CLICK,()=>{this.log("ima.requestAd: click event"),this.pause()})}),t=>t()):void 0}async playAd(){if(this.log("ima.playAd()",this),!this._adsManager||!this._adLoaded)return;const t=this.currentAd();if(t&&(!this.customPlaybackEnabled||t.isLinear()))try{await this.startAndWaitForAdCompletion(this._adsManager,t.isLinear())}catch(t){throw this.log("ima.playAd",t),t}finally{this._adLoaded=!1,Tv(this._timers)}}startAndWaitForAdCompletion(t,e){if(!this._started)return this.log("ima.startAndWaitForAdCompletion(manager: %o)",{volume:t.getVolume()}),new Promise((s,i)=>{let r=!1;this.once(t,this.google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,()=>{if(this.log("ima.startAndWaitForAdCompletion: CONTENT_RESUME_REQUESTED <<< happened"),this._started=!1,r)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),r=!0;try{const{ok:e}=await IMA.pollForFatalError({err:t,ima:this});e&&(r=!1)}catch(e){this._started=!1,i(t)}});const n=this.getVideoTag();if(!n)return;const a=()=>{e&&(this._started=!0),t.start(),this.eventHandler.trigger(ar)};if(!e||n.hasState(ge)||n.hasState(ev))return a();n.paused||n.pause(),n.once(M,()=>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:i,resize_non_linear:r}){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||r)&&(i||this.log("ima.onResize %s x %s",t,e),this._adsManager.resize(t,e,this.google.ima.ViewMode.NORMAL))))}onAdRequestEnd(){var t;this.customPlaybackEnabled||(this.loadingController.adRequestEnd(),null===(t=this._adsManager)||void 0===t||t.updateAdsRenderingSettings({loadVideoTimeout:this.opts.media_timeout||-1}))}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>0)}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,[Zi,lr],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(),i=e.getInnerError(),r=i?IMA.unwrapError(i,e.message):"";s={reason:r,type:e.getType(),code:e.getErrorCode()}}catch(t){}const i=e._currentRemaining;return new Promise((t,r)=>{const n=setTimeout(()=>{e.eventHandler&&e.eventHandler.trigger(Fi,s),r(new Error("Ad not progressing"))},2500);e.eventHandler.once(Wi,e=>{const s=e.detail.remaining;-1!==s&&s<i&&(clearTimeout(n),t({ok:1}))})})}static pollRemaining({ima:t,adsManager:e}){let s=-1;return Ev(t._timers,250,function(){const i=e.getRemainingTime();-1!=t._currentRemaining&&t._currentRemaining<=i||(t._currentRemaining=e.getRemainingTime(),s!=t._currentRemaining&&(s=t._currentRemaining,t.eventHandler.trigger(Wi,{remaining:t._currentRemaining,duration:t._currentDuration})))})}once(t,e,s){this._adHandlers.push(function(t,e,s){const i=r=>{s(r),t.removeEventListener(e,i)};return t.addEventListener(e,i),()=>t.removeEventListener(e,i)}(t,e,s))}static race(t,e,s){e.forEach(i=>{const r=(...i)=>{e.forEach(e=>t.removeListener(e,r)),s(i)};t.on(i,r)})}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),i=function(t){try{return t.getAdPodInfo().getTotalAds()}catch(t){return}}(e),r={ad:{duration:e.getDuration(),width:e.getWidth(),height:e.getHeight(),position:s,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)`,r,e),this.eventHandler.trigger(t,r)}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:Sv(e),ad:e})}catch(t){}}}var bv=function(t){var e={exports:{}};return t(e,e.exports),e.exports}(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}(),i=Object.prototype.hasOwnProperty;e.arrayToObject=function(t,e){for(var s=e.plainObjects?Object.create(null):{},i=0;i<t.length;++i)void 0!==t[i]&&(s[i]=t[i]);return s},e.merge=function(t,s,r){if(!s)return t;if("object"!=typeof s){if(Array.isArray(t))t.push(s);else{if("object"!=typeof t)return[t,s];(r.plainObjects||r.allowPrototypes||!i.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,r)),Object.keys(s).reduce(function(t,n){var a=s[n];return i.call(t,n)?t[n]=e.merge(t[n],a,r):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),i="",r=0;r<e.length;++r){var n=e.charCodeAt(r);45===n||46===n||95===n||126===n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122?i+=e.charAt(r):n<128?i+=s[n]:n<2048?i+=s[192|n>>6]+s[128|63&n]:n<55296||n>=57344?i+=s[224|n>>12]+s[128|n>>6&63]+s[128|63&n]:(r+=1,n=65536+((1023&n)<<10|1023&e.charCodeAt(r)),i+=s[240|n>>18]+s[128|n>>12&63]+s[128|n>>6&63]+s[128|63&n])}return i},e.compact=function(t,s){if("object"!=typeof t||null===t)return t;var i=s||[],r=i.indexOf(t);if(-1!==r)return i[r];if(i.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],i)):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],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))}}),Lv={brackets:function(t){return t+"[]"},indices:function(t,e){return t+"["+e+"]"},repeat:function(t){return t}},Rv={delimiter:"&",strictNullHandling:!1,skipNulls:!1,encode:!0,encoder:bv.encode},Iv=function t(e,s,i,r,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(r)return a?a(s):s;c=""}if("string"==typeof c||"number"==typeof c||"boolean"==typeof c||bv.isBuffer(c))return a?[a(s)+"="+a(c)]:[s+"="+String(c)];var h,u=[];if(void 0===c)return u;if(Array.isArray(o))h=o;else{var f=Object.keys(c);h=l?f.sort(l):f}for(var g=0;g<h.length;++g){var p=h[g];n&&null===c[p]||(u=Array.isArray(c)?u.concat(t(c[p],i(s,p),i,r,n,a,o,l,d)):u.concat(t(c[p],s+(d?"."+p:"["+p+"]"),i,r,n,a,o,l,d)))}return u},kv=Object.prototype.hasOwnProperty,wv={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3,strictNullHandling:!1,plainObjects:!1,allowPrototypes:!1,allowDots:!1,decoder:bv.decode},Pv=function t(e,s,i){if(!e.length)return s;var r,n=e.shift();if("[]"===n)r=(r=[]).concat(t(e,s,i));else{r=i.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&&i.parseArrays&&o<=i.arrayLimit?(r=[])[o]=t(e,s,i):r[a]=t(e,s,i)}return r},Dv=function(t,e,s){if(t){var i=s.allowDots?t.replace(/\.([^.[]+)/g,"[$1]"):t,r=/(\[[^[\]]*])/g,n=/(\[[^[\]]*])/.exec(i),a=n?i.slice(0,n.index):i,o=[];if(a){if(!s.plainObjects&&kv.call(Object.prototype,a)&&!s.allowPrototypes)return;o.push(a)}for(var l=0;null!==(n=r.exec(i))&&l<s.depth;){if(l+=1,!s.plainObjects&&kv.call(Object.prototype,n[1].slice(1,-1))&&!s.allowPrototypes)return;o.push(n[1])}return n&&o.push("["+i.slice(n.index)+"]"),Pv(o,e,s)}},Cv=function(t,e){var s,i,r=t,n=e||{},a=void 0===n.delimiter?Rv.delimiter:n.delimiter,o="boolean"==typeof n.strictNullHandling?n.strictNullHandling:Rv.strictNullHandling,l="boolean"==typeof n.skipNulls?n.skipNulls:Rv.skipNulls,d=("boolean"==typeof n.encode?n.encode:Rv.encode)?"function"==typeof n.encoder?n.encoder:Rv.encoder:null,c="function"==typeof n.sort?n.sort:null,h=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?r=(i=n.filter)("",r):Array.isArray(n.filter)&&(s=i=n.filter);var u,f=[];if("object"!=typeof r||null===r)return"";u=n.arrayFormat in Lv?n.arrayFormat:"indices"in n?n.indices?"indices":"repeat":"indices";var g=Lv[u];s||(s=Object.keys(r)),c&&s.sort(c);for(var p=0;p<s.length;++p){var m=s[p];l&&null===r[m]||(f=f.concat(Iv(r[m],m,g,o,l,d,i,c,h)))}return f.join(a)},Ov=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||bv.isRegExp(s.delimiter)?s.delimiter:wv.delimiter,s.depth="number"==typeof s.depth?s.depth:wv.depth,s.arrayLimit="number"==typeof s.arrayLimit?s.arrayLimit:wv.arrayLimit,s.parseArrays=!1!==s.parseArrays,s.decoder="function"==typeof s.decoder?s.decoder:wv.decoder,s.allowDots="boolean"==typeof s.allowDots?s.allowDots:wv.allowDots,s.plainObjects="boolean"==typeof s.plainObjects?s.plainObjects:wv.plainObjects,s.allowPrototypes="boolean"==typeof s.allowPrototypes?s.allowPrototypes:wv.allowPrototypes,s.parameterLimit="number"==typeof s.parameterLimit?s.parameterLimit:wv.parameterLimit,s.strictNullHandling="boolean"==typeof s.strictNullHandling?s.strictNullHandling:wv.strictNullHandling,""===t||null==t)return s.plainObjects?Object.create(null):{};for(var i="string"==typeof t?function(t,e){for(var s={},i=t.split(e.delimiter,e.parameterLimit===1/0?void 0:e.parameterLimit),r=0;r<i.length;++r){var n,a,o=i[r],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))),kv.call(s,n)?s[n]=[].concat(s[n]).concat(a):s[n]=a}return s}(t,s):t,r=s.plainObjects?Object.create(null):{},n=Object.keys(i),a=0;a<n.length;++a){var o=n[a],l=Dv(o,i[o],s);r=bv.merge(r,l,s)}return bv.compact(r)};const Mv=ci("fpads:macros"),xv=/\[([\s\S]+?)\]/g;class Macros{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((i,r)=>{const n=Macros.process_str(r,e,s,!0),a=t[r];return null===a?(i[n]=a,i):"object"==typeof a?(i[n]=Macros.process_obj(a,e,s),i):"string"==typeof a?(i[n]=Macros.process_str(a,e,s),i):(console.error(new Error(`${a} at ${r} not a handled Macro type`)),i)},{})}static process_str(t,e,s,i=!1){return t.replace(e.pattern,(t,e)=>{const r=Macros.normalize(e);if(!(r in s)||void 0===s[r])return t;const n=s[r],a=i?n:Macros.cast(n);return Mv("Macro.replace(raw: %s, macro: %s, value: %s)",i,e,a),a})}constructor(t={},e=xv){this.vars=t,this.pattern=e}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),[i,r]=t.split("?"),n=Ov(r||"",{strictNullHandling:!0,decoder:t=>t}),a=Cv(Macros.process_obj(n,this,s),{encode:!1,strictNullHandling:!0});return Macros.process_str(i,this,s,!0)+"?"+a}}function Fv(t,e={width:0,height:0}){let s,i;try{const t=document.createElement("a");t.href=s=window.location!=window.parent.location?document.referrer:document.location.href,i=t.hostname}catch(t){console.error(t)}const{width:r,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:i,player_width:r,player_height:n,video_url:a,videourl:a},o)}Macros.patterns={BRACKETS:xv,CURLY:/\{([\s\S]+?)\}/g,UNDERSCORE:/__([\s\S]+?)__/g};const Nv=/^flowplayer:\/\/(.+)/;async function Uv(t){if("string"==typeof t&&Nv.test(t)){const e=Nv.exec(t),s=e&&window[e[1]];if(s)return Uv(s)}if("function"!=typeof t)return t;try{return await t()}catch(t){return""}}async function Bv(t){if("function"==typeof t)return[await Uv(t)];if("string"==typeof t)return[await Uv(t)];if(Array.isArray(t)){const e=t;return await Promise.all(e.map(Uv))}if("object"==typeof t&&t&&t.adTag)return await Bv(t.adTag);throw new Error(`\n unhandled ads type ${typeof t}:\n ${JSON.stringify(t)}\n can be:\n | Array<string>\n | string\n | function\n | {adTag: Array<string>|string|function}\n `)}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 i=s?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 $v=Object.prototype,Gv=Object.getPrototypeOf;const Hv=ci("fpads:ads:state");var Kv;!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"}(Kv||(Kv={}));class AdsState{static of(){return new AdsState}constructor(t=0){this._state=t}reset(){this._state=0}toggleState(t,e){return void 0===t&&Hv(new Error("AdState cannot toggleState for `undefined`")),void 0===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 Vv={ok:ci("fpads:analytics:request-queue"),err:ci("fpads:analytics:request-queue:err"),warn:ci("fpads:analytics:request-queue:warn")};class RequestQueue{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 Vv.ok("maybe_spawn_req called Queue that is EMPTY"),t;if(RequestQueue.is_high_water(t))return Vv.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){Vv.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,i]){if(Vv.ok(`Request[${i.event_type}] request`,i,t.stats),Date.now()<t.stats.ttl)return Vv.warn(`Request[${i.event_type}] skipping because too many errors too quickly`,t.stats);const r=new XMLHttpRequest;t.open.push(r),r.timeout=RequestQueue.REQUEST_TIMEOUT_MS,r.ontimeout=function(){RequestQueue.handle_error(t,r),Vv.warn(`Request[${i.event_type}] timed out in ${r.timeout}ms`,t.stats)},r.onerror=function(e){RequestQueue.handle_error(t,r),e&&Vv.err(e),Vv.warn(`Request[${i.event_type}] encountered an Error`,r.responseText,t.stats)},r.onreadystatechange=function(){r.readyState==XMLHttpRequest.DONE&&RequestQueue.rm(t,r),Math.floor(r.status/100)},r.onload=function(){RequestQueue.rm(t,r),t.stats.failures&&t.stats.failures--,Vv.ok(`Request[${i.event_type}] :ok`,r.status)},r.open(s,e),r.setRequestHeader("Content-Type","text/plain;charset=UTF-8");try{r.send(JSON.stringify(i))}catch(t){Vv.err(t)}}static rpush(t,...e){return e.forEach(e=>{if(RequestQueue.is_high_water(t))return Vv.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}constructor(t=[],e=[],s={failures:0,ttl:0}){this.pending=t,this.open=e,this.stats=s}}RequestQueue.MAX_OPEN_REQUESTS=3,RequestQueue.REQUEST_TIMEOUT_MS=4e3,RequestQueue.REQUEST_TTL_MS=5e3,RequestQueue.MAX_FAILURE_COUNT=3;const jv={"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"},qv={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"},Wv={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},Yv={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"},zv={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":case"NT 5.1":return"XP";case"NT 5.0":return"2000";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 i=Utils.getVersionPrecision(t),r=Utils.getVersionPrecision(e);let n=Math.max(i,r),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(i,r)),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 i;if(Array.prototype.map)return Array.prototype.map.call(t,e);for(i=0;i<t.length;i+=1)s.push(e(t[i]));return s}static find(t,e){let s,i;if(Array.prototype.find)return Array.prototype.find.call(t,e);for(s=0,i=t.length;s<i;s+=1){const i=t[s];if(e(i,s))return i}}static assign(t,...e){const s=t;let i,r;if(Object.assign)return Object.assign(t,...e);for(i=0,r=e.length;i<r;i+=1){const t=e[i];if("object"==typeof t&&null!==t){Object.keys(t).forEach(e=>{s[e]=t[e]})}}return t}static getBrowserAlias(t){return jv[t]}static getBrowserTypeByAlias(t){return qv[t]||""}}const Qv=/version\/(\d+(\.?_?\d+)+)/i,Xv=[{test:[/googlebot/i],describe(t){const e={name:"Googlebot"},s=Utils.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,t)||Utils.getFirstMatch(Qv,t);return s&&(e.version=s),e}},{test:[/opera/i],describe(t){const e={name:"Opera"},s=Utils.getFirstMatch(Qv,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(Qv,t);return s&&(e.version=s),e}},{test:[/SamsungBrowser/i],describe(t){const e={name:"Samsung Internet for Android"},s=Utils.getFirstMatch(Qv,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(Qv,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(Qv,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(Qv,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(Qv,t);return s&&(e.version=s),e}},{test:[/coast/i],describe(t){const e={name:"Opera Coast"},s=Utils.getFirstMatch(Qv,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(Qv,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(Qv,t);return s&&(e.version=s),e}},{test:[/ucbrowser/i],describe(t){const e={name:"UC Browser"},s=Utils.getFirstMatch(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,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(Qv,t);return s&&(e.version=s),e}},{test:[/playstation 4/i],describe(t){const e={name:"PlayStation 4"},s=Utils.getFirstMatch(Qv,t);return s&&(e.version=s),e}},{test:[/safari|applewebkit/i],describe(t){const e={name:"Safari"},s=Utils.getFirstMatch(Qv,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 Zv=[{test:[/Roku\/DVP/],describe(t){const e=Utils.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,t);return{name:Yv.Roku,version:e}}},{test:[/windows phone/i],describe(t){const e=Utils.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,t);return{name:Yv.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:Yv.Windows,version:e,versionName:s}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(t){const e={name:Yv.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),i={name:Yv.MacOS,version:e};return s&&(i.versionName=s),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:Yv.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),i={name:Yv.Android,version:e};return s&&(i.versionName=s),i}},{test:[/(web|hpw)[o0]s/i],describe(t){const e=Utils.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,t),s={name:Yv.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:Yv.BlackBerry,version:e}}},{test:[/bada/i],describe(t){const e=Utils.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,t);return{name:Yv.Bada,version:e}}},{test:[/tizen/i],describe(t){const e=Utils.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,t);return{name:Yv.Tizen,version:e}}},{test:[/linux/i],describe:()=>({name:Yv.Linux})},{test:[/CrOS/],describe:()=>({name:Yv.ChromeOS})},{test:[/PlayStation 4/],describe(t){const e=Utils.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,t);return{name:Yv.PlayStation4,version:e}}}],Jv=[{test:[/googlebot/i],describe:()=>({type:"bot",vendor:"Google"})},{test:[/huawei/i],describe(t){const e=Utils.getFirstMatch(/(can-l01)/i,t)&&"Nova",s={type:Wv.mobile,vendor:"Huawei"};return e&&(s.model=e),s}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:()=>({type:Wv.tablet,vendor:"Nexus"})},{test:[/ipad/i],describe:()=>({type:Wv.tablet,vendor:"Apple",model:"iPad"})},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:()=>({type:Wv.tablet,vendor:"Apple",model:"iPad"})},{test:[/kftt build/i],describe:()=>({type:Wv.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"})},{test:[/silk/i],describe:()=>({type:Wv.tablet,vendor:"Amazon"})},{test:[/tablet(?! pc)/i],describe:()=>({type:Wv.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:Wv.mobile,vendor:"Apple",model:e}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:()=>({type:Wv.mobile,vendor:"Nexus"})},{test:[/[^-]mobi/i],describe:()=>({type:Wv.mobile})},{test:t=>"blackberry"===t.getBrowserName(!0),describe:()=>({type:Wv.mobile,vendor:"BlackBerry"})},{test:t=>"bada"===t.getBrowserName(!0),describe:()=>({type:Wv.mobile})},{test:t=>"windows phone"===t.getBrowserName(),describe:()=>({type:Wv.mobile,vendor:"Microsoft"})},{test(t){const e=Number(String(t.getOSVersion()).split(".")[0]);return"android"===t.getOSName(!0)&&e>=3},describe:()=>({type:Wv.tablet})},{test:t=>"android"===t.getOSName(!0),describe:()=>({type:Wv.mobile})},{test:t=>"macos"===t.getOSName(!0),describe:()=>({type:Wv.desktop,vendor:"Apple"})},{test:t=>"windows"===t.getOSName(!0),describe:()=>({type:Wv.desktop})},{test:t=>"linux"===t.getOSName(!0),describe:()=>({type:Wv.desktop})},{test:t=>"playstation 4"===t.getOSName(!0),describe:()=>({type:Wv.tv})},{test:t=>"roku"===t.getOSName(!0),describe:()=>({type:Wv.tv})}],ty=[{test:t=>"microsoft edge"===t.getBrowserName(!0),describe(t){if(/\sedg\//i.test(t))return{name:zv.Blink};const e=Utils.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,t);return{name:zv.EdgeHTML,version:e}}},{test:[/trident/i],describe(t){const e={name:zv.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:zv.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:zv.Gecko},s=Utils.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,t);return s&&(e.version=s),e}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:zv.Blink})},{test:[/(apple)?webkit/i],describe(t){const e={name:zv.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(Xv,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(Zv,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(Jv,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(ty,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 i={};let r=0;if(Object.keys(t).forEach(n=>{const a=t[n];"string"==typeof a?(i[n]=a,r+=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 i=Utils.find(t,t=>this.isPlatform(t));if(i){const t=this.satisfies(e[i]);if(void 0!==t)return t}}if(r>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 s=this.getBrowserName().toLowerCase();let i=t.toLowerCase();const r=Utils.getBrowserTypeByAlias(i);return e&&r&&(i=r.toLowerCase()),i===s}compareVersion(t){let e=[0],s=t,i=!1;const r=this.getBrowserVersion();if("string"==typeof r)return">"===t[0]||"<"===t[0]?(s=t.substr(1),"="===t[1]?(i=!0,s=t.substr(2)):e=[],">"===t[0]?e.push(1):e.push(-1)):"="===t[0]?s=t.substr(1):"~"===t[0]&&(i=!0,s=t.substr(1)),e.indexOf(Utils.compareVersions(r,s,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))}}
2
2
  /*!
3
3
  * Bowser - a browser detector
4
4
  * https://github.com/lancedikson/bowser
5
5
  * MIT License | (c) Dustin Diaz 2012-2015
6
6
  * MIT License | (c) Denis Demchenko 2015-2019
7
- */const ey=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 qv}static get ENGINE_MAP(){return zv}static get OS_MAP(){return Yv}static get PLATFORMS_MAP(){return Wv}}.parse(window.navigator.userAgent),{platform:sy,os:iy,browser:ry}=ey,ny=t=>t&&t.toLowerCase();var ay={rnd:Math.random().toString(36).substr(2,32),os:ny(iy.name+(iy.versionName?` ${iy.versionName}`:"")),device:ny(sy.type),browser:ny(ry.name),browser_version:(ry&&ry.version?ry.version:"unknown").split(".").shift(),plugin_version:"3.43.0-rc.1"};const oy="https://fp-eu-w1-aai.flowplayer.com/in",ly="POST",dy=[$i,Bi,Gi,Vi,Ki,lr,Yi],cy=["event_type","ad_tag_id","media_id","player_id","site_id","sitegroup_id","rnd","os","device","browser","browser_version","plugin_version","player_version"],hy=["vast_error","reason","request_load_time","ad_type","vast_ad_id"],uy=ci("ads/analytics"),fy=RequestQueue.of(),gy=(...t)=>Object.assign({},...t);class Analytics{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,gy(t.metadata,e,{player_version:"3.43.0-rc.1"})),t}constructor(t,e={}){this.emitter=t,this.metadata=gy(ay,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),uy(this),this.wireup()}wireup(){this.events.forEach(t=>{this.emitter.on(t,e=>{const s=e.detail,i=gy(this.metadata,{event_type:t},s),r=Analytics.pluck_valid_keys(this,i),n=Analytics.ensure_required_keys(this,r);if(uy(`Event[${t}]`,{payload:r,observation:s}),n.length)return uy(`Analytics.validate_metadata() failed for\n Event[${t}]\n missing keys: ${n}`,r);RequestQueue.rpush(fy,[oy,ly,r])})})}destroy(){const t=this;t.emitter=t.metadata=t.events=t.required_keys=t.optional_keys=t.valid_keys=void 0}}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)}}const py=ci("ads/controller"),my={show_all_ads_on_seek:!1,timeout:5e3,preload_advance:5};class AdsController extends EventBus{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({},my),t),this.analytics=(e=this,Analytics.of(e,{required_keys:cy,optional_keys:hy,events:dy})),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();const t=this;t.analytics=void 0,t.opts=void 0,t.adapter=void 0,t._state=void 0,t._schedule=void 0,t._lastAd=void 0,t._macros=void 0}stop(){this.adapter&&this.adapter.stop()}onContentNewSrc(){var t;this._state.reset(),this.adapter.destroyManager(),this.adapter.contentComplete(),null===(t=this.videoTag)||void 0===t||t.root.classList.remove(sv)}wireup(){const t=()=>{var t,e;this.adapter.onAdRequestEnd(),null===(t=this.videoTag)||void 0===t||t.setState("ad-paused",!1),null===(e=this.videoTag)||void 0===e||e.setState("ad-playing",!0),this._state.toggleState(Kv.PLAYING,!0)};this.on(ar,t),this.on(Ki,t),this.on(qi,t);const e=t=>{var e,s;(null==t?void 0:t.type)!==Bi&&this.adapter.onAdRequestEnd(),null===(e=this.videoTag)||void 0===e||e.setState("ad-paused",(null==t?void 0:t.type)===ji),null===(s=this.videoTag)||void 0===s||s.setState("ad-playing",!1),this.adPlaying&&this._state.toggleState(Kv.PLAYING,!1)};this.on(Zi,e),this.on(Ni,e),this.on(Fi,e),this.on(Bi,e),this.on(ji,e),this.on(Yi,e),this.on(Vi,e),this.on(Zi,()=>{this._state.toggleState(Kv.BREAK_ACTIVE,!1)}),this.on(nr,()=>{console.error("Adapter init failed"),e(),this._state.toggleState(Kv.FATAL_ERROR,!0)}),this.on(or,async t=>{if(py("Ads.on(RELOAD_AD_REQUESTED)",t),this._schedule){if(e(),t)return this._schedule.reset(this._schedule.getAds());this._state.hasAny(Kv.AD_AVAILABLE)&&(this._schedule.decrement(),this._state.toggleState(Kv.AD_AVAILABLE,!1))}})}async initialize(t,e={},s){return py("Ads.initialize():",t,e,s),this._state.toggleState(Kv.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){py("Ads.setVideoTag():",t),await this.adapter.setVideoTag(t),this.trigger(Ui,t),this.adapter.isReady()&&await this.adapterInitialized(),t.on(dr,()=>this.adapter.pause()),t.on(cr,()=>this.adapter.resume()),t.on(hr,()=>t.toggleMute()),t.on(b,()=>{this.adapter.volume(t.muted?0:0==t.volume?.1:t.volume)}),t.on(F,()=>{if(t.currentSrc){if(!t.hasState("ad-playing")&&!t.hasState("ad-paused"))return this.onContentNewSrc();if(this.stop(),!this.adapter.isLinearAd())return this.onContentNewSrc();this.setIsContentProcessingNewSrc(!0),this.once(Zi,()=>{setTimeout(()=>{this.setIsContentProcessingNewSrc(!1),this.onContentNewSrc()},0)})}})}waitForVideoTag(){return new Promise(t=>{const e=this.adapter.getVideoTag();if(e)return t(e);this.on(Ui,e=>{this.once(xi,()=>t(e))})})}async adapterInitialized(t){py("Ads.adapterInitialized()"),this._state.toggleState(Kv.INITIALIZING,!1),this._state.toggleState(Kv.BREAK_ACTIVE,!!this.hasPreroll()),await this.setCurrentTime(0,t),t||(this.checkIfBreakComplete(),this.adapter.isAdPod()||this.trigger(Ni))}async fetchNextAd(t,e=0){var s,i;if(!this._schedule||this.getIsContentProcessingNewSrc())return;if(!this.adapter.isReady())return;if(e>50)throw this._state.toggleState(Kv.FATAL_ERROR,!0),this._state.toggleState(Kv.FETCHING_AD,!1),new Error("Ads.fetchNextAd() :max_recursion_depth");const r=(null===(s=this._schedule)||void 0===s?void 0:s.getNextAd())||(null===(i=this._schedule)||void 0===i?void 0:i.getPostroll());if(!r||this.adapter.canDismissNonLinear()||-1===t)if(this._schedule.waitForLoad(t,r,this.opts.preload_ads))this._state.toggleState(Kv.FETCHING_AD,!1);else if(r!==this._schedule.getPostroll()||(this._schedule.setPostrollActive(),-1===t))if(this._schedule.isDrained()||this._schedule.increment(),r){py("Ads.fetchNextAd",r),this._state.toggleState(Kv.FETCHING_AD,!0);try{return await this.requestAd(r),this._state.toggleState(Kv.AD_AVAILABLE,!0),void this._state.toggleState(Kv.FETCHING_AD,!1)}catch(s){return py("Ads.fetchNextAd(err: %o, ad: %o)",s,r),this.setLastAd(r),r!==this._schedule.getPostroll()?await this.fetchNextAd(t,++e):void this._state.toggleState(Kv.FETCHING_AD,!1)}}else this._state.toggleState(Kv.FETCHING_AD,!1);else this._state.toggleState(Kv.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(Kv.FETCHING_AD))return;if(this._state.hasAny(Kv.BREAK_ACTIVE)&&this.adapter.isLinearAd())return;if(this._state.hasAny(Kv.PLAYING)&&this.adapter.isLinearAd())return;const i=0===t&&0===this._schedule.getNextIndex();try{if(s&&!this.opts.show_all_ads_on_seek&&this.skipAdsOnSeek(t),this._state.hasAny(Kv.AD_AVAILABLE)||await this.fetchNextAd(t),!this._state.hasAny(Kv.AD_AVAILABLE)||!this.shallPlayAd(t))return;await this.playAd(),await this.setCurrentTime(t),this.checkIfBreakComplete()}catch(t){py("setCurrentTime: Error(from: setCurrentTime, message: %s)",t.message)}finally{i&&this.trigger(tr)}}async playAd(){var t;if(!this._state.hasAny(Kv.AD_AVAILABLE))return;this._state.toggleState(Kv.AD_AVAILABLE,!1),this._state.toggleState(Kv.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(Kv.BREAK_ACTIVE))return py("Ads.checkIfBreakComplete(:bail, ad: %o)",this.getLastAd());py("Ads.checkIfBreakComplete(:run, ad: %o)",this.getLastAd()),this._state.toggleState(Kv.BREAK_ACTIVE,!1),this.adapter.isAdPod()||this.trigger(Zi)}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(t===Zi&&this._state.hasAny(Kv.BREAK_ACTIVE)&&!this.adapter.isAdPod()&&!e.force)return py("skipping AD_BREAK_COMPLETE reason: %s pod=%s",this._state.toString(),this.adapter.isAdPod());if(null===(i=e)||"object"!=typeof i||Gv(i)!==$v)return this.dispatch(t,e);var i;const r=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,r)}dispatch(t,e){const s=this.adapter.getVideoTag();if(s){py(":dispatch",t,e),this.adapter.isAdPod()&&"object"==typeof e&&"time"in e&&"preroll"!==e.ad_type&&(e.time=this.adapter.getAdBreakTime());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}};s.dispatchEvent(new CustomEvent(He,{detail:i}))}catch(t){py(":error",t)}this.emit(t,e),Ts(s,t,e)}}get ad_type(){if(!this.videoTag)return;if(!this.adapter.isAdPod())return this._schedule&&this._schedule.getCurrentType();const t=this.adapter.getAdBreakTime();return-1===t?"postroll":this.videoTag.hasState(Zt)||t<1?"preroll":"midroll"}shouldRestartContent(t){var e,s;if(!(null===(e=this.videoTag)||void 0===e?void 0:e.root.classList.contains(iv)))return!1;if(t===Ni&&!(null===(s=this.videoTag)||void 0===s?void 0:s.hasState(qt)))return!1;if(this.getIsContentProcessingNewSrc())return!1;if(this.adapter.isAdPod())return!0;const i=this.getLastAd();return!i||!i.outstream&&!1!==i.restart}async finished(t){if(this._schedule&&(py("Ads.finished"),!(this.adapter.isCustomPlaybackEnabled()&&this._state.hasAny(Kv.PLAYING)&&this.adapter.isLinearAd()))){py("Ads.finished: trying to play postroll");try{if(!this._schedule.getPostroll())return py("Ads.finished: no postroll found"),await this.adapter.contentComplete();this._state.hasAny(Kv.AD_AVAILABLE)||await this.fetchNextAd(-1),await this.playAd(),this.adapter.contentComplete()}catch(t){py("Ads.finished: postroll failed:",t)}finally{this.trigger(Ji),this.checkIfBreakComplete(),"function"==typeof t&&t()}}}hasPreroll(){return this._schedule&&Schedule.hasPreroll(this._schedule.getAds())}shallPlayAd(t){var e,s;return!!(null===(e=this.videoTag)||void 0===e?void 0:e.root.classList.contains(iv))&&((!this.adapter||!this.adapter.isAdPod())&&(!(!this._state||this._state.hasAny(Kv.FATAL_ERROR))&&!!(null===(s=this._schedule)||void 0===s?void 0:s.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;py("Ads.requestAd(ad: %o)",{ad:t,timeout:s,idx:e});const i=await Bv(t);if(void 0===i[e])return setTimeout(()=>this.trigger(Ni),0),Promise.reject(new Error("Ad failed, no fallbacks left"));if(!i[e])return await this.requestAd(i,e+1,s);this.trigger($i,t);const r=this._macros.compile(i[e],Fv(this.opts,this.adapter.getDimensions()));try{return void await this.adapter.initAd(r,s)}catch(t){return py(`Ads.requestAd(:fallback, idx: ${e}, length: ${i.length}, adTag: ${i[e]})\nError `,{adTag:i,err:t}),this.requestAd(i,e+1,s)}}resetSchedule(t){this._schedule&&this._schedule.reset(t)}get adPlaying(){return this._state&&this._state.hasAny(Kv.PLAYING)}get adBreak(){return this._state&&this._state.hasAny(Kv.BREAK_ACTIVE)}get adRequesting(){return this._state.hasAny(Kv.FETCHING_AD)}get adLinear(){return this.adBreak&&this.adapter.isLinearAd()}}var vy=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"}),yy=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 Ey(t){return Object.assign({muted:!1,timeout:250,inline:!1},t)}function Ty(t,e){var s=t.muted,i=t.timeout,r=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===r&&a.setAttribute("playsinline","playsinline"),a.src=o,new Promise(function(t){l=a.play(),d=setTimeout(function(){c(!1,new Error("Timeout "+i+" ms has been reached"))},i),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 Sy={audio:function(t){return Ty(t=Ey(t),function(){return{element:document.createElement("audio"),source:URL.createObjectURL(vy)}})},video:function(t){return Ty(t=Ey(t),function(){return{element:document.createElement("video"),source:URL.createObjectURL(yy)}})}};let Ay;async function _y(t=!0){return Ay||(Ay=await Sy.video({timeout:500,muted:t}),Ay)}var by=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 Ly=["progress","duration","remaining"];class AdUI extends HTMLElement{static get observedAttributes(){return Ly}constructor(t){super(),this.player=t,this.className="fp-ad-ui",this.append(...t.createComponents(ln,dn)),t.on(gr,t=>{let{ui_flags:e}=t.detail;if(e=e||0,(8&e)>0){const t=document.createElement("div");t.classList.add("ad-attribution"),t.textContent=this.player.i18n("ads.advertisement","Advertisement"),this.append(t)}})}}const Ry=ci("fpads:native:outstream"),Iy={OUTSTREAM:"is-outstream",HIDDEN:"is-outstream-hidden",SHOWING:"is-outstream-visible",DONE:"is-outstream-done"};var ky,wy;!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"}(ky||(ky={})),function(t){t[t.None=0]="None",t[t.Booting=1]="Booting",t[t.Ready=2]="Ready",t[t.Disposed=3]="Disposed"}(wy||(wy={}));class Outstream{constructor({ads:t,root:e,content:s,ima:i}){this.state=wy.None,Ry("creating Outstream instance"),this.content=s,this.ads=t,this.root=e,this.ima=i,this.aspectRatio=s.videoHeight/s.videoWidth,this.dimensions=function(t){if(t.clientWidth>0||t.clientHeight)return Jm(t);const e={height:t.style.height};tv(t,"opacity",0),tv(t,"display","absolute"),tv(t,"display","inline-block"),tv(t,"height","auto");const s=Jm(t);return tv(t,"height",e.height),tv(t,"opacity",1),s}(this.root),this.adUi=new AdUI(s),this.initialVolumeState={},e.classList.add(Iy.OUTSTREAM),e.classList.add(iv),e.append(this.adUi),this.hide(),this.ads.on(Hi,t=>{var e;if(this.state==wy.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(m,t=>{if(this.state==wy.Disposed)return;const e=t.detail;e&&(this.dimensions={width:e.contentRect.width,height:e.contentRect.height},this.ads.resize(this.dimensions))});let r=1,n=!0;s.on(X,t=>{if(this.state==wy.Disposed)return;const e=t.detail;if(e)switch(this.state){case wy.Booting:return Ry(":boot skipping intersectionchange");case wy.None:return this.state=wy.Booting,this.begin_life_cycle();case wy.Ready:if(r=e.ratio,e.ratio>=.5&&this.ads.adPlaying)return;e.ratio>=.5&&n&&this.ads.resume(),e.ratio<.5&&this.ads.pause()}}),this.content.on(ji,()=>n=r<.5),this.setup(),setTimeout(()=>(this.state=wy.Booting,this.begin_life_cycle()),0)}hide(){return this}restore_aspect_ratio(){return Ry(`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.content.setState("ad-linear",!0)}async begin_life_cycle(){var t;this.state=wy.Ready;const{error:e,result:s}=await _y(!1),{result:i}=await _y(!0);this.content.emit(gr,{ui_flags:null===(t=this.content.opts.ads)||void 0===t?void 0:t.ui}),this.attach_ad_listeners(),this.initialVolumeState={can_autoplay:!(!s&&!i),muted:!s},Ry(`Outstream.show() :autoplay >> sound=${s}`),e&&this.content&&!s&&(this.content.muted=!0,this.content.volume=0),await this.ads.setVideoTag(this.content),await cv({ads:this.ads,content:this.content,adContainer:this.adUi,ima:this.ima,state:{listening:!1},config:this.content.opts}),pv({content:this.content,ads:this.ads}),this.state=wy.Ready}attach_ad_listeners(){this.ads.once(Hi,()=>{this.show(),this.ads.adPlaying&&this.ads.pause()});const t=()=>{lv.forEach(e=>this.ads.removeListener(e,t));const e=new CustomEvent(ky.OUTSTREAM_TEARDOWN);Ry("Outstream(:teardown)",e),this.content.dispatchEvent(e)};lv.forEach(e=>this.ads.once(e,t)),this.content.once(ky.OUTSTREAM_TEARDOWN,t=>{setTimeout(()=>{if(t.defaultPrevented)return this.handle_endscreen();this.dispose()},0)})}handle_endscreen(){this.reset_ui(),this.ads.reset(),fv({config:this.content.opts,ui:this.adUi,ads:this.ads,adContainer:this.adUi,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(rv)})}setup(){this.root.classList.add(Outstream.CLASS.OUTSTREAM),this.root.classList.add(Outstream.CLASS.HIDDEN),this.content.setState("ad-linear",!1),this.empty_src()}reset_ui(){const t=this.root;t.classList.remove(Outstream.CLASS.SHOWING),t.classList.remove(Outstream.CLASS.OUTSTREAM)}dispose(){if(this.state==wy.Disposed)return;const t=this.root,e=this.content;this.reset_ui(),t.classList.add(Outstream.CLASS.OUTSTREAM),t.classList.add(Outstream.CLASS.DONE);const s=this;s.video=s.container=s.ads=0,this.state=wy.Disposed,e.destroy(),t.innerHTML=""}}function Py(t){return t&&"number"==typeof t.time}function Dy(t){return t&&"number"==typeof t.percentage&&"number"!=typeof t.time}Outstream.CLASS=Iy;const Cy=ci("ads/ima/sdk");var Oy,My;async function xy(t,e){var s;const i=null===(s=null===window||void 0===window?void 0:window.google)||void 0===s?void 0:s.ima;if(e?null==i?void 0:i.dai:i)return void Cy(":noop");const r=e?"https://imasdk.googleapis.com/js/sdkloader/ima3_dai.js":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 i=document.querySelector(`script[src='${t}']`);if(i)return Fy(i,e,s);i=document.createElement("script"),i.setAttribute("state",Oy.LOADING),Fy(i,e,s),i.src=t,document.head.appendChild(i)})}(r),void Cy(":loaded")}catch(t){Cy(`:error ${t.message}`,t)}}function Fy(t,e,s){const i=t.getAttribute("state");if(i&&[Oy.ERROR,Oy.LOADED].includes(i))return e(void 0);t.addEventListener("load",()=>{t.setAttribute("state",Oy.LOADED),e(void 0)},{once:!0}),["error","abort"].forEach(e=>{t.addEventListener(e,()=>{t.setAttribute("state",Oy.ERROR),s("script failed to load")},{once:!0})})}!function(t){t.LOADING="loading",t.LOADED="loaded",t.ERROR="error"}(Oy||(Oy={})),function(t){t.LOADING="loading",t.LOADED="loaded",t.ERROR="error"}(My||(My={}));const Ny=ci("ads/ima/sdk"),Uy="https://cdn.jsdelivr.net/npm/prebid.js@latest/dist/not-for-prod/prebid.js",By=Uy;async function $y(t){var e;const s=t._storage.getItem("prebid/debug")?Uy:By;if(null===(e=null===window||void 0===window?void 0:window.pbjs)||void 0===e?void 0:e.version)Ny(":noop");else if(!document.querySelector(`script[src='${s}']`))try{return await async function(t){return new Promise((e,s)=>{let i=document.querySelector(`script[src='${t}']`);i||(i=document.createElement("script")),i.setAttribute("state",My.LOADING);const r=i.getAttribute("state");if(r&&[My.ERROR,My.LOADED].includes(r))return e(void 0);i.addEventListener("load",()=>{i.setAttribute("state",My.LOADED),e(void 0)},{once:!0}),["error","abort"].forEach(t=>{i.addEventListener(t,()=>{i.setAttribute("state",My.ERROR),s("script failed to load")},{once:!0})}),i.src=t,document.head.appendChild(i)})}(s),void Ny(":loaded")}catch(t){console.warn(`:error / failed to load prebid.js / ${t.message}`,t)}}const Gy=window.pbjs=window.pbjs||{};Gy.que=Gy.que||[];class PrebidAdController{constructor(t,e){this.player=t,this.config=e,this.player=t,this.bestOffer="",Gy.que.push(()=>{var s,i;const r=this.createAdUnit();Gy.addAdUnits(r);const n=(null===(i=null===(s=e.ads)||void 0===s?void 0:s.prebid)||void 0===i?void 0:i.pbjs)||{};Gy.setConfig(Object.assign({enableSendAllBids:!0},n)),t.emit(pr,{pbjs:Gy}),Gy.requestBids({bidsBackHandler:t=>{var s,i,n,a,o;const l=null===(s=t[this.prebidCode()])||void 0===s?void 0:s.bids;if(!l)return;if(0==l.length)return;const d=l[0];if(d&&d.vastUrl)return this.bestOffer=d.vastUrl;const c=Gy.adServers.dfp.buildVideoUrl({adUnit:r,params:{iu:null===(n=null===(i=e.ads)||void 0===i?void 0:i.prebid)||void 0===n?void 0:n.iu,cust_params:null===(o=null===(a=e.ads)||void 0===a?void 0:a.prebid)||void 0===o?void 0:o.custom_params,output:"vast"}});this.bestOffer=c}})})}prebidCode(){var t,e;return(null===(e=null===(t=this.config.ads)||void 0===t?void 0:t.prebid)||void 0===e?void 0:e.code)||this.player.root.id}videoInfo(){var t,e;return(null===(e=null===(t=this.config.ads)||void 0===t?void 0:t.prebid)||void 0===e?void 0:e.video)||{context:"instream",playerSize:[[this.player.videoWidth||640,this.player.videoHeight||480]]}}createAdUnit(){var t,e;return{code:this.prebidCode(),mediaTypes:{video:this.videoInfo()},bids:null===(e=null===(t=this.config.ads)||void 0===t?void 0:t.prebid)||void 0===e?void 0:e.bidders}}vastGenerator(){return async()=>this.bestOffer}}function Hy(t,e){var s,i;const r=null===(s=e.ads)||void 0===s?void 0:s.prebid;if(!r)return;if((null===(i=t.prebidController)||void 0===i?void 0:i.config)===e)return;Je(t,{feature_name:"prebid",behavior:"used"}),t.prebidController||(t.prebidController=new PrebidAdController(t,e),$y(t));const n=t.prebidController;if(n){const e=r.breaks.map(t=>({adTag:n.vastGenerator(),time:t}));t.setOpts({ima:{ads:e}})}}const Ky=ci("ads/index");async function Vy(t,e,s){var i;let r;if(s.on(et,()=>{var e,i;void 0===r&&t.autoplay&&(_v(i=t.ima)&&(null==i?void 0:i.ads.find(t=>!t.time||"percentage"in t&&0===t.percentage)))&&!s.currentSrc&&(r=Pe(t.autoplay),t.autoplay=0),(null===(e=t.ads)||void 0===e?void 0:e.prebid)&&Hy(s,t),_v(t.ima)&&Av(s)&&Object.assign(t,{hls:{native:!0}}),s.ads&&l()}),s.once(_,()=>{setTimeout(async()=>{if(void 0!==r&&(await xy(s),!("google"in window))){if(t.autoplay=r,s.setState(ee,!0),!s.hasState(ge))return s.once(M,()=>s.togglePlay(!0));s.togglePlay(!0)}},0)}),await xy(s),!("google"in window))return console.warn("google.ima unavailable");let n=!1;const a=s.ads=new AdsController,o=a.analytics;function l(){if(!_v(t.ima))return;const i=t.ima,l=t.duration||s.duration;if(i.ads=function(t,e){return Array.isArray(t)?t.filter(t=>Py(t)||Dy(t)).reduce((t,s)=>{if(Py(s))return t.push(s),t;if(s.lazy)return t.push(s),t;if(Dy(s)){const i=Object.assign({},s),r=s.percentage?s.percentage*e:0;return isNaN(r)||(i.time=r<0||r===e?-1:r),t.push(i),t}return t},[]):(console.warn("AdSchedule was not an Array"),[])}(i.ads,l),a.setSchedule(i.ads,l),t.metadata&&Analytics.mergeMetadata(o,t.metadata),t.metadata&&a.mergeMacros(t.metadata),t.metadata&&i.parameters&&(i.parameters=Object.assign(Object.assign({},i.parameters),t.metadata)),Analytics.mergeMetadata(o,{muted:t.muted||!1,autoplay:t.autoplay||!1}),!n){if(n=!0,t.lang&&!i.Locale&&(i.Locale=t.lang),Schedule.isOutstream(i.ads))return Ky("is outstream, returning"),new Outstream({root:e,content:s,ads:a,ima:i});dv({config:Object.assign(Object.assign({},t),{autoplay:r}),root:e,content:s,ads:a,ima:i})}}a.resize(Jm(e)),a.on(Ji,()=>{a.adapter.isCustomPlaybackEnabled()&&a.once(Zi,()=>{s.src=s.original_src,s.once(w,()=>{s.togglePlay(!1)}),s.webkitExitFullscreen()})}),s.on(N,function(){a&&a.destroy()}),(null===(i=t.ads)||void 0===i?void 0:i.prebid)&&Hy(s,t),l()}class AdControls extends HTMLElement{constructor(t){super(),this.player=t,this.classList.add("fp-ad-controls"),this.append(this.adRemainingTime(),Le(this.player,cn),this.playbackButtons(),this.volumeBtn(),Le(this.player,vt),...this.fullscreenIcons(),this.adChoices()),t.on(gr,this.applyStyleFlags.bind(this))}fullscreenIcons(){return this.player.createComponents(Ct,Ot).map(t=>(t.onclick=()=>this.player.toggleFullScreen(),t))}volumeBtn(){const t=Le(this.player,Ft);return t.onclick=()=>this.player.emit(hr),t}playbackButtons(){const t=document.createElement("div");t.classList.add("ad-playback-controls");const e=Le(this.player,kt),s=Le(this.player,wt);return e.addEventListener("click",()=>{this.player.emit(cr),setTimeout(function(){s.focus&&s.focus()},100)}),s.addEventListener("click",()=>{this.player.emit(dr),setTimeout(function(){e.focus&&e.focus()},100)}),t.append(e,s),t}adChoices(){const t=document.createElement("div");return 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")}),t}adRemainingTime(){const t=document.createElement("div");return t.classList.add("fp-ad-remaining","fp-color-text"),this.prepend(t),this.player.on(Wi,e=>{const s=e.detail.remaining;t.textContent=cs(parseFloat(s+""))}),t}applyStyleFlags(t){var e;const s=null!==(e=t.detail.ui_flags)&&void 0!==e?e:0;this.classList.toggle("is-ad-controls-sticky",(1&s)>0),this.classList.toggle("no-indicator",(4&s)>0),this.classList.toggle("is-ad-choices",(16&s)>0),this.classList.toggle("no-volume-bar",!(64&s)),this.classList.toggle("is-ad-remaining",(32&s)>0),this.classList.toggle("no-fullscreen",(2&s)>0)}}class AdCountdown extends HTMLElement{static get observedAttributes(){return["remaining"]}constructor(t){super(),this.player=t,this.className="fp-ad-countdown",t.on(Wi,t=>{const{duration:e,remaining:s}=t.detail;this.setAttribute("duration",e+""),this.setAttribute("remaining",s+"")}),t.on(Ki,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)})}attributeChangedCallback(t,e,s){if("remaining"===t)return this.onRemaining(s)}onRemaining(t){const e=parseFloat(this.getAttribute("duration")||"0");t||(t=e+"");const s=parseFloat(t),i=this.style.getPropertyValue("--ad-percent-complete")||"0";this.style.setProperty("--ad-percent-previous",i),this.classList.remove("go");const r=((e-s)/e*100).toFixed(3);requestAnimationFrame(()=>{this.style.setProperty("--ad-percent-complete",r),this.classList.add("go")})}}class AdIndicator extends HTMLElement{static get observedAttributes(){return["position","totals"]}constructor(t){super(),this.player=t,this.render(),t.on(Ki,t=>{const{position:e,totals:s}=t.detail.ad;this.setAttribute("position",e+""),this.setAttribute("totals",s+"")})}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 jy,qy=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:Wy}=s(),Yy=(jy=class Ads{constructor(t){this.umd=t,Re(t,on,AdUI),Re(t,ln,AdControls),Re(t,dn,AdCountdown),Re(t,cn,AdIndicator)}init(t,e,s){if(Fs.from_token(t.token||"").is_granted(Fs.permissions.ADS)&&!Wy)return Vy(t,e,s)}},jy.pluginName="ads",jy.events=vr,jy.ui=by,jy.tags=qy,jy),zy=ws(window,Yy);return Kn.extensions.push(am,Zm,zy),Object.assign(Kn,{hls:am,ads:zy,ovp:Zm}),Kn});
7
+ */const ey=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 qv}static get ENGINE_MAP(){return zv}static get OS_MAP(){return Yv}static get PLATFORMS_MAP(){return Wv}}.parse(window.navigator.userAgent),{platform:sy,os:iy,browser:ry}=ey,ny=t=>t&&t.toLowerCase();var ay={rnd:Math.random().toString(36).substr(2,32),os:ny(iy.name+(iy.versionName?` ${iy.versionName}`:"")),device:ny(sy.type),browser:ny(ry.name),browser_version:(ry&&ry.version?ry.version:"unknown").split(".").shift(),plugin_version:"3.43.0"};const oy="https://fp-eu-w1-aai.flowplayer.com/in",ly="POST",dy=[$i,Bi,Gi,Vi,Ki,lr,Yi],cy=["event_type","ad_tag_id","media_id","player_id","site_id","sitegroup_id","rnd","os","device","browser","browser_version","plugin_version","player_version"],hy=["vast_error","reason","request_load_time","ad_type","vast_ad_id"],uy=ci("ads/analytics"),fy=RequestQueue.of(),gy=(...t)=>Object.assign({},...t);class Analytics{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,gy(t.metadata,e,{player_version:"3.43.0"})),t}constructor(t,e={}){this.emitter=t,this.metadata=gy(ay,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),uy(this),this.wireup()}wireup(){this.events.forEach(t=>{this.emitter.on(t,e=>{const s=e.detail,i=gy(this.metadata,{event_type:t},s),r=Analytics.pluck_valid_keys(this,i),n=Analytics.ensure_required_keys(this,r);if(uy(`Event[${t}]`,{payload:r,observation:s}),n.length)return uy(`Analytics.validate_metadata() failed for\n Event[${t}]\n missing keys: ${n}`,r);RequestQueue.rpush(fy,[oy,ly,r])})})}destroy(){const t=this;t.emitter=t.metadata=t.events=t.required_keys=t.optional_keys=t.valid_keys=void 0}}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)}}const py=ci("ads/controller"),my={show_all_ads_on_seek:!1,timeout:5e3,preload_advance:5};class AdsController extends EventBus{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({},my),t),this.analytics=(e=this,Analytics.of(e,{required_keys:cy,optional_keys:hy,events:dy})),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();const t=this;t.analytics=void 0,t.opts=void 0,t.adapter=void 0,t._state=void 0,t._schedule=void 0,t._lastAd=void 0,t._macros=void 0}stop(){this.adapter&&this.adapter.stop()}onContentNewSrc(){var t;this._state.reset(),this.adapter.destroyManager(),this.adapter.contentComplete(),null===(t=this.videoTag)||void 0===t||t.root.classList.remove(sv)}wireup(){const t=()=>{var t,e;this.adapter.onAdRequestEnd(),null===(t=this.videoTag)||void 0===t||t.setState("ad-paused",!1),null===(e=this.videoTag)||void 0===e||e.setState("ad-playing",!0),this._state.toggleState(Kv.PLAYING,!0)};this.on(ar,t),this.on(Ki,t),this.on(qi,t);const e=t=>{var e,s;(null==t?void 0:t.type)!==Bi&&this.adapter.onAdRequestEnd(),null===(e=this.videoTag)||void 0===e||e.setState("ad-paused",(null==t?void 0:t.type)===ji),null===(s=this.videoTag)||void 0===s||s.setState("ad-playing",!1),this.adPlaying&&this._state.toggleState(Kv.PLAYING,!1)};this.on(Zi,e),this.on(Ni,e),this.on(Fi,e),this.on(Bi,e),this.on(ji,e),this.on(Yi,e),this.on(Vi,e),this.on(Zi,()=>{this._state.toggleState(Kv.BREAK_ACTIVE,!1)}),this.on(nr,()=>{console.error("Adapter init failed"),e(),this._state.toggleState(Kv.FATAL_ERROR,!0)}),this.on(or,async t=>{if(py("Ads.on(RELOAD_AD_REQUESTED)",t),this._schedule){if(e(),t)return this._schedule.reset(this._schedule.getAds());this._state.hasAny(Kv.AD_AVAILABLE)&&(this._schedule.decrement(),this._state.toggleState(Kv.AD_AVAILABLE,!1))}})}async initialize(t,e={},s){return py("Ads.initialize():",t,e,s),this._state.toggleState(Kv.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){py("Ads.setVideoTag():",t),await this.adapter.setVideoTag(t),this.trigger(Ui,t),this.adapter.isReady()&&await this.adapterInitialized(),t.on(dr,()=>this.adapter.pause()),t.on(cr,()=>this.adapter.resume()),t.on(hr,()=>t.toggleMute()),t.on(b,()=>{this.adapter.volume(t.muted?0:0==t.volume?.1:t.volume)}),t.on(F,()=>{if(t.currentSrc){if(!t.hasState("ad-playing")&&!t.hasState("ad-paused"))return this.onContentNewSrc();if(this.stop(),!this.adapter.isLinearAd())return this.onContentNewSrc();this.setIsContentProcessingNewSrc(!0),this.once(Zi,()=>{setTimeout(()=>{this.setIsContentProcessingNewSrc(!1),this.onContentNewSrc()},0)})}})}waitForVideoTag(){return new Promise(t=>{const e=this.adapter.getVideoTag();if(e)return t(e);this.on(Ui,e=>{this.once(xi,()=>t(e))})})}async adapterInitialized(t){py("Ads.adapterInitialized()"),this._state.toggleState(Kv.INITIALIZING,!1),this._state.toggleState(Kv.BREAK_ACTIVE,!!this.hasPreroll()),await this.setCurrentTime(0,t),t||(this.checkIfBreakComplete(),this.adapter.isAdPod()||this.trigger(Ni))}async fetchNextAd(t,e=0){var s,i;if(!this._schedule||this.getIsContentProcessingNewSrc())return;if(!this.adapter.isReady())return;if(e>50)throw this._state.toggleState(Kv.FATAL_ERROR,!0),this._state.toggleState(Kv.FETCHING_AD,!1),new Error("Ads.fetchNextAd() :max_recursion_depth");const r=(null===(s=this._schedule)||void 0===s?void 0:s.getNextAd())||(null===(i=this._schedule)||void 0===i?void 0:i.getPostroll());if(!r||this.adapter.canDismissNonLinear()||-1===t)if(this._schedule.waitForLoad(t,r,this.opts.preload_ads))this._state.toggleState(Kv.FETCHING_AD,!1);else if(r!==this._schedule.getPostroll()||(this._schedule.setPostrollActive(),-1===t))if(this._schedule.isDrained()||this._schedule.increment(),r){py("Ads.fetchNextAd",r),this._state.toggleState(Kv.FETCHING_AD,!0);try{return await this.requestAd(r),this._state.toggleState(Kv.AD_AVAILABLE,!0),void this._state.toggleState(Kv.FETCHING_AD,!1)}catch(s){return py("Ads.fetchNextAd(err: %o, ad: %o)",s,r),this.setLastAd(r),r!==this._schedule.getPostroll()?await this.fetchNextAd(t,++e):void this._state.toggleState(Kv.FETCHING_AD,!1)}}else this._state.toggleState(Kv.FETCHING_AD,!1);else this._state.toggleState(Kv.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(Kv.FETCHING_AD))return;if(this._state.hasAny(Kv.BREAK_ACTIVE)&&this.adapter.isLinearAd())return;if(this._state.hasAny(Kv.PLAYING)&&this.adapter.isLinearAd())return;const i=0===t&&0===this._schedule.getNextIndex();try{if(s&&!this.opts.show_all_ads_on_seek&&this.skipAdsOnSeek(t),this._state.hasAny(Kv.AD_AVAILABLE)||await this.fetchNextAd(t),!this._state.hasAny(Kv.AD_AVAILABLE)||!this.shallPlayAd(t))return;await this.playAd(),await this.setCurrentTime(t),this.checkIfBreakComplete()}catch(t){py("setCurrentTime: Error(from: setCurrentTime, message: %s)",t.message)}finally{i&&this.trigger(tr)}}async playAd(){var t;if(!this._state.hasAny(Kv.AD_AVAILABLE))return;this._state.toggleState(Kv.AD_AVAILABLE,!1),this._state.toggleState(Kv.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(Kv.BREAK_ACTIVE))return py("Ads.checkIfBreakComplete(:bail, ad: %o)",this.getLastAd());py("Ads.checkIfBreakComplete(:run, ad: %o)",this.getLastAd()),this._state.toggleState(Kv.BREAK_ACTIVE,!1),this.adapter.isAdPod()||this.trigger(Zi)}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(t===Zi&&this._state.hasAny(Kv.BREAK_ACTIVE)&&!this.adapter.isAdPod()&&!e.force)return py("skipping AD_BREAK_COMPLETE reason: %s pod=%s",this._state.toString(),this.adapter.isAdPod());if(null===(i=e)||"object"!=typeof i||Gv(i)!==$v)return this.dispatch(t,e);var i;const r=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,r)}dispatch(t,e){const s=this.adapter.getVideoTag();if(s){py(":dispatch",t,e),this.adapter.isAdPod()&&"object"==typeof e&&"time"in e&&"preroll"!==e.ad_type&&(e.time=this.adapter.getAdBreakTime());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}};s.dispatchEvent(new CustomEvent(He,{detail:i}))}catch(t){py(":error",t)}this.emit(t,e),Ts(s,t,e)}}get ad_type(){if(!this.videoTag)return;if(!this.adapter.isAdPod())return this._schedule&&this._schedule.getCurrentType();const t=this.adapter.getAdBreakTime();return-1===t?"postroll":this.videoTag.hasState(Zt)||t<1?"preroll":"midroll"}shouldRestartContent(t){var e,s;if(!(null===(e=this.videoTag)||void 0===e?void 0:e.root.classList.contains(iv)))return!1;if(t===Ni&&!(null===(s=this.videoTag)||void 0===s?void 0:s.hasState(qt)))return!1;if(this.getIsContentProcessingNewSrc())return!1;if(this.adapter.isAdPod())return!0;const i=this.getLastAd();return!i||!i.outstream&&!1!==i.restart}async finished(t){if(this._schedule&&(py("Ads.finished"),!(this.adapter.isCustomPlaybackEnabled()&&this._state.hasAny(Kv.PLAYING)&&this.adapter.isLinearAd()))){py("Ads.finished: trying to play postroll");try{if(!this._schedule.getPostroll())return py("Ads.finished: no postroll found"),await this.adapter.contentComplete();this._state.hasAny(Kv.AD_AVAILABLE)||await this.fetchNextAd(-1),await this.playAd(),this.adapter.contentComplete()}catch(t){py("Ads.finished: postroll failed:",t)}finally{this.trigger(Ji),this.checkIfBreakComplete(),"function"==typeof t&&t()}}}hasPreroll(){return this._schedule&&Schedule.hasPreroll(this._schedule.getAds())}shallPlayAd(t){var e,s;return!!(null===(e=this.videoTag)||void 0===e?void 0:e.root.classList.contains(iv))&&((!this.adapter||!this.adapter.isAdPod())&&(!(!this._state||this._state.hasAny(Kv.FATAL_ERROR))&&!!(null===(s=this._schedule)||void 0===s?void 0:s.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;py("Ads.requestAd(ad: %o)",{ad:t,timeout:s,idx:e});const i=await Bv(t);if(void 0===i[e])return setTimeout(()=>this.trigger(Ni),0),Promise.reject(new Error("Ad failed, no fallbacks left"));if(!i[e])return await this.requestAd(i,e+1,s);this.trigger($i,t);const r=this._macros.compile(i[e],Fv(this.opts,this.adapter.getDimensions()));try{return void await this.adapter.initAd(r,s)}catch(t){return py(`Ads.requestAd(:fallback, idx: ${e}, length: ${i.length}, adTag: ${i[e]})\nError `,{adTag:i,err:t}),this.requestAd(i,e+1,s)}}resetSchedule(t){this._schedule&&this._schedule.reset(t)}get adPlaying(){return this._state&&this._state.hasAny(Kv.PLAYING)}get adBreak(){return this._state&&this._state.hasAny(Kv.BREAK_ACTIVE)}get adRequesting(){return this._state.hasAny(Kv.FETCHING_AD)}get adLinear(){return this.adBreak&&this.adapter.isLinearAd()}}var vy=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"}),yy=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 Ey(t){return Object.assign({muted:!1,timeout:250,inline:!1},t)}function Ty(t,e){var s=t.muted,i=t.timeout,r=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===r&&a.setAttribute("playsinline","playsinline"),a.src=o,new Promise(function(t){l=a.play(),d=setTimeout(function(){c(!1,new Error("Timeout "+i+" ms has been reached"))},i),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 Sy={audio:function(t){return Ty(t=Ey(t),function(){return{element:document.createElement("audio"),source:URL.createObjectURL(vy)}})},video:function(t){return Ty(t=Ey(t),function(){return{element:document.createElement("video"),source:URL.createObjectURL(yy)}})}};let Ay;async function _y(t=!0){return Ay||(Ay=await Sy.video({timeout:500,muted:t}),Ay)}var by=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 Ly=["progress","duration","remaining"];class AdUI extends HTMLElement{static get observedAttributes(){return Ly}constructor(t){super(),this.player=t,this.className="fp-ad-ui",this.append(...t.createComponents(ln,dn)),t.on(gr,t=>{let{ui_flags:e}=t.detail;if(e=e||0,(8&e)>0){const t=document.createElement("div");t.classList.add("ad-attribution"),t.textContent=this.player.i18n("ads.advertisement","Advertisement"),this.append(t)}})}}const Ry=ci("fpads:native:outstream"),Iy={OUTSTREAM:"is-outstream",HIDDEN:"is-outstream-hidden",SHOWING:"is-outstream-visible",DONE:"is-outstream-done"};var ky,wy;!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"}(ky||(ky={})),function(t){t[t.None=0]="None",t[t.Booting=1]="Booting",t[t.Ready=2]="Ready",t[t.Disposed=3]="Disposed"}(wy||(wy={}));class Outstream{constructor({ads:t,root:e,content:s,ima:i}){this.state=wy.None,Ry("creating Outstream instance"),this.content=s,this.ads=t,this.root=e,this.ima=i,this.aspectRatio=s.videoHeight/s.videoWidth,this.dimensions=function(t){if(t.clientWidth>0||t.clientHeight)return Jm(t);const e={height:t.style.height};tv(t,"opacity",0),tv(t,"display","absolute"),tv(t,"display","inline-block"),tv(t,"height","auto");const s=Jm(t);return tv(t,"height",e.height),tv(t,"opacity",1),s}(this.root),this.adUi=new AdUI(s),this.initialVolumeState={},e.classList.add(Iy.OUTSTREAM),e.classList.add(iv),e.append(this.adUi),this.hide(),this.ads.on(Hi,t=>{var e;if(this.state==wy.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(m,t=>{if(this.state==wy.Disposed)return;const e=t.detail;e&&(this.dimensions={width:e.contentRect.width,height:e.contentRect.height},this.ads.resize(this.dimensions))});let r=1,n=!0;s.on(X,t=>{if(this.state==wy.Disposed)return;const e=t.detail;if(e)switch(this.state){case wy.Booting:return Ry(":boot skipping intersectionchange");case wy.None:return this.state=wy.Booting,this.begin_life_cycle();case wy.Ready:if(r=e.ratio,e.ratio>=.5&&this.ads.adPlaying)return;e.ratio>=.5&&n&&this.ads.resume(),e.ratio<.5&&this.ads.pause()}}),this.content.on(ji,()=>n=r<.5),this.setup(),setTimeout(()=>(this.state=wy.Booting,this.begin_life_cycle()),0)}hide(){return this}restore_aspect_ratio(){return Ry(`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.content.setState("ad-linear",!0)}async begin_life_cycle(){var t;this.state=wy.Ready;const{error:e,result:s}=await _y(!1),{result:i}=await _y(!0);this.content.emit(gr,{ui_flags:null===(t=this.content.opts.ads)||void 0===t?void 0:t.ui}),this.attach_ad_listeners(),this.initialVolumeState={can_autoplay:!(!s&&!i),muted:!s},Ry(`Outstream.show() :autoplay >> sound=${s}`),e&&this.content&&!s&&(this.content.muted=!0,this.content.volume=0),await this.ads.setVideoTag(this.content),await cv({ads:this.ads,content:this.content,adContainer:this.adUi,ima:this.ima,state:{listening:!1},config:this.content.opts}),pv({content:this.content,ads:this.ads}),this.state=wy.Ready}attach_ad_listeners(){this.ads.once(Hi,()=>{this.show(),this.ads.adPlaying&&this.ads.pause()});const t=()=>{lv.forEach(e=>this.ads.removeListener(e,t));const e=new CustomEvent(ky.OUTSTREAM_TEARDOWN);Ry("Outstream(:teardown)",e),this.content.dispatchEvent(e)};lv.forEach(e=>this.ads.once(e,t)),this.content.once(ky.OUTSTREAM_TEARDOWN,t=>{setTimeout(()=>{if(t.defaultPrevented)return this.handle_endscreen();this.dispose()},0)})}handle_endscreen(){this.reset_ui(),this.ads.reset(),fv({config:this.content.opts,ui:this.adUi,ads:this.ads,adContainer:this.adUi,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(rv)})}setup(){this.root.classList.add(Outstream.CLASS.OUTSTREAM),this.root.classList.add(Outstream.CLASS.HIDDEN),this.content.setState("ad-linear",!1),this.empty_src()}reset_ui(){const t=this.root;t.classList.remove(Outstream.CLASS.SHOWING),t.classList.remove(Outstream.CLASS.OUTSTREAM)}dispose(){if(this.state==wy.Disposed)return;const t=this.root,e=this.content;this.reset_ui(),t.classList.add(Outstream.CLASS.OUTSTREAM),t.classList.add(Outstream.CLASS.DONE);const s=this;s.video=s.container=s.ads=0,this.state=wy.Disposed,e.destroy(),t.innerHTML=""}}function Py(t){return t&&"number"==typeof t.time}function Dy(t){return t&&"number"==typeof t.percentage&&"number"!=typeof t.time}Outstream.CLASS=Iy;const Cy=ci("ads/ima/sdk");var Oy,My;async function xy(t,e){var s;const i=null===(s=null===window||void 0===window?void 0:window.google)||void 0===s?void 0:s.ima;if(e?null==i?void 0:i.dai:i)return void Cy(":noop");const r=e?"https://imasdk.googleapis.com/js/sdkloader/ima3_dai.js":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 i=document.querySelector(`script[src='${t}']`);if(i)return Fy(i,e,s);i=document.createElement("script"),i.setAttribute("state",Oy.LOADING),Fy(i,e,s),i.src=t,document.head.appendChild(i)})}(r),void Cy(":loaded")}catch(t){Cy(`:error ${t.message}`,t)}}function Fy(t,e,s){const i=t.getAttribute("state");if(i&&[Oy.ERROR,Oy.LOADED].includes(i))return e(void 0);t.addEventListener("load",()=>{t.setAttribute("state",Oy.LOADED),e(void 0)},{once:!0}),["error","abort"].forEach(e=>{t.addEventListener(e,()=>{t.setAttribute("state",Oy.ERROR),s("script failed to load")},{once:!0})})}!function(t){t.LOADING="loading",t.LOADED="loaded",t.ERROR="error"}(Oy||(Oy={})),function(t){t.LOADING="loading",t.LOADED="loaded",t.ERROR="error"}(My||(My={}));const Ny=ci("ads/ima/sdk"),Uy="https://cdn.jsdelivr.net/npm/prebid.js@latest/dist/not-for-prod/prebid.js",By=Uy;async function $y(t){var e;const s=t._storage.getItem("prebid/debug")?Uy:By;if(null===(e=null===window||void 0===window?void 0:window.pbjs)||void 0===e?void 0:e.version)Ny(":noop");else if(!document.querySelector(`script[src='${s}']`))try{return await async function(t){return new Promise((e,s)=>{let i=document.querySelector(`script[src='${t}']`);i||(i=document.createElement("script")),i.setAttribute("state",My.LOADING);const r=i.getAttribute("state");if(r&&[My.ERROR,My.LOADED].includes(r))return e(void 0);i.addEventListener("load",()=>{i.setAttribute("state",My.LOADED),e(void 0)},{once:!0}),["error","abort"].forEach(t=>{i.addEventListener(t,()=>{i.setAttribute("state",My.ERROR),s("script failed to load")},{once:!0})}),i.src=t,document.head.appendChild(i)})}(s),void Ny(":loaded")}catch(t){console.warn(`:error / failed to load prebid.js / ${t.message}`,t)}}const Gy=window.pbjs=window.pbjs||{};Gy.que=Gy.que||[];class PrebidAdController{constructor(t,e){this.player=t,this.config=e,this.player=t,this.bestOffer="",Gy.que.push(()=>{var s,i;const r=this.createAdUnit();Gy.addAdUnits(r);const n=(null===(i=null===(s=e.ads)||void 0===s?void 0:s.prebid)||void 0===i?void 0:i.pbjs)||{};Gy.setConfig(Object.assign({enableSendAllBids:!0},n)),t.emit(pr,{pbjs:Gy}),Gy.requestBids({bidsBackHandler:t=>{var s,i,n,a,o;const l=null===(s=t[this.prebidCode()])||void 0===s?void 0:s.bids;if(!l)return;if(0==l.length)return;const d=l[0];if(d&&d.vastUrl)return this.bestOffer=d.vastUrl;const c=Gy.adServers.dfp.buildVideoUrl({adUnit:r,params:{iu:null===(n=null===(i=e.ads)||void 0===i?void 0:i.prebid)||void 0===n?void 0:n.iu,cust_params:null===(o=null===(a=e.ads)||void 0===a?void 0:a.prebid)||void 0===o?void 0:o.custom_params,output:"vast"}});this.bestOffer=c}})})}prebidCode(){var t,e;return(null===(e=null===(t=this.config.ads)||void 0===t?void 0:t.prebid)||void 0===e?void 0:e.code)||this.player.root.id}videoInfo(){var t,e;return(null===(e=null===(t=this.config.ads)||void 0===t?void 0:t.prebid)||void 0===e?void 0:e.video)||{context:"instream",playerSize:[[this.player.videoWidth||640,this.player.videoHeight||480]]}}createAdUnit(){var t,e;return{code:this.prebidCode(),mediaTypes:{video:this.videoInfo()},bids:null===(e=null===(t=this.config.ads)||void 0===t?void 0:t.prebid)||void 0===e?void 0:e.bidders}}vastGenerator(){return async()=>this.bestOffer}}function Hy(t,e){var s,i;const r=null===(s=e.ads)||void 0===s?void 0:s.prebid;if(!r)return;if((null===(i=t.prebidController)||void 0===i?void 0:i.config)===e)return;Je(t,{feature_name:"prebid",behavior:"used"}),t.prebidController||(t.prebidController=new PrebidAdController(t,e),$y(t));const n=t.prebidController;if(n){const e=r.breaks.map(t=>({adTag:n.vastGenerator(),time:t}));t.setOpts({ima:{ads:e}})}}const Ky=ci("ads/index");async function Vy(t,e,s){var i;let r;if(s.on(et,()=>{var e,i;void 0===r&&t.autoplay&&(_v(i=t.ima)&&(null==i?void 0:i.ads.find(t=>!t.time||"percentage"in t&&0===t.percentage)))&&!s.currentSrc&&(r=Pe(t.autoplay),t.autoplay=0),(null===(e=t.ads)||void 0===e?void 0:e.prebid)&&Hy(s,t),_v(t.ima)&&Av(s)&&Object.assign(t,{hls:{native:!0}}),s.ads&&l()}),s.once(_,()=>{setTimeout(async()=>{if(void 0!==r&&(await xy(s),!("google"in window))){if(t.autoplay=r,s.setState(ee,!0),!s.hasState(ge))return s.once(M,()=>s.togglePlay(!0));s.togglePlay(!0)}},0)}),await xy(s),!("google"in window))return console.warn("google.ima unavailable");let n=!1;const a=s.ads=new AdsController,o=a.analytics;function l(){if(!_v(t.ima))return;const i=t.ima,l=t.duration||s.duration;if(i.ads=function(t,e){return Array.isArray(t)?t.filter(t=>Py(t)||Dy(t)).reduce((t,s)=>{if(Py(s))return t.push(s),t;if(s.lazy)return t.push(s),t;if(Dy(s)){const i=Object.assign({},s),r=s.percentage?s.percentage*e:0;return isNaN(r)||(i.time=r<0||r===e?-1:r),t.push(i),t}return t},[]):(console.warn("AdSchedule was not an Array"),[])}(i.ads,l),a.setSchedule(i.ads,l),t.metadata&&Analytics.mergeMetadata(o,t.metadata),t.metadata&&a.mergeMacros(t.metadata),t.metadata&&i.parameters&&(i.parameters=Object.assign(Object.assign({},i.parameters),t.metadata)),Analytics.mergeMetadata(o,{muted:t.muted||!1,autoplay:t.autoplay||!1}),!n){if(n=!0,t.lang&&!i.Locale&&(i.Locale=t.lang),Schedule.isOutstream(i.ads))return Ky("is outstream, returning"),new Outstream({root:e,content:s,ads:a,ima:i});dv({config:Object.assign(Object.assign({},t),{autoplay:r}),root:e,content:s,ads:a,ima:i})}}a.resize(Jm(e)),a.on(Ji,()=>{a.adapter.isCustomPlaybackEnabled()&&a.once(Zi,()=>{s.src=s.original_src,s.once(w,()=>{s.togglePlay(!1)}),s.webkitExitFullscreen()})}),s.on(N,function(){a&&a.destroy()}),(null===(i=t.ads)||void 0===i?void 0:i.prebid)&&Hy(s,t),l()}class AdControls extends HTMLElement{constructor(t){super(),this.player=t,this.classList.add("fp-ad-controls"),this.append(this.adRemainingTime(),Le(this.player,cn),this.playbackButtons(),this.volumeBtn(),Le(this.player,vt),...this.fullscreenIcons(),this.adChoices()),t.on(gr,this.applyStyleFlags.bind(this))}fullscreenIcons(){return this.player.createComponents(Ct,Ot).map(t=>(t.onclick=()=>this.player.toggleFullScreen(),t))}volumeBtn(){const t=Le(this.player,Ft);return t.onclick=()=>this.player.emit(hr),t}playbackButtons(){const t=document.createElement("div");t.classList.add("ad-playback-controls");const e=Le(this.player,kt),s=Le(this.player,wt);return e.addEventListener("click",()=>{this.player.emit(cr),setTimeout(function(){s.focus&&s.focus()},100)}),s.addEventListener("click",()=>{this.player.emit(dr),setTimeout(function(){e.focus&&e.focus()},100)}),t.append(e,s),t}adChoices(){const t=document.createElement("div");return 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")}),t}adRemainingTime(){const t=document.createElement("div");return t.classList.add("fp-ad-remaining","fp-color-text"),this.prepend(t),this.player.on(Wi,e=>{const s=e.detail.remaining;t.textContent=cs(parseFloat(s+""))}),t}applyStyleFlags(t){var e;const s=null!==(e=t.detail.ui_flags)&&void 0!==e?e:0;this.classList.toggle("is-ad-controls-sticky",(1&s)>0),this.classList.toggle("no-indicator",(4&s)>0),this.classList.toggle("is-ad-choices",(16&s)>0),this.classList.toggle("no-volume-bar",!(64&s)),this.classList.toggle("is-ad-remaining",(32&s)>0),this.classList.toggle("no-fullscreen",(2&s)>0)}}class AdCountdown extends HTMLElement{static get observedAttributes(){return["remaining"]}constructor(t){super(),this.player=t,this.className="fp-ad-countdown",t.on(Wi,t=>{const{duration:e,remaining:s}=t.detail;this.setAttribute("duration",e+""),this.setAttribute("remaining",s+"")}),t.on(Ki,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)})}attributeChangedCallback(t,e,s){if("remaining"===t)return this.onRemaining(s)}onRemaining(t){const e=parseFloat(this.getAttribute("duration")||"0");t||(t=e+"");const s=parseFloat(t),i=this.style.getPropertyValue("--ad-percent-complete")||"0";this.style.setProperty("--ad-percent-previous",i),this.classList.remove("go");const r=((e-s)/e*100).toFixed(3);requestAnimationFrame(()=>{this.style.setProperty("--ad-percent-complete",r),this.classList.add("go")})}}class AdIndicator extends HTMLElement{static get observedAttributes(){return["position","totals"]}constructor(t){super(),this.player=t,this.render(),t.on(Ki,t=>{const{position:e,totals:s}=t.detail.ad;this.setAttribute("position",e+""),this.setAttribute("totals",s+"")})}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 jy,qy=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:Wy}=s(),Yy=(jy=class Ads{constructor(t){this.umd=t,Re(t,on,AdUI),Re(t,ln,AdControls),Re(t,dn,AdCountdown),Re(t,cn,AdIndicator)}init(t,e,s){if(Fs.from_token(t.token||"").is_granted(Fs.permissions.ADS)&&!Wy)return Vy(t,e,s)}},jy.pluginName="ads",jy.events=vr,jy.ui=by,jy.tags=qy,jy),zy=ws(window,Yy);return Kn.extensions.push(am,Zm,zy),Object.assign(Kn,{hls:am,ads:zy,ovp:Zm}),Kn});